adding optional argument KIND to all org-called-interactively-p function invocations
[org-mode.git] / lisp / org.el
blob47a34655e1252159920fbd8be15462d4d4680598
1 ;;; org.el --- Outline-based notes management and organizer
2 ;; Carstens outline-mode for keeping track of everything.
3 ;; Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011
4 ;; Free Software Foundation, Inc.
5 ;;
6 ;; Author: Carsten Dominik <carsten at orgmode dot org>
7 ;; Keywords: outlines, hypermedia, calendar, wp
8 ;; Homepage: http://orgmode.org
9 ;; Version: 7.5
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
27 ;;; Commentary:
29 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
30 ;; project planning with a fast and effective plain-text system.
32 ;; Org-mode develops organizational tasks around NOTES files that contain
33 ;; information about projects as plain text. Org-mode is implemented on
34 ;; top of outline-mode, which makes it possible to keep the content of
35 ;; large files well structured. Visibility cycling and structure editing
36 ;; help to work with the tree. Tables are easily created with a built-in
37 ;; table editor. Org-mode supports ToDo items, deadlines, time stamps,
38 ;; and scheduling. It dynamically compiles entries into an agenda that
39 ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
40 ;; Plain text URL-like links connect to websites, emails, Usenet
41 ;; messages, BBDB entries, and any files related to the projects. For
42 ;; printing and sharing of notes, an Org-mode file can be exported as a
43 ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
44 ;; iCalendar file. It can also serve as a publishing tool for a set of
45 ;; linked webpages.
47 ;; Installation and Activation
48 ;; ---------------------------
49 ;; See the corresponding sections in the manual at
51 ;; http://orgmode.org/org.html#Installation
53 ;; Documentation
54 ;; -------------
55 ;; The documentation of Org-mode can be found in the TeXInfo file. The
56 ;; distribution also contains a PDF version of it. At the homepage of
57 ;; Org-mode, you can read the same text online as HTML. There is also an
58 ;; excellent reference card made by Philip Rooke. This card can be found
59 ;; in the etc/ directory of Emacs 22.
61 ;; A list of recent changes can be found at
62 ;; http://orgmode.org/Changes.html
64 ;;; Code:
66 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
67 (defvar org-table-formula-constants-local nil
68 "Local version of `org-table-formula-constants'.")
69 (make-variable-buffer-local 'org-table-formula-constants-local)
71 ;;;; Require other packages
73 (eval-when-compile
74 (require 'cl)
75 (require 'gnus-sum))
77 (require 'calendar)
79 ;; Emacs 22 calendar compatibility: Make sure the new variables are available
80 (when (fboundp 'defvaralias)
81 (unless (boundp 'calendar-view-holidays-initially-flag)
82 (defvaralias 'calendar-view-holidays-initially-flag
83 'view-calendar-holidays-initially))
84 (unless (boundp 'calendar-view-diary-initially-flag)
85 (defvaralias 'calendar-view-diary-initially-flag
86 'view-diary-entries-initially))
87 (unless (boundp 'diary-fancy-buffer)
88 (defvaralias 'diary-fancy-buffer 'fancy-diary-buffer)))
90 (require 'outline) (require 'noutline)
91 ;; Other stuff we need.
92 (require 'time-date)
93 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
94 (require 'easymenu)
95 (require 'overlay)
97 (require 'org-macs)
98 (require 'org-entities)
99 (require 'org-compat)
100 (require 'org-faces)
101 (require 'org-list)
102 (require 'org-pcomplete)
103 (require 'org-src)
104 (require 'org-footnote)
106 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
107 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
108 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
110 ;; babel
111 (require 'ob)
112 (require 'ob-table)
113 (require 'ob-lob)
114 (require 'ob-ref)
115 (require 'ob-tangle)
116 (require 'ob-comint)
117 (require 'ob-keys)
119 ;; load languages based on value of `org-babel-load-languages'
120 (defvar org-babel-load-languages)
121 ;;;###autoload
122 (defun org-babel-do-load-languages (sym value)
123 "Load the languages defined in `org-babel-load-languages'."
124 (set-default sym value)
125 (mapc (lambda (pair)
126 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
127 (if active
128 (progn
129 (require (intern (concat "ob-" lang))))
130 (progn
131 (funcall 'fmakunbound
132 (intern (concat "org-babel-execute:" lang)))
133 (funcall 'fmakunbound
134 (intern (concat "org-babel-expand-body:" lang)))))))
135 org-babel-load-languages))
137 (defcustom org-babel-load-languages '((emacs-lisp . t))
138 "Languages which can be evaluated in Org-mode buffers.
139 This list can be used to load support for any of the languages
140 below, note that each language will depend on a different set of
141 system executables and/or Emacs modes. When a language is
142 \"loaded\", then code blocks in that language can be evaluated
143 with `org-babel-execute-src-block' bound by default to C-c
144 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
145 be set to remove code block evaluation from the C-c C-c
146 keybinding. By default only Emacs Lisp (which has no
147 requirements) is loaded."
148 :group 'org-babel
149 :set 'org-babel-do-load-languages
150 :type '(alist :tag "Babel Languages"
151 :key-type
152 (choice
153 (const :tag "Awk" awk)
154 (const :tag "C" C)
155 (const :tag "R" R)
156 (const :tag "Asymptote" asymptote)
157 (const :tag "Calc" calc)
158 (const :tag "Clojure" clojure)
159 (const :tag "CSS" css)
160 (const :tag "Ditaa" ditaa)
161 (const :tag "Dot" dot)
162 (const :tag "Emacs Lisp" emacs-lisp)
163 (const :tag "Gnuplot" gnuplot)
164 (const :tag "Haskell" haskell)
165 (const :tag "Javascript" js)
166 (const :tag "Latex" latex)
167 (const :tag "Ledger" ledger)
168 (const :tag "Maxima" maxima)
169 (const :tag "Matlab" matlab)
170 (const :tag "Mscgen" mscgen)
171 (const :tag "Ocaml" ocaml)
172 (const :tag "Octave" octave)
173 (const :tag "Org" org)
174 (const :tag "Perl" perl)
175 (const :tag "PlantUML" plantuml)
176 (const :tag "Python" python)
177 (const :tag "Ruby" ruby)
178 (const :tag "Sass" sass)
179 (const :tag "Scheme" scheme)
180 (const :tag "Screen" screen)
181 (const :tag "Shell Script" sh)
182 (const :tag "Sql" sql)
183 (const :tag "Sqlite" sqlite))
184 :value-type (boolean :tag "Activate" :value t)))
186 ;;;; Customization variables
187 (defcustom org-clone-delete-id nil
188 "Remove ID property of clones of a subtree.
189 When non-nil, clones of a subtree don't inherit the ID property.
190 Otherwise they inherit the ID property with a new unique
191 identifier."
192 :type 'boolean
193 :group 'org-id)
195 ;;; Version
197 (defconst org-version "7.5"
198 "The version number of the file org.el.")
200 (defun org-version (&optional here)
201 "Show the org-mode version in the echo area.
202 With prefix arg HERE, insert it at point."
203 (interactive "P")
204 (let* ((origin default-directory)
205 (version org-version)
206 (git-version)
207 (dir (concat (file-name-directory (locate-library "org")) "../" )))
208 (when (and (file-exists-p (expand-file-name ".git" dir))
209 (executable-find "git"))
210 (unwind-protect
211 (progn
212 (cd dir)
213 (when (eql 0 (shell-command "git describe --abbrev=4 HEAD"))
214 (with-current-buffer "*Shell Command Output*"
215 (goto-char (point-min))
216 (setq git-version (buffer-substring (point) (point-at-eol))))
217 (subst-char-in-string ?- ?. git-version t)
218 (when (string-match "\\S-"
219 (shell-command-to-string
220 "git diff-index --name-only HEAD --"))
221 (setq git-version (concat git-version ".dirty")))
222 (setq version (concat version " (" git-version ")"))))
223 (cd origin)))
224 (setq version (format "Org-mode version %s" version))
225 (if here (insert version))
226 (message version)))
228 ;;; Compatibility constants
230 ;;; The custom variables
232 (defgroup org nil
233 "Outline-based notes management and organizer."
234 :tag "Org"
235 :group 'outlines
236 :group 'calendar)
238 (defcustom org-mode-hook nil
239 "Mode hook for Org-mode, run after the mode was turned on."
240 :group 'org
241 :type 'hook)
243 (defcustom org-load-hook nil
244 "Hook that is run after org.el has been loaded."
245 :group 'org
246 :type 'hook)
248 (defvar org-modules) ; defined below
249 (defvar org-modules-loaded nil
250 "Have the modules been loaded already?")
252 (defun org-load-modules-maybe (&optional force)
253 "Load all extensions listed in `org-modules'."
254 (when (or force (not org-modules-loaded))
255 (mapc (lambda (ext)
256 (condition-case nil (require ext)
257 (error (message "Problems while trying to load feature `%s'" ext))))
258 org-modules)
259 (setq org-modules-loaded t)))
261 (defun org-set-modules (var value)
262 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
263 (set var value)
264 (when (featurep 'org)
265 (org-load-modules-maybe 'force)))
267 (when (org-bound-and-true-p org-modules)
268 (let ((a (member 'org-infojs org-modules)))
269 (and a (setcar a 'org-jsinfo))))
271 (defcustom org-modules '(org-bbdb org-bibtex org-docview org-gnus org-info org-jsinfo org-irc org-mew org-mhe org-rmail org-vm org-w3m org-wl)
272 "Modules that should always be loaded together with org.el.
273 If a description starts with <C>, the file is not part of Emacs
274 and loading it will require that you have downloaded and properly installed
275 the org-mode distribution.
277 You can also use this system to load external packages (i.e. neither Org
278 core modules, nor modules from the CONTRIB directory). Just add symbols
279 to the end of the list. If the package is called org-xyz.el, then you need
280 to add the symbol `xyz', and the package must have a call to
282 (provide 'org-xyz)"
283 :group 'org
284 :set 'org-set-modules
285 :type
286 '(set :greedy t
287 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
288 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
289 (const :tag " crypt: Encryption of subtrees" org-crypt)
290 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
291 (const :tag " docview: Links to doc-view buffers" org-docview)
292 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
293 (const :tag " id: Global IDs for identifying entries" org-id)
294 (const :tag " info: Links to Info nodes" org-info)
295 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
296 (const :tag " habit: Track your consistency with habits" org-habit)
297 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
298 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
299 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
300 (const :tag " mew Links to Mew folders/messages" org-mew)
301 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
302 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
303 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
304 (const :tag " special-blocks: Turn blocks into LaTeX envs and HTML divs" org-special-blocks)
305 (const :tag " vm: Links to VM folders/messages" org-vm)
306 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
307 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
308 (const :tag " mouse: Additional mouse support" org-mouse)
309 (const :tag " TaskJuggler: Export tasks to a TaskJuggler project" org-taskjuggler)
311 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
312 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
313 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
314 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
315 (const :tag "C collector: Collect properties into tables" org-collector)
316 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
317 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
318 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
319 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
320 (const :tag "C eval: Include command output as text" org-eval)
321 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
322 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
323 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
324 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
325 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
327 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
329 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
330 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
331 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
332 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
333 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
334 (const :tag "C mac-link-grabber Grab links and URLs from various Mac applications" org-mac-link-grabber)
335 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
336 (const :tag "C mtags: Support for muse-like tags" org-mtags)
337 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
338 (const :tag "C registry: A registry for Org-mode links" org-registry)
339 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
340 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
341 (const :tag "C secretary: Team management with org-mode" org-secretary)
342 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
343 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
344 (const :tag "C track: Keep up with Org-mode development" org-track)
345 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
346 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
347 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
349 (defcustom org-support-shift-select nil
350 "Non-nil means make shift-cursor commands select text when possible.
352 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys start
353 selecting a region, or enlarge regions started in this way.
354 In Org-mode, in special contexts, these same keys are used for other
355 purposes, important enough to compete with shift selection. Org tries
356 to balance these needs by supporting `shift-select-mode' outside these
357 special contexts, under control of this variable.
359 The default of this variable is nil, to avoid confusing behavior. Shifted
360 cursor keys will then execute Org commands in the following contexts:
361 - on a headline, changing TODO state (left/right) and priority (up/down)
362 - on a time stamp, changing the time
363 - in a plain list item, changing the bullet type
364 - in a property definition line, switching between allowed values
365 - in the BEGIN line of a clock table (changing the time block).
366 Outside these contexts, the commands will throw an error.
368 When this variable is t and the cursor is not in a special context,
369 Org-mode will support shift-selection for making and enlarging regions.
370 To make this more effective, the bullet cycling will no longer happen
371 anywhere in an item line, but only if the cursor is exactly on the bullet.
373 If you set this variable to the symbol `always', then the keys
374 will not be special in headlines, property lines, and item lines, to make
375 shift selection work there as well. If this is what you want, you can
376 use the following alternative commands: `C-c C-t' and `C-c ,' to
377 change TODO state and priority, `C-u C-u C-c C-t' can be used to switch
378 TODO sets, `C-c -' to cycle item bullet types, and properties can be
379 edited by hand or in column view.
381 However, when the cursor is on a timestamp, shift-cursor commands
382 will still edit the time stamp - this is just too good to give up.
384 XEmacs user should have this variable set to nil, because shift-select-mode
385 is Emacs 23 only."
386 :group 'org
387 :type '(choice
388 (const :tag "Never" nil)
389 (const :tag "When outside special context" t)
390 (const :tag "Everywhere except timestamps" always)))
392 (defgroup org-startup nil
393 "Options concerning startup of Org-mode."
394 :tag "Org Startup"
395 :group 'org)
397 (defcustom org-startup-folded t
398 "Non-nil means entering Org-mode will switch to OVERVIEW.
399 This can also be configured on a per-file basis by adding one of
400 the following lines anywhere in the buffer:
402 #+STARTUP: fold (or `overview', this is equivalent)
403 #+STARTUP: nofold (or `showall', this is equivalent)
404 #+STARTUP: content
405 #+STARTUP: showeverything"
406 :group 'org-startup
407 :type '(choice
408 (const :tag "nofold: show all" nil)
409 (const :tag "fold: overview" t)
410 (const :tag "content: all headlines" content)
411 (const :tag "show everything, even drawers" showeverything)))
413 (defcustom org-startup-truncated t
414 "Non-nil means entering Org-mode will set `truncate-lines'.
415 This is useful since some lines containing links can be very long and
416 uninteresting. Also tables look terrible when wrapped."
417 :group 'org-startup
418 :type 'boolean)
420 (defcustom org-startup-indented nil
421 "Non-nil means turn on `org-indent-mode' on startup.
422 This can also be configured on a per-file basis by adding one of
423 the following lines anywhere in the buffer:
425 #+STARTUP: indent
426 #+STARTUP: noindent"
427 :group 'org-structure
428 :type '(choice
429 (const :tag "Not" nil)
430 (const :tag "Globally (slow on startup in large files)" t)))
432 (defcustom org-use-sub-superscripts t
433 "Non-nil means interpret \"_\" and \"^\" for export.
434 When this option is turned on, you can use TeX-like syntax for sub- and
435 superscripts. Several characters after \"_\" or \"^\" will be
436 considered as a single item - so grouping with {} is normally not
437 needed. For example, the following things will be parsed as single
438 sub- or superscripts.
440 10^24 or 10^tau several digits will be considered 1 item.
441 10^-12 or 10^-tau a leading sign with digits or a word
442 x^2-y^3 will be read as x^2 - y^3, because items are
443 terminated by almost any nonword/nondigit char.
444 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
446 Still, ambiguity is possible - so when in doubt use {} to enclose the
447 sub/superscript. If you set this variable to the symbol `{}',
448 the braces are *required* in order to trigger interpretations as
449 sub/superscript. This can be helpful in documents that need \"_\"
450 frequently in plain text.
452 Not all export backends support this, but HTML does.
454 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
455 :group 'org-startup
456 :group 'org-export-translation
457 :type '(choice
458 (const :tag "Always interpret" t)
459 (const :tag "Only with braces" {})
460 (const :tag "Never interpret" nil)))
462 (if (fboundp 'defvaralias)
463 (defvaralias 'org-export-with-sub-superscripts 'org-use-sub-superscripts))
466 (defcustom org-startup-with-beamer-mode nil
467 "Non-nil means turn on `org-beamer-mode' on startup.
468 This can also be configured on a per-file basis by adding one of
469 the following lines anywhere in the buffer:
471 #+STARTUP: beamer"
472 :group 'org-startup
473 :type 'boolean)
475 (defcustom org-startup-align-all-tables nil
476 "Non-nil means align all tables when visiting a file.
477 This is useful when the column width in tables is forced with <N> cookies
478 in table fields. Such tables will look correct only after the first re-align.
479 This can also be configured on a per-file basis by adding one of
480 the following lines anywhere in the buffer:
481 #+STARTUP: align
482 #+STARTUP: noalign"
483 :group 'org-startup
484 :type 'boolean)
486 (defcustom org-startup-with-inline-images nil
487 "Non-nil means show inline images when loading a new Org file.
488 This can also be configured on a per-file basis by adding one of
489 the following lines anywhere in the buffer:
490 #+STARTUP: inlineimages
491 #+STARTUP: noinlineimages"
492 :group 'org-startup
493 :type 'boolean)
495 (defcustom org-insert-mode-line-in-empty-file nil
496 "Non-nil means insert the first line setting Org-mode in empty files.
497 When the function `org-mode' is called interactively in an empty file, this
498 normally means that the file name does not automatically trigger Org-mode.
499 To ensure that the file will always be in Org-mode in the future, a
500 line enforcing Org-mode will be inserted into the buffer, if this option
501 has been set."
502 :group 'org-startup
503 :type 'boolean)
505 (defcustom org-replace-disputed-keys nil
506 "Non-nil means use alternative key bindings for some keys.
507 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
508 These keys are also used by other packages like shift-selection-mode'
509 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
510 If you want to use Org-mode together with one of these other modes,
511 or more generally if you would like to move some Org-mode commands to
512 other keys, set this variable and configure the keys with the variable
513 `org-disputed-keys'.
515 This option is only relevant at load-time of Org-mode, and must be set
516 *before* org.el is loaded. Changing it requires a restart of Emacs to
517 become effective."
518 :group 'org-startup
519 :type 'boolean)
521 (defcustom org-use-extra-keys nil
522 "Non-nil means use extra key sequence definitions for certain commands.
523 This happens automatically if you run XEmacs or if `window-system'
524 is nil. This variable lets you do the same manually. You must
525 set it before loading org.
527 Example: on Carbon Emacs 22 running graphically, with an external
528 keyboard on a Powerbook, the default way of setting M-left might
529 not work for either Alt or ESC. Setting this variable will make
530 it work for ESC."
531 :group 'org-startup
532 :type 'boolean)
534 (if (fboundp 'defvaralias)
535 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
537 (defcustom org-disputed-keys
538 '(([(shift up)] . [(meta p)])
539 ([(shift down)] . [(meta n)])
540 ([(shift left)] . [(meta -)])
541 ([(shift right)] . [(meta +)])
542 ([(control shift right)] . [(meta shift +)])
543 ([(control shift left)] . [(meta shift -)]))
544 "Keys for which Org-mode and other modes compete.
545 This is an alist, cars are the default keys, second element specifies
546 the alternative to use when `org-replace-disputed-keys' is t.
548 Keys can be specified in any syntax supported by `define-key'.
549 The value of this option takes effect only at Org-mode's startup,
550 therefore you'll have to restart Emacs to apply it after changing."
551 :group 'org-startup
552 :type 'alist)
554 (defun org-key (key)
555 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
556 Or return the original if not disputed.
557 Also apply the translations defined in `org-xemacs-key-equivalents'."
558 (when org-replace-disputed-keys
559 (let* ((nkey (key-description key))
560 (x (org-find-if (lambda (x)
561 (equal (key-description (car x)) nkey))
562 org-disputed-keys)))
563 (setq key (if x (cdr x) key))))
564 (when (featurep 'xemacs)
565 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
566 key)
568 (defun org-find-if (predicate seq)
569 (catch 'exit
570 (while seq
571 (if (funcall predicate (car seq))
572 (throw 'exit (car seq))
573 (pop seq)))))
575 (defun org-defkey (keymap key def)
576 "Define a key, possibly translated, as returned by `org-key'."
577 (define-key keymap (org-key key) def))
579 (defcustom org-ellipsis nil
580 "The ellipsis to use in the Org-mode outline.
581 When nil, just use the standard three dots. When a string, use that instead,
582 When a face, use the standard 3 dots, but with the specified face.
583 The change affects only Org-mode (which will then use its own display table).
584 Changing this requires executing `M-x org-mode' in a buffer to become
585 effective."
586 :group 'org-startup
587 :type '(choice (const :tag "Default" nil)
588 (face :tag "Face" :value org-warning)
589 (string :tag "String" :value "...#")))
591 (defvar org-display-table nil
592 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
594 (defgroup org-keywords nil
595 "Keywords in Org-mode."
596 :tag "Org Keywords"
597 :group 'org)
599 (defcustom org-deadline-string "DEADLINE:"
600 "String to mark deadline entries.
601 A deadline is this string, followed by a time stamp. Should be a word,
602 terminated by a colon. You can insert a schedule keyword and
603 a timestamp with \\[org-deadline].
604 Changes become only effective after restarting Emacs."
605 :group 'org-keywords
606 :type 'string)
608 (defcustom org-scheduled-string "SCHEDULED:"
609 "String to mark scheduled TODO entries.
610 A schedule is this string, followed by a time stamp. Should be a word,
611 terminated by a colon. You can insert a schedule keyword and
612 a timestamp with \\[org-schedule].
613 Changes become only effective after restarting Emacs."
614 :group 'org-keywords
615 :type 'string)
617 (defcustom org-closed-string "CLOSED:"
618 "String used as the prefix for timestamps logging closing a TODO entry."
619 :group 'org-keywords
620 :type 'string)
622 (defcustom org-clock-string "CLOCK:"
623 "String used as prefix for timestamps clocking work hours on an item."
624 :group 'org-keywords
625 :type 'string)
627 (defcustom org-comment-string "COMMENT"
628 "Entries starting with this keyword will never be exported.
629 An entry can be toggled between COMMENT and normal with
630 \\[org-toggle-comment].
631 Changes become only effective after restarting Emacs."
632 :group 'org-keywords
633 :type 'string)
635 (defcustom org-quote-string "QUOTE"
636 "Entries starting with this keyword will be exported in fixed-width font.
637 Quoting applies only to the text in the entry following the headline, and does
638 not extend beyond the next headline, even if that is lower level.
639 An entry can be toggled between QUOTE and normal with
640 \\[org-toggle-fixed-width-section]."
641 :group 'org-keywords
642 :type 'string)
644 (defconst org-repeat-re
645 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)"
646 "Regular expression for specifying repeated events.
647 After a match, group 1 contains the repeat expression.")
649 (defgroup org-structure nil
650 "Options concerning the general structure of Org-mode files."
651 :tag "Org Structure"
652 :group 'org)
654 (defgroup org-reveal-location nil
655 "Options about how to make context of a location visible."
656 :tag "Org Reveal Location"
657 :group 'org-structure)
659 (defconst org-context-choice
660 '(choice
661 (const :tag "Always" t)
662 (const :tag "Never" nil)
663 (repeat :greedy t :tag "Individual contexts"
664 (cons
665 (choice :tag "Context"
666 (const agenda)
667 (const org-goto)
668 (const occur-tree)
669 (const tags-tree)
670 (const link-search)
671 (const mark-goto)
672 (const bookmark-jump)
673 (const isearch)
674 (const default))
675 (boolean))))
676 "Contexts for the reveal options.")
678 (defcustom org-show-hierarchy-above '((default . t))
679 "Non-nil means show full hierarchy when revealing a location.
680 Org-mode often shows locations in an org-mode file which might have
681 been invisible before. When this is set, the hierarchy of headings
682 above the exposed location is shown.
683 Turning this off for example for sparse trees makes them very compact.
684 Instead of t, this can also be an alist specifying this option for different
685 contexts. Valid contexts are
686 agenda when exposing an entry from the agenda
687 org-goto when using the command `org-goto' on key C-c C-j
688 occur-tree when using the command `org-occur' on key C-c /
689 tags-tree when constructing a sparse tree based on tags matches
690 link-search when exposing search matches associated with a link
691 mark-goto when exposing the jump goal of a mark
692 bookmark-jump when exposing a bookmark location
693 isearch when exiting from an incremental search
694 default default for all contexts not set explicitly"
695 :group 'org-reveal-location
696 :type org-context-choice)
698 (defcustom org-show-following-heading '((default . nil))
699 "Non-nil means show following heading when revealing a location.
700 Org-mode often shows locations in an org-mode file which might have
701 been invisible before. When this is set, the heading following the
702 match is shown.
703 Turning this off for example for sparse trees makes them very compact,
704 but makes it harder to edit the location of the match. In such a case,
705 use the command \\[org-reveal] to show more context.
706 Instead of t, this can also be an alist specifying this option for different
707 contexts. See `org-show-hierarchy-above' for valid contexts."
708 :group 'org-reveal-location
709 :type org-context-choice)
711 (defcustom org-show-siblings '((default . nil) (isearch t))
712 "Non-nil means show all sibling heading when revealing a location.
713 Org-mode often shows locations in an org-mode file which might have
714 been invisible before. When this is set, the sibling of the current entry
715 heading are all made visible. If `org-show-hierarchy-above' is t,
716 the same happens on each level of the hierarchy above the current entry.
718 By default this is on for the isearch context, off for all other contexts.
719 Turning this off for example for sparse trees makes them very compact,
720 but makes it harder to edit the location of the match. In such a case,
721 use the command \\[org-reveal] to show more context.
722 Instead of t, this can also be an alist specifying this option for different
723 contexts. See `org-show-hierarchy-above' for valid contexts."
724 :group 'org-reveal-location
725 :type org-context-choice)
727 (defcustom org-show-entry-below '((default . nil))
728 "Non-nil means show the entry below a headline when revealing a location.
729 Org-mode often shows locations in an org-mode file which might have
730 been invisible before. When this is set, the text below the headline that is
731 exposed is also shown.
733 By default this is off for all contexts.
734 Instead of t, this can also be an alist specifying this option for different
735 contexts. See `org-show-hierarchy-above' for valid contexts."
736 :group 'org-reveal-location
737 :type org-context-choice)
739 (defcustom org-indirect-buffer-display 'other-window
740 "How should indirect tree buffers be displayed?
741 This applies to indirect buffers created with the commands
742 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
743 Valid values are:
744 current-window Display in the current window
745 other-window Just display in another window.
746 dedicated-frame Create one new frame, and re-use it each time.
747 new-frame Make a new frame each time. Note that in this case
748 previously-made indirect buffers are kept, and you need to
749 kill these buffers yourself."
750 :group 'org-structure
751 :group 'org-agenda-windows
752 :type '(choice
753 (const :tag "In current window" current-window)
754 (const :tag "In current frame, other window" other-window)
755 (const :tag "Each time a new frame" new-frame)
756 (const :tag "One dedicated frame" dedicated-frame)))
758 (defcustom org-use-speed-commands nil
759 "Non-nil means activate single letter commands at beginning of a headline.
760 This may also be a function to test for appropriate locations where speed
761 commands should be active."
762 :group 'org-structure
763 :type '(choice
764 (const :tag "Never" nil)
765 (const :tag "At beginning of headline stars" t)
766 (function)))
768 (defcustom org-speed-commands-user nil
769 "Alist of additional speed commands.
770 This list will be checked before `org-speed-commands-default'
771 when the variable `org-use-speed-commands' is non-nil
772 and when the cursor is at the beginning of a headline.
773 The car if each entry is a string with a single letter, which must
774 be assigned to `self-insert-command' in the global map.
775 The cdr is either a command to be called interactively, a function
776 to be called, or a form to be evaluated.
777 An entry that is just a list with a single string will be interpreted
778 as a descriptive headline that will be added when listing the speed
779 commands in the Help buffer using the `?' speed command."
780 :group 'org-structure
781 :type '(repeat :value ("k" . ignore)
782 (choice :value ("k" . ignore)
783 (list :tag "Descriptive Headline" (string :tag "Headline"))
784 (cons :tag "Letter and Command"
785 (string :tag "Command letter")
786 (choice
787 (function)
788 (sexp))))))
790 (defgroup org-cycle nil
791 "Options concerning visibility cycling in Org-mode."
792 :tag "Org Cycle"
793 :group 'org-structure)
795 (defcustom org-cycle-skip-children-state-if-no-children t
796 "Non-nil means skip CHILDREN state in entries that don't have any."
797 :group 'org-cycle
798 :type 'boolean)
800 (defcustom org-cycle-max-level nil
801 "Maximum level which should still be subject to visibility cycling.
802 Levels higher than this will, for cycling, be treated as text, not a headline.
803 When `org-odd-levels-only' is set, a value of N in this variable actually
804 means 2N-1 stars as the limiting headline.
805 When nil, cycle all levels.
806 Note that the limiting level of cycling is also influenced by
807 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
808 `org-inlinetask-min-level' is, cycling will be limited to levels one less
809 than its value."
810 :group 'org-cycle
811 :type '(choice
812 (const :tag "No limit" nil)
813 (integer :tag "Maximum level")))
815 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK")
816 "Names of drawers. Drawers are not opened by cycling on the headline above.
817 Drawers only open with a TAB on the drawer line itself. A drawer looks like
818 this:
819 :DRAWERNAME:
820 .....
821 :END:
822 The drawer \"PROPERTIES\" is special for capturing properties through
823 the property API.
825 Drawers can be defined on the per-file basis with a line like:
827 #+DRAWERS: HIDDEN STATE PROPERTIES"
828 :group 'org-structure
829 :group 'org-cycle
830 :type '(repeat (string :tag "Drawer Name")))
832 (defcustom org-hide-block-startup nil
833 "Non-nil means entering Org-mode will fold all blocks.
834 This can also be set in on a per-file basis with
836 #+STARTUP: hideblocks
837 #+STARTUP: showblocks"
838 :group 'org-startup
839 :group 'org-cycle
840 :type 'boolean)
842 (defcustom org-cycle-global-at-bob nil
843 "Cycle globally if cursor is at beginning of buffer and not at a headline.
844 This makes it possible to do global cycling without having to use S-TAB or
845 \\[universal-argument] TAB. For this special case to work, the first line \
846 of the buffer
847 must not be a headline - it may be empty or some other text. When used in
848 this way, `org-cycle-hook' is disables temporarily, to make sure the
849 cursor stays at the beginning of the buffer.
850 When this option is nil, don't do anything special at the beginning
851 of the buffer."
852 :group 'org-cycle
853 :type 'boolean)
855 (defcustom org-cycle-level-after-item/entry-creation t
856 "Non-nil means cycle entry level or item indentation in new empty entries.
858 When the cursor is at the end of an empty headline, i.e with only stars
859 and maybe a TODO keyword, TAB will then switch the entry to become a child,
860 and then all possible ancestor states, before returning to the original state.
861 This makes data entry extremely fast: M-RET to create a new headline,
862 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
864 When the cursor is at the end of an empty plain list item, one TAB will
865 make it a subitem, two or more tabs will back up to make this an item
866 higher up in the item hierarchy."
867 :group 'org-cycle
868 :type 'boolean)
870 (defcustom org-cycle-emulate-tab t
871 "Where should `org-cycle' emulate TAB.
872 nil Never
873 white Only in completely white lines
874 whitestart Only at the beginning of lines, before the first non-white char
875 t Everywhere except in headlines
876 exc-hl-bol Everywhere except at the start of a headline
877 If TAB is used in a place where it does not emulate TAB, the current subtree
878 visibility is cycled."
879 :group 'org-cycle
880 :type '(choice (const :tag "Never" nil)
881 (const :tag "Only in completely white lines" white)
882 (const :tag "Before first char in a line" whitestart)
883 (const :tag "Everywhere except in headlines" t)
884 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
887 (defcustom org-cycle-separator-lines 2
888 "Number of empty lines needed to keep an empty line between collapsed trees.
889 If you leave an empty line between the end of a subtree and the following
890 headline, this empty line is hidden when the subtree is folded.
891 Org-mode will leave (exactly) one empty line visible if the number of
892 empty lines is equal or larger to the number given in this variable.
893 So the default 2 means at least 2 empty lines after the end of a subtree
894 are needed to produce free space between a collapsed subtree and the
895 following headline.
897 If the number is negative, and the number of empty lines is at least -N,
898 all empty lines are shown.
900 Special case: when 0, never leave empty lines in collapsed view."
901 :group 'org-cycle
902 :type 'integer)
903 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
905 (defcustom org-pre-cycle-hook nil
906 "Hook that is run before visibility cycling is happening.
907 The function(s) in this hook must accept a single argument which indicates
908 the new state that will be set right after running this hook. The
909 argument is a symbol. Before a global state change, it can have the values
910 `overview', `content', or `all'. Before a local state change, it can have
911 the values `folded', `children', or `subtree'."
912 :group 'org-cycle
913 :type 'hook)
915 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
916 org-cycle-hide-drawers
917 org-cycle-show-empty-lines
918 org-optimize-window-after-visibility-change)
919 "Hook that is run after `org-cycle' has changed the buffer visibility.
920 The function(s) in this hook must accept a single argument which indicates
921 the new state that was set by the most recent `org-cycle' command. The
922 argument is a symbol. After a global state change, it can have the values
923 `overview', `content', or `all'. After a local state change, it can have
924 the values `folded', `children', or `subtree'."
925 :group 'org-cycle
926 :type 'hook)
928 (defgroup org-edit-structure nil
929 "Options concerning structure editing in Org-mode."
930 :tag "Org Edit Structure"
931 :group 'org-structure)
933 (defcustom org-odd-levels-only nil
934 "Non-nil means skip even levels and only use odd levels for the outline.
935 This has the effect that two stars are being added/taken away in
936 promotion/demotion commands. It also influences how levels are
937 handled by the exporters.
938 Changing it requires restart of `font-lock-mode' to become effective
939 for fontification also in regions already fontified.
940 You may also set this on a per-file basis by adding one of the following
941 lines to the buffer:
943 #+STARTUP: odd
944 #+STARTUP: oddeven"
945 :group 'org-edit-structure
946 :group 'org-appearance
947 :type 'boolean)
949 (defcustom org-adapt-indentation t
950 "Non-nil means adapt indentation to outline node level.
952 When this variable is set, Org assumes that you write outlines by
953 indenting text in each node to align with the headline (after the stars).
954 The following issues are influenced by this variable:
956 - When this is set and the *entire* text in an entry is indented, the
957 indentation is increased by one space in a demotion command, and
958 decreased by one in a promotion command. If any line in the entry
959 body starts with text at column 0, indentation is not changed at all.
961 - Property drawers and planning information is inserted indented when
962 this variable s set. When nil, they will not be indented.
964 - TAB indents a line relative to context. The lines below a headline
965 will be indented when this variable is set.
967 Note that this is all about true indentation, by adding and removing
968 space characters. See also `org-indent.el' which does level-dependent
969 indentation in a virtual way, i.e. at display time in Emacs."
970 :group 'org-edit-structure
971 :type 'boolean)
973 (defcustom org-special-ctrl-a/e nil
974 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
976 When t, `C-a' will bring back the cursor to the beginning of the
977 headline text, i.e. after the stars and after a possible TODO keyword.
978 In an item, this will be the position after the bullet.
979 When the cursor is already at that position, another `C-a' will bring
980 it to the beginning of the line.
982 `C-e' will jump to the end of the headline, ignoring the presence of tags
983 in the headline. A second `C-e' will then jump to the true end of the
984 line, after any tags. This also means that, when this variable is
985 non-nil, `C-e' also will never jump beyond the end of the heading of a
986 folded section, i.e. not after the ellipses.
988 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
989 going to the true line boundary first. Only a directly following, identical
990 keypress will bring the cursor to the special positions.
992 This may also be a cons cell where the behavior for `C-a' and `C-e' is
993 set separately."
994 :group 'org-edit-structure
995 :type '(choice
996 (const :tag "off" nil)
997 (const :tag "on: after stars/bullet and before tags first" t)
998 (const :tag "reversed: true line boundary first" reversed)
999 (cons :tag "Set C-a and C-e separately"
1000 (choice :tag "Special C-a"
1001 (const :tag "off" nil)
1002 (const :tag "on: after stars/bullet first" t)
1003 (const :tag "reversed: before stars/bullet first" reversed))
1004 (choice :tag "Special C-e"
1005 (const :tag "off" nil)
1006 (const :tag "on: before tags first" t)
1007 (const :tag "reversed: after tags first" reversed)))))
1008 (if (fboundp 'defvaralias)
1009 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
1011 (defcustom org-special-ctrl-k nil
1012 "Non-nil means `C-k' will behave specially in headlines.
1013 When nil, `C-k' will call the default `kill-line' command.
1014 When t, the following will happen while the cursor is in the headline:
1016 - When the cursor is at the beginning of a headline, kill the entire
1017 line and possible the folded subtree below the line.
1018 - When in the middle of the headline text, kill the headline up to the tags.
1019 - When after the headline text, kill the tags."
1020 :group 'org-edit-structure
1021 :type 'boolean)
1023 (defcustom org-ctrl-k-protect-subtree nil
1024 "Non-nil means, do not delete a hidden subtree with C-k.
1025 When set to the symbol `error', simply throw an error when C-k is
1026 used to kill (part-of) a headline that has hidden text behind it.
1027 Any other non-nil value will result in a query to the user, if it is
1028 OK to kill that hidden subtree. When nil, kill without remorse."
1029 :group 'org-edit-structure
1030 :type '(choice
1031 (const :tag "Do not protect hidden subtrees" nil)
1032 (const :tag "Protect hidden subtrees with a security query" t)
1033 (const :tag "Never kill a hidden subtree with C-k" error)))
1035 (defcustom org-yank-folded-subtrees t
1036 "Non-nil means when yanking subtrees, fold them.
1037 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1038 it starts with a heading and all other headings in it are either children
1039 or siblings, then fold all the subtrees. However, do this only if no
1040 text after the yank would be swallowed into a folded tree by this action."
1041 :group 'org-edit-structure
1042 :type 'boolean)
1044 (defcustom org-yank-adjusted-subtrees nil
1045 "Non-nil means when yanking subtrees, adjust the level.
1046 With this setting, `org-paste-subtree' is used to insert the subtree, see
1047 this function for details."
1048 :group 'org-edit-structure
1049 :type 'boolean)
1051 (defcustom org-M-RET-may-split-line '((default . t))
1052 "Non-nil means M-RET will split the line at the cursor position.
1053 When nil, it will go to the end of the line before making a
1054 new line.
1055 You may also set this option in a different way for different
1056 contexts. Valid contexts are:
1058 headline when creating a new headline
1059 item when creating a new item
1060 table in a table field
1061 default the value to be used for all contexts not explicitly
1062 customized"
1063 :group 'org-structure
1064 :group 'org-table
1065 :type '(choice
1066 (const :tag "Always" t)
1067 (const :tag "Never" nil)
1068 (repeat :greedy t :tag "Individual contexts"
1069 (cons
1070 (choice :tag "Context"
1071 (const headline)
1072 (const item)
1073 (const table)
1074 (const default))
1075 (boolean)))))
1078 (defcustom org-insert-heading-respect-content nil
1079 "Non-nil means insert new headings after the current subtree.
1080 When nil, the new heading is created directly after the current line.
1081 The commands \\[org-insert-heading-respect-content] and
1082 \\[org-insert-todo-heading-respect-content] turn this variable on
1083 for the duration of the command."
1084 :group 'org-structure
1085 :type 'boolean)
1087 (defcustom org-blank-before-new-entry '((heading . auto)
1088 (plain-list-item . auto))
1089 "Should `org-insert-heading' leave a blank line before new heading/item?
1090 The value is an alist, with `heading' and `plain-list-item' as car,
1091 and a boolean flag as cdr. The cdr may also be the symbol `auto', and then
1092 Org will look at the surrounding headings/items and try to make an
1093 intelligent decision whether to insert a blank line or not.
1095 For plain lists, if the variable `org-empty-line-terminates-plain-lists' is
1096 set, the setting here is ignored and no empty line is inserted, to avoid
1097 breaking the list structure."
1098 :group 'org-edit-structure
1099 :type '(list
1100 (cons (const heading)
1101 (choice (const :tag "Never" nil)
1102 (const :tag "Always" t)
1103 (const :tag "Auto" auto)))
1104 (cons (const plain-list-item)
1105 (choice (const :tag "Never" nil)
1106 (const :tag "Always" t)
1107 (const :tag "Auto" auto)))))
1109 (defcustom org-insert-heading-hook nil
1110 "Hook being run after inserting a new heading."
1111 :group 'org-edit-structure
1112 :type 'hook)
1114 (defcustom org-enable-fixed-width-editor t
1115 "Non-nil means lines starting with \":\" are treated as fixed-width.
1116 This currently only means they are never auto-wrapped.
1117 When nil, such lines will be treated like ordinary lines.
1118 See also the QUOTE keyword."
1119 :group 'org-edit-structure
1120 :type 'boolean)
1122 (defcustom org-goto-auto-isearch t
1123 "Non-nil means typing characters in `org-goto' starts incremental search."
1124 :group 'org-edit-structure
1125 :type 'boolean)
1127 (defgroup org-sparse-trees nil
1128 "Options concerning sparse trees in Org-mode."
1129 :tag "Org Sparse Trees"
1130 :group 'org-structure)
1132 (defcustom org-highlight-sparse-tree-matches t
1133 "Non-nil means highlight all matches that define a sparse tree.
1134 The highlights will automatically disappear the next time the buffer is
1135 changed by an edit command."
1136 :group 'org-sparse-trees
1137 :type 'boolean)
1139 (defcustom org-remove-highlights-with-change t
1140 "Non-nil means any change to the buffer will remove temporary highlights.
1141 Such highlights are created by `org-occur' and `org-clock-display'.
1142 When nil, `C-c C-c needs to be used to get rid of the highlights.
1143 The highlights created by `org-preview-latex-fragment' always need
1144 `C-c C-c' to be removed."
1145 :group 'org-sparse-trees
1146 :group 'org-time
1147 :type 'boolean)
1150 (defcustom org-occur-hook '(org-first-headline-recenter)
1151 "Hook that is run after `org-occur' has constructed a sparse tree.
1152 This can be used to recenter the window to show as much of the structure
1153 as possible."
1154 :group 'org-sparse-trees
1155 :type 'hook)
1157 (defgroup org-imenu-and-speedbar nil
1158 "Options concerning imenu and speedbar in Org-mode."
1159 :tag "Org Imenu and Speedbar"
1160 :group 'org-structure)
1162 (defcustom org-imenu-depth 2
1163 "The maximum level for Imenu access to Org-mode headlines.
1164 This also applied for speedbar access."
1165 :group 'org-imenu-and-speedbar
1166 :type 'integer)
1168 (defgroup org-table nil
1169 "Options concerning tables in Org-mode."
1170 :tag "Org Table"
1171 :group 'org)
1173 (defcustom org-enable-table-editor 'optimized
1174 "Non-nil means lines starting with \"|\" are handled by the table editor.
1175 When nil, such lines will be treated like ordinary lines.
1177 When equal to the symbol `optimized', the table editor will be optimized to
1178 do the following:
1179 - Automatic overwrite mode in front of whitespace in table fields.
1180 This makes the structure of the table stay in tact as long as the edited
1181 field does not exceed the column width.
1182 - Minimize the number of realigns. Normally, the table is aligned each time
1183 TAB or RET are pressed to move to another field. With optimization this
1184 happens only if changes to a field might have changed the column width.
1185 Optimization requires replacing the functions `self-insert-command',
1186 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1187 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1188 very good at guessing when a re-align will be necessary, but you can always
1189 force one with \\[org-ctrl-c-ctrl-c].
1191 If you would like to use the optimized version in Org-mode, but the
1192 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1194 This variable can be used to turn on and off the table editor during a session,
1195 but in order to toggle optimization, a restart is required.
1197 See also the variable `org-table-auto-blank-field'."
1198 :group 'org-table
1199 :type '(choice
1200 (const :tag "off" nil)
1201 (const :tag "on" t)
1202 (const :tag "on, optimized" optimized)))
1204 (defcustom org-self-insert-cluster-for-undo t
1205 "Non-nil means cluster self-insert commands for undo when possible.
1206 If this is set, then, like in the Emacs command loop, 20 consecutive
1207 characters will be undone together.
1208 This is configurable, because there is some impact on typing performance."
1209 :group 'org-table
1210 :type 'boolean)
1212 (defcustom org-table-tab-recognizes-table.el t
1213 "Non-nil means TAB will automatically notice a table.el table.
1214 When it sees such a table, it moves point into it and - if necessary -
1215 calls `table-recognize-table'."
1216 :group 'org-table-editing
1217 :type 'boolean)
1219 (defgroup org-link nil
1220 "Options concerning links in Org-mode."
1221 :tag "Org Link"
1222 :group 'org)
1224 (defvar org-link-abbrev-alist-local nil
1225 "Buffer-local version of `org-link-abbrev-alist', which see.
1226 The value of this is taken from the #+LINK lines.")
1227 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1229 (defcustom org-link-abbrev-alist nil
1230 "Alist of link abbreviations.
1231 The car of each element is a string, to be replaced at the start of a link.
1232 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1233 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1235 [[linkkey:tag][description]]
1237 The 'linkkey' must be a word word, starting with a letter, followed
1238 by letters, numbers, '-' or '_'.
1240 If REPLACE is a string, the tag will simply be appended to create the link.
1241 If the string contains \"%s\", the tag will be inserted there. Alternatively,
1242 the placeholder \"%h\" will cause a url-encoded version of the tag to
1243 be inserted at that point (see the function `url-hexify-string').
1245 REPLACE may also be a function that will be called with the tag as the
1246 only argument to create the link, which should be returned as a string.
1248 See the manual for examples."
1249 :group 'org-link
1250 :type '(repeat
1251 (cons
1252 (string :tag "Protocol")
1253 (choice
1254 (string :tag "Format")
1255 (function)))))
1257 (defcustom org-descriptive-links t
1258 "Non-nil means hide link part and only show description of bracket links.
1259 Bracket links are like [[link][description]]. This variable sets the initial
1260 state in new org-mode buffers. The setting can then be toggled on a
1261 per-buffer basis from the Org->Hyperlinks menu."
1262 :group 'org-link
1263 :type 'boolean)
1265 (defcustom org-link-file-path-type 'adaptive
1266 "How the path name in file links should be stored.
1267 Valid values are:
1269 relative Relative to the current directory, i.e. the directory of the file
1270 into which the link is being inserted.
1271 absolute Absolute path, if possible with ~ for home directory.
1272 noabbrev Absolute path, no abbreviation of home directory.
1273 adaptive Use relative path for files in the current directory and sub-
1274 directories of it. For other files, use an absolute path."
1275 :group 'org-link
1276 :type '(choice
1277 (const relative)
1278 (const absolute)
1279 (const noabbrev)
1280 (const adaptive)))
1282 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1283 "Types of links that should be activated in Org-mode files.
1284 This is a list of symbols, each leading to the activation of a certain link
1285 type. In principle, it does not hurt to turn on most link types - there may
1286 be a small gain when turning off unused link types. The types are:
1288 bracket The recommended [[link][description]] or [[link]] links with hiding.
1289 angle Links in angular brackets that may contain whitespace like
1290 <bbdb:Carsten Dominik>.
1291 plain Plain links in normal text, no whitespace, like http://google.com.
1292 radio Text that is matched by a radio target, see manual for details.
1293 tag Tag settings in a headline (link to tag search).
1294 date Time stamps (link to calendar).
1295 footnote Footnote labels.
1297 Changing this variable requires a restart of Emacs to become effective."
1298 :group 'org-link
1299 :type '(set :greedy t
1300 (const :tag "Double bracket links" bracket)
1301 (const :tag "Angular bracket links" angle)
1302 (const :tag "Plain text links" plain)
1303 (const :tag "Radio target matches" radio)
1304 (const :tag "Tags" tag)
1305 (const :tag "Timestamps" date)
1306 (const :tag "Footnotes" footnote)))
1308 (defcustom org-make-link-description-function nil
1309 "Function to use to generate link descriptions from links.
1310 If nil the link location will be used. This function must take
1311 two parameters; the first is the link and the second the
1312 description `org-insert-link' has generated, and should return the
1313 description to use."
1314 :group 'org-link
1315 :type 'function)
1317 (defgroup org-link-store nil
1318 "Options concerning storing links in Org-mode."
1319 :tag "Org Store Link"
1320 :group 'org-link)
1322 (defcustom org-email-link-description-format "Email %c: %.30s"
1323 "Format of the description part of a link to an email or usenet message.
1324 The following %-escapes will be replaced by corresponding information:
1326 %F full \"From\" field
1327 %f name, taken from \"From\" field, address if no name
1328 %T full \"To\" field
1329 %t first name in \"To\" field, address if no name
1330 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1331 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1332 %s subject
1333 %d date
1334 %m message-id.
1336 You may use normal field width specification between the % and the letter.
1337 This is for example useful to limit the length of the subject.
1339 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1340 :group 'org-link-store
1341 :type 'string)
1343 (defcustom org-from-is-user-regexp
1344 (let (r1 r2)
1345 (when (and user-mail-address (not (string= user-mail-address "")))
1346 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1347 (when (and user-full-name (not (string= user-full-name "")))
1348 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1349 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1350 "Regexp matched against the \"From:\" header of an email or usenet message.
1351 It should match if the message is from the user him/herself."
1352 :group 'org-link-store
1353 :type 'regexp)
1355 (defcustom org-link-to-org-use-id 'create-if-interactive-and-no-custom-id
1356 "Non-nil means storing a link to an Org file will use entry IDs.
1358 Note that before this variable is even considered, org-id must be loaded,
1359 so please customize `org-modules' and turn it on.
1361 The variable can have the following values:
1363 t Create an ID if needed to make a link to the current entry.
1365 create-if-interactive
1366 If `org-store-link' is called directly (interactively, as a user
1367 command), do create an ID to support the link. But when doing the
1368 job for remember, only use the ID if it already exists. The
1369 purpose of this setting is to avoid proliferation of unwanted
1370 IDs, just because you happen to be in an Org file when you
1371 call `org-remember' that automatically and preemptively
1372 creates a link. If you do want to get an ID link in a remember
1373 template to an entry not having an ID, create it first by
1374 explicitly creating a link to it, using `C-c C-l' first.
1376 create-if-interactive-and-no-custom-id
1377 Like create-if-interactive, but do not create an ID if there is
1378 a CUSTOM_ID property defined in the entry. This is the default.
1380 use-existing
1381 Use existing ID, do not create one.
1383 nil Never use an ID to make a link, instead link using a text search for
1384 the headline text."
1385 :group 'org-link-store
1386 :type '(choice
1387 (const :tag "Create ID to make link" t)
1388 (const :tag "Create if storing link interactively"
1389 create-if-interactive)
1390 (const :tag "Create if storing link interactively and no CUSTOM_ID is present"
1391 create-if-interactive-and-no-custom-id)
1392 (const :tag "Only use existing" use-existing)
1393 (const :tag "Do not use ID to create link" nil)))
1395 (defcustom org-context-in-file-links t
1396 "Non-nil means file links from `org-store-link' contain context.
1397 A search string will be added to the file name with :: as separator and
1398 used to find the context when the link is activated by the command
1399 `org-open-at-point'. When this option is t, the entire active region
1400 will be placed in the search string of the file link. If set to a
1401 positive integer, only the first n lines of context will be stored.
1403 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1404 negates this setting for the duration of the command."
1405 :group 'org-link-store
1406 :type '(choice boolean integer))
1408 (defcustom org-keep-stored-link-after-insertion nil
1409 "Non-nil means keep link in list for entire session.
1411 The command `org-store-link' adds a link pointing to the current
1412 location to an internal list. These links accumulate during a session.
1413 The command `org-insert-link' can be used to insert links into any
1414 Org-mode file (offering completion for all stored links). When this
1415 option is nil, every link which has been inserted once using \\[org-insert-link]
1416 will be removed from the list, to make completing the unused links
1417 more efficient."
1418 :group 'org-link-store
1419 :type 'boolean)
1421 (defgroup org-link-follow nil
1422 "Options concerning following links in Org-mode."
1423 :tag "Org Follow Link"
1424 :group 'org-link)
1426 (defcustom org-link-translation-function nil
1427 "Function to translate links with different syntax to Org syntax.
1428 This can be used to translate links created for example by the Planner
1429 or emacs-wiki packages to Org syntax.
1430 The function must accept two parameters, a TYPE containing the link
1431 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1432 which is everything after the link protocol. It should return a cons
1433 with possibly modified values of type and path.
1434 Org contains a function for this, so if you set this variable to
1435 `org-translate-link-from-planner', you should be able follow many
1436 links created by planner."
1437 :group 'org-link-follow
1438 :type 'function)
1440 (defcustom org-follow-link-hook nil
1441 "Hook that is run after a link has been followed."
1442 :group 'org-link-follow
1443 :type 'hook)
1445 (defcustom org-tab-follows-link nil
1446 "Non-nil means on links TAB will follow the link.
1447 Needs to be set before org.el is loaded.
1448 This really should not be used, it does not make sense, and the
1449 implementation is bad."
1450 :group 'org-link-follow
1451 :type 'boolean)
1453 (defcustom org-return-follows-link nil
1454 "Non-nil means on links RET will follow the link."
1455 :group 'org-link-follow
1456 :type 'boolean)
1458 (defcustom org-mouse-1-follows-link
1459 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1460 "Non-nil means mouse-1 on a link will follow the link.
1461 A longer mouse click will still set point. Does not work on XEmacs.
1462 Needs to be set before org.el is loaded."
1463 :group 'org-link-follow
1464 :type 'boolean)
1466 (defcustom org-mark-ring-length 4
1467 "Number of different positions to be recorded in the ring.
1468 Changing this requires a restart of Emacs to work correctly."
1469 :group 'org-link-follow
1470 :type 'integer)
1472 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1473 "Non-nil means internal links in Org files must exactly match a headline.
1474 When nil, the link search tries to match a phrase with all words
1475 in the search text."
1476 :group 'org-link-follow
1477 :type '(choice
1478 (const :tag "Use fuzy text search" nil)
1479 (const :tag "Match only exact headline" t)
1480 (const :tag "Match extact headline or query to create it"
1481 query-to-create)))
1483 (defcustom org-link-frame-setup
1484 '((vm . vm-visit-folder-other-frame)
1485 (gnus . org-gnus-no-new-news)
1486 (file . find-file-other-window)
1487 (wl . wl-other-frame))
1488 "Setup the frame configuration for following links.
1489 When following a link with Emacs, it may often be useful to display
1490 this link in another window or frame. This variable can be used to
1491 set this up for the different types of links.
1492 For VM, use any of
1493 `vm-visit-folder'
1494 `vm-visit-folder-other-window'
1495 `vm-visit-folder-other-frame'
1496 For Gnus, use any of
1497 `gnus'
1498 `gnus-other-frame'
1499 `org-gnus-no-new-news'
1500 For FILE, use any of
1501 `find-file'
1502 `find-file-other-window'
1503 `find-file-other-frame'
1504 For Wanderlust use any of
1505 `wl'
1506 `wl-other-frame'
1507 For the calendar, use the variable `calendar-setup'.
1508 For BBDB, it is currently only possible to display the matches in
1509 another window."
1510 :group 'org-link-follow
1511 :type '(list
1512 (cons (const vm)
1513 (choice
1514 (const vm-visit-folder)
1515 (const vm-visit-folder-other-window)
1516 (const vm-visit-folder-other-frame)))
1517 (cons (const gnus)
1518 (choice
1519 (const gnus)
1520 (const gnus-other-frame)
1521 (const org-gnus-no-new-news)))
1522 (cons (const file)
1523 (choice
1524 (const find-file)
1525 (const find-file-other-window)
1526 (const find-file-other-frame)))
1527 (cons (const wl)
1528 (choice
1529 (const wl)
1530 (const wl-other-frame)))))
1532 (defcustom org-display-internal-link-with-indirect-buffer nil
1533 "Non-nil means use indirect buffer to display infile links.
1534 Activating internal links (from one location in a file to another location
1535 in the same file) normally just jumps to the location. When the link is
1536 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1537 is displayed in
1538 another window. When this option is set, the other window actually displays
1539 an indirect buffer clone of the current buffer, to avoid any visibility
1540 changes to the current buffer."
1541 :group 'org-link-follow
1542 :type 'boolean)
1544 (defcustom org-open-non-existing-files nil
1545 "Non-nil means `org-open-file' will open non-existing files.
1546 When nil, an error will be generated.
1547 This variable applies only to external applications because they
1548 might choke on non-existing files. If the link is to a file that
1549 will be opened in Emacs, the variable is ignored."
1550 :group 'org-link-follow
1551 :type 'boolean)
1553 (defcustom org-open-directory-means-index-dot-org nil
1554 "Non-nil means a link to a directory really means to index.org.
1555 When nil, following a directory link will run dired or open a finder/explorer
1556 window on that directory."
1557 :group 'org-link-follow
1558 :type 'boolean)
1560 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1561 "Function and arguments to call for following mailto links.
1562 This is a list with the first element being a Lisp function, and the
1563 remaining elements being arguments to the function. In string arguments,
1564 %a will be replaced by the address, and %s will be replaced by the subject
1565 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1566 :group 'org-link-follow
1567 :type '(choice
1568 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1569 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1570 (const :tag "message-mail" (message-mail "%a" "%s"))
1571 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1573 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1574 "Non-nil means ask for confirmation before executing shell links.
1575 Shell links can be dangerous: just think about a link
1577 [[shell:rm -rf ~/*][Google Search]]
1579 This link would show up in your Org-mode document as \"Google Search\",
1580 but really it would remove your entire home directory.
1581 Therefore we advise against setting this variable to nil.
1582 Just change it to `y-or-n-p' if you want to confirm with a
1583 single keystroke rather than having to type \"yes\"."
1584 :group 'org-link-follow
1585 :type '(choice
1586 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1587 (const :tag "with y-or-n (faster)" y-or-n-p)
1588 (const :tag "no confirmation (dangerous)" nil)))
1589 (put 'org-confirm-shell-link-function
1590 'safe-local-variable
1591 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1593 (defcustom org-confirm-shell-link-not-regexp ""
1594 "A regexp to skip confirmation for shell links."
1595 :group 'org-link-follow
1596 :type 'regexp)
1598 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1599 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1600 Elisp links can be dangerous: just think about a link
1602 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1604 This link would show up in your Org-mode document as \"Google Search\",
1605 but really it would remove your entire home directory.
1606 Therefore we advise against setting this variable to nil.
1607 Just change it to `y-or-n-p' if you want to confirm with a
1608 single keystroke rather than having to type \"yes\"."
1609 :group 'org-link-follow
1610 :type '(choice
1611 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1612 (const :tag "with y-or-n (faster)" y-or-n-p)
1613 (const :tag "no confirmation (dangerous)" nil)))
1614 (put 'org-confirm-shell-link-function
1615 'safe-local-variable
1616 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1618 (defcustom org-confirm-elisp-link-not-regexp ""
1619 "A regexp to skip confirmation for Elisp links."
1620 :group 'org-link-follow
1621 :type 'regexp)
1623 (defconst org-file-apps-defaults-gnu
1624 '((remote . emacs)
1625 (system . mailcap)
1626 (t . mailcap))
1627 "Default file applications on a UNIX or GNU/Linux system.
1628 See `org-file-apps'.")
1630 (defconst org-file-apps-defaults-macosx
1631 '((remote . emacs)
1632 (t . "open %s")
1633 (system . "open %s")
1634 ("ps.gz" . "gv %s")
1635 ("eps.gz" . "gv %s")
1636 ("dvi" . "xdvi %s")
1637 ("fig" . "xfig %s"))
1638 "Default file applications on a MacOS X system.
1639 The system \"open\" is known as a default, but we use X11 applications
1640 for some files for which the OS does not have a good default.
1641 See `org-file-apps'.")
1643 (defconst org-file-apps-defaults-windowsnt
1644 (list
1645 '(remote . emacs)
1646 (cons t
1647 (list (if (featurep 'xemacs)
1648 'mswindows-shell-execute
1649 'w32-shell-execute)
1650 "open" 'file))
1651 (cons 'system
1652 (list (if (featurep 'xemacs)
1653 'mswindows-shell-execute
1654 'w32-shell-execute)
1655 "open" 'file)))
1656 "Default file applications on a Windows NT system.
1657 The system \"open\" is used for most files.
1658 See `org-file-apps'.")
1660 (defcustom org-file-apps
1662 (auto-mode . emacs)
1663 ("\\.mm\\'" . default)
1664 ("\\.x?html?\\'" . default)
1665 ("\\.pdf\\'" . default)
1667 "External applications for opening `file:path' items in a document.
1668 Org-mode uses system defaults for different file types, but
1669 you can use this variable to set the application for a given file
1670 extension. The entries in this list are cons cells where the car identifies
1671 files and the cdr the corresponding command. Possible values for the
1672 file identifier are
1673 \"string\" A string as a file identifier can be interpreted in different
1674 ways, depending on its contents:
1676 - Alphanumeric characters only:
1677 Match links with this file extension.
1678 Example: (\"pdf\" . \"evince %s\")
1679 to open PDFs with evince.
1681 - Regular expression: Match links where the
1682 filename matches the regexp. If you want to
1683 use groups here, use shy groups.
1685 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1686 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1687 to open *.html and *.xhtml with firefox.
1689 - Regular expression which contains (non-shy) groups:
1690 Match links where the whole link, including \"::\", and
1691 anything after that, matches the regexp.
1692 In a custom command string, %1, %2, etc. are replaced with
1693 the parts of the link that were matched by the groups.
1694 For backwards compatibility, if a command string is given
1695 that does not use any of the group matches, this case is
1696 handled identically to the second one (i.e. match against
1697 file name only).
1698 In a custom lisp form, you can access the group matches with
1699 (match-string n link).
1701 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1702 to open [[file:document.pdf::5]] with evince at page 5.
1704 `directory' Matches a directory
1705 `remote' Matches a remote file, accessible through tramp or efs.
1706 Remote files most likely should be visited through Emacs
1707 because external applications cannot handle such paths.
1708 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1709 so all files Emacs knows how to handle. Using this with
1710 command `emacs' will open most files in Emacs. Beware that this
1711 will also open html files inside Emacs, unless you add
1712 (\"html\" . default) to the list as well.
1713 t Default for files not matched by any of the other options.
1714 `system' The system command to open files, like `open' on Windows
1715 and Mac OS X, and mailcap under GNU/Linux. This is the command
1716 that will be selected if you call `C-c C-o' with a double
1717 \\[universal-argument] \\[universal-argument] prefix.
1719 Possible values for the command are:
1720 `emacs' The file will be visited by the current Emacs process.
1721 `default' Use the default application for this file type, which is the
1722 association for t in the list, most likely in the system-specific
1723 part.
1724 This can be used to overrule an unwanted setting in the
1725 system-specific variable.
1726 `system' Use the system command for opening files, like \"open\".
1727 This command is specified by the entry whose car is `system'.
1728 Most likely, the system-specific version of this variable
1729 does define this command, but you can overrule/replace it
1730 here.
1731 string A command to be executed by a shell; %s will be replaced
1732 by the path to the file.
1733 sexp A Lisp form which will be evaluated. The file path will
1734 be available in the Lisp variable `file'.
1735 For more examples, see the system specific constants
1736 `org-file-apps-defaults-macosx'
1737 `org-file-apps-defaults-windowsnt'
1738 `org-file-apps-defaults-gnu'."
1739 :group 'org-link-follow
1740 :type '(repeat
1741 (cons (choice :value ""
1742 (string :tag "Extension")
1743 (const :tag "System command to open files" system)
1744 (const :tag "Default for unrecognized files" t)
1745 (const :tag "Remote file" remote)
1746 (const :tag "Links to a directory" directory)
1747 (const :tag "Any files that have Emacs modes"
1748 auto-mode))
1749 (choice :value ""
1750 (const :tag "Visit with Emacs" emacs)
1751 (const :tag "Use default" default)
1752 (const :tag "Use the system command" system)
1753 (string :tag "Command")
1754 (sexp :tag "Lisp form")))))
1758 (defgroup org-refile nil
1759 "Options concerning refiling entries in Org-mode."
1760 :tag "Org Refile"
1761 :group 'org)
1763 (defcustom org-directory "~/org"
1764 "Directory with org files.
1765 This is just a default location to look for Org files. There is no need
1766 at all to put your files into this directory. It is only used in the
1767 following situations:
1769 1. When a remember template specifies a target file that is not an
1770 absolute path. The path will then be interpreted relative to
1771 `org-directory'
1772 2. When a remember note is filed away in an interactive way (when exiting the
1773 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1774 with `org-directory' as the default path."
1775 :group 'org-refile
1776 :group 'org-remember
1777 :type 'directory)
1779 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1780 "Default target for storing notes.
1781 Used as a fall back file for org-remember.el and org-capture.el, for
1782 templates that do not specify a target file."
1783 :group 'org-refile
1784 :group 'org-remember
1785 :type '(choice
1786 (const :tag "Default from remember-data-file" nil)
1787 file))
1789 (defcustom org-goto-interface 'outline
1790 "The default interface to be used for `org-goto'.
1791 Allowed values are:
1792 outline The interface shows an outline of the relevant file
1793 and the correct heading is found by moving through
1794 the outline or by searching with incremental search.
1795 outline-path-completion Headlines in the current buffer are offered via
1796 completion. This is the interface also used by
1797 the refile command."
1798 :group 'org-refile
1799 :type '(choice
1800 (const :tag "Outline" outline)
1801 (const :tag "Outline-path-completion" outline-path-completion)))
1803 (defcustom org-goto-max-level 5
1804 "Maximum target level when running `org-goto' with refile interface."
1805 :group 'org-refile
1806 :type 'integer)
1808 (defcustom org-reverse-note-order nil
1809 "Non-nil means store new notes at the beginning of a file or entry.
1810 When nil, new notes will be filed to the end of a file or entry.
1811 This can also be a list with cons cells of regular expressions that
1812 are matched against file names, and values."
1813 :group 'org-remember
1814 :group 'org-refile
1815 :type '(choice
1816 (const :tag "Reverse always" t)
1817 (const :tag "Reverse never" nil)
1818 (repeat :tag "By file name regexp"
1819 (cons regexp boolean))))
1821 (defcustom org-log-refile nil
1822 "Information to record when a task is refiled.
1824 Possible values are:
1826 nil Don't add anything
1827 time Add a time stamp to the task
1828 note Prompt for a note and add it with template `org-log-note-headings'
1830 This option can also be set with on a per-file-basis with
1832 #+STARTUP: nologrefile
1833 #+STARTUP: logrefile
1834 #+STARTUP: lognoterefile
1836 You can have local logging settings for a subtree by setting the LOGGING
1837 property to one or more of these keywords.
1839 When bulk-refiling from the agenda, the value `note' is forbidden and
1840 will temporarily be changed to `time'."
1841 :group 'org-refile
1842 :group 'org-progress
1843 :type '(choice
1844 (const :tag "No logging" nil)
1845 (const :tag "Record timestamp" time)
1846 (const :tag "Record timestamp with note." note)))
1848 (defcustom org-refile-targets nil
1849 "Targets for refiling entries with \\[org-refile].
1850 This is list of cons cells. Each cell contains:
1851 - a specification of the files to be considered, either a list of files,
1852 or a symbol whose function or variable value will be used to retrieve
1853 a file name or a list of file names. If you use `org-agenda-files' for
1854 that, all agenda files will be scanned for targets. Nil means consider
1855 headings in the current buffer.
1856 - A specification of how to find candidate refile targets. This may be
1857 any of:
1858 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1859 This tag has to be present in all target headlines, inheritance will
1860 not be considered.
1861 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1862 todo keyword.
1863 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1864 headlines that are refiling targets.
1865 - a cons cell (:level . N). Any headline of level N is considered a target.
1866 Note that, when `org-odd-levels-only' is set, level corresponds to
1867 order in hierarchy, not to the number of stars.
1868 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1869 Note that, when `org-odd-levels-only' is set, level corresponds to
1870 order in hierarchy, not to the number of stars.
1872 You can set the variable `org-refile-target-verify-function' to a function
1873 to verify each headline found by the simple criteria above.
1875 When this variable is nil, all top-level headlines in the current buffer
1876 are used, equivalent to the value `((nil . (:level . 1))'."
1877 :group 'org-refile
1878 :type '(repeat
1879 (cons
1880 (choice :value org-agenda-files
1881 (const :tag "All agenda files" org-agenda-files)
1882 (const :tag "Current buffer" nil)
1883 (function) (variable) (file))
1884 (choice :tag "Identify target headline by"
1885 (cons :tag "Specific tag" (const :value :tag) (string))
1886 (cons :tag "TODO keyword" (const :value :todo) (string))
1887 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1888 (cons :tag "Level number" (const :value :level) (integer))
1889 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1891 (defcustom org-refile-target-verify-function nil
1892 "Function to verify if the headline at point should be a refile target.
1893 The function will be called without arguments, with point at the
1894 beginning of the headline. It should return t and leave point
1895 where it is if the headline is a valid target for refiling.
1897 If the target should not be selected, the function must return nil.
1898 In addition to this, it may move point to a place from where the search
1899 should be continued. For example, the function may decide that the entire
1900 subtree of the current entry should be excluded and move point to the end
1901 of the subtree."
1902 :group 'org-refile
1903 :type 'function)
1905 (defcustom org-refile-use-cache nil
1906 "Non-nil means cache refile targets to speed up the process.
1907 The cache for a particular file will be updated automatically when
1908 the buffer has been killed, or when any of the marker used for flagging
1909 refile targets no longer points at a live buffer.
1910 If you have added new entries to a buffer that might themselves be targets,
1911 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
1912 find that easier, `C-u C-u C-u C-c C-w'."
1913 :group 'org-refile
1914 :type 'boolean)
1916 (defcustom org-refile-use-outline-path nil
1917 "Non-nil means provide refile targets as paths.
1918 So a level 3 headline will be available as level1/level2/level3.
1920 When the value is `file', also include the file name (without directory)
1921 into the path. In this case, you can also stop the completion after
1922 the file name, to get entries inserted as top level in the file.
1924 When `full-file-path', include the full file path."
1925 :group 'org-refile
1926 :type '(choice
1927 (const :tag "Not" nil)
1928 (const :tag "Yes" t)
1929 (const :tag "Start with file name" file)
1930 (const :tag "Start with full file path" full-file-path)))
1932 (defcustom org-outline-path-complete-in-steps t
1933 "Non-nil means complete the outline path in hierarchical steps.
1934 When Org-mode uses the refile interface to select an outline path
1935 \(see variable `org-refile-use-outline-path'), the completion of
1936 the path can be done is a single go, or if can be done in steps down
1937 the headline hierarchy. Going in steps is probably the best if you
1938 do not use a special completion package like `ido' or `icicles'.
1939 However, when using these packages, going in one step can be very
1940 fast, while still showing the whole path to the entry."
1941 :group 'org-refile
1942 :type 'boolean)
1944 (defcustom org-refile-allow-creating-parent-nodes nil
1945 "Non-nil means allow to create new nodes as refile targets.
1946 New nodes are then created by adding \"/new node name\" to the completion
1947 of an existing node. When the value of this variable is `confirm',
1948 new node creation must be confirmed by the user (recommended)
1949 When nil, the completion must match an existing entry.
1951 Note that, if the new heading is not seen by the criteria
1952 listed in `org-refile-targets', multiple instances of the same
1953 heading would be created by trying again to file under the new
1954 heading."
1955 :group 'org-refile
1956 :type '(choice
1957 (const :tag "Never" nil)
1958 (const :tag "Always" t)
1959 (const :tag "Prompt for confirmation" confirm)))
1961 (defgroup org-todo nil
1962 "Options concerning TODO items in Org-mode."
1963 :tag "Org TODO"
1964 :group 'org)
1966 (defgroup org-progress nil
1967 "Options concerning Progress logging in Org-mode."
1968 :tag "Org Progress"
1969 :group 'org-time)
1971 (defvar org-todo-interpretation-widgets
1973 (:tag "Sequence (cycling hits every state)" sequence)
1974 (:tag "Type (cycling directly to DONE)" type))
1975 "The available interpretation symbols for customizing `org-todo-keywords'.
1976 Interested libraries should add to this list.")
1978 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1979 "List of TODO entry keyword sequences and their interpretation.
1980 \\<org-mode-map>This is a list of sequences.
1982 Each sequence starts with a symbol, either `sequence' or `type',
1983 indicating if the keywords should be interpreted as a sequence of
1984 action steps, or as different types of TODO items. The first
1985 keywords are states requiring action - these states will select a headline
1986 for inclusion into the global TODO list Org-mode produces. If one of
1987 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
1988 signify that no further action is necessary. If \"|\" is not found,
1989 the last keyword is treated as the only DONE state of the sequence.
1991 The command \\[org-todo] cycles an entry through these states, and one
1992 additional state where no keyword is present. For details about this
1993 cycling, see the manual.
1995 TODO keywords and interpretation can also be set on a per-file basis with
1996 the special #+SEQ_TODO and #+TYP_TODO lines.
1998 Each keyword can optionally specify a character for fast state selection
1999 \(in combination with the variable `org-use-fast-todo-selection')
2000 and specifiers for state change logging, using the same syntax
2001 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
2002 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2003 indicates to record a time stamp each time this state is selected.
2005 Each keyword may also specify if a timestamp or a note should be
2006 recorded when entering or leaving the state, by adding additional
2007 characters in the parenthesis after the keyword. This looks like this:
2008 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2009 record only the time of the state change. With X and Y being either
2010 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2011 Y when leaving the state if and only if the *target* state does not
2012 define X. You may omit any of the fast-selection key or X or /Y,
2013 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2015 For backward compatibility, this variable may also be just a list
2016 of keywords - in this case the interpretation (sequence or type) will be
2017 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2018 :group 'org-todo
2019 :group 'org-keywords
2020 :type '(choice
2021 (repeat :tag "Old syntax, just keywords"
2022 (string :tag "Keyword"))
2023 (repeat :tag "New syntax"
2024 (cons
2025 (choice
2026 :tag "Interpretation"
2027 ;;Quick and dirty way to see
2028 ;;`org-todo-interpretations'. This takes the
2029 ;;place of item arguments
2030 :convert-widget
2031 (lambda (widget)
2032 (widget-put widget
2033 :args (mapcar
2034 #'(lambda (x)
2035 (widget-convert
2036 (cons 'const x)))
2037 org-todo-interpretation-widgets))
2038 widget))
2039 (repeat
2040 (string :tag "Keyword"))))))
2042 (defvar org-todo-keywords-1 nil
2043 "All TODO and DONE keywords active in a buffer.")
2044 (make-variable-buffer-local 'org-todo-keywords-1)
2045 (defvar org-todo-keywords-for-agenda nil)
2046 (defvar org-done-keywords-for-agenda nil)
2047 (defvar org-drawers-for-agenda nil)
2048 (defvar org-todo-keyword-alist-for-agenda nil)
2049 (defvar org-tag-alist-for-agenda nil)
2050 (defvar org-agenda-contributing-files nil)
2051 (defvar org-not-done-keywords nil)
2052 (make-variable-buffer-local 'org-not-done-keywords)
2053 (defvar org-done-keywords nil)
2054 (make-variable-buffer-local 'org-done-keywords)
2055 (defvar org-todo-heads nil)
2056 (make-variable-buffer-local 'org-todo-heads)
2057 (defvar org-todo-sets nil)
2058 (make-variable-buffer-local 'org-todo-sets)
2059 (defvar org-todo-log-states nil)
2060 (make-variable-buffer-local 'org-todo-log-states)
2061 (defvar org-todo-kwd-alist nil)
2062 (make-variable-buffer-local 'org-todo-kwd-alist)
2063 (defvar org-todo-key-alist nil)
2064 (make-variable-buffer-local 'org-todo-key-alist)
2065 (defvar org-todo-key-trigger nil)
2066 (make-variable-buffer-local 'org-todo-key-trigger)
2068 (defcustom org-todo-interpretation 'sequence
2069 "Controls how TODO keywords are interpreted.
2070 This variable is in principle obsolete and is only used for
2071 backward compatibility, if the interpretation of todo keywords is
2072 not given already in `org-todo-keywords'. See that variable for
2073 more information."
2074 :group 'org-todo
2075 :group 'org-keywords
2076 :type '(choice (const sequence)
2077 (const type)))
2079 (defcustom org-use-fast-todo-selection t
2080 "Non-nil means use the fast todo selection scheme with C-c C-t.
2081 This variable describes if and under what circumstances the cycling
2082 mechanism for TODO keywords will be replaced by a single-key, direct
2083 selection scheme.
2085 When nil, fast selection is never used.
2087 When the symbol `prefix', it will be used when `org-todo' is called with
2088 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
2089 in an agenda buffer.
2091 When t, fast selection is used by default. In this case, the prefix
2092 argument forces cycling instead.
2094 In all cases, the special interface is only used if access keys have actually
2095 been assigned by the user, i.e. if keywords in the configuration are followed
2096 by a letter in parenthesis, like TODO(t)."
2097 :group 'org-todo
2098 :type '(choice
2099 (const :tag "Never" nil)
2100 (const :tag "By default" t)
2101 (const :tag "Only with C-u C-c C-t" prefix)))
2103 (defcustom org-provide-todo-statistics t
2104 "Non-nil means update todo statistics after insert and toggle.
2105 ALL-HEADLINES means update todo statistics by including headlines
2106 with no TODO keyword as well, counting them as not done.
2107 A list of TODO keywords means the same, but skip keywords that are
2108 not in this list.
2110 When this is set, todo statistics is updated in the parent of the
2111 current entry each time a todo state is changed."
2112 :group 'org-todo
2113 :type '(choice
2114 (const :tag "Yes, only for TODO entries" t)
2115 (const :tag "Yes, including all entries" 'all-headlines)
2116 (repeat :tag "Yes, for TODOs in this list"
2117 (string :tag "TODO keyword"))
2118 (other :tag "No TODO statistics" nil)))
2120 (defcustom org-hierarchical-todo-statistics t
2121 "Non-nil means TODO statistics covers just direct children.
2122 When nil, all entries in the subtree are considered.
2123 This has only an effect if `org-provide-todo-statistics' is set.
2124 To set this to nil for only a single subtree, use a COOKIE_DATA
2125 property and include the word \"recursive\" into the value."
2126 :group 'org-todo
2127 :type 'boolean)
2129 (defcustom org-after-todo-state-change-hook nil
2130 "Hook which is run after the state of a TODO item was changed.
2131 The new state (a string with a TODO keyword, or nil) is available in the
2132 Lisp variable `state'."
2133 :group 'org-todo
2134 :type 'hook)
2136 (defvar org-blocker-hook nil
2137 "Hook for functions that are allowed to block a state change.
2139 Each function gets as its single argument a property list, see
2140 `org-trigger-hook' for more information about this list.
2142 If any of the functions in this hook returns nil, the state change
2143 is blocked.")
2145 (defvar org-trigger-hook nil
2146 "Hook for functions that are triggered by a state change.
2148 Each function gets as its single argument a property list with at least
2149 the following elements:
2151 (:type type-of-change :position pos-at-entry-start
2152 :from old-state :to new-state)
2154 Depending on the type, more properties may be present.
2156 This mechanism is currently implemented for:
2158 TODO state changes
2159 ------------------
2160 :type todo-state-change
2161 :from previous state (keyword as a string), or nil, or a symbol
2162 'todo' or 'done', to indicate the general type of state.
2163 :to new state, like in :from")
2165 (defcustom org-enforce-todo-dependencies nil
2166 "Non-nil means undone TODO entries will block switching the parent to DONE.
2167 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2168 be blocked if any prior sibling is not yet done.
2169 Finally, if the parent is blocked because of ordered siblings of its own,
2170 the child will also be blocked.
2171 This variable needs to be set before org.el is loaded, and you need to
2172 restart Emacs after a change to make the change effective. The only way
2173 to change is while Emacs is running is through the customize interface."
2174 :set (lambda (var val)
2175 (set var val)
2176 (if val
2177 (add-hook 'org-blocker-hook
2178 'org-block-todo-from-children-or-siblings-or-parent)
2179 (remove-hook 'org-blocker-hook
2180 'org-block-todo-from-children-or-siblings-or-parent)))
2181 :group 'org-todo
2182 :type 'boolean)
2184 (defcustom org-enforce-todo-checkbox-dependencies nil
2185 "Non-nil means unchecked boxes will block switching the parent to DONE.
2186 When this is nil, checkboxes have no influence on switching TODO states.
2187 When non-nil, you first need to check off all check boxes before the TODO
2188 entry can be switched to DONE.
2189 This variable needs to be set before org.el is loaded, and you need to
2190 restart Emacs after a change to make the change effective. The only way
2191 to change is while Emacs is running is through the customize interface."
2192 :set (lambda (var val)
2193 (set var val)
2194 (if val
2195 (add-hook 'org-blocker-hook
2196 'org-block-todo-from-checkboxes)
2197 (remove-hook 'org-blocker-hook
2198 'org-block-todo-from-checkboxes)))
2199 :group 'org-todo
2200 :type 'boolean)
2202 (defcustom org-treat-insert-todo-heading-as-state-change nil
2203 "Non-nil means inserting a TODO heading is treated as state change.
2204 So when the command \\[org-insert-todo-heading] is used, state change
2205 logging will apply if appropriate. When nil, the new TODO item will
2206 be inserted directly, and no logging will take place."
2207 :group 'org-todo
2208 :type 'boolean)
2210 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2211 "Non-nil means switching TODO states with S-cursor counts as state change.
2212 This is the default behavior. However, setting this to nil allows a
2213 convenient way to select a TODO state and bypass any logging associated
2214 with that."
2215 :group 'org-todo
2216 :type 'boolean)
2218 (defcustom org-todo-state-tags-triggers nil
2219 "Tag changes that should be triggered by TODO state changes.
2220 This is a list. Each entry is
2222 (state-change (tag . flag) .......)
2224 State-change can be a string with a state, and empty string to indicate the
2225 state that has no TODO keyword, or it can be one of the symbols `todo'
2226 or `done', meaning any not-done or done state, respectively."
2227 :group 'org-todo
2228 :group 'org-tags
2229 :type '(repeat
2230 (cons (choice :tag "When changing to"
2231 (const :tag "Not-done state" todo)
2232 (const :tag "Done state" done)
2233 (string :tag "State"))
2234 (repeat
2235 (cons :tag "Tag action"
2236 (string :tag "Tag")
2237 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2239 (defcustom org-log-done nil
2240 "Information to record when a task moves to the DONE state.
2242 Possible values are:
2244 nil Don't add anything, just change the keyword
2245 time Add a time stamp to the task
2246 note Prompt for a note and add it with template `org-log-note-headings'
2248 This option can also be set with on a per-file-basis with
2250 #+STARTUP: nologdone
2251 #+STARTUP: logdone
2252 #+STARTUP: lognotedone
2254 You can have local logging settings for a subtree by setting the LOGGING
2255 property to one or more of these keywords."
2256 :group 'org-todo
2257 :group 'org-progress
2258 :type '(choice
2259 (const :tag "No logging" nil)
2260 (const :tag "Record CLOSED timestamp" time)
2261 (const :tag "Record CLOSED timestamp with note." note)))
2263 ;; Normalize old uses of org-log-done.
2264 (cond
2265 ((eq org-log-done t) (setq org-log-done 'time))
2266 ((and (listp org-log-done) (memq 'done org-log-done))
2267 (setq org-log-done 'note)))
2269 (defcustom org-log-reschedule nil
2270 "Information to record when the scheduling date of a tasks is modified.
2272 Possible values are:
2274 nil Don't add anything, just change the date
2275 time Add a time stamp to the task
2276 note Prompt for a note and add it with template `org-log-note-headings'
2278 This option can also be set with on a per-file-basis with
2280 #+STARTUP: nologreschedule
2281 #+STARTUP: logreschedule
2282 #+STARTUP: lognotereschedule"
2283 :group 'org-todo
2284 :group 'org-progress
2285 :type '(choice
2286 (const :tag "No logging" nil)
2287 (const :tag "Record timestamp" time)
2288 (const :tag "Record timestamp with note." note)))
2290 (defcustom org-log-redeadline nil
2291 "Information to record when the deadline date of a tasks is modified.
2293 Possible values are:
2295 nil Don't add anything, just change the date
2296 time Add a time stamp to the task
2297 note Prompt for a note and add it with template `org-log-note-headings'
2299 This option can also be set with on a per-file-basis with
2301 #+STARTUP: nologredeadline
2302 #+STARTUP: logredeadline
2303 #+STARTUP: lognoteredeadline
2305 You can have local logging settings for a subtree by setting the LOGGING
2306 property to one or more of these keywords."
2307 :group 'org-todo
2308 :group 'org-progress
2309 :type '(choice
2310 (const :tag "No logging" nil)
2311 (const :tag "Record timestamp" time)
2312 (const :tag "Record timestamp with note." note)))
2314 (defcustom org-log-note-clock-out nil
2315 "Non-nil means record a note when clocking out of an item.
2316 This can also be configured on a per-file basis by adding one of
2317 the following lines anywhere in the buffer:
2319 #+STARTUP: lognoteclock-out
2320 #+STARTUP: nolognoteclock-out"
2321 :group 'org-todo
2322 :group 'org-progress
2323 :type 'boolean)
2325 (defcustom org-log-done-with-time t
2326 "Non-nil means the CLOSED time stamp will contain date and time.
2327 When nil, only the date will be recorded."
2328 :group 'org-progress
2329 :type 'boolean)
2331 (defcustom org-log-note-headings
2332 '((done . "CLOSING NOTE %t")
2333 (state . "State %-12s from %-12S %t")
2334 (note . "Note taken on %t")
2335 (reschedule . "Rescheduled from %S on %t")
2336 (delschedule . "Not scheduled, was %S on %t")
2337 (redeadline . "New deadline from %S on %t")
2338 (deldeadline . "Removed deadline, was %S on %t")
2339 (refile . "Refiled on %t")
2340 (clock-out . ""))
2341 "Headings for notes added to entries.
2342 The value is an alist, with the car being a symbol indicating the note
2343 context, and the cdr is the heading to be used. The heading may also be the
2344 empty string.
2345 %t in the heading will be replaced by a time stamp.
2346 %T will be an active time stamp instead the default inactive one
2347 %s will be replaced by the new TODO state, in double quotes.
2348 %S will be replaced by the old TODO state, in double quotes.
2349 %u will be replaced by the user name.
2350 %U will be replaced by the full user name.
2352 In fact, it is not a good idea to change the `state' entry, because
2353 agenda log mode depends on the format of these entries."
2354 :group 'org-todo
2355 :group 'org-progress
2356 :type '(list :greedy t
2357 (cons (const :tag "Heading when closing an item" done) string)
2358 (cons (const :tag
2359 "Heading when changing todo state (todo sequence only)"
2360 state) string)
2361 (cons (const :tag "Heading when just taking a note" note) string)
2362 (cons (const :tag "Heading when clocking out" clock-out) string)
2363 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2364 (cons (const :tag "Heading when rescheduling" reschedule) string)
2365 (cons (const :tag "Heading when changing deadline" redeadline) string)
2366 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2367 (cons (const :tag "Heading when refiling" refile) string)))
2369 (unless (assq 'note org-log-note-headings)
2370 (push '(note . "%t") org-log-note-headings))
2372 (defcustom org-log-into-drawer nil
2373 "Non-nil means insert state change notes and time stamps into a drawer.
2374 When nil, state changes notes will be inserted after the headline and
2375 any scheduling and clock lines, but not inside a drawer.
2377 The value of this variable should be the name of the drawer to use.
2378 LOGBOOK is proposed as the default drawer for this purpose, you can
2379 also set this to a string to define the drawer of your choice.
2381 A value of t is also allowed, representing \"LOGBOOK\".
2383 If this variable is set, `org-log-state-notes-insert-after-drawers'
2384 will be ignored.
2386 You can set the property LOG_INTO_DRAWER to overrule this setting for
2387 a subtree."
2388 :group 'org-todo
2389 :group 'org-progress
2390 :type '(choice
2391 (const :tag "Not into a drawer" nil)
2392 (const :tag "LOGBOOK" t)
2393 (string :tag "Other")))
2395 (if (fboundp 'defvaralias)
2396 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2398 (defun org-log-into-drawer ()
2399 "Return the value of `org-log-into-drawer', but let properties overrule.
2400 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2401 used instead of the default value."
2402 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit)))
2403 (cond
2404 ((or (not p) (equal p "nil")) org-log-into-drawer)
2405 ((equal p "t") "LOGBOOK")
2406 (t p))))
2408 (defcustom org-log-state-notes-insert-after-drawers nil
2409 "Non-nil means insert state change notes after any drawers in entry.
2410 Only the drawers that *immediately* follow the headline and the
2411 deadline/scheduled line are skipped.
2412 When nil, insert notes right after the heading and perhaps the line
2413 with deadline/scheduling if present.
2415 This variable will have no effect if `org-log-into-drawer' is
2416 set."
2417 :group 'org-todo
2418 :group 'org-progress
2419 :type 'boolean)
2421 (defcustom org-log-states-order-reversed t
2422 "Non-nil means the latest state note will be directly after heading.
2423 When nil, the state change notes will be ordered according to time."
2424 :group 'org-todo
2425 :group 'org-progress
2426 :type 'boolean)
2428 (defcustom org-todo-repeat-to-state nil
2429 "The TODO state to which a repeater should return the repeating task.
2430 By default this is the first task in a TODO sequence, or the previous state
2431 in a TODO_TYP set. But you can specify another task here.
2432 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2433 :group 'org-todo
2434 :type '(choice (const :tag "Head of sequence" nil)
2435 (string :tag "Specific state")))
2437 (defcustom org-log-repeat 'time
2438 "Non-nil means record moving through the DONE state when triggering repeat.
2439 An auto-repeating task is immediately switched back to TODO when
2440 marked DONE. If you are not logging state changes (by adding \"@\"
2441 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2442 record a closing note, there will be no record of the task moving
2443 through DONE. This variable forces taking a note anyway.
2445 nil Don't force a record
2446 time Record a time stamp
2447 note Record a note
2449 This option can also be set with on a per-file-basis with
2451 #+STARTUP: logrepeat
2452 #+STARTUP: lognoterepeat
2453 #+STARTUP: nologrepeat
2455 You can have local logging settings for a subtree by setting the LOGGING
2456 property to one or more of these keywords."
2457 :group 'org-todo
2458 :group 'org-progress
2459 :type '(choice
2460 (const :tag "Don't force a record" nil)
2461 (const :tag "Force recording the DONE state" time)
2462 (const :tag "Force recording a note with the DONE state" note)))
2465 (defgroup org-priorities nil
2466 "Priorities in Org-mode."
2467 :tag "Org Priorities"
2468 :group 'org-todo)
2470 (defcustom org-enable-priority-commands t
2471 "Non-nil means priority commands are active.
2472 When nil, these commands will be disabled, so that you never accidentally
2473 set a priority."
2474 :group 'org-priorities
2475 :type 'boolean)
2477 (defcustom org-highest-priority ?A
2478 "The highest priority of TODO items. A character like ?A, ?B etc.
2479 Must have a smaller ASCII number than `org-lowest-priority'."
2480 :group 'org-priorities
2481 :type 'character)
2483 (defcustom org-lowest-priority ?C
2484 "The lowest priority of TODO items. A character like ?A, ?B etc.
2485 Must have a larger ASCII number than `org-highest-priority'."
2486 :group 'org-priorities
2487 :type 'character)
2489 (defcustom org-default-priority ?B
2490 "The default priority of TODO items.
2491 This is the priority an item gets if no explicit priority is given.
2492 When starting to cycle on an empty priority the first step in the cycle
2493 depends on `org-priority-start-cycle-with-default'. The resulting first
2494 step priority must not exceed the range from `org-highest-priority' to
2495 `org-lowest-priority' which means that `org-default-priority' has to be
2496 in this range exclusive or inclusive the range boundaries. Else the
2497 first step refuses to set the default and the second will fall back
2498 to (depending on the command used) the highest or lowest priority."
2499 :group 'org-priorities
2500 :type 'character)
2502 (defcustom org-priority-start-cycle-with-default t
2503 "Non-nil means start with default priority when starting to cycle.
2504 When this is nil, the first step in the cycle will be (depending on the
2505 command used) one higher or lower than the default priority.
2506 See also `org-default-priority'."
2507 :group 'org-priorities
2508 :type 'boolean)
2510 (defcustom org-get-priority-function nil
2511 "Function to extract the priority from a string.
2512 The string is normally the headline. If this is nil Org computes the
2513 priority from the priority cookie like [#A] in the headline. It returns
2514 an integer, increasing by 1000 for each priority level.
2515 The user can set a different function here, which should take a string
2516 as an argument and return the numeric priority."
2517 :group 'org-priorities
2518 :type 'function)
2520 (defgroup org-time nil
2521 "Options concerning time stamps and deadlines in Org-mode."
2522 :tag "Org Time"
2523 :group 'org)
2525 (defcustom org-insert-labeled-timestamps-at-point nil
2526 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2527 When nil, these labeled time stamps are forces into the second line of an
2528 entry, just after the headline. When scheduling from the global TODO list,
2529 the time stamp will always be forced into the second line."
2530 :group 'org-time
2531 :type 'boolean)
2533 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2534 "Formats for `format-time-string' which are used for time stamps.
2535 It is not recommended to change this constant.")
2537 (defcustom org-time-stamp-rounding-minutes '(0 5)
2538 "Number of minutes to round time stamps to.
2539 These are two values, the first applies when first creating a time stamp.
2540 The second applies when changing it with the commands `S-up' and `S-down'.
2541 When changing the time stamp, this means that it will change in steps
2542 of N minutes, as given by the second value.
2544 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2545 numbers should be factors of 60, so for example 5, 10, 15.
2547 When this is larger than 1, you can still force an exact time stamp by using
2548 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2549 and by using a prefix arg to `S-up/down' to specify the exact number
2550 of minutes to shift."
2551 :group 'org-time
2552 :get #'(lambda (var) ; Make sure both elements are there
2553 (if (integerp (default-value var))
2554 (list (default-value var) 5)
2555 (default-value var)))
2556 :type '(list
2557 (integer :tag "when inserting times")
2558 (integer :tag "when modifying times")))
2560 ;; Normalize old customizations of this variable.
2561 (when (integerp org-time-stamp-rounding-minutes)
2562 (setq org-time-stamp-rounding-minutes
2563 (list org-time-stamp-rounding-minutes
2564 org-time-stamp-rounding-minutes)))
2566 (defcustom org-display-custom-times nil
2567 "Non-nil means overlay custom formats over all time stamps.
2568 The formats are defined through the variable `org-time-stamp-custom-formats'.
2569 To turn this on on a per-file basis, insert anywhere in the file:
2570 #+STARTUP: customtime"
2571 :group 'org-time
2572 :set 'set-default
2573 :type 'sexp)
2574 (make-variable-buffer-local 'org-display-custom-times)
2576 (defcustom org-time-stamp-custom-formats
2577 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2578 "Custom formats for time stamps. See `format-time-string' for the syntax.
2579 These are overlayed over the default ISO format if the variable
2580 `org-display-custom-times' is set. Time like %H:%M should be at the
2581 end of the second format. The custom formats are also honored by export
2582 commands, if custom time display is turned on at the time of export."
2583 :group 'org-time
2584 :type 'sexp)
2586 (defun org-time-stamp-format (&optional long inactive)
2587 "Get the right format for a time string."
2588 (let ((f (if long (cdr org-time-stamp-formats)
2589 (car org-time-stamp-formats))))
2590 (if inactive
2591 (concat "[" (substring f 1 -1) "]")
2592 f)))
2594 (defcustom org-time-clocksum-format "%d:%02d"
2595 "The format string used when creating CLOCKSUM lines.
2596 This is also used when org-mode generates a time duration."
2597 :group 'org-time
2598 :type 'string)
2600 (defcustom org-time-clocksum-use-fractional nil
2601 "If non-nil, \\[org-clock-display] uses fractional times.
2602 org-mode generates a time duration."
2603 :group 'org-time
2604 :type 'boolean)
2606 (defcustom org-time-clocksum-fractional-format "%.2f"
2607 "The format string used when creating CLOCKSUM lines, or when
2608 org-mode generates a time duration."
2609 :group 'org-time
2610 :type 'string)
2612 (defcustom org-deadline-warning-days 14
2613 "No. of days before expiration during which a deadline becomes active.
2614 This variable governs the display in sparse trees and in the agenda.
2615 When 0 or negative, it means use this number (the absolute value of it)
2616 even if a deadline has a different individual lead time specified.
2618 Custom commands can set this variable in the options section."
2619 :group 'org-time
2620 :group 'org-agenda-daily/weekly
2621 :type 'integer)
2623 (defcustom org-read-date-prefer-future t
2624 "Non-nil means assume future for incomplete date input from user.
2625 This affects the following situations:
2626 1. The user gives a month but not a year.
2627 For example, if it is April and you enter \"feb 2\", this will be read
2628 as Feb 2, *next* year. \"May 5\", however, will be this year.
2629 2. The user gives a day, but no month.
2630 For example, if today is the 15th, and you enter \"3\", Org-mode will
2631 read this as the third of *next* month. However, if you enter \"17\",
2632 it will be considered as *this* month.
2634 If you set this variable to the symbol `time', then also the following
2635 will work:
2637 3. If the user gives a time, but no day. If the time is before now,
2638 to will be interpreted as tomorrow.
2640 Currently none of this works for ISO week specifications.
2642 When this option is nil, the current day, month and year will always be
2643 used as defaults.
2645 See also `org-agenda-jump-prefer-future'."
2646 :group 'org-time
2647 :type '(choice
2648 (const :tag "Never" nil)
2649 (const :tag "Check month and day" t)
2650 (const :tag "Check month, day, and time" time)))
2652 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
2653 "Should the agenda jump command prefer the future for incomplete dates?
2654 The default is to do the same as configured in `org-read-date-prefer-future'.
2655 But you can also set a deviating value here.
2656 This may t or nil, or the symbol `org-read-date-prefer-future'."
2657 :group 'org-agenda
2658 :group 'org-time
2659 :type '(choice
2660 (const :tag "Use org-read-date-prefer-future"
2661 org-read-date-prefer-future)
2662 (const :tag "Never" nil)
2663 (const :tag "Always" t)))
2665 (defcustom org-read-date-force-compatible-dates t
2666 "Should date/time prompt force dates that are guaranteed to work in Emacs?
2668 Depending on the system Emacs is running on, certain dates cannot
2669 be represented with the type used internally to represent time.
2670 Dates between 1970-1-1 and 2038-1-1 can always be represented
2671 correctly. Some systems allow for earlier dates, some for later,
2672 some for both. One way to find out it to insert any date into an
2673 Org buffer, putting the cursor on the year and hitting S-up and
2674 S-down to test the range.
2676 When this variable is set to t, the date/time prompt will not let
2677 you specify dates outside the 1970-2037 range, so it is certain that
2678 these dates will work in whatever version of Emacs you are
2679 running, and also that you can move a file from one Emacs implementation
2680 to another. WHenever Org is forcing the year for you, it will display
2681 a message and beep.
2683 When this variable is nil, Org will check if the date is
2684 representable in the specific Emacs implementation you are using.
2685 If not, it will force a year, usually the current year, and beep
2686 to remind you. Currently this setting is not recommended because
2687 the likelihood that you will open your Org files in an Emacs that
2688 has limited date range is not negligible.
2690 A workaround for this problem is to use diary sexp dates for time
2691 stamps outside of this range."
2692 :group 'org-time
2693 :type 'boolean)
2695 (defcustom org-read-date-display-live t
2696 "Non-nil means display current interpretation of date prompt live.
2697 This display will be in an overlay, in the minibuffer."
2698 :group 'org-time
2699 :type 'boolean)
2701 (defcustom org-read-date-popup-calendar t
2702 "Non-nil means pop up a calendar when prompting for a date.
2703 In the calendar, the date can be selected with mouse-1. However, the
2704 minibuffer will also be active, and you can simply enter the date as well.
2705 When nil, only the minibuffer will be available."
2706 :group 'org-time
2707 :type 'boolean)
2708 (if (fboundp 'defvaralias)
2709 (defvaralias 'org-popup-calendar-for-date-prompt
2710 'org-read-date-popup-calendar))
2712 (defcustom org-read-date-minibuffer-setup-hook nil
2713 "Hook to be used to set up keys for the date/time interface.
2714 Add key definitions to `minibuffer-local-map', which will be a temporary
2715 copy."
2716 :group 'org-time
2717 :type 'hook)
2719 (defcustom org-extend-today-until 0
2720 "The hour when your day really ends. Must be an integer.
2721 This has influence for the following applications:
2722 - When switching the agenda to \"today\". It it is still earlier than
2723 the time given here, the day recognized as TODAY is actually yesterday.
2724 - When a date is read from the user and it is still before the time given
2725 here, the current date and time will be assumed to be yesterday, 23:59.
2726 Also, timestamps inserted in remember templates follow this rule.
2728 IMPORTANT: This is a feature whose implementation is and likely will
2729 remain incomplete. Really, it is only here because past midnight seems to
2730 be the favorite working time of John Wiegley :-)"
2731 :group 'org-time
2732 :type 'integer)
2734 (defcustom org-edit-timestamp-down-means-later nil
2735 "Non-nil means S-down will increase the time in a time stamp.
2736 When nil, S-up will increase."
2737 :group 'org-time
2738 :type 'boolean)
2740 (defcustom org-calendar-follow-timestamp-change t
2741 "Non-nil means make the calendar window follow timestamp changes.
2742 When a timestamp is modified and the calendar window is visible, it will be
2743 moved to the new date."
2744 :group 'org-time
2745 :type 'boolean)
2747 (defgroup org-tags nil
2748 "Options concerning tags in Org-mode."
2749 :tag "Org Tags"
2750 :group 'org)
2752 (defcustom org-tag-alist nil
2753 "List of tags allowed in Org-mode files.
2754 When this list is nil, Org-mode will base TAG input on what is already in the
2755 buffer.
2756 The value of this variable is an alist, the car of each entry must be a
2757 keyword as a string, the cdr may be a character that is used to select
2758 that tag through the fast-tag-selection interface.
2759 See the manual for details."
2760 :group 'org-tags
2761 :type '(repeat
2762 (choice
2763 (cons (string :tag "Tag name")
2764 (character :tag "Access char"))
2765 (list :tag "Start radio group"
2766 (const :startgroup)
2767 (option (string :tag "Group description")))
2768 (list :tag "End radio group"
2769 (const :endgroup)
2770 (option (string :tag "Group description")))
2771 (const :tag "New line" (:newline)))))
2773 (defcustom org-tag-persistent-alist nil
2774 "List of tags that will always appear in all Org-mode files.
2775 This is in addition to any in buffer settings or customizations
2776 of `org-tag-alist'.
2777 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2778 The value of this variable is an alist, the car of each entry must be a
2779 keyword as a string, the cdr may be a character that is used to select
2780 that tag through the fast-tag-selection interface.
2781 See the manual for details.
2782 To disable these tags on a per-file basis, insert anywhere in the file:
2783 #+STARTUP: noptag"
2784 :group 'org-tags
2785 :type '(repeat
2786 (choice
2787 (cons (string :tag "Tag name")
2788 (character :tag "Access char"))
2789 (const :tag "Start radio group" (:startgroup))
2790 (const :tag "End radio group" (:endgroup))
2791 (const :tag "New line" (:newline)))))
2793 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
2794 "If non-nil, always offer completion for all tags of all agenda files.
2795 Instead of customizing this variable directly, you might want to
2796 set it locally for capture buffers, because there no list of
2797 tags in that file can be created dynamically (there are none).
2799 (add-hook 'org-capture-mode-hook
2800 (lambda ()
2801 (set (make-local-variable
2802 'org-complete-tags-always-offer-all-agenda-tags)
2803 t)))"
2804 :group 'org-tags
2805 :type 'boolean)
2807 (defvar org-file-tags nil
2808 "List of tags that can be inherited by all entries in the file.
2809 The tags will be inherited if the variable `org-use-tag-inheritance'
2810 says they should be.
2811 This variable is populated from #+FILETAGS lines.")
2813 (defcustom org-use-fast-tag-selection 'auto
2814 "Non-nil means use fast tag selection scheme.
2815 This is a special interface to select and deselect tags with single keys.
2816 When nil, fast selection is never used.
2817 When the symbol `auto', fast selection is used if and only if selection
2818 characters for tags have been configured, either through the variable
2819 `org-tag-alist' or through a #+TAGS line in the buffer.
2820 When t, fast selection is always used and selection keys are assigned
2821 automatically if necessary."
2822 :group 'org-tags
2823 :type '(choice
2824 (const :tag "Always" t)
2825 (const :tag "Never" nil)
2826 (const :tag "When selection characters are configured" 'auto)))
2828 (defcustom org-fast-tag-selection-single-key nil
2829 "Non-nil means fast tag selection exits after first change.
2830 When nil, you have to press RET to exit it.
2831 During fast tag selection, you can toggle this flag with `C-c'.
2832 This variable can also have the value `expert'. In this case, the window
2833 displaying the tags menu is not even shown, until you press C-c again."
2834 :group 'org-tags
2835 :type '(choice
2836 (const :tag "No" nil)
2837 (const :tag "Yes" t)
2838 (const :tag "Expert" expert)))
2840 (defvar org-fast-tag-selection-include-todo nil
2841 "Non-nil means fast tags selection interface will also offer TODO states.
2842 This is an undocumented feature, you should not rely on it.")
2844 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2845 "The column to which tags should be indented in a headline.
2846 If this number is positive, it specifies the column. If it is negative,
2847 it means that the tags should be flushright to that column. For example,
2848 -80 works well for a normal 80 character screen."
2849 :group 'org-tags
2850 :type 'integer)
2852 (defcustom org-auto-align-tags t
2853 "Non-nil keeps tags aligned when modifying headlines.
2854 Some operations (i.e. demoting) change the length of a headline and
2855 therefore shift the tags around. With this option turned on, after
2856 each such operation the tags are again aligned to `org-tags-column'."
2857 :group 'org-tags
2858 :type 'boolean)
2860 (defcustom org-use-tag-inheritance t
2861 "Non-nil means tags in levels apply also for sublevels.
2862 When nil, only the tags directly given in a specific line apply there.
2863 This may also be a list of tags that should be inherited, or a regexp that
2864 matches tags that should be inherited. Additional control is possible
2865 with the variable `org-tags-exclude-from-inheritance' which gives an
2866 explicit list of tags to be excluded from inheritance., even if the value of
2867 `org-use-tag-inheritance' would select it for inheritance.
2869 If this option is t, a match early-on in a tree can lead to a large
2870 number of matches in the subtree when constructing the agenda or creating
2871 a sparse tree. If you only want to see the first match in a tree during
2872 a search, check out the variable `org-tags-match-list-sublevels'."
2873 :group 'org-tags
2874 :type '(choice
2875 (const :tag "Not" nil)
2876 (const :tag "Always" t)
2877 (repeat :tag "Specific tags" (string :tag "Tag"))
2878 (regexp :tag "Tags matched by regexp")))
2880 (defcustom org-tags-exclude-from-inheritance nil
2881 "List of tags that should never be inherited.
2882 This is a way to exclude a few tags from inheritance. For way to do
2883 the opposite, to actively allow inheritance for selected tags,
2884 see the variable `org-use-tag-inheritance'."
2885 :group 'org-tags
2886 :type '(repeat (string :tag "Tag")))
2888 (defun org-tag-inherit-p (tag)
2889 "Check if TAG is one that should be inherited."
2890 (cond
2891 ((member tag org-tags-exclude-from-inheritance) nil)
2892 ((eq org-use-tag-inheritance t) t)
2893 ((not org-use-tag-inheritance) nil)
2894 ((stringp org-use-tag-inheritance)
2895 (string-match org-use-tag-inheritance tag))
2896 ((listp org-use-tag-inheritance)
2897 (member tag org-use-tag-inheritance))
2898 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
2900 (defcustom org-tags-match-list-sublevels t
2901 "Non-nil means list also sublevels of headlines matching a search.
2902 This variable applies to tags/property searches, and also to stuck
2903 projects because this search is based on a tags match as well.
2905 When set to the symbol `indented', sublevels are indented with
2906 leading dots.
2908 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2909 the sublevels of a headline matching a tag search often also match
2910 the same search. Listing all of them can create very long lists.
2911 Setting this variable to nil causes subtrees of a match to be skipped.
2913 This variable is semi-obsolete and probably should always be true. It
2914 is better to limit inheritance to certain tags using the variables
2915 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
2916 :group 'org-tags
2917 :type '(choice
2918 (const :tag "No, don't list them" nil)
2919 (const :tag "Yes, do list them" t)
2920 (const :tag "List them, indented with leading dots" indented)))
2922 (defcustom org-tags-sort-function nil
2923 "When set, tags are sorted using this function as a comparator."
2924 :group 'org-tags
2925 :type '(choice
2926 (const :tag "No sorting" nil)
2927 (const :tag "Alphabetical" string<)
2928 (const :tag "Reverse alphabetical" string>)
2929 (function :tag "Custom function" nil)))
2931 (defvar org-tags-history nil
2932 "History of minibuffer reads for tags.")
2933 (defvar org-last-tags-completion-table nil
2934 "The last used completion table for tags.")
2935 (defvar org-after-tags-change-hook nil
2936 "Hook that is run after the tags in a line have changed.")
2938 (defgroup org-properties nil
2939 "Options concerning properties in Org-mode."
2940 :tag "Org Properties"
2941 :group 'org)
2943 (defcustom org-property-format "%-10s %s"
2944 "How property key/value pairs should be formatted by `indent-line'.
2945 When `indent-line' hits a property definition, it will format the line
2946 according to this format, mainly to make sure that the values are
2947 lined-up with respect to each other."
2948 :group 'org-properties
2949 :type 'string)
2951 (defcustom org-use-property-inheritance nil
2952 "Non-nil means properties apply also for sublevels.
2954 This setting is chiefly used during property searches. Turning it on can
2955 cause significant overhead when doing a search, which is why it is not
2956 on by default.
2958 When nil, only the properties directly given in the current entry count.
2959 When t, every property is inherited. The value may also be a list of
2960 properties that should have inheritance, or a regular expression matching
2961 properties that should be inherited.
2963 However, note that some special properties use inheritance under special
2964 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2965 and the properties ending in \"_ALL\" when they are used as descriptor
2966 for valid values of a property.
2968 Note for programmers:
2969 When querying an entry with `org-entry-get', you can control if inheritance
2970 should be used. By default, `org-entry-get' looks only at the local
2971 properties. You can request inheritance by setting the inherit argument
2972 to t (to force inheritance) or to `selective' (to respect the setting
2973 in this variable)."
2974 :group 'org-properties
2975 :type '(choice
2976 (const :tag "Not" nil)
2977 (const :tag "Always" t)
2978 (repeat :tag "Specific properties" (string :tag "Property"))
2979 (regexp :tag "Properties matched by regexp")))
2981 (defun org-property-inherit-p (property)
2982 "Check if PROPERTY is one that should be inherited."
2983 (cond
2984 ((eq org-use-property-inheritance t) t)
2985 ((not org-use-property-inheritance) nil)
2986 ((stringp org-use-property-inheritance)
2987 (string-match org-use-property-inheritance property))
2988 ((listp org-use-property-inheritance)
2989 (member property org-use-property-inheritance))
2990 (t (error "Invalid setting of `org-use-property-inheritance'"))))
2992 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2993 "The default column format, if no other format has been defined.
2994 This variable can be set on the per-file basis by inserting a line
2996 #+COLUMNS: %25ITEM ....."
2997 :group 'org-properties
2998 :type 'string)
3000 (defcustom org-columns-ellipses ".."
3001 "The ellipses to be used when a field in column view is truncated.
3002 When this is the empty string, as many characters as possible are shown,
3003 but then there will be no visual indication that the field has been truncated.
3004 When this is a string of length N, the last N characters of a truncated
3005 field are replaced by this string. If the column is narrower than the
3006 ellipses string, only part of the ellipses string will be shown."
3007 :group 'org-properties
3008 :type 'string)
3010 (defcustom org-columns-modify-value-for-display-function nil
3011 "Function that modifies values for display in column view.
3012 For example, it can be used to cut out a certain part from a time stamp.
3013 The function must take 2 arguments:
3015 column-title The title of the column (*not* the property name)
3016 value The value that should be modified.
3018 The function should return the value that should be displayed,
3019 or nil if the normal value should be used."
3020 :group 'org-properties
3021 :type 'function)
3023 (defcustom org-effort-property "Effort"
3024 "The property that is being used to keep track of effort estimates.
3025 Effort estimates given in this property need to have the format H:MM."
3026 :group 'org-properties
3027 :group 'org-progress
3028 :type '(string :tag "Property"))
3030 (defconst org-global-properties-fixed
3031 '(("VISIBILITY_ALL" . "folded children content all")
3032 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3033 "List of property/value pairs that can be inherited by any entry.
3035 These are fixed values, for the preset properties. The user variable
3036 that can be used to add to this list is `org-global-properties'.
3038 The entries in this list are cons cells where the car is a property
3039 name and cdr is a string with the value. If the value represents
3040 multiple items like an \"_ALL\" property, separate the items by
3041 spaces.")
3043 (defcustom org-global-properties nil
3044 "List of property/value pairs that can be inherited by any entry.
3046 This list will be combined with the constant `org-global-properties-fixed'.
3048 The entries in this list are cons cells where the car is a property
3049 name and cdr is a string with the value.
3051 You can set buffer-local values for the same purpose in the variable
3052 `org-file-properties' this by adding lines like
3054 #+PROPERTY: NAME VALUE"
3055 :group 'org-properties
3056 :type '(repeat
3057 (cons (string :tag "Property")
3058 (string :tag "Value"))))
3060 (defvar org-file-properties nil
3061 "List of property/value pairs that can be inherited by any entry.
3062 Valid for the current buffer.
3063 This variable is populated from #+PROPERTY lines.")
3064 (make-variable-buffer-local 'org-file-properties)
3066 (defgroup org-agenda nil
3067 "Options concerning agenda views in Org-mode."
3068 :tag "Org Agenda"
3069 :group 'org)
3071 (defvar org-category nil
3072 "Variable used by org files to set a category for agenda display.
3073 Such files should use a file variable to set it, for example
3075 # -*- mode: org; org-category: \"ELisp\"
3077 or contain a special line
3079 #+CATEGORY: ELisp
3081 If the file does not specify a category, then file's base name
3082 is used instead.")
3083 (make-variable-buffer-local 'org-category)
3084 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3086 (defcustom org-agenda-files nil
3087 "The files to be used for agenda display.
3088 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3089 \\[org-remove-file]. You can also use customize to edit the list.
3091 If an entry is a directory, all files in that directory that are matched by
3092 `org-agenda-file-regexp' will be part of the file list.
3094 If the value of the variable is not a list but a single file name, then
3095 the list of agenda files is actually stored and maintained in that file, one
3096 agenda file per line. In this file paths can be given relative to
3097 `org-directory'. Tilde expansion and environment variable substitution
3098 are also made."
3099 :group 'org-agenda
3100 :type '(choice
3101 (repeat :tag "List of files and directories" file)
3102 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3104 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3105 "Regular expression to match files for `org-agenda-files'.
3106 If any element in the list in that variable contains a directory instead
3107 of a normal file, all files in that directory that are matched by this
3108 regular expression will be included."
3109 :group 'org-agenda
3110 :type 'regexp)
3112 (defcustom org-agenda-text-search-extra-files nil
3113 "List of extra files to be searched by text search commands.
3114 These files will be search in addition to the agenda files by the
3115 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3116 Note that these files will only be searched for text search commands,
3117 not for the other agenda views like todo lists, tag searches or the weekly
3118 agenda. This variable is intended to list notes and possibly archive files
3119 that should also be searched by these two commands.
3120 In fact, if the first element in the list is the symbol `agenda-archives',
3121 than all archive files of all agenda files will be added to the search
3122 scope."
3123 :group 'org-agenda
3124 :type '(set :greedy t
3125 (const :tag "Agenda Archives" agenda-archives)
3126 (repeat :inline t (file))))
3128 (if (fboundp 'defvaralias)
3129 (defvaralias 'org-agenda-multi-occur-extra-files
3130 'org-agenda-text-search-extra-files))
3132 (defcustom org-agenda-skip-unavailable-files nil
3133 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3134 A nil value means to remove them, after a query, from the list."
3135 :group 'org-agenda
3136 :type 'boolean)
3138 (defcustom org-calendar-to-agenda-key [?c]
3139 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3140 The command `org-calendar-goto-agenda' will be bound to this key. The
3141 default is the character `c' because then `c' can be used to switch back and
3142 forth between agenda and calendar."
3143 :group 'org-agenda
3144 :type 'sexp)
3146 (defcustom org-calendar-agenda-action-key [?k]
3147 "The key to be installed in `calendar-mode-map' for agenda-action.
3148 The command `org-agenda-action' will be bound to this key. The
3149 default is the character `k' because we use the same key in the agenda."
3150 :group 'org-agenda
3151 :type 'sexp)
3153 (defcustom org-calendar-insert-diary-entry-key [?i]
3154 "The key to be installed in `calendar-mode-map' for adding diary entries.
3155 This option is irrelevant until `org-agenda-diary-file' has been configured
3156 to point to an Org-mode file. When that is the case, the command
3157 `org-agenda-diary-entry' will be bound to the key given here, by default
3158 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3159 if you want to continue doing this, you need to change this to a different
3160 key."
3161 :group 'org-agenda
3162 :type 'sexp)
3164 (defcustom org-agenda-diary-file 'diary-file
3165 "File to which to add new entries with the `i' key in agenda and calendar.
3166 When this is the symbol `diary-file', the functionality in the Emacs
3167 calendar will be used to add entries to the `diary-file'. But when this
3168 points to a file, `org-agenda-diary-entry' will be used instead."
3169 :group 'org-agenda
3170 :type '(choice
3171 (const :tag "The standard Emacs diary file" diary-file)
3172 (file :tag "Special Org file diary entries")))
3174 (eval-after-load "calendar"
3175 '(progn
3176 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3177 'org-calendar-goto-agenda)
3178 (org-defkey calendar-mode-map org-calendar-agenda-action-key
3179 'org-agenda-action)
3180 (add-hook 'calendar-mode-hook
3181 (lambda ()
3182 (unless (eq org-agenda-diary-file 'diary-file)
3183 (define-key calendar-mode-map
3184 org-calendar-insert-diary-entry-key
3185 'org-agenda-diary-entry))))))
3187 (defgroup org-latex nil
3188 "Options for embedding LaTeX code into Org-mode."
3189 :tag "Org LaTeX"
3190 :group 'org)
3192 (defcustom org-format-latex-options
3193 '(:foreground default :background default :scale 1.0
3194 :html-foreground "Black" :html-background "Transparent"
3195 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3196 "Options for creating images from LaTeX fragments.
3197 This is a property list with the following properties:
3198 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3199 `default' means use the foreground of the default face.
3200 :background the background color, or \"Transparent\".
3201 `default' means use the background of the default face.
3202 :scale a scaling factor for the size of the images, to get more pixels
3203 :html-foreground, :html-background, :html-scale
3204 the same numbers for HTML export.
3205 :matchers a list indicating which matchers should be used to
3206 find LaTeX fragments. Valid members of this list are:
3207 \"begin\" find environments
3208 \"$1\" find single characters surrounded by $.$
3209 \"$\" find math expressions surrounded by $...$
3210 \"$$\" find math expressions surrounded by $$....$$
3211 \"\\(\" find math expressions surrounded by \\(...\\)
3212 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3213 :group 'org-latex
3214 :type 'plist)
3216 (defcustom org-format-latex-signal-error t
3217 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3218 When nil, just push out a message."
3219 :group 'org-latex
3220 :type 'boolean)
3222 (defcustom org-format-latex-header "\\documentclass{article}
3223 \\usepackage[usenames]{color}
3224 \\usepackage{amsmath}
3225 \\usepackage[mathscr]{eucal}
3226 \\pagestyle{empty} % do not remove
3227 \[PACKAGES]
3228 \[DEFAULT-PACKAGES]
3229 % The settings below are copied from fullpage.sty
3230 \\setlength{\\textwidth}{\\paperwidth}
3231 \\addtolength{\\textwidth}{-3cm}
3232 \\setlength{\\oddsidemargin}{1.5cm}
3233 \\addtolength{\\oddsidemargin}{-2.54cm}
3234 \\setlength{\\evensidemargin}{\\oddsidemargin}
3235 \\setlength{\\textheight}{\\paperheight}
3236 \\addtolength{\\textheight}{-\\headheight}
3237 \\addtolength{\\textheight}{-\\headsep}
3238 \\addtolength{\\textheight}{-\\footskip}
3239 \\addtolength{\\textheight}{-3cm}
3240 \\setlength{\\topmargin}{1.5cm}
3241 \\addtolength{\\topmargin}{-2.54cm}"
3242 "The document header used for processing LaTeX fragments.
3243 It is imperative that this header make sure that no page number
3244 appears on the page. The package defined in the variables
3245 `org-export-latex-default-packages-alist' and `org-export-latex-packages-alist'
3246 will either replace the placeholder \"[PACKAGES]\" in this header, or they
3247 will be appended."
3248 :group 'org-latex
3249 :type 'string)
3251 (defvar org-format-latex-header-extra nil)
3253 (defun org-set-packages-alist (var val)
3254 "Set the packages alist and make sure it has 3 elements per entry."
3255 (set var (mapcar (lambda (x)
3256 (if (and (consp x) (= (length x) 2))
3257 (list (car x) (nth 1 x) t)
3259 val)))
3261 (defun org-get-packages-alist (var)
3263 "Get the packages alist and make sure it has 3 elements per entry."
3264 (mapcar (lambda (x)
3265 (if (and (consp x) (= (length x) 2))
3266 (list (car x) (nth 1 x) t)
3268 (default-value var)))
3270 ;; The following variables are defined here because is it also used
3271 ;; when formatting latex fragments. Originally it was part of the
3272 ;; LaTeX exporter, which is why the name includes "export".
3273 (defcustom org-export-latex-default-packages-alist
3274 '(("AUTO" "inputenc" t)
3275 ("T1" "fontenc" t)
3276 ("" "fixltx2e" nil)
3277 ("" "graphicx" t)
3278 ("" "longtable" nil)
3279 ("" "float" nil)
3280 ("" "wrapfig" nil)
3281 ("" "soul" t)
3282 ("" "textcomp" t)
3283 ("" "marvosym" t)
3284 ("" "wasysym" t)
3285 ("" "latexsym" t)
3286 ("" "amssymb" t)
3287 ("" "hyperref" nil)
3288 "\\tolerance=1000"
3290 "Alist of default packages to be inserted in the header.
3291 Change this only if one of the packages here causes an incompatibility
3292 with another package you are using.
3293 The packages in this list are needed by one part or another of Org-mode
3294 to function properly.
3296 - inputenc, fontenc: for basic font and character selection
3297 - textcomp, marvosymb, wasysym, latexsym, amssym: for various symbols used
3298 for interpreting the entities in `org-entities'. You can skip some of these
3299 packages if you don't use any of the symbols in it.
3300 - graphicx: for including images
3301 - float, wrapfig: for figure placement
3302 - longtable: for long tables
3303 - hyperref: for cross references
3305 Therefore you should not modify this variable unless you know what you
3306 are doing. The one reason to change it anyway is that you might be loading
3307 some other package that conflicts with one of the default packages.
3308 Each cell is of the format \( \"options\" \"package\" snippet-flag\).
3309 If SNIPPET-FLAG is t, the package also needs to be included when
3310 compiling LaTeX snippets into images for inclusion into HTML."
3311 :group 'org-export-latex
3312 :set 'org-set-packages-alist
3313 :get 'org-get-packages-alist
3314 :type '(repeat
3315 (choice
3316 (list :tag "options/package pair"
3317 (string :tag "options")
3318 (string :tag "package")
3319 (boolean :tag "Snippet"))
3320 (string :tag "A line of LaTeX"))))
3322 (defcustom org-export-latex-packages-alist nil
3323 "Alist of packages to be inserted in every LaTeX header.
3324 These will be inserted after `org-export-latex-default-packages-alist'.
3325 Each cell is of the format \( \"options\" \"package\" snippet-flag \).
3326 SNIPPET-FLAG, when t, indicates that this package is also needed when
3327 turning LaTeX snippets into images for inclusion into HTML.
3328 Make sure that you only list packages here which:
3329 - you want in every file
3330 - do not conflict with the default packages in
3331 `org-export-latex-default-packages-alist'
3332 - do not conflict with the setup in `org-format-latex-header'."
3333 :group 'org-export-latex
3334 :set 'org-set-packages-alist
3335 :get 'org-get-packages-alist
3336 :type '(repeat
3337 (choice
3338 (list :tag "options/package pair"
3339 (string :tag "options")
3340 (string :tag "package")
3341 (boolean :tag "Snippet"))
3342 (string :tag "A line of LaTeX"))))
3345 (defgroup org-appearance nil
3346 "Settings for Org-mode appearance."
3347 :tag "Org Appearance"
3348 :group 'org)
3350 (defcustom org-level-color-stars-only nil
3351 "Non-nil means fontify only the stars in each headline.
3352 When nil, the entire headline is fontified.
3353 Changing it requires restart of `font-lock-mode' to become effective
3354 also in regions already fontified."
3355 :group 'org-appearance
3356 :type 'boolean)
3358 (defcustom org-hide-leading-stars nil
3359 "Non-nil means hide the first N-1 stars in a headline.
3360 This works by using the face `org-hide' for these stars. This
3361 face is white for a light background, and black for a dark
3362 background. You may have to customize the face `org-hide' to
3363 make this work.
3364 Changing it requires restart of `font-lock-mode' to become effective
3365 also in regions already fontified.
3366 You may also set this on a per-file basis by adding one of the following
3367 lines to the buffer:
3369 #+STARTUP: hidestars
3370 #+STARTUP: showstars"
3371 :group 'org-appearance
3372 :type 'boolean)
3374 (defcustom org-hidden-keywords nil
3375 "List of symbols corresponding to keywords to be hidden the org buffer.
3376 For example, a value '(title) for this list will make the document's title
3377 appear in the buffer without the initial #+TITLE: keyword."
3378 :group 'org-appearance
3379 :type '(set (const :tag "#+AUTHOR" author)
3380 (const :tag "#+DATE" date)
3381 (const :tag "#+EMAIL" email)
3382 (const :tag "#+TITLE" title)))
3384 (defcustom org-fontify-done-headline nil
3385 "Non-nil means change the face of a headline if it is marked DONE.
3386 Normally, only the TODO/DONE keyword indicates the state of a headline.
3387 When this is non-nil, the headline after the keyword is set to the
3388 `org-headline-done' as an additional indication."
3389 :group 'org-appearance
3390 :type 'boolean)
3392 (defcustom org-fontify-emphasized-text t
3393 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3394 Changing this variable requires a restart of Emacs to take effect."
3395 :group 'org-appearance
3396 :type 'boolean)
3398 (defcustom org-fontify-whole-heading-line nil
3399 "Non-nil means fontify the whole line for headings.
3400 This is useful when setting a background color for the
3401 org-level-* faces."
3402 :group 'org-appearance
3403 :type 'boolean)
3405 (defcustom org-highlight-latex-fragments-and-specials nil
3406 "Non-nil means fontify what is treated specially by the exporters."
3407 :group 'org-appearance
3408 :type 'boolean)
3410 (defcustom org-hide-emphasis-markers nil
3411 "Non-nil mean font-lock should hide the emphasis marker characters."
3412 :group 'org-appearance
3413 :type 'boolean)
3415 (defcustom org-pretty-entities nil
3416 "Non-nil means show entities as UTF8 characters.
3417 When nil, the \\name form remains in the buffer."
3418 :group 'org-appearance
3419 :type 'boolean)
3421 (defcustom org-pretty-entities-include-sub-superscripts t
3422 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3423 :group 'org-appearance
3424 :type 'boolean)
3426 (defvar org-emph-re nil
3427 "Regular expression for matching emphasis.
3428 After a match, the match groups contain these elements:
3429 0 The match of the full regular expression, including the characters
3430 before and after the proper match
3431 1 The character before the proper match, or empty at beginning of line
3432 2 The proper match, including the leading and trailing markers
3433 3 The leading marker like * or /, indicating the type of highlighting
3434 4 The text between the emphasis markers, not including the markers
3435 5 The character after the match, empty at the end of a line")
3436 (defvar org-verbatim-re nil
3437 "Regular expression for matching verbatim text.")
3438 (defvar org-emphasis-regexp-components) ; defined just below
3439 (defvar org-emphasis-alist) ; defined just below
3440 (defun org-set-emph-re (var val)
3441 "Set variable and compute the emphasis regular expression."
3442 (set var val)
3443 (when (and (boundp 'org-emphasis-alist)
3444 (boundp 'org-emphasis-regexp-components)
3445 org-emphasis-alist org-emphasis-regexp-components)
3446 (let* ((e org-emphasis-regexp-components)
3447 (pre (car e))
3448 (post (nth 1 e))
3449 (border (nth 2 e))
3450 (body (nth 3 e))
3451 (nl (nth 4 e))
3452 (body1 (concat body "*?"))
3453 (markers (mapconcat 'car org-emphasis-alist ""))
3454 (vmarkers (mapconcat
3455 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3456 org-emphasis-alist "")))
3457 ;; make sure special characters appear at the right position in the class
3458 (if (string-match "\\^" markers)
3459 (setq markers (concat (replace-match "" t t markers) "^")))
3460 (if (string-match "-" markers)
3461 (setq markers (concat (replace-match "" t t markers) "-")))
3462 (if (string-match "\\^" vmarkers)
3463 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3464 (if (string-match "-" vmarkers)
3465 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3466 (if (> nl 0)
3467 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3468 (int-to-string nl) "\\}")))
3469 ;; Make the regexp
3470 (setq org-emph-re
3471 (concat "\\([" pre "]\\|^\\)"
3472 "\\("
3473 "\\([" markers "]\\)"
3474 "\\("
3475 "[^" border "]\\|"
3476 "[^" border "]"
3477 body1
3478 "[^" border "]"
3479 "\\)"
3480 "\\3\\)"
3481 "\\([" post "]\\|$\\)"))
3482 (setq org-verbatim-re
3483 (concat "\\([" pre "]\\|^\\)"
3484 "\\("
3485 "\\([" vmarkers "]\\)"
3486 "\\("
3487 "[^" border "]\\|"
3488 "[^" border "]"
3489 body1
3490 "[^" border "]"
3491 "\\)"
3492 "\\3\\)"
3493 "\\([" post "]\\|$\\)")))))
3495 (defcustom org-emphasis-regexp-components
3496 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
3497 "Components used to build the regular expression for emphasis.
3498 This is a list with five entries. Terminology: In an emphasis string
3499 like \" *strong word* \", we call the initial space PREMATCH, the final
3500 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3501 and \"trong wor\" is the body. The different components in this variable
3502 specify what is allowed/forbidden in each part:
3504 pre Chars allowed as prematch. Beginning of line will be allowed too.
3505 post Chars allowed as postmatch. End of line will be allowed too.
3506 border The chars *forbidden* as border characters.
3507 body-regexp A regexp like \".\" to match a body character. Don't use
3508 non-shy groups here, and don't allow newline here.
3509 newline The maximum number of newlines allowed in an emphasis exp.
3511 Use customize to modify this, or restart Emacs after changing it."
3512 :group 'org-appearance
3513 :set 'org-set-emph-re
3514 :type '(list
3515 (sexp :tag "Allowed chars in pre ")
3516 (sexp :tag "Allowed chars in post ")
3517 (sexp :tag "Forbidden chars in border ")
3518 (sexp :tag "Regexp for body ")
3519 (integer :tag "number of newlines allowed")
3520 (option (boolean :tag "Please ignore this button"))))
3522 (defcustom org-emphasis-alist
3523 `(("*" bold "<b>" "</b>")
3524 ("/" italic "<i>" "</i>")
3525 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
3526 ("=" org-code "<code>" "</code>" verbatim)
3527 ("~" org-verbatim "<code>" "</code>" verbatim)
3528 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
3529 "<del>" "</del>")
3531 "Special syntax for emphasized text.
3532 Text starting and ending with a special character will be emphasized, for
3533 example *bold*, _underlined_ and /italic/. This variable sets the marker
3534 characters, the face to be used by font-lock for highlighting in Org-mode
3535 Emacs buffers, and the HTML tags to be used for this.
3536 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
3537 For DocBook export, see the variable `org-export-docbook-emphasis-alist'.
3538 Use customize to modify this, or restart Emacs after changing it."
3539 :group 'org-appearance
3540 :set 'org-set-emph-re
3541 :type '(repeat
3542 (list
3543 (string :tag "Marker character")
3544 (choice
3545 (face :tag "Font-lock-face")
3546 (plist :tag "Face property list"))
3547 (string :tag "HTML start tag")
3548 (string :tag "HTML end tag")
3549 (option (const verbatim)))))
3551 (defvar org-protecting-blocks
3552 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
3553 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
3554 This is needed for font-lock setup.")
3556 ;;; Miscellaneous options
3558 (defgroup org-completion nil
3559 "Completion in Org-mode."
3560 :tag "Org Completion"
3561 :group 'org)
3563 (defcustom org-completion-use-ido nil
3564 "Non-nil means use ido completion wherever possible.
3565 Note that `ido-mode' must be active for this variable to be relevant.
3566 If you decide to turn this variable on, you might well want to turn off
3567 `org-outline-path-complete-in-steps'.
3568 See also `org-completion-use-iswitchb'."
3569 :group 'org-completion
3570 :type 'boolean)
3572 (defcustom org-completion-use-iswitchb nil
3573 "Non-nil means use iswitchb completion wherever possible.
3574 Note that `iswitchb-mode' must be active for this variable to be relevant.
3575 If you decide to turn this variable on, you might well want to turn off
3576 `org-outline-path-complete-in-steps'.
3577 Note that this variable has only an effect if `org-completion-use-ido' is nil."
3578 :group 'org-completion
3579 :type 'boolean)
3581 (defcustom org-completion-fallback-command 'hippie-expand
3582 "The expansion command called by \\[pcomplete] in normal context.
3583 Normal means, no org-mode-specific context."
3584 :group 'org-completion
3585 :type 'function)
3587 ;;; Functions and variables from their packages
3588 ;; Declared here to avoid compiler warnings
3590 ;; XEmacs only
3591 (defvar outline-mode-menu-heading)
3592 (defvar outline-mode-menu-show)
3593 (defvar outline-mode-menu-hide)
3594 (defvar zmacs-regions) ; XEmacs regions
3596 ;; Emacs only
3597 (defvar mark-active)
3599 ;; Various packages
3600 (declare-function calendar-absolute-from-iso "cal-iso" (date))
3601 (declare-function calendar-forward-day "cal-move" (arg))
3602 (declare-function calendar-goto-date "cal-move" (date))
3603 (declare-function calendar-goto-today "cal-move" ())
3604 (declare-function calendar-iso-from-absolute "cal-iso" (date))
3605 (defvar calc-embedded-close-formula)
3606 (defvar calc-embedded-open-formula)
3607 (declare-function cdlatex-tab "ext:cdlatex" ())
3608 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3609 (defvar font-lock-unfontify-region-function)
3610 (declare-function iswitchb-read-buffer "iswitchb"
3611 (prompt &optional default require-match start matches-set))
3612 (defvar iswitchb-temp-buflist)
3613 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
3614 (defvar org-agenda-tags-todo-honor-ignore-options)
3615 (declare-function org-agenda-skip "org-agenda" ())
3616 (declare-function
3617 org-format-agenda-item "org-agenda"
3618 (extra txt &optional category tags dotime noprefix remove-re habitp))
3619 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
3620 (declare-function org-agenda-change-all-lines "org-agenda"
3621 (newhead hdmarker &optional fixface just-this))
3622 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
3623 (declare-function org-agenda-maybe-redo "org-agenda" ())
3624 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
3625 (beg end))
3626 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
3627 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
3628 "org-agenda" (&optional end))
3629 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
3630 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
3631 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
3632 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
3633 (declare-function org-indent-mode "org-indent" (&optional arg))
3634 (declare-function parse-time-string "parse-time" (string))
3635 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
3636 (declare-function org-export-latex-fix-inputenc "org-latex" ())
3637 (declare-function orgtbl-send-table "org-table" (&optional maybe))
3638 (defvar remember-data-file)
3639 (defvar texmathp-why)
3640 (declare-function speedbar-line-directory "speedbar" (&optional depth))
3641 (declare-function table--at-cell-p "table" (position &optional object at-column))
3643 (defvar w3m-current-url)
3644 (defvar w3m-current-title)
3646 (defvar org-latex-regexps)
3648 ;;; Autoload and prepare some org modules
3650 ;; Some table stuff that needs to be defined here, because it is used
3651 ;; by the functions setting up org-mode or checking for table context.
3653 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
3654 "Detect an org-type or table-type table.")
3655 (defconst org-table-line-regexp "^[ \t]*|"
3656 "Detect an org-type table line.")
3657 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
3658 "Detect an org-type table line.")
3659 (defconst org-table-hline-regexp "^[ \t]*|-"
3660 "Detect an org-type table hline.")
3661 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
3662 "Detect a table-type table hline.")
3663 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
3664 "Detect the first line outside a table when searching from within it.
3665 This works for both table types.")
3667 ;; Autoload the functions in org-table.el that are needed by functions here.
3669 (eval-and-compile
3670 (org-autoload "org-table"
3671 '(org-table-align org-table-begin org-table-blank-field
3672 org-table-convert org-table-convert-region org-table-copy-down
3673 org-table-copy-region org-table-create
3674 org-table-create-or-convert-from-region
3675 org-table-create-with-table.el org-table-current-dline
3676 org-table-cut-region org-table-delete-column org-table-edit-field
3677 org-table-edit-formulas org-table-end org-table-eval-formula
3678 org-table-export org-table-field-info
3679 org-table-get-stored-formulas org-table-goto-column
3680 org-table-hline-and-move org-table-import org-table-insert-column
3681 org-table-insert-hline org-table-insert-row org-table-iterate
3682 org-table-justify-field-maybe org-table-kill-row
3683 org-table-maybe-eval-formula org-table-maybe-recalculate-line
3684 org-table-move-column org-table-move-column-left
3685 org-table-move-column-right org-table-move-row
3686 org-table-move-row-down org-table-move-row-up
3687 org-table-next-field org-table-next-row org-table-paste-rectangle
3688 org-table-previous-field org-table-recalculate
3689 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
3690 org-table-toggle-coordinate-overlays
3691 org-table-toggle-formula-debugger org-table-wrap-region
3692 orgtbl-mode turn-on-orgtbl org-table-to-lisp
3693 orgtbl-to-generic orgtbl-to-tsv orgtbl-to-csv orgtbl-to-latex
3694 orgtbl-to-orgtbl orgtbl-to-html orgtbl-to-texinfo)))
3696 (defun org-at-table-p (&optional table-type)
3697 "Return t if the cursor is inside an org-type table.
3698 If TABLE-TYPE is non-nil, also check for table.el-type tables."
3699 (if org-enable-table-editor
3700 (save-excursion
3701 (beginning-of-line 1)
3702 (looking-at (if table-type org-table-any-line-regexp
3703 org-table-line-regexp)))
3704 nil))
3705 (defsubst org-table-p () (org-at-table-p))
3707 (defun org-at-table.el-p ()
3708 "Return t if and only if we are at a table.el table."
3709 (and (org-at-table-p 'any)
3710 (save-excursion
3711 (goto-char (org-table-begin 'any))
3712 (looking-at org-table1-hline-regexp))))
3713 (defun org-table-recognize-table.el ()
3714 "If there is a table.el table nearby, recognize it and move into it."
3715 (if org-table-tab-recognizes-table.el
3716 (if (org-at-table.el-p)
3717 (progn
3718 (beginning-of-line 1)
3719 (if (looking-at org-table-dataline-regexp)
3721 (if (looking-at org-table1-hline-regexp)
3722 (progn
3723 (beginning-of-line 2)
3724 (if (looking-at org-table-any-border-regexp)
3725 (beginning-of-line -1)))))
3726 (if (re-search-forward "|" (org-table-end t) t)
3727 (progn
3728 (require 'table)
3729 (if (table--at-cell-p (point))
3731 (message "recognizing table.el table...")
3732 (table-recognize-table)
3733 (message "recognizing table.el table...done")))
3734 (error "This should not happen"))
3736 nil)
3737 nil))
3739 (defun org-at-table-hline-p ()
3740 "Return t if the cursor is inside a hline in a table."
3741 (if org-enable-table-editor
3742 (save-excursion
3743 (beginning-of-line 1)
3744 (looking-at org-table-hline-regexp))
3745 nil))
3747 (defvar org-table-clean-did-remove-column nil)
3749 (defun org-table-map-tables (function &optional quietly)
3750 "Apply FUNCTION to the start of all tables in the buffer."
3751 (save-excursion
3752 (save-restriction
3753 (widen)
3754 (goto-char (point-min))
3755 (while (re-search-forward org-table-any-line-regexp nil t)
3756 (unless quietly
3757 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
3758 (beginning-of-line 1)
3759 (when (looking-at org-table-line-regexp)
3760 (save-excursion (funcall function))
3761 (or (looking-at org-table-line-regexp)
3762 (forward-char 1)))
3763 (re-search-forward org-table-any-border-regexp nil 1))))
3764 (unless quietly (message "Mapping tables: done")))
3766 ;; Declare and autoload functions from org-exp.el & Co
3768 (declare-function org-default-export-plist "org-exp")
3769 (declare-function org-infile-export-plist "org-exp")
3770 (declare-function org-get-current-options "org-exp")
3771 (eval-and-compile
3772 (org-autoload "org-exp"
3773 '(org-export org-export-visible
3774 org-insert-export-options-template
3775 org-table-clean-before-export))
3776 (org-autoload "org-ascii"
3777 '(org-export-as-ascii org-export-ascii-preprocess
3778 org-export-as-ascii-to-buffer org-replace-region-by-ascii
3779 org-export-region-as-ascii))
3780 (org-autoload "org-latex"
3781 '(org-export-as-latex-batch org-export-as-latex-to-buffer
3782 org-replace-region-by-latex org-export-region-as-latex
3783 org-export-as-latex org-export-as-pdf
3784 org-export-as-pdf-and-open))
3785 (org-autoload "org-html"
3786 '(org-export-as-html-and-open
3787 org-export-as-html-batch org-export-as-html-to-buffer
3788 org-replace-region-by-html org-export-region-as-html
3789 org-export-as-html))
3790 (org-autoload "org-docbook"
3791 '(org-export-as-docbook-batch org-export-as-docbook-to-buffer
3792 org-replace-region-by-docbook org-export-region-as-docbook
3793 org-export-as-docbook-pdf org-export-as-docbook-pdf-and-open
3794 org-export-as-docbook))
3795 (org-autoload "org-icalendar"
3796 '(org-export-icalendar-this-file
3797 org-export-icalendar-all-agenda-files
3798 org-export-icalendar-combine-agenda-files))
3799 (org-autoload "org-xoxo" '(org-export-as-xoxo))
3800 (org-autoload "org-beamer" '(org-beamer-mode org-beamer-sectioning)))
3802 ;; Declare and autoload functions from org-agenda.el
3804 (eval-and-compile
3805 (org-autoload "org-agenda"
3806 '(org-agenda org-agenda-list org-search-view
3807 org-todo-list org-tags-view org-agenda-list-stuck-projects
3808 org-diary org-agenda-to-appt
3809 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
3811 ;; Autoload org-remember
3813 (eval-and-compile
3814 (org-autoload "org-remember"
3815 '(org-remember-insinuate org-remember-annotation
3816 org-remember-apply-template org-remember org-remember-handler)))
3818 (eval-and-compile
3819 (org-autoload "org-capture"
3820 '(org-capture org-capture-insert-template-here
3821 org-capture-import-remember-templates)))
3823 ;; Autoload org-clock.el
3825 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
3826 (beg end))
3827 (declare-function org-clock-update-mode-line "org-clock" ())
3828 (declare-function org-resolve-clocks "org-clock"
3829 (&optional also-non-dangling-p prompt last-valid))
3830 (defvar org-clock-start-time)
3831 (defvar org-clock-marker (make-marker)
3832 "Marker recording the last clock-in.")
3833 (defvar org-clock-hd-marker (make-marker)
3834 "Marker recording the last clock-in, but the headline position.")
3835 (defvar org-clock-heading ""
3836 "The heading of the current clock entry.")
3837 (defun org-clock-is-active ()
3838 "Return non-nil if clock is currently running.
3839 The return value is actually the clock marker."
3840 (marker-buffer org-clock-marker))
3842 (eval-and-compile
3843 (org-autoload
3844 "org-clock"
3845 '(org-clock-in org-clock-out org-clock-cancel
3846 org-clock-goto org-clock-sum org-clock-display
3847 org-clock-remove-overlays org-clock-report
3848 org-clocktable-shift org-dblock-write:clocktable
3849 org-get-clocktable org-resolve-clocks)))
3851 (defun org-clock-update-time-maybe ()
3852 "If this is a CLOCK line, update it and return t.
3853 Otherwise, return nil."
3854 (interactive)
3855 (save-excursion
3856 (beginning-of-line 1)
3857 (skip-chars-forward " \t")
3858 (when (looking-at org-clock-string)
3859 (let ((re (concat "[ \t]*" org-clock-string
3860 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
3861 "\\([ \t]*=>.*\\)?\\)?"))
3862 ts te h m s neg)
3863 (cond
3864 ((not (looking-at re))
3865 nil)
3866 ((not (match-end 2))
3867 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3868 (> org-clock-marker (point))
3869 (<= org-clock-marker (point-at-eol)))
3870 ;; The clock is running here
3871 (setq org-clock-start-time
3872 (apply 'encode-time
3873 (org-parse-time-string (match-string 1))))
3874 (org-clock-update-mode-line)))
3876 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
3877 (end-of-line 1)
3878 (setq ts (match-string 1)
3879 te (match-string 3))
3880 (setq s (- (org-float-time
3881 (apply 'encode-time (org-parse-time-string te)))
3882 (org-float-time
3883 (apply 'encode-time (org-parse-time-string ts))))
3884 neg (< s 0)
3885 s (abs s)
3886 h (floor (/ s 3600))
3887 s (- s (* 3600 h))
3888 m (floor (/ s 60))
3889 s (- s (* 60 s)))
3890 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
3891 t))))))
3893 (defun org-check-running-clock ()
3894 "Check if the current buffer contains the running clock.
3895 If yes, offer to stop it and to save the buffer with the changes."
3896 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3897 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
3898 (buffer-name))))
3899 (org-clock-out)
3900 (when (y-or-n-p "Save changed buffer?")
3901 (save-buffer))))
3903 (defun org-clocktable-try-shift (dir n)
3904 "Check if this line starts a clock table, if yes, shift the time block."
3905 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
3906 (org-clocktable-shift dir n)))
3908 ;; Autoload org-timer.el
3910 (eval-and-compile
3911 (org-autoload
3912 "org-timer"
3913 '(org-timer-start org-timer org-timer-item
3914 org-timer-change-times-in-region
3915 org-timer-set-timer
3916 org-timer-reset-timers
3917 org-timer-show-remaining-time)))
3919 ;; Autoload org-feed.el
3921 (eval-and-compile
3922 (org-autoload
3923 "org-feed"
3924 '(org-feed-update org-feed-update-all org-feed-goto-inbox)))
3927 ;; Autoload org-indent.el
3929 ;; Define the variable already here, to make sure we have it.
3930 (defvar org-indent-mode nil
3931 "Non-nil if Org-Indent mode is enabled.
3932 Use the command `org-indent-mode' to change this variable.")
3934 (eval-and-compile
3935 (org-autoload
3936 "org-indent"
3937 '(org-indent-mode)))
3939 ;; Autoload org-mobile.el
3941 (eval-and-compile
3942 (org-autoload
3943 "org-mobile"
3944 '(org-mobile-push org-mobile-pull org-mobile-create-sumo-agenda)))
3946 ;; Autoload archiving code
3947 ;; The stuff that is needed for cycling and tags has to be defined here.
3949 (defgroup org-archive nil
3950 "Options concerning archiving in Org-mode."
3951 :tag "Org Archive"
3952 :group 'org-structure)
3954 (defcustom org-archive-location "%s_archive::"
3955 "The location where subtrees should be archived.
3957 The value of this variable is a string, consisting of two parts,
3958 separated by a double-colon. The first part is a filename and
3959 the second part is a headline.
3961 When the filename is omitted, archiving happens in the same file.
3962 %s in the filename will be replaced by the current file
3963 name (without the directory part). Archiving to a different file
3964 is useful to keep archived entries from contributing to the
3965 Org-mode Agenda.
3967 The archived entries will be filed as subtrees of the specified
3968 headline. When the headline is omitted, the subtrees are simply
3969 filed away at the end of the file, as top-level entries. Also in
3970 the heading you can use %s to represent the file name, this can be
3971 useful when using the same archive for a number of different files.
3973 Here are a few examples:
3974 \"%s_archive::\"
3975 If the current file is Projects.org, archive in file
3976 Projects.org_archive, as top-level trees. This is the default.
3978 \"::* Archived Tasks\"
3979 Archive in the current file, under the top-level headline
3980 \"* Archived Tasks\".
3982 \"~/org/archive.org::\"
3983 Archive in file ~/org/archive.org (absolute path), as top-level trees.
3985 \"~/org/archive.org::From %s\"
3986 Archive in file ~/org/archive.org (absolute path), under headlines
3987 \"From FILENAME\" where file name is the current file name.
3989 \"basement::** Finished Tasks\"
3990 Archive in file ./basement (relative path), as level 3 trees
3991 below the level 2 heading \"** Finished Tasks\".
3993 You may set this option on a per-file basis by adding to the buffer a
3994 line like
3996 #+ARCHIVE: basement::** Finished Tasks
3998 You may also define it locally for a subtree by setting an ARCHIVE property
3999 in the entry. If such a property is found in an entry, or anywhere up
4000 the hierarchy, it will be used."
4001 :group 'org-archive
4002 :type 'string)
4004 (defcustom org-archive-tag "ARCHIVE"
4005 "The tag that marks a subtree as archived.
4006 An archived subtree does not open during visibility cycling, and does
4007 not contribute to the agenda listings.
4008 After changing this, font-lock must be restarted in the relevant buffers to
4009 get the proper fontification."
4010 :group 'org-archive
4011 :group 'org-keywords
4012 :type 'string)
4014 (defcustom org-agenda-skip-archived-trees t
4015 "Non-nil means the agenda will skip any items located in archived trees.
4016 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4017 variable is no longer recommended, you should leave it at the value t.
4018 Instead, use the key `v' to cycle the archives-mode in the agenda."
4019 :group 'org-archive
4020 :group 'org-agenda-skip
4021 :type 'boolean)
4023 (defcustom org-columns-skip-archived-trees t
4024 "Non-nil means ignore archived trees when creating column view."
4025 :group 'org-archive
4026 :group 'org-properties
4027 :type 'boolean)
4029 (defcustom org-cycle-open-archived-trees nil
4030 "Non-nil means `org-cycle' will open archived trees.
4031 An archived tree is a tree marked with the tag ARCHIVE.
4032 When nil, archived trees will stay folded. You can still open them with
4033 normal outline commands like `show-all', but not with the cycling commands."
4034 :group 'org-archive
4035 :group 'org-cycle
4036 :type 'boolean)
4038 (defcustom org-sparse-tree-open-archived-trees nil
4039 "Non-nil means sparse tree construction shows matches in archived trees.
4040 When nil, matches in these trees are highlighted, but the trees are kept in
4041 collapsed state."
4042 :group 'org-archive
4043 :group 'org-sparse-trees
4044 :type 'boolean)
4046 (defun org-cycle-hide-archived-subtrees (state)
4047 "Re-hide all archived subtrees after a visibility state change."
4048 (when (and (not org-cycle-open-archived-trees)
4049 (not (memq state '(overview folded))))
4050 (save-excursion
4051 (let* ((globalp (memq state '(contents all)))
4052 (beg (if globalp (point-min) (point)))
4053 (end (if globalp (point-max) (org-end-of-subtree t))))
4054 (org-hide-archived-subtrees beg end)
4055 (goto-char beg)
4056 (if (looking-at (concat ".*:" org-archive-tag ":"))
4057 (message "%s" (substitute-command-keys
4058 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4060 (defun org-force-cycle-archived ()
4061 "Cycle subtree even if it is archived."
4062 (interactive)
4063 (setq this-command 'org-cycle)
4064 (let ((org-cycle-open-archived-trees t))
4065 (call-interactively 'org-cycle)))
4067 (defun org-hide-archived-subtrees (beg end)
4068 "Re-hide all archived subtrees after a visibility state change."
4069 (save-excursion
4070 (let* ((re (concat ":" org-archive-tag ":")))
4071 (goto-char beg)
4072 (while (re-search-forward re end t)
4073 (when (org-on-heading-p)
4074 (org-flag-subtree t)
4075 (org-end-of-subtree t))))))
4077 (defun org-flag-subtree (flag)
4078 (save-excursion
4079 (org-back-to-heading t)
4080 (outline-end-of-heading)
4081 (outline-flag-region (point)
4082 (progn (org-end-of-subtree t) (point))
4083 flag)))
4085 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4087 (eval-and-compile
4088 (org-autoload "org-archive"
4089 '(org-add-archive-files org-archive-subtree
4090 org-archive-to-archive-sibling org-toggle-archive-tag
4091 org-archive-subtree-default
4092 org-archive-subtree-default-with-confirmation)))
4094 ;; Autoload Column View Code
4096 (declare-function org-columns-number-to-string "org-colview")
4097 (declare-function org-columns-get-format-and-top-level "org-colview")
4098 (declare-function org-columns-compute "org-colview")
4100 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4101 '(org-columns-number-to-string org-columns-get-format-and-top-level
4102 org-columns-compute org-agenda-columns org-columns-remove-overlays
4103 org-columns org-insert-columns-dblock org-dblock-write:columnview))
4105 ;; Autoload ID code
4107 (declare-function org-id-store-link "org-id")
4108 (declare-function org-id-locations-load "org-id")
4109 (declare-function org-id-locations-save "org-id")
4110 (defvar org-id-track-globally)
4111 (org-autoload "org-id"
4112 '(org-id-get-create org-id-new org-id-copy org-id-get
4113 org-id-get-with-outline-path-completion
4114 org-id-get-with-outline-drilling org-id-store-link
4115 org-id-goto org-id-find org-id-store-link))
4117 ;; Autoload Plotting Code
4119 (org-autoload "org-plot"
4120 '(org-plot/gnuplot))
4122 ;;; Variables for pre-computed regular expressions, all buffer local
4124 (defvar org-drawer-regexp nil
4125 "Matches first line of a hidden block.")
4126 (make-variable-buffer-local 'org-drawer-regexp)
4127 (defvar org-todo-regexp nil
4128 "Matches any of the TODO state keywords.")
4129 (make-variable-buffer-local 'org-todo-regexp)
4130 (defvar org-not-done-regexp nil
4131 "Matches any of the TODO state keywords except the last one.")
4132 (make-variable-buffer-local 'org-not-done-regexp)
4133 (defvar org-not-done-heading-regexp nil
4134 "Matches a TODO headline that is not done.")
4135 (make-variable-buffer-local 'org-not-done-regexp)
4136 (defvar org-todo-line-regexp nil
4137 "Matches a headline and puts TODO state into group 2 if present.")
4138 (make-variable-buffer-local 'org-todo-line-regexp)
4139 (defvar org-complex-heading-regexp nil
4140 "Matches a headline and puts everything into groups:
4141 group 1: the stars
4142 group 2: The todo keyword, maybe
4143 group 3: Priority cookie
4144 group 4: True headline
4145 group 5: Tags")
4146 (make-variable-buffer-local 'org-complex-heading-regexp)
4147 (defvar org-complex-heading-regexp-format nil
4148 "Printf format to make regexp to match an exact headline.
4149 This regexp will match the headline of any node which hase the exact
4150 headline text that is put into the format, but may have any TODO state,
4151 priority and tags.")
4152 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4153 (defvar org-todo-line-tags-regexp nil
4154 "Matches a headline and puts TODO state into group 2 if present.
4155 Also put tags into group 4 if tags are present.")
4156 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4157 (defvar org-nl-done-regexp nil
4158 "Matches newline followed by a headline with the DONE keyword.")
4159 (make-variable-buffer-local 'org-nl-done-regexp)
4160 (defvar org-looking-at-done-regexp nil
4161 "Matches the DONE keyword a point.")
4162 (make-variable-buffer-local 'org-looking-at-done-regexp)
4163 (defvar org-ds-keyword-length 12
4164 "Maximum length of the Deadline and SCHEDULED keywords.")
4165 (make-variable-buffer-local 'org-ds-keyword-length)
4166 (defvar org-deadline-regexp nil
4167 "Matches the DEADLINE keyword.")
4168 (make-variable-buffer-local 'org-deadline-regexp)
4169 (defvar org-deadline-time-regexp nil
4170 "Matches the DEADLINE keyword together with a time stamp.")
4171 (make-variable-buffer-local 'org-deadline-time-regexp)
4172 (defvar org-deadline-line-regexp nil
4173 "Matches the DEADLINE keyword and the rest of the line.")
4174 (make-variable-buffer-local 'org-deadline-line-regexp)
4175 (defvar org-scheduled-regexp nil
4176 "Matches the SCHEDULED keyword.")
4177 (make-variable-buffer-local 'org-scheduled-regexp)
4178 (defvar org-scheduled-time-regexp nil
4179 "Matches the SCHEDULED keyword together with a time stamp.")
4180 (make-variable-buffer-local 'org-scheduled-time-regexp)
4181 (defvar org-closed-time-regexp nil
4182 "Matches the CLOSED keyword together with a time stamp.")
4183 (make-variable-buffer-local 'org-closed-time-regexp)
4185 (defvar org-keyword-time-regexp nil
4186 "Matches any of the 4 keywords, together with the time stamp.")
4187 (make-variable-buffer-local 'org-keyword-time-regexp)
4188 (defvar org-keyword-time-not-clock-regexp nil
4189 "Matches any of the 3 keywords, together with the time stamp.")
4190 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4191 (defvar org-maybe-keyword-time-regexp nil
4192 "Matches a timestamp, possibly preceded by a keyword.")
4193 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4194 (defvar org-planning-or-clock-line-re nil
4195 "Matches a line with planning or clock info.")
4196 (make-variable-buffer-local 'org-planning-or-clock-line-re)
4197 (defvar org-all-time-keywords nil
4198 "List of time keywords.")
4199 (make-variable-buffer-local 'org-all-time-keywords)
4201 (defconst org-plain-time-of-day-regexp
4202 (concat
4203 "\\(\\<[012]?[0-9]"
4204 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4205 "\\(--?"
4206 "\\(\\<[012]?[0-9]"
4207 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4208 "\\)?")
4209 "Regular expression to match a plain time or time range.
4210 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4211 groups carry important information:
4212 0 the full match
4213 1 the first time, range or not
4214 8 the second time, if it is a range.")
4216 (defconst org-plain-time-extension-regexp
4217 (concat
4218 "\\(\\<[012]?[0-9]"
4219 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4220 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4221 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4222 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4223 groups carry important information:
4224 0 the full match
4225 7 hours of duration
4226 9 minutes of duration")
4228 (defconst org-stamp-time-of-day-regexp
4229 (concat
4230 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4231 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4232 "\\(--?"
4233 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4234 "Regular expression to match a timestamp time or time range.
4235 After a match, the following groups carry important information:
4236 0 the full match
4237 1 date plus weekday, for back referencing to make sure both times are on the same day
4238 2 the first time, range or not
4239 4 the second time, if it is a range.")
4241 (defconst org-startup-options
4242 '(("fold" org-startup-folded t)
4243 ("overview" org-startup-folded t)
4244 ("nofold" org-startup-folded nil)
4245 ("showall" org-startup-folded nil)
4246 ("showeverything" org-startup-folded showeverything)
4247 ("content" org-startup-folded content)
4248 ("indent" org-startup-indented t)
4249 ("noindent" org-startup-indented nil)
4250 ("hidestars" org-hide-leading-stars t)
4251 ("showstars" org-hide-leading-stars nil)
4252 ("odd" org-odd-levels-only t)
4253 ("oddeven" org-odd-levels-only nil)
4254 ("align" org-startup-align-all-tables t)
4255 ("noalign" org-startup-align-all-tables nil)
4256 ("inlineimages" org-startup-with-inline-images t)
4257 ("noinlineimages" org-startup-with-inline-images nil)
4258 ("customtime" org-display-custom-times t)
4259 ("logdone" org-log-done time)
4260 ("lognotedone" org-log-done note)
4261 ("nologdone" org-log-done nil)
4262 ("lognoteclock-out" org-log-note-clock-out t)
4263 ("nolognoteclock-out" org-log-note-clock-out nil)
4264 ("logrepeat" org-log-repeat state)
4265 ("lognoterepeat" org-log-repeat note)
4266 ("nologrepeat" org-log-repeat nil)
4267 ("logreschedule" org-log-reschedule time)
4268 ("lognotereschedule" org-log-reschedule note)
4269 ("nologreschedule" org-log-reschedule nil)
4270 ("logredeadline" org-log-redeadline time)
4271 ("lognoteredeadline" org-log-redeadline note)
4272 ("nologredeadline" org-log-redeadline nil)
4273 ("logrefile" org-log-refile time)
4274 ("lognoterefile" org-log-refile note)
4275 ("nologrefile" org-log-refile nil)
4276 ("fninline" org-footnote-define-inline t)
4277 ("nofninline" org-footnote-define-inline nil)
4278 ("fnlocal" org-footnote-section nil)
4279 ("fnauto" org-footnote-auto-label t)
4280 ("fnprompt" org-footnote-auto-label nil)
4281 ("fnconfirm" org-footnote-auto-label confirm)
4282 ("fnplain" org-footnote-auto-label plain)
4283 ("fnadjust" org-footnote-auto-adjust t)
4284 ("nofnadjust" org-footnote-auto-adjust nil)
4285 ("constcgs" constants-unit-system cgs)
4286 ("constSI" constants-unit-system SI)
4287 ("noptag" org-tag-persistent-alist nil)
4288 ("hideblocks" org-hide-block-startup t)
4289 ("nohideblocks" org-hide-block-startup nil)
4290 ("beamer" org-startup-with-beamer-mode t)
4291 ("entitiespretty" org-pretty-entities t)
4292 ("entitiesplain" org-pretty-entities nil))
4293 "Variable associated with STARTUP options for org-mode.
4294 Each element is a list of three items: The startup options as written
4295 in the #+STARTUP line, the corresponding variable, and the value to
4296 set this variable to if the option is found. An optional forth element PUSH
4297 means to push this value onto the list in the variable.")
4299 (defun org-set-regexps-and-options ()
4300 "Precompute regular expressions for current buffer."
4301 (when (org-mode-p)
4302 (org-set-local 'org-todo-kwd-alist nil)
4303 (org-set-local 'org-todo-key-alist nil)
4304 (org-set-local 'org-todo-key-trigger nil)
4305 (org-set-local 'org-todo-keywords-1 nil)
4306 (org-set-local 'org-done-keywords nil)
4307 (org-set-local 'org-todo-heads nil)
4308 (org-set-local 'org-todo-sets nil)
4309 (org-set-local 'org-todo-log-states nil)
4310 (org-set-local 'org-file-properties nil)
4311 (org-set-local 'org-file-tags nil)
4312 (let ((re (org-make-options-regexp
4313 '("CATEGORY" "TODO" "COLUMNS"
4314 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
4315 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE" "LATEX_CLASS"
4316 "OPTIONS")
4317 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4318 (splitre "[ \t]+")
4319 (scripts org-use-sub-superscripts)
4320 kwds kws0 kwsa key log value cat arch tags const links hw dws
4321 tail sep kws1 prio props ftags drawers beamer-p
4322 ext-setup-or-nil setup-contents (start 0))
4323 (save-excursion
4324 (save-restriction
4325 (widen)
4326 (goto-char (point-min))
4327 (while (or (and ext-setup-or-nil
4328 (string-match re ext-setup-or-nil start)
4329 (setq start (match-end 0)))
4330 (and (setq ext-setup-or-nil nil start 0)
4331 (re-search-forward re nil t)))
4332 (setq key (upcase (match-string 1 ext-setup-or-nil))
4333 value (org-match-string-no-properties 2 ext-setup-or-nil))
4334 (if (stringp value) (setq value (org-trim value)))
4335 (cond
4336 ((equal key "CATEGORY")
4337 (setq cat value))
4338 ((member key '("SEQ_TODO" "TODO"))
4339 (push (cons 'sequence (org-split-string value splitre)) kwds))
4340 ((equal key "TYP_TODO")
4341 (push (cons 'type (org-split-string value splitre)) kwds))
4342 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4343 ;; general TODO-like setup
4344 (push (cons (intern (downcase (match-string 1 key)))
4345 (org-split-string value splitre)) kwds))
4346 ((equal key "TAGS")
4347 (setq tags (append tags (if tags '("\\n") nil)
4348 (org-split-string value splitre))))
4349 ((equal key "COLUMNS")
4350 (org-set-local 'org-columns-default-format value))
4351 ((equal key "LINK")
4352 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4353 (push (cons (match-string 1 value)
4354 (org-trim (match-string 2 value)))
4355 links)))
4356 ((equal key "PRIORITIES")
4357 (setq prio (org-split-string value " +")))
4358 ((equal key "PROPERTY")
4359 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4360 (push (cons (match-string 1 value) (match-string 2 value))
4361 props)))
4362 ((equal key "FILETAGS")
4363 (when (string-match "\\S-" value)
4364 (setq ftags
4365 (append
4366 ftags
4367 (apply 'append
4368 (mapcar (lambda (x) (org-split-string x ":"))
4369 (org-split-string value)))))))
4370 ((equal key "DRAWERS")
4371 (setq drawers (org-split-string value splitre)))
4372 ((equal key "CONSTANTS")
4373 (setq const (append const (org-split-string value splitre))))
4374 ((equal key "STARTUP")
4375 (let ((opts (org-split-string value splitre))
4376 l var val)
4377 (while (setq l (pop opts))
4378 (when (setq l (assoc l org-startup-options))
4379 (setq var (nth 1 l) val (nth 2 l))
4380 (if (not (nth 3 l))
4381 (set (make-local-variable var) val)
4382 (if (not (listp (symbol-value var)))
4383 (set (make-local-variable var) nil))
4384 (set (make-local-variable var) (symbol-value var))
4385 (add-to-list var val))))))
4386 ((equal key "ARCHIVE")
4387 (setq arch value)
4388 (remove-text-properties 0 (length arch)
4389 '(face t fontified t) arch))
4390 ((equal key "LATEX_CLASS")
4391 (setq beamer-p (equal value "beamer")))
4392 ((equal key "OPTIONS")
4393 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4394 (setq scripts (read (match-string 2 value)))))
4395 ((equal key "SETUPFILE")
4396 (setq setup-contents (org-file-contents
4397 (expand-file-name
4398 (org-remove-double-quotes value))
4399 'noerror))
4400 (if (not ext-setup-or-nil)
4401 (setq ext-setup-or-nil setup-contents start 0)
4402 (setq ext-setup-or-nil
4403 (concat (substring ext-setup-or-nil 0 start)
4404 "\n" setup-contents "\n"
4405 (substring ext-setup-or-nil start)))))
4406 ))))
4407 (org-set-local 'org-use-sub-superscripts scripts)
4408 (when cat
4409 (org-set-local 'org-category (intern cat))
4410 (push (cons "CATEGORY" cat) props))
4411 (when prio
4412 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4413 (setq prio (mapcar 'string-to-char prio))
4414 (org-set-local 'org-highest-priority (nth 0 prio))
4415 (org-set-local 'org-lowest-priority (nth 1 prio))
4416 (org-set-local 'org-default-priority (nth 2 prio)))
4417 (and props (org-set-local 'org-file-properties (nreverse props)))
4418 (and ftags (org-set-local 'org-file-tags
4419 (mapcar 'org-add-prop-inherited ftags)))
4420 (and drawers (org-set-local 'org-drawers drawers))
4421 (and arch (org-set-local 'org-archive-location arch))
4422 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4423 ;; Process the TODO keywords
4424 (unless kwds
4425 ;; Use the global values as if they had been given locally.
4426 (setq kwds (default-value 'org-todo-keywords))
4427 (if (stringp (car kwds))
4428 (setq kwds (list (cons org-todo-interpretation
4429 (default-value 'org-todo-keywords)))))
4430 (setq kwds (reverse kwds)))
4431 (setq kwds (nreverse kwds))
4432 (let (inter kws kw)
4433 (while (setq kws (pop kwds))
4434 (let ((kws (or
4435 (run-hook-with-args-until-success
4436 'org-todo-setup-filter-hook kws)
4437 kws)))
4438 (setq inter (pop kws) sep (member "|" kws)
4439 kws0 (delete "|" (copy-sequence kws))
4440 kwsa nil
4441 kws1 (mapcar
4442 (lambda (x)
4443 ;; 1 2
4444 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4445 (progn
4446 (setq kw (match-string 1 x)
4447 key (and (match-end 2) (match-string 2 x))
4448 log (org-extract-log-state-settings x))
4449 (push (cons kw (and key (string-to-char key))) kwsa)
4450 (and log (push log org-todo-log-states))
4452 (error "Invalid TODO keyword %s" x)))
4453 kws0)
4454 kwsa (if kwsa (append '((:startgroup))
4455 (nreverse kwsa)
4456 '((:endgroup))))
4457 hw (car kws1)
4458 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4459 tail (list inter hw (car dws) (org-last dws))))
4460 (add-to-list 'org-todo-heads hw 'append)
4461 (push kws1 org-todo-sets)
4462 (setq org-done-keywords (append org-done-keywords dws nil))
4463 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4464 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4465 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4466 (setq org-todo-sets (nreverse org-todo-sets)
4467 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4468 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4469 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4470 ;; Process the constants
4471 (when const
4472 (let (e cst)
4473 (while (setq e (pop const))
4474 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4475 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4476 (setq org-table-formula-constants-local cst)))
4478 ;; Process the tags.
4479 (when tags
4480 (let (e tgs)
4481 (while (setq e (pop tags))
4482 (cond
4483 ((equal e "{") (push '(:startgroup) tgs))
4484 ((equal e "}") (push '(:endgroup) tgs))
4485 ((equal e "\\n") (push '(:newline) tgs))
4486 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4487 (push (cons (match-string 1 e)
4488 (string-to-char (match-string 2 e)))
4489 tgs))
4490 (t (push (list e) tgs))))
4491 (org-set-local 'org-tag-alist nil)
4492 (while (setq e (pop tgs))
4493 (or (and (stringp (car e))
4494 (assoc (car e) org-tag-alist))
4495 (push e org-tag-alist)))))
4497 ;; Compute the regular expressions and other local variables
4498 (if (not org-done-keywords)
4499 (setq org-done-keywords (and org-todo-keywords-1
4500 (list (org-last org-todo-keywords-1)))))
4501 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4502 (length org-scheduled-string)
4503 (length org-clock-string)
4504 (length org-closed-string)))
4505 org-drawer-regexp
4506 (concat "^[ \t]*:\\("
4507 (mapconcat 'regexp-quote org-drawers "\\|")
4508 "\\):[ \t]*$")
4509 org-not-done-keywords
4510 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4511 org-todo-regexp
4512 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
4513 "\\|") "\\)\\>")
4514 org-not-done-regexp
4515 (concat "\\<\\("
4516 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4517 "\\)\\>")
4518 org-not-done-heading-regexp
4519 (concat "^\\(\\*+\\)[ \t]+\\("
4520 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4521 "\\)\\>")
4522 org-todo-line-regexp
4523 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4524 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4525 "\\)\\>\\)?[ \t]*\\(.*\\)")
4526 org-complex-heading-regexp
4527 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4528 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4529 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
4530 "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
4531 org-complex-heading-regexp-format
4532 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4533 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4534 "\\)\\>\\)?"
4535 "\\(?:[ \t]*\\(\\[#.\\]\\)\\)?"
4536 "\\(?:[ \t]*\\(?:\\[[0-9%%/]+\\]\\)\\)?" ;; stats cookie
4537 "[ \t]*\\(%s\\)"
4538 "\\(?:[ \t]*\\(?:\\[[0-9%%/]+\\]\\)\\)?" ;; stats cookie
4539 "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?[ \t]*$")
4540 org-nl-done-regexp
4541 (concat "\n\\*+[ \t]+"
4542 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
4543 "\\)" "\\>")
4544 org-todo-line-tags-regexp
4545 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4546 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4547 (org-re
4548 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@#%]+:[ \t]*\\)?$\\)"))
4549 org-looking-at-done-regexp
4550 (concat "^" "\\(?:"
4551 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
4552 "\\>")
4553 org-deadline-regexp (concat "\\<" org-deadline-string)
4554 org-deadline-time-regexp
4555 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4556 org-deadline-line-regexp
4557 (concat "\\<\\(" org-deadline-string "\\).*")
4558 org-scheduled-regexp
4559 (concat "\\<" org-scheduled-string)
4560 org-scheduled-time-regexp
4561 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4562 org-closed-time-regexp
4563 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4564 org-keyword-time-regexp
4565 (concat "\\<\\(" org-scheduled-string
4566 "\\|" org-deadline-string
4567 "\\|" org-closed-string
4568 "\\|" org-clock-string "\\)"
4569 " *[[<]\\([^]>]+\\)[]>]")
4570 org-keyword-time-not-clock-regexp
4571 (concat "\\<\\(" org-scheduled-string
4572 "\\|" org-deadline-string
4573 "\\|" org-closed-string
4574 "\\)"
4575 " *[[<]\\([^]>]+\\)[]>]")
4576 org-maybe-keyword-time-regexp
4577 (concat "\\(\\<\\(" org-scheduled-string
4578 "\\|" org-deadline-string
4579 "\\|" org-closed-string
4580 "\\|" org-clock-string "\\)\\)?"
4581 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4582 org-planning-or-clock-line-re
4583 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
4584 "\\|" org-deadline-string
4585 "\\|" org-closed-string "\\|" org-clock-string
4586 "\\)\\>\\)")
4587 org-all-time-keywords
4588 (mapcar (lambda (w) (substring w 0 -1))
4589 (list org-scheduled-string org-deadline-string
4590 org-clock-string org-closed-string))
4592 (org-compute-latex-and-specials-regexp)
4593 (org-set-font-lock-defaults))))
4595 (defun org-file-contents (file &optional noerror)
4596 "Return the contents of FILE, as a string."
4597 (if (or (not file)
4598 (not (file-readable-p file)))
4599 (if noerror
4600 (progn
4601 (message "Cannot read file \"%s\"" file)
4602 (ding) (sit-for 2)
4604 (error "Cannot read file \"%s\"" file))
4605 (with-temp-buffer
4606 (insert-file-contents file)
4607 (buffer-string))))
4609 (defun org-extract-log-state-settings (x)
4610 "Extract the log state setting from a TODO keyword string.
4611 This will extract info from a string like \"WAIT(w@/!)\"."
4612 (let (kw key log1 log2)
4613 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4614 (setq kw (match-string 1 x)
4615 key (and (match-end 2) (match-string 2 x))
4616 log1 (and (match-end 3) (match-string 3 x))
4617 log2 (and (match-end 4) (match-string 4 x)))
4618 (and (or log1 log2)
4619 (list kw
4620 (and log1 (if (equal log1 "!") 'time 'note))
4621 (and log2 (if (equal log2 "!") 'time 'note)))))))
4623 (defun org-remove-keyword-keys (list)
4624 "Remove a pair of parenthesis at the end of each string in LIST."
4625 (mapcar (lambda (x)
4626 (if (string-match "(.*)$" x)
4627 (substring x 0 (match-beginning 0))
4629 list))
4631 (defun org-assign-fast-keys (alist)
4632 "Assign fast keys to a keyword-key alist.
4633 Respect keys that are already there."
4634 (let (new e (alt ?0))
4635 (while (setq e (pop alist))
4636 (if (or (memq (car e) '(:newline :endgroup :startgroup))
4637 (cdr e)) ;; Key already assigned.
4638 (push e new)
4639 (let ((clist (string-to-list (downcase (car e))))
4640 (used (append new alist)))
4641 (when (= (car clist) ?@)
4642 (pop clist))
4643 (while (and clist (rassoc (car clist) used))
4644 (pop clist))
4645 (unless clist
4646 (while (rassoc alt used)
4647 (incf alt)))
4648 (push (cons (car e) (or (car clist) alt)) new))))
4649 (nreverse new)))
4651 ;;; Some variables used in various places
4653 (defvar org-window-configuration nil
4654 "Used in various places to store a window configuration.")
4655 (defvar org-selected-window nil
4656 "Used in various places to store a window configuration.")
4657 (defvar org-finish-function nil
4658 "Function to be called when `C-c C-c' is used.
4659 This is for getting out of special buffers like remember.")
4662 ;; FIXME: Occasionally check by commenting these, to make sure
4663 ;; no other functions uses these, forgetting to let-bind them.
4664 (defvar entry)
4665 (defvar last-state)
4666 (defvar date)
4668 ;; Defined somewhere in this file, but used before definition.
4669 (defvar org-entities) ;; defined in org-entities.el
4670 (defvar org-struct-menu)
4671 (defvar org-org-menu)
4672 (defvar org-tbl-menu)
4674 ;;;; Define the Org-mode
4676 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4677 (error "Conflict with outdated version of allout.el. Load org.el before allout.el, or upgrade to newer allout, for example by switching to Emacs 22"))
4680 ;; We use a before-change function to check if a table might need
4681 ;; an update.
4682 (defvar org-table-may-need-update t
4683 "Indicates that a table might need an update.
4684 This variable is set by `org-before-change-function'.
4685 `org-table-align' sets it back to nil.")
4686 (defun org-before-change-function (beg end)
4687 "Every change indicates that a table might need an update."
4688 (setq org-table-may-need-update t))
4689 (defvar org-mode-map)
4690 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4691 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
4692 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4693 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
4694 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
4695 (defvar org-table-buffer-is-an nil)
4696 (defconst org-outline-regexp "\\*+ ")
4698 ;;;###autoload
4699 (define-derived-mode org-mode outline-mode "Org"
4700 "Outline-based notes management and organizer, alias
4701 \"Carsten's outline-mode for keeping track of everything.\"
4703 Org-mode develops organizational tasks around a NOTES file which
4704 contains information about projects as plain text. Org-mode is
4705 implemented on top of outline-mode, which is ideal to keep the content
4706 of large files well structured. It supports ToDo items, deadlines and
4707 time stamps, which magically appear in the diary listing of the Emacs
4708 calendar. Tables are easily created with a built-in table editor.
4709 Plain text URL-like links connect to websites, emails (VM), Usenet
4710 messages (Gnus), BBDB entries, and any files related to the project.
4711 For printing and sharing of notes, an Org-mode file (or a part of it)
4712 can be exported as a structured ASCII or HTML file.
4714 The following commands are available:
4716 \\{org-mode-map}"
4718 ;; Get rid of Outline menus, they are not needed
4719 ;; Need to do this here because define-derived-mode sets up
4720 ;; the keymap so late. Still, it is a waste to call this each time
4721 ;; we switch another buffer into org-mode.
4722 (if (featurep 'xemacs)
4723 (when (boundp 'outline-mode-menu-heading)
4724 ;; Assume this is Greg's port, it uses easymenu
4725 (easy-menu-remove outline-mode-menu-heading)
4726 (easy-menu-remove outline-mode-menu-show)
4727 (easy-menu-remove outline-mode-menu-hide))
4728 (define-key org-mode-map [menu-bar headings] 'undefined)
4729 (define-key org-mode-map [menu-bar hide] 'undefined)
4730 (define-key org-mode-map [menu-bar show] 'undefined))
4732 (org-load-modules-maybe)
4733 (easy-menu-add org-org-menu)
4734 (easy-menu-add org-tbl-menu)
4735 (org-install-agenda-files-menu)
4736 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
4737 (add-to-invisibility-spec '(org-cwidth))
4738 (add-to-invisibility-spec '(org-hide-block . t))
4739 (when (featurep 'xemacs)
4740 (org-set-local 'line-move-ignore-invisible t))
4741 (org-set-local 'outline-regexp org-outline-regexp)
4742 (org-set-local 'outline-level 'org-outline-level)
4743 (when (and org-ellipsis
4744 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
4745 (fboundp 'make-glyph-code))
4746 (unless org-display-table
4747 (setq org-display-table (make-display-table)))
4748 (set-display-table-slot
4749 org-display-table 4
4750 (vconcat (mapcar
4751 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
4752 org-ellipsis)))
4753 (if (stringp org-ellipsis) org-ellipsis "..."))))
4754 (setq buffer-display-table org-display-table))
4755 (org-set-regexps-and-options)
4756 (when (and org-tag-faces (not org-tags-special-faces-re))
4757 ;; tag faces set outside customize.... force initialization.
4758 (org-set-tag-faces 'org-tag-faces org-tag-faces))
4759 ;; Calc embedded
4760 (org-set-local 'calc-embedded-open-mode "# ")
4761 (modify-syntax-entry ?@ "w")
4762 (if org-startup-truncated (setq truncate-lines t))
4763 (org-set-local 'font-lock-unfontify-region-function
4764 'org-unfontify-region)
4765 ;; Activate before-change-function
4766 (org-set-local 'org-table-may-need-update t)
4767 (org-add-hook 'before-change-functions 'org-before-change-function nil
4768 'local)
4769 ;; Check for running clock before killing a buffer
4770 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
4771 ;; Paragraphs and auto-filling
4772 (org-set-autofill-regexps)
4773 (setq indent-line-function 'org-indent-line-function)
4774 (org-update-radio-target-regexp)
4775 ;; Beginning/end of defun
4776 (org-set-local 'beginning-of-defun-function 'org-beginning-of-defun)
4777 (org-set-local 'end-of-defun-function 'org-end-of-defun)
4778 ;; Next error for sparse trees
4779 (org-set-local 'next-error-function 'org-occur-next-match)
4780 ;; Make sure dependence stuff works reliably, even for users who set it
4781 ;; too late :-(
4782 (if org-enforce-todo-dependencies
4783 (add-hook 'org-blocker-hook
4784 'org-block-todo-from-children-or-siblings-or-parent)
4785 (remove-hook 'org-blocker-hook
4786 'org-block-todo-from-children-or-siblings-or-parent))
4787 (if org-enforce-todo-checkbox-dependencies
4788 (add-hook 'org-blocker-hook
4789 'org-block-todo-from-checkboxes)
4790 (remove-hook 'org-blocker-hook
4791 'org-block-todo-from-checkboxes))
4793 ;; Comment characters
4794 (org-set-local 'comment-start "#")
4795 (org-set-local 'comment-padding " ")
4797 ;; Align options lines
4798 (org-set-local
4799 'align-mode-rules-list
4800 '((org-in-buffer-settings
4801 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
4802 (modes . '(org-mode)))))
4804 ;; Imenu
4805 (org-set-local 'imenu-create-index-function
4806 'org-imenu-get-tree)
4808 ;; Make isearch reveal context
4809 (if (or (featurep 'xemacs)
4810 (not (boundp 'outline-isearch-open-invisible-function)))
4811 ;; Emacs 21 and XEmacs make use of the hook
4812 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
4813 ;; Emacs 22 deals with this through a special variable
4814 (org-set-local 'outline-isearch-open-invisible-function
4815 (lambda (&rest ignore) (org-show-context 'isearch))))
4817 ;; Turn on org-beamer-mode?
4818 (and org-startup-with-beamer-mode (org-beamer-mode 1))
4820 ;; Setup the pcomplete hooks
4821 (set (make-local-variable 'pcomplete-command-completion-function)
4822 'org-pcomplete-initial)
4823 (set (make-local-variable 'pcomplete-command-name-function)
4824 'org-command-at-point)
4825 (set (make-local-variable 'pcomplete-default-completion-function)
4826 'ignore)
4827 (set (make-local-variable 'pcomplete-parse-arguments-function)
4828 'org-parse-arguments)
4829 (set (make-local-variable 'pcomplete-termination-string) "")
4831 ;; If empty file that did not turn on org-mode automatically, make it to.
4832 (if (and org-insert-mode-line-in-empty-file
4833 (org-called-interactively-p 'any)
4834 (= (point-min) (point-max)))
4835 (insert "# -*- mode: org -*-\n\n"))
4836 (unless org-inhibit-startup
4837 (when org-startup-align-all-tables
4838 (let ((bmp (buffer-modified-p)))
4839 (org-table-map-tables 'org-table-align 'quietly)
4840 (set-buffer-modified-p bmp)))
4841 (when org-startup-with-inline-images
4842 (org-display-inline-images))
4843 (when org-startup-indented
4844 (require 'org-indent)
4845 (org-indent-mode 1))
4846 (unless org-inhibit-startup-visibility-stuff
4847 (org-set-startup-visibility))))
4849 (when (fboundp 'abbrev-table-put)
4850 (abbrev-table-put org-mode-abbrev-table
4851 :parents (list text-mode-abbrev-table)))
4853 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
4855 (defun org-current-time ()
4856 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
4857 (if (> (car org-time-stamp-rounding-minutes) 1)
4858 (let ((r (car org-time-stamp-rounding-minutes))
4859 (time (decode-time)))
4860 (apply 'encode-time
4861 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
4862 (nthcdr 2 time))))
4863 (current-time)))
4865 (defun org-today ()
4866 "Return today date, considering `org-extend-today-until'."
4867 (time-to-days
4868 (time-subtract (current-time)
4869 (list 0 (* 3600 org-extend-today-until) 0))))
4871 ;;;; Font-Lock stuff, including the activators
4873 (defvar org-mouse-map (make-sparse-keymap))
4874 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
4875 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
4876 (when org-mouse-1-follows-link
4877 (org-defkey org-mouse-map [follow-link] 'mouse-face))
4878 (when org-tab-follows-link
4879 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
4880 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
4882 (require 'font-lock)
4884 (defconst org-non-link-chars "]\t\n\r<>")
4885 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
4886 "shell" "elisp" "doi" "message"))
4887 (defvar org-link-types-re nil
4888 "Matches a link that has a url-like prefix like \"http:\"")
4889 (defvar org-link-re-with-space nil
4890 "Matches a link with spaces, optional angular brackets around it.")
4891 (defvar org-link-re-with-space2 nil
4892 "Matches a link with spaces, optional angular brackets around it.")
4893 (defvar org-link-re-with-space3 nil
4894 "Matches a link with spaces, only for internal part in bracket links.")
4895 (defvar org-angle-link-re nil
4896 "Matches link with angular brackets, spaces are allowed.")
4897 (defvar org-plain-link-re nil
4898 "Matches plain link, without spaces.")
4899 (defvar org-bracket-link-regexp nil
4900 "Matches a link in double brackets.")
4901 (defvar org-bracket-link-analytic-regexp nil
4902 "Regular expression used to analyze links.
4903 Here is what the match groups contain after a match:
4904 1: http:
4905 2: http
4906 3: path
4907 4: [desc]
4908 5: desc")
4909 (defvar org-bracket-link-analytic-regexp++ nil
4910 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
4911 (defvar org-any-link-re nil
4912 "Regular expression matching any link.")
4914 (defcustom org-match-sexp-depth 3
4915 "Number of stacked braces for sub/superscript matching.
4916 This has to be set before loading org.el to be effective."
4917 :group 'org-export-translation ; ??????????????????????????/
4918 :type 'integer)
4920 (defun org-create-multibrace-regexp (left right n)
4921 "Create a regular expression which will match a balanced sexp.
4922 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
4923 as single character strings.
4924 The regexp returned will match the entire expression including the
4925 delimiters. It will also define a single group which contains the
4926 match except for the outermost delimiters. The maximum depth of
4927 stacked delimiters is N. Escaping delimiters is not possible."
4928 (let* ((nothing (concat "[^" left right "]*?"))
4929 (or "\\|")
4930 (re nothing)
4931 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
4932 (while (> n 1)
4933 (setq n (1- n)
4934 re (concat re or next)
4935 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
4936 (concat left "\\(" re "\\)" right)))
4938 (defvar org-match-substring-regexp
4939 (concat
4940 "\\([^\\]\\)\\([_^]\\)\\("
4941 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
4942 "\\|"
4943 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
4944 "\\|"
4945 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
4946 "The regular expression matching a sub- or superscript.")
4948 (defvar org-match-substring-with-braces-regexp
4949 (concat
4950 "\\([^\\]\\)\\([_^]\\)\\("
4951 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
4952 "\\)")
4953 "The regular expression matching a sub- or superscript, forcing braces.")
4955 (defun org-make-link-regexps ()
4956 "Update the link regular expressions.
4957 This should be called after the variable `org-link-types' has changed."
4958 (setq org-link-types-re
4959 (concat
4960 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
4961 org-link-re-with-space
4962 (concat
4963 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4964 "\\([^" org-non-link-chars " ]"
4965 "[^" org-non-link-chars "]*"
4966 "[^" org-non-link-chars " ]\\)>?")
4967 org-link-re-with-space2
4968 (concat
4969 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4970 "\\([^" org-non-link-chars " ]"
4971 "[^\t\n\r]*"
4972 "[^" org-non-link-chars " ]\\)>?")
4973 org-link-re-with-space3
4974 (concat
4975 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4976 "\\([^" org-non-link-chars " ]"
4977 "[^\t\n\r]*\\)")
4978 org-angle-link-re
4979 (concat
4980 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4981 "\\([^" org-non-link-chars " ]"
4982 "[^" org-non-link-chars "]*"
4983 "\\)>")
4984 org-plain-link-re
4985 (concat
4986 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4987 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
4988 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
4989 org-bracket-link-regexp
4990 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
4991 org-bracket-link-analytic-regexp
4992 (concat
4993 "\\[\\["
4994 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
4995 "\\([^]]+\\)"
4996 "\\]"
4997 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4998 "\\]")
4999 org-bracket-link-analytic-regexp++
5000 (concat
5001 "\\[\\["
5002 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5003 "\\([^]]+\\)"
5004 "\\]"
5005 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5006 "\\]")
5007 org-any-link-re
5008 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5009 org-angle-link-re "\\)\\|\\("
5010 org-plain-link-re "\\)")))
5012 (org-make-link-regexps)
5014 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
5015 "Regular expression for fast time stamp matching.")
5016 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?\\)[]>]"
5017 "Regular expression for fast time stamp matching.")
5018 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5019 "Regular expression matching time strings for analysis.
5020 This one does not require the space after the date, so it can be used
5021 on a string that terminates immediately after the date.")
5022 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5023 "Regular expression matching time strings for analysis.")
5024 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5025 "Regular expression matching time stamps, with groups.")
5026 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5027 "Regular expression matching time stamps (also [..]), with groups.")
5028 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5029 "Regular expression matching a time stamp range.")
5030 (defconst org-tr-regexp-both
5031 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5032 "Regular expression matching a time stamp range.")
5033 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5034 org-ts-regexp "\\)?")
5035 "Regular expression matching a time stamp or time stamp range.")
5036 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5037 org-ts-regexp-both "\\)?")
5038 "Regular expression matching a time stamp or time stamp range.
5039 The time stamps may be either active or inactive.")
5041 (defvar org-emph-face nil)
5043 (defun org-do-emphasis-faces (limit)
5044 "Run through the buffer and add overlays to links."
5045 (let (rtn a)
5046 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5047 (if (not (= (char-after (match-beginning 3))
5048 (char-after (match-beginning 4))))
5049 (progn
5050 (setq rtn t)
5051 (setq a (assoc (match-string 3) org-emphasis-alist))
5052 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5053 'face
5054 (nth 1 a))
5055 (and (nth 4 a)
5056 (org-remove-flyspell-overlays-in
5057 (match-beginning 0) (match-end 0)))
5058 (add-text-properties (match-beginning 2) (match-end 2)
5059 '(font-lock-multiline t org-emphasis t))
5060 (when org-hide-emphasis-markers
5061 (add-text-properties (match-end 4) (match-beginning 5)
5062 '(invisible org-link))
5063 (add-text-properties (match-beginning 3) (match-end 3)
5064 '(invisible org-link)))))
5065 (backward-char 1))
5066 rtn))
5068 (defun org-emphasize (&optional char)
5069 "Insert or change an emphasis, i.e. a font like bold or italic.
5070 If there is an active region, change that region to a new emphasis.
5071 If there is no region, just insert the marker characters and position
5072 the cursor between them.
5073 CHAR should be either the marker character, or the first character of the
5074 HTML tag associated with that emphasis. If CHAR is a space, the means
5075 to remove the emphasis of the selected region.
5076 If char is not given (for example in an interactive call) it
5077 will be prompted for."
5078 (interactive)
5079 (let ((eal org-emphasis-alist) e det
5080 (erc org-emphasis-regexp-components)
5081 (prompt "")
5082 (string "") beg end move tag c s)
5083 (if (org-region-active-p)
5084 (setq beg (region-beginning) end (region-end)
5085 string (buffer-substring beg end))
5086 (setq move t))
5088 (while (setq e (pop eal))
5089 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5090 c (aref tag 0))
5091 (push (cons c (string-to-char (car e))) det)
5092 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5093 (substring tag 1)))))
5094 (setq det (nreverse det))
5095 (unless char
5096 (message "%s" (concat "Emphasis marker or tag:" prompt))
5097 (setq char (read-char-exclusive)))
5098 (setq char (or (cdr (assoc char det)) char))
5099 (if (equal char ?\ )
5100 (setq s "" move nil)
5101 (unless (assoc (char-to-string char) org-emphasis-alist)
5102 (error "No such emphasis marker: \"%c\"" char))
5103 (setq s (char-to-string char)))
5104 (while (and (> (length string) 1)
5105 (equal (substring string 0 1) (substring string -1))
5106 (assoc (substring string 0 1) org-emphasis-alist))
5107 (setq string (substring string 1 -1)))
5108 (setq string (concat s string s))
5109 (if beg (delete-region beg end))
5110 (unless (or (bolp)
5111 (string-match (concat "[" (nth 0 erc) "\n]")
5112 (char-to-string (char-before (point)))))
5113 (insert " "))
5114 (unless (or (eobp)
5115 (string-match (concat "[" (nth 1 erc) "\n]")
5116 (char-to-string (char-after (point)))))
5117 (insert " ") (backward-char 1))
5118 (insert string)
5119 (and move (backward-char 1))))
5121 (defconst org-nonsticky-props
5122 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
5124 (defsubst org-rear-nonsticky-at (pos)
5125 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5127 (defun org-activate-plain-links (limit)
5128 "Run through the buffer and add overlays to links."
5129 (catch 'exit
5130 (let (f)
5131 (if (re-search-forward org-plain-link-re limit t)
5132 (progn
5133 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5134 (setq f (get-text-property (match-beginning 0) 'face))
5135 (if (or (eq f 'org-tag)
5136 (and (listp f) (memq 'org-tag f)))
5138 (add-text-properties (match-beginning 0) (match-end 0)
5139 (list 'mouse-face 'highlight
5140 'face 'org-link
5141 'keymap org-mouse-map))
5142 (org-rear-nonsticky-at (match-end 0)))
5143 t)))))
5145 (defun org-activate-code (limit)
5146 (if (re-search-forward "^[ \t]*\\(: .*\n?\\)" limit t)
5147 (progn
5148 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5149 (remove-text-properties (match-beginning 0) (match-end 0)
5150 '(display t invisible t intangible t))
5151 t)))
5153 (defcustom org-src-fontify-natively nil
5154 "When non-nil, fontify code in code blocks."
5155 :type 'boolean
5156 :group 'org-appearance
5157 :group 'org-babel)
5159 (defun org-fontify-meta-lines-and-blocks (limit)
5160 (condition-case nil
5161 (org-fontify-meta-lines-and-blocks-1 limit)
5162 (error (message "org-mode fontification error"))))
5164 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5165 "Fontify #+ lines and blocks, in the correct ways."
5166 (let ((case-fold-search t))
5167 (if (re-search-forward
5168 "^\\([ \t]*#\\+\\(\\([a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5169 limit t)
5170 (let ((beg (match-beginning 0))
5171 (block-start (match-end 0))
5172 (block-end nil)
5173 (lang (match-string 7))
5174 (beg1 (line-beginning-position 2))
5175 (dc1 (downcase (match-string 2)))
5176 (dc3 (downcase (match-string 3)))
5177 end end1 quoting block-type ovl)
5178 (cond
5179 ((member dc1 '("html:" "ascii:" "latex:" "docbook:"))
5180 ;; a single line of backend-specific content
5181 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5182 (remove-text-properties (match-beginning 0) (match-end 0)
5183 '(display t invisible t intangible t))
5184 (add-text-properties (match-beginning 1) (match-end 3)
5185 '(font-lock-fontified t face org-meta-line))
5186 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5187 '(font-lock-fontified t face org-block))
5188 ; for backend-specific code
5190 ((and (match-end 4) (equal dc3 "begin"))
5191 ;; Truly a block
5192 (setq block-type (downcase (match-string 5))
5193 quoting (member block-type org-protecting-blocks))
5194 (when (re-search-forward
5195 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5196 nil t) ;; on purpose, we look further than LIMIT
5197 (setq end (match-end 0) end1 (1- (match-beginning 0)))
5198 (setq block-end (match-beginning 0))
5199 (when quoting
5200 (remove-text-properties beg end
5201 '(display t invisible t intangible t)))
5202 (add-text-properties
5203 beg end
5204 '(font-lock-fontified t font-lock-multiline t))
5205 (add-text-properties beg beg1 '(face org-meta-line))
5206 (add-text-properties end1 (+ end 1) '(face org-meta-line))
5207 ; for end_src
5208 (cond
5209 ((and lang org-src-fontify-natively)
5210 (org-src-font-lock-fontify-block lang block-start block-end)
5211 ;; remove old background overlays
5212 (mapc (lambda (ov)
5213 (if (eq (overlay-get ov 'face) 'org-block-background)
5214 (delete-overlay ov)))
5215 (overlays-at (/ (+ beg1 block-end) 2)))
5216 ;; add a background overlay
5217 (setq ovl (make-overlay beg1 block-end))
5218 (overlay-put ovl 'face 'org-block-background)
5219 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5220 (quoting
5221 (add-text-properties beg1 (+ end1 1) '(face org-block)))
5222 ; end of source block
5223 ((not org-fontify-quote-and-verse-blocks))
5224 ((string= block-type "quote")
5225 (add-text-properties beg1 (1+ end1) '(face org-quote)))
5226 ((string= block-type "verse")
5227 (add-text-properties beg1 (1+ end1) '(face org-verse))))
5228 (add-text-properties beg beg1 '(face org-block-begin-line))
5229 (add-text-properties (1+ end) (1+ end1) '(face org-block-end-line))
5231 ((member dc1 '("title:" "author:" "email:" "date:"))
5232 (add-text-properties
5233 beg (match-end 3)
5234 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5235 '(font-lock-fontified t invisible t)
5236 '(font-lock-fontified t face org-document-info-keyword)))
5237 (add-text-properties
5238 (match-beginning 6) (match-end 6)
5239 (if (string-equal dc1 "title:")
5240 '(font-lock-fontified t face org-document-title)
5241 '(font-lock-fontified t face org-document-info))))
5242 ((not (member (char-after beg) '(?\ ?\t)))
5243 ;; just any other in-buffer setting, but not indented
5244 (add-text-properties
5245 beg (1+ (match-end 0))
5246 '(font-lock-fontified t face org-meta-line))
5248 ((or (member dc1 '("begin:" "end:" "caption:" "label:"
5249 "orgtbl:" "tblfm:" "tblname:" "result:"
5250 "results:" "source:" "srcname:" "call:"))
5251 (and (match-end 4) (equal dc3 "attr")))
5252 (add-text-properties
5253 beg (match-end 0)
5254 '(font-lock-fontified t face org-meta-line))
5256 ((member dc3 '(" " ""))
5257 (add-text-properties
5258 beg (match-end 0)
5259 '(font-lock-fontified t face font-lock-comment-face)))
5260 (t nil))))))
5262 (defun org-activate-angle-links (limit)
5263 "Run through the buffer and add overlays to links."
5264 (if (re-search-forward org-angle-link-re limit t)
5265 (progn
5266 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5267 (add-text-properties (match-beginning 0) (match-end 0)
5268 (list 'mouse-face 'highlight
5269 'keymap org-mouse-map))
5270 (org-rear-nonsticky-at (match-end 0))
5271 t)))
5273 (defun org-activate-footnote-links (limit)
5274 "Run through the buffer and add overlays to links."
5275 (let ((fn (org-footnote-next-reference-or-definition limit)))
5276 (when fn
5277 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5278 (org-remove-flyspell-overlays-in beg end)
5279 (add-text-properties beg end
5280 (list 'mouse-face 'highlight
5281 'keymap org-mouse-map
5282 'help-echo
5283 (if (= (point-at-bol) beg)
5284 "Footnote definition"
5285 "Footnote reference")))
5286 (save-excursion
5287 (goto-char beg)
5288 (looking-at (regexp-quote (buffer-substring beg end))))))))
5290 (defun org-activate-bracket-links (limit)
5291 "Run through the buffer and add overlays to bracketed links."
5292 (if (re-search-forward org-bracket-link-regexp limit t)
5293 (let* ((help (concat "LINK: "
5294 (org-match-string-no-properties 1)))
5295 ;; FIXME: above we should remove the escapes.
5296 ;; but that requires another match, protecting match data,
5297 ;; a lot of overhead for font-lock.
5298 (ip (org-maybe-intangible
5299 (list 'invisible 'org-link
5300 'keymap org-mouse-map 'mouse-face 'highlight
5301 'font-lock-multiline t 'help-echo help)))
5302 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5303 'font-lock-multiline t 'help-echo help)))
5304 ;; We need to remove the invisible property here. Table narrowing
5305 ;; may have made some of this invisible.
5306 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5307 (remove-text-properties (match-beginning 0) (match-end 0)
5308 '(invisible nil))
5309 (if (match-end 3)
5310 (progn
5311 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5312 (org-rear-nonsticky-at (match-beginning 3))
5313 (add-text-properties (match-beginning 3) (match-end 3) vp)
5314 (org-rear-nonsticky-at (match-end 3))
5315 (add-text-properties (match-end 3) (match-end 0) ip)
5316 (org-rear-nonsticky-at (match-end 0)))
5317 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5318 (org-rear-nonsticky-at (match-beginning 1))
5319 (add-text-properties (match-beginning 1) (match-end 1) vp)
5320 (org-rear-nonsticky-at (match-end 1))
5321 (add-text-properties (match-end 1) (match-end 0) ip)
5322 (org-rear-nonsticky-at (match-end 0)))
5323 t)))
5325 (defun org-activate-dates (limit)
5326 "Run through the buffer and add overlays to dates."
5327 (if (re-search-forward org-tsr-regexp-both limit t)
5328 (progn
5329 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5330 (add-text-properties (match-beginning 0) (match-end 0)
5331 (list 'mouse-face 'highlight
5332 'keymap org-mouse-map))
5333 (org-rear-nonsticky-at (match-end 0))
5334 (when org-display-custom-times
5335 (if (match-end 3)
5336 (org-display-custom-time (match-beginning 3) (match-end 3)))
5337 (org-display-custom-time (match-beginning 1) (match-end 1)))
5338 t)))
5340 (defvar org-target-link-regexp nil
5341 "Regular expression matching radio targets in plain text.")
5342 (make-variable-buffer-local 'org-target-link-regexp)
5343 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5344 "Regular expression matching a link target.")
5345 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5346 "Regular expression matching a radio target.")
5347 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5348 "Regular expression matching any target.")
5350 (defun org-activate-target-links (limit)
5351 "Run through the buffer and add overlays to target matches."
5352 (when org-target-link-regexp
5353 (let ((case-fold-search t))
5354 (if (re-search-forward org-target-link-regexp limit t)
5355 (progn
5356 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5357 (add-text-properties (match-beginning 0) (match-end 0)
5358 (list 'mouse-face 'highlight
5359 'keymap org-mouse-map
5360 'help-echo "Radio target link"
5361 'org-linked-text t))
5362 (org-rear-nonsticky-at (match-end 0))
5363 t)))))
5365 (defun org-update-radio-target-regexp ()
5366 "Find all radio targets in this file and update the regular expression."
5367 (interactive)
5368 (when (memq 'radio org-activate-links)
5369 (setq org-target-link-regexp
5370 (org-make-target-link-regexp (org-all-targets 'radio)))
5371 (org-restart-font-lock)))
5373 (defun org-hide-wide-columns (limit)
5374 (let (s e)
5375 (setq s (text-property-any (point) (or limit (point-max))
5376 'org-cwidth t))
5377 (when s
5378 (setq e (next-single-property-change s 'org-cwidth))
5379 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5380 (goto-char e)
5381 t)))
5383 (defvar org-latex-and-specials-regexp nil
5384 "Regular expression for highlighting export special stuff.")
5385 (defvar org-match-substring-regexp)
5386 (defvar org-match-substring-with-braces-regexp)
5388 ;; This should be with the exporter code, but we also use if for font-locking
5389 (defconst org-export-html-special-string-regexps
5390 '(("\\\\-" . "&shy;")
5391 ("---\\([^-]\\)" . "&mdash;\\1")
5392 ("--\\([^-]\\)" . "&ndash;\\1")
5393 ("\\.\\.\\." . "&hellip;"))
5394 "Regular expressions for special string conversion.")
5397 (defun org-compute-latex-and-specials-regexp ()
5398 "Compute regular expression for stuff treated specially by exporters."
5399 (if (not org-highlight-latex-fragments-and-specials)
5400 (org-set-local 'org-latex-and-specials-regexp nil)
5401 (require 'org-exp)
5402 (let*
5403 ((matchers (plist-get org-format-latex-options :matchers))
5404 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5405 org-latex-regexps)))
5406 (org-export-allow-BIND nil)
5407 (options (org-combine-plists (org-default-export-plist)
5408 (org-infile-export-plist)))
5409 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5410 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5411 (org-export-with-TeX-macros (plist-get options :TeX-macros))
5412 (org-export-html-expand (plist-get options :expand-quoted-html))
5413 (org-export-with-special-strings (plist-get options :special-strings))
5414 (re-sub
5415 (cond
5416 ((equal org-export-with-sub-superscripts '{})
5417 (list org-match-substring-with-braces-regexp))
5418 (org-export-with-sub-superscripts
5419 (list org-match-substring-regexp))
5420 (t nil)))
5421 (re-latex
5422 (if org-export-with-LaTeX-fragments
5423 (mapcar (lambda (x) (nth 1 x)) latexs)))
5424 (re-macros
5425 (if org-export-with-TeX-macros
5426 (list (concat "\\\\"
5427 (regexp-opt
5428 (append
5430 (delq nil
5431 (mapcar 'car-safe
5432 (append org-entities-user
5433 org-entities)))
5434 (if (boundp 'org-latex-entities)
5435 (mapcar (lambda (x)
5436 (or (car-safe x) x))
5437 org-latex-entities)
5438 nil))
5439 'words))) ; FIXME
5441 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5442 (re-special (if org-export-with-special-strings
5443 (mapcar (lambda (x) (car x))
5444 org-export-html-special-string-regexps)))
5445 (re-rest
5446 (delq nil
5447 (list
5448 (if org-export-html-expand "@<[^>\n]+>")
5449 ))))
5450 (org-set-local
5451 'org-latex-and-specials-regexp
5452 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5453 re-rest) "\\|")))))
5455 (defun org-do-latex-and-special-faces (limit)
5456 "Run through the buffer and add overlays to links."
5457 (when org-latex-and-specials-regexp
5458 (let (rtn d)
5459 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5460 limit t))
5461 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5462 'face))
5463 '(org-code org-verbatim underline)))
5464 (progn
5465 (setq rtn t
5466 d (cond ((member (char-after (1+ (match-beginning 0)))
5467 '(?_ ?^)) 1)
5468 (t 0)))
5469 (font-lock-prepend-text-property
5470 (+ d (match-beginning 0)) (match-end 0)
5471 'face 'org-latex-and-export-specials)
5472 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5473 '(font-lock-multiline t)))))
5474 rtn)))
5476 (defun org-restart-font-lock ()
5477 "Restart `font-lock-mode', to force refontification."
5478 (when (and (boundp 'font-lock-mode) font-lock-mode)
5479 (font-lock-mode -1)
5480 (font-lock-mode 1)))
5482 (defun org-all-targets (&optional radio)
5483 "Return a list of all targets in this file.
5484 With optional argument RADIO, only find radio targets."
5485 (let ((re (if radio org-radio-target-regexp org-target-regexp))
5486 rtn)
5487 (save-excursion
5488 (goto-char (point-min))
5489 (while (re-search-forward re nil t)
5490 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
5491 rtn)))
5493 (defun org-make-target-link-regexp (targets)
5494 "Make regular expression matching all strings in TARGETS.
5495 The regular expression finds the targets also if there is a line break
5496 between words."
5497 (and targets
5498 (concat
5499 "\\<\\("
5500 (mapconcat
5501 (lambda (x)
5502 (setq x (regexp-quote x))
5503 (while (string-match " +" x)
5504 (setq x (replace-match "\\s-+" t t x)))
5506 targets
5507 "\\|")
5508 "\\)\\>")))
5510 (defun org-activate-tags (limit)
5511 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
5512 (progn
5513 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5514 (add-text-properties (match-beginning 1) (match-end 1)
5515 (list 'mouse-face 'highlight
5516 'keymap org-mouse-map))
5517 (org-rear-nonsticky-at (match-end 1))
5518 t)))
5520 (defun org-outline-level ()
5521 "Compute the outline level of the heading at point.
5522 This function assumes that the cursor is at the beginning of a line matched
5523 by `outline-regexp'. Otherwise it returns garbage.
5524 If this is called at a normal headline, the level is the number of stars.
5525 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
5526 (save-excursion
5527 (looking-at outline-regexp)
5528 (1- (- (match-end 0) (match-beginning 0)))))
5530 (defvar org-font-lock-keywords nil)
5532 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
5533 "Regular expression matching a property line.")
5535 (defvar org-font-lock-hook nil
5536 "Functions to be called for special font lock stuff.")
5538 (defvar org-font-lock-set-keywords-hook nil
5539 "Functions that can manipulate `org-font-lock-extra-keywords'.
5540 This is calles after `org-font-lock-extra-keywords' is defined, but before
5541 it is installed to be used by font lock. This can be useful if something
5542 needs to be inserted at a specific position in the font-lock sequence.")
5544 (defun org-font-lock-hook (limit)
5545 (run-hook-with-args 'org-font-lock-hook limit))
5547 (defun org-set-font-lock-defaults ()
5548 (let* ((em org-fontify-emphasized-text)
5549 (lk org-activate-links)
5550 (org-font-lock-extra-keywords
5551 (list
5552 ;; Call the hook
5553 '(org-font-lock-hook)
5554 ;; Headlines
5555 `(,(if org-fontify-whole-heading-line
5556 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
5557 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
5558 (1 (org-get-level-face 1))
5559 (2 (org-get-level-face 2))
5560 (3 (org-get-level-face 3)))
5561 ;; Table lines
5562 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5563 (1 'org-table t))
5564 ;; Table internals
5565 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5566 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5567 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5568 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
5569 ;; Drawers
5570 (list org-drawer-regexp '(0 'org-special-keyword t))
5571 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5572 ;; Properties
5573 (list org-property-re
5574 '(1 'org-special-keyword t)
5575 '(3 'org-property-value t))
5576 ;; Links
5577 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5578 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5579 (if (memq 'plain lk) '(org-activate-plain-links))
5580 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5581 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5582 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5583 (if (memq 'footnote lk) '(org-activate-footnote-links
5584 (0 'org-footnote t)))
5585 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5586 '(org-hide-wide-columns (0 nil append))
5587 ;; TODO lines
5588 (list (concat "^\\*+[ \t]+" org-todo-regexp "\\([ \t]\\|$\\)")
5589 '(1 (org-get-todo-face 1) t))
5590 ;; DONE
5591 (if org-fontify-done-headline
5592 (list (concat "^[*]+ +\\<\\("
5593 (mapconcat 'regexp-quote org-done-keywords "\\|")
5594 "\\)\\(.*\\)")
5595 '(2 'org-headline-done t))
5596 nil)
5597 ;; Priorities
5598 '(org-font-lock-add-priority-faces)
5599 ;; Tags
5600 '(org-font-lock-add-tag-faces)
5601 ;; Special keywords
5602 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5603 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5604 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5605 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5606 ;; Emphasis
5607 (if em
5608 (if (featurep 'xemacs)
5609 '(org-do-emphasis-faces (0 nil append))
5610 '(org-do-emphasis-faces)))
5611 ;; Checkboxes
5612 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
5613 1 'org-checkbox prepend)
5614 (if (cdr (assq 'checkbox org-list-automatic-rules))
5615 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5616 (0 (org-get-checkbox-statistics-face) t)))
5617 ;; Description list items
5618 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
5619 1 'bold prepend)
5620 ;; ARCHIVEd headings
5621 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
5622 '(1 'org-archived prepend))
5623 ;; Specials
5624 '(org-do-latex-and-special-faces)
5625 '(org-fontify-entities)
5626 '(org-raise-scripts)
5627 ;; Code
5628 '(org-activate-code (1 'org-code t))
5629 ;; COMMENT
5630 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
5631 "\\|" org-quote-string "\\)\\>")
5632 '(1 'org-special-keyword t))
5633 '("^#.*" (0 'font-lock-comment-face t))
5634 ;; Blocks and meta lines
5635 '(org-fontify-meta-lines-and-blocks)
5637 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5638 (run-hooks 'org-font-lock-set-keywords-hook)
5639 ;; Now set the full font-lock-keywords
5640 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5641 (org-set-local 'font-lock-defaults
5642 '(org-font-lock-keywords t nil nil backward-paragraph))
5643 (kill-local-variable 'font-lock-keywords) nil))
5645 (defun org-toggle-pretty-entities ()
5646 "Toggle the composition display of entities as UTF8 characters."
5647 (interactive)
5648 (org-set-local 'org-pretty-entities (not org-pretty-entities))
5649 (org-restart-font-lock)
5650 (if org-pretty-entities
5651 (message "Entities are displayed as UTF8 characers")
5652 (save-restriction
5653 (widen)
5654 (org-decompose-region (point-min) (point-max))
5655 (message "Entities are displayed plain"))))
5657 (defun org-fontify-entities (limit)
5658 "Find an entity to fontify."
5659 (let (ee)
5660 (when org-pretty-entities
5661 (catch 'match
5662 (while (re-search-forward
5663 "\\\\\\([a-zA-Z][a-zA-Z0-9]*\\)\\($\\|[^[:alnum:]\n]\\)"
5664 limit t)
5665 (if (and (not (org-in-indented-comment-line))
5666 (setq ee (org-entity-get (match-string 1)))
5667 (= (length (nth 6 ee)) 1))
5668 (progn
5669 (add-text-properties
5670 (match-beginning 0) (match-end 1)
5671 (list 'font-lock-fontified t))
5672 (compose-region (match-beginning 0) (match-end 1)
5673 (nth 6 ee) nil)
5674 (backward-char 1)
5675 (throw 'match t))))
5676 nil))))
5678 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
5679 "Fontify string S like in Org-mode."
5680 (with-temp-buffer
5681 (insert s)
5682 (let ((org-odd-levels-only odd-levels))
5683 (org-mode)
5684 (font-lock-fontify-buffer)
5685 (buffer-string))))
5687 (defvar org-m nil)
5688 (defvar org-l nil)
5689 (defvar org-f nil)
5690 (defun org-get-level-face (n)
5691 "Get the right face for match N in font-lock matching of headlines."
5692 (setq org-l (- (match-end 2) (match-beginning 1) 1))
5693 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
5694 (if org-cycle-level-faces
5695 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
5696 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
5697 (cond
5698 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
5699 ((eq n 2) org-f)
5700 (t (if org-level-color-stars-only nil org-f))))
5703 (defun org-get-todo-face (kwd)
5704 "Get the right face for a TODO keyword KWD.
5705 If KWD is a number, get the corresponding match group."
5706 (if (numberp kwd) (setq kwd (match-string kwd)))
5707 (or (org-face-from-face-or-color
5708 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
5709 (and (member kwd org-done-keywords) 'org-done)
5710 'org-todo))
5712 (defun org-face-from-face-or-color (context inherit face-or-color)
5713 "Create a face list that inherits INHERIT, but sets the foreground color.
5714 When FACE-OR-COLOR is not a string, just return it."
5715 (if (stringp face-or-color)
5716 (list :inherit inherit
5717 (cdr (assoc context org-faces-easy-properties))
5718 face-or-color)
5719 face-or-color))
5721 (defun org-font-lock-add-tag-faces (limit)
5722 "Add the special tag faces."
5723 (when (and org-tag-faces org-tags-special-faces-re)
5724 (while (re-search-forward org-tags-special-faces-re limit t)
5725 (add-text-properties (match-beginning 1) (match-end 1)
5726 (list 'face (org-get-tag-face 1)
5727 'font-lock-fontified t))
5728 (backward-char 1))))
5730 (defun org-font-lock-add-priority-faces (limit)
5731 "Add the special priority faces."
5732 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
5733 (add-text-properties
5734 (match-beginning 0) (match-end 0)
5735 (list 'face (or (org-face-from-face-or-color
5736 'priority 'org-special-keyword
5737 (cdr (assoc (char-after (match-beginning 1))
5738 org-priority-faces)))
5739 'org-special-keyword)
5740 'font-lock-fontified t))))
5742 (defun org-get-tag-face (kwd)
5743 "Get the right face for a TODO keyword KWD.
5744 If KWD is a number, get the corresponding match group."
5745 (if (numberp kwd) (setq kwd (match-string kwd)))
5746 (or (org-face-from-face-or-color
5747 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
5748 'org-tag))
5750 (defun org-unfontify-region (beg end &optional maybe_loudly)
5751 "Remove fontification and activation overlays from links."
5752 (font-lock-default-unfontify-region beg end)
5753 (let* ((buffer-undo-list t)
5754 (inhibit-read-only t) (inhibit-point-motion-hooks t)
5755 (inhibit-modification-hooks t)
5756 deactivate-mark buffer-file-name buffer-file-truename)
5757 (org-decompose-region beg end)
5758 (remove-text-properties
5759 beg end
5760 (if org-indent-mode
5761 ;; also remove line-prefix and wrap-prefix properties
5762 '(mouse-face t keymap t org-linked-text t
5763 invisible t intangible t
5764 line-prefix t wrap-prefix t
5765 org-no-flyspell t org-emphasis t)
5766 '(mouse-face t keymap t org-linked-text t
5767 invisible t intangible t
5768 org-no-flyspell t org-emphasis t)))
5769 (org-remove-font-lock-display-properties beg end)))
5771 (defconst org-script-display '(((raise -0.3) (height 0.7))
5772 ((raise 0.3) (height 0.7))
5773 ((raise -0.5))
5774 ((raise 0.5)))
5775 "Display properties for showing superscripts and subscripts.")
5777 (defun org-remove-font-lock-display-properties (beg end)
5778 "Remove specific display properties that have been added by font lock.
5779 The will remove the raise properties that are used to show superscripts
5780 and subscripts."
5781 (let (next prop)
5782 (while (< beg end)
5783 (setq next (next-single-property-change beg 'display nil end)
5784 prop (get-text-property beg 'display))
5785 (if (member prop org-script-display)
5786 (put-text-property beg next 'display nil))
5787 (setq beg next))))
5789 (defun org-raise-scripts (limit)
5790 "Add raise properties to sub/superscripts."
5791 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
5792 (if (re-search-forward
5793 (if (eq org-use-sub-superscripts t)
5794 org-match-substring-regexp
5795 org-match-substring-with-braces-regexp)
5796 limit t)
5797 (let* ((pos (point)) table-p comment-p
5798 (mpos (match-beginning 3))
5799 (emph-p (get-text-property mpos 'org-emphasis))
5800 (link-p (get-text-property mpos 'mouse-face))
5801 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
5802 (goto-char (point-at-bol))
5803 (setq table-p (org-looking-at-p org-table-dataline-regexp)
5804 comment-p (org-looking-at-p "[ \t]*#"))
5805 (goto-char pos)
5806 ;; FIXME: Should we go back one character here, for a_b^c
5807 ;; (goto-char (1- pos)) ;????????????????????
5808 (if (or comment-p emph-p link-p keyw-p)
5810 (put-text-property (match-beginning 3) (match-end 0)
5811 'display
5812 (if (equal (char-after (match-beginning 2)) ?^)
5813 (nth (if table-p 3 1) org-script-display)
5814 (nth (if table-p 2 0) org-script-display)))
5815 (add-text-properties (match-beginning 2) (match-end 2)
5816 (list 'invisible t
5817 'org-dwidth t 'org-dwidth-n 1))
5818 (if (and (eq (char-after (match-beginning 3)) ?{)
5819 (eq (char-before (match-end 3)) ?}))
5820 (progn
5821 (add-text-properties
5822 (match-beginning 3) (1+ (match-beginning 3))
5823 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
5824 (add-text-properties
5825 (1- (match-end 3)) (match-end 3)
5826 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
5827 t)))))
5829 ;;;; Visibility cycling, including org-goto and indirect buffer
5831 ;;; Cycling
5833 (defvar org-cycle-global-status nil)
5834 (make-variable-buffer-local 'org-cycle-global-status)
5835 (defvar org-cycle-subtree-status nil)
5836 (make-variable-buffer-local 'org-cycle-subtree-status)
5838 ;;;###autoload
5840 (defvar org-inlinetask-min-level)
5842 (defun org-cycle (&optional arg)
5843 "TAB-action and visibility cycling for Org-mode.
5845 This is the command invoked in Org-mode by the TAB key. Its main purpose
5846 is outline visibility cycling, but it also invokes other actions
5847 in special contexts.
5849 - When this function is called with a prefix argument, rotate the entire
5850 buffer through 3 states (global cycling)
5851 1. OVERVIEW: Show only top-level headlines.
5852 2. CONTENTS: Show all headlines of all levels, but no body text.
5853 3. SHOW ALL: Show everything.
5854 When called with two `C-u C-u' prefixes, switch to the startup visibility,
5855 determined by the variable `org-startup-folded', and by any VISIBILITY
5856 properties in the buffer.
5857 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
5858 including any drawers.
5860 - When inside a table, re-align the table and move to the next field.
5862 - When point is at the beginning of a headline, rotate the subtree started
5863 by this line through 3 different states (local cycling)
5864 1. FOLDED: Only the main headline is shown.
5865 2. CHILDREN: The main headline and the direct children are shown.
5866 From this state, you can move to one of the children
5867 and zoom in further.
5868 3. SUBTREE: Show the entire subtree, including body text.
5869 If there is no subtree, switch directly from CHILDREN to FOLDED.
5871 - When point is at the beginning of an empty headline and the variable
5872 `org-cycle-level-after-item/entry-creation' is set, cycle the level
5873 of the headline by demoting and promoting it to likely levels. This
5874 speeds up creation document structure by pressing TAB once or several
5875 times right after creating a new headline.
5877 - When there is a numeric prefix, go up to a heading with level ARG, do
5878 a `show-subtree' and return to the previous cursor position. If ARG
5879 is negative, go up that many levels.
5881 - When point is not at the beginning of a headline, execute the global
5882 binding for TAB, which is re-indenting the line. See the option
5883 `org-cycle-emulate-tab' for details.
5885 - Special case: if point is at the beginning of the buffer and there is
5886 no headline in line 1, this function will act as if called with prefix arg
5887 (C-u TAB, same as S-TAB) also when called without prefix arg.
5888 But only if also the variable `org-cycle-global-at-bob' is t."
5889 (interactive "P")
5890 (org-load-modules-maybe)
5891 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
5892 (and org-cycle-level-after-item/entry-creation
5893 (or (org-cycle-level)
5894 (org-cycle-item-indentation))))
5895 (let* ((limit-level
5896 (or org-cycle-max-level
5897 (and (boundp 'org-inlinetask-min-level)
5898 org-inlinetask-min-level
5899 (1- org-inlinetask-min-level))))
5900 (nstars (and limit-level
5901 (if org-odd-levels-only
5902 (and limit-level (1- (* limit-level 2)))
5903 limit-level)))
5904 (outline-regexp
5905 (if (not (org-mode-p))
5906 outline-regexp
5907 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
5908 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
5909 (not (looking-at outline-regexp))))
5910 (org-cycle-hook
5911 (if bob-special
5912 (delq 'org-optimize-window-after-visibility-change
5913 (copy-sequence org-cycle-hook))
5914 org-cycle-hook))
5915 (pos (point)))
5917 (if (or bob-special (equal arg '(4)))
5918 ;; special case: use global cycling
5919 (setq arg t))
5921 (cond
5923 ((equal arg '(16))
5924 (setq last-command 'dummy)
5925 (org-set-startup-visibility)
5926 (message "Startup visibility, plus VISIBILITY properties"))
5928 ((equal arg '(64))
5929 (show-all)
5930 (message "Entire buffer visible, including drawers"))
5932 ;; Table: enter it or move to the next field.
5933 ((org-at-table-p 'any)
5934 (if (org-at-table.el-p)
5935 (message "Use C-c ' to edit table.el tables")
5936 (if arg (org-table-edit-field t)
5937 (org-table-justify-field-maybe)
5938 (call-interactively 'org-table-next-field))))
5940 ((run-hook-with-args-until-success
5941 'org-tab-after-check-for-table-hook))
5943 ;; Global cycling: delegate to `org-cycle-internal-global'.
5944 ((eq arg t) (org-cycle-internal-global))
5946 ;; Drawers: delegate to `org-flag-drawer'.
5947 ((and org-drawers org-drawer-regexp
5948 (save-excursion
5949 (beginning-of-line 1)
5950 (looking-at org-drawer-regexp)))
5951 (org-flag-drawer ; toggle block visibility
5952 (not (get-char-property (match-end 0) 'invisible))))
5954 ;; Show-subtree, ARG levels up from here.
5955 ((integerp arg)
5956 (save-excursion
5957 (org-back-to-heading)
5958 (outline-up-heading (if (< arg 0) (- arg)
5959 (- (funcall outline-level) arg)))
5960 (org-show-subtree)))
5962 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
5963 ((and (featurep 'org-inlinetask)
5964 (org-inlinetask-at-task-p)
5965 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
5966 (org-inlinetask-toggle-visibility))
5968 ;; At an item/headline: delegate to `org-cycle-internal-local'.
5969 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
5970 (save-excursion (beginning-of-line 1)
5971 (looking-at outline-regexp)))
5972 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
5973 (org-cycle-internal-local))
5975 ;; From there: TAB emulation and template completion.
5976 (buffer-read-only (org-back-to-heading))
5978 ((run-hook-with-args-until-success
5979 'org-tab-after-check-for-cycling-hook))
5981 ((org-try-structure-completion))
5983 ((org-try-cdlatex-tab))
5985 ((run-hook-with-args-until-success
5986 'org-tab-before-tab-emulation-hook))
5988 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
5989 (or (not (bolp))
5990 (not (looking-at outline-regexp))))
5991 (call-interactively (global-key-binding "\t")))
5993 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
5994 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
5995 (or (and (eq org-cycle-emulate-tab 'white)
5996 (= (match-end 0) (point-at-eol)))
5997 (and (eq org-cycle-emulate-tab 'whitestart)
5998 (>= (match-end 0) pos))))
6000 (eq org-cycle-emulate-tab t))
6001 (call-interactively (global-key-binding "\t")))
6003 (t (save-excursion
6004 (org-back-to-heading)
6005 (org-cycle)))))))
6007 (defun org-cycle-internal-global ()
6008 "Do the global cycling action."
6009 (cond
6010 ((and (eq last-command this-command)
6011 (eq org-cycle-global-status 'overview))
6012 ;; We just created the overview - now do table of contents
6013 ;; This can be slow in very large buffers, so indicate action
6014 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6015 (message "CONTENTS...")
6016 (org-content)
6017 (message "CONTENTS...done")
6018 (setq org-cycle-global-status 'contents)
6019 (run-hook-with-args 'org-cycle-hook 'contents))
6021 ((and (eq last-command this-command)
6022 (eq org-cycle-global-status 'contents))
6023 ;; We just showed the table of contents - now show everything
6024 (run-hook-with-args 'org-pre-cycle-hook 'all)
6025 (show-all)
6026 (message "SHOW ALL")
6027 (setq org-cycle-global-status 'all)
6028 (run-hook-with-args 'org-cycle-hook 'all))
6031 ;; Default action: go to overview
6032 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6033 (org-overview)
6034 (message "OVERVIEW")
6035 (setq org-cycle-global-status 'overview)
6036 (run-hook-with-args 'org-cycle-hook 'overview))))
6038 (defun org-cycle-internal-local ()
6039 "Do the local cycling action."
6040 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6041 ;; First, determine end of headline (EOH), end of subtree or item
6042 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6043 (save-excursion
6044 (if (org-at-item-p)
6045 (progn
6046 (beginning-of-line)
6047 (setq struct (org-list-struct))
6048 (setq eoh (point-at-eol))
6049 (setq eos (org-list-get-item-end-before-blank (point) struct))
6050 (setq has-children (org-list-has-child-p (point) struct)))
6051 (org-back-to-heading)
6052 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6053 (setq eos (save-excursion
6054 (org-end-of-subtree t)
6055 (unless (eobp)
6056 (skip-chars-forward " \t\n"))
6057 (if (eobp) (point) (1- (point)))))
6058 (setq has-children
6059 (or (save-excursion
6060 (let ((level (funcall outline-level)))
6061 (outline-next-heading)
6062 (and (org-at-heading-p t)
6063 (> (funcall outline-level) level))))
6064 (save-excursion
6065 (org-list-search-forward (org-item-beginning-re) eos t)))))
6066 ;; Determine end invisible part of buffer (EOL)
6067 (beginning-of-line 2)
6068 ;; XEmacs doesn't have `next-single-char-property-change'
6069 (if (featurep 'xemacs)
6070 (while (and (not (eobp)) ;; this is like `next-line'
6071 (get-char-property (1- (point)) 'invisible))
6072 (beginning-of-line 2))
6073 (while (and (not (eobp)) ;; this is like `next-line'
6074 (get-char-property (1- (point)) 'invisible))
6075 (goto-char (next-single-char-property-change (point) 'invisible))
6076 (and (eolp) (beginning-of-line 2))))
6077 (setq eol (point)))
6078 ;; Find out what to do next and set `this-command'
6079 (cond
6080 ((= eos eoh)
6081 ;; Nothing is hidden behind this heading
6082 (run-hook-with-args 'org-pre-cycle-hook 'empty)
6083 (message "EMPTY ENTRY")
6084 (setq org-cycle-subtree-status nil)
6085 (save-excursion
6086 (goto-char eos)
6087 (outline-next-heading)
6088 (if (outline-invisible-p) (org-flag-heading nil))))
6089 ((and (or (>= eol eos)
6090 (not (string-match "\\S-" (buffer-substring eol eos))))
6091 (or has-children
6092 (not (setq children-skipped
6093 org-cycle-skip-children-state-if-no-children))))
6094 ;; Entire subtree is hidden in one line: children view
6095 (run-hook-with-args 'org-pre-cycle-hook 'children)
6096 (if (org-at-item-p)
6097 (org-list-set-item-visibility (point-at-bol) struct 'children)
6098 (org-show-entry)
6099 (show-children)
6100 ;; Fold every list in subtree to top-level items.
6101 (when (eq org-cycle-include-plain-lists 'integrate)
6102 (save-excursion
6103 (org-back-to-heading)
6104 (while (org-list-search-forward (org-item-beginning-re) eos t)
6105 (beginning-of-line 1)
6106 (let* ((struct (org-list-struct))
6107 (prevs (org-list-prevs-alist struct))
6108 (end (org-list-get-bottom-point struct)))
6109 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6110 (org-list-get-all-items (point) struct prevs))
6111 (goto-char end))))))
6112 (message "CHILDREN")
6113 (save-excursion
6114 (goto-char eos)
6115 (outline-next-heading)
6116 (if (outline-invisible-p) (org-flag-heading nil)))
6117 (setq org-cycle-subtree-status 'children)
6118 (run-hook-with-args 'org-cycle-hook 'children))
6119 ((or children-skipped
6120 (and (eq last-command this-command)
6121 (eq org-cycle-subtree-status 'children)))
6122 ;; We just showed the children, or no children are there,
6123 ;; now show everything.
6124 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
6125 (outline-flag-region eoh eos nil)
6126 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6127 (setq org-cycle-subtree-status 'subtree)
6128 (run-hook-with-args 'org-cycle-hook 'subtree))
6130 ;; Default action: hide the subtree.
6131 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6132 (outline-flag-region eoh eos t)
6133 (message "FOLDED")
6134 (setq org-cycle-subtree-status 'folded)
6135 (run-hook-with-args 'org-cycle-hook 'folded)))))
6137 ;;;###autoload
6138 (defun org-global-cycle (&optional arg)
6139 "Cycle the global visibility. For details see `org-cycle'.
6140 With \\[universal-argument] prefix arg, switch to startup visibility.
6141 With a numeric prefix, show all headlines up to that level."
6142 (interactive "P")
6143 (let ((org-cycle-include-plain-lists
6144 (if (org-mode-p) org-cycle-include-plain-lists nil)))
6145 (cond
6146 ((integerp arg)
6147 (show-all)
6148 (hide-sublevels arg)
6149 (setq org-cycle-global-status 'contents))
6150 ((equal arg '(4))
6151 (org-set-startup-visibility)
6152 (message "Startup visibility, plus VISIBILITY properties."))
6154 (org-cycle '(4))))))
6156 (defun org-set-startup-visibility ()
6157 "Set the visibility required by startup options and properties."
6158 (cond
6159 ((eq org-startup-folded t)
6160 (org-cycle '(4)))
6161 ((eq org-startup-folded 'content)
6162 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6163 (org-cycle '(4)) (org-cycle '(4)))))
6164 (unless (eq org-startup-folded 'showeverything)
6165 (if org-hide-block-startup (org-hide-block-all))
6166 (org-set-visibility-according-to-property 'no-cleanup)
6167 (org-cycle-hide-archived-subtrees 'all)
6168 (org-cycle-hide-drawers 'all)
6169 (org-cycle-show-empty-lines t)))
6171 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6172 "Switch subtree visibilities according to :VISIBILITY: property."
6173 (interactive)
6174 (let (org-show-entry-below state)
6175 (save-excursion
6176 (goto-char (point-min))
6177 (while (re-search-forward
6178 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6179 nil t)
6180 (setq state (match-string 1))
6181 (save-excursion
6182 (org-back-to-heading t)
6183 (hide-subtree)
6184 (org-reveal)
6185 (cond
6186 ((equal state '("fold" "folded"))
6187 (hide-subtree))
6188 ((equal state "children")
6189 (org-show-hidden-entry)
6190 (show-children))
6191 ((equal state "content")
6192 (save-excursion
6193 (save-restriction
6194 (org-narrow-to-subtree)
6195 (org-content))))
6196 ((member state '("all" "showall"))
6197 (show-subtree)))))
6198 (unless no-cleanup
6199 (org-cycle-hide-archived-subtrees 'all)
6200 (org-cycle-hide-drawers 'all)
6201 (org-cycle-show-empty-lines 'all)))))
6203 (defun org-overview ()
6204 "Switch to overview mode, showing only top-level headlines.
6205 Really, this shows all headlines with level equal or greater than the level
6206 of the first headline in the buffer. This is important, because if the
6207 first headline is not level one, then (hide-sublevels 1) gives confusing
6208 results."
6209 (interactive)
6210 (let ((level (save-excursion
6211 (goto-char (point-min))
6212 (if (re-search-forward (concat "^" outline-regexp) nil t)
6213 (progn
6214 (goto-char (match-beginning 0))
6215 (funcall outline-level))))))
6216 (and level (hide-sublevels level))))
6218 (defun org-content (&optional arg)
6219 "Show all headlines in the buffer, like a table of contents.
6220 With numerical argument N, show content up to level N."
6221 (interactive "P")
6222 (save-excursion
6223 ;; Visit all headings and show their offspring
6224 (and (integerp arg) (org-overview))
6225 (goto-char (point-max))
6226 (catch 'exit
6227 (while (and (progn (condition-case nil
6228 (outline-previous-visible-heading 1)
6229 (error (goto-char (point-min))))
6231 (looking-at outline-regexp))
6232 (if (integerp arg)
6233 (show-children (1- arg))
6234 (show-branches))
6235 (if (bobp) (throw 'exit nil))))))
6238 (defun org-optimize-window-after-visibility-change (state)
6239 "Adjust the window after a change in outline visibility.
6240 This function is the default value of the hook `org-cycle-hook'."
6241 (when (get-buffer-window (current-buffer))
6242 (cond
6243 ((eq state 'content) nil)
6244 ((eq state 'all) nil)
6245 ((eq state 'folded) nil)
6246 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6247 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6249 (defun org-remove-empty-overlays-at (pos)
6250 "Remove outline overlays that do not contain non-white stuff."
6251 (mapc
6252 (lambda (o)
6253 (and (eq 'outline (overlay-get o 'invisible))
6254 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6255 (overlay-end o))))
6256 (delete-overlay o)))
6257 (overlays-at pos)))
6259 (defun org-clean-visibility-after-subtree-move ()
6260 "Fix visibility issues after moving a subtree."
6261 ;; First, find a reasonable region to look at:
6262 ;; Start two siblings above, end three below
6263 (let* ((beg (save-excursion
6264 (and (org-get-last-sibling)
6265 (org-get-last-sibling))
6266 (point)))
6267 (end (save-excursion
6268 (and (org-get-next-sibling)
6269 (org-get-next-sibling)
6270 (org-get-next-sibling))
6271 (if (org-at-heading-p)
6272 (point-at-eol)
6273 (point))))
6274 (level (looking-at "\\*+"))
6275 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6276 (save-excursion
6277 (save-restriction
6278 (narrow-to-region beg end)
6279 (when re
6280 ;; Properly fold already folded siblings
6281 (goto-char (point-min))
6282 (while (re-search-forward re nil t)
6283 (if (and (not (outline-invisible-p))
6284 (save-excursion
6285 (goto-char (point-at-eol)) (outline-invisible-p)))
6286 (hide-entry))))
6287 (org-cycle-show-empty-lines 'overview)
6288 (org-cycle-hide-drawers 'overview)))))
6290 (defun org-cycle-show-empty-lines (state)
6291 "Show empty lines above all visible headlines.
6292 The region to be covered depends on STATE when called through
6293 `org-cycle-hook'. Lisp program can use t for STATE to get the
6294 entire buffer covered. Note that an empty line is only shown if there
6295 are at least `org-cycle-separator-lines' empty lines before the headline."
6296 (when (not (= org-cycle-separator-lines 0))
6297 (save-excursion
6298 (let* ((n (abs org-cycle-separator-lines))
6299 (re (cond
6300 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6301 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6302 (t (let ((ns (number-to-string (- n 2))))
6303 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6304 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6305 beg end b e)
6306 (cond
6307 ((memq state '(overview contents t))
6308 (setq beg (point-min) end (point-max)))
6309 ((memq state '(children folded))
6310 (setq beg (point) end (progn (org-end-of-subtree t t)
6311 (beginning-of-line 2)
6312 (point)))))
6313 (when beg
6314 (goto-char beg)
6315 (while (re-search-forward re end t)
6316 (unless (get-char-property (match-end 1) 'invisible)
6317 (setq e (match-end 1))
6318 (if (< org-cycle-separator-lines 0)
6319 (setq b (save-excursion
6320 (goto-char (match-beginning 0))
6321 (org-back-over-empty-lines)
6322 (if (save-excursion
6323 (goto-char (max (point-min) (1- (point))))
6324 (org-on-heading-p))
6325 (1- (point))
6326 (point))))
6327 (setq b (match-beginning 1)))
6328 (outline-flag-region b e nil)))))))
6329 ;; Never hide empty lines at the end of the file.
6330 (save-excursion
6331 (goto-char (point-max))
6332 (outline-previous-heading)
6333 (outline-end-of-heading)
6334 (if (and (looking-at "[ \t\n]+")
6335 (= (match-end 0) (point-max)))
6336 (outline-flag-region (point) (match-end 0) nil))))
6338 (defun org-show-empty-lines-in-parent ()
6339 "Move to the parent and re-show empty lines before visible headlines."
6340 (save-excursion
6341 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6342 (org-cycle-show-empty-lines context))))
6344 (defun org-files-list ()
6345 "Return `org-agenda-files' list, plus all open org-mode files.
6346 This is useful for operations that need to scan all of a user's
6347 open and agenda-wise Org files."
6348 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6349 (dolist (buf (buffer-list))
6350 (with-current-buffer buf
6351 (if (and (org-mode-p) (buffer-file-name))
6352 (let ((file (expand-file-name (buffer-file-name))))
6353 (unless (member file files)
6354 (push file files))))))
6355 files))
6357 (defsubst org-entry-beginning-position ()
6358 "Return the beginning position of the current entry."
6359 (save-excursion (outline-back-to-heading t) (point)))
6361 (defsubst org-entry-end-position ()
6362 "Return the end position of the current entry."
6363 (save-excursion (outline-next-heading) (point)))
6365 (defun org-cycle-hide-drawers (state)
6366 "Re-hide all drawers after a visibility state change."
6367 (when (and (org-mode-p)
6368 (not (memq state '(overview folded contents))))
6369 (save-excursion
6370 (let* ((globalp (memq state '(contents all)))
6371 (beg (if globalp (point-min) (point)))
6372 (end (if globalp (point-max)
6373 (if (eq state 'children)
6374 (save-excursion (outline-next-heading) (point))
6375 (org-end-of-subtree t)))))
6376 (goto-char beg)
6377 (while (re-search-forward org-drawer-regexp end t)
6378 (org-flag-drawer t))))))
6380 (defun org-flag-drawer (flag)
6381 (save-excursion
6382 (beginning-of-line 1)
6383 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6384 (let ((b (match-end 0))
6385 (outline-regexp org-outline-regexp))
6386 (if (re-search-forward
6387 "^[ \t]*:END:"
6388 (save-excursion (outline-next-heading) (point)) t)
6389 (outline-flag-region b (point-at-eol) flag)
6390 (error ":END: line missing at position %s" b))))))
6392 (defun org-subtree-end-visible-p ()
6393 "Is the end of the current subtree visible?"
6394 (pos-visible-in-window-p
6395 (save-excursion (org-end-of-subtree t) (point))))
6397 (defun org-first-headline-recenter (&optional N)
6398 "Move cursor to the first headline and recenter the headline.
6399 Optional argument N means put the headline into the Nth line of the window."
6400 (goto-char (point-min))
6401 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
6402 (beginning-of-line)
6403 (recenter (prefix-numeric-value N))))
6405 ;;; Saving and restoring visibility
6407 (defun org-outline-overlay-data (&optional use-markers)
6408 "Return a list of the locations of all outline overlays.
6409 These are overlays with the `invisible' property value `outline'.
6410 The return value is a list of cons cells, with start and stop
6411 positions for each overlay.
6412 If USE-MARKERS is set, return the positions as markers."
6413 (let (beg end)
6414 (save-excursion
6415 (save-restriction
6416 (widen)
6417 (delq nil
6418 (mapcar (lambda (o)
6419 (when (eq (overlay-get o 'invisible) 'outline)
6420 (setq beg (overlay-start o)
6421 end (overlay-end o))
6422 (and beg end (> end beg)
6423 (if use-markers
6424 (cons (move-marker (make-marker) beg)
6425 (move-marker (make-marker) end))
6426 (cons beg end)))))
6427 (overlays-in (point-min) (point-max))))))))
6429 (defun org-set-outline-overlay-data (data)
6430 "Create visibility overlays for all positions in DATA.
6431 DATA should have been made by `org-outline-overlay-data'."
6432 (let (o)
6433 (save-excursion
6434 (save-restriction
6435 (widen)
6436 (show-all)
6437 (mapc (lambda (c)
6438 (setq o (make-overlay (car c) (cdr c)))
6439 (overlay-put o 'invisible 'outline))
6440 data)))))
6442 ;;; Folding of blocks
6444 (defconst org-block-regexp
6445 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
6446 "Regular expression for hiding blocks.")
6448 (defvar org-hide-block-overlays nil
6449 "Overlays hiding blocks.")
6450 (make-variable-buffer-local 'org-hide-block-overlays)
6452 (defun org-block-map (function &optional start end)
6453 "Call FUNCTION at the head of all source blocks in the current buffer.
6454 Optional arguments START and END can be used to limit the range."
6455 (let ((start (or start (point-min)))
6456 (end (or end (point-max))))
6457 (save-excursion
6458 (goto-char start)
6459 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
6460 (save-excursion
6461 (save-match-data
6462 (goto-char (match-beginning 0))
6463 (funcall function)))))))
6465 (defun org-hide-block-toggle-all ()
6466 "Toggle the visibility of all blocks in the current buffer."
6467 (org-block-map #'org-hide-block-toggle))
6469 (defun org-hide-block-all ()
6470 "Fold all blocks in the current buffer."
6471 (interactive)
6472 (org-show-block-all)
6473 (org-block-map #'org-hide-block-toggle-maybe))
6475 (defun org-show-block-all ()
6476 "Unfold all blocks in the current buffer."
6477 (interactive)
6478 (mapc 'delete-overlay org-hide-block-overlays)
6479 (setq org-hide-block-overlays nil))
6481 (defun org-hide-block-toggle-maybe ()
6482 "Toggle visibility of block at point."
6483 (interactive)
6484 (let ((case-fold-search t))
6485 (if (save-excursion
6486 (beginning-of-line 1)
6487 (looking-at org-block-regexp))
6488 (progn (org-hide-block-toggle)
6489 t) ;; to signal that we took action
6490 nil))) ;; to signal that we did not
6492 (defun org-hide-block-toggle (&optional force)
6493 "Toggle the visibility of the current block."
6494 (interactive)
6495 (save-excursion
6496 (beginning-of-line)
6497 (if (re-search-forward org-block-regexp nil t)
6498 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
6499 (end (match-end 0)) ;; end of entire body
6501 (if (memq t (mapcar (lambda (overlay)
6502 (eq (overlay-get overlay 'invisible)
6503 'org-hide-block))
6504 (overlays-at start)))
6505 (if (or (not force) (eq force 'off))
6506 (mapc (lambda (ov)
6507 (when (member ov org-hide-block-overlays)
6508 (setq org-hide-block-overlays
6509 (delq ov org-hide-block-overlays)))
6510 (when (eq (overlay-get ov 'invisible)
6511 'org-hide-block)
6512 (delete-overlay ov)))
6513 (overlays-at start)))
6514 (setq ov (make-overlay start end))
6515 (overlay-put ov 'invisible 'org-hide-block)
6516 ;; make the block accessible to isearch
6517 (overlay-put
6518 ov 'isearch-open-invisible
6519 (lambda (ov)
6520 (when (member ov org-hide-block-overlays)
6521 (setq org-hide-block-overlays
6522 (delq ov org-hide-block-overlays)))
6523 (when (eq (overlay-get ov 'invisible)
6524 'org-hide-block)
6525 (delete-overlay ov))))
6526 (push ov org-hide-block-overlays)))
6527 (error "Not looking at a source block"))))
6529 ;; org-tab-after-check-for-cycling-hook
6530 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
6531 ;; Remove overlays when changing major mode
6532 (add-hook 'org-mode-hook
6533 (lambda () (org-add-hook 'change-major-mode-hook
6534 'org-show-block-all 'append 'local)))
6536 ;;; Org-goto
6538 (defvar org-goto-window-configuration nil)
6539 (defvar org-goto-marker nil)
6540 (defvar org-goto-map
6541 (let ((map (make-sparse-keymap)))
6542 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
6543 (while (setq cmd (pop cmds))
6544 (substitute-key-definition cmd cmd map global-map)))
6545 (suppress-keymap map)
6546 (org-defkey map "\C-m" 'org-goto-ret)
6547 (org-defkey map [(return)] 'org-goto-ret)
6548 (org-defkey map [(left)] 'org-goto-left)
6549 (org-defkey map [(right)] 'org-goto-right)
6550 (org-defkey map [(control ?g)] 'org-goto-quit)
6551 (org-defkey map "\C-i" 'org-cycle)
6552 (org-defkey map [(tab)] 'org-cycle)
6553 (org-defkey map [(down)] 'outline-next-visible-heading)
6554 (org-defkey map [(up)] 'outline-previous-visible-heading)
6555 (if org-goto-auto-isearch
6556 (if (fboundp 'define-key-after)
6557 (define-key-after map [t] 'org-goto-local-auto-isearch)
6558 nil)
6559 (org-defkey map "q" 'org-goto-quit)
6560 (org-defkey map "n" 'outline-next-visible-heading)
6561 (org-defkey map "p" 'outline-previous-visible-heading)
6562 (org-defkey map "f" 'outline-forward-same-level)
6563 (org-defkey map "b" 'outline-backward-same-level)
6564 (org-defkey map "u" 'outline-up-heading))
6565 (org-defkey map "/" 'org-occur)
6566 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
6567 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
6568 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
6569 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
6570 (org-defkey map "\C-c\C-u" 'outline-up-heading)
6571 map))
6573 (defconst org-goto-help
6574 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
6575 RET=jump to location [Q]uit and return to previous location
6576 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
6578 (defvar org-goto-start-pos) ; dynamically scoped parameter
6580 ;; FIXME: Docstring does not mention both interfaces
6581 (defun org-goto (&optional alternative-interface)
6582 "Look up a different location in the current file, keeping current visibility.
6584 When you want look-up or go to a different location in a document, the
6585 fastest way is often to fold the entire buffer and then dive into the tree.
6586 This method has the disadvantage, that the previous location will be folded,
6587 which may not be what you want.
6589 This command works around this by showing a copy of the current buffer
6590 in an indirect buffer, in overview mode. You can dive into the tree in
6591 that copy, use org-occur and incremental search to find a location.
6592 When pressing RET or `Q', the command returns to the original buffer in
6593 which the visibility is still unchanged. After RET is will also jump to
6594 the location selected in the indirect buffer and expose the headline
6595 hierarchy above."
6596 (interactive "P")
6597 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
6598 (org-refile-use-outline-path t)
6599 (org-refile-target-verify-function nil)
6600 (interface
6601 (if (not alternative-interface)
6602 org-goto-interface
6603 (if (eq org-goto-interface 'outline)
6604 'outline-path-completion
6605 'outline)))
6606 (org-goto-start-pos (point))
6607 (selected-point
6608 (if (eq interface 'outline)
6609 (car (org-get-location (current-buffer) org-goto-help))
6610 (let ((pa (org-refile-get-location "Goto")))
6611 (org-refile-check-position pa)
6612 (nth 3 pa)))))
6613 (if selected-point
6614 (progn
6615 (org-mark-ring-push org-goto-start-pos)
6616 (goto-char selected-point)
6617 (if (or (outline-invisible-p) (org-invisible-p2))
6618 (org-show-context 'org-goto)))
6619 (message "Quit"))))
6621 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
6622 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
6623 (defvar org-goto-local-auto-isearch-map) ; defined below
6625 (defun org-get-location (buf help)
6626 "Let the user select a location in the Org-mode buffer BUF.
6627 This function uses a recursive edit. It returns the selected position
6628 or nil."
6629 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
6630 (isearch-hide-immediately nil)
6631 (isearch-search-fun-function
6632 (lambda () 'org-goto-local-search-headings))
6633 (org-goto-selected-point org-goto-exit-command)
6634 (pop-up-frames nil)
6635 (special-display-buffer-names nil)
6636 (special-display-regexps nil)
6637 (special-display-function nil))
6638 (save-excursion
6639 (save-window-excursion
6640 (delete-other-windows)
6641 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
6642 (switch-to-buffer
6643 (condition-case nil
6644 (make-indirect-buffer (current-buffer) "*org-goto*")
6645 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
6646 (with-output-to-temp-buffer "*Help*"
6647 (princ help))
6648 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
6649 (setq buffer-read-only nil)
6650 (let ((org-startup-truncated t)
6651 (org-startup-folded nil)
6652 (org-startup-align-all-tables nil))
6653 (org-mode)
6654 (org-overview))
6655 (setq buffer-read-only t)
6656 (if (and (boundp 'org-goto-start-pos)
6657 (integer-or-marker-p org-goto-start-pos))
6658 (let ((org-show-hierarchy-above t)
6659 (org-show-siblings t)
6660 (org-show-following-heading t))
6661 (goto-char org-goto-start-pos)
6662 (and (outline-invisible-p) (org-show-context)))
6663 (goto-char (point-min)))
6664 (let (org-special-ctrl-a/e) (org-beginning-of-line))
6665 (message "Select location and press RET")
6666 (use-local-map org-goto-map)
6667 (recursive-edit)
6669 (kill-buffer "*org-goto*")
6670 (cons org-goto-selected-point org-goto-exit-command)))
6672 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
6673 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
6674 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
6675 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
6677 (defun org-goto-local-search-headings (string bound noerror)
6678 "Search and make sure that any matches are in headlines."
6679 (catch 'return
6680 (while (if isearch-forward
6681 (search-forward string bound noerror)
6682 (search-backward string bound noerror))
6683 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
6684 (and (member :headline context)
6685 (not (member :tags context))))
6686 (throw 'return (point))))))
6688 (defun org-goto-local-auto-isearch ()
6689 "Start isearch."
6690 (interactive)
6691 (goto-char (point-min))
6692 (let ((keys (this-command-keys)))
6693 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
6694 (isearch-mode t)
6695 (isearch-process-search-char (string-to-char keys)))))
6697 (defun org-goto-ret (&optional arg)
6698 "Finish `org-goto' by going to the new location."
6699 (interactive "P")
6700 (setq org-goto-selected-point (point)
6701 org-goto-exit-command 'return)
6702 (throw 'exit nil))
6704 (defun org-goto-left ()
6705 "Finish `org-goto' by going to the new location."
6706 (interactive)
6707 (if (org-on-heading-p)
6708 (progn
6709 (beginning-of-line 1)
6710 (setq org-goto-selected-point (point)
6711 org-goto-exit-command 'left)
6712 (throw 'exit nil))
6713 (error "Not on a heading")))
6715 (defun org-goto-right ()
6716 "Finish `org-goto' by going to the new location."
6717 (interactive)
6718 (if (org-on-heading-p)
6719 (progn
6720 (setq org-goto-selected-point (point)
6721 org-goto-exit-command 'right)
6722 (throw 'exit nil))
6723 (error "Not on a heading")))
6725 (defun org-goto-quit ()
6726 "Finish `org-goto' without cursor motion."
6727 (interactive)
6728 (setq org-goto-selected-point nil)
6729 (setq org-goto-exit-command 'quit)
6730 (throw 'exit nil))
6732 ;;; Indirect buffer display of subtrees
6734 (defvar org-indirect-dedicated-frame nil
6735 "This is the frame being used for indirect tree display.")
6736 (defvar org-last-indirect-buffer nil)
6738 (defun org-tree-to-indirect-buffer (&optional arg)
6739 "Create indirect buffer and narrow it to current subtree.
6740 With numerical prefix ARG, go up to this level and then take that tree.
6741 If ARG is negative, go up that many levels.
6742 If `org-indirect-buffer-display' is not `new-frame', the command removes the
6743 indirect buffer previously made with this command, to avoid proliferation of
6744 indirect buffers. However, when you call the command with a \
6745 \\[universal-argument] prefix, or
6746 when `org-indirect-buffer-display' is `new-frame', the last buffer
6747 is kept so that you can work with several indirect buffers at the same time.
6748 If `org-indirect-buffer-display' is `dedicated-frame', the \
6749 \\[universal-argument] prefix also
6750 requests that a new frame be made for the new buffer, so that the dedicated
6751 frame is not changed."
6752 (interactive "P")
6753 (let ((cbuf (current-buffer))
6754 (cwin (selected-window))
6755 (pos (point))
6756 beg end level heading ibuf)
6757 (save-excursion
6758 (org-back-to-heading t)
6759 (when (numberp arg)
6760 (setq level (org-outline-level))
6761 (if (< arg 0) (setq arg (+ level arg)))
6762 (while (> (setq level (org-outline-level)) arg)
6763 (outline-up-heading 1 t)))
6764 (setq beg (point)
6765 heading (org-get-heading))
6766 (org-end-of-subtree t t)
6767 (if (org-on-heading-p) (backward-char 1))
6768 (setq end (point)))
6769 (if (and (buffer-live-p org-last-indirect-buffer)
6770 (not (eq org-indirect-buffer-display 'new-frame))
6771 (not arg))
6772 (kill-buffer org-last-indirect-buffer))
6773 (setq ibuf (org-get-indirect-buffer cbuf)
6774 org-last-indirect-buffer ibuf)
6775 (cond
6776 ((or (eq org-indirect-buffer-display 'new-frame)
6777 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
6778 (select-frame (make-frame))
6779 (delete-other-windows)
6780 (switch-to-buffer ibuf)
6781 (org-set-frame-title heading))
6782 ((eq org-indirect-buffer-display 'dedicated-frame)
6783 (raise-frame
6784 (select-frame (or (and org-indirect-dedicated-frame
6785 (frame-live-p org-indirect-dedicated-frame)
6786 org-indirect-dedicated-frame)
6787 (setq org-indirect-dedicated-frame (make-frame)))))
6788 (delete-other-windows)
6789 (switch-to-buffer ibuf)
6790 (org-set-frame-title (concat "Indirect: " heading)))
6791 ((eq org-indirect-buffer-display 'current-window)
6792 (switch-to-buffer ibuf))
6793 ((eq org-indirect-buffer-display 'other-window)
6794 (pop-to-buffer ibuf))
6795 (t (error "Invalid value")))
6796 (if (featurep 'xemacs)
6797 (save-excursion (org-mode) (turn-on-font-lock)))
6798 (narrow-to-region beg end)
6799 (show-all)
6800 (goto-char pos)
6801 (and (window-live-p cwin) (select-window cwin))))
6803 (defun org-get-indirect-buffer (&optional buffer)
6804 (setq buffer (or buffer (current-buffer)))
6805 (let ((n 1) (base (buffer-name buffer)) bname)
6806 (while (buffer-live-p
6807 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
6808 (setq n (1+ n)))
6809 (condition-case nil
6810 (make-indirect-buffer buffer bname 'clone)
6811 (error (make-indirect-buffer buffer bname)))))
6813 (defun org-set-frame-title (title)
6814 "Set the title of the current frame to the string TITLE."
6815 ;; FIXME: how to name a single frame in XEmacs???
6816 (unless (featurep 'xemacs)
6817 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
6819 ;;;; Structure editing
6821 ;;; Inserting headlines
6823 (defun org-previous-line-empty-p ()
6824 (save-excursion
6825 (and (not (bobp))
6826 (or (beginning-of-line 0) t)
6827 (save-match-data
6828 (looking-at "[ \t]*$")))))
6830 (defun org-insert-heading (&optional force-heading invisible-ok)
6831 "Insert a new heading or item with same depth at point.
6832 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
6833 If point is at the beginning of a headline, insert a sibling before the
6834 current headline. If point is not at the beginning, split the line,
6835 create the new headline with the text in the current line after point
6836 \(but see also the variable `org-M-RET-may-split-line').
6838 When INVISIBLE-OK is set, stop at invisible headlines when going back.
6839 This is important for non-interactive uses of the command."
6840 (interactive "P")
6841 (if (or (= (buffer-size) 0)
6842 (and (not (save-excursion
6843 (and (ignore-errors (org-back-to-heading invisible-ok))
6844 (org-on-heading-p))))
6845 (not (org-in-item-p))))
6846 (progn
6847 (insert "\n* ")
6848 (run-hooks 'org-insert-heading-hook))
6849 (when (or force-heading (not (org-insert-item)))
6850 (let* ((empty-line-p nil)
6851 (level nil)
6852 (on-heading (org-on-heading-p))
6853 (head (save-excursion
6854 (condition-case nil
6855 (progn
6856 (org-back-to-heading invisible-ok)
6857 (when (and (not on-heading)
6858 (featurep 'org-inlinetask)
6859 (integerp org-inlinetask-min-level)
6860 (>= (length (match-string 0))
6861 org-inlinetask-min-level))
6862 ;; Find a heading level before the inline task
6863 (while (and (setq level (org-up-heading-safe))
6864 (>= level org-inlinetask-min-level)))
6865 (if (org-on-heading-p)
6866 (org-back-to-heading invisible-ok)
6867 (error "This should not happen")))
6868 (setq empty-line-p (org-previous-line-empty-p))
6869 (match-string 0))
6870 (error "*"))))
6871 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
6872 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
6873 pos hide-previous previous-pos)
6874 (cond
6875 ((and (org-on-heading-p) (bolp)
6876 (or (bobp)
6877 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
6878 ;; insert before the current line
6879 (open-line (if blank 2 1)))
6880 ((and (bolp)
6881 (not org-insert-heading-respect-content)
6882 (or (bobp)
6883 (save-excursion
6884 (backward-char 1) (not (outline-invisible-p)))))
6885 ;; insert right here
6886 nil)
6888 ;; somewhere in the line
6889 (save-excursion
6890 (setq previous-pos (point-at-bol))
6891 (end-of-line)
6892 (setq hide-previous (outline-invisible-p)))
6893 (and org-insert-heading-respect-content (org-show-subtree))
6894 (let ((split
6895 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
6896 (save-excursion
6897 (let ((p (point)))
6898 (goto-char (point-at-bol))
6899 (and (looking-at org-complex-heading-regexp)
6900 (> p (match-beginning 4)))))))
6901 tags pos)
6902 (cond
6903 (org-insert-heading-respect-content
6904 (org-end-of-subtree nil t)
6905 (when (featurep 'org-inlinetask)
6906 (while (and (not (eobp))
6907 (looking-at "\\(\\*+\\)[ \t]+")
6908 (>= (length (match-string 1))
6909 org-inlinetask-min-level))
6910 (org-end-of-subtree nil t)))
6911 (or (bolp) (newline))
6912 (or (org-previous-line-empty-p)
6913 (and blank (newline)))
6914 (open-line 1))
6915 ((org-on-heading-p)
6916 (when hide-previous
6917 (show-children)
6918 (org-show-entry))
6919 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
6920 (setq tags (and (match-end 2) (match-string 2)))
6921 (and (match-end 1)
6922 (delete-region (match-beginning 1) (match-end 1)))
6923 (setq pos (point-at-bol))
6924 (or split (end-of-line 1))
6925 (delete-horizontal-space)
6926 (if (string-match "\\`\\*+\\'"
6927 (buffer-substring (point-at-bol) (point)))
6928 (insert " "))
6929 (newline (if blank 2 1))
6930 (when tags
6931 (save-excursion
6932 (goto-char pos)
6933 (end-of-line 1)
6934 (insert " " tags)
6935 (org-set-tags nil 'align))))
6937 (or split (end-of-line 1))
6938 (newline (if blank 2 1)))))))
6939 (insert head) (just-one-space)
6940 (setq pos (point))
6941 (end-of-line 1)
6942 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
6943 (when (and org-insert-heading-respect-content hide-previous)
6944 (save-excursion
6945 (goto-char previous-pos)
6946 (hide-subtree)))
6947 (run-hooks 'org-insert-heading-hook)))))
6949 (defun org-get-heading (&optional no-tags)
6950 "Return the heading of the current entry, without the stars."
6951 (save-excursion
6952 (org-back-to-heading t)
6953 (if (looking-at
6954 (if no-tags
6955 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@#%]+:[ \t]*\\)?$")
6956 "\\*+[ \t]+\\([^\r\n]*\\)"))
6957 (match-string 1) "")))
6959 (defun org-heading-components ()
6960 "Return the components of the current heading.
6961 This is a list with the following elements:
6962 - the level as an integer
6963 - the reduced level, different if `org-odd-levels-only' is set.
6964 - the TODO keyword, or nil
6965 - the priority character, like ?A, or nil if no priority is given
6966 - the headline text itself, or the tags string if no headline text
6967 - the tags string, or nil."
6968 (save-excursion
6969 (org-back-to-heading t)
6970 (if (let (case-fold-search) (looking-at org-complex-heading-regexp))
6971 (list (length (match-string 1))
6972 (org-reduced-level (length (match-string 1)))
6973 (org-match-string-no-properties 2)
6974 (and (match-end 3) (aref (match-string 3) 2))
6975 (org-match-string-no-properties 4)
6976 (org-match-string-no-properties 5)))))
6978 (defun org-get-entry ()
6979 "Get the entry text, after heading, entire subtree."
6980 (save-excursion
6981 (org-back-to-heading t)
6982 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
6984 (defun org-insert-heading-after-current ()
6985 "Insert a new heading with same level as current, after current subtree."
6986 (interactive)
6987 (org-back-to-heading)
6988 (org-insert-heading)
6989 (org-move-subtree-down)
6990 (end-of-line 1))
6992 (defun org-insert-heading-respect-content ()
6993 (interactive)
6994 (let ((org-insert-heading-respect-content t))
6995 (org-insert-heading t)))
6997 (defun org-insert-todo-heading-respect-content (&optional force-state)
6998 (interactive "P")
6999 (let ((org-insert-heading-respect-content t))
7000 (org-insert-todo-heading force-state t)))
7002 (defun org-insert-todo-heading (arg &optional force-heading)
7003 "Insert a new heading with the same level and TODO state as current heading.
7004 If the heading has no TODO state, or if the state is DONE, use the first
7005 state (TODO by default). Also with prefix arg, force first state."
7006 (interactive "P")
7007 (when (or force-heading (not (org-insert-item 'checkbox)))
7008 (org-insert-heading force-heading)
7009 (save-excursion
7010 (org-back-to-heading)
7011 (outline-previous-heading)
7012 (looking-at org-todo-line-regexp))
7013 (let*
7014 ((new-mark-x
7015 (if (or arg
7016 (not (match-beginning 2))
7017 (member (match-string 2) org-done-keywords))
7018 (car org-todo-keywords-1)
7019 (match-string 2)))
7020 (new-mark
7022 (run-hook-with-args-until-success
7023 'org-todo-get-default-hook new-mark-x nil)
7024 new-mark-x)))
7025 (beginning-of-line 1)
7026 (and (looking-at "\\*+ ") (goto-char (match-end 0))
7027 (if org-treat-insert-todo-heading-as-state-change
7028 (org-todo new-mark)
7029 (insert new-mark " "))))
7030 (when org-provide-todo-statistics
7031 (org-update-parent-todo-statistics))))
7033 (defun org-insert-subheading (arg)
7034 "Insert a new subheading and demote it.
7035 Works for outline headings and for plain lists alike."
7036 (interactive "P")
7037 (org-insert-heading arg)
7038 (cond
7039 ((org-on-heading-p) (org-do-demote))
7040 ((org-at-item-p) (org-indent-item))))
7042 (defun org-insert-todo-subheading (arg)
7043 "Insert a new subheading with TODO keyword or checkbox and demote it.
7044 Works for outline headings and for plain lists alike."
7045 (interactive "P")
7046 (org-insert-todo-heading arg)
7047 (cond
7048 ((org-on-heading-p) (org-do-demote))
7049 ((org-at-item-p) (org-indent-item))))
7051 ;;; Promotion and Demotion
7053 (defvar org-after-demote-entry-hook nil
7054 "Hook run after an entry has been demoted.
7055 The cursor will be at the beginning of the entry.
7056 When a subtree is being demoted, the hook will be called for each node.")
7058 (defvar org-after-promote-entry-hook nil
7059 "Hook run after an entry has been promoted.
7060 The cursor will be at the beginning of the entry.
7061 When a subtree is being promoted, the hook will be called for each node.")
7063 (defun org-promote-subtree ()
7064 "Promote the entire subtree.
7065 See also `org-promote'."
7066 (interactive)
7067 (save-excursion
7068 (org-with-limited-levels (org-map-tree 'org-promote)))
7069 (org-fix-position-after-promote))
7071 (defun org-demote-subtree ()
7072 "Demote the entire subtree. See `org-demote'.
7073 See also `org-promote'."
7074 (interactive)
7075 (save-excursion
7076 (org-with-limited-levels (org-map-tree 'org-demote)))
7077 (org-fix-position-after-promote))
7080 (defun org-do-promote ()
7081 "Promote the current heading higher up the tree.
7082 If the region is active in `transient-mark-mode', promote all headings
7083 in the region."
7084 (interactive)
7085 (save-excursion
7086 (if (org-region-active-p)
7087 (org-map-region 'org-promote (region-beginning) (region-end))
7088 (org-promote)))
7089 (org-fix-position-after-promote))
7091 (defun org-do-demote ()
7092 "Demote the current heading lower down the tree.
7093 If the region is active in `transient-mark-mode', demote all headings
7094 in the region."
7095 (interactive)
7096 (save-excursion
7097 (if (org-region-active-p)
7098 (org-map-region 'org-demote (region-beginning) (region-end))
7099 (org-demote)))
7100 (org-fix-position-after-promote))
7102 (defun org-fix-position-after-promote ()
7103 "Make sure that after pro/demotion cursor position is right."
7104 (let ((pos (point)))
7105 (when (save-excursion
7106 (beginning-of-line 1)
7107 (looking-at org-todo-line-regexp)
7108 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7109 (cond ((eobp) (insert " "))
7110 ((eolp) (insert " "))
7111 ((equal (char-after) ?\ ) (forward-char 1))))))
7113 (defun org-current-level ()
7114 "Return the level of the current entry, or nil if before the first headline.
7115 The level is the number of stars at the beginning of the headline."
7116 (save-excursion
7117 (org-with-limited-levels
7118 (ignore-errors
7119 (org-back-to-heading t)
7120 (funcall outline-level)))))
7122 (defun org-get-previous-line-level ()
7123 "Return the outline depth of the last headline before the current line.
7124 Returns 0 for the first headline in the buffer, and nil if before the
7125 first headline."
7126 (let ((current-level (org-current-level))
7127 (prev-level (when (> (line-number-at-pos) 1)
7128 (save-excursion
7129 (beginning-of-line 0)
7130 (org-current-level)))))
7131 (cond ((null current-level) nil) ; Before first headline
7132 ((null prev-level) 0) ; At first headline
7133 (prev-level))))
7135 (defun org-reduced-level (l)
7136 "Compute the effective level of a heading.
7137 This takes into account the setting of `org-odd-levels-only'."
7138 (cond
7139 ((zerop l) 0)
7140 (org-odd-levels-only (1+ (floor (/ l 2))))
7141 (t l)))
7143 (defun org-level-increment ()
7144 "Return the number of stars that will be added or removed at a
7145 time to headlines when structure editing, based on the value of
7146 `org-odd-levels-only'."
7147 (if org-odd-levels-only 2 1))
7149 (defun org-get-valid-level (level &optional change)
7150 "Rectify a level change under the influence of `org-odd-levels-only'
7151 LEVEL is a current level, CHANGE is by how much the level should be
7152 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7153 even level numbers will become the next higher odd number."
7154 (if org-odd-levels-only
7155 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7156 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7157 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7158 (max 1 (+ level (or change 0)))))
7160 (if (boundp 'define-obsolete-function-alias)
7161 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7162 (define-obsolete-function-alias 'org-get-legal-level
7163 'org-get-valid-level)
7164 (define-obsolete-function-alias 'org-get-legal-level
7165 'org-get-valid-level "23.1")))
7167 (defun org-promote ()
7168 "Promote the current heading higher up the tree.
7169 If the region is active in `transient-mark-mode', promote all headings
7170 in the region."
7171 (org-back-to-heading t)
7172 (let* ((level (save-match-data (funcall outline-level)))
7173 (after-change-functions (remove 'flyspell-after-change-function
7174 after-change-functions))
7175 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7176 (diff (abs (- level (length up-head) -1))))
7177 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
7178 (replace-match up-head nil t)
7179 ;; Fixup tag positioning
7180 (and org-auto-align-tags (org-set-tags nil t))
7181 (if org-adapt-indentation (org-fixup-indentation (- diff)))
7182 (run-hooks 'org-after-promote-entry-hook)))
7184 (defun org-demote ()
7185 "Demote the current heading lower down the tree.
7186 If the region is active in `transient-mark-mode', demote all headings
7187 in the region."
7188 (org-back-to-heading t)
7189 (let* ((level (save-match-data (funcall outline-level)))
7190 (after-change-functions (remove 'flyspell-after-change-function
7191 after-change-functions))
7192 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7193 (diff (abs (- level (length down-head) -1))))
7194 (replace-match down-head nil t)
7195 ;; Fixup tag positioning
7196 (and org-auto-align-tags (org-set-tags nil t))
7197 (if org-adapt-indentation (org-fixup-indentation diff))
7198 (run-hooks 'org-after-demote-entry-hook)))
7200 (defun org-cycle-level ()
7201 "Cycle the level of an empty headline through possible states.
7202 This goes first to child, then to parent, level, then up the hierarchy.
7203 After top level, it switches back to sibling level."
7204 (interactive)
7205 (let ((org-adapt-indentation nil))
7206 (when (org-point-at-end-of-empty-headline)
7207 (setq this-command 'org-cycle-level) ; Only needed for caching
7208 (let ((cur-level (org-current-level))
7209 (prev-level (org-get-previous-line-level)))
7210 (cond
7211 ;; If first headline in file, promote to top-level.
7212 ((= prev-level 0)
7213 (loop repeat (/ (- cur-level 1) (org-level-increment))
7214 do (org-do-promote)))
7215 ;; If same level as prev, demote one.
7216 ((= prev-level cur-level)
7217 (org-do-demote))
7218 ;; If parent is top-level, promote to top level if not already.
7219 ((= prev-level 1)
7220 (loop repeat (/ (- cur-level 1) (org-level-increment))
7221 do (org-do-promote)))
7222 ;; If top-level, return to prev-level.
7223 ((= cur-level 1)
7224 (loop repeat (/ (- prev-level 1) (org-level-increment))
7225 do (org-do-demote)))
7226 ;; If less than prev-level, promote one.
7227 ((< cur-level prev-level)
7228 (org-do-promote))
7229 ;; If deeper than prev-level, promote until higher than
7230 ;; prev-level.
7231 ((> cur-level prev-level)
7232 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7233 do (org-do-promote))))
7234 t))))
7236 (defun org-map-tree (fun)
7237 "Call FUN for every heading underneath the current one."
7238 (org-back-to-heading)
7239 (let ((level (funcall outline-level)))
7240 (save-excursion
7241 (funcall fun)
7242 (while (and (progn
7243 (outline-next-heading)
7244 (> (funcall outline-level) level))
7245 (not (eobp)))
7246 (funcall fun)))))
7248 (defun org-map-region (fun beg end)
7249 "Call FUN for every heading between BEG and END."
7250 (let ((org-ignore-region t))
7251 (save-excursion
7252 (setq end (copy-marker end))
7253 (goto-char beg)
7254 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
7255 (< (point) end))
7256 (funcall fun))
7257 (while (and (progn
7258 (outline-next-heading)
7259 (< (point) end))
7260 (not (eobp)))
7261 (funcall fun)))))
7263 (defun org-fixup-indentation (diff)
7264 "Change the indentation in the current entry by DIFF.
7265 However, if any line in the current entry has no indentation, or if it
7266 would end up with no indentation after the change, nothing at all is done."
7267 (save-excursion
7268 (let ((end (save-excursion (outline-next-heading)
7269 (point-marker)))
7270 (prohibit (if (> diff 0)
7271 "^\\S-"
7272 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7273 col)
7274 (unless (save-excursion (end-of-line 1)
7275 (re-search-forward prohibit end t))
7276 (while (and (< (point) end)
7277 (re-search-forward "^[ \t]+" end t))
7278 (goto-char (match-end 0))
7279 (setq col (current-column))
7280 (if (< diff 0) (replace-match ""))
7281 (org-indent-to-column (+ diff col))))
7282 (move-marker end nil))))
7284 (defun org-convert-to-odd-levels ()
7285 "Convert an org-mode file with all levels allowed to one with odd levels.
7286 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7287 level 5 etc."
7288 (interactive)
7289 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7290 (let ((outline-regexp org-outline-regexp)
7291 (outline-level 'org-outline-level)
7292 (org-odd-levels-only nil) n)
7293 (save-excursion
7294 (goto-char (point-min))
7295 (while (re-search-forward "^\\*\\*+ " nil t)
7296 (setq n (- (length (match-string 0)) 2))
7297 (while (>= (setq n (1- n)) 0)
7298 (org-demote))
7299 (end-of-line 1))))))
7301 (defun org-convert-to-oddeven-levels ()
7302 "Convert an org-mode file with only odd levels to one with odd/even levels.
7303 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7304 file contains a section with an even level, conversion would
7305 destroy the structure of the file. An error is signaled in this
7306 case."
7307 (interactive)
7308 (goto-char (point-min))
7309 ;; First check if there are no even levels
7310 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7311 (org-show-context t)
7312 (error "Not all levels are odd in this file. Conversion not possible"))
7313 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
7314 (let ((outline-regexp org-outline-regexp)
7315 (outline-level 'org-outline-level)
7316 (org-odd-levels-only nil) n)
7317 (save-excursion
7318 (goto-char (point-min))
7319 (while (re-search-forward "^\\*\\*+ " nil t)
7320 (setq n (/ (1- (length (match-string 0))) 2))
7321 (while (>= (setq n (1- n)) 0)
7322 (org-promote))
7323 (end-of-line 1))))))
7325 (defun org-tr-level (n)
7326 "Make N odd if required."
7327 (if org-odd-levels-only (1+ (/ n 2)) n))
7329 ;;; Vertical tree motion, cutting and pasting of subtrees
7331 (defun org-move-subtree-up (&optional arg)
7332 "Move the current subtree up past ARG headlines of the same level."
7333 (interactive "p")
7334 (org-move-subtree-down (- (prefix-numeric-value arg))))
7336 (defun org-move-subtree-down (&optional arg)
7337 "Move the current subtree down past ARG headlines of the same level."
7338 (interactive "p")
7339 (setq arg (prefix-numeric-value arg))
7340 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
7341 'org-get-last-sibling))
7342 (ins-point (make-marker))
7343 (cnt (abs arg))
7344 (col (current-column))
7345 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
7346 ;; Select the tree
7347 (org-back-to-heading)
7348 (setq beg0 (point))
7349 (save-excursion
7350 (setq ne-beg (org-back-over-empty-lines))
7351 (setq beg (point)))
7352 (save-match-data
7353 (save-excursion (outline-end-of-heading)
7354 (setq folded (outline-invisible-p)))
7355 (outline-end-of-subtree))
7356 (outline-next-heading)
7357 (setq ne-end (org-back-over-empty-lines))
7358 (setq end (point))
7359 (goto-char beg0)
7360 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
7361 ;; include less whitespace
7362 (save-excursion
7363 (goto-char beg)
7364 (forward-line (- ne-beg ne-end))
7365 (setq beg (point))))
7366 ;; Find insertion point, with error handling
7367 (while (> cnt 0)
7368 (or (and (funcall movfunc) (looking-at outline-regexp))
7369 (progn (goto-char beg0)
7370 (error "Cannot move past superior level or buffer limit")))
7371 (setq cnt (1- cnt)))
7372 (if (> arg 0)
7373 ;; Moving forward - still need to move over subtree
7374 (progn (org-end-of-subtree t t)
7375 (save-excursion
7376 (org-back-over-empty-lines)
7377 (or (bolp) (newline)))))
7378 (setq ne-ins (org-back-over-empty-lines))
7379 (move-marker ins-point (point))
7380 (setq txt (buffer-substring beg end))
7381 (org-save-markers-in-region beg end)
7382 (delete-region beg end)
7383 (org-remove-empty-overlays-at beg)
7384 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
7385 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
7386 (and (not (bolp)) (looking-at "\n") (forward-char 1))
7387 (let ((bbb (point)))
7388 (insert-before-markers txt)
7389 (org-reinstall-markers-in-region bbb)
7390 (move-marker ins-point bbb))
7391 (or (bolp) (insert "\n"))
7392 (setq ins-end (point))
7393 (goto-char ins-point)
7394 (org-skip-whitespace)
7395 (when (and (< arg 0)
7396 (org-first-sibling-p)
7397 (> ne-ins ne-beg))
7398 ;; Move whitespace back to beginning
7399 (save-excursion
7400 (goto-char ins-end)
7401 (let ((kill-whole-line t))
7402 (kill-line (- ne-ins ne-beg)) (point)))
7403 (insert (make-string (- ne-ins ne-beg) ?\n)))
7404 (move-marker ins-point nil)
7405 (if folded
7406 (hide-subtree)
7407 (org-show-entry)
7408 (show-children)
7409 (org-cycle-hide-drawers 'children))
7410 (org-clean-visibility-after-subtree-move)
7411 ;; move back to the initial column we were at
7412 (move-to-column col)))
7414 (defvar org-subtree-clip ""
7415 "Clipboard for cut and paste of subtrees.
7416 This is actually only a copy of the kill, because we use the normal kill
7417 ring. We need it to check if the kill was created by `org-copy-subtree'.")
7419 (defvar org-subtree-clip-folded nil
7420 "Was the last copied subtree folded?
7421 This is used to fold the tree back after pasting.")
7423 (defun org-cut-subtree (&optional n)
7424 "Cut the current subtree into the clipboard.
7425 With prefix arg N, cut this many sequential subtrees.
7426 This is a short-hand for marking the subtree and then cutting it."
7427 (interactive "p")
7428 (org-copy-subtree n 'cut))
7430 (defun org-copy-subtree (&optional n cut force-store-markers)
7431 "Cut the current subtree into the clipboard.
7432 With prefix arg N, cut this many sequential subtrees.
7433 This is a short-hand for marking the subtree and then copying it.
7434 If CUT is non-nil, actually cut the subtree.
7435 If FORCE-STORE-MARKERS is non-nil, store the relative locations
7436 of some markers in the region, even if CUT is non-nil. This is
7437 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
7438 (interactive "p")
7439 (let (beg end folded (beg0 (point)))
7440 (if (org-called-interactively-p 'any)
7441 (org-back-to-heading nil) ; take what looks like a subtree
7442 (org-back-to-heading t)) ; take what is really there
7443 (org-back-over-empty-lines)
7444 (setq beg (point))
7445 (skip-chars-forward " \t\r\n")
7446 (save-match-data
7447 (save-excursion (outline-end-of-heading)
7448 (setq folded (outline-invisible-p)))
7449 (condition-case nil
7450 (org-forward-same-level (1- n) t)
7451 (error nil))
7452 (org-end-of-subtree t t))
7453 (org-back-over-empty-lines)
7454 (setq end (point))
7455 (goto-char beg0)
7456 (when (> end beg)
7457 (setq org-subtree-clip-folded folded)
7458 (when (or cut force-store-markers)
7459 (org-save-markers-in-region beg end))
7460 (if cut (kill-region beg end) (copy-region-as-kill beg end))
7461 (setq org-subtree-clip (current-kill 0))
7462 (message "%s: Subtree(s) with %d characters"
7463 (if cut "Cut" "Copied")
7464 (length org-subtree-clip)))))
7466 (defun org-paste-subtree (&optional level tree for-yank)
7467 "Paste the clipboard as a subtree, with modification of headline level.
7468 The entire subtree is promoted or demoted in order to match a new headline
7469 level.
7471 If the cursor is at the beginning of a headline, the same level as
7472 that headline is used to paste the tree
7474 If not, the new level is derived from the *visible* headings
7475 before and after the insertion point, and taken to be the inferior headline
7476 level of the two. So if the previous visible heading is level 3 and the
7477 next is level 4 (or vice versa), level 4 will be used for insertion.
7478 This makes sure that the subtree remains an independent subtree and does
7479 not swallow low level entries.
7481 You can also force a different level, either by using a numeric prefix
7482 argument, or by inserting the heading marker by hand. For example, if the
7483 cursor is after \"*****\", then the tree will be shifted to level 5.
7485 If optional TREE is given, use this text instead of the kill ring.
7487 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
7488 move back over whitespace before inserting, and move point to the end of
7489 the inserted text when done."
7490 (interactive "P")
7491 (setq tree (or tree (and kill-ring (current-kill 0))))
7492 (unless (org-kill-is-subtree-p tree)
7493 (error "%s"
7494 (substitute-command-keys
7495 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
7496 (let* ((visp (not (outline-invisible-p)))
7497 (txt tree)
7498 (^re (concat "^\\(" outline-regexp "\\)"))
7499 (re (concat "\\(" outline-regexp "\\)"))
7500 (^re_ (concat "\\(\\*+\\)[ \t]*"))
7502 (old-level (if (string-match ^re txt)
7503 (- (match-end 0) (match-beginning 0) 1)
7504 -1))
7505 (force-level (cond (level (prefix-numeric-value level))
7506 ((and (looking-at "[ \t]*$")
7507 (string-match
7508 ^re_ (buffer-substring
7509 (point-at-bol) (point))))
7510 (- (match-end 1) (match-beginning 1)))
7511 ((and (bolp)
7512 (looking-at org-outline-regexp))
7513 (- (match-end 0) (point) 1))
7514 (t nil)))
7515 (previous-level (save-excursion
7516 (condition-case nil
7517 (progn
7518 (outline-previous-visible-heading 1)
7519 (if (looking-at re)
7520 (- (match-end 0) (match-beginning 0) 1)
7522 (error 1))))
7523 (next-level (save-excursion
7524 (condition-case nil
7525 (progn
7526 (or (looking-at outline-regexp)
7527 (outline-next-visible-heading 1))
7528 (if (looking-at re)
7529 (- (match-end 0) (match-beginning 0) 1)
7531 (error 1))))
7532 (new-level (or force-level (max previous-level next-level)))
7533 (shift (if (or (= old-level -1)
7534 (= new-level -1)
7535 (= old-level new-level))
7537 (- new-level old-level)))
7538 (delta (if (> shift 0) -1 1))
7539 (func (if (> shift 0) 'org-demote 'org-promote))
7540 (org-odd-levels-only nil)
7541 beg end newend)
7542 ;; Remove the forced level indicator
7543 (if force-level
7544 (delete-region (point-at-bol) (point)))
7545 ;; Paste
7546 (beginning-of-line 1)
7547 (unless for-yank (org-back-over-empty-lines))
7548 (setq beg (point))
7549 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
7550 (insert-before-markers txt)
7551 (unless (string-match "\n\\'" txt) (insert "\n"))
7552 (setq newend (point))
7553 (org-reinstall-markers-in-region beg)
7554 (setq end (point))
7555 (goto-char beg)
7556 (skip-chars-forward " \t\n\r")
7557 (setq beg (point))
7558 (if (and (outline-invisible-p) visp)
7559 (save-excursion (outline-show-heading)))
7560 ;; Shift if necessary
7561 (unless (= shift 0)
7562 (save-restriction
7563 (narrow-to-region beg end)
7564 (while (not (= shift 0))
7565 (org-map-region func (point-min) (point-max))
7566 (setq shift (+ delta shift)))
7567 (goto-char (point-min))
7568 (setq newend (point-max))))
7569 (when (or (org-called-interactively-p 'interactive) for-yank)
7570 (message "Clipboard pasted as level %d subtree" new-level))
7571 (if (and (not for-yank) ; in this case, org-yank will decide about folding
7572 kill-ring
7573 (eq org-subtree-clip (current-kill 0))
7574 org-subtree-clip-folded)
7575 ;; The tree was folded before it was killed/copied
7576 (hide-subtree))
7577 (and for-yank (goto-char newend))))
7579 (defun org-kill-is-subtree-p (&optional txt)
7580 "Check if the current kill is an outline subtree, or a set of trees.
7581 Returns nil if kill does not start with a headline, or if the first
7582 headline level is not the largest headline level in the tree.
7583 So this will actually accept several entries of equal levels as well,
7584 which is OK for `org-paste-subtree'.
7585 If optional TXT is given, check this string instead of the current kill."
7586 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
7587 (start-level (and kill
7588 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
7589 org-outline-regexp "\\)")
7590 kill)
7591 (- (match-end 2) (match-beginning 2) 1)))
7592 (re (concat "^" org-outline-regexp))
7593 (start (1+ (or (match-beginning 2) -1))))
7594 (if (not start-level)
7595 (progn
7596 nil) ;; does not even start with a heading
7597 (catch 'exit
7598 (while (setq start (string-match re kill (1+ start)))
7599 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
7600 (throw 'exit nil)))
7601 t))))
7603 (defvar org-markers-to-move nil
7604 "Markers that should be moved with a cut-and-paste operation.
7605 Those markers are stored together with their positions relative to
7606 the start of the region.")
7608 (defun org-save-markers-in-region (beg end)
7609 "Check markers in region.
7610 If these markers are between BEG and END, record their position relative
7611 to BEG, so that after moving the block of text, we can put the markers back
7612 into place.
7613 This function gets called just before an entry or tree gets cut from the
7614 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
7615 called immediately, to move the markers with the entries."
7616 (setq org-markers-to-move nil)
7617 (when (featurep 'org-clock)
7618 (org-clock-save-markers-for-cut-and-paste beg end))
7619 (when (featurep 'org-agenda)
7620 (org-agenda-save-markers-for-cut-and-paste beg end)))
7622 (defun org-check-and-save-marker (marker beg end)
7623 "Check if MARKER is between BEG and END.
7624 If yes, remember the marker and the distance to BEG."
7625 (when (and (marker-buffer marker)
7626 (equal (marker-buffer marker) (current-buffer)))
7627 (if (and (>= marker beg) (< marker end))
7628 (push (cons marker (- marker beg)) org-markers-to-move))))
7630 (defun org-reinstall-markers-in-region (beg)
7631 "Move all remembered markers to their position relative to BEG."
7632 (mapc (lambda (x)
7633 (move-marker (car x) (+ beg (cdr x))))
7634 org-markers-to-move)
7635 (setq org-markers-to-move nil))
7637 (defun org-narrow-to-subtree ()
7638 "Narrow buffer to the current subtree."
7639 (interactive)
7640 (save-excursion
7641 (save-match-data
7642 (org-with-limited-levels
7643 (narrow-to-region
7644 (progn (org-back-to-heading t) (point))
7645 (progn (org-end-of-subtree t t)
7646 (if (and (org-on-heading-p) (not (eobp))) (backward-char 1))
7647 (point)))))))
7649 (defun org-narrow-to-block ()
7650 "Narrow buffer to the current block."
7651 (interactive)
7652 (let ((bstart "^[ \t]*#\\+begin")
7653 (bend "[ \t]*#\\+end")
7654 (case-fold-search t) ;; allow #+BEGIN
7655 b_start b_end)
7656 (if (org-in-regexps-block-p bstart bend)
7657 (progn
7658 (save-excursion (re-search-backward bstart nil t)
7659 (setq b_start (match-beginning 0)))
7660 (save-excursion (re-search-forward bend nil t)
7661 (setq b_end (match-end 0)))
7662 (narrow-to-region b_start b_end))
7663 (error "Not in a block"))))
7665 (eval-when-compile
7666 (defvar org-property-drawer-re))
7668 (defvar org-property-start-re) ;; defined below
7669 (defun org-clone-subtree-with-time-shift (n &optional shift)
7670 "Clone the task (subtree) at point N times.
7671 The clones will be inserted as siblings.
7673 In interactive use, the user will be prompted for the number of
7674 clones to be produced, and for a time SHIFT, which may be a
7675 repeater as used in time stamps, for example `+3d'.
7677 When a valid repeater is given and the entry contains any time
7678 stamps, the clones will become a sequence in time, with time
7679 stamps in the subtree shifted for each clone produced. If SHIFT
7680 is nil or the empty string, time stamps will be left alone. The
7681 ID property of the original subtree is removed.
7683 If the original subtree did contain time stamps with a repeater,
7684 the following will happen:
7685 - the repeater will be removed in each clone
7686 - an additional clone will be produced, with the current, unshifted
7687 date(s) in the entry.
7688 - the original entry will be placed *after* all the clones, with
7689 repeater intact.
7690 - the start days in the repeater in the original entry will be shifted
7691 to past the last clone.
7692 I this way you can spell out a number of instances of a repeating task,
7693 and still retain the repeater to cover future instances of the task."
7694 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
7695 (let (beg end template task idprop
7696 shift-n shift-what doshift nmin nmax (n-no-remove -1))
7697 (if (not (and (integerp n) (> n 0)))
7698 (error "Invalid number of replications %s" n))
7699 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
7700 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
7701 shift)))
7702 (error "Invalid shift specification %s" shift))
7703 (when doshift
7704 (setq shift-n (string-to-number (match-string 1 shift))
7705 shift-what (cdr (assoc (match-string 2 shift)
7706 '(("d" . day) ("w" . week)
7707 ("m" . month) ("y" . year))))))
7708 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
7709 (setq nmin 1 nmax n)
7710 (org-back-to-heading t)
7711 (setq beg (point))
7712 (setq idprop (org-entry-get nil "ID"))
7713 (org-end-of-subtree t t)
7714 (or (bolp) (insert "\n"))
7715 (setq end (point))
7716 (setq template (buffer-substring beg end))
7717 (when (and doshift
7718 (string-match "<[^<>\n]+ \\+[0-9]+[dwmy][^<>\n]*>" template))
7719 (delete-region beg end)
7720 (setq end beg)
7721 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
7722 (goto-char end)
7723 (loop for n from nmin to nmax do
7724 ;; prepare clone
7725 (with-temp-buffer
7726 (insert template)
7727 (org-mode)
7728 (goto-char (point-min))
7729 (and idprop (if org-clone-delete-id
7730 (org-entry-delete nil "ID")
7731 (org-id-get-create t)))
7732 (while (re-search-forward org-property-start-re nil t)
7733 (org-remove-empty-drawer-at "PROPERTIES" (point)))
7734 (goto-char (point-min))
7735 (when doshift
7736 (while (re-search-forward org-ts-regexp-both nil t)
7737 (org-timestamp-change (* n shift-n) shift-what))
7738 (unless (= n n-no-remove)
7739 (goto-char (point-min))
7740 (while (re-search-forward org-ts-regexp nil t)
7741 (save-excursion
7742 (goto-char (match-beginning 0))
7743 (if (looking-at "<[^<>\n]+\\( +\\+[0-9]+[dwmy]\\)")
7744 (delete-region (match-beginning 1) (match-end 1)))))))
7745 (setq task (buffer-string)))
7746 (insert task))
7747 (goto-char beg)))
7749 ;;; Outline Sorting
7751 (defun org-sort (with-case)
7752 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
7753 Optional argument WITH-CASE means sort case-sensitively.
7754 With a double prefix argument, also remove duplicate entries."
7755 (interactive "P")
7756 (cond
7757 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
7758 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
7760 (org-call-with-arg 'org-sort-entries with-case))))
7762 (defun org-sort-remove-invisible (s)
7763 (remove-text-properties 0 (length s) org-rm-props s)
7764 (while (string-match org-bracket-link-regexp s)
7765 (setq s (replace-match (if (match-end 2)
7766 (match-string 3 s)
7767 (match-string 1 s)) t t s)))
7770 (defvar org-priority-regexp) ; defined later in the file
7772 (defvar org-after-sorting-entries-or-items-hook nil
7773 "Hook that is run after a bunch of entries or items have been sorted.
7774 When children are sorted, the cursor is in the parent line when this
7775 hook gets called. When a region or a plain list is sorted, the cursor
7776 will be in the first entry of the sorted region/list.")
7778 (defun org-sort-entries
7779 (&optional with-case sorting-type getkey-func compare-func property)
7780 "Sort entries on a certain level of an outline tree.
7781 If there is an active region, the entries in the region are sorted.
7782 Else, if the cursor is before the first entry, sort the top-level items.
7783 Else, the children of the entry at point are sorted.
7785 Sorting can be alphabetically, numerically, by date/time as given by
7786 a time stamp, by a property or by priority.
7788 The command prompts for the sorting type unless it has been given to the
7789 function through the SORTING-TYPE argument, which needs to be a character,
7790 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F). Here is the
7791 precise meaning of each character:
7793 n Numerically, by converting the beginning of the entry/item to a number.
7794 a Alphabetically, ignoring the TODO keyword and the priority, if any.
7795 t By date/time, either the first active time stamp in the entry, or, if
7796 none exist, by the first inactive one.
7797 s By the scheduled date/time.
7798 d By deadline date/time.
7799 c By creation time, which is assumed to be the first inactive time stamp
7800 at the beginning of a line.
7801 p By priority according to the cookie.
7802 r By the value of a property.
7804 Capital letters will reverse the sort order.
7806 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
7807 called with point at the beginning of the record. It must return either
7808 a string or a number that should serve as the sorting key for that record.
7810 Comparing entries ignores case by default. However, with an optional argument
7811 WITH-CASE, the sorting considers case as well."
7812 (interactive "P")
7813 (let ((case-func (if with-case 'identity 'downcase))
7814 start beg end stars re re2
7815 txt what tmp)
7816 ;; Find beginning and end of region to sort
7817 (cond
7818 ((org-region-active-p)
7819 ;; we will sort the region
7820 (setq end (region-end)
7821 what "region")
7822 (goto-char (region-beginning))
7823 (if (not (org-on-heading-p)) (outline-next-heading))
7824 (setq start (point)))
7825 ((or (org-on-heading-p)
7826 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
7827 ;; we will sort the children of the current headline
7828 (org-back-to-heading)
7829 (setq start (point)
7830 end (progn (org-end-of-subtree t t)
7831 (or (bolp) (insert "\n"))
7832 (org-back-over-empty-lines)
7833 (point))
7834 what "children")
7835 (goto-char start)
7836 (show-subtree)
7837 (outline-next-heading))
7839 ;; we will sort the top-level entries in this file
7840 (goto-char (point-min))
7841 (or (org-on-heading-p) (outline-next-heading))
7842 (setq start (point))
7843 (goto-char (point-max))
7844 (beginning-of-line 1)
7845 (when (looking-at ".*?\\S-")
7846 ;; File ends in a non-white line
7847 (end-of-line 1)
7848 (insert "\n"))
7849 (setq end (point-max))
7850 (setq what "top-level")
7851 (goto-char start)
7852 (show-all)))
7854 (setq beg (point))
7855 (if (>= beg end) (error "Nothing to sort"))
7857 (looking-at "\\(\\*+\\)")
7858 (setq stars (match-string 1)
7859 re (concat "^" (regexp-quote stars) " +")
7860 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
7861 txt (buffer-substring beg end))
7862 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
7863 (if (and (not (equal stars "*")) (string-match re2 txt))
7864 (error "Region to sort contains a level above the first entry"))
7866 (unless sorting-type
7867 (message
7868 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
7869 [t]ime [s]cheduled [d]eadline [c]reated
7870 A/N/T/S/D/C/P/O/F means reversed:"
7871 what)
7872 (setq sorting-type (read-char-exclusive))
7874 (and (= (downcase sorting-type) ?f)
7875 (setq getkey-func
7876 (org-icompleting-read "Sort using function: "
7877 obarray 'fboundp t nil nil))
7878 (setq getkey-func (intern getkey-func)))
7880 (and (= (downcase sorting-type) ?r)
7881 (setq property
7882 (org-icompleting-read "Property: "
7883 (mapcar 'list (org-buffer-property-keys t))
7884 nil t))))
7886 (message "Sorting entries...")
7888 (save-restriction
7889 (narrow-to-region start end)
7890 (let ((dcst (downcase sorting-type))
7891 (case-fold-search nil)
7892 (now (current-time)))
7893 (sort-subr
7894 (/= dcst sorting-type)
7895 ;; This function moves to the beginning character of the "record" to
7896 ;; be sorted.
7897 (lambda nil
7898 (if (re-search-forward re nil t)
7899 (goto-char (match-beginning 0))
7900 (goto-char (point-max))))
7901 ;; This function moves to the last character of the "record" being
7902 ;; sorted.
7903 (lambda nil
7904 (save-match-data
7905 (condition-case nil
7906 (outline-forward-same-level 1)
7907 (error
7908 (goto-char (point-max))))))
7909 ;; This function returns the value that gets sorted against.
7910 (lambda nil
7911 (cond
7912 ((= dcst ?n)
7913 (if (looking-at org-complex-heading-regexp)
7914 (string-to-number (match-string 4))
7915 nil))
7916 ((= dcst ?a)
7917 (if (looking-at org-complex-heading-regexp)
7918 (funcall case-func (match-string 4))
7919 nil))
7920 ((= dcst ?t)
7921 (let ((end (save-excursion (outline-next-heading) (point))))
7922 (if (or (re-search-forward org-ts-regexp end t)
7923 (re-search-forward org-ts-regexp-both end t))
7924 (org-time-string-to-seconds (match-string 0))
7925 (org-float-time now))))
7926 ((= dcst ?c)
7927 (let ((end (save-excursion (outline-next-heading) (point))))
7928 (if (re-search-forward
7929 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
7930 end t)
7931 (org-time-string-to-seconds (match-string 0))
7932 (org-float-time now))))
7933 ((= dcst ?s)
7934 (let ((end (save-excursion (outline-next-heading) (point))))
7935 (if (re-search-forward org-scheduled-time-regexp end t)
7936 (org-time-string-to-seconds (match-string 1))
7937 (org-float-time now))))
7938 ((= dcst ?d)
7939 (let ((end (save-excursion (outline-next-heading) (point))))
7940 (if (re-search-forward org-deadline-time-regexp end t)
7941 (org-time-string-to-seconds (match-string 1))
7942 (org-float-time now))))
7943 ((= dcst ?p)
7944 (if (re-search-forward org-priority-regexp (point-at-eol) t)
7945 (string-to-char (match-string 2))
7946 org-default-priority))
7947 ((= dcst ?r)
7948 (or (org-entry-get nil property) ""))
7949 ((= dcst ?o)
7950 (if (looking-at org-complex-heading-regexp)
7951 (- 9999 (length (member (match-string 2)
7952 org-todo-keywords-1)))))
7953 ((= dcst ?f)
7954 (if getkey-func
7955 (progn
7956 (setq tmp (funcall getkey-func))
7957 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
7958 tmp)
7959 (error "Invalid key function `%s'" getkey-func)))
7960 (t (error "Invalid sorting type `%c'" sorting-type))))
7962 (cond
7963 ((= dcst ?a) 'string<)
7964 ((= dcst ?f) compare-func)
7965 ((member dcst '(?p ?t ?s ?d ?c)) '<)
7966 (t nil)))))
7967 (run-hooks 'org-after-sorting-entries-or-items-hook)
7968 (message "Sorting entries...done")))
7970 (defun org-do-sort (table what &optional with-case sorting-type)
7971 "Sort TABLE of WHAT according to SORTING-TYPE.
7972 The user will be prompted for the SORTING-TYPE if the call to this
7973 function does not specify it. WHAT is only for the prompt, to indicate
7974 what is being sorted. The sorting key will be extracted from
7975 the car of the elements of the table.
7976 If WITH-CASE is non-nil, the sorting will be case-sensitive."
7977 (unless sorting-type
7978 (message
7979 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
7980 what)
7981 (setq sorting-type (read-char-exclusive)))
7982 (let ((dcst (downcase sorting-type))
7983 extractfun comparefun)
7984 ;; Define the appropriate functions
7985 (cond
7986 ((= dcst ?n)
7987 (setq extractfun 'string-to-number
7988 comparefun (if (= dcst sorting-type) '< '>)))
7989 ((= dcst ?a)
7990 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
7991 (lambda(x) (downcase (org-sort-remove-invisible x))))
7992 comparefun (if (= dcst sorting-type)
7993 'string<
7994 (lambda (a b) (and (not (string< a b))
7995 (not (string= a b)))))))
7996 ((= dcst ?t)
7997 (setq extractfun
7998 (lambda (x)
7999 (if (or (string-match org-ts-regexp x)
8000 (string-match org-ts-regexp-both x))
8001 (org-float-time
8002 (org-time-string-to-time (match-string 0 x)))
8004 comparefun (if (= dcst sorting-type) '< '>)))
8005 (t (error "Invalid sorting type `%c'" sorting-type)))
8007 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8008 table)
8009 (lambda (a b) (funcall comparefun (car a) (car b))))))
8012 ;;; The orgstruct minor mode
8014 ;; Define a minor mode which can be used in other modes in order to
8015 ;; integrate the org-mode structure editing commands.
8017 ;; This is really a hack, because the org-mode structure commands use
8018 ;; keys which normally belong to the major mode. Here is how it
8019 ;; works: The minor mode defines all the keys necessary to operate the
8020 ;; structure commands, but wraps the commands into a function which
8021 ;; tests if the cursor is currently at a headline or a plain list
8022 ;; item. If that is the case, the structure command is used,
8023 ;; temporarily setting many Org-mode variables like regular
8024 ;; expressions for filling etc. However, when any of those keys is
8025 ;; used at a different location, function uses `key-binding' to look
8026 ;; up if the key has an associated command in another currently active
8027 ;; keymap (minor modes, major mode, global), and executes that
8028 ;; command. There might be problems if any of the keys is otherwise
8029 ;; used as a prefix key.
8031 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
8032 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
8033 ;; addresses this by checking explicitly for both bindings.
8035 (defvar orgstruct-mode-map (make-sparse-keymap)
8036 "Keymap for the minor `orgstruct-mode'.")
8038 (defvar org-local-vars nil
8039 "List of local variables, for use by `orgstruct-mode'.")
8041 ;;;###autoload
8042 (define-minor-mode orgstruct-mode
8043 "Toggle the minor mode `orgstruct-mode'.
8044 This mode is for using Org-mode structure commands in other
8045 modes. The following keys behave as if Org-mode were active, if
8046 the cursor is on a headline, or on a plain list item (both as
8047 defined by Org-mode).
8049 M-up Move entry/item up
8050 M-down Move entry/item down
8051 M-left Promote
8052 M-right Demote
8053 M-S-up Move entry/item up
8054 M-S-down Move entry/item down
8055 M-S-left Promote subtree
8056 M-S-right Demote subtree
8057 M-q Fill paragraph and items like in Org-mode
8058 C-c ^ Sort entries
8059 C-c - Cycle list bullet
8060 TAB Cycle item visibility
8061 M-RET Insert new heading/item
8062 S-M-RET Insert new TODO heading / Checkbox item
8063 C-c C-c Set tags / toggle checkbox"
8064 nil " OrgStruct" nil
8065 (org-load-modules-maybe)
8066 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
8068 ;;;###autoload
8069 (defun turn-on-orgstruct ()
8070 "Unconditionally turn on `orgstruct-mode'."
8071 (orgstruct-mode 1))
8073 (defun orgstruct++-mode (&optional arg)
8074 "Toggle `orgstruct-mode', the enhanced version of it.
8075 In addition to setting orgstruct-mode, this also exports all indentation
8076 and autofilling variables from org-mode into the buffer. It will also
8077 recognize item context in multiline items.
8078 Note that turning off orgstruct-mode will *not* remove the
8079 indentation/paragraph settings. This can only be done by refreshing the
8080 major mode, for example with \\[normal-mode]."
8081 (interactive "P")
8082 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8083 (if (< arg 1)
8084 (orgstruct-mode -1)
8085 (orgstruct-mode 1)
8086 (let (var val)
8087 (mapc
8088 (lambda (x)
8089 (when (string-match
8090 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
8091 (symbol-name (car x)))
8092 (setq var (car x) val (nth 1 x))
8093 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8094 org-local-vars)
8095 (org-set-local 'orgstruct-is-++ t))))
8097 (defvar orgstruct-is-++ nil
8098 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8099 (make-variable-buffer-local 'orgstruct-is-++)
8101 ;;;###autoload
8102 (defun turn-on-orgstruct++ ()
8103 "Unconditionally turn on `orgstruct++-mode'."
8104 (orgstruct++-mode 1))
8106 (defun orgstruct-error ()
8107 "Error when there is no default binding for a structure key."
8108 (interactive)
8109 (error "This key has no function outside structure elements"))
8111 (defun orgstruct-setup ()
8112 "Setup orgstruct keymaps."
8113 (let ((nfunc 0)
8114 (bindings
8115 (list
8116 '([(meta up)] org-metaup)
8117 '([(meta down)] org-metadown)
8118 '([(meta left)] org-metaleft)
8119 '([(meta right)] org-metaright)
8120 '([(meta shift up)] org-shiftmetaup)
8121 '([(meta shift down)] org-shiftmetadown)
8122 '([(meta shift left)] org-shiftmetaleft)
8123 '([(meta shift right)] org-shiftmetaright)
8124 '([?\e (up)] org-metaup)
8125 '([?\e (down)] org-metadown)
8126 '([?\e (left)] org-metaleft)
8127 '([?\e (right)] org-metaright)
8128 '([?\e (shift up)] org-shiftmetaup)
8129 '([?\e (shift down)] org-shiftmetadown)
8130 '([?\e (shift left)] org-shiftmetaleft)
8131 '([?\e (shift right)] org-shiftmetaright)
8132 '([(shift up)] org-shiftup)
8133 '([(shift down)] org-shiftdown)
8134 '([(shift left)] org-shiftleft)
8135 '([(shift right)] org-shiftright)
8136 '("\C-c\C-c" org-ctrl-c-ctrl-c)
8137 '("\M-q" fill-paragraph)
8138 '("\C-c^" org-sort)
8139 '("\C-c-" org-cycle-list-bullet)))
8140 elt key fun cmd)
8141 (while (setq elt (pop bindings))
8142 (setq nfunc (1+ nfunc))
8143 (setq key (org-key (car elt))
8144 fun (nth 1 elt)
8145 cmd (orgstruct-make-binding fun nfunc key))
8146 (org-defkey orgstruct-mode-map key cmd))
8148 ;; Special treatment needed for TAB and RET
8149 (org-defkey orgstruct-mode-map [(tab)]
8150 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
8151 (org-defkey orgstruct-mode-map "\C-i"
8152 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
8154 (org-defkey orgstruct-mode-map "\M-\C-m"
8155 (orgstruct-make-binding 'org-insert-heading 105
8156 "\M-\C-m" [(meta return)]))
8157 (org-defkey orgstruct-mode-map [(meta return)]
8158 (orgstruct-make-binding 'org-insert-heading 106
8159 [(meta return)] "\M-\C-m"))
8161 (org-defkey orgstruct-mode-map [(shift meta return)]
8162 (orgstruct-make-binding 'org-insert-todo-heading 107
8163 [(meta return)] "\M-\C-m"))
8165 (org-defkey orgstruct-mode-map "\e\C-m"
8166 (orgstruct-make-binding 'org-insert-heading 108
8167 "\e\C-m" [?\e (return)]))
8168 (org-defkey orgstruct-mode-map [?\e (return)]
8169 (orgstruct-make-binding 'org-insert-heading 109
8170 [?\e (return)] "\e\C-m"))
8171 (org-defkey orgstruct-mode-map [?\e (shift return)]
8172 (orgstruct-make-binding 'org-insert-todo-heading 110
8173 [?\e (return)] "\e\C-m"))
8175 (unless org-local-vars
8176 (setq org-local-vars (org-get-local-variables)))
8180 (defun orgstruct-make-binding (fun n &rest keys)
8181 "Create a function for binding in the structure minor mode.
8182 FUN is the command to call inside a table. N is used to create a unique
8183 command name. KEYS are keys that should be checked in for a command
8184 to execute outside of tables."
8185 (eval
8186 (list 'defun
8187 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
8188 '(arg)
8189 (concat "In Structure, run `" (symbol-name fun) "'.\n"
8190 "Outside of structure, run the binding of `"
8191 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
8192 "'.")
8193 '(interactive "p")
8194 (list 'if
8195 `(org-context-p 'headline 'item
8196 (and orgstruct-is-++
8197 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
8198 'item-body))
8199 (list 'org-run-like-in-org-mode (list 'quote fun))
8200 (list 'let '(orgstruct-mode)
8201 (list 'call-interactively
8202 (append '(or)
8203 (mapcar (lambda (k)
8204 (list 'key-binding k))
8205 keys)
8206 '('orgstruct-error))))))))
8208 (defun org-context-p (&rest contexts)
8209 "Check if local context is any of CONTEXTS.
8210 Possible values in the list of contexts are `table', `headline', and `item'."
8211 (let ((pos (point)))
8212 (goto-char (point-at-bol))
8213 (prog1 (or (and (memq 'table contexts)
8214 (looking-at "[ \t]*|"))
8215 (and (memq 'headline contexts)
8216 ;;????????? (looking-at "\\*+"))
8217 (looking-at outline-regexp))
8218 (and (memq 'item contexts)
8219 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
8220 (and (memq 'item-body contexts)
8221 (org-in-item-p)))
8222 (goto-char pos))))
8224 (defun org-get-local-variables ()
8225 "Return a list of all local variables in an org-mode buffer."
8226 (let (varlist)
8227 (with-current-buffer (get-buffer-create "*Org tmp*")
8228 (erase-buffer)
8229 (org-mode)
8230 (setq varlist (buffer-local-variables)))
8231 (kill-buffer "*Org tmp*")
8232 (delq nil
8233 (mapcar
8234 (lambda (x)
8235 (setq x
8236 (if (symbolp x)
8237 (list x)
8238 (list (car x) (list 'quote (cdr x)))))
8239 (if (string-match
8240 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
8241 (symbol-name (car x)))
8242 x nil))
8243 varlist))))
8245 (defun org-clone-local-variables (from-buffer &optional regexp)
8246 "Clone local variables from FROM-BUFFER.
8247 Optional argument REGEXP selects variables to clone."
8248 (mapc
8249 (lambda (pair)
8250 (and (symbolp (car pair))
8251 (or (null regexp)
8252 (string-match regexp (symbol-name (car pair))))
8253 (set (make-local-variable (car pair))
8254 (cdr pair))))
8255 (buffer-local-variables from-buffer)))
8257 ;;;###autoload
8258 (defun org-run-like-in-org-mode (cmd)
8259 "Run a command, pretending that the current buffer is in Org-mode.
8260 This will temporarily bind local variables that are typically bound in
8261 Org-mode to the values they have in Org-mode, and then interactively
8262 call CMD."
8263 (org-load-modules-maybe)
8264 (unless org-local-vars
8265 (setq org-local-vars (org-get-local-variables)))
8266 (eval (list 'let org-local-vars
8267 (list 'call-interactively (list 'quote cmd)))))
8269 ;;;; Archiving
8271 (defun org-get-category (&optional pos force-refresh)
8272 "Get the category applying to position POS."
8273 (if force-refresh (org-refresh-category-properties))
8274 (let ((pos (or pos (point))))
8275 (or (get-text-property pos 'org-category)
8276 (progn (org-refresh-category-properties)
8277 (get-text-property pos 'org-category)))))
8279 (defun org-refresh-category-properties ()
8280 "Refresh category text properties in the buffer."
8281 (let ((def-cat (cond
8282 ((null org-category)
8283 (if buffer-file-name
8284 (file-name-sans-extension
8285 (file-name-nondirectory buffer-file-name))
8286 "???"))
8287 ((symbolp org-category) (symbol-name org-category))
8288 (t org-category)))
8289 beg end cat pos optionp)
8290 (org-unmodified
8291 (save-excursion
8292 (save-restriction
8293 (widen)
8294 (goto-char (point-min))
8295 (put-text-property (point) (point-max) 'org-category def-cat)
8296 (while (re-search-forward
8297 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8298 (setq pos (match-end 0)
8299 optionp (equal (char-after (match-beginning 0)) ?#)
8300 cat (org-trim (match-string 2)))
8301 (if optionp
8302 (setq beg (point-at-bol) end (point-max))
8303 (org-back-to-heading t)
8304 (setq beg (point) end (org-end-of-subtree t t)))
8305 (put-text-property beg end 'org-category cat)
8306 (goto-char pos)))))))
8309 ;;;; Link Stuff
8311 ;;; Link abbreviations
8313 (defun org-link-expand-abbrev (link)
8314 "Apply replacements as defined in `org-link-abbrev-alist."
8315 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
8316 (let* ((key (match-string 1 link))
8317 (as (or (assoc key org-link-abbrev-alist-local)
8318 (assoc key org-link-abbrev-alist)))
8319 (tag (and (match-end 2) (match-string 3 link)))
8320 rpl)
8321 (if (not as)
8322 link
8323 (setq rpl (cdr as))
8324 (cond
8325 ((symbolp rpl) (funcall rpl tag))
8326 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
8327 ((string-match "%h" rpl)
8328 (replace-match (url-hexify-string (or tag "")) t t rpl))
8329 (t (concat rpl tag)))))
8330 link))
8332 ;;; Storing and inserting links
8334 (defvar org-insert-link-history nil
8335 "Minibuffer history for links inserted with `org-insert-link'.")
8337 (defvar org-stored-links nil
8338 "Contains the links stored with `org-store-link'.")
8340 (defvar org-store-link-plist nil
8341 "Plist with info about the most recently link created with `org-store-link'.")
8343 (defvar org-link-protocols nil
8344 "Link protocols added to Org-mode using `org-add-link-type'.")
8346 (defvar org-store-link-functions nil
8347 "List of functions that are called to create and store a link.
8348 Each function will be called in turn until one returns a non-nil
8349 value. Each function should check if it is responsible for creating
8350 this link (for example by looking at the major mode).
8351 If not, it must exit and return nil.
8352 If yes, it should return a non-nil value after a calling
8353 `org-store-link-props' with a list of properties and values.
8354 Special properties are:
8356 :type The link prefix, like \"http\". This must be given.
8357 :link The link, like \"http://www.astro.uva.nl/~dominik\".
8358 This is obligatory as well.
8359 :description Optional default description for the second pair
8360 of brackets in an Org-mode link. The user can still change
8361 this when inserting this link into an Org-mode buffer.
8363 In addition to these, any additional properties can be specified
8364 and then used in remember templates.")
8366 (defun org-add-link-type (type &optional follow export)
8367 "Add TYPE to the list of `org-link-types'.
8368 Re-compute all regular expressions depending on `org-link-types'
8370 FOLLOW and EXPORT are two functions.
8372 FOLLOW should take the link path as the single argument and do whatever
8373 is necessary to follow the link, for example find a file or display
8374 a mail message.
8376 EXPORT should format the link path for export to one of the export formats.
8377 It should be a function accepting three arguments:
8379 path the path of the link, the text after the prefix (like \"http:\")
8380 desc the description of the link, if any, or a description added by
8381 org-export-normalize-links if there is none
8382 format the export format, a symbol like `html' or `latex' or `ascii'..
8384 The function may use the FORMAT information to return different values
8385 depending on the format. The return value will be put literally into
8386 the exported file. If the return value is nil, this means Org should
8387 do what it normally does with links which do not have EXPORT defined.
8389 Org-mode has a built-in default for exporting links. If you are happy with
8390 this default, there is no need to define an export function for the link
8391 type. For a simple example of an export function, see `org-bbdb.el'."
8392 (add-to-list 'org-link-types type t)
8393 (org-make-link-regexps)
8394 (if (assoc type org-link-protocols)
8395 (setcdr (assoc type org-link-protocols) (list follow export))
8396 (push (list type follow export) org-link-protocols)))
8398 (defvar org-agenda-buffer-name)
8400 ;;;###autoload
8401 (defun org-store-link (arg)
8402 "\\<org-mode-map>Store an org-link to the current location.
8403 This link is added to `org-stored-links' and can later be inserted
8404 into an org-buffer with \\[org-insert-link].
8406 For some link types, a prefix arg is interpreted:
8407 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
8408 For file links, arg negates `org-context-in-file-links'."
8409 (interactive "P")
8410 (org-load-modules-maybe)
8411 (setq org-store-link-plist nil) ; reset
8412 (org-with-limited-levels
8413 (let (link cpltxt desc description search txt custom-id agenda-link)
8414 (cond
8416 ((run-hook-with-args-until-success 'org-store-link-functions)
8417 (setq link (plist-get org-store-link-plist :link)
8418 desc (or (plist-get org-store-link-plist :description) link)))
8420 ((equal (buffer-name) "*Org Edit Src Example*")
8421 (let (label gc)
8422 (while (or (not label)
8423 (save-excursion
8424 (save-restriction
8425 (widen)
8426 (goto-char (point-min))
8427 (re-search-forward
8428 (regexp-quote (format org-coderef-label-format label))
8429 nil t))))
8430 (when label (message "Label exists already") (sit-for 2))
8431 (setq label (read-string "Code line label: " label)))
8432 (end-of-line 1)
8433 (setq link (format org-coderef-label-format label))
8434 (setq gc (- 79 (length link)))
8435 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
8436 (insert link)
8437 (setq link (concat "(" label ")") desc nil)))
8439 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
8440 ;; We are in the agenda, link to referenced location
8441 (let ((m (or (get-text-property (point) 'org-hd-marker)
8442 (get-text-property (point) 'org-marker))))
8443 (when m
8444 (org-with-point-at m
8445 (setq agenda-link
8446 (if (org-called-interactively-p 'any)
8447 (call-interactively 'org-store-link)
8448 (org-store-link nil)))))))
8450 ((eq major-mode 'calendar-mode)
8451 (let ((cd (calendar-cursor-to-date)))
8452 (setq link
8453 (format-time-string
8454 (car org-time-stamp-formats)
8455 (apply 'encode-time
8456 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
8457 nil nil nil))))
8458 (org-store-link-props :type "calendar" :date cd)))
8460 ((eq major-mode 'w3-mode)
8461 (setq cpltxt (if (and (buffer-name)
8462 (not (string-match "Untitled" (buffer-name))))
8463 (buffer-name)
8464 (url-view-url t))
8465 link (org-make-link (url-view-url t)))
8466 (org-store-link-props :type "w3" :url (url-view-url t)))
8468 ((eq major-mode 'w3m-mode)
8469 (setq cpltxt (or w3m-current-title w3m-current-url)
8470 link (org-make-link w3m-current-url))
8471 (org-store-link-props :type "w3m" :url (url-view-url t)))
8473 ((setq search (run-hook-with-args-until-success
8474 'org-create-file-search-functions))
8475 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
8476 "::" search))
8477 (setq cpltxt (or description link)))
8479 ((eq major-mode 'image-mode)
8480 (setq cpltxt (concat "file:"
8481 (abbreviate-file-name buffer-file-name))
8482 link (org-make-link cpltxt))
8483 (org-store-link-props :type "image" :file buffer-file-name))
8485 ((eq major-mode 'dired-mode)
8486 ;; link to the file in the current line
8487 (let ((file (dired-get-filename nil t)))
8488 (setq file (if file
8489 (abbreviate-file-name
8490 (expand-file-name (dired-get-filename nil t)))
8491 ;; otherwise, no file so use current directory.
8492 default-directory))
8493 (setq cpltxt (concat "file:" file)
8494 link (org-make-link cpltxt))))
8496 ((and (buffer-file-name (buffer-base-buffer)) (org-mode-p))
8497 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
8498 (cond
8499 ((org-in-regexp "<<\\(.*?\\)>>")
8500 (setq cpltxt
8501 (concat "file:"
8502 (abbreviate-file-name
8503 (buffer-file-name (buffer-base-buffer)))
8504 "::" (match-string 1))
8505 link (org-make-link cpltxt)))
8506 ((and (featurep 'org-id)
8507 (or (eq org-link-to-org-use-id t)
8508 (and (eq org-link-to-org-use-id 'create-if-interactive)
8509 (org-called-interactively-p 'any))
8510 (and (eq org-link-to-org-use-id
8511 'create-if-interactive-and-no-custom-id)
8512 (org-called-interactively-p 'any)
8513 (not custom-id))
8514 (and org-link-to-org-use-id
8515 (org-entry-get nil "ID"))))
8516 ;; We can make a link using the ID.
8517 (setq link (condition-case nil
8518 (prog1 (org-id-store-link)
8519 (setq desc (plist-get org-store-link-plist
8520 :description)))
8521 (error
8522 ;; probably before first headline, link to file only
8523 (concat "file:"
8524 (abbreviate-file-name
8525 (buffer-file-name (buffer-base-buffer))))))))
8527 ;; Just link to current headline
8528 (setq cpltxt (concat "file:"
8529 (abbreviate-file-name
8530 (buffer-file-name (buffer-base-buffer)))))
8531 ;; Add a context search string
8532 (when (org-xor org-context-in-file-links arg)
8533 (setq txt (cond
8534 ((org-on-heading-p) nil)
8535 ((org-region-active-p)
8536 (buffer-substring (region-beginning) (region-end)))
8537 (t nil)))
8538 (when (or (null txt) (string-match "\\S-" txt))
8539 (setq cpltxt
8540 (concat cpltxt "::"
8541 (condition-case nil
8542 (org-make-org-heading-search-string txt)
8543 (error "")))
8544 desc (or (nth 4 (ignore-errors
8545 (org-heading-components))) "NONE"))))
8546 (if (string-match "::\\'" cpltxt)
8547 (setq cpltxt (substring cpltxt 0 -2)))
8548 (setq link (org-make-link cpltxt)))))
8550 ((buffer-file-name (buffer-base-buffer))
8551 ;; Just link to this file here.
8552 (setq cpltxt (concat "file:"
8553 (abbreviate-file-name
8554 (buffer-file-name (buffer-base-buffer)))))
8555 ;; Add a context string
8556 (when (org-xor org-context-in-file-links arg)
8557 (setq txt (if (org-region-active-p)
8558 (buffer-substring (region-beginning) (region-end))
8559 (buffer-substring (point-at-bol) (point-at-eol))))
8560 ;; Only use search option if there is some text.
8561 (when (string-match "\\S-" txt)
8562 (setq cpltxt
8563 (concat cpltxt "::" (org-make-org-heading-search-string txt))
8564 desc "NONE")))
8565 (setq link (org-make-link cpltxt)))
8567 ((org-called-interactively-p 'interactive)
8568 (error "Cannot link to a buffer which is not visiting a file"))
8570 (t (setq link nil)))
8572 (if (consp link) (setq cpltxt (car link) link (cdr link)))
8573 (setq link (or link cpltxt)
8574 desc (or desc cpltxt))
8575 (if (equal desc "NONE") (setq desc nil))
8577 (if (and (or (org-called-interactively-p 'any) executing-kbd-macro) link)
8578 (progn
8579 (setq org-stored-links
8580 (cons (list link desc) org-stored-links))
8581 (message "Stored: %s" (or desc link))
8582 (when custom-id
8583 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
8584 "::#" custom-id))
8585 (setq org-stored-links
8586 (cons (list link desc) org-stored-links))))
8587 (or agenda-link (and link (org-make-link-string link desc)))))))
8589 (defun org-store-link-props (&rest plist)
8590 "Store link properties, extract names and addresses."
8591 (let (x adr)
8592 (when (setq x (plist-get plist :from))
8593 (setq adr (mail-extract-address-components x))
8594 (setq plist (plist-put plist :fromname (car adr)))
8595 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
8596 (when (setq x (plist-get plist :to))
8597 (setq adr (mail-extract-address-components x))
8598 (setq plist (plist-put plist :toname (car adr)))
8599 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
8600 (let ((from (plist-get plist :from))
8601 (to (plist-get plist :to)))
8602 (when (and from to org-from-is-user-regexp)
8603 (setq plist
8604 (plist-put plist :fromto
8605 (if (string-match org-from-is-user-regexp from)
8606 (concat "to %t")
8607 (concat "from %f"))))))
8608 (setq org-store-link-plist plist))
8610 (defun org-add-link-props (&rest plist)
8611 "Add these properties to the link property list."
8612 (let (key value)
8613 (while plist
8614 (setq key (pop plist) value (pop plist))
8615 (setq org-store-link-plist
8616 (plist-put org-store-link-plist key value)))))
8618 (defun org-email-link-description (&optional fmt)
8619 "Return the description part of an email link.
8620 This takes information from `org-store-link-plist' and formats it
8621 according to FMT (default from `org-email-link-description-format')."
8622 (setq fmt (or fmt org-email-link-description-format))
8623 (let* ((p org-store-link-plist)
8624 (to (plist-get p :toaddress))
8625 (from (plist-get p :fromaddress))
8626 (table
8627 (list
8628 (cons "%c" (plist-get p :fromto))
8629 (cons "%F" (plist-get p :from))
8630 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
8631 (cons "%T" (plist-get p :to))
8632 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
8633 (cons "%s" (plist-get p :subject))
8634 (cons "%d" (plist-get p :date))
8635 (cons "%m" (plist-get p :message-id)))))
8636 (when (string-match "%c" fmt)
8637 ;; Check if the user wrote this message
8638 (if (and org-from-is-user-regexp from to
8639 (save-match-data (string-match org-from-is-user-regexp from)))
8640 (setq fmt (replace-match "to %t" t t fmt))
8641 (setq fmt (replace-match "from %f" t t fmt))))
8642 (org-replace-escapes fmt table)))
8644 (defun org-make-org-heading-search-string (&optional string heading)
8645 "Make search string for STRING or current headline."
8646 (interactive)
8647 (let ((s (or string (org-get-heading)))
8648 (lines org-context-in-file-links))
8649 (unless (and string (not heading))
8650 ;; We are using a headline, clean up garbage in there.
8651 (if (string-match org-todo-regexp s)
8652 (setq s (replace-match "" t t s)))
8653 (if (string-match (org-re ":[[:alnum:]_@#%:]+:[ \t]*$") s)
8654 (setq s (replace-match "" t t s)))
8655 (setq s (org-trim s))
8656 (if (string-match (concat "^\\(" org-quote-string "\\|"
8657 org-comment-string "\\)") s)
8658 (setq s (replace-match "" t t s)))
8659 (while (string-match org-ts-regexp s)
8660 (setq s (replace-match "" t t s))))
8661 (or string (setq s (concat "*" s))) ; Add * for headlines
8662 (when (and string (integerp lines) (> lines 0))
8663 (let ((slines (org-split-string s "\n")))
8664 (when (< lines (length slines))
8665 (setq s (mapconcat
8666 'identity
8667 (reverse (nthcdr (- (length slines) lines)
8668 (reverse slines))) "\n")))))
8669 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
8671 (defun org-make-link (&rest strings)
8672 "Concatenate STRINGS."
8673 (apply 'concat strings))
8675 (defun org-make-link-string (link &optional description)
8676 "Make a link with brackets, consisting of LINK and DESCRIPTION."
8677 (unless (string-match "\\S-" link)
8678 (error "Empty link"))
8679 (when (and description
8680 (stringp description)
8681 (not (string-match "\\S-" description)))
8682 (setq description nil))
8683 (when (stringp description)
8684 ;; Remove brackets from the description, they are fatal.
8685 (while (string-match "\\[" description)
8686 (setq description (replace-match "{" t t description)))
8687 (while (string-match "\\]" description)
8688 (setq description (replace-match "}" t t description))))
8689 (when (equal (org-link-escape link) description)
8690 ;; No description needed, it is identical
8691 (setq description nil))
8692 (when (and (not description)
8693 (not (equal link (org-link-escape link))))
8694 (setq description (org-extract-attributes link)))
8695 (setq link (if (string-match org-link-types-re link)
8696 (concat (match-string 1 link)
8697 (org-link-escape (substring link (match-end 1))))
8698 (org-link-escape link)))
8699 (concat "[[" link "]"
8700 (if description (concat "[" description "]") "")
8701 "]"))
8703 (defconst org-link-escape-chars
8704 '(?\ ?\[ ?\] ?\; ?\= ?\+)
8705 "List of characters that should be escaped in link.
8706 This is the list that is used for internal purposes.")
8708 (defvar org-url-encoding-use-url-hexify nil)
8710 (defconst org-link-escape-chars-browser
8711 '(?\ )
8712 "List of escapes for characters that are problematic in links.
8713 This is the list that is used before handing over to the browser.")
8715 (defun org-link-escape (text &optional table merge)
8716 "Return percent escaped representation of TEXT.
8717 TEXT is a string with the text to escape.
8718 Optional argument TABLE is a list with characters that should be
8719 escaped. When nil, `org-link-escape-chars' is used.
8720 If optional argument MERGE is set, merge TABLE into
8721 `org-link-escape-chars'."
8722 (if (and org-url-encoding-use-url-hexify (not table))
8723 (url-hexify-string text)
8724 (cond
8725 ((and table merge)
8726 (mapc (lambda (defchr)
8727 (unless (member defchr table)
8728 (setq table (cons defchr table)))) org-link-escape-chars))
8729 ((null table)
8730 (setq table org-link-escape-chars)))
8731 (mapconcat
8732 (lambda (char)
8733 (if (or (member char table)
8734 (< char 32) (= char 37) (> char 126))
8735 (mapconcat (lambda (sequence-element)
8736 (format "%%%.2X" sequence-element))
8737 (or (encode-coding-char char 'utf-8)
8738 (error "Unable to percent escape character: %s"
8739 (char-to-string char))) "")
8740 (char-to-string char))) text "")))
8742 (defun org-link-unescape (str)
8743 "Unhex hexified unicode strings as returned from the JavaScript function
8744 encodeURIComponent. E.g. `%C3%B6' is the german Umlaut `ö'."
8745 (unless (and (null str) (string= "" str))
8746 (let ((pos 0) (case-fold-search t) unhexed)
8747 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
8748 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
8749 (setq str (replace-match unhexed t t str))
8750 (setq pos (+ pos (length unhexed))))))
8751 str)
8753 (defun org-link-unescape-compound (hex)
8754 "Unhexify unicode hex-chars. E.g. `%C3%B6' is the German Umlaut `ö'.
8755 Note: this function also decodes single byte encodings like
8756 `%E1' (\"á\") if not followed by another `%[A-F0-9]{2}' group."
8757 (save-match-data
8758 (let* ((bytes (cdr (split-string hex "%")))
8759 (ret "")
8760 (eat 0)
8761 (sum 0))
8762 (while bytes
8763 (let* ((val (string-to-number (pop bytes) 16))
8764 (shift-xor
8765 (if (= 0 eat)
8766 (cond
8767 ((>= val 252) (cons 6 252))
8768 ((>= val 248) (cons 5 248))
8769 ((>= val 240) (cons 4 240))
8770 ((>= val 224) (cons 3 224))
8771 ((>= val 192) (cons 2 192))
8772 (t (cons 0 0)))
8773 (cons 6 128))))
8774 (if (>= val 192) (setq eat (car shift-xor)))
8775 (setq val (logxor val (cdr shift-xor)))
8776 (setq sum (+ (lsh sum (car shift-xor)) val))
8777 (if (> eat 0) (setq eat (- eat 1)))
8778 (cond
8779 ((= 0 eat) ;multi byte
8780 (setq ret (concat ret (org-char-to-string sum)))
8781 (setq sum 0))
8782 ((not bytes) ; single byte(s)
8783 (setq ret (org-link-unescape-single-byte-sequence hex))))
8784 )) ;; end (while bytes
8785 ret )))
8787 (defun org-link-unescape-single-byte-sequence (hex)
8788 "Unhexify hex-encoded single byte character sequences."
8789 (mapconcat (lambda (byte)
8790 (char-to-string (string-to-number byte 16)))
8791 (cdr (split-string hex "%")) ""))
8793 (defun org-xor (a b)
8794 "Exclusive or."
8795 (if a (not b) b))
8797 (defun org-fixup-message-id-for-http (s)
8798 "Replace special characters in a message id, so it can be used in an http query."
8799 (when (string-match "%" s)
8800 (setq s (mapconcat (lambda (c)
8801 (if (eq c ?%)
8802 "%25"
8803 (char-to-string c)))
8804 s "")))
8805 (while (string-match "<" s)
8806 (setq s (replace-match "%3C" t t s)))
8807 (while (string-match ">" s)
8808 (setq s (replace-match "%3E" t t s)))
8809 (while (string-match "@" s)
8810 (setq s (replace-match "%40" t t s)))
8813 ;;;###autoload
8814 (defun org-insert-link-global ()
8815 "Insert a link like Org-mode does.
8816 This command can be called in any mode to insert a link in Org-mode syntax."
8817 (interactive)
8818 (org-load-modules-maybe)
8819 (org-run-like-in-org-mode 'org-insert-link))
8821 (defun org-insert-link (&optional complete-file link-location)
8822 "Insert a link. At the prompt, enter the link.
8824 Completion can be used to insert any of the link protocol prefixes like
8825 http or ftp in use.
8827 The history can be used to select a link previously stored with
8828 `org-store-link'. When the empty string is entered (i.e. if you just
8829 press RET at the prompt), the link defaults to the most recently
8830 stored link. As SPC triggers completion in the minibuffer, you need to
8831 use M-SPC or C-q SPC to force the insertion of a space character.
8833 You will also be prompted for a description, and if one is given, it will
8834 be displayed in the buffer instead of the link.
8836 If there is already a link at point, this command will allow you to edit link
8837 and description parts.
8839 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
8840 be selected using completion. The path to the file will be relative to the
8841 current directory if the file is in the current directory or a subdirectory.
8842 Otherwise, the link will be the absolute path as completed in the minibuffer
8843 \(i.e. normally ~/path/to/file). You can configure this behavior using the
8844 option `org-link-file-path-type'.
8846 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
8847 the current directory or below.
8849 With three \\[universal-argument] prefixes, negate the meaning of
8850 `org-keep-stored-link-after-insertion'.
8852 If `org-make-link-description-function' is non-nil, this function will be
8853 called with the link target, and the result will be the default
8854 link description.
8856 If the LINK-LOCATION parameter is non-nil, this value will be
8857 used as the link location instead of reading one interactively."
8858 (interactive "P")
8859 (let* ((wcf (current-window-configuration))
8860 (region (if (org-region-active-p)
8861 (buffer-substring (region-beginning) (region-end))))
8862 (remove (and region (list (region-beginning) (region-end))))
8863 (desc region)
8864 tmphist ; byte-compile incorrectly complains about this
8865 (link link-location)
8866 entry file all-prefixes)
8867 (cond
8868 (link-location) ; specified by arg, just use it.
8869 ((org-in-regexp org-bracket-link-regexp 1)
8870 ;; We do have a link at point, and we are going to edit it.
8871 (setq remove (list (match-beginning 0) (match-end 0)))
8872 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
8873 (setq link (read-string "Link: "
8874 (org-link-unescape
8875 (org-match-string-no-properties 1)))))
8876 ((or (org-in-regexp org-angle-link-re)
8877 (org-in-regexp org-plain-link-re))
8878 ;; Convert to bracket link
8879 (setq remove (list (match-beginning 0) (match-end 0))
8880 link (read-string "Link: "
8881 (org-remove-angle-brackets (match-string 0)))))
8882 ((member complete-file '((4) (16)))
8883 ;; Completing read for file names.
8884 (setq link (org-file-complete-link complete-file)))
8886 ;; Read link, with completion for stored links.
8887 (with-output-to-temp-buffer "*Org Links*"
8888 (princ "Insert a link.
8889 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
8890 (when org-stored-links
8891 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
8892 (princ (mapconcat
8893 (lambda (x)
8894 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
8895 (reverse org-stored-links) "\n"))))
8896 (let ((cw (selected-window)))
8897 (select-window (get-buffer-window "*Org Links*" 'visible))
8898 (with-current-buffer "*Org Links*" (setq truncate-lines) t)
8899 (unless (pos-visible-in-window-p (point-max))
8900 (org-fit-window-to-buffer))
8901 (and (window-live-p cw) (select-window cw)))
8902 ;; Fake a link history, containing the stored links.
8903 (setq tmphist (append (mapcar 'car org-stored-links)
8904 org-insert-link-history))
8905 (setq all-prefixes (append (mapcar 'car org-link-abbrev-alist-local)
8906 (mapcar 'car org-link-abbrev-alist)
8907 org-link-types))
8908 (unwind-protect
8909 (progn
8910 (setq link
8911 (let ((org-completion-use-ido nil)
8912 (org-completion-use-iswitchb nil))
8913 (org-completing-read
8914 "Link: "
8915 (append
8916 (mapcar (lambda (x) (list (concat x ":")))
8917 all-prefixes)
8918 (mapcar 'car org-stored-links))
8919 nil nil nil
8920 'tmphist
8921 (car (car org-stored-links)))))
8922 (if (not (string-match "\\S-" link))
8923 (error "No link selected"))
8924 (if (or (member link all-prefixes)
8925 (and (equal ":" (substring link -1))
8926 (member (substring link 0 -1) all-prefixes)
8927 (setq link (substring link 0 -1))))
8928 (setq link (org-link-try-special-completion link))))
8929 (set-window-configuration wcf)
8930 (kill-buffer "*Org Links*"))
8931 (setq entry (assoc link org-stored-links))
8932 (or entry (push link org-insert-link-history))
8933 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
8934 (not org-keep-stored-link-after-insertion))
8935 (setq org-stored-links (delq (assoc link org-stored-links)
8936 org-stored-links)))
8937 (setq desc (or desc (nth 1 entry)))))
8939 (if (string-match org-plain-link-re link)
8940 ;; URL-like link, normalize the use of angular brackets.
8941 (setq link (org-make-link (org-remove-angle-brackets link))))
8943 ;; Check if we are linking to the current file with a search option
8944 ;; If yes, simplify the link by using only the search option.
8945 (when (and buffer-file-name
8946 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
8947 (let* ((path (match-string 1 link))
8948 (case-fold-search nil)
8949 (search (match-string 2 link)))
8950 (save-match-data
8951 (if (equal (file-truename buffer-file-name) (file-truename path))
8952 ;; We are linking to this same file, with a search option
8953 (setq link search)))))
8955 ;; Check if we can/should use a relative path. If yes, simplify the link
8956 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
8957 (let* ((type (match-string 1 link))
8958 (path (match-string 2 link))
8959 (origpath path)
8960 (case-fold-search nil))
8961 (cond
8962 ((or (eq org-link-file-path-type 'absolute)
8963 (equal complete-file '(16)))
8964 (setq path (abbreviate-file-name (expand-file-name path))))
8965 ((eq org-link-file-path-type 'noabbrev)
8966 (setq path (expand-file-name path)))
8967 ((eq org-link-file-path-type 'relative)
8968 (setq path (file-relative-name path)))
8970 (save-match-data
8971 (if (string-match (concat "^" (regexp-quote
8972 (expand-file-name
8973 (file-name-as-directory
8974 default-directory))))
8975 (expand-file-name path))
8976 ;; We are linking a file with relative path name.
8977 (setq path (substring (expand-file-name path)
8978 (match-end 0)))
8979 (setq path (abbreviate-file-name (expand-file-name path)))))))
8980 (setq link (concat type path))
8981 (if (equal desc origpath)
8982 (setq desc path))))
8984 (if org-make-link-description-function
8985 (setq desc (funcall org-make-link-description-function link desc)))
8987 (setq desc (read-string "Description: " desc))
8988 (unless (string-match "\\S-" desc) (setq desc nil))
8989 (if remove (apply 'delete-region remove))
8990 (insert (org-make-link-string link desc))))
8992 (defun org-link-try-special-completion (type)
8993 "If there is completion support for link type TYPE, offer it."
8994 (let ((fun (intern (concat "org-" type "-complete-link"))))
8995 (if (functionp fun)
8996 (funcall fun)
8997 (read-string "Link (no completion support): " (concat type ":")))))
8999 (defun org-file-complete-link (&optional arg)
9000 "Create a file link using completion."
9001 (let (file link)
9002 (setq file (read-file-name "File: "))
9003 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9004 (pwd1 (file-name-as-directory (abbreviate-file-name
9005 (expand-file-name ".")))))
9006 (cond
9007 ((equal arg '(16))
9008 (setq link (org-make-link
9009 "file:"
9010 (abbreviate-file-name (expand-file-name file)))))
9011 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9012 (setq link (org-make-link "file:" (match-string 1 file))))
9013 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9014 (expand-file-name file))
9015 (setq link (org-make-link
9016 "file:" (match-string 1 (expand-file-name file)))))
9017 (t (setq link (org-make-link "file:" file)))))
9018 link))
9020 (defun org-completing-read (&rest args)
9021 "Completing-read with SPACE being a normal character."
9022 (let ((minibuffer-local-completion-map
9023 (copy-keymap minibuffer-local-completion-map)))
9024 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
9025 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
9026 (apply 'org-icompleting-read args)))
9028 (defun org-completing-read-no-i (&rest args)
9029 (let (org-completion-use-ido org-completion-use-iswitchb)
9030 (apply 'org-completing-read args)))
9032 (defun org-iswitchb-completing-read (prompt choices &rest args)
9033 "Use iswitch as a completing-read replacement to choose from choices.
9034 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
9035 from."
9036 (let* ((iswitchb-use-virtual-buffers nil)
9037 (iswitchb-make-buflist-hook
9038 (lambda ()
9039 (setq iswitchb-temp-buflist choices))))
9040 (iswitchb-read-buffer prompt)))
9042 (defun org-icompleting-read (&rest args)
9043 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
9044 (org-without-partial-completion
9045 (if (and org-completion-use-ido
9046 (fboundp 'ido-completing-read)
9047 (boundp 'ido-mode) ido-mode
9048 (listp (second args)))
9049 (let ((ido-enter-matching-directory nil))
9050 (apply 'ido-completing-read (concat (car args))
9051 (if (consp (car (nth 1 args)))
9052 (mapcar 'car (nth 1 args))
9053 (nth 1 args))
9054 (cddr args)))
9055 (if (and org-completion-use-iswitchb
9056 (boundp 'iswitchb-mode) iswitchb-mode
9057 (listp (second args)))
9058 (apply 'org-iswitchb-completing-read (concat (car args))
9059 (if (consp (car (nth 1 args)))
9060 (mapcar 'car (nth 1 args))
9061 (nth 1 args))
9062 (cddr args))
9063 (apply 'completing-read args)))))
9065 (defun org-extract-attributes (s)
9066 "Extract the attributes cookie from a string and set as text property."
9067 (let (a attr (start 0) key value)
9068 (save-match-data
9069 (when (string-match "{{\\([^}]+\\)}}$" s)
9070 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
9071 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
9072 (setq key (match-string 1 a) value (match-string 2 a)
9073 start (match-end 0)
9074 attr (plist-put attr (intern key) value))))
9075 (org-add-props s nil 'org-attr attr))
9078 (defun org-extract-attributes-from-string (tag)
9079 (let (key value attr)
9080 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
9081 (setq key (match-string 1 tag) value (match-string 2 tag)
9082 tag (replace-match "" t t tag)
9083 attr (plist-put attr (intern key) value)))
9084 (cons tag attr)))
9086 (defun org-attributes-to-string (plist)
9087 "Format a property list into an HTML attribute list."
9088 (let ((s "") key value)
9089 (while plist
9090 (setq key (pop plist) value (pop plist))
9091 (and value
9092 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
9095 ;;; Opening/following a link
9097 (defvar org-link-search-failed nil)
9099 (defvar org-open-link-functions nil
9100 "Hook for functions finding a plain text link.
9101 These functions must take a single argument, the link content.
9102 They will be called for links that look like [[link text][description]]
9103 when LINK TEXT does not have a protocol like \"http:\" and does not look
9104 like a filename (e.g. \"./blue.png\").
9106 These functions will be called *before* Org attempts to resolve the
9107 link by doing text searches in the current buffer - so if you want a
9108 link \"[[target]]\" to still find \"<<target>>\", your function should
9109 handle this as a special case.
9111 When the function does handle the link, it must return a non-nil value.
9112 If it decides that it is not responsible for this link, it must return
9113 nil to indicate that that Org-mode can continue with other options
9114 like exact and fuzzy text search.")
9116 (defun org-next-link ()
9117 "Move forward to the next link.
9118 If the link is in hidden text, expose it."
9119 (interactive)
9120 (when (and org-link-search-failed (eq this-command last-command))
9121 (goto-char (point-min))
9122 (message "Link search wrapped back to beginning of buffer"))
9123 (setq org-link-search-failed nil)
9124 (let* ((pos (point))
9125 (ct (org-context))
9126 (a (assoc :link ct)))
9127 (if a (goto-char (nth 2 a)))
9128 (if (re-search-forward org-any-link-re nil t)
9129 (progn
9130 (goto-char (match-beginning 0))
9131 (if (outline-invisible-p) (org-show-context)))
9132 (goto-char pos)
9133 (setq org-link-search-failed t)
9134 (error "No further link found"))))
9136 (defun org-previous-link ()
9137 "Move backward to the previous link.
9138 If the link is in hidden text, expose it."
9139 (interactive)
9140 (when (and org-link-search-failed (eq this-command last-command))
9141 (goto-char (point-max))
9142 (message "Link search wrapped back to end of buffer"))
9143 (setq org-link-search-failed nil)
9144 (let* ((pos (point))
9145 (ct (org-context))
9146 (a (assoc :link ct)))
9147 (if a (goto-char (nth 1 a)))
9148 (if (re-search-backward org-any-link-re nil t)
9149 (progn
9150 (goto-char (match-beginning 0))
9151 (if (outline-invisible-p) (org-show-context)))
9152 (goto-char pos)
9153 (setq org-link-search-failed t)
9154 (error "No further link found"))))
9156 (defun org-translate-link (s)
9157 "Translate a link string if a translation function has been defined."
9158 (if (and org-link-translation-function
9159 (fboundp org-link-translation-function)
9160 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
9161 (progn
9162 (setq s (funcall org-link-translation-function
9163 (match-string 1) (match-string 2)))
9164 (concat (car s) ":" (cdr s)))
9167 (defun org-translate-link-from-planner (type path)
9168 "Translate a link from Emacs Planner syntax so that Org can follow it.
9169 This is still an experimental function, your mileage may vary."
9170 (cond
9171 ((member type '("http" "https" "news" "ftp"))
9172 ;; standard Internet links are the same.
9173 nil)
9174 ((and (equal type "irc") (string-match "^//" path))
9175 ;; Planner has two / at the beginning of an irc link, we have 1.
9176 ;; We should have zero, actually....
9177 (setq path (substring path 1)))
9178 ((and (equal type "lisp") (string-match "^/" path))
9179 ;; Planner has a slash, we do not.
9180 (setq type "elisp" path (substring path 1)))
9181 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9182 ;; A typical message link. Planner has the id after the final slash,
9183 ;; we separate it with a hash mark
9184 (setq path (concat (match-string 1 path) "#"
9185 (org-remove-angle-brackets (match-string 2 path)))))
9187 (cons type path))
9189 (defun org-find-file-at-mouse (ev)
9190 "Open file link or URL at mouse."
9191 (interactive "e")
9192 (mouse-set-point ev)
9193 (org-open-at-point 'in-emacs))
9195 (defun org-open-at-mouse (ev)
9196 "Open file link or URL at mouse."
9197 (interactive "e")
9198 (mouse-set-point ev)
9199 (if (eq major-mode 'org-agenda-mode)
9200 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
9201 (org-open-at-point))
9203 (defvar org-window-config-before-follow-link nil
9204 "The window configuration before following a link.
9205 This is saved in case the need arises to restore it.")
9207 (defvar org-open-link-marker (make-marker)
9208 "Marker pointing to the location where `org-open-at-point; was called.")
9210 ;;;###autoload
9211 (defun org-open-at-point-global ()
9212 "Follow a link like Org-mode does.
9213 This command can be called in any mode to follow a link that has
9214 Org-mode syntax."
9215 (interactive)
9216 (org-run-like-in-org-mode 'org-open-at-point))
9218 ;;;###autoload
9219 (defun org-open-link-from-string (s &optional arg reference-buffer)
9220 "Open a link in the string S, as if it was in Org-mode."
9221 (interactive "sLink: \nP")
9222 (let ((reference-buffer (or reference-buffer (current-buffer))))
9223 (with-temp-buffer
9224 (let ((org-inhibit-startup t))
9225 (org-mode)
9226 (insert s)
9227 (goto-char (point-min))
9228 (when reference-buffer
9229 (setq org-link-abbrev-alist-local
9230 (with-current-buffer reference-buffer
9231 org-link-abbrev-alist-local)))
9232 (org-open-at-point arg reference-buffer)))))
9234 (defvar org-open-at-point-functions nil
9235 "Hook that is run when following a link at point.
9237 Functions in this hook must return t if they identify and follow
9238 a link at point. If they don't find anything interesting at point,
9239 they must return nil.")
9241 (defun org-open-at-point (&optional arg reference-buffer)
9242 "Open link at or after point.
9243 If there is no link at point, this function will search forward up to
9244 the end of the current line.
9245 Normally, files will be opened by an appropriate application. If the
9246 optional prefix argument ARG is non-nil, Emacs will visit the file.
9247 With a double prefix argument, try to open outside of Emacs, in the
9248 application the system uses for this file type."
9249 (interactive "P")
9250 ;; if in a code block, then open the block's results
9251 (unless (call-interactively #'org-babel-open-src-block-result)
9252 (org-load-modules-maybe)
9253 (move-marker org-open-link-marker (point))
9254 (setq org-window-config-before-follow-link (current-window-configuration))
9255 (org-remove-occur-highlights nil nil t)
9256 (cond
9257 ((and (org-on-heading-p)
9258 (not (org-in-regexp
9259 (concat org-plain-link-re "\\|"
9260 org-bracket-link-regexp "\\|"
9261 org-angle-link-re "\\|"
9262 "[ \t]:[^ \t\n]+:[ \t]*$")))
9263 (not (get-text-property (point) 'org-linked-text)))
9264 (or (org-offer-links-in-entry arg)
9265 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
9266 ((run-hook-with-args-until-success 'org-open-at-point-functions))
9267 ((org-at-timestamp-p t) (org-follow-timestamp-link))
9268 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
9269 (not (org-in-regexp org-bracket-link-regexp)))
9270 (org-footnote-action))
9272 (let (type path link line search (pos (point)))
9273 (catch 'match
9274 (save-excursion
9275 (skip-chars-forward "^]\n\r")
9276 (when (org-in-regexp org-bracket-link-regexp 1)
9277 (setq link (org-extract-attributes
9278 (org-link-unescape (org-match-string-no-properties 1))))
9279 (while (string-match " *\n *" link)
9280 (setq link (replace-match " " t t link)))
9281 (setq link (org-link-expand-abbrev link))
9282 (cond
9283 ((or (file-name-absolute-p link)
9284 (string-match "^\\.\\.?/" link))
9285 (setq type "file" path link))
9286 ((string-match org-link-re-with-space3 link)
9287 (setq type (match-string 1 link) path (match-string 2 link)))
9288 (t (setq type "thisfile" path link)))
9289 (throw 'match t)))
9291 (when (get-text-property (point) 'org-linked-text)
9292 (setq type "thisfile"
9293 pos (if (get-text-property (1+ (point)) 'org-linked-text)
9294 (1+ (point)) (point))
9295 path (buffer-substring
9296 (or (previous-single-property-change pos 'org-linked-text)
9297 (point-min))
9298 (or (next-single-property-change pos 'org-linked-text)
9299 (point-max))))
9300 (throw 'match t))
9302 (save-excursion
9303 (when (or (org-in-regexp org-angle-link-re)
9304 (org-in-regexp org-plain-link-re))
9305 (setq type (match-string 1) path (match-string 2))
9306 (throw 'match t)))
9307 (save-excursion
9308 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
9309 (setq type "tags"
9310 path (match-string 1))
9311 (while (string-match ":" path)
9312 (setq path (replace-match "+" t t path)))
9313 (throw 'match t)))
9314 (when (org-in-regexp "<\\([^><\n]+\\)>")
9315 (setq type "tree-match"
9316 path (match-string 1))
9317 (throw 'match t)))
9318 (unless path
9319 (error "No link found"))
9321 ;; switch back to reference buffer
9322 ;; needed when if called in a temporary buffer through
9323 ;; org-open-link-from-string
9324 (with-current-buffer (or reference-buffer (current-buffer))
9326 ;; Remove any trailing spaces in path
9327 (if (string-match " +\\'" path)
9328 (setq path (replace-match "" t t path)))
9329 (if (and org-link-translation-function
9330 (fboundp org-link-translation-function))
9331 ;; Check if we need to translate the link
9332 (let ((tmp (funcall org-link-translation-function type path)))
9333 (setq type (car tmp) path (cdr tmp))))
9335 (cond
9337 ((assoc type org-link-protocols)
9338 (funcall (nth 1 (assoc type org-link-protocols)) path))
9340 ((equal type "mailto")
9341 (let ((cmd (car org-link-mailto-program))
9342 (args (cdr org-link-mailto-program)) args1
9343 (address path) (subject "") a)
9344 (if (string-match "\\(.*\\)::\\(.*\\)" path)
9345 (setq address (match-string 1 path)
9346 subject (org-link-escape (match-string 2 path))))
9347 (while args
9348 (cond
9349 ((not (stringp (car args))) (push (pop args) args1))
9350 (t (setq a (pop args))
9351 (if (string-match "%a" a)
9352 (setq a (replace-match address t t a)))
9353 (if (string-match "%s" a)
9354 (setq a (replace-match subject t t a)))
9355 (push a args1))))
9356 (apply cmd (nreverse args1))))
9358 ((member type '("http" "https" "ftp" "news"))
9359 (browse-url (concat type ":" (org-link-escape
9360 path org-link-escape-chars-browser))))
9362 ((string= type "doi")
9363 (browse-url (concat "http://dx.doi.org/"
9364 (org-link-escape
9365 path org-link-escape-chars-browser))))
9367 ((member type '("message"))
9368 (browse-url (concat type ":" path)))
9370 ((string= type "tags")
9371 (org-tags-view arg path))
9373 ((string= type "tree-match")
9374 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
9376 ((string= type "file")
9377 (if (string-match "::\\([0-9]+\\)\\'" path)
9378 (setq line (string-to-number (match-string 1 path))
9379 path (substring path 0 (match-beginning 0)))
9380 (if (string-match "::\\(.+\\)\\'" path)
9381 (setq search (match-string 1 path)
9382 path (substring path 0 (match-beginning 0)))))
9383 (if (string-match "[*?{]" (file-name-nondirectory path))
9384 (dired path)
9385 (org-open-file path arg line search)))
9387 ((string= type "shell")
9388 (let ((cmd path))
9389 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
9390 (string-match org-confirm-shell-link-not-regexp cmd))
9391 (not org-confirm-shell-link-function)
9392 (funcall org-confirm-shell-link-function
9393 (format "Execute \"%s\" in shell? "
9394 (org-add-props cmd nil
9395 'face 'org-warning))))
9396 (progn
9397 (message "Executing %s" cmd)
9398 (shell-command cmd))
9399 (error "Abort"))))
9401 ((string= type "elisp")
9402 (let ((cmd path))
9403 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
9404 (string-match org-confirm-elisp-link-not-regexp cmd))
9405 (not org-confirm-elisp-link-function)
9406 (funcall org-confirm-elisp-link-function
9407 (format "Execute \"%s\" as elisp? "
9408 (org-add-props cmd nil
9409 'face 'org-warning))))
9410 (message "%s => %s" cmd
9411 (if (equal (string-to-char cmd) ?\()
9412 (eval (read cmd))
9413 (call-interactively (read cmd))))
9414 (error "Abort"))))
9416 ((and (string= type "thisfile")
9417 (run-hook-with-args-until-success
9418 'org-open-link-functions path)))
9420 ((string= type "thisfile")
9421 (if arg
9422 (switch-to-buffer-other-window
9423 (org-get-buffer-for-internal-link (current-buffer)))
9424 (org-mark-ring-push))
9425 (let ((cmd `(org-link-search
9426 ,path
9427 ,(cond ((equal arg '(4)) ''occur)
9428 ((equal arg '(16)) ''org-occur)
9429 (t nil))
9430 ,pos)))
9431 (condition-case nil (eval cmd)
9432 (error (progn (widen) (eval cmd))))))
9435 (browse-url-at-point)))))))
9436 (move-marker org-open-link-marker nil)
9437 (run-hook-with-args 'org-follow-link-hook)))
9439 (defun org-offer-links-in-entry (&optional nth zero)
9440 "Offer links in the current entry and follow the selected link.
9441 If there is only one link, follow it immediately as well.
9442 If NTH is an integer, immediately pick the NTH link found.
9443 If ZERO is a string, check also this string for a link, and if
9444 there is one, offer it as link number zero."
9445 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
9446 "\\(" org-angle-link-re "\\)\\|"
9447 "\\(" org-plain-link-re "\\)"))
9448 (cnt ?0)
9449 (in-emacs (if (integerp nth) nil nth))
9450 have-zero end links link c)
9451 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
9452 (push (match-string 0 zero) links)
9453 (setq cnt (1- cnt) have-zero t))
9454 (save-excursion
9455 (org-back-to-heading t)
9456 (setq end (save-excursion (outline-next-heading) (point)))
9457 (while (re-search-forward re end t)
9458 (push (match-string 0) links))
9459 (setq links (org-uniquify (reverse links))))
9461 (cond
9462 ((null links)
9463 (message "No links"))
9464 ((equal (length links) 1)
9465 (setq link (list (car links))))
9466 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
9467 (setq link (nth (if have-zero nth (1- nth)) links)))
9468 (t ; we have to select a link
9469 (save-excursion
9470 (save-window-excursion
9471 (delete-other-windows)
9472 (with-output-to-temp-buffer "*Select Link*"
9473 (mapc (lambda (l)
9474 (if (not (string-match org-bracket-link-regexp l))
9475 (princ (format "[%c] %s\n" (incf cnt)
9476 (org-remove-angle-brackets l)))
9477 (if (match-end 3)
9478 (princ (format "[%c] %s (%s)\n" (incf cnt)
9479 (match-string 3 l) (match-string 1 l)))
9480 (princ (format "[%c] %s\n" (incf cnt)
9481 (match-string 1 l))))))
9482 links))
9483 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
9484 (message "Select link to open, RET to open all:")
9485 (setq c (read-char-exclusive))
9486 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
9487 (when (equal c ?q) (error "Abort"))
9488 (if (equal c ?\C-m)
9489 (setq link links)
9490 (setq nth (- c ?0))
9491 (if have-zero (setq nth (1+ nth)))
9492 (unless (and (integerp nth) (>= (length links) nth))
9493 (error "Invalid link selection"))
9494 (setq link (list (nth (1- nth) links))))))
9495 (if link
9496 (let ((buf (current-buffer)))
9497 (dolist (l link)
9498 (org-open-link-from-string l in-emacs buf))
9500 nil)))
9502 ;; Add special file links that specify the way of opening
9504 (org-add-link-type "file+sys" 'org-open-file-with-system)
9505 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
9506 (defun org-open-file-with-system (path)
9507 "Open file at PATH using the system way of opening it."
9508 (org-open-file path 'system))
9509 (defun org-open-file-with-emacs (path)
9510 "Open file at PATH in Emacs."
9511 (org-open-file path 'emacs))
9512 (defun org-remove-file-link-modifiers ()
9513 "Remove the file link modifiers in `file+sys:' and `file+emacs:' links."
9514 (goto-char (point-min))
9515 (while (re-search-forward "\\<file\\+\\(sys\\|emacs\\):" nil t)
9516 (org-if-unprotected
9517 (replace-match "file:" t t))))
9518 (eval-after-load "org-exp"
9519 '(add-hook 'org-export-preprocess-before-normalizing-links-hook
9520 'org-remove-file-link-modifiers))
9522 ;;;; Time estimates
9524 (defun org-get-effort (&optional pom)
9525 "Get the effort estimate for the current entry."
9526 (org-entry-get pom org-effort-property))
9528 ;;; File search
9530 (defvar org-create-file-search-functions nil
9531 "List of functions to construct the right search string for a file link.
9532 These functions are called in turn with point at the location to
9533 which the link should point.
9535 A function in the hook should first test if it would like to
9536 handle this file type, for example by checking the `major-mode'
9537 or the file extension. If it decides not to handle this file, it
9538 should just return nil to give other functions a chance. If it
9539 does handle the file, it must return the search string to be used
9540 when following the link. The search string will be part of the
9541 file link, given after a double colon, and `org-open-at-point'
9542 will automatically search for it. If special measures must be
9543 taken to make the search successful, another function should be
9544 added to the companion hook `org-execute-file-search-functions',
9545 which see.
9547 A function in this hook may also use `setq' to set the variable
9548 `description' to provide a suggestion for the descriptive text to
9549 be used for this link when it gets inserted into an Org-mode
9550 buffer with \\[org-insert-link].")
9552 (defvar org-execute-file-search-functions nil
9553 "List of functions to execute a file search triggered by a link.
9555 Functions added to this hook must accept a single argument, the
9556 search string that was part of the file link, the part after the
9557 double colon. The function must first check if it would like to
9558 handle this search, for example by checking the `major-mode' or
9559 the file extension. If it decides not to handle this search, it
9560 should just return nil to give other functions a chance. If it
9561 does handle the search, it must return a non-nil value to keep
9562 other functions from trying.
9564 Each function can access the current prefix argument through the
9565 variable `current-prefix-argument'. Note that a single prefix is
9566 used to force opening a link in Emacs, so it may be good to only
9567 use a numeric or double prefix to guide the search function.
9569 In case this is needed, a function in this hook can also restore
9570 the window configuration before `org-open-at-point' was called using:
9572 (set-window-configuration org-window-config-before-follow-link)")
9574 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
9575 (defun org-link-search (s &optional type avoid-pos)
9576 "Search for a link search option.
9577 If S is surrounded by forward slashes, it is interpreted as a
9578 regular expression. In org-mode files, this will create an `org-occur'
9579 sparse tree. In ordinary files, `occur' will be used to list matches.
9580 If the current buffer is in `dired-mode', grep will be used to search
9581 in all files. If AVOID-POS is given, ignore matches near that position."
9582 (let ((case-fold-search t)
9583 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
9584 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
9585 (append '(("") (" ") ("\t") ("\n"))
9586 org-emphasis-alist)
9587 "\\|") "\\)"))
9588 (pos (point))
9589 (pre nil) (post nil)
9590 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
9591 (cond
9592 ;; First check if there are any special search functions
9593 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
9594 ;; Now try the builtin stuff
9595 ((and (equal (string-to-char s0) ?#)
9596 (> (length s0) 1)
9597 (save-excursion
9598 (goto-char (point-min))
9599 (and
9600 (re-search-forward
9601 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
9602 (setq type 'dedicated
9603 pos (match-beginning 0))))
9604 ;; There is an exact target for this
9605 (goto-char pos)
9606 (org-back-to-heading t)))
9607 ((save-excursion
9608 (goto-char (point-min))
9609 (and
9610 (re-search-forward
9611 (concat "<<" (regexp-quote s0) ">>") nil t)
9612 (setq type 'dedicated
9613 pos (match-beginning 0))))
9614 ;; There is an exact target for this
9615 (goto-char pos))
9616 ((and (string-match "^(\\(.*\\))$" s0)
9617 (save-excursion
9618 (goto-char (point-min))
9619 (and
9620 (re-search-forward
9621 (concat "[^[]" (regexp-quote
9622 (format org-coderef-label-format
9623 (match-string 1 s0))))
9624 nil t)
9625 (setq type 'dedicated
9626 pos (1+ (match-beginning 0))))))
9627 ;; There is a coderef target for this
9628 (goto-char pos))
9629 ((string-match "^/\\(.*\\)/$" s)
9630 ;; A regular expression
9631 (cond
9632 ((org-mode-p)
9633 (org-occur (match-string 1 s)))
9634 ;;((eq major-mode 'dired-mode)
9635 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
9636 (t (org-do-occur (match-string 1 s)))))
9637 ((and (org-mode-p) org-link-search-must-match-exact-headline)
9638 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
9639 (goto-char (point-min))
9640 (cond
9641 ((let (case-fold-search)
9642 (re-search-forward (format org-complex-heading-regexp-format
9643 (regexp-quote s))
9644 nil t))
9645 ;; OK, found a match
9646 (setq type 'dedicated)
9647 (goto-char (match-beginning 0)))
9648 ((and (not org-link-search-inhibit-query)
9649 (eq org-link-search-must-match-exact-headline 'query-to-create)
9650 (y-or-n-p "No match - create this as a new heading? "))
9651 (goto-char (point-max))
9652 (or (bolp) (newline))
9653 (insert "* " s "\n")
9654 (beginning-of-line 0))
9656 (goto-char pos)
9657 (error "No match"))))
9659 ;; A normal search string
9660 (when (equal (string-to-char s) ?*)
9661 ;; Anchor on headlines, post may include tags.
9662 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
9663 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
9664 s (substring s 1)))
9665 (remove-text-properties
9666 0 (length s)
9667 '(face nil mouse-face nil keymap nil fontified nil) s)
9668 ;; Make a series of regular expressions to find a match
9669 (setq words (org-split-string s "[ \n\r\t]+")
9671 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
9672 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
9673 "\\)" markers)
9674 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
9675 re2a (concat "[ \t\r\n]" re2a_)
9676 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
9677 re4 (concat "[^a-zA-Z_]" re4_)
9679 re1 (concat pre re2 post)
9680 re3 (concat pre (if pre re4_ re4) post)
9681 re5 (concat pre ".*" re4)
9682 re2 (concat pre re2)
9683 re2a (concat pre (if pre re2a_ re2a))
9684 re4 (concat pre (if pre re4_ re4))
9685 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
9686 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
9687 re5 "\\)"
9689 (cond
9690 ((eq type 'org-occur) (org-occur reall))
9691 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
9692 (t (goto-char (point-min))
9693 (setq type 'fuzzy)
9694 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
9695 (org-search-not-self 1 re1 nil t)
9696 (org-search-not-self 1 re2 nil t)
9697 (org-search-not-self 1 re2a nil t)
9698 (org-search-not-self 1 re3 nil t)
9699 (org-search-not-self 1 re4 nil t)
9700 (org-search-not-self 1 re5 nil t)
9702 (goto-char (match-beginning 1))
9703 (goto-char pos)
9704 (error "No match"))))))
9705 (and (org-mode-p) (org-show-context 'link-search))
9706 type))
9708 (defun org-search-not-self (group &rest args)
9709 "Execute `re-search-forward', but only accept matches that do not
9710 enclose the position of `org-open-link-marker'."
9711 (let ((m org-open-link-marker))
9712 (catch 'exit
9713 (while (apply 're-search-forward args)
9714 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
9715 (goto-char (match-end group))
9716 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
9717 (> (match-beginning 0) (marker-position m))
9718 (< (match-end 0) (marker-position m)))
9719 (save-match-data
9720 (or (not (org-in-regexp
9721 org-bracket-link-analytic-regexp 1))
9722 (not (match-end 4)) ; no description
9723 (and (<= (match-beginning 4) (point))
9724 (>= (match-end 4) (point))))))
9725 (throw 'exit (point))))))))
9727 (defun org-get-buffer-for-internal-link (buffer)
9728 "Return a buffer to be used for displaying the link target of internal links."
9729 (cond
9730 ((not org-display-internal-link-with-indirect-buffer)
9731 buffer)
9732 ((string-match "(Clone)$" (buffer-name buffer))
9733 (message "Buffer is already a clone, not making another one")
9734 ;; we also do not modify visibility in this case
9735 buffer)
9736 (t ; make a new indirect buffer for displaying the link
9737 (let* ((bn (buffer-name buffer))
9738 (ibn (concat bn "(Clone)"))
9739 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
9740 (with-current-buffer ib (org-overview))
9741 ib))))
9743 (defun org-do-occur (regexp &optional cleanup)
9744 "Call the Emacs command `occur'.
9745 If CLEANUP is non-nil, remove the printout of the regular expression
9746 in the *Occur* buffer. This is useful if the regex is long and not useful
9747 to read."
9748 (occur regexp)
9749 (when cleanup
9750 (let ((cwin (selected-window)) win beg end)
9751 (when (setq win (get-buffer-window "*Occur*"))
9752 (select-window win))
9753 (goto-char (point-min))
9754 (when (re-search-forward "match[a-z]+" nil t)
9755 (setq beg (match-end 0))
9756 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
9757 (setq end (1- (match-beginning 0)))))
9758 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
9759 (goto-char (point-min))
9760 (select-window cwin))))
9762 ;;; The mark ring for links jumps
9764 (defvar org-mark-ring nil
9765 "Mark ring for positions before jumps in Org-mode.")
9766 (defvar org-mark-ring-last-goto nil
9767 "Last position in the mark ring used to go back.")
9768 ;; Fill and close the ring
9769 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
9770 (loop for i from 1 to org-mark-ring-length do
9771 (push (make-marker) org-mark-ring))
9772 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
9773 org-mark-ring)
9775 (defun org-mark-ring-push (&optional pos buffer)
9776 "Put the current position or POS into the mark ring and rotate it."
9777 (interactive)
9778 (setq pos (or pos (point)))
9779 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
9780 (move-marker (car org-mark-ring)
9781 (or pos (point))
9782 (or buffer (current-buffer)))
9783 (message "%s"
9784 (substitute-command-keys
9785 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
9787 (defun org-mark-ring-goto (&optional n)
9788 "Jump to the previous position in the mark ring.
9789 With prefix arg N, jump back that many stored positions. When
9790 called several times in succession, walk through the entire ring.
9791 Org-mode commands jumping to a different position in the current file,
9792 or to another Org-mode file, automatically push the old position
9793 onto the ring."
9794 (interactive "p")
9795 (let (p m)
9796 (if (eq last-command this-command)
9797 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
9798 (setq p org-mark-ring))
9799 (setq org-mark-ring-last-goto p)
9800 (setq m (car p))
9801 (switch-to-buffer (marker-buffer m))
9802 (goto-char m)
9803 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
9805 (defun org-remove-angle-brackets (s)
9806 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
9807 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
9809 (defun org-add-angle-brackets (s)
9810 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
9811 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
9813 (defun org-remove-double-quotes (s)
9814 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
9815 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
9818 ;;; Following specific links
9820 (defun org-follow-timestamp-link ()
9821 (cond
9822 ((org-at-date-range-p t)
9823 (let ((org-agenda-start-on-weekday)
9824 (t1 (match-string 1))
9825 (t2 (match-string 2)))
9826 (setq t1 (time-to-days (org-time-string-to-time t1))
9827 t2 (time-to-days (org-time-string-to-time t2)))
9828 (org-agenda-list nil t1 (1+ (- t2 t1)))))
9829 ((org-at-timestamp-p t)
9830 (org-agenda-list nil (time-to-days (org-time-string-to-time
9831 (substring (match-string 1) 0 10)))
9833 (t (error "This should not happen"))))
9836 ;;; Following file links
9837 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
9838 (declare-function mailcap-extension-to-mime "mailcap" (extn))
9839 (declare-function mailcap-mime-info
9840 "mailcap" (string &optional request no-decode))
9841 (defvar org-wait nil)
9842 (defun org-open-file (path &optional in-emacs line search)
9843 "Open the file at PATH.
9844 First, this expands any special file name abbreviations. Then the
9845 configuration variable `org-file-apps' is checked if it contains an
9846 entry for this file type, and if yes, the corresponding command is launched.
9848 If no application is found, Emacs simply visits the file.
9850 With optional prefix argument IN-EMACS, Emacs will visit the file.
9851 With a double \\[universal-argument] \\[universal-argument] \
9852 prefix arg, Org tries to avoid opening in Emacs
9853 and to use an external application to visit the file.
9855 Optional LINE specifies a line to go to, optional SEARCH a string
9856 to search for. If LINE or SEARCH is given, the file will be
9857 opened in Emacs, unless an entry from org-file-apps that makes
9858 use of groups in a regexp matches.
9859 If the file does not exist, an error is thrown."
9860 (let* ((file (if (equal path "")
9861 buffer-file-name
9862 (substitute-in-file-name (expand-file-name path))))
9863 (file-apps (append org-file-apps (org-default-apps)))
9864 (apps (org-remove-if
9865 'org-file-apps-entry-match-against-dlink-p file-apps))
9866 (apps-dlink (org-remove-if-not
9867 'org-file-apps-entry-match-against-dlink-p file-apps))
9868 (remp (and (assq 'remote apps) (org-file-remote-p file)))
9869 (dirp (if remp nil (file-directory-p file)))
9870 (file (if (and dirp org-open-directory-means-index-dot-org)
9871 (concat (file-name-as-directory file) "index.org")
9872 file))
9873 (a-m-a-p (assq 'auto-mode apps))
9874 (dfile (downcase file))
9875 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
9876 (link (cond ((and (eq line nil)
9877 (eq search nil))
9878 file)
9879 (line
9880 (concat file "::" (number-to-string line)))
9881 (search
9882 (concat file "::" search))))
9883 (dlink (downcase link))
9884 (old-buffer (current-buffer))
9885 (old-pos (point))
9886 (old-mode major-mode)
9887 ext cmd link-match-data)
9888 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
9889 (setq ext (match-string 1 dfile))
9890 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
9891 (setq ext (match-string 1 dfile))))
9892 (cond
9893 ((member in-emacs '((16) system))
9894 (setq cmd (cdr (assoc 'system apps))))
9895 (in-emacs (setq cmd 'emacs))
9897 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
9898 (and dirp (cdr (assoc 'directory apps)))
9899 ; first, try matching against apps-dlink
9900 ; if we get a match here, store the match data for later
9901 (let ((match (assoc-default dlink apps-dlink
9902 'string-match)))
9903 (if match
9904 (progn (setq link-match-data (match-data))
9905 match)
9906 (progn (setq in-emacs (or in-emacs line search))
9907 nil))) ; if we have no match in apps-dlink,
9908 ; always open the file in emacs if line or search
9909 ; is given (for backwards compatibility)
9910 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
9911 'string-match)
9912 (cdr (assoc ext apps))
9913 (cdr (assoc t apps))))))
9914 (when (eq cmd 'system)
9915 (setq cmd (cdr (assoc 'system apps))))
9916 (when (eq cmd 'default)
9917 (setq cmd (cdr (assoc t apps))))
9918 (when (eq cmd 'mailcap)
9919 (require 'mailcap)
9920 (mailcap-parse-mailcaps)
9921 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
9922 (command (mailcap-mime-info mime-type)))
9923 (if (stringp command)
9924 (setq cmd command)
9925 (setq cmd 'emacs))))
9926 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
9927 (not (file-exists-p file))
9928 (not org-open-non-existing-files))
9929 (error "No such file: %s" file))
9930 (cond
9931 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
9932 ;; Remove quotes around the file name - we'll use shell-quote-argument.
9933 (while (string-match "['\"]%s['\"]" cmd)
9934 (setq cmd (replace-match "%s" t t cmd)))
9935 (while (string-match "%s" cmd)
9936 (setq cmd (replace-match
9937 (save-match-data
9938 (shell-quote-argument
9939 (convert-standard-filename file)))
9940 t t cmd)))
9942 ;; Replace "%1", "%2" etc. in command with group matches from regex
9943 (save-match-data
9944 (let ((match-index 1)
9945 (number-of-groups (- (/ (length link-match-data) 2) 1)))
9946 (set-match-data link-match-data)
9947 (while (<= match-index number-of-groups)
9948 (let ((regex (concat "%" (number-to-string match-index)))
9949 (replace-with (match-string match-index dlink)))
9950 (while (string-match regex cmd)
9951 (setq cmd (replace-match replace-with t t cmd))))
9952 (setq match-index (+ match-index 1)))))
9954 (save-window-excursion
9955 (start-process-shell-command cmd nil cmd)
9956 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
9958 ((or (stringp cmd)
9959 (eq cmd 'emacs))
9960 (funcall (cdr (assq 'file org-link-frame-setup)) file)
9961 (widen)
9962 (if line (org-goto-line line)
9963 (if search (org-link-search search))))
9964 ((consp cmd)
9965 (let ((file (convert-standard-filename file)))
9966 (save-match-data
9967 (set-match-data link-match-data)
9968 (eval cmd))))
9969 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
9970 (and (org-mode-p) (eq old-mode 'org-mode)
9971 (or (not (equal old-buffer (current-buffer)))
9972 (not (equal old-pos (point))))
9973 (org-mark-ring-push old-pos old-buffer))))
9975 (defun org-file-apps-entry-match-against-dlink-p (entry)
9976 "This function returns non-nil if `entry' uses a regular
9977 expression which should be matched against the whole link by
9978 org-open-file.
9980 It assumes that is the case when the entry uses a regular
9981 expression which has at least one grouping construct and the
9982 action is either a lisp form or a command string containing
9983 '%1', i.e. using at least one subexpression match as a
9984 parameter."
9985 (let ((selector (car entry))
9986 (action (cdr entry)))
9987 (if (stringp selector)
9988 (and (> (regexp-opt-depth selector) 0)
9989 (or (and (stringp action)
9990 (string-match "%[0-9]" action))
9991 (consp action)))
9992 nil)))
9994 (defun org-default-apps ()
9995 "Return the default applications for this operating system."
9996 (cond
9997 ((eq system-type 'darwin)
9998 org-file-apps-defaults-macosx)
9999 ((eq system-type 'windows-nt)
10000 org-file-apps-defaults-windowsnt)
10001 (t org-file-apps-defaults-gnu)))
10003 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10004 "Convert extensions to regular expressions in the cars of LIST.
10005 Also, weed out any non-string entries, because the return value is used
10006 only for regexp matching.
10007 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10008 point to the symbol `emacs', indicating that the file should
10009 be opened in Emacs."
10010 (append
10011 (delq nil
10012 (mapcar (lambda (x)
10013 (if (not (stringp (car x)))
10015 (if (string-match "\\W" (car x))
10017 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10018 list))
10019 (if add-auto-mode
10020 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10022 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10023 (defun org-file-remote-p (file)
10024 "Test whether FILE specifies a location on a remote system.
10025 Return non-nil if the location is indeed remote.
10027 For example, the filename \"/user@host:/foo\" specifies a location
10028 on the system \"/user@host:\"."
10029 (cond ((fboundp 'file-remote-p)
10030 (file-remote-p file))
10031 ((fboundp 'tramp-handle-file-remote-p)
10032 (tramp-handle-file-remote-p file))
10033 ((and (boundp 'ange-ftp-name-format)
10034 (string-match (car ange-ftp-name-format) file))
10036 (t nil)))
10039 ;;;; Refiling
10041 (defun org-get-org-file ()
10042 "Read a filename, with default directory `org-directory'."
10043 (let ((default (or org-default-notes-file remember-data-file)))
10044 (read-file-name (format "File name [%s]: " default)
10045 (file-name-as-directory org-directory)
10046 default)))
10048 (defun org-notes-order-reversed-p ()
10049 "Check if the current file should receive notes in reversed order."
10050 (cond
10051 ((not org-reverse-note-order) nil)
10052 ((eq t org-reverse-note-order) t)
10053 ((not (listp org-reverse-note-order)) nil)
10054 (t (catch 'exit
10055 (let ((all org-reverse-note-order)
10056 entry)
10057 (while (setq entry (pop all))
10058 (if (string-match (car entry) buffer-file-name)
10059 (throw 'exit (cdr entry))))
10060 nil)))))
10062 (defvar org-refile-target-table nil
10063 "The list of refile targets, created by `org-refile'.")
10065 (defvar org-agenda-new-buffers nil
10066 "Buffers created to visit agenda files.")
10068 (defvar org-refile-cache nil
10069 "Cache for refile targets.")
10071 (defvar org-refile-markers nil
10072 "All the markers used for caching refile locations.")
10074 (defun org-refile-marker (pos)
10075 "Get a new refile marker, but only if caching is in use."
10076 (if (not org-refile-use-cache)
10078 (let ((m (make-marker)))
10079 (move-marker m pos)
10080 (push m org-refile-markers)
10081 m)))
10083 (defun org-refile-cache-clear ()
10084 "Clear the refile cache and disable all the markers."
10085 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
10086 (setq org-refile-markers nil)
10087 (setq org-refile-cache nil)
10088 (message "Refile cache has been cleared"))
10090 (defun org-refile-cache-check-set (set)
10091 "Check if all the markers in the cache still have live buffers."
10092 (let (marker)
10093 (catch 'exit
10094 (while (and set (setq marker (nth 3 (pop set))))
10095 ;; if org-refile-use-outline-path is 'file, marker may be nil
10096 (when (and marker (null (marker-buffer marker)))
10097 (message "not found") (sit-for 3)
10098 (throw 'exit nil)))
10099 t)))
10101 (defun org-refile-cache-put (set &rest identifiers)
10102 "Push the refile targets SET into the cache, under IDENTIFIERS."
10103 (let* ((key (sha1 (prin1-to-string identifiers)))
10104 (entry (assoc key org-refile-cache)))
10105 (if entry
10106 (setcdr entry set)
10107 (push (cons key set) org-refile-cache))))
10109 (defun org-refile-cache-get (&rest identifiers)
10110 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10111 (cond
10112 ((not org-refile-cache) nil)
10113 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10115 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10116 org-refile-cache))))
10117 (and set (org-refile-cache-check-set set) set)))))
10119 (defun org-refile-get-targets (&optional default-buffer)
10120 "Produce a table with refile targets."
10121 (let ((case-fold-search nil)
10122 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10123 (entries (or org-refile-targets '((nil . (:level . 1)))))
10124 targets tgs txt re files f desc descre fast-path-p level pos0)
10125 (message "Getting targets...")
10126 (with-current-buffer (or default-buffer (current-buffer))
10127 (while (setq entry (pop entries))
10128 (setq files (car entry) desc (cdr entry))
10129 (setq fast-path-p nil)
10130 (cond
10131 ((null files) (setq files (list (current-buffer))))
10132 ((eq files 'org-agenda-files)
10133 (setq files (org-agenda-files 'unrestricted)))
10134 ((and (symbolp files) (fboundp files))
10135 (setq files (funcall files)))
10136 ((and (symbolp files) (boundp files))
10137 (setq files (symbol-value files))))
10138 (if (stringp files) (setq files (list files)))
10139 (cond
10140 ((eq (car desc) :tag)
10141 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
10142 ((eq (car desc) :todo)
10143 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
10144 ((eq (car desc) :regexp)
10145 (setq descre (cdr desc)))
10146 ((eq (car desc) :level)
10147 (setq descre (concat "^\\*\\{" (number-to-string
10148 (if org-odd-levels-only
10149 (1- (* 2 (cdr desc)))
10150 (cdr desc)))
10151 "\\}[ \t]")))
10152 ((eq (car desc) :maxlevel)
10153 (setq fast-path-p t)
10154 (setq descre (concat "^\\*\\{1," (number-to-string
10155 (if org-odd-levels-only
10156 (1- (* 2 (cdr desc)))
10157 (cdr desc)))
10158 "\\}[ \t]")))
10159 (t (error "Bad refiling target description %s" desc)))
10160 (while (setq f (pop files))
10161 (with-current-buffer
10162 (if (bufferp f) f (org-get-agenda-file-buffer f))
10164 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
10165 (progn
10166 (if (bufferp f) (setq f (buffer-file-name
10167 (buffer-base-buffer f))))
10168 (setq f (and f (expand-file-name f)))
10169 (if (eq org-refile-use-outline-path 'file)
10170 (push (list (file-name-nondirectory f) f nil nil) tgs))
10171 (save-excursion
10172 (save-restriction
10173 (widen)
10174 (goto-char (point-min))
10175 (while (re-search-forward descre nil t)
10176 (goto-char (setq pos0 (point-at-bol)))
10177 (catch 'next
10178 (when org-refile-target-verify-function
10179 (save-match-data
10180 (or (funcall org-refile-target-verify-function)
10181 (throw 'next t))))
10182 (when (looking-at org-complex-heading-regexp)
10183 (setq level (org-reduced-level
10184 (- (match-end 1) (match-beginning 1)))
10185 txt (org-link-display-format (match-string 4))
10186 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
10187 re (format org-complex-heading-regexp-format
10188 (regexp-quote (match-string 4))))
10189 (when org-refile-use-outline-path
10190 (setq txt (mapconcat
10191 'org-protect-slash
10192 (append
10193 (if (eq org-refile-use-outline-path
10194 'file)
10195 (list (file-name-nondirectory
10196 (buffer-file-name
10197 (buffer-base-buffer))))
10198 (if (eq org-refile-use-outline-path
10199 'full-file-path)
10200 (list (buffer-file-name
10201 (buffer-base-buffer)))))
10202 (org-get-outline-path fast-path-p
10203 level txt)
10204 (list txt))
10205 "/")))
10206 (push (list txt f re (org-refile-marker (point)))
10207 tgs)))
10208 (when (= (point) pos0)
10209 ;; verification function has not moved point
10210 (goto-char (point-at-eol))))))))
10211 (when org-refile-use-cache
10212 (org-refile-cache-put tgs (buffer-file-name) descre))
10213 (setq targets (append tgs targets))
10214 ))))
10215 (message "Getting targets...done")
10216 (nreverse targets)))
10218 (defun org-protect-slash (s)
10219 (while (string-match "/" s)
10220 (setq s (replace-match "\\" t t s)))
10223 (defvar org-olpa (make-vector 20 nil))
10225 (defun org-get-outline-path (&optional fastp level heading)
10226 "Return the outline path to the current entry, as a list.
10228 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
10229 routine which makes outline path derivations for an entire file,
10230 avoiding backtracing. Refile target collection makes use of that."
10231 (if fastp
10232 (progn
10233 (if (> level 19)
10234 (error "Outline path failure, more than 19 levels"))
10235 (loop for i from level upto 19 do
10236 (aset org-olpa i nil))
10237 (prog1
10238 (delq nil (append org-olpa nil))
10239 (aset org-olpa level heading)))
10240 (let (rtn case-fold-search)
10241 (save-excursion
10242 (save-restriction
10243 (widen)
10244 (while (org-up-heading-safe)
10245 (when (looking-at org-complex-heading-regexp)
10246 (push (org-match-string-no-properties 4) rtn)))
10247 rtn)))))
10249 (defun org-format-outline-path (path &optional width prefix)
10250 "Format the outline path PATH for display.
10251 Width is the maximum number of characters that is available.
10252 Prefix is a prefix to be included in the returned string,
10253 such as the file name."
10254 (setq width (or width 79))
10255 (if prefix (setq width (- width (length prefix))))
10256 (if (not path)
10257 (or prefix "")
10258 (let* ((nsteps (length path))
10259 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
10260 (maxwidth (if (<= total-width width)
10261 10000 ;; everything fits
10262 ;; we need to shorten the level headings
10263 (/ (- width nsteps) nsteps)))
10264 (org-odd-levels-only nil)
10265 (n 0)
10266 (total (1+ (length prefix))))
10267 (setq maxwidth (max maxwidth 10))
10268 (concat prefix
10269 (mapconcat
10270 (lambda (h)
10271 (setq n (1+ n))
10272 (if (and (= n nsteps) (< maxwidth 10000))
10273 (setq maxwidth (- total-width total)))
10274 (if (< (length h) maxwidth)
10275 (progn (setq total (+ total (length h) 1)) h)
10276 (setq h (substring h 0 (- maxwidth 2))
10277 total (+ total maxwidth 1))
10278 (if (string-match "[ \t]+\\'" h)
10279 (setq h (substring h 0 (match-beginning 0))))
10280 (setq h (concat h "..")))
10281 (org-add-props h nil 'face
10282 (nth (% (1- n) org-n-level-faces)
10283 org-level-faces))
10285 path "/")))))
10287 (defun org-display-outline-path (&optional file current)
10288 "Display the current outline path in the echo area."
10289 (interactive "P")
10290 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
10291 (case-fold-search nil)
10292 (path (and (org-mode-p) (org-get-outline-path))))
10293 (if current (setq path (append path
10294 (save-excursion
10295 (org-back-to-heading t)
10296 (if (looking-at org-complex-heading-regexp)
10297 (list (match-string 4)))))))
10298 (message "%s"
10299 (org-format-outline-path
10300 path
10301 (1- (frame-width))
10302 (and file bfn (concat (file-name-nondirectory bfn) "/"))))))
10304 (defvar org-refile-history nil
10305 "History for refiling operations.")
10307 (defvar org-after-refile-insert-hook nil
10308 "Hook run after `org-refile' has inserted its stuff at the new location.
10309 Note that this is still *before* the stuff will be removed from
10310 the *old* location.")
10312 (defvar org-capture-last-stored-marker)
10313 (defun org-refile (&optional goto default-buffer rfloc)
10314 "Move the entry at point to another heading.
10315 The list of target headings is compiled using the information in
10316 `org-refile-targets', which see. This list is created before each use
10317 and will therefore always be up-to-date.
10319 At the target location, the entry is filed as a subitem of the target heading.
10320 Depending on `org-reverse-note-order', the new subitem will either be the
10321 first or the last subitem.
10323 If there is an active region, all entries in that region will be moved.
10324 However, the region must fulfill the requirement that the first heading
10325 is the first one sets the top-level of the moved text - at most siblings
10326 below it are allowed.
10328 With prefix arg GOTO, the command will only visit the target location,
10329 not actually move anything.
10330 With a double prefix arg \\[universal-argument] \\[universal-argument], \
10331 go to the location where the last refiling
10332 operation has put the subtree.
10333 With a prefix argument of `2', refile to the running clock.
10335 RFLOC can be a refile location obtained in a different way.
10337 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
10339 If you are using target caching (see `org-refile-use-cache'),
10340 You have to clear the target cache in order to find new targets.
10341 This can be done with a 0 prefix: `C-0 C-c C-w'"
10342 (interactive "P")
10343 (if (member goto '(0 (64)))
10344 (org-refile-cache-clear)
10345 (let* ((cbuf (current-buffer))
10346 (regionp (org-region-active-p))
10347 (region-start (and regionp (region-beginning)))
10348 (region-end (and regionp (region-end)))
10349 (region-length (and regionp (- region-end region-start)))
10350 (filename (buffer-file-name (buffer-base-buffer cbuf)))
10351 pos it nbuf file re level reversed)
10352 (setq last-command nil)
10353 (when regionp
10354 (goto-char region-start)
10355 (or (bolp) (goto-char (point-at-bol)))
10356 (setq region-start (point))
10357 (unless (org-kill-is-subtree-p
10358 (buffer-substring region-start region-end))
10359 (error "The region is not a (sequence of) subtree(s)")))
10360 (if (equal goto '(16))
10361 (org-refile-goto-last-stored)
10362 (when (or
10363 (and (equal goto 2)
10364 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
10365 (prog1
10366 (setq it (list (or org-clock-heading "running clock")
10367 (buffer-file-name
10368 (marker-buffer org-clock-hd-marker))
10370 (marker-position org-clock-hd-marker)))
10371 (setq goto nil)))
10372 (setq it (or rfloc
10373 (save-excursion
10374 (org-refile-get-location
10375 (if goto "Goto" "Refile to") default-buffer
10376 org-refile-allow-creating-parent-nodes)))))
10377 (setq file (nth 1 it)
10378 re (nth 2 it)
10379 pos (nth 3 it))
10380 (if (and (not goto)
10382 (equal (buffer-file-name) file)
10383 (if regionp
10384 (and (>= pos region-start)
10385 (<= pos region-end))
10386 (and (>= pos (point))
10387 (< pos (save-excursion
10388 (org-end-of-subtree t t))))))
10389 (error "Cannot refile to position inside the tree or region"))
10391 (setq nbuf (or (find-buffer-visiting file)
10392 (find-file-noselect file)))
10393 (if goto
10394 (progn
10395 (switch-to-buffer nbuf)
10396 (goto-char pos)
10397 (org-show-context 'org-goto))
10398 (if regionp
10399 (progn
10400 (org-kill-new (buffer-substring region-start region-end))
10401 (org-save-markers-in-region region-start region-end))
10402 (org-copy-subtree 1 nil t))
10403 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
10404 (find-file-noselect file)))
10405 (setq reversed (org-notes-order-reversed-p))
10406 (save-excursion
10407 (save-restriction
10408 (widen)
10409 (if pos
10410 (progn
10411 (goto-char pos)
10412 (looking-at outline-regexp)
10413 (setq level (org-get-valid-level (funcall outline-level) 1))
10414 (goto-char
10415 (if reversed
10416 (or (outline-next-heading) (point-max))
10417 (or (save-excursion (org-get-next-sibling))
10418 (org-end-of-subtree t t)
10419 (point-max)))))
10420 (setq level 1)
10421 (if (not reversed)
10422 (goto-char (point-max))
10423 (goto-char (point-min))
10424 (or (outline-next-heading) (goto-char (point-max)))))
10425 (if (not (bolp)) (newline))
10426 (org-paste-subtree level)
10427 (when org-log-refile
10428 (org-add-log-setup 'refile nil nil 'findpos
10429 org-log-refile)
10430 (unless (eq org-log-refile 'note)
10431 (save-excursion (org-add-log-note))))
10432 (and org-auto-align-tags (org-set-tags nil t))
10433 (bookmark-set "org-refile-last-stored")
10434 ;; If we are refiling for capture, make sure that the
10435 ;; last-capture pointers point here
10436 (when (org-bound-and-true-p org-refile-for-capture)
10437 (bookmark-set "org-capture-last-stored-marker")
10438 (move-marker org-capture-last-stored-marker (point)))
10439 (if (fboundp 'deactivate-mark) (deactivate-mark))
10440 (run-hooks 'org-after-refile-insert-hook))))
10441 (if regionp
10442 (delete-region (point) (+ (point) region-length))
10443 (org-cut-subtree))
10444 (when (featurep 'org-inlinetask)
10445 (org-inlinetask-remove-END-maybe))
10446 (setq org-markers-to-move nil)
10447 (message "Refiled to \"%s\" in file %s" (car it) file)))))))
10449 (defun org-refile-goto-last-stored ()
10450 "Go to the location where the last refile was stored."
10451 (interactive)
10452 (bookmark-jump "org-refile-last-stored")
10453 (message "This is the location of the last refile"))
10455 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
10456 "Prompt the user for a refile location, using PROMPT.
10457 PROMPT should not be suffixed with a colon and a space, because
10458 this function appends the default value from
10459 `org-refile-history' automatically, if that is not empty."
10460 (let ((org-refile-targets org-refile-targets)
10461 (org-refile-use-outline-path org-refile-use-outline-path))
10462 (setq org-refile-target-table (org-refile-get-targets default-buffer)))
10463 (unless org-refile-target-table
10464 (error "No refile targets"))
10465 (let* ((prompt (concat prompt
10466 (and (car org-refile-history)
10467 (concat " (default " (car org-refile-history) ")"))
10468 ": "))
10469 (cbuf (current-buffer))
10470 (partial-completion-mode nil)
10471 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
10472 (cfunc (if (and org-refile-use-outline-path
10473 org-outline-path-complete-in-steps)
10474 'org-olpath-completing-read
10475 'org-icompleting-read))
10476 (extra (if org-refile-use-outline-path "/" ""))
10477 (filename (and cfn (expand-file-name cfn)))
10478 (tbl (mapcar
10479 (lambda (x)
10480 (if (and (not (member org-refile-use-outline-path
10481 '(file full-file-path)))
10482 (not (equal filename (nth 1 x))))
10483 (cons (concat (car x) extra " ("
10484 (file-name-nondirectory (nth 1 x)) ")")
10485 (cdr x))
10486 (cons (concat (car x) extra) (cdr x))))
10487 org-refile-target-table))
10488 (completion-ignore-case t)
10489 pa answ parent-target child parent old-hist)
10490 (setq old-hist org-refile-history)
10491 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
10492 nil 'org-refile-history (car org-refile-history)))
10493 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
10494 (org-refile-check-position pa)
10495 (if pa
10496 (progn
10497 (when (or (not org-refile-history)
10498 (not (eq old-hist org-refile-history))
10499 (not (equal (car pa) (car org-refile-history))))
10500 (setq org-refile-history
10501 (cons (car pa) (if (assoc (car org-refile-history) tbl)
10502 org-refile-history
10503 (cdr org-refile-history))))
10504 (if (equal (car org-refile-history) (nth 1 org-refile-history))
10505 (pop org-refile-history)))
10507 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
10508 (progn
10509 (setq parent (match-string 1 answ)
10510 child (match-string 2 answ))
10511 (setq parent-target (or (assoc parent tbl)
10512 (assoc (concat parent "/") tbl)))
10513 (when (and parent-target
10514 (or (eq new-nodes t)
10515 (and (eq new-nodes 'confirm)
10516 (y-or-n-p (format "Create new node \"%s\"? "
10517 child)))))
10518 (org-refile-new-child parent-target child)))
10519 (error "Invalid target location")))))
10521 (defun org-refile-check-position (refile-pointer)
10522 "Check if the refile pointer matches the readline to which it points."
10523 (let* ((file (nth 1 refile-pointer))
10524 (re (nth 2 refile-pointer))
10525 (pos (nth 3 refile-pointer))
10526 buffer)
10527 (when (org-string-nw-p re)
10528 (setq buffer (if (markerp pos)
10529 (marker-buffer pos)
10530 (or (find-buffer-visiting file)
10531 (find-file-noselect file))))
10532 (with-current-buffer buffer
10533 (save-excursion
10534 (save-restriction
10535 (widen)
10536 (goto-char pos)
10537 (beginning-of-line 1)
10538 (unless (org-looking-at-p re)
10539 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
10541 (defun org-refile-new-child (parent-target child)
10542 "Use refile target PARENT-TARGET to add new CHILD below it."
10543 (unless parent-target
10544 (error "Cannot find parent for new node"))
10545 (let ((file (nth 1 parent-target))
10546 (pos (nth 3 parent-target))
10547 level)
10548 (with-current-buffer (or (find-buffer-visiting file)
10549 (find-file-noselect file))
10550 (save-excursion
10551 (save-restriction
10552 (widen)
10553 (if pos
10554 (goto-char pos)
10555 (goto-char (point-max))
10556 (if (not (bolp)) (newline)))
10557 (when (looking-at outline-regexp)
10558 (setq level (funcall outline-level))
10559 (org-end-of-subtree t t))
10560 (org-back-over-empty-lines)
10561 (insert "\n" (make-string
10562 (if pos (org-get-valid-level level 1) 1) ?*)
10563 " " child "\n")
10564 (beginning-of-line 0)
10565 (list (concat (car parent-target) "/" child) file "" (point)))))))
10567 (defun org-olpath-completing-read (prompt collection &rest args)
10568 "Read an outline path like a file name."
10569 (let ((thetable collection)
10570 (org-completion-use-ido nil) ; does not work with ido.
10571 (org-completion-use-iswitchb nil)) ; or iswitchb
10572 (apply
10573 'org-icompleting-read prompt
10574 (lambda (string predicate &optional flag)
10575 (let (rtn r f (l (length string)))
10576 (cond
10577 ((eq flag nil)
10578 ;; try completion
10579 (try-completion string thetable))
10580 ((eq flag t)
10581 ;; all-completions
10582 (setq rtn (all-completions string thetable predicate))
10583 (mapcar
10584 (lambda (x)
10585 (setq r (substring x l))
10586 (if (string-match " ([^)]*)$" x)
10587 (setq f (match-string 0 x))
10588 (setq f ""))
10589 (if (string-match "/" r)
10590 (concat string (substring r 0 (match-end 0)) f)
10592 rtn))
10593 ((eq flag 'lambda)
10594 ;; exact match?
10595 (assoc string thetable)))
10597 args)))
10599 ;;;; Dynamic blocks
10601 (defun org-find-dblock (name)
10602 "Find the first dynamic block with name NAME in the buffer.
10603 If not found, stay at current position and return nil."
10604 (let (pos)
10605 (save-excursion
10606 (goto-char (point-min))
10607 (setq pos (and (re-search-forward (concat "^[ \t]*#\\+BEGIN:[ \t]+" name "\\>")
10608 nil t)
10609 (match-beginning 0))))
10610 (if pos (goto-char pos))
10611 pos))
10613 (defconst org-dblock-start-re
10614 "^[ \t]*#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
10615 "Matches the start line of a dynamic block, with parameters.")
10617 (defconst org-dblock-end-re "^[ \t]*#\\+END\\([: \t\r\n]\\|$\\)"
10618 "Matches the end of a dynamic block.")
10620 (defun org-create-dblock (plist)
10621 "Create a dynamic block section, with parameters taken from PLIST.
10622 PLIST must contain a :name entry which is used as name of the block."
10623 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
10624 (end-of-line 1)
10625 (newline))
10626 (let ((col (current-column))
10627 (name (plist-get plist :name)))
10628 (insert "#+BEGIN: " name)
10629 (while plist
10630 (if (eq (car plist) :name)
10631 (setq plist (cddr plist))
10632 (insert " " (prin1-to-string (pop plist)))))
10633 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
10634 (beginning-of-line -2)))
10636 (defun org-prepare-dblock ()
10637 "Prepare dynamic block for refresh.
10638 This empties the block, puts the cursor at the insert position and returns
10639 the property list including an extra property :name with the block name."
10640 (unless (looking-at org-dblock-start-re)
10641 (error "Not at a dynamic block"))
10642 (let* ((begdel (1+ (match-end 0)))
10643 (name (org-no-properties (match-string 1)))
10644 (params (append (list :name name)
10645 (read (concat "(" (match-string 3) ")")))))
10646 (save-excursion
10647 (beginning-of-line 1)
10648 (skip-chars-forward " \t")
10649 (setq params (plist-put params :indentation-column (current-column))))
10650 (unless (re-search-forward org-dblock-end-re nil t)
10651 (error "Dynamic block not terminated"))
10652 (setq params
10653 (append params
10654 (list :content (buffer-substring
10655 begdel (match-beginning 0)))))
10656 (delete-region begdel (match-beginning 0))
10657 (goto-char begdel)
10658 (open-line 1)
10659 params))
10661 (defun org-map-dblocks (&optional command)
10662 "Apply COMMAND to all dynamic blocks in the current buffer.
10663 If COMMAND is not given, use `org-update-dblock'."
10664 (let ((cmd (or command 'org-update-dblock)))
10665 (save-excursion
10666 (goto-char (point-min))
10667 (while (re-search-forward org-dblock-start-re nil t)
10668 (goto-char (match-beginning 0))
10669 (save-excursion
10670 (condition-case nil
10671 (funcall cmd)
10672 (error (message "Error during update of dynamic block"))))
10673 (unless (re-search-forward org-dblock-end-re nil t)
10674 (error "Dynamic block not terminated"))))))
10676 (defun org-dblock-update (&optional arg)
10677 "User command for updating dynamic blocks.
10678 Update the dynamic block at point. With prefix ARG, update all dynamic
10679 blocks in the buffer."
10680 (interactive "P")
10681 (if arg
10682 (org-update-all-dblocks)
10683 (or (looking-at org-dblock-start-re)
10684 (org-beginning-of-dblock))
10685 (org-update-dblock)))
10687 (defun org-update-dblock ()
10688 "Update the dynamic block at point.
10689 This means to empty the block, parse for parameters and then call
10690 the correct writing function."
10691 (interactive)
10692 (save-window-excursion
10693 (let* ((pos (point))
10694 (line (org-current-line))
10695 (params (org-prepare-dblock))
10696 (name (plist-get params :name))
10697 (indent (plist-get params :indentation-column))
10698 (cmd (intern (concat "org-dblock-write:" name))))
10699 (message "Updating dynamic block `%s' at line %d..." name line)
10700 (funcall cmd params)
10701 (message "Updating dynamic block `%s' at line %d...done" name line)
10702 (goto-char pos)
10703 (when (and indent (> indent 0))
10704 (setq indent (make-string indent ?\ ))
10705 (save-excursion
10706 (org-beginning-of-dblock)
10707 (forward-line 1)
10708 (while (not (looking-at org-dblock-end-re))
10709 (insert indent)
10710 (beginning-of-line 2))
10711 (when (looking-at org-dblock-end-re)
10712 (and (looking-at "[ \t]+")
10713 (replace-match ""))
10714 (insert indent)))))))
10716 (defun org-beginning-of-dblock ()
10717 "Find the beginning of the dynamic block at point.
10718 Error if there is no such block at point."
10719 (let ((pos (point))
10720 beg)
10721 (end-of-line 1)
10722 (if (and (re-search-backward org-dblock-start-re nil t)
10723 (setq beg (match-beginning 0))
10724 (re-search-forward org-dblock-end-re nil t)
10725 (> (match-end 0) pos))
10726 (goto-char beg)
10727 (goto-char pos)
10728 (error "Not in a dynamic block"))))
10730 (defun org-update-all-dblocks ()
10731 "Update all dynamic blocks in the buffer.
10732 This function can be used in a hook."
10733 (interactive)
10734 (when (org-mode-p)
10735 (org-map-dblocks 'org-update-dblock)))
10738 ;;;; Completion
10740 (defconst org-additional-option-like-keywords
10741 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML:"
10742 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook:"
10743 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"
10744 "LATEX_CLASS:" "LATEX_CLASS_OPTIONS:" "ATTR_LaTeX:"
10745 "BEGIN:" "END:"
10746 "ORGTBL" "TBLFM:" "TBLNAME:"
10747 "BEGIN_EXAMPLE" "END_EXAMPLE"
10748 "BEGIN_QUOTE" "END_QUOTE"
10749 "BEGIN_VERSE" "END_VERSE"
10750 "BEGIN_CENTER" "END_CENTER"
10751 "BEGIN_SRC" "END_SRC"
10752 "BEGIN_RESULT" "END_RESULT"
10753 "SOURCE:" "SRCNAME:" "FUNCTION:"
10754 "RESULTS:"
10755 "HEADER:" "HEADERS:"
10756 "BABEL:"
10757 "CATEGORY:" "COLUMNS:" "PROPERTY:"
10758 "CAPTION:" "LABEL:"
10759 "SETUPFILE:"
10760 "INCLUDE:"
10761 "BIND:"
10762 "MACRO:"))
10764 (defcustom org-structure-template-alist
10766 ("s" "#+begin_src ?\n\n#+end_src"
10767 "<src lang=\"?\">\n\n</src>")
10768 ("e" "#+begin_example\n?\n#+end_example"
10769 "<example>\n?\n</example>")
10770 ("q" "#+begin_quote\n?\n#+end_quote"
10771 "<quote>\n?\n</quote>")
10772 ("v" "#+begin_verse\n?\n#+end_verse"
10773 "<verse>\n?\n/verse>")
10774 ("c" "#+begin_center\n?\n#+end_center"
10775 "<center>\n?\n/center>")
10776 ("l" "#+begin_latex\n?\n#+end_latex"
10777 "<literal style=\"latex\">\n?\n</literal>")
10778 ("L" "#+latex: "
10779 "<literal style=\"latex\">?</literal>")
10780 ("h" "#+begin_html\n?\n#+end_html"
10781 "<literal style=\"html\">\n?\n</literal>")
10782 ("H" "#+html: "
10783 "<literal style=\"html\">?</literal>")
10784 ("a" "#+begin_ascii\n?\n#+end_ascii")
10785 ("A" "#+ascii: ")
10786 ("i" "#+index: ?"
10787 "#+index: ?")
10788 ("I" "#+include %file ?"
10789 "<include file=%file markup=\"?\">")
10791 "Structure completion elements.
10792 This is a list of abbreviation keys and values. The value gets inserted
10793 if you type `<' followed by the key and then press the completion key,
10794 usually `M-TAB'. %file will be replaced by a file name after prompting
10795 for the file using completion. The cursor will be placed at the position
10796 of the `?` in the template.
10797 There are two templates for each key, the first uses the original Org syntax,
10798 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
10799 the default when the /org-mtags.el/ module has been loaded. See also the
10800 variable `org-mtags-prefer-muse-templates'.
10801 This is an experimental feature, it is undecided if it is going to stay in."
10802 :group 'org-completion
10803 :type '(repeat
10804 (string :tag "Key")
10805 (string :tag "Template")
10806 (string :tag "Muse Template")))
10808 (defun org-try-structure-completion ()
10809 "Try to complete a structure template before point.
10810 This looks for strings like \"<e\" on an otherwise empty line and
10811 expands them."
10812 (let ((l (buffer-substring (point-at-bol) (point)))
10814 (when (and (looking-at "[ \t]*$")
10815 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
10816 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
10817 (org-complete-expand-structure-template (+ -1 (point-at-bol)
10818 (match-beginning 1)) a)
10819 t)))
10821 (defun org-complete-expand-structure-template (start cell)
10822 "Expand a structure template."
10823 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
10824 (rpl (nth (if musep 2 1) cell))
10825 (ind ""))
10826 (delete-region start (point))
10827 (when (string-match "\\`#\\+" rpl)
10828 (cond
10829 ((bolp))
10830 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
10831 (setq ind (buffer-substring (point-at-bol) (point))))
10832 (t (newline))))
10833 (setq start (point))
10834 (if (string-match "%file" rpl)
10835 (setq rpl (replace-match
10836 (concat
10837 "\""
10838 (save-match-data
10839 (abbreviate-file-name (read-file-name "Include file: ")))
10840 "\"")
10841 t t rpl)))
10842 (setq rpl (mapconcat 'identity (split-string rpl "\n")
10843 (concat "\n" ind)))
10844 (insert rpl)
10845 (if (re-search-backward "\\?" start t) (delete-char 1))))
10847 ;;;; TODO, DEADLINE, Comments
10849 (defun org-toggle-comment ()
10850 "Change the COMMENT state of an entry."
10851 (interactive)
10852 (save-excursion
10853 (org-back-to-heading)
10854 (let (case-fold-search)
10855 (if (looking-at (concat outline-regexp
10856 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
10857 (replace-match "" t t nil 1)
10858 (if (looking-at outline-regexp)
10859 (progn
10860 (goto-char (match-end 0))
10861 (insert org-comment-string " ")))))))
10863 (defvar org-last-todo-state-is-todo nil
10864 "This is non-nil when the last TODO state change led to a TODO state.
10865 If the last change removed the TODO tag or switched to DONE, then
10866 this is nil.")
10868 (defvar org-setting-tags nil) ; dynamically skipped
10870 (defvar org-todo-setup-filter-hook nil
10871 "Hook for functions that pre-filter todo specs.
10872 Each function takes a todo spec and returns either nil or the spec
10873 transformed into canonical form." )
10875 (defvar org-todo-get-default-hook nil
10876 "Hook for functions that get a default item for todo.
10877 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
10878 nil or a string to be used for the todo mark." )
10880 (defvar org-agenda-headline-snapshot-before-repeat)
10882 (defun org-todo (&optional arg)
10883 "Change the TODO state of an item.
10884 The state of an item is given by a keyword at the start of the heading,
10885 like
10886 *** TODO Write paper
10887 *** DONE Call mom
10889 The different keywords are specified in the variable `org-todo-keywords'.
10890 By default the available states are \"TODO\" and \"DONE\".
10891 So for this example: when the item starts with TODO, it is changed to DONE.
10892 When it starts with DONE, the DONE is removed. And when neither TODO nor
10893 DONE are present, add TODO at the beginning of the heading.
10895 With \\[universal-argument] prefix arg, use completion to determine the new \
10896 state.
10897 With numeric prefix arg, switch to that state.
10898 With a double \\[universal-argument] prefix, switch to the next set of TODO \
10899 keywords (nextset).
10900 With a triple \\[universal-argument] prefix, circumvent any state blocking.
10902 For calling through lisp, arg is also interpreted in the following way:
10903 'none -> empty state
10904 \"\"(empty string) -> switch to empty state
10905 'done -> switch to DONE
10906 'nextset -> switch to the next set of keywords
10907 'previousset -> switch to the previous set of keywords
10908 \"WAITING\" -> switch to the specified keyword, but only if it
10909 really is a member of `org-todo-keywords'."
10910 (interactive "P")
10911 (if (equal arg '(16)) (setq arg 'nextset))
10912 (let ((org-blocker-hook org-blocker-hook)
10913 (case-fold-search nil))
10914 (when (equal arg '(64))
10915 (setq arg nil org-blocker-hook nil))
10916 (when (and org-blocker-hook
10917 (or org-inhibit-blocking
10918 (org-entry-get nil "NOBLOCKING")))
10919 (setq org-blocker-hook nil))
10920 (save-excursion
10921 (catch 'exit
10922 (org-back-to-heading t)
10923 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
10924 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|$\\)"))
10925 (looking-at " *"))
10926 (let* ((match-data (match-data))
10927 (startpos (point-at-bol))
10928 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
10929 (org-log-done org-log-done)
10930 (org-log-repeat org-log-repeat)
10931 (org-todo-log-states org-todo-log-states)
10932 (this (match-string 1))
10933 (hl-pos (match-beginning 0))
10934 (head (org-get-todo-sequence-head this))
10935 (ass (assoc head org-todo-kwd-alist))
10936 (interpret (nth 1 ass))
10937 (done-word (nth 3 ass))
10938 (final-done-word (nth 4 ass))
10939 (last-state (or this ""))
10940 (completion-ignore-case t)
10941 (member (member this org-todo-keywords-1))
10942 (tail (cdr member))
10943 (state (cond
10944 ((and org-todo-key-trigger
10945 (or (and (equal arg '(4))
10946 (eq org-use-fast-todo-selection 'prefix))
10947 (and (not arg) org-use-fast-todo-selection
10948 (not (eq org-use-fast-todo-selection
10949 'prefix)))))
10950 ;; Use fast selection
10951 (org-fast-todo-selection))
10952 ((and (equal arg '(4))
10953 (or (not org-use-fast-todo-selection)
10954 (not org-todo-key-trigger)))
10955 ;; Read a state with completion
10956 (org-icompleting-read
10957 "State: " (mapcar (lambda(x) (list x))
10958 org-todo-keywords-1)
10959 nil t))
10960 ((eq arg 'right)
10961 (if this
10962 (if tail (car tail) nil)
10963 (car org-todo-keywords-1)))
10964 ((eq arg 'left)
10965 (if (equal member org-todo-keywords-1)
10967 (if this
10968 (nth (- (length org-todo-keywords-1)
10969 (length tail) 2)
10970 org-todo-keywords-1)
10971 (org-last org-todo-keywords-1))))
10972 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
10973 (setq arg nil))) ; hack to fall back to cycling
10974 (arg
10975 ;; user or caller requests a specific state
10976 (cond
10977 ((equal arg "") nil)
10978 ((eq arg 'none) nil)
10979 ((eq arg 'done) (or done-word (car org-done-keywords)))
10980 ((eq arg 'nextset)
10981 (or (car (cdr (member head org-todo-heads)))
10982 (car org-todo-heads)))
10983 ((eq arg 'previousset)
10984 (let ((org-todo-heads (reverse org-todo-heads)))
10985 (or (car (cdr (member head org-todo-heads)))
10986 (car org-todo-heads))))
10987 ((car (member arg org-todo-keywords-1)))
10988 ((stringp arg)
10989 (error "State `%s' not valid in this file" arg))
10990 ((nth (1- (prefix-numeric-value arg))
10991 org-todo-keywords-1))))
10992 ((null member) (or head (car org-todo-keywords-1)))
10993 ((equal this final-done-word) nil) ;; -> make empty
10994 ((null tail) nil) ;; -> first entry
10995 ((memq interpret '(type priority))
10996 (if (eq this-command last-command)
10997 (car tail)
10998 (if (> (length tail) 0)
10999 (or done-word (car org-done-keywords))
11000 nil)))
11002 (car tail))))
11003 (state (or
11004 (run-hook-with-args-until-success
11005 'org-todo-get-default-hook state last-state)
11006 state))
11007 (next (if state (concat " " state " ") " "))
11008 (change-plist (list :type 'todo-state-change :from this :to state
11009 :position startpos))
11010 dolog now-done-p)
11011 (when org-blocker-hook
11012 (setq org-last-todo-state-is-todo
11013 (not (member this org-done-keywords)))
11014 (unless (save-excursion
11015 (save-match-data
11016 (org-with-wide-buffer
11017 (run-hook-with-args-until-failure
11018 'org-blocker-hook change-plist))))
11019 (if (org-called-interactively-p 'interactive)
11020 (error "TODO state change from %s to %s blocked" this state)
11021 ;; fail silently
11022 (message "TODO state change from %s to %s blocked" this state)
11023 (throw 'exit nil))))
11024 (store-match-data match-data)
11025 (replace-match next t t)
11026 (unless (pos-visible-in-window-p hl-pos)
11027 (message "TODO state changed to %s" (org-trim next)))
11028 (unless head
11029 (setq head (org-get-todo-sequence-head state)
11030 ass (assoc head org-todo-kwd-alist)
11031 interpret (nth 1 ass)
11032 done-word (nth 3 ass)
11033 final-done-word (nth 4 ass)))
11034 (when (memq arg '(nextset previousset))
11035 (message "Keyword-Set %d/%d: %s"
11036 (- (length org-todo-sets) -1
11037 (length (memq (assoc state org-todo-sets) org-todo-sets)))
11038 (length org-todo-sets)
11039 (mapconcat 'identity (assoc state org-todo-sets) " ")))
11040 (setq org-last-todo-state-is-todo
11041 (not (member state org-done-keywords)))
11042 (setq now-done-p (and (member state org-done-keywords)
11043 (not (member this org-done-keywords))))
11044 (and logging (org-local-logging logging))
11045 (when (and (or org-todo-log-states org-log-done)
11046 (not (eq org-inhibit-logging t))
11047 (not (memq arg '(nextset previousset))))
11048 ;; we need to look at recording a time and note
11049 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
11050 (nth 2 (assoc this org-todo-log-states))))
11051 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
11052 (setq dolog 'time))
11053 (when (and state
11054 (member state org-not-done-keywords)
11055 (not (member this org-not-done-keywords)))
11056 ;; This is now a todo state and was not one before
11057 ;; If there was a CLOSED time stamp, get rid of it.
11058 (org-add-planning-info nil nil 'closed))
11059 (when (and now-done-p org-log-done)
11060 ;; It is now done, and it was not done before
11061 (org-add-planning-info 'closed (org-current-time))
11062 (if (and (not dolog) (eq 'note org-log-done))
11063 (org-add-log-setup 'done state this 'findpos 'note)))
11064 (when (and state dolog)
11065 ;; This is a non-nil state, and we need to log it
11066 (org-add-log-setup 'state state this 'findpos dolog)))
11067 ;; Fixup tag positioning
11068 (org-todo-trigger-tag-changes state)
11069 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
11070 (when org-provide-todo-statistics
11071 (org-update-parent-todo-statistics))
11072 (run-hooks 'org-after-todo-state-change-hook)
11073 (if (and arg (not (member state org-done-keywords)))
11074 (setq head (org-get-todo-sequence-head state)))
11075 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
11076 ;; Do we need to trigger a repeat?
11077 (when now-done-p
11078 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
11079 ;; This is for the agenda, take a snapshot of the headline.
11080 (save-match-data
11081 (setq org-agenda-headline-snapshot-before-repeat
11082 (org-get-heading))))
11083 (org-auto-repeat-maybe state))
11084 ;; Fixup cursor location if close to the keyword
11085 (if (and (outline-on-heading-p)
11086 (not (bolp))
11087 (save-excursion (beginning-of-line 1)
11088 (looking-at org-todo-line-regexp))
11089 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
11090 (progn
11091 (goto-char (or (match-end 2) (match-end 1)))
11092 (and (looking-at " ") (just-one-space))))
11093 (when org-trigger-hook
11094 (save-excursion
11095 (run-hook-with-args 'org-trigger-hook change-plist))))))))
11097 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
11098 "Block turning an entry into a TODO, using the hierarchy.
11099 This checks whether the current task should be blocked from state
11100 changes. Such blocking occurs when:
11102 1. The task has children which are not all in a completed state.
11104 2. A task has a parent with the property :ORDERED:, and there
11105 are siblings prior to the current task with incomplete
11106 status.
11108 3. The parent of the task is blocked because it has siblings that should
11109 be done first, or is child of a block grandparent TODO entry."
11111 (if (not org-enforce-todo-dependencies)
11112 t ; if locally turned off don't block
11113 (catch 'dont-block
11114 ;; If this is not a todo state change, or if this entry is already DONE,
11115 ;; do not block
11116 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11117 (member (plist-get change-plist :from)
11118 (cons 'done org-done-keywords))
11119 (member (plist-get change-plist :to)
11120 (cons 'todo org-not-done-keywords))
11121 (not (plist-get change-plist :to)))
11122 (throw 'dont-block t))
11123 ;; If this task has children, and any are undone, it's blocked
11124 (save-excursion
11125 (org-back-to-heading t)
11126 (let ((this-level (funcall outline-level)))
11127 (outline-next-heading)
11128 (let ((child-level (funcall outline-level)))
11129 (while (and (not (eobp))
11130 (> child-level this-level))
11131 ;; this todo has children, check whether they are all
11132 ;; completed
11133 (if (and (not (org-entry-is-done-p))
11134 (org-entry-is-todo-p))
11135 (throw 'dont-block nil))
11136 (outline-next-heading)
11137 (setq child-level (funcall outline-level))))))
11138 ;; Otherwise, if the task's parent has the :ORDERED: property, and
11139 ;; any previous siblings are undone, it's blocked
11140 (save-excursion
11141 (org-back-to-heading t)
11142 (let* ((pos (point))
11143 (parent-pos (and (org-up-heading-safe) (point))))
11144 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11145 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11146 (forward-line 1)
11147 (re-search-forward org-not-done-heading-regexp pos t))
11148 (throw 'dont-block nil)) ; block, there is an older sibling not done.
11149 ;; Search further up the hierarchy, to see if an anchestor is blocked
11150 (while t
11151 (goto-char parent-pos)
11152 (if (not (looking-at org-not-done-heading-regexp))
11153 (throw 'dont-block t)) ; do not block, parent is not a TODO
11154 (setq pos (point))
11155 (setq parent-pos (and (org-up-heading-safe) (point)))
11156 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11157 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11158 (forward-line 1)
11159 (re-search-forward org-not-done-heading-regexp pos t))
11160 (throw 'dont-block nil)))))))) ; block, older sibling not done.
11162 (defcustom org-track-ordered-property-with-tag nil
11163 "Should the ORDERED property also be shown as a tag?
11164 The ORDERED property decides if an entry should require subtasks to be
11165 completed in sequence. Since a property is not very visible, setting
11166 this option means that toggling the ORDERED property with the command
11167 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
11168 not relevant for the behavior, but it makes things more visible.
11170 Note that toggling the tag with tags commands will not change the property
11171 and therefore not influence behavior!
11173 This can be t, meaning the tag ORDERED should be used, It can also be a
11174 string to select a different tag for this task."
11175 :group 'org-todo
11176 :type '(choice
11177 (const :tag "No tracking" nil)
11178 (const :tag "Track with ORDERED tag" t)
11179 (string :tag "Use other tag")))
11181 (defun org-toggle-ordered-property ()
11182 "Toggle the ORDERED property of the current entry.
11183 For better visibility, you can track the value of this property with a tag.
11184 See variable `org-track-ordered-property-with-tag'."
11185 (interactive)
11186 (let* ((t1 org-track-ordered-property-with-tag)
11187 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
11188 (save-excursion
11189 (org-back-to-heading)
11190 (if (org-entry-get nil "ORDERED")
11191 (progn
11192 (org-delete-property "ORDERED")
11193 (and tag (org-toggle-tag tag 'off))
11194 (message "Subtasks can be completed in arbitrary order"))
11195 (org-entry-put nil "ORDERED" "t")
11196 (and tag (org-toggle-tag tag 'on))
11197 (message "Subtasks must be completed in sequence")))))
11199 (defvar org-blocked-by-checkboxes) ; dynamically scoped
11200 (defun org-block-todo-from-checkboxes (change-plist)
11201 "Block turning an entry into a TODO, using checkboxes.
11202 This checks whether the current task should be blocked from state
11203 changes because there are unchecked boxes in this entry."
11204 (if (not org-enforce-todo-checkbox-dependencies)
11205 t ; if locally turned off don't block
11206 (catch 'dont-block
11207 ;; If this is not a todo state change, or if this entry is already DONE,
11208 ;; do not block
11209 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11210 (member (plist-get change-plist :from)
11211 (cons 'done org-done-keywords))
11212 (member (plist-get change-plist :to)
11213 (cons 'todo org-not-done-keywords))
11214 (not (plist-get change-plist :to)))
11215 (throw 'dont-block t))
11216 ;; If this task has checkboxes that are not checked, it's blocked
11217 (save-excursion
11218 (org-back-to-heading t)
11219 (let ((beg (point)) end)
11220 (outline-next-heading)
11221 (setq end (point))
11222 (goto-char beg)
11223 (if (re-search-forward "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\)[ \t]+\\[[- ]\\]"
11224 end t)
11225 (progn
11226 (if (boundp 'org-blocked-by-checkboxes)
11227 (setq org-blocked-by-checkboxes t))
11228 (throw 'dont-block nil)))))
11229 t))) ; do not block
11231 (defun org-entry-blocked-p ()
11232 "Is the current entry blocked?"
11233 (if (org-entry-get nil "NOBLOCKING")
11234 nil ;; Never block this entry
11235 (not
11236 (run-hook-with-args-until-failure
11237 'org-blocker-hook
11238 (list :type 'todo-state-change
11239 :position (point)
11240 :from 'todo
11241 :to 'done)))))
11243 (defun org-update-statistics-cookies (all)
11244 "Update the statistics cookie, either from TODO or from checkboxes.
11245 This should be called with the cursor in a line with a statistics cookie."
11246 (interactive "P")
11247 (if all
11248 (progn
11249 (org-update-checkbox-count 'all)
11250 (org-map-entries 'org-update-parent-todo-statistics))
11251 (if (not (org-on-heading-p))
11252 (org-update-checkbox-count)
11253 (let ((pos (move-marker (make-marker) (point)))
11254 end l1 l2)
11255 (ignore-errors (org-back-to-heading t))
11256 (if (not (org-on-heading-p))
11257 (org-update-checkbox-count)
11258 (setq l1 (org-outline-level))
11259 (setq end (save-excursion
11260 (outline-next-heading)
11261 (if (org-on-heading-p) (setq l2 (org-outline-level)))
11262 (point)))
11263 (if (and (save-excursion
11264 (re-search-forward
11265 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
11266 (not (save-excursion (re-search-forward
11267 ":COOKIE_DATA:.*\\<todo\\>" end t))))
11268 (org-update-checkbox-count)
11269 (if (and l2 (> l2 l1))
11270 (progn
11271 (goto-char end)
11272 (org-update-parent-todo-statistics))
11273 (goto-char pos)
11274 (beginning-of-line 1)
11275 (while (re-search-forward
11276 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
11277 (point-at-eol) t)
11278 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
11279 (goto-char pos)
11280 (move-marker pos nil)))))
11282 (defvar org-entry-property-inherited-from) ;; defined below
11283 (defun org-update-parent-todo-statistics ()
11284 "Update any statistics cookie in the parent of the current headline.
11285 When `org-hierarchical-todo-statistics' is nil, statistics will cover
11286 the entire subtree and this will travel up the hierarchy and update
11287 statistics everywhere."
11288 (interactive)
11289 (let* ((lim 0) prop
11290 (recursive (or (not org-hierarchical-todo-statistics)
11291 (string-match
11292 "\\<recursive\\>"
11293 (or (setq prop (org-entry-get
11294 nil "COOKIE_DATA" 'inherit)) ""))))
11295 (lim (or (and prop (marker-position
11296 org-entry-property-inherited-from))
11297 lim))
11298 (first t)
11299 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
11300 level ltoggle l1 new ndel
11301 (cnt-all 0) (cnt-done 0) is-percent kwd
11302 checkbox-beg ov ovs ove cookie-present)
11303 (catch 'exit
11304 (save-excursion
11305 (beginning-of-line 1)
11306 (if (org-at-heading-p)
11307 (setq ltoggle (funcall outline-level))
11308 (error "This should not happen"))
11309 (while (and (setq level (org-up-heading-safe))
11310 (or recursive first)
11311 (>= (point) lim))
11312 (setq first nil cookie-present nil)
11313 (unless (and level
11314 (not (string-match
11315 "\\<checkbox\\>"
11316 (downcase
11317 (or (org-entry-get
11318 nil "COOKIE_DATA")
11319 "")))))
11320 (throw 'exit nil))
11321 (while (re-search-forward box-re (point-at-eol) t)
11322 (setq cnt-all 0 cnt-done 0 cookie-present t)
11323 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
11324 (save-match-data
11325 (unless (outline-next-heading) (throw 'exit nil))
11326 (while (and (looking-at org-complex-heading-regexp)
11327 (> (setq l1 (length (match-string 1))) level))
11328 (setq kwd (and (or recursive (= l1 ltoggle))
11329 (match-string 2)))
11330 (if (or (eq org-provide-todo-statistics 'all-headlines)
11331 (and (listp org-provide-todo-statistics)
11332 (or (member kwd org-provide-todo-statistics)
11333 (member kwd org-done-keywords))))
11334 (setq cnt-all (1+ cnt-all))
11335 (if (eq org-provide-todo-statistics t)
11336 (and kwd (setq cnt-all (1+ cnt-all)))))
11337 (and (member kwd org-done-keywords)
11338 (setq cnt-done (1+ cnt-done)))
11339 (outline-next-heading)))
11340 (setq new
11341 (if is-percent
11342 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
11343 (format "[%d/%d]" cnt-done cnt-all))
11344 ndel (- (match-end 0) checkbox-beg))
11345 ;; handle overlays when updating cookie from column view
11346 (when (setq ov (car (overlays-at checkbox-beg)))
11347 (setq ovs (overlay-start ov) ove (overlay-end ov))
11348 (delete-overlay ov))
11349 (goto-char checkbox-beg)
11350 (insert new)
11351 (delete-region (point) (+ (point) ndel))
11352 (when org-auto-align-tags (org-fix-tags-on-the-fly))
11353 (when ov (move-overlay ov ovs ove)))
11354 (when cookie-present
11355 (run-hook-with-args 'org-after-todo-statistics-hook
11356 cnt-done (- cnt-all cnt-done))))))
11357 (run-hooks 'org-todo-statistics-hook)))
11359 (defvar org-after-todo-statistics-hook nil
11360 "Hook that is called after a TODO statistics cookie has been updated.
11361 Each function is called with two arguments: the number of not-done entries
11362 and the number of done entries.
11364 For example, the following function, when added to this hook, will switch
11365 an entry to DONE when all children are done, and back to TODO when new
11366 entries are set to a TODO status. Note that this hook is only called
11367 when there is a statistics cookie in the headline!
11369 (defun org-summary-todo (n-done n-not-done)
11370 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
11371 (let (org-log-done org-log-states) ; turn off logging
11372 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
11375 (defvar org-todo-statistics-hook nil
11376 "Hook that is run whenever Org thinks TODO statistics should be updated.
11377 This hook runs even if there is no statistics cookie present, in which case
11378 `org-after-todo-statistics-hook' would not run.")
11380 (defun org-todo-trigger-tag-changes (state)
11381 "Apply the changes defined in `org-todo-state-tags-triggers'."
11382 (let ((l org-todo-state-tags-triggers)
11383 changes)
11384 (when (or (not state) (equal state ""))
11385 (setq changes (append changes (cdr (assoc "" l)))))
11386 (when (and (stringp state) (> (length state) 0))
11387 (setq changes (append changes (cdr (assoc state l)))))
11388 (when (member state org-not-done-keywords)
11389 (setq changes (append changes (cdr (assoc 'todo l)))))
11390 (when (member state org-done-keywords)
11391 (setq changes (append changes (cdr (assoc 'done l)))))
11392 (dolist (c changes)
11393 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
11395 (defun org-local-logging (value)
11396 "Get logging settings from a property VALUE."
11397 (let* (words w a)
11398 ;; directly set the variables, they are already local.
11399 (setq org-log-done nil
11400 org-log-repeat nil
11401 org-todo-log-states nil)
11402 (setq words (org-split-string value))
11403 (while (setq w (pop words))
11404 (cond
11405 ((setq a (assoc w org-startup-options))
11406 (and (member (nth 1 a) '(org-log-done org-log-repeat))
11407 (set (nth 1 a) (nth 2 a))))
11408 ((setq a (org-extract-log-state-settings w))
11409 (and (member (car a) org-todo-keywords-1)
11410 (push a org-todo-log-states)))))))
11412 (defun org-get-todo-sequence-head (kwd)
11413 "Return the head of the TODO sequence to which KWD belongs.
11414 If KWD is not set, check if there is a text property remembering the
11415 right sequence."
11416 (let (p)
11417 (cond
11418 ((not kwd)
11419 (or (get-text-property (point-at-bol) 'org-todo-head)
11420 (progn
11421 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
11422 nil (point-at-eol)))
11423 (get-text-property p 'org-todo-head))))
11424 ((not (member kwd org-todo-keywords-1))
11425 (car org-todo-keywords-1))
11426 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
11428 (defun org-fast-todo-selection ()
11429 "Fast TODO keyword selection with single keys.
11430 Returns the new TODO keyword, or nil if no state change should occur."
11431 (let* ((fulltable org-todo-key-alist)
11432 (done-keywords org-done-keywords) ;; needed for the faces.
11433 (maxlen (apply 'max (mapcar
11434 (lambda (x)
11435 (if (stringp (car x)) (string-width (car x)) 0))
11436 fulltable)))
11437 (expert nil)
11438 (fwidth (+ maxlen 3 1 3))
11439 (ncol (/ (- (window-width) 4) fwidth))
11440 tg cnt e c tbl
11441 groups ingroup)
11442 (save-excursion
11443 (save-window-excursion
11444 (if expert
11445 (set-buffer (get-buffer-create " *Org todo*"))
11446 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
11447 (erase-buffer)
11448 (org-set-local 'org-done-keywords done-keywords)
11449 (setq tbl fulltable cnt 0)
11450 (while (setq e (pop tbl))
11451 (cond
11452 ((equal e '(:startgroup))
11453 (push '() groups) (setq ingroup t)
11454 (when (not (= cnt 0))
11455 (setq cnt 0)
11456 (insert "\n"))
11457 (insert "{ "))
11458 ((equal e '(:endgroup))
11459 (setq ingroup nil cnt 0)
11460 (insert "}\n"))
11461 ((equal e '(:newline))
11462 (when (not (= cnt 0))
11463 (setq cnt 0)
11464 (insert "\n")
11465 (setq e (car tbl))
11466 (while (equal (car tbl) '(:newline))
11467 (insert "\n")
11468 (setq tbl (cdr tbl)))))
11470 (setq tg (car e) c (cdr e))
11471 (if ingroup (push tg (car groups)))
11472 (setq tg (org-add-props tg nil 'face
11473 (org-get-todo-face tg)))
11474 (if (and (= cnt 0) (not ingroup)) (insert " "))
11475 (insert "[" c "] " tg (make-string
11476 (- fwidth 4 (length tg)) ?\ ))
11477 (when (= (setq cnt (1+ cnt)) ncol)
11478 (insert "\n")
11479 (if ingroup (insert " "))
11480 (setq cnt 0)))))
11481 (insert "\n")
11482 (goto-char (point-min))
11483 (if (not expert) (org-fit-window-to-buffer))
11484 (message "[a-z..]:Set [SPC]:clear")
11485 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
11486 (cond
11487 ((or (= c ?\C-g)
11488 (and (= c ?q) (not (rassoc c fulltable))))
11489 (setq quit-flag t))
11490 ((= c ?\ ) nil)
11491 ((setq e (rassoc c fulltable) tg (car e))
11493 (t (setq quit-flag t)))))))
11495 (defun org-entry-is-todo-p ()
11496 (member (org-get-todo-state) org-not-done-keywords))
11498 (defun org-entry-is-done-p ()
11499 (member (org-get-todo-state) org-done-keywords))
11501 (defun org-get-todo-state ()
11502 (save-excursion
11503 (org-back-to-heading t)
11504 (and (looking-at org-todo-line-regexp)
11505 (match-end 2)
11506 (match-string 2))))
11508 (defun org-at-date-range-p (&optional inactive-ok)
11509 "Is the cursor inside a date range?"
11510 (interactive)
11511 (save-excursion
11512 (catch 'exit
11513 (let ((pos (point)))
11514 (skip-chars-backward "^[<\r\n")
11515 (skip-chars-backward "<[")
11516 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
11517 (>= (match-end 0) pos)
11518 (throw 'exit t))
11519 (skip-chars-backward "^<[\r\n")
11520 (skip-chars-backward "<[")
11521 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
11522 (>= (match-end 0) pos)
11523 (throw 'exit t)))
11524 nil)))
11526 (defun org-get-repeat (&optional tagline)
11527 "Check if there is a deadline/schedule with repeater in this entry."
11528 (save-match-data
11529 (save-excursion
11530 (org-back-to-heading t)
11531 (and (re-search-forward (if tagline
11532 (concat tagline "\\s-*" org-repeat-re)
11533 org-repeat-re)
11534 (org-entry-end-position) t)
11535 (match-string-no-properties 1)))))
11537 (defvar org-last-changed-timestamp)
11538 (defvar org-last-inserted-timestamp)
11539 (defvar org-log-post-message)
11540 (defvar org-log-note-purpose)
11541 (defvar org-log-note-how)
11542 (defvar org-log-note-extra)
11543 (defun org-auto-repeat-maybe (done-word)
11544 "Check if the current headline contains a repeated deadline/schedule.
11545 If yes, set TODO state back to what it was and change the base date
11546 of repeating deadline/scheduled time stamps to new date.
11547 This function is run automatically after each state change to a DONE state."
11548 ;; last-state is dynamically scoped into this function
11549 (let* ((repeat (org-get-repeat))
11550 (aa (assoc last-state org-todo-kwd-alist))
11551 (interpret (nth 1 aa))
11552 (head (nth 2 aa))
11553 (whata '(("d" . day) ("m" . month) ("y" . year)))
11554 (msg "Entry repeats: ")
11555 (org-log-done nil)
11556 (org-todo-log-states nil)
11557 re type n what ts time to-state)
11558 (when repeat
11559 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
11560 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
11561 org-todo-repeat-to-state))
11562 (unless (and to-state (member to-state org-todo-keywords-1))
11563 (setq to-state (if (eq interpret 'type) last-state head)))
11564 (org-todo to-state)
11565 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
11566 (org-entry-put nil "LAST_REPEAT" (format-time-string
11567 (org-time-stamp-format t t))))
11568 (when org-log-repeat
11569 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
11570 (memq 'org-add-log-note post-command-hook))
11571 ;; OK, we are already setup for some record
11572 (if (eq org-log-repeat 'note)
11573 ;; make sure we take a note, not only a time stamp
11574 (setq org-log-note-how 'note))
11575 ;; Set up for taking a record
11576 (org-add-log-setup 'state (or done-word (car org-done-keywords))
11577 last-state
11578 'findpos org-log-repeat)))
11579 (org-back-to-heading t)
11580 (org-add-planning-info nil nil 'closed)
11581 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
11582 org-deadline-time-regexp "\\)\\|\\("
11583 org-ts-regexp "\\)"))
11584 (while (re-search-forward
11585 re (save-excursion (outline-next-heading) (point)) t)
11586 (setq type (if (match-end 1) org-scheduled-string
11587 (if (match-end 3) org-deadline-string "Plain:"))
11588 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
11589 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
11590 (setq n (string-to-number (match-string 2 ts))
11591 what (match-string 3 ts))
11592 (if (equal what "w") (setq n (* n 7) what "d"))
11593 ;; Preparation, see if we need to modify the start date for the change
11594 (when (match-end 1)
11595 (setq time (save-match-data (org-time-string-to-time ts)))
11596 (cond
11597 ((equal (match-string 1 ts) ".")
11598 ;; Shift starting date to today
11599 (org-timestamp-change
11600 (- (time-to-days (current-time)) (time-to-days time))
11601 'day))
11602 ((equal (match-string 1 ts) "+")
11603 (let ((nshiftmax 10) (nshift 0))
11604 (while (or (= nshift 0)
11605 (<= (time-to-days time)
11606 (time-to-days (current-time))))
11607 (when (= (incf nshift) nshiftmax)
11608 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
11609 (error "Abort")))
11610 (org-timestamp-change n (cdr (assoc what whata)))
11611 (org-at-timestamp-p t)
11612 (setq ts (match-string 1))
11613 (setq time (save-match-data (org-time-string-to-time ts)))))
11614 (org-timestamp-change (- n) (cdr (assoc what whata)))
11615 ;; rematch, so that we have everything in place for the real shift
11616 (org-at-timestamp-p t)
11617 (setq ts (match-string 1))
11618 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
11619 (org-timestamp-change n (cdr (assoc what whata)))
11620 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
11621 (setq org-log-post-message msg)
11622 (message "%s" msg))))
11624 (defun org-show-todo-tree (arg)
11625 "Make a compact tree which shows all headlines marked with TODO.
11626 The tree will show the lines where the regexp matches, and all higher
11627 headlines above the match.
11628 With a \\[universal-argument] prefix, prompt for a regexp to match.
11629 With a numeric prefix N, construct a sparse tree for the Nth element
11630 of `org-todo-keywords-1'."
11631 (interactive "P")
11632 (let ((case-fold-search nil)
11633 (kwd-re
11634 (cond ((null arg) org-not-done-regexp)
11635 ((equal arg '(4))
11636 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
11637 (mapcar 'list org-todo-keywords-1))))
11638 (concat "\\("
11639 (mapconcat 'identity (org-split-string kwd "|") "\\|")
11640 "\\)\\>")))
11641 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
11642 (regexp-quote (nth (1- (prefix-numeric-value arg))
11643 org-todo-keywords-1)))
11644 (t (error "Invalid prefix argument: %s" arg)))))
11645 (message "%d TODO entries found"
11646 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
11648 (defun org-deadline (&optional remove time)
11649 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
11650 With argument REMOVE, remove any deadline from the item.
11651 When TIME is set, it should be an internal time specification, and the
11652 scheduling will use the corresponding date."
11653 (interactive "P")
11654 (let* ((old-date (org-entry-get nil "DEADLINE"))
11655 (repeater (and old-date
11656 (string-match
11657 "\\([.+-]+[0-9]+[dwmy]\\(?:[/ ][-+]?[0-9]+[dwmy]\\)?\\) ?"
11658 old-date)
11659 (match-string 1 old-date))))
11660 (if remove
11661 (progn
11662 (when (and old-date org-log-redeadline)
11663 (org-add-log-setup 'deldeadline nil old-date 'findpos
11664 org-log-redeadline))
11665 (org-remove-timestamp-with-keyword org-deadline-string)
11666 (message "Item no longer has a deadline."))
11667 (org-add-planning-info 'deadline time 'closed)
11668 (when (and old-date org-log-redeadline
11669 (not (equal old-date
11670 (substring org-last-inserted-timestamp 1 -1))))
11671 (org-add-log-setup 'redeadline nil old-date 'findpos
11672 org-log-redeadline))
11673 (when repeater
11674 (save-excursion
11675 (org-back-to-heading t)
11676 (when (re-search-forward (concat org-deadline-string " "
11677 org-last-inserted-timestamp)
11678 (save-excursion
11679 (outline-next-heading) (point)) t)
11680 (goto-char (1- (match-end 0)))
11681 (insert " " repeater)
11682 (setq org-last-inserted-timestamp
11683 (concat (substring org-last-inserted-timestamp 0 -1)
11684 " " repeater
11685 (substring org-last-inserted-timestamp -1))))))
11686 (message "Deadline on %s" org-last-inserted-timestamp))))
11688 (defun org-schedule (&optional remove time)
11689 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
11690 With argument REMOVE, remove any scheduling date from the item.
11691 When TIME is set, it should be an internal time specification, and the
11692 scheduling will use the corresponding date."
11693 (interactive "P")
11694 (let* ((old-date (org-entry-get nil "SCHEDULED"))
11695 (repeater (and old-date
11696 (string-match
11697 "\\([.+-]+[0-9]+[dwmy]\\(?:[/ ][-+]?[0-9]+[dwmy]\\)?\\) ?"
11698 old-date)
11699 (match-string 1 old-date))))
11700 (if remove
11701 (progn
11702 (when (and old-date org-log-reschedule)
11703 (org-add-log-setup 'delschedule nil old-date 'findpos
11704 org-log-reschedule))
11705 (org-remove-timestamp-with-keyword org-scheduled-string)
11706 (message "Item is no longer scheduled."))
11707 (org-add-planning-info 'scheduled time 'closed)
11708 (when (and old-date org-log-reschedule
11709 (not (equal old-date
11710 (substring org-last-inserted-timestamp 1 -1))))
11711 (org-add-log-setup 'reschedule nil old-date 'findpos
11712 org-log-reschedule))
11713 (when repeater
11714 (save-excursion
11715 (org-back-to-heading t)
11716 (when (re-search-forward (concat org-scheduled-string " "
11717 org-last-inserted-timestamp)
11718 (save-excursion
11719 (outline-next-heading) (point)) t)
11720 (goto-char (1- (match-end 0)))
11721 (insert " " repeater)
11722 (setq org-last-inserted-timestamp
11723 (concat (substring org-last-inserted-timestamp 0 -1)
11724 " " repeater
11725 (substring org-last-inserted-timestamp -1))))))
11726 (message "Scheduled to %s" org-last-inserted-timestamp))))
11728 (defun org-get-scheduled-time (pom &optional inherit)
11729 "Get the scheduled time as a time tuple, of a format suitable
11730 for calling org-schedule with, or if there is no scheduling,
11731 returns nil."
11732 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
11733 (when time
11734 (apply 'encode-time (org-parse-time-string time)))))
11736 (defun org-get-deadline-time (pom &optional inherit)
11737 "Get the deadline as a time tuple, of a format suitable for
11738 calling org-deadline with, or if there is no scheduling, returns
11739 nil."
11740 (let ((time (org-entry-get pom "DEADLINE" inherit)))
11741 (when time
11742 (apply 'encode-time (org-parse-time-string time)))))
11744 (defun org-remove-timestamp-with-keyword (keyword)
11745 "Remove all time stamps with KEYWORD in the current entry."
11746 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
11747 beg)
11748 (save-excursion
11749 (org-back-to-heading t)
11750 (setq beg (point))
11751 (outline-next-heading)
11752 (while (re-search-backward re beg t)
11753 (replace-match "")
11754 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
11755 (equal (char-before) ?\ ))
11756 (backward-delete-char 1)
11757 (if (string-match "^[ \t]*$" (buffer-substring
11758 (point-at-bol) (point-at-eol)))
11759 (delete-region (point-at-bol)
11760 (min (point-max) (1+ (point-at-eol))))))))))
11762 (defun org-add-planning-info (what &optional time &rest remove)
11763 "Insert new timestamp with keyword in the line directly after the headline.
11764 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
11765 If non is given, the user is prompted for a date.
11766 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
11767 be removed."
11768 (interactive)
11769 (let (org-time-was-given org-end-time-was-given ts
11770 end default-time default-input)
11772 (catch 'exit
11773 (when (and (not time) (memq what '(scheduled deadline)))
11774 ;; Try to get a default date/time from existing timestamp
11775 (save-excursion
11776 (org-back-to-heading t)
11777 (setq end (save-excursion (outline-next-heading) (point)))
11778 (when (re-search-forward (if (eq what 'scheduled)
11779 org-scheduled-time-regexp
11780 org-deadline-time-regexp)
11781 end t)
11782 (setq ts (match-string 1)
11783 default-time
11784 (apply 'encode-time (org-parse-time-string ts))
11785 default-input (and ts (org-get-compact-tod ts))))))
11786 (when what
11787 ;; If necessary, get the time from the user
11788 (setq time (or time (org-read-date nil 'to-time nil nil
11789 default-time default-input))))
11791 (when (and org-insert-labeled-timestamps-at-point
11792 (member what '(scheduled deadline)))
11793 (insert
11794 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
11795 (org-insert-time-stamp time org-time-was-given
11796 nil nil nil (list org-end-time-was-given))
11797 (setq what nil))
11798 (save-excursion
11799 (save-restriction
11800 (let (col list elt ts buffer-invisibility-spec)
11801 (org-back-to-heading t)
11802 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
11803 (goto-char (match-end 1))
11804 (setq col (current-column))
11805 (goto-char (match-end 0))
11806 (if (eobp) (insert "\n") (forward-char 1))
11807 (when (and (not what)
11808 (not (looking-at
11809 (concat "[ \t]*"
11810 org-keyword-time-not-clock-regexp))))
11811 ;; Nothing to add, nothing to remove...... :-)
11812 (throw 'exit nil))
11813 (if (and (not (looking-at outline-regexp))
11814 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
11815 "[^\r\n]*"))
11816 (not (equal (match-string 1) org-clock-string)))
11817 (narrow-to-region (match-beginning 0) (match-end 0))
11818 (insert-before-markers "\n")
11819 (backward-char 1)
11820 (narrow-to-region (point) (point))
11821 (and org-adapt-indentation (org-indent-to-column col)))
11822 ;; Check if we have to remove something.
11823 (setq list (cons what remove))
11824 (while list
11825 (setq elt (pop list))
11826 (goto-char (point-min))
11827 (when (or (and (eq elt 'scheduled)
11828 (re-search-forward org-scheduled-time-regexp nil t))
11829 (and (eq elt 'deadline)
11830 (re-search-forward org-deadline-time-regexp nil t))
11831 (and (eq elt 'closed)
11832 (re-search-forward org-closed-time-regexp nil t)))
11833 (replace-match "")
11834 (if (looking-at "--+<[^>]+>") (replace-match ""))
11835 (skip-chars-backward " ")
11836 (if (looking-at " +") (replace-match ""))))
11837 (goto-char (point-max))
11838 (and org-adapt-indentation (bolp) (org-indent-to-column col))
11839 (when what
11840 (insert
11841 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
11842 (cond ((eq what 'scheduled) org-scheduled-string)
11843 ((eq what 'deadline) org-deadline-string)
11844 ((eq what 'closed) org-closed-string))
11845 " ")
11846 (setq ts (org-insert-time-stamp
11847 time
11848 (or org-time-was-given
11849 (and (eq what 'closed) org-log-done-with-time))
11850 (eq what 'closed)
11851 nil nil (list org-end-time-was-given)))
11852 (end-of-line 1))
11853 (goto-char (point-min))
11854 (widen)
11855 (if (and (looking-at "[ \t]*\n")
11856 (equal (char-before) ?\n))
11857 (delete-region (1- (point)) (point-at-eol)))
11858 ts))))))
11860 (defvar org-log-note-marker (make-marker))
11861 (defvar org-log-note-purpose nil)
11862 (defvar org-log-note-state nil)
11863 (defvar org-log-note-previous-state nil)
11864 (defvar org-log-note-how nil)
11865 (defvar org-log-note-extra nil)
11866 (defvar org-log-note-window-configuration nil)
11867 (defvar org-log-note-return-to (make-marker))
11868 (defvar org-log-post-message nil
11869 "Message to be displayed after a log note has been stored.
11870 The auto-repeater uses this.")
11872 (defun org-add-note ()
11873 "Add a note to the current entry.
11874 This is done in the same way as adding a state change note."
11875 (interactive)
11876 (org-add-log-setup 'note nil nil 'findpos nil))
11878 (defvar org-property-end-re)
11879 (defun org-add-log-setup (&optional purpose state prev-state
11880 findpos how extra)
11881 "Set up the post command hook to take a note.
11882 If this is about to TODO state change, the new state is expected in STATE.
11883 When FINDPOS is non-nil, find the correct position for the note in
11884 the current entry. If not, assume that it can be inserted at point.
11885 HOW is an indicator what kind of note should be created.
11886 EXTRA is additional text that will be inserted into the notes buffer."
11887 (let* ((org-log-into-drawer (org-log-into-drawer))
11888 (drawer (cond ((stringp org-log-into-drawer)
11889 org-log-into-drawer)
11890 (org-log-into-drawer "LOGBOOK")
11891 (t nil))))
11892 (save-restriction
11893 (save-excursion
11894 (when findpos
11895 (org-back-to-heading t)
11896 (narrow-to-region (point) (save-excursion
11897 (outline-next-heading) (point)))
11898 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
11899 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
11900 "[^\r\n]*\\)?"))
11901 (goto-char (match-end 0))
11902 (cond
11903 (drawer
11904 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
11905 nil t)
11906 (progn
11907 (goto-char (match-end 0))
11908 (or org-log-states-order-reversed
11909 (and (re-search-forward org-property-end-re nil t)
11910 (goto-char (1- (match-beginning 0))))))
11911 (insert "\n:" drawer ":\n:END:")
11912 (beginning-of-line 0)
11913 (org-indent-line-function)
11914 (beginning-of-line 2)
11915 (org-indent-line-function)
11916 (end-of-line 0)))
11917 ((and org-log-state-notes-insert-after-drawers
11918 (save-excursion
11919 (forward-line) (looking-at org-drawer-regexp)))
11920 (forward-line)
11921 (while (looking-at org-drawer-regexp)
11922 (goto-char (match-end 0))
11923 (re-search-forward org-property-end-re (point-max) t)
11924 (forward-line))
11925 (forward-line -1)))
11926 (unless org-log-states-order-reversed
11927 (and (= (char-after) ?\n) (forward-char 1))
11928 (org-skip-over-state-notes)
11929 (skip-chars-backward " \t\n\r")))
11930 (move-marker org-log-note-marker (point))
11931 (setq org-log-note-purpose purpose
11932 org-log-note-state state
11933 org-log-note-previous-state prev-state
11934 org-log-note-how how
11935 org-log-note-extra extra)
11936 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
11938 (defun org-skip-over-state-notes ()
11939 "Skip past the list of State notes in an entry."
11940 (if (looking-at "\n[ \t]*- State") (forward-char 1))
11941 (when (ignore-errors (goto-char (org-in-item-p)))
11942 (let* ((struct (org-list-struct))
11943 (prevs (org-list-prevs-alist struct)))
11944 (while (looking-at "[ \t]*- State")
11945 (goto-char (or (org-list-get-next-item (point) struct prevs)
11946 (org-list-get-item-end (point) struct)))))))
11948 (defun org-add-log-note (&optional purpose)
11949 "Pop up a window for taking a note, and add this note later at point."
11950 (remove-hook 'post-command-hook 'org-add-log-note)
11951 (setq org-log-note-window-configuration (current-window-configuration))
11952 (delete-other-windows)
11953 (move-marker org-log-note-return-to (point))
11954 (switch-to-buffer (marker-buffer org-log-note-marker))
11955 (goto-char org-log-note-marker)
11956 (org-switch-to-buffer-other-window "*Org Note*")
11957 (erase-buffer)
11958 (if (memq org-log-note-how '(time state))
11959 (let (current-prefix-arg) (org-store-log-note))
11960 (let ((org-inhibit-startup t)) (org-mode))
11961 (insert (format "# Insert note for %s.
11962 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
11963 (cond
11964 ((eq org-log-note-purpose 'clock-out) "stopped clock")
11965 ((eq org-log-note-purpose 'done) "closed todo item")
11966 ((eq org-log-note-purpose 'state)
11967 (format "state change from \"%s\" to \"%s\""
11968 (or org-log-note-previous-state "")
11969 (or org-log-note-state "")))
11970 ((eq org-log-note-purpose 'reschedule)
11971 "rescheduling")
11972 ((eq org-log-note-purpose 'delschedule)
11973 "no longer scheduled")
11974 ((eq org-log-note-purpose 'redeadline)
11975 "changing deadline")
11976 ((eq org-log-note-purpose 'deldeadline)
11977 "removing deadline")
11978 ((eq org-log-note-purpose 'refile)
11979 "refiling")
11980 ((eq org-log-note-purpose 'note)
11981 "this entry")
11982 (t (error "This should not happen")))))
11983 (if org-log-note-extra (insert org-log-note-extra))
11984 (org-set-local 'org-finish-function 'org-store-log-note)))
11986 (defvar org-note-abort nil) ; dynamically scoped
11987 (defun org-store-log-note ()
11988 "Finish taking a log note, and insert it to where it belongs."
11989 (let ((txt (buffer-string))
11990 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
11991 lines ind bul)
11992 (kill-buffer (current-buffer))
11993 (while (string-match "\\`#.*\n[ \t\n]*" txt)
11994 (setq txt (replace-match "" t t txt)))
11995 (if (string-match "\\s-+\\'" txt)
11996 (setq txt (replace-match "" t t txt)))
11997 (setq lines (org-split-string txt "\n"))
11998 (when (and note (string-match "\\S-" note))
11999 (setq note
12000 (org-replace-escapes
12001 note
12002 (list (cons "%u" (user-login-name))
12003 (cons "%U" user-full-name)
12004 (cons "%t" (format-time-string
12005 (org-time-stamp-format 'long 'inactive)
12006 (current-time)))
12007 (cons "%T" (format-time-string
12008 (org-time-stamp-format 'long nil)
12009 (current-time)))
12010 (cons "%s" (if org-log-note-state
12011 (concat "\"" org-log-note-state "\"")
12012 ""))
12013 (cons "%S" (if org-log-note-previous-state
12014 (concat "\"" org-log-note-previous-state "\"")
12015 "\"\"")))))
12016 (if lines (setq note (concat note " \\\\")))
12017 (push note lines))
12018 (when (or current-prefix-arg org-note-abort)
12019 (when org-log-into-drawer
12020 (org-remove-empty-drawer-at
12021 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
12022 org-log-note-marker))
12023 (setq lines nil))
12024 (when lines
12025 (with-current-buffer (marker-buffer org-log-note-marker)
12026 (save-excursion
12027 (goto-char org-log-note-marker)
12028 (move-marker org-log-note-marker nil)
12029 (end-of-line 1)
12030 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
12031 (setq ind (save-excursion
12032 (if (ignore-errors (goto-char (org-in-item-p)))
12033 (let ((struct (org-list-struct)))
12034 (org-list-get-ind
12035 (org-list-get-top-point struct) struct))
12036 (skip-chars-backward " \r\t\n")
12037 (cond
12038 ((and (org-at-heading-p)
12039 org-adapt-indentation)
12040 (1+ (org-current-level)))
12041 ((org-at-heading-p) 0)
12042 (t (org-get-indentation))))))
12043 (setq bul (org-list-bullet-string "-"))
12044 (org-indent-line-to ind)
12045 (insert bul (pop lines))
12046 (let ((ind-body (+ (length bul) ind)))
12047 (while lines
12048 (insert "\n")
12049 (org-indent-line-to ind-body)
12050 (insert (pop lines))))
12051 (message "Note stored")
12052 (org-back-to-heading t)
12053 (org-cycle-hide-drawers 'children)))))
12054 (set-window-configuration org-log-note-window-configuration)
12055 (with-current-buffer (marker-buffer org-log-note-return-to)
12056 (goto-char org-log-note-return-to))
12057 (move-marker org-log-note-return-to nil)
12058 (and org-log-post-message (message "%s" org-log-post-message)))
12060 (defun org-remove-empty-drawer-at (drawer pos)
12061 "Remove an empty drawer DRAWER at position POS.
12062 POS may also be a marker."
12063 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
12064 (save-excursion
12065 (save-restriction
12066 (widen)
12067 (goto-char pos)
12068 (if (org-in-regexp
12069 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
12070 (replace-match ""))))))
12072 (defun org-sparse-tree (&optional arg)
12073 "Create a sparse tree, prompt for the details.
12074 This command can create sparse trees. You first need to select the type
12075 of match used to create the tree:
12077 t Show all TODO entries.
12078 T Show entries with a specific TODO keyword.
12079 m Show entries selected by a tags/property match.
12080 p Enter a property name and its value (both with completion on existing
12081 names/values) and show entries with that property.
12082 r Show entries matching a regular expression (`/' can be used as well)
12083 d Show deadlines due within `org-deadline-warning-days'.
12084 b Show deadlines and scheduled items before a date.
12085 a Show deadlines and scheduled items after a date."
12086 (interactive "P")
12087 (let (ans kwd value)
12088 (message "Sparse tree: [r]egexp [/]regexp [t]odo [T]odo-kwd [m]atch [p]roperty\n [d]eadlines [b]efore-date [a]fter-date")
12089 (setq ans (read-char-exclusive))
12090 (cond
12091 ((equal ans ?d)
12092 (call-interactively 'org-check-deadlines))
12093 ((equal ans ?b)
12094 (call-interactively 'org-check-before-date))
12095 ((equal ans ?a)
12096 (call-interactively 'org-check-after-date))
12097 ((equal ans ?t)
12098 (org-show-todo-tree nil))
12099 ((equal ans ?T)
12100 (org-show-todo-tree '(4)))
12101 ((member ans '(?T ?m))
12102 (call-interactively 'org-match-sparse-tree))
12103 ((member ans '(?p ?P))
12104 (setq kwd (org-icompleting-read "Property: "
12105 (mapcar 'list (org-buffer-property-keys))))
12106 (setq value (org-icompleting-read "Value: "
12107 (mapcar 'list (org-property-values kwd))))
12108 (unless (string-match "\\`{.*}\\'" value)
12109 (setq value (concat "\"" value "\"")))
12110 (org-match-sparse-tree arg (concat kwd "=" value)))
12111 ((member ans '(?r ?R ?/))
12112 (call-interactively 'org-occur))
12113 (t (error "No such sparse tree command \"%c\"" ans)))))
12115 (defvar org-occur-highlights nil
12116 "List of overlays used for occur matches.")
12117 (make-variable-buffer-local 'org-occur-highlights)
12118 (defvar org-occur-parameters nil
12119 "Parameters of the active org-occur calls.
12120 This is a list, each call to org-occur pushes as cons cell,
12121 containing the regular expression and the callback, onto the list.
12122 The list can contain several entries if `org-occur' has been called
12123 several time with the KEEP-PREVIOUS argument. Otherwise, this list
12124 will only contain one set of parameters. When the highlights are
12125 removed (for example with `C-c C-c', or with the next edit (depending
12126 on `org-remove-highlights-with-change'), this variable is emptied
12127 as well.")
12128 (make-variable-buffer-local 'org-occur-parameters)
12130 (defun org-occur (regexp &optional keep-previous callback)
12131 "Make a compact tree which shows all matches of REGEXP.
12132 The tree will show the lines where the regexp matches, and all higher
12133 headlines above the match. It will also show the heading after the match,
12134 to make sure editing the matching entry is easy.
12135 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
12136 call to `org-occur' will be kept, to allow stacking of calls to this
12137 command.
12138 If CALLBACK is non-nil, it is a function which is called to confirm
12139 that the match should indeed be shown."
12140 (interactive "sRegexp: \nP")
12141 (when (equal regexp "")
12142 (error "Regexp cannot be empty"))
12143 (unless keep-previous
12144 (org-remove-occur-highlights nil nil t))
12145 (push (cons regexp callback) org-occur-parameters)
12146 (let ((cnt 0))
12147 (save-excursion
12148 (goto-char (point-min))
12149 (if (or (not keep-previous) ; do not want to keep
12150 (not org-occur-highlights)) ; no previous matches
12151 ;; hide everything
12152 (org-overview))
12153 (while (re-search-forward regexp nil t)
12154 (when (or (not callback)
12155 (save-match-data (funcall callback)))
12156 (setq cnt (1+ cnt))
12157 (when org-highlight-sparse-tree-matches
12158 (org-highlight-new-match (match-beginning 0) (match-end 0)))
12159 (org-show-context 'occur-tree))))
12160 (when org-remove-highlights-with-change
12161 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
12162 nil 'local))
12163 (unless org-sparse-tree-open-archived-trees
12164 (org-hide-archived-subtrees (point-min) (point-max)))
12165 (run-hooks 'org-occur-hook)
12166 (if (org-called-interactively-p 'interactive)
12167 (message "%d match(es) for regexp %s" cnt regexp))
12168 cnt))
12170 (defun org-occur-next-match (&optional n reset)
12171 "Function for `next-error-function' to find sparse tree matches.
12172 N is the number of matches to move, when negative move backwards.
12173 RESET is entirely ignored - this function always goes back to the
12174 starting point when no match is found."
12175 (let* ((limit (if (< n 0) (point-min) (point-max)))
12176 (search-func (if (< n 0)
12177 'previous-single-char-property-change
12178 'next-single-char-property-change))
12179 (n (abs n))
12180 (pos (point))
12182 (catch 'exit
12183 (while (setq p1 (funcall search-func (point) 'org-type))
12184 (when (equal p1 limit)
12185 (goto-char pos)
12186 (error "No more matches"))
12187 (when (equal (get-char-property p1 'org-type) 'org-occur)
12188 (setq n (1- n))
12189 (when (= n 0)
12190 (goto-char p1)
12191 (throw 'exit (point))))
12192 (goto-char p1))
12193 (goto-char p1)
12194 (error "No more matches"))))
12196 (defun org-show-context (&optional key)
12197 "Make sure point and context are visible.
12198 How much context is shown depends upon the variables
12199 `org-show-hierarchy-above', `org-show-following-heading'. and
12200 `org-show-siblings'."
12201 (let ((heading-p (org-on-heading-p t))
12202 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
12203 (following-p (org-get-alist-option org-show-following-heading key))
12204 (entry-p (org-get-alist-option org-show-entry-below key))
12205 (siblings-p (org-get-alist-option org-show-siblings key)))
12206 (catch 'exit
12207 ;; Show heading or entry text
12208 (if (and heading-p (not entry-p))
12209 (org-flag-heading nil) ; only show the heading
12210 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
12211 (org-show-hidden-entry))) ; show entire entry
12212 (when following-p
12213 ;; Show next sibling, or heading below text
12214 (save-excursion
12215 (and (if heading-p (org-goto-sibling) (outline-next-heading))
12216 (org-flag-heading nil))))
12217 (when siblings-p (org-show-siblings))
12218 (when hierarchy-p
12219 ;; show all higher headings, possibly with siblings
12220 (save-excursion
12221 (while (and (condition-case nil
12222 (progn (org-up-heading-all 1) t)
12223 (error nil))
12224 (not (bobp)))
12225 (org-flag-heading nil)
12226 (when siblings-p (org-show-siblings))))))))
12228 (defvar org-reveal-start-hook nil
12229 "Hook run before revealing a location.")
12231 (defun org-reveal (&optional siblings)
12232 "Show current entry, hierarchy above it, and the following headline.
12233 This can be used to show a consistent set of context around locations
12234 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
12235 not t for the search context.
12237 With optional argument SIBLINGS, on each level of the hierarchy all
12238 siblings are shown. This repairs the tree structure to what it would
12239 look like when opened with hierarchical calls to `org-cycle'.
12240 With double optional argument \\[universal-argument] \\[universal-argument], \
12241 go to the parent and show the
12242 entire tree."
12243 (interactive "P")
12244 (run-hooks 'org-reveal-start-hook)
12245 (let ((org-show-hierarchy-above t)
12246 (org-show-following-heading t)
12247 (org-show-siblings (if siblings t org-show-siblings)))
12248 (org-show-context nil))
12249 (when (equal siblings '(16))
12250 (save-excursion
12251 (when (org-up-heading-safe)
12252 (org-show-subtree)
12253 (run-hook-with-args 'org-cycle-hook 'subtree)))))
12255 (defun org-highlight-new-match (beg end)
12256 "Highlight from BEG to END and mark the highlight is an occur headline."
12257 (let ((ov (make-overlay beg end)))
12258 (overlay-put ov 'face 'secondary-selection)
12259 (overlay-put ov 'org-type 'org-occur)
12260 (push ov org-occur-highlights)))
12262 (defun org-remove-occur-highlights (&optional beg end noremove)
12263 "Remove the occur highlights from the buffer.
12264 BEG and END are ignored. If NOREMOVE is nil, remove this function
12265 from the `before-change-functions' in the current buffer."
12266 (interactive)
12267 (unless org-inhibit-highlight-removal
12268 (mapc 'delete-overlay org-occur-highlights)
12269 (setq org-occur-highlights nil)
12270 (setq org-occur-parameters nil)
12271 (unless noremove
12272 (remove-hook 'before-change-functions
12273 'org-remove-occur-highlights 'local))))
12275 ;;;; Priorities
12277 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
12278 "Regular expression matching the priority indicator.")
12280 (defvar org-remove-priority-next-time nil)
12282 (defun org-priority-up ()
12283 "Increase the priority of the current item."
12284 (interactive)
12285 (org-priority 'up))
12287 (defun org-priority-down ()
12288 "Decrease the priority of the current item."
12289 (interactive)
12290 (org-priority 'down))
12292 (defun org-priority (&optional action)
12293 "Change the priority of an item by ARG.
12294 ACTION can be `set', `up', `down', or a character."
12295 (interactive)
12296 (unless org-enable-priority-commands
12297 (error "Priority commands are disabled"))
12298 (setq action (or action 'set))
12299 (let (current new news have remove)
12300 (save-excursion
12301 (org-back-to-heading t)
12302 (if (looking-at org-priority-regexp)
12303 (setq current (string-to-char (match-string 2))
12304 have t))
12305 (cond
12306 ((eq action 'remove)
12307 (setq remove t new ?\ ))
12308 ((or (eq action 'set)
12309 (if (featurep 'xemacs) (characterp action) (integerp action)))
12310 (if (not (eq action 'set))
12311 (setq new action)
12312 (message "Priority %c-%c, SPC to remove: "
12313 org-highest-priority org-lowest-priority)
12314 (save-match-data
12315 (setq new (read-char-exclusive))))
12316 (if (and (= (upcase org-highest-priority) org-highest-priority)
12317 (= (upcase org-lowest-priority) org-lowest-priority))
12318 (setq new (upcase new)))
12319 (cond ((equal new ?\ ) (setq remove t))
12320 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
12321 (error "Priority must be between `%c' and `%c'"
12322 org-highest-priority org-lowest-priority))))
12323 ((eq action 'up)
12324 (setq new (if have
12325 (1- current) ; normal cycling
12326 ;; last priority was empty
12327 (if (eq last-command this-command)
12328 org-lowest-priority ; wrap around empty to lowest
12329 ;; default
12330 (if org-priority-start-cycle-with-default
12331 org-default-priority
12332 (1- org-default-priority))))))
12333 ((eq action 'down)
12334 (setq new (if have
12335 (1+ current) ; normal cycling
12336 ;; last priority was empty
12337 (if (eq last-command this-command)
12338 org-highest-priority ; wrap around empty to highest
12339 ;; default
12340 (if org-priority-start-cycle-with-default
12341 org-default-priority
12342 (1+ org-default-priority))))))
12343 (t (error "Invalid action")))
12344 (if (or (< (upcase new) org-highest-priority)
12345 (> (upcase new) org-lowest-priority))
12346 (if (and (memq action '(up down))
12347 (not have) (not (eq last-command this-command)))
12348 ;; `new' is from default priority
12349 (error
12350 "The default can not be set, see `org-default-priority' why")
12351 ;; normal cycling: `new' is beyond highest/lowest priority
12352 ;; and is wrapped around to the empty priority
12353 (setq remove t)))
12354 (setq news (format "%c" new))
12355 (if have
12356 (if remove
12357 (replace-match "" t t nil 1)
12358 (replace-match news t t nil 2))
12359 (if remove
12360 (error "No priority cookie found in line")
12361 (let ((case-fold-search nil))
12362 (looking-at org-todo-line-regexp))
12363 (if (match-end 2)
12364 (progn
12365 (goto-char (match-end 2))
12366 (insert " [#" news "]"))
12367 (goto-char (match-beginning 3))
12368 (insert "[#" news "] "))))
12369 (org-preserve-lc (org-set-tags nil 'align)))
12370 (if remove
12371 (message "Priority removed")
12372 (message "Priority of current item set to %s" news))))
12374 (defun org-get-priority (s)
12375 "Find priority cookie and return priority."
12376 (if (functionp org-get-priority-function)
12377 (funcall org-get-priority-function)
12378 (save-match-data
12379 (if (not (string-match org-priority-regexp s))
12380 (* 1000 (- org-lowest-priority org-default-priority))
12381 (* 1000 (- org-lowest-priority
12382 (string-to-char (match-string 2 s))))))))
12384 ;;;; Tags
12386 (defvar org-agenda-archives-mode)
12387 (defvar org-map-continue-from nil
12388 "Position from where mapping should continue.
12389 Can be set by the action argument to `org-scan-tag's and `org-map-entries'.")
12391 (defvar org-scanner-tags nil
12392 "The current tag list while the tags scanner is running.")
12393 (defvar org-trust-scanner-tags nil
12394 "Should `org-get-tags-at' use the tags for the scanner.
12395 This is for internal dynamical scoping only.
12396 When this is non-nil, the function `org-get-tags-at' will return the value
12397 of `org-scanner-tags' instead of building the list by itself. This
12398 can lead to large speed-ups when the tags scanner is used in a file with
12399 many entries, and when the list of tags is retrieved, for example to
12400 obtain a list of properties. Building the tags list for each entry in such
12401 a file becomes an N^2 operation - but with this variable set, it scales
12402 as N.")
12404 (defun org-scan-tags (action matcher &optional todo-only)
12405 "Scan headline tags with inheritance and produce output ACTION.
12407 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
12408 or `agenda' to produce an entry list for an agenda view. It can also be
12409 a Lisp form or a function that should be called at each matched headline, in
12410 this case the return value is a list of all return values from these calls.
12412 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
12413 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
12414 only lines with a TODO keyword are included in the output."
12415 (require 'org-agenda)
12416 (let* ((re (concat "^" outline-regexp " *\\(\\<\\("
12417 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
12418 (org-re
12419 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
12420 (props (list 'face 'default
12421 'done-face 'org-agenda-done
12422 'undone-face 'default
12423 'mouse-face 'highlight
12424 'org-not-done-regexp org-not-done-regexp
12425 'org-todo-regexp org-todo-regexp
12426 'help-echo
12427 (format "mouse-2 or RET jump to org file %s"
12428 (abbreviate-file-name
12429 (or (buffer-file-name (buffer-base-buffer))
12430 (buffer-name (buffer-base-buffer)))))))
12431 (case-fold-search nil)
12432 (org-map-continue-from nil)
12433 lspos tags tags-list
12434 (tags-alist (list (cons 0 org-file-tags)))
12435 (llast 0) rtn rtn1 level category i txt
12436 todo marker entry priority)
12437 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
12438 (setq action (list 'lambda nil action)))
12439 (save-excursion
12440 (goto-char (point-min))
12441 (when (eq action 'sparse-tree)
12442 (org-overview)
12443 (org-remove-occur-highlights))
12444 (while (re-search-forward re nil t)
12445 (catch :skip
12446 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
12447 tags (if (match-end 4) (org-match-string-no-properties 4)))
12448 (goto-char (setq lspos (match-beginning 0)))
12449 (setq level (org-reduced-level (funcall outline-level))
12450 category (org-get-category))
12451 (setq i llast llast level)
12452 ;; remove tag lists from same and sublevels
12453 (while (>= i level)
12454 (when (setq entry (assoc i tags-alist))
12455 (setq tags-alist (delete entry tags-alist)))
12456 (setq i (1- i)))
12457 ;; add the next tags
12458 (when tags
12459 (setq tags (org-split-string tags ":")
12460 tags-alist
12461 (cons (cons level tags) tags-alist)))
12462 ;; compile tags for current headline
12463 (setq tags-list
12464 (if org-use-tag-inheritance
12465 (apply 'append (mapcar 'cdr (reverse tags-alist)))
12466 tags)
12467 org-scanner-tags tags-list)
12468 (when org-use-tag-inheritance
12469 (setcdr (car tags-alist)
12470 (mapcar (lambda (x)
12471 (setq x (copy-sequence x))
12472 (org-add-prop-inherited x))
12473 (cdar tags-alist))))
12474 (when (and tags org-use-tag-inheritance
12475 (or (not (eq t org-use-tag-inheritance))
12476 org-tags-exclude-from-inheritance))
12477 ;; selective inheritance, remove uninherited ones
12478 (setcdr (car tags-alist)
12479 (org-remove-uninherited-tags (cdar tags-alist))))
12480 (when (and
12482 ;; eval matcher only when the todo condition is OK
12483 (and (or (not todo-only) (member todo org-not-done-keywords))
12484 (let ((case-fold-search t)) (eval matcher)))
12486 ;; Call the skipper, but return t if it does not skip,
12487 ;; so that the `and' form continues evaluating
12488 (progn
12489 (unless (eq action 'sparse-tree) (org-agenda-skip))
12492 ;; Check if timestamps are deselecting this entry
12493 (or (not todo-only)
12494 (and (member todo org-not-done-keywords)
12495 (or (not org-agenda-tags-todo-honor-ignore-options)
12496 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
12498 ;; Extra check for the archive tag
12499 ;; FIXME: Does the skipper already do this????
12501 (not (member org-archive-tag tags-list))
12502 ;; we have an archive tag, should we use this anyway?
12503 (or (not org-agenda-skip-archived-trees)
12504 (and (eq action 'agenda) org-agenda-archives-mode))))
12506 ;; select this headline
12508 (cond
12509 ((eq action 'sparse-tree)
12510 (and org-highlight-sparse-tree-matches
12511 (org-get-heading) (match-end 0)
12512 (org-highlight-new-match
12513 (match-beginning 0) (match-beginning 1)))
12514 (org-show-context 'tags-tree))
12515 ((eq action 'agenda)
12516 (setq txt (org-format-agenda-item
12518 (concat
12519 (if (eq org-tags-match-list-sublevels 'indented)
12520 (make-string (1- level) ?.) "")
12521 (org-get-heading))
12522 category
12523 tags-list
12525 priority (org-get-priority txt))
12526 (goto-char lspos)
12527 (setq marker (org-agenda-new-marker))
12528 (org-add-props txt props
12529 'org-marker marker 'org-hd-marker marker 'org-category category
12530 'todo-state todo
12531 'priority priority 'type "tagsmatch")
12532 (push txt rtn))
12533 ((functionp action)
12534 (setq org-map-continue-from nil)
12535 (save-excursion
12536 (setq rtn1 (funcall action))
12537 (push rtn1 rtn)))
12538 (t (error "Invalid action")))
12540 ;; if we are to skip sublevels, jump to end of subtree
12541 (unless org-tags-match-list-sublevels
12542 (org-end-of-subtree t)
12543 (backward-char 1))))
12544 ;; Get the correct position from where to continue
12545 (if org-map-continue-from
12546 (goto-char org-map-continue-from)
12547 (and (= (point) lspos) (end-of-line 1)))))
12548 (when (and (eq action 'sparse-tree)
12549 (not org-sparse-tree-open-archived-trees))
12550 (org-hide-archived-subtrees (point-min) (point-max)))
12551 (nreverse rtn)))
12553 (defun org-remove-uninherited-tags (tags)
12554 "Remove all tags that are not inherited from the list TAGS."
12555 (cond
12556 ((eq org-use-tag-inheritance t)
12557 (if org-tags-exclude-from-inheritance
12558 (org-delete-all org-tags-exclude-from-inheritance tags)
12559 tags))
12560 ((not org-use-tag-inheritance) nil)
12561 ((stringp org-use-tag-inheritance)
12562 (delq nil (mapcar
12563 (lambda (x)
12564 (if (and (string-match org-use-tag-inheritance x)
12565 (not (member x org-tags-exclude-from-inheritance)))
12566 x nil))
12567 tags)))
12568 ((listp org-use-tag-inheritance)
12569 (delq nil (mapcar
12570 (lambda (x)
12571 (if (member x org-use-tag-inheritance) x nil))
12572 tags)))))
12574 (defvar todo-only) ;; dynamically scoped
12576 (defun org-match-sparse-tree (&optional todo-only match)
12577 "Create a sparse tree according to tags string MATCH.
12578 MATCH can contain positive and negative selection of tags, like
12579 \"+WORK+URGENT-WITHBOSS\".
12580 If optional argument TODO-ONLY is non-nil, only select lines that are
12581 also TODO lines."
12582 (interactive "P")
12583 (org-prepare-agenda-buffers (list (current-buffer)))
12584 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
12586 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
12588 (defvar org-cached-props nil)
12589 (defun org-cached-entry-get (pom property)
12590 (if (or (eq t org-use-property-inheritance)
12591 (and (stringp org-use-property-inheritance)
12592 (string-match org-use-property-inheritance property))
12593 (and (listp org-use-property-inheritance)
12594 (member property org-use-property-inheritance)))
12595 ;; Caching is not possible, check it directly
12596 (org-entry-get pom property 'inherit)
12597 ;; Get all properties, so that we can do complicated checks easily
12598 (cdr (assoc property (or org-cached-props
12599 (setq org-cached-props
12600 (org-entry-properties pom)))))))
12602 (defun org-global-tags-completion-table (&optional files)
12603 "Return the list of all tags in all agenda buffer/files.
12604 Optional FILES argument is a list of files to which can be used
12605 instead of the agenda files."
12606 (save-excursion
12607 (org-uniquify
12608 (delq nil
12609 (apply 'append
12610 (mapcar
12611 (lambda (file)
12612 (set-buffer (find-file-noselect file))
12613 (append (org-get-buffer-tags)
12614 (mapcar (lambda (x) (if (stringp (car-safe x))
12615 (list (car-safe x)) nil))
12616 org-tag-alist)))
12617 (if (and files (car files))
12618 files
12619 (org-agenda-files))))))))
12621 (defun org-make-tags-matcher (match)
12622 "Create the TAGS/TODO matcher form for the selection string MATCH."
12623 ;; todo-only is scoped dynamically into this function, and the function
12624 ;; may change it if the matcher asks for it.
12625 (unless match
12626 ;; Get a new match request, with completion
12627 (let ((org-last-tags-completion-table
12628 (org-global-tags-completion-table)))
12629 (setq match (org-completing-read-no-i
12630 "Match: " 'org-tags-completion-function nil nil nil
12631 'org-tags-history))))
12633 ;; Parse the string and create a lisp form
12634 (let ((match0 match)
12635 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
12636 minus tag mm
12637 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
12638 orterms term orlist re-p str-p level-p level-op time-p
12639 prop-p pn pv po gv rest)
12640 (if (string-match "/+" match)
12641 ;; match contains also a todo-matching request
12642 (progn
12643 (setq tagsmatch (substring match 0 (match-beginning 0))
12644 todomatch (substring match (match-end 0)))
12645 (if (string-match "^!" todomatch)
12646 (setq todo-only t todomatch (substring todomatch 1)))
12647 (if (string-match "^\\s-*$" todomatch)
12648 (setq todomatch nil)))
12649 ;; only matching tags
12650 (setq tagsmatch match todomatch nil))
12652 ;; Make the tags matcher
12653 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
12654 (setq tagsmatcher t)
12655 (setq orterms (org-split-string tagsmatch "|") orlist nil)
12656 (while (setq term (pop orterms))
12657 (while (and (equal (substring term -1) "\\") orterms)
12658 (setq term (concat term "|" (pop orterms)))) ; repair bad split
12659 (while (string-match re term)
12660 (setq rest (substring term (match-end 0))
12661 minus (and (match-end 1)
12662 (equal (match-string 1 term) "-"))
12663 tag (save-match-data (replace-regexp-in-string
12664 "\\\\-" "-"
12665 (match-string 2 term)))
12666 re-p (equal (string-to-char tag) ?{)
12667 level-p (match-end 4)
12668 prop-p (match-end 5)
12669 mm (cond
12670 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
12671 (level-p
12672 (setq level-op (org-op-to-function (match-string 3 term)))
12673 `(,level-op level ,(string-to-number
12674 (match-string 4 term))))
12675 (prop-p
12676 (setq pn (match-string 5 term)
12677 po (match-string 6 term)
12678 pv (match-string 7 term)
12679 re-p (equal (string-to-char pv) ?{)
12680 str-p (equal (string-to-char pv) ?\")
12681 time-p (save-match-data
12682 (string-match "^\"[[<].*[]>]\"$" pv))
12683 pv (if (or re-p str-p) (substring pv 1 -1) pv))
12684 (if time-p (setq pv (org-matcher-time pv)))
12685 (setq po (org-op-to-function po (if time-p 'time str-p)))
12686 (cond
12687 ((equal pn "CATEGORY")
12688 (setq gv '(get-text-property (point) 'org-category)))
12689 ((equal pn "TODO")
12690 (setq gv 'todo))
12692 (setq gv `(org-cached-entry-get nil ,pn))))
12693 (if re-p
12694 (if (eq po 'org<>)
12695 `(not (string-match ,pv (or ,gv "")))
12696 `(string-match ,pv (or ,gv "")))
12697 (if str-p
12698 `(,po (or ,gv "") ,pv)
12699 `(,po (string-to-number (or ,gv ""))
12700 ,(string-to-number pv) ))))
12701 (t `(member ,tag tags-list)))
12702 mm (if minus (list 'not mm) mm)
12703 term rest)
12704 (push mm tagsmatcher))
12705 (push (if (> (length tagsmatcher) 1)
12706 (cons 'and tagsmatcher)
12707 (car tagsmatcher))
12708 orlist)
12709 (setq tagsmatcher nil))
12710 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
12711 (setq tagsmatcher
12712 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
12713 ;; Make the todo matcher
12714 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
12715 (setq todomatcher t)
12716 (setq orterms (org-split-string todomatch "|") orlist nil)
12717 (while (setq term (pop orterms))
12718 (while (string-match re term)
12719 (setq minus (and (match-end 1)
12720 (equal (match-string 1 term) "-"))
12721 kwd (match-string 2 term)
12722 re-p (equal (string-to-char kwd) ?{)
12723 term (substring term (match-end 0))
12724 mm (if re-p
12725 `(string-match ,(substring kwd 1 -1) todo)
12726 (list 'equal 'todo kwd))
12727 mm (if minus (list 'not mm) mm))
12728 (push mm todomatcher))
12729 (push (if (> (length todomatcher) 1)
12730 (cons 'and todomatcher)
12731 (car todomatcher))
12732 orlist)
12733 (setq todomatcher nil))
12734 (setq todomatcher (if (> (length orlist) 1)
12735 (cons 'or orlist) (car orlist))))
12737 ;; Return the string and lisp forms of the matcher
12738 (setq matcher (if todomatcher
12739 (list 'and tagsmatcher todomatcher)
12740 tagsmatcher))
12741 (cons match0 matcher)))
12743 (defun org-op-to-function (op &optional stringp)
12744 "Turn an operator into the appropriate function."
12745 (setq op
12746 (cond
12747 ((equal op "<" ) '(< string< org-time<))
12748 ((equal op ">" ) '(> org-string> org-time>))
12749 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
12750 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
12751 ((member op '("=" "==")) '(= string= org-time=))
12752 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
12753 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
12755 (defun org<> (a b) (not (= a b)))
12756 (defun org-string<= (a b) (or (string= a b) (string< a b)))
12757 (defun org-string>= (a b) (not (string< a b)))
12758 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
12759 (defun org-string<> (a b) (not (string= 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) (>= a b)))
12765 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
12766 (defun org-2ft (s)
12767 "Convert S to a floating point time.
12768 If S is already a number, just return it. If it is a string, parse
12769 it as a time string and apply `float-time' to it. If S is nil, just return 0."
12770 (cond
12771 ((numberp s) s)
12772 ((stringp s)
12773 (condition-case nil
12774 (float-time (apply 'encode-time (org-parse-time-string s)))
12775 (error 0.)))
12776 (t 0.)))
12778 (defun org-time-today ()
12779 "Time in seconds today at 0:00.
12780 Returns the float number of seconds since the beginning of the
12781 epoch to the beginning of today (00:00)."
12782 (float-time (apply 'encode-time
12783 (append '(0 0 0) (nthcdr 3 (decode-time))))))
12785 (defun org-matcher-time (s)
12786 "Interpret a time comparison value."
12787 (save-match-data
12788 (cond
12789 ((string= s "<now>") (float-time))
12790 ((string= s "<today>") (org-time-today))
12791 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
12792 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
12793 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
12794 (+ (org-time-today)
12795 (* (string-to-number (match-string 1 s))
12796 (cdr (assoc (match-string 2 s)
12797 '(("d" . 86400.0) ("w" . 604800.0)
12798 ("m" . 2678400.0) ("y" . 31557600.0)))))))
12799 (t (org-2ft s)))))
12801 (defun org-match-any-p (re list)
12802 "Does re match any element of list?"
12803 (setq list (mapcar (lambda (x) (string-match re x)) list))
12804 (delq nil list))
12806 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
12807 (defvar org-tags-overlay (make-overlay 1 1))
12808 (org-detach-overlay org-tags-overlay)
12810 (defun org-get-local-tags-at (&optional pos)
12811 "Get a list of tags defined in the current headline."
12812 (org-get-tags-at pos 'local))
12814 (defun org-get-local-tags ()
12815 "Get a list of tags defined in the current headline."
12816 (org-get-tags-at nil 'local))
12818 (defun org-get-tags-at (&optional pos local)
12819 "Get a list of all headline tags applicable at POS.
12820 POS defaults to point. If tags are inherited, the list contains
12821 the targets in the same sequence as the headlines appear, i.e.
12822 the tags of the current headline come last.
12823 When LOCAL is non-nil, only return tags from the current headline,
12824 ignore inherited ones."
12825 (interactive)
12826 (if (and org-trust-scanner-tags
12827 (or (not pos) (equal pos (point)))
12828 (not local))
12829 org-scanner-tags
12830 (let (tags ltags lastpos parent)
12831 (save-excursion
12832 (save-restriction
12833 (widen)
12834 (goto-char (or pos (point)))
12835 (save-match-data
12836 (catch 'done
12837 (condition-case nil
12838 (progn
12839 (org-back-to-heading t)
12840 (while (not (equal lastpos (point)))
12841 (setq lastpos (point))
12842 (when (looking-at
12843 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
12844 (setq ltags (org-split-string
12845 (org-match-string-no-properties 1) ":"))
12846 (when parent
12847 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
12848 (setq tags (append
12849 (if parent
12850 (org-remove-uninherited-tags ltags)
12851 ltags)
12852 tags)))
12853 (or org-use-tag-inheritance (throw 'done t))
12854 (if local (throw 'done t))
12855 (or (org-up-heading-safe) (error nil))
12856 (setq parent t)))
12857 (error nil)))))
12858 (if local
12859 tags
12860 (append (org-remove-uninherited-tags org-file-tags) tags))))))
12862 (defun org-add-prop-inherited (s)
12863 (add-text-properties 0 (length s) '(inherited t) s)
12866 (defun org-toggle-tag (tag &optional onoff)
12867 "Toggle the tag TAG for the current line.
12868 If ONOFF is `on' or `off', don't toggle but set to this state."
12869 (let (res current)
12870 (save-excursion
12871 (org-back-to-heading t)
12872 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
12873 (point-at-eol) t)
12874 (progn
12875 (setq current (match-string 1))
12876 (replace-match ""))
12877 (setq current ""))
12878 (setq current (nreverse (org-split-string current ":")))
12879 (cond
12880 ((eq onoff 'on)
12881 (setq res t)
12882 (or (member tag current) (push tag current)))
12883 ((eq onoff 'off)
12884 (or (not (member tag current)) (setq current (delete tag current))))
12885 (t (if (member tag current)
12886 (setq current (delete tag current))
12887 (setq res t)
12888 (push tag current))))
12889 (end-of-line 1)
12890 (if current
12891 (progn
12892 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
12893 (org-set-tags nil t))
12894 (delete-horizontal-space))
12895 (run-hooks 'org-after-tags-change-hook))
12896 res))
12898 (defun org-align-tags-here (to-col)
12899 ;; Assumes that this is a headline
12900 (let ((pos (point)) (col (current-column)) ncol tags-l p)
12901 (beginning-of-line 1)
12902 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
12903 (< pos (match-beginning 2)))
12904 (progn
12905 (setq tags-l (- (match-end 2) (match-beginning 2)))
12906 (goto-char (match-beginning 1))
12907 (insert " ")
12908 (delete-region (point) (1+ (match-beginning 2)))
12909 (setq ncol (max (1+ (current-column))
12910 (1+ col)
12911 (if (> to-col 0)
12912 to-col
12913 (- (abs to-col) tags-l))))
12914 (setq p (point))
12915 (insert (make-string (- ncol (current-column)) ?\ ))
12916 (setq ncol (current-column))
12917 (when indent-tabs-mode (tabify p (point-at-eol)))
12918 (org-move-to-column (min ncol col) t))
12919 (goto-char pos))))
12921 (defun org-set-tags-command (&optional arg just-align)
12922 "Call the set-tags command for the current entry."
12923 (interactive "P")
12924 (if (org-on-heading-p)
12925 (org-set-tags arg just-align)
12926 (save-excursion
12927 (org-back-to-heading t)
12928 (org-set-tags arg just-align))))
12930 (defun org-set-tags-to (data)
12931 "Set the tags of the current entry to DATA, replacing the current tags.
12932 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
12933 If DATA is nil or the empty string, any tags will be removed."
12934 (interactive "sTags: ")
12935 (setq data
12936 (cond
12937 ((eq data nil) "")
12938 ((equal data "") "")
12939 ((stringp data)
12940 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
12941 ":"))
12942 ((listp data)
12943 (concat ":" (mapconcat 'identity data ":") ":"))
12944 (t nil)))
12945 (when data
12946 (save-excursion
12947 (org-back-to-heading t)
12948 (when (looking-at org-complex-heading-regexp)
12949 (if (match-end 5)
12950 (progn
12951 (goto-char (match-beginning 5))
12952 (insert data)
12953 (delete-region (point) (point-at-eol))
12954 (org-set-tags nil 'align))
12955 (goto-char (point-at-eol))
12956 (insert " " data)
12957 (org-set-tags nil 'align)))
12958 (beginning-of-line 1)
12959 (if (looking-at ".*?\\([ \t]+\\)$")
12960 (delete-region (match-beginning 1) (match-end 1))))))
12962 (defun org-align-all-tags ()
12963 "Align the tags i all headings."
12964 (interactive)
12965 (save-excursion
12966 (or (ignore-errors (org-back-to-heading t))
12967 (outline-next-heading))
12968 (if (org-on-heading-p)
12969 (org-set-tags t)
12970 (message "No headings"))))
12972 (defvar org-indent-indentation-per-level)
12973 (defun org-set-tags (&optional arg just-align)
12974 "Set the tags for the current headline.
12975 With prefix ARG, realign all tags in headings in the current buffer."
12976 (interactive "P")
12977 (let* ((re (concat "^" outline-regexp))
12978 (current (org-get-tags-string))
12979 (col (current-column))
12980 (org-setting-tags t)
12981 table current-tags inherited-tags ; computed below when needed
12982 tags p0 c0 c1 rpl di tc level)
12983 (if arg
12984 (save-excursion
12985 (goto-char (point-min))
12986 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
12987 (while (re-search-forward re nil t)
12988 (org-set-tags nil t)
12989 (end-of-line 1)))
12990 (message "All tags realigned to column %d" org-tags-column))
12991 (if just-align
12992 (setq tags current)
12993 ;; Get a new set of tags from the user
12994 (save-excursion
12995 (setq table (append org-tag-persistent-alist
12996 (or org-tag-alist (org-get-buffer-tags))
12997 (and
12998 org-complete-tags-always-offer-all-agenda-tags
12999 (org-global-tags-completion-table
13000 (org-agenda-files))))
13001 org-last-tags-completion-table table
13002 current-tags (org-split-string current ":")
13003 inherited-tags (nreverse
13004 (nthcdr (length current-tags)
13005 (nreverse (org-get-tags-at))))
13006 tags
13007 (if (or (eq t org-use-fast-tag-selection)
13008 (and org-use-fast-tag-selection
13009 (delq nil (mapcar 'cdr table))))
13010 (org-fast-tag-selection
13011 current-tags inherited-tags table
13012 (if org-fast-tag-selection-include-todo
13013 org-todo-key-alist))
13014 (let ((org-add-colon-after-tag-completion t))
13015 (org-trim
13016 (org-without-partial-completion
13017 (org-icompleting-read "Tags: "
13018 'org-tags-completion-function
13019 nil nil current 'org-tags-history)))))))
13020 (while (string-match "[-+&]+" tags)
13021 ;; No boolean logic, just a list
13022 (setq tags (replace-match ":" t t tags))))
13024 (setq tags (replace-regexp-in-string "[,]" ":" tags))
13026 (if org-tags-sort-function
13027 (setq tags (mapconcat 'identity
13028 (sort (org-split-string
13029 tags (org-re "[^[:alnum:]_@#%]+"))
13030 org-tags-sort-function) ":")))
13032 (if (string-match "\\`[\t ]*\\'" tags)
13033 (setq tags "")
13034 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
13035 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
13037 ;; Insert new tags at the correct column
13038 (beginning-of-line 1)
13039 (setq level (or (and (looking-at org-outline-regexp)
13040 (- (match-end 0) (point) 1))
13042 (cond
13043 ((and (equal current "") (equal tags "")))
13044 ((re-search-forward
13045 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
13046 (point-at-eol) t)
13047 (if (equal tags "")
13048 (setq rpl "")
13049 (goto-char (match-beginning 0))
13050 (setq c0 (current-column)
13051 ;; compute offset for the case of org-indent-mode active
13052 di (if org-indent-mode
13053 (* (1- org-indent-indentation-per-level) (1- level))
13055 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
13056 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
13057 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
13058 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
13059 (replace-match rpl t t)
13060 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
13061 tags)
13062 (t (error "Tags alignment failed")))
13063 (org-move-to-column col)
13064 (unless just-align
13065 (run-hooks 'org-after-tags-change-hook)))))
13067 (defun org-change-tag-in-region (beg end tag off)
13068 "Add or remove TAG for each entry in the region.
13069 This works in the agenda, and also in an org-mode buffer."
13070 (interactive
13071 (list (region-beginning) (region-end)
13072 (let ((org-last-tags-completion-table
13073 (if (org-mode-p)
13074 (org-get-buffer-tags)
13075 (org-global-tags-completion-table))))
13076 (org-icompleting-read
13077 "Tag: " 'org-tags-completion-function nil nil nil
13078 'org-tags-history))
13079 (progn
13080 (message "[s]et or [r]emove? ")
13081 (equal (read-char-exclusive) ?r))))
13082 (if (fboundp 'deactivate-mark) (deactivate-mark))
13083 (let ((agendap (equal major-mode 'org-agenda-mode))
13084 l1 l2 m buf pos newhead (cnt 0))
13085 (goto-char end)
13086 (setq l2 (1- (org-current-line)))
13087 (goto-char beg)
13088 (setq l1 (org-current-line))
13089 (loop for l from l1 to l2 do
13090 (org-goto-line l)
13091 (setq m (get-text-property (point) 'org-hd-marker))
13092 (when (or (and (org-mode-p) (org-on-heading-p))
13093 (and agendap m))
13094 (setq buf (if agendap (marker-buffer m) (current-buffer))
13095 pos (if agendap m (point)))
13096 (with-current-buffer buf
13097 (save-excursion
13098 (save-restriction
13099 (goto-char pos)
13100 (setq cnt (1+ cnt))
13101 (org-toggle-tag tag (if off 'off 'on))
13102 (setq newhead (org-get-heading)))))
13103 (and agendap (org-agenda-change-all-lines newhead m))))
13104 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
13106 (defun org-tags-completion-function (string predicate &optional flag)
13107 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
13108 (confirm (lambda (x) (stringp (car x)))))
13109 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
13110 (setq s1 (match-string 1 string)
13111 s2 (match-string 2 string))
13112 (setq s1 "" s2 string))
13113 (cond
13114 ((eq flag nil)
13115 ;; try completion
13116 (setq rtn (try-completion s2 ctable confirm))
13117 (if (stringp rtn)
13118 (setq rtn
13119 (concat s1 s2 (substring rtn (length s2))
13120 (if (and org-add-colon-after-tag-completion
13121 (assoc rtn ctable))
13122 ":" ""))))
13123 rtn)
13124 ((eq flag t)
13125 ;; all-completions
13126 (all-completions s2 ctable confirm)
13128 ((eq flag 'lambda)
13129 ;; exact match?
13130 (assoc s2 ctable)))
13133 (defun org-fast-tag-insert (kwd tags face &optional end)
13134 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
13135 (insert (format "%-12s" (concat kwd ":"))
13136 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
13137 (or end "")))
13139 (defun org-fast-tag-show-exit (flag)
13140 (save-excursion
13141 (org-goto-line 3)
13142 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
13143 (replace-match ""))
13144 (when flag
13145 (end-of-line 1)
13146 (org-move-to-column (- (window-width) 19) t)
13147 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
13149 (defun org-set-current-tags-overlay (current prefix)
13150 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
13151 (if (featurep 'xemacs)
13152 (org-overlay-display org-tags-overlay (concat prefix s)
13153 'secondary-selection)
13154 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
13155 (org-overlay-display org-tags-overlay (concat prefix s)))))
13157 (defvar org-last-tag-selection-key nil)
13158 (defun org-fast-tag-selection (current inherited table &optional todo-table)
13159 "Fast tag selection with single keys.
13160 CURRENT is the current list of tags in the headline, INHERITED is the
13161 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
13162 possibly with grouping information. TODO-TABLE is a similar table with
13163 TODO keywords, should these have keys assigned to them.
13164 If the keys are nil, a-z are automatically assigned.
13165 Returns the new tags string, or nil to not change the current settings."
13166 (let* ((fulltable (append table todo-table))
13167 (maxlen (apply 'max (mapcar
13168 (lambda (x)
13169 (if (stringp (car x)) (string-width (car x)) 0))
13170 fulltable)))
13171 (buf (current-buffer))
13172 (expert (eq org-fast-tag-selection-single-key 'expert))
13173 (buffer-tags nil)
13174 (fwidth (+ maxlen 3 1 3))
13175 (ncol (/ (- (window-width) 4) fwidth))
13176 (i-face 'org-done)
13177 (c-face 'org-todo)
13178 tg cnt e c char c1 c2 ntable tbl rtn
13179 ov-start ov-end ov-prefix
13180 (exit-after-next org-fast-tag-selection-single-key)
13181 (done-keywords org-done-keywords)
13182 groups ingroup)
13183 (save-excursion
13184 (beginning-of-line 1)
13185 (if (looking-at
13186 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13187 (setq ov-start (match-beginning 1)
13188 ov-end (match-end 1)
13189 ov-prefix "")
13190 (setq ov-start (1- (point-at-eol))
13191 ov-end (1+ ov-start))
13192 (skip-chars-forward "^\n\r")
13193 (setq ov-prefix
13194 (concat
13195 (buffer-substring (1- (point)) (point))
13196 (if (> (current-column) org-tags-column)
13198 (make-string (- org-tags-column (current-column)) ?\ ))))))
13199 (move-overlay org-tags-overlay ov-start ov-end)
13200 (save-window-excursion
13201 (if expert
13202 (set-buffer (get-buffer-create " *Org tags*"))
13203 (delete-other-windows)
13204 (split-window-vertically)
13205 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
13206 (erase-buffer)
13207 (org-set-local 'org-done-keywords done-keywords)
13208 (org-fast-tag-insert "Inherited" inherited i-face "\n")
13209 (org-fast-tag-insert "Current" current c-face "\n\n")
13210 (org-fast-tag-show-exit exit-after-next)
13211 (org-set-current-tags-overlay current ov-prefix)
13212 (setq tbl fulltable char ?a cnt 0)
13213 (while (setq e (pop tbl))
13214 (cond
13215 ((equal (car e) :startgroup)
13216 (push '() groups) (setq ingroup t)
13217 (when (not (= cnt 0))
13218 (setq cnt 0)
13219 (insert "\n"))
13220 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
13221 ((equal (car e) :endgroup)
13222 (setq ingroup nil cnt 0)
13223 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
13224 ((equal e '(:newline))
13225 (when (not (= cnt 0))
13226 (setq cnt 0)
13227 (insert "\n")
13228 (setq e (car tbl))
13229 (while (equal (car tbl) '(:newline))
13230 (insert "\n")
13231 (setq tbl (cdr tbl)))))
13233 (setq tg (copy-sequence (car e)) c2 nil)
13234 (if (cdr e)
13235 (setq c (cdr e))
13236 ;; automatically assign a character.
13237 (setq c1 (string-to-char
13238 (downcase (substring
13239 tg (if (= (string-to-char tg) ?@) 1 0)))))
13240 (if (or (rassoc c1 ntable) (rassoc c1 table))
13241 (while (or (rassoc char ntable) (rassoc char table))
13242 (setq char (1+ char)))
13243 (setq c2 c1))
13244 (setq c (or c2 char)))
13245 (if ingroup (push tg (car groups)))
13246 (setq tg (org-add-props tg nil 'face
13247 (cond
13248 ((not (assoc tg table))
13249 (org-get-todo-face tg))
13250 ((member tg current) c-face)
13251 ((member tg inherited) i-face)
13252 (t nil))))
13253 (if (and (= cnt 0) (not ingroup)) (insert " "))
13254 (insert "[" c "] " tg (make-string
13255 (- fwidth 4 (length tg)) ?\ ))
13256 (push (cons tg c) ntable)
13257 (when (= (setq cnt (1+ cnt)) ncol)
13258 (insert "\n")
13259 (if ingroup (insert " "))
13260 (setq cnt 0)))))
13261 (setq ntable (nreverse ntable))
13262 (insert "\n")
13263 (goto-char (point-min))
13264 (if (not expert) (org-fit-window-to-buffer))
13265 (setq rtn
13266 (catch 'exit
13267 (while t
13268 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
13269 (if (not groups) "no " "")
13270 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
13271 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13272 (setq org-last-tag-selection-key c)
13273 (cond
13274 ((= c ?\r) (throw 'exit t))
13275 ((= c ?!)
13276 (setq groups (not groups))
13277 (goto-char (point-min))
13278 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
13279 ((= c ?\C-c)
13280 (if (not expert)
13281 (org-fast-tag-show-exit
13282 (setq exit-after-next (not exit-after-next)))
13283 (setq expert nil)
13284 (delete-other-windows)
13285 (set-window-buffer (split-window-vertically) " *Org tags*")
13286 (org-switch-to-buffer-other-window " *Org tags*")
13287 (org-fit-window-to-buffer)))
13288 ((or (= c ?\C-g)
13289 (and (= c ?q) (not (rassoc c ntable))))
13290 (org-detach-overlay org-tags-overlay)
13291 (setq quit-flag t))
13292 ((= c ?\ )
13293 (setq current nil)
13294 (if exit-after-next (setq exit-after-next 'now)))
13295 ((= c ?\t)
13296 (condition-case nil
13297 (setq tg (org-icompleting-read
13298 "Tag: "
13299 (or buffer-tags
13300 (with-current-buffer buf
13301 (org-get-buffer-tags)))))
13302 (quit (setq tg "")))
13303 (when (string-match "\\S-" tg)
13304 (add-to-list 'buffer-tags (list tg))
13305 (if (member tg current)
13306 (setq current (delete tg current))
13307 (push tg current)))
13308 (if exit-after-next (setq exit-after-next 'now)))
13309 ((setq e (rassoc c todo-table) tg (car e))
13310 (with-current-buffer buf
13311 (save-excursion (org-todo tg)))
13312 (if exit-after-next (setq exit-after-next 'now)))
13313 ((setq e (rassoc c ntable) tg (car e))
13314 (if (member tg current)
13315 (setq current (delete tg current))
13316 (loop for g in groups do
13317 (if (member tg g)
13318 (mapc (lambda (x)
13319 (setq current (delete x current)))
13320 g)))
13321 (push tg current))
13322 (if exit-after-next (setq exit-after-next 'now))))
13324 ;; Create a sorted list
13325 (setq current
13326 (sort current
13327 (lambda (a b)
13328 (assoc b (cdr (memq (assoc a ntable) ntable))))))
13329 (if (eq exit-after-next 'now) (throw 'exit t))
13330 (goto-char (point-min))
13331 (beginning-of-line 2)
13332 (delete-region (point) (point-at-eol))
13333 (org-fast-tag-insert "Current" current c-face)
13334 (org-set-current-tags-overlay current ov-prefix)
13335 (while (re-search-forward
13336 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
13337 (setq tg (match-string 1))
13338 (add-text-properties
13339 (match-beginning 1) (match-end 1)
13340 (list 'face
13341 (cond
13342 ((member tg current) c-face)
13343 ((member tg inherited) i-face)
13344 (t (get-text-property (match-beginning 1) 'face))))))
13345 (goto-char (point-min)))))
13346 (org-detach-overlay org-tags-overlay)
13347 (if rtn
13348 (mapconcat 'identity current ":")
13349 nil))))
13351 (defun org-get-tags-string ()
13352 "Get the TAGS string in the current headline."
13353 (unless (org-on-heading-p t)
13354 (error "Not on a heading"))
13355 (save-excursion
13356 (beginning-of-line 1)
13357 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13358 (org-match-string-no-properties 1)
13359 "")))
13361 (defun org-get-tags ()
13362 "Get the list of tags specified in the current headline."
13363 (org-split-string (org-get-tags-string) ":"))
13365 (defun org-get-buffer-tags ()
13366 "Get a table of all tags used in the buffer, for completion."
13367 (let (tags)
13368 (save-excursion
13369 (goto-char (point-min))
13370 (while (re-search-forward
13371 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
13372 (when (equal (char-after (point-at-bol 0)) ?*)
13373 (mapc (lambda (x) (add-to-list 'tags x))
13374 (org-split-string (org-match-string-no-properties 1) ":")))))
13375 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
13376 (mapcar 'list tags)))
13378 ;;;; The mapping API
13380 ;;;###autoload
13381 (defun org-map-entries (func &optional match scope &rest skip)
13382 "Call FUNC at each headline selected by MATCH in SCOPE.
13384 FUNC is a function or a lisp form. The function will be called without
13385 arguments, with the cursor positioned at the beginning of the headline.
13386 The return values of all calls to the function will be collected and
13387 returned as a list.
13389 The call to FUNC will be wrapped into a save-excursion form, so FUNC
13390 does not need to preserve point. After evaluation, the cursor will be
13391 moved to the end of the line (presumably of the headline of the
13392 processed entry) and search continues from there. Under some
13393 circumstances, this may not produce the wanted results. For example,
13394 if you have removed (e.g. archived) the current (sub)tree it could
13395 mean that the next entry will be skipped entirely. In such cases, you
13396 can specify the position from where search should continue by making
13397 FUNC set the variable `org-map-continue-from' to the desired buffer
13398 position.
13400 MATCH is a tags/property/todo match as it is used in the agenda tags view.
13401 Only headlines that are matched by this query will be considered during
13402 the iteration. When MATCH is nil or t, all headlines will be
13403 visited by the iteration.
13405 SCOPE determines the scope of this command. It can be any of:
13407 nil The current buffer, respecting the restriction if any
13408 tree The subtree started with the entry at point
13409 file The current buffer, without restriction
13410 file-with-archives
13411 The current buffer, and any archives associated with it
13412 agenda All agenda files
13413 agenda-with-archives
13414 All agenda files with any archive files associated with them
13415 \(file1 file2 ...)
13416 If this is a list, all files in the list will be scanned
13418 The remaining args are treated as settings for the skipping facilities of
13419 the scanner. The following items can be given here:
13421 archive skip trees with the archive tag.
13422 comment skip trees with the COMMENT keyword
13423 function or Emacs Lisp form:
13424 will be used as value for `org-agenda-skip-function', so whenever
13425 the function returns t, FUNC will not be called for that
13426 entry and search will continue from the point where the
13427 function leaves it.
13429 If your function needs to retrieve the tags including inherited tags
13430 at the *current* entry, you can use the value of the variable
13431 `org-scanner-tags' which will be much faster than getting the value
13432 with `org-get-tags-at'. If your function gets properties with
13433 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
13434 to t around the call to `org-entry-properties' to get the same speedup.
13435 Note that if your function moves around to retrieve tags and properties at
13436 a *different* entry, you cannot use these techniques."
13437 (let* ((org-agenda-archives-mode nil) ; just to make sure
13438 (org-agenda-skip-archived-trees (memq 'archive skip))
13439 (org-agenda-skip-comment-trees (memq 'comment skip))
13440 (org-agenda-skip-function
13441 (car (org-delete-all '(comment archive) skip)))
13442 (org-tags-match-list-sublevels t)
13443 matcher file res
13444 org-todo-keywords-for-agenda
13445 org-done-keywords-for-agenda
13446 org-todo-keyword-alist-for-agenda
13447 org-drawers-for-agenda
13448 org-tag-alist-for-agenda)
13450 (cond
13451 ((eq match t) (setq matcher t))
13452 ((eq match nil) (setq matcher t))
13453 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
13455 (save-excursion
13456 (save-restriction
13457 (when (eq scope 'tree)
13458 (org-back-to-heading t)
13459 (org-narrow-to-subtree)
13460 (setq scope nil))
13462 (if (not scope)
13463 (progn
13464 (org-prepare-agenda-buffers
13465 (list (buffer-file-name (current-buffer))))
13466 (setq res (org-scan-tags func matcher)))
13467 ;; Get the right scope
13468 (cond
13469 ((and scope (listp scope) (symbolp (car scope)))
13470 (setq scope (eval scope)))
13471 ((eq scope 'agenda)
13472 (setq scope (org-agenda-files t)))
13473 ((eq scope 'agenda-with-archives)
13474 (setq scope (org-agenda-files t))
13475 (setq scope (org-add-archive-files scope)))
13476 ((eq scope 'file)
13477 (setq scope (list (buffer-file-name))))
13478 ((eq scope 'file-with-archives)
13479 (setq scope (org-add-archive-files (list (buffer-file-name))))))
13480 (org-prepare-agenda-buffers scope)
13481 (while (setq file (pop scope))
13482 (with-current-buffer (org-find-base-buffer-visiting file)
13483 (save-excursion
13484 (save-restriction
13485 (widen)
13486 (goto-char (point-min))
13487 (setq res (append res (org-scan-tags func matcher))))))))))
13488 res))
13490 ;;;; Properties
13492 ;;; Setting and retrieving properties
13494 (defconst org-special-properties
13495 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
13496 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM")
13497 "The special properties valid in Org-mode.
13499 These are properties that are not defined in the property drawer,
13500 but in some other way.")
13502 (defconst org-default-properties
13503 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
13504 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
13505 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
13506 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
13507 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
13508 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
13509 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
13510 "Some properties that are used by Org-mode for various purposes.
13511 Being in this list makes sure that they are offered for completion.")
13513 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
13514 "Regular expression matching the first line of a property drawer.")
13516 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
13517 "Regular expression matching the last line of a property drawer.")
13519 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
13520 "Regular expression matching the first line of a property drawer.")
13522 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
13523 "Regular expression matching the first line of a property drawer.")
13525 (defconst org-property-drawer-re
13526 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
13527 org-property-end-re "\\)\n?")
13528 "Matches an entire property drawer.")
13530 (defconst org-clock-drawer-re
13531 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
13532 org-property-end-re "\\)\n?")
13533 "Matches an entire clock drawer.")
13535 (defsubst org-re-property (property)
13536 "Return a regexp matching PROPERTY.
13537 Match group 1 will be set to the value "
13538 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
13540 (defun org-property-action ()
13541 "Do an action on properties."
13542 (interactive)
13543 (let (c)
13544 (org-at-property-p)
13545 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
13546 (setq c (read-char-exclusive))
13547 (cond
13548 ((equal c ?s)
13549 (call-interactively 'org-set-property))
13550 ((equal c ?d)
13551 (call-interactively 'org-delete-property))
13552 ((equal c ?D)
13553 (call-interactively 'org-delete-property-globally))
13554 ((equal c ?c)
13555 (call-interactively 'org-compute-property-at-point))
13556 (t (error "No such property action %c" c)))))
13558 (defun org-set-effort (&optional value)
13559 "Set the effort property of the current entry.
13560 With numerical prefix arg, use the nth allowed value, 0 stands for the 10th
13561 allowed value."
13562 (interactive "P")
13563 (if (equal value 0) (setq value 10))
13564 (let* ((completion-ignore-case t)
13565 (prop org-effort-property)
13566 (cur (org-entry-get nil prop))
13567 (allowed (org-property-get-allowed-values nil prop 'table))
13568 (existing (mapcar 'list (org-property-values prop)))
13570 (val (cond
13571 ((stringp value) value)
13572 ((and allowed (integerp value))
13573 (or (car (nth (1- value) allowed))
13574 (car (org-last allowed))))
13575 (allowed
13576 (message "Select 1-9,0, [RET%s]: %s"
13577 (if cur (concat "=" cur) "")
13578 (mapconcat 'car allowed " "))
13579 (setq rpl (read-char-exclusive))
13580 (if (equal rpl ?\r)
13582 (setq rpl (- rpl ?0))
13583 (if (equal rpl 0) (setq rpl 10))
13584 (if (and (> rpl 0) (<= rpl (length allowed)))
13585 (car (nth (1- rpl) allowed))
13586 (org-completing-read "Effort: " allowed nil))))
13588 (let (org-completion-use-ido org-completion-use-iswitchb)
13589 (org-completing-read
13590 (concat "Effort " (if (and cur (string-match "\\S-" cur))
13591 (concat "[" cur "]") "")
13592 ": ")
13593 existing nil nil "" nil cur))))))
13594 (unless (equal (org-entry-get nil prop) val)
13595 (org-entry-put nil prop val))
13596 (message "%s is now %s" prop val)))
13598 (defun org-at-property-p ()
13599 "Is cursor inside a property drawer?"
13600 (save-excursion
13601 (beginning-of-line 1)
13602 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
13603 (save-match-data ;; Used by calling procedures
13604 (let ((p (point))
13605 (range (unless (org-before-first-heading-p)
13606 (org-get-property-block))))
13607 (and range (<= (car range) p) (< p (cdr range))))))))
13609 (defun org-get-property-block (&optional beg end force)
13610 "Return the (beg . end) range of the body of the property drawer.
13611 BEG and END can be beginning and end of subtree, if not given
13612 they will be found.
13613 If the drawer does not exist and FORCE is non-nil, create the drawer."
13614 (catch 'exit
13615 (save-excursion
13616 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
13617 (end (or end (progn (outline-next-heading) (point)))))
13618 (goto-char beg)
13619 (if (re-search-forward org-property-start-re end t)
13620 (setq beg (1+ (match-end 0)))
13621 (if force
13622 (save-excursion
13623 (org-insert-property-drawer)
13624 (setq end (progn (outline-next-heading) (point))))
13625 (throw 'exit nil))
13626 (goto-char beg)
13627 (if (re-search-forward org-property-start-re end t)
13628 (setq beg (1+ (match-end 0)))))
13629 (if (re-search-forward org-property-end-re end t)
13630 (setq end (match-beginning 0))
13631 (or force (throw 'exit nil))
13632 (goto-char beg)
13633 (setq end beg)
13634 (org-indent-line-function)
13635 (insert ":END:\n"))
13636 (cons beg end)))))
13638 (defun org-entry-properties (&optional pom which specific)
13639 "Get all properties of the entry at point-or-marker POM.
13640 This includes the TODO keyword, the tags, time strings for deadline,
13641 scheduled, and clocking, and any additional properties defined in the
13642 entry. The return value is an alist, keys may occur multiple times
13643 if the property key was used several times.
13644 POM may also be nil, in which case the current entry is used.
13645 If WHICH is nil or `all', get all properties. If WHICH is
13646 `special' or `standard', only get that subclass. If WHICH
13647 is a string only get exactly this property. SPECIFIC can be a string, the
13648 specific property we are interested in. Specifying it can speed
13649 things up because then unnecessary parsing is avoided."
13650 (setq which (or which 'all))
13651 (org-with-point-at pom
13652 (let ((clockstr (substring org-clock-string 0 -1))
13653 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
13654 (case-fold-search nil)
13655 beg end range props sum-props key key1 value string clocksum)
13656 (save-excursion
13657 (when (condition-case nil
13658 (and (org-mode-p) (org-back-to-heading t))
13659 (error nil))
13660 (setq beg (point))
13661 (setq sum-props (get-text-property (point) 'org-summaries))
13662 (setq clocksum (get-text-property (point) :org-clock-minutes))
13663 (outline-next-heading)
13664 (setq end (point))
13665 (when (memq which '(all special))
13666 ;; Get the special properties, like TODO and tags
13667 (goto-char beg)
13668 (when (and (or (not specific) (string= specific "TODO"))
13669 (looking-at org-todo-line-regexp) (match-end 2))
13670 (push (cons "TODO" (org-match-string-no-properties 2)) props))
13671 (when (and (or (not specific) (string= specific "PRIORITY"))
13672 (looking-at org-priority-regexp))
13673 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
13674 (when (or (not specific) (string= specific "FILE"))
13675 (push (cons "FILE" buffer-file-name) props))
13676 (when (and (or (not specific) (string= specific "TAGS"))
13677 (setq value (org-get-tags-string))
13678 (string-match "\\S-" value))
13679 (push (cons "TAGS" value) props))
13680 (when (and (or (not specific) (string= specific "ALLTAGS"))
13681 (setq value (org-get-tags-at)))
13682 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
13683 ":"))
13684 props))
13685 (when (or (not specific) (string= specific "BLOCKED"))
13686 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
13687 (when (or (not specific)
13688 (member specific
13689 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
13690 "TIMESTAMP" "TIMESTAMP_IA")))
13691 (catch 'match
13692 (while (re-search-forward org-maybe-keyword-time-regexp end t)
13693 (setq key (if (match-end 1)
13694 (substring (org-match-string-no-properties 1)
13695 0 -1))
13696 string (if (equal key clockstr)
13697 (org-no-properties
13698 (org-trim
13699 (buffer-substring
13700 (match-beginning 3) (goto-char
13701 (point-at-eol)))))
13702 (substring (org-match-string-no-properties 3)
13703 1 -1)))
13704 ;; Get the correct property name from the key. This is
13705 ;; necessary if the user has configured time keywords.
13706 (setq key1 (concat key ":"))
13707 (cond
13708 ((not key)
13709 (setq key
13710 (if (= (char-after (match-beginning 3)) ?\[)
13711 "TIMESTAMP_IA" "TIMESTAMP")))
13712 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
13713 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
13714 ((equal key1 org-closed-string) (setq key "CLOSED"))
13715 ((equal key1 org-clock-string) (setq key "CLOCK")))
13716 (if (and specific (equal key specific) (not (equal key "CLOCK")))
13717 (progn
13718 (push (cons key string) props)
13719 ;; no need to search further if match is found
13720 (throw 'match t))
13721 (when (or (equal key "CLOCK") (not (assoc key props)))
13722 (push (cons key string) props))))))
13725 (when (memq which '(all standard))
13726 ;; Get the standard properties, like :PROP: ...
13727 (setq range (org-get-property-block beg end))
13728 (when range
13729 (goto-char (car range))
13730 (while (re-search-forward
13731 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
13732 (cdr range) t)
13733 (setq key (org-match-string-no-properties 1)
13734 value (org-trim (or (org-match-string-no-properties 2) "")))
13735 (unless (member key excluded)
13736 (push (cons key (or value "")) props)))))
13737 (if clocksum
13738 (push (cons "CLOCKSUM"
13739 (org-columns-number-to-string (/ (float clocksum) 60.)
13740 'add_times))
13741 props))
13742 (unless (assoc "CATEGORY" props)
13743 (push (cons "CATEGORY" (org-get-category)) props))
13744 (append sum-props (nreverse props)))))))
13746 (defun org-entry-get (pom property &optional inherit literal-nil)
13747 "Get value of PROPERTY for entry at point-or-marker POM.
13748 If INHERIT is non-nil and the entry does not have the property,
13749 then also check higher levels of the hierarchy.
13750 If INHERIT is the symbol `selective', use inheritance only if the setting
13751 in `org-use-property-inheritance' selects PROPERTY for inheritance.
13752 If the property is present but empty, the return value is the empty string.
13753 If the property is not present at all, nil is returned.
13755 If LITERAL-NIL is set, return the string value \"nil\" as a string,
13756 do not interpret it as the list atom nil. This is used for inheritance
13757 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
13758 (org-with-point-at pom
13759 (if (and inherit (if (eq inherit 'selective)
13760 (org-property-inherit-p property)
13762 (org-entry-get-with-inheritance property literal-nil)
13763 (if (member property org-special-properties)
13764 ;; We need a special property. Use `org-entry-properties' to
13765 ;; retrieve it, but specify the wanted property
13766 (cdr (assoc property (org-entry-properties nil 'special property)))
13767 (let ((range (unless (org-before-first-heading-p)
13768 (org-get-property-block))))
13769 (if (and range
13770 (goto-char (car range))
13771 (re-search-forward
13772 (org-re-property property)
13773 (cdr range) t))
13774 ;; Found the property, return it.
13775 (if (match-end 1)
13776 (if literal-nil
13777 (org-match-string-no-properties 1)
13778 (org-not-nil (org-match-string-no-properties 1)))
13779 "")))))))
13781 (defun org-property-or-variable-value (var &optional inherit)
13782 "Check if there is a property fixing the value of VAR.
13783 If yes, return this value. If not, return the current value of the variable."
13784 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
13785 (if (and prop (stringp prop) (string-match "\\S-" prop))
13786 (read prop)
13787 (symbol-value var))))
13789 (defun org-entry-delete (pom property)
13790 "Delete the property PROPERTY from entry at point-or-marker POM."
13791 (org-with-point-at pom
13792 (if (member property org-special-properties)
13793 nil ; cannot delete these properties.
13794 (let ((range (org-get-property-block)))
13795 (if (and range
13796 (goto-char (car range))
13797 (re-search-forward
13798 (org-re-property property)
13799 (cdr range) t))
13800 (progn
13801 (delete-region (match-beginning 0) (1+ (point-at-eol)))
13803 nil)))))
13805 ;; Multi-values properties are properties that contain multiple values
13806 ;; These values are assumed to be single words, separated by whitespace.
13807 (defun org-entry-add-to-multivalued-property (pom property value)
13808 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
13809 (let* ((old (org-entry-get pom property))
13810 (values (and old (org-split-string old "[ \t]"))))
13811 (setq value (org-entry-protect-space value))
13812 (unless (member value values)
13813 (setq values (cons value values))
13814 (org-entry-put pom property
13815 (mapconcat 'identity values " ")))))
13817 (defun org-entry-remove-from-multivalued-property (pom property value)
13818 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
13819 (let* ((old (org-entry-get pom property))
13820 (values (and old (org-split-string old "[ \t]"))))
13821 (setq value (org-entry-protect-space value))
13822 (when (member value values)
13823 (setq values (delete value values))
13824 (org-entry-put pom property
13825 (mapconcat 'identity values " ")))))
13827 (defun org-entry-member-in-multivalued-property (pom property value)
13828 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
13829 (let* ((old (org-entry-get pom property))
13830 (values (and old (org-split-string old "[ \t]"))))
13831 (setq value (org-entry-protect-space value))
13832 (member value values)))
13834 (defun org-entry-get-multivalued-property (pom property)
13835 "Return a list of values in a multivalued property."
13836 (let* ((value (org-entry-get pom property))
13837 (values (and value (org-split-string value "[ \t]"))))
13838 (mapcar 'org-entry-restore-space values)))
13840 (defun org-entry-put-multivalued-property (pom property &rest values)
13841 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
13842 VALUES should be a list of strings. Spaces will be protected."
13843 (org-entry-put pom property
13844 (mapconcat 'org-entry-protect-space values " "))
13845 (let* ((value (org-entry-get pom property))
13846 (values (and value (org-split-string value "[ \t]"))))
13847 (mapcar 'org-entry-restore-space values)))
13849 (defun org-entry-protect-space (s)
13850 "Protect spaces and newline in string S."
13851 (while (string-match " " s)
13852 (setq s (replace-match "%20" t t s)))
13853 (while (string-match "\n" s)
13854 (setq s (replace-match "%0A" t t s)))
13857 (defun org-entry-restore-space (s)
13858 "Restore spaces and newline in string S."
13859 (while (string-match "%20" s)
13860 (setq s (replace-match " " t t s)))
13861 (while (string-match "%0A" s)
13862 (setq s (replace-match "\n" t t s)))
13865 (defvar org-entry-property-inherited-from (make-marker)
13866 "Marker pointing to the entry from where a property was inherited.
13867 Each call to `org-entry-get-with-inheritance' will set this marker to the
13868 location of the entry where the inheritance search matched. If there was
13869 no match, the marker will point nowhere.
13870 Note that also `org-entry-get' calls this function, if the INHERIT flag
13871 is set.")
13873 (defun org-entry-get-with-inheritance (property &optional literal-nil)
13874 "Get entry property, and search higher levels if not present.
13875 The search will stop at the first ancestor which has the property defined.
13876 If the value found is \"nil\", return nil to show that the property
13877 should be considered as undefined (this is the meaning of nil here).
13878 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
13879 (move-marker org-entry-property-inherited-from nil)
13880 (let (tmp)
13881 (unless (org-before-first-heading-p)
13882 (save-excursion
13883 (save-restriction
13884 (widen)
13885 (catch 'ex
13886 (while t
13887 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
13888 (org-back-to-heading t)
13889 (move-marker org-entry-property-inherited-from (point))
13890 (throw 'ex tmp))
13891 (or (org-up-heading-safe) (throw 'ex nil)))))))
13892 (setq tmp (or tmp
13893 (cdr (assoc property org-file-properties))
13894 (cdr (assoc property org-global-properties))
13895 (cdr (assoc property org-global-properties-fixed))))
13896 (if literal-nil tmp (org-not-nil tmp))))
13898 (defvar org-property-changed-functions nil
13899 "Hook called when the value of a property has changed.
13900 Each hook function should accept two arguments, the name of the property
13901 and the new value.")
13903 (defun org-entry-put (pom property value)
13904 "Set PROPERTY to VALUE for entry at point-or-marker POM."
13905 (org-with-point-at pom
13906 (org-back-to-heading t)
13907 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
13908 range)
13909 (cond
13910 ((equal property "TODO")
13911 (when (and (stringp value) (string-match "\\S-" value)
13912 (not (member value org-todo-keywords-1)))
13913 (error "\"%s\" is not a valid TODO state" value))
13914 (if (or (not value)
13915 (not (string-match "\\S-" value)))
13916 (setq value 'none))
13917 (org-todo value)
13918 (org-set-tags nil 'align))
13919 ((equal property "PRIORITY")
13920 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
13921 (string-to-char value) ?\ ))
13922 (org-set-tags nil 'align))
13923 ((equal property "SCHEDULED")
13924 (if (re-search-forward org-scheduled-time-regexp end t)
13925 (cond
13926 ((eq value 'earlier) (org-timestamp-change -1 'day))
13927 ((eq value 'later) (org-timestamp-change 1 'day))
13928 (t (call-interactively 'org-schedule)))
13929 (call-interactively 'org-schedule)))
13930 ((equal property "DEADLINE")
13931 (if (re-search-forward org-deadline-time-regexp end t)
13932 (cond
13933 ((eq value 'earlier) (org-timestamp-change -1 'day))
13934 ((eq value 'later) (org-timestamp-change 1 'day))
13935 (t (call-interactively 'org-deadline)))
13936 (call-interactively 'org-deadline)))
13937 ((member property org-special-properties)
13938 (error "The %s property can not yet be set with `org-entry-put'"
13939 property))
13940 (t ; a non-special property
13941 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
13942 (setq range (org-get-property-block beg end 'force))
13943 (goto-char (car range))
13944 (if (re-search-forward
13945 (org-re-property property) (cdr range) t)
13946 (progn
13947 (delete-region (match-beginning 0) (match-end 0))
13948 (goto-char (match-beginning 0)))
13949 (goto-char (cdr range))
13950 (insert "\n")
13951 (backward-char 1)
13952 (org-indent-line-function))
13953 (insert ":" property ":")
13954 (and value (insert " " value))
13955 (org-indent-line-function)))))
13956 (run-hook-with-args 'org-property-changed-functions property value)))
13958 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
13959 "Get all property keys in the current buffer.
13960 With INCLUDE-SPECIALS, also list the special properties that reflect things
13961 like tags and TODO state.
13962 With INCLUDE-DEFAULTS, also include properties that has special meaning
13963 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
13964 and others.
13965 With INCLUDE-COLUMNS, also include property names given in COLUMN
13966 formats in the current buffer."
13967 (let (rtn range cfmt s p)
13968 (save-excursion
13969 (save-restriction
13970 (widen)
13971 (goto-char (point-min))
13972 (while (re-search-forward org-property-start-re nil t)
13973 (setq range (org-get-property-block))
13974 (goto-char (car range))
13975 (while (re-search-forward
13976 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
13977 (cdr range) t)
13978 (add-to-list 'rtn (org-match-string-no-properties 1)))
13979 (outline-next-heading))))
13981 (when include-specials
13982 (setq rtn (append org-special-properties rtn)))
13984 (when include-defaults
13985 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
13986 (add-to-list 'rtn org-effort-property))
13988 (when include-columns
13989 (save-excursion
13990 (save-restriction
13991 (widen)
13992 (goto-char (point-min))
13993 (while (re-search-forward
13994 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
13995 nil t)
13996 (setq cfmt (match-string 2) s 0)
13997 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
13998 cfmt s)
13999 (setq s (match-end 0)
14000 p (match-string 1 cfmt))
14001 (unless (or (equal p "ITEM")
14002 (member p org-special-properties))
14003 (add-to-list 'rtn (match-string 1 cfmt))))))))
14005 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
14007 (defun org-property-values (key)
14008 "Return a list of all values of property KEY in the current buffer."
14009 (save-excursion
14010 (save-restriction
14011 (widen)
14012 (goto-char (point-min))
14013 (let ((re (org-re-property key))
14014 values)
14015 (while (re-search-forward re nil t)
14016 (add-to-list 'values (org-trim (match-string 1))))
14017 (delete "" values)))))
14019 (defun org-insert-property-drawer ()
14020 "Insert a property drawer into the current entry."
14021 (interactive)
14022 (org-back-to-heading t)
14023 (looking-at outline-regexp)
14024 (let ((indent (if org-adapt-indentation
14025 (- (match-end 0)(match-beginning 0))
14027 (beg (point))
14028 (re (concat "^[ \t]*" org-keyword-time-regexp))
14029 end hiddenp)
14030 (outline-next-heading)
14031 (setq end (point))
14032 (goto-char beg)
14033 (while (re-search-forward re end t))
14034 (setq hiddenp (outline-invisible-p))
14035 (end-of-line 1)
14036 (and (equal (char-after) ?\n) (forward-char 1))
14037 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
14038 (if (member (match-string 1) '("CLOCK:" ":END:"))
14039 ;; just skip this line
14040 (beginning-of-line 2)
14041 ;; Drawer start, find the end
14042 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
14043 (beginning-of-line 1)))
14044 (org-skip-over-state-notes)
14045 (skip-chars-backward " \t\n\r")
14046 (if (eq (char-before) ?*) (forward-char 1))
14047 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
14048 (beginning-of-line 0)
14049 (org-indent-to-column indent)
14050 (beginning-of-line 2)
14051 (org-indent-to-column indent)
14052 (beginning-of-line 0)
14053 (if hiddenp
14054 (save-excursion
14055 (org-back-to-heading t)
14056 (hide-entry))
14057 (org-flag-drawer t))))
14059 (defvar org-property-set-functions-alist nil
14060 "Property set function alist.
14061 Each entry should have the following format:
14063 (PROPERTY . READ-FUNCTION)
14065 The read function will be called with the same argument as
14066 `org-completing-read'.")
14068 (defun org-set-property-function (property)
14069 "Get the function that should be used to set PROPERTY.
14070 This is computed according to `org-property-set-functions-alist'."
14071 (or (cdr (assoc property org-property-set-functions-alist))
14072 'org-completing-read))
14074 (defun org-read-property-value (property)
14075 "Read PROPERTY value from user."
14076 (let* ((completion-ignore-case t)
14077 (allowed (org-property-get-allowed-values nil property 'table))
14078 (cur (org-entry-get nil property))
14079 (prompt (concat property " value"
14080 (if (and cur (string-match "\\S-" cur))
14081 (concat " [" cur "]") "") ": "))
14082 (set-function (org-set-property-function property))
14083 (val (if allowed
14084 (funcall set-function prompt allowed nil
14085 (not (get-text-property 0 'org-unrestricted
14086 (caar allowed))))
14087 (let (org-completion-use-ido org-completion-use-iswitchb)
14088 (funcall set-function prompt
14089 (mapcar 'list (org-property-values property))
14090 nil nil "" nil cur)))))
14091 (if (equal val "")
14093 val)))
14095 (defun org-read-property-name ()
14096 "Read a property name."
14097 (let* ((completion-ignore-case t)
14098 (keys (org-buffer-property-keys nil t t))
14099 (default-prop (save-excursion
14100 (save-match-data
14101 (beginning-of-line)
14102 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
14103 (null (string= (match-string 1) "END"))
14104 (match-string 1)))))
14105 (property (org-icompleting-read
14106 (concat "Property"
14107 (if default-prop (concat " [" default-prop "]") "")
14108 ": ")
14109 (mapcar 'list keys)
14110 nil nil nil nil
14111 default-prop
14113 (if (member property keys)
14114 property
14115 (or (cdr (assoc (downcase property)
14116 (mapcar (lambda (x) (cons (downcase x) x))
14117 keys)))
14118 property))))
14120 (defun org-set-property (property value)
14121 "In the current entry, set PROPERTY to VALUE.
14122 When called interactively, this will prompt for a property name, offering
14123 completion on existing and default properties. And then it will prompt
14124 for a value, offering completion either on allowed values (via an inherited
14125 xxx_ALL property) or on existing values in other instances of this property
14126 in the current file."
14127 (interactive (list nil nil))
14128 (let* ((property (or property (org-read-property-name)))
14129 (value (or value (org-read-property-value property))))
14130 (unless (equal (org-entry-get nil property) value)
14131 (org-entry-put nil property value))))
14133 (defun org-delete-property (property)
14134 "In the current entry, delete PROPERTY."
14135 (interactive
14136 (let* ((completion-ignore-case t)
14137 (prop (org-icompleting-read "Property: "
14138 (org-entry-properties nil 'standard))))
14139 (list prop)))
14140 (message "Property %s %s" property
14141 (if (org-entry-delete nil property)
14142 "deleted"
14143 "was not present in the entry")))
14145 (defun org-delete-property-globally (property)
14146 "Remove PROPERTY globally, from all entries."
14147 (interactive
14148 (let* ((completion-ignore-case t)
14149 (prop (org-icompleting-read
14150 "Globally remove property: "
14151 (mapcar 'list (org-buffer-property-keys)))))
14152 (list prop)))
14153 (save-excursion
14154 (save-restriction
14155 (widen)
14156 (goto-char (point-min))
14157 (let ((cnt 0))
14158 (while (re-search-forward
14159 (org-re-property property)
14160 nil t)
14161 (setq cnt (1+ cnt))
14162 (replace-match ""))
14163 (message "Property \"%s\" removed from %d entries" property cnt)))))
14165 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
14167 (defun org-compute-property-at-point ()
14168 "Compute the property at point.
14169 This looks for an enclosing column format, extracts the operator and
14170 then applies it to the property in the column format's scope."
14171 (interactive)
14172 (unless (org-at-property-p)
14173 (error "Not at a property"))
14174 (let ((prop (org-match-string-no-properties 2)))
14175 (org-columns-get-format-and-top-level)
14176 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
14177 (error "No operator defined for property %s" prop))
14178 (org-columns-compute prop)))
14180 (defvar org-property-allowed-value-functions nil
14181 "Hook for functions supplying allowed values for a specific property.
14182 The functions must take a single argument, the name of the property, and
14183 return a flat list of allowed values. If \":ETC\" is one of
14184 the values, this means that these values are intended as defaults for
14185 completion, but that other values should be allowed too.
14186 The functions must return nil if they are not responsible for this
14187 property.")
14189 (defun org-property-get-allowed-values (pom property &optional table)
14190 "Get allowed values for the property PROPERTY.
14191 When TABLE is non-nil, return an alist that can directly be used for
14192 completion."
14193 (let (vals)
14194 (cond
14195 ((equal property "TODO")
14196 (setq vals (org-with-point-at pom
14197 (append org-todo-keywords-1 '("")))))
14198 ((equal property "PRIORITY")
14199 (let ((n org-lowest-priority))
14200 (while (>= n org-highest-priority)
14201 (push (char-to-string n) vals)
14202 (setq n (1- n)))))
14203 ((member property org-special-properties))
14204 ((setq vals (run-hook-with-args-until-success
14205 'org-property-allowed-value-functions property)))
14207 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
14208 (when (and vals (string-match "\\S-" vals))
14209 (setq vals (car (read-from-string (concat "(" vals ")"))))
14210 (setq vals (mapcar (lambda (x)
14211 (cond ((stringp x) x)
14212 ((numberp x) (number-to-string x))
14213 ((symbolp x) (symbol-name x))
14214 (t "???")))
14215 vals)))))
14216 (when (member ":ETC" vals)
14217 (setq vals (remove ":ETC" vals))
14218 (org-add-props (car vals) '(org-unrestricted t)))
14219 (if table (mapcar 'list vals) vals)))
14221 (defun org-property-previous-allowed-value (&optional previous)
14222 "Switch to the next allowed value for this property."
14223 (interactive)
14224 (org-property-next-allowed-value t))
14226 (defun org-property-next-allowed-value (&optional previous)
14227 "Switch to the next allowed value for this property."
14228 (interactive)
14229 (unless (org-at-property-p)
14230 (error "Not at a property"))
14231 (let* ((key (match-string 2))
14232 (value (match-string 3))
14233 (allowed (or (org-property-get-allowed-values (point) key)
14234 (and (member value '("[ ]" "[-]" "[X]"))
14235 '("[ ]" "[X]"))))
14236 nval)
14237 (unless allowed
14238 (error "Allowed values for this property have not been defined"))
14239 (if previous (setq allowed (reverse allowed)))
14240 (if (member value allowed)
14241 (setq nval (car (cdr (member value allowed)))))
14242 (setq nval (or nval (car allowed)))
14243 (if (equal nval value)
14244 (error "Only one allowed value for this property"))
14245 (org-at-property-p)
14246 (replace-match (concat " :" key ": " nval) t t)
14247 (org-indent-line-function)
14248 (beginning-of-line 1)
14249 (skip-chars-forward " \t")
14250 (run-hook-with-args 'org-property-changed-functions key nval)))
14252 (defun org-find-olp (path &optional this-buffer)
14253 "Return a marker pointing to the entry at outline path OLP.
14254 If anything goes wrong, throw an error.
14255 You can wrap this call to catch the error like this:
14257 (condition-case msg
14258 (org-mobile-locate-entry (match-string 4))
14259 (error (nth 1 msg)))
14261 The return value will then be either a string with the error message,
14262 or a marker if everything is OK.
14264 If THIS-BUFFER is set, the outline path does not contain a file,
14265 only headings."
14266 (let* ((file (if this-buffer buffer-file-name (pop path)))
14267 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
14268 (level 1)
14269 (lmin 1)
14270 (lmax 1)
14271 limit re end found pos heading cnt flevel)
14272 (unless buffer (error "File not found :%s" file))
14273 (with-current-buffer buffer
14274 (save-excursion
14275 (save-restriction
14276 (widen)
14277 (setq limit (point-max))
14278 (goto-char (point-min))
14279 (while (setq heading (pop path))
14280 (setq re (format org-complex-heading-regexp-format
14281 (regexp-quote heading)))
14282 (setq cnt 0 pos (point))
14283 (while (re-search-forward re end t)
14284 (setq level (- (match-end 1) (match-beginning 1)))
14285 (if (and (>= level lmin) (<= level lmax))
14286 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
14287 (when (= cnt 0) (error "Heading not found on level %d: %s"
14288 lmax heading))
14289 (when (> cnt 1) (error "Heading not unique on level %d: %s"
14290 lmax heading))
14291 (goto-char found)
14292 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
14293 (setq end (save-excursion (org-end-of-subtree t t))))
14294 (when (org-on-heading-p)
14295 (move-marker (make-marker) (point))))))))
14297 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
14298 "Find node HEADING in BUFFER.
14299 Return a marker to the heading if it was found, or nil if not.
14300 If POS-ONLY is set, return just the position instead of a marker.
14302 The heading text must match exact, but it may have a TODO keyword,
14303 a priority cookie and tags in the standard locations."
14304 (with-current-buffer (or buffer (current-buffer))
14305 (save-excursion
14306 (save-restriction
14307 (widen)
14308 (goto-char (point-min))
14309 (let (case-fold-search)
14310 (if (re-search-forward
14311 (format org-complex-heading-regexp-format
14312 (regexp-quote heading)) nil t)
14313 (if pos-only
14314 (match-beginning 0)
14315 (move-marker (make-marker) (match-beginning 0)))))))))
14317 (defun org-find-exact-heading-in-directory (heading &optional dir)
14318 "Find Org node headline HEADING in all .org files in directory DIR.
14319 When the target headline is found, return a marker to this location."
14320 (let ((files (directory-files (or dir default-directory)
14321 nil "\\`[^.#].*\\.org\\'"))
14322 file visiting m buffer)
14323 (catch 'found
14324 (while (setq file (pop files))
14325 (message "trying %s" file)
14326 (setq visiting (org-find-base-buffer-visiting file))
14327 (setq buffer (or visiting (find-file-noselect file)))
14328 (setq m (org-find-exact-headline-in-buffer
14329 heading buffer))
14330 (when (and (not m) (not visiting)) (kill-buffer buffer))
14331 (and m (throw 'found m))))))
14333 (defun org-find-entry-with-id (ident)
14334 "Locate the entry that contains the ID property with exact value IDENT.
14335 IDENT can be a string, a symbol or a number, this function will search for
14336 the string representation of it.
14337 Return the position where this entry starts, or nil if there is no such entry."
14338 (interactive "sID: ")
14339 (let ((id (cond
14340 ((stringp ident) ident)
14341 ((symbol-name ident) (symbol-name ident))
14342 ((numberp ident) (number-to-string ident))
14343 (t (error "IDENT %s must be a string, symbol or number" ident))))
14344 (case-fold-search nil))
14345 (save-excursion
14346 (save-restriction
14347 (widen)
14348 (goto-char (point-min))
14349 (when (re-search-forward
14350 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
14351 nil t)
14352 (org-back-to-heading t)
14353 (point))))))
14355 ;;;; Timestamps
14357 (defvar org-last-changed-timestamp nil)
14358 (defvar org-last-inserted-timestamp nil
14359 "The last time stamp inserted with `org-insert-time-stamp'.")
14360 (defvar org-time-was-given) ; dynamically scoped parameter
14361 (defvar org-end-time-was-given) ; dynamically scoped parameter
14362 (defvar org-ts-what) ; dynamically scoped parameter
14364 (defun org-time-stamp (arg &optional inactive)
14365 "Prompt for a date/time and insert a time stamp.
14366 If the user specifies a time like HH:MM, or if this command is called
14367 with a prefix argument, the time stamp will contain date and time.
14368 Otherwise, only the date will be included. All parts of a date not
14369 specified by the user will be filled in from the current date/time.
14370 So if you press just return without typing anything, the time stamp
14371 will represent the current date/time. If there is already a timestamp
14372 at the cursor, it will be modified."
14373 (interactive "P")
14374 (let* ((ts nil)
14375 (default-time
14376 ;; Default time is either today, or, when entering a range,
14377 ;; the range start.
14378 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
14379 (save-excursion
14380 (re-search-backward
14381 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
14382 (- (point) 20) t)))
14383 (apply 'encode-time (org-parse-time-string (match-string 1)))
14384 (current-time)))
14385 (default-input (and ts (org-get-compact-tod ts)))
14386 (repeater (save-excursion
14387 (save-match-data
14388 (beginning-of-line)
14389 (when (re-search-forward
14390 "\\([.+-]+[0-9]+[dwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[dwmy]\\)?\\) ?"
14391 (save-excursion (progn (end-of-line) (point))) t)
14392 (match-string 0)))))
14393 org-time-was-given org-end-time-was-given time)
14394 (cond
14395 ((and (org-at-timestamp-p t)
14396 (memq last-command '(org-time-stamp org-time-stamp-inactive))
14397 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
14398 (insert "--")
14399 (setq time (let ((this-command this-command))
14400 (org-read-date arg 'totime nil nil
14401 default-time default-input)))
14402 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
14403 ((org-at-timestamp-p t)
14404 (setq time (let ((this-command this-command))
14405 (org-read-date arg 'totime nil nil default-time default-input)))
14406 (when (org-at-timestamp-p t) ; just to get the match data
14407 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
14408 (replace-match "")
14409 (setq org-last-changed-timestamp
14410 (org-insert-time-stamp
14411 time (or org-time-was-given arg)
14412 inactive nil nil (list org-end-time-was-given)))
14413 (when repeater (goto-char (1- (point))) (insert " " repeater)
14414 (setq org-last-changed-timestamp
14415 (concat (substring org-last-inserted-timestamp 0 -1)
14416 " " repeater ">"))))
14417 (message "Timestamp updated"))
14419 (setq time (let ((this-command this-command))
14420 (org-read-date arg 'totime nil nil default-time default-input)))
14421 (org-insert-time-stamp time (or org-time-was-given arg) inactive
14422 nil nil (list org-end-time-was-given))))))
14424 ;; FIXME: can we use this for something else, like computing time differences?
14425 (defun org-get-compact-tod (s)
14426 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
14427 (let* ((t1 (match-string 1 s))
14428 (h1 (string-to-number (match-string 2 s)))
14429 (m1 (string-to-number (match-string 3 s)))
14430 (t2 (and (match-end 4) (match-string 5 s)))
14431 (h2 (and t2 (string-to-number (match-string 6 s))))
14432 (m2 (and t2 (string-to-number (match-string 7 s))))
14433 dh dm)
14434 (if (not t2)
14436 (setq dh (- h2 h1) dm (- m2 m1))
14437 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
14438 (concat t1 "+" (number-to-string dh)
14439 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
14441 (defun org-time-stamp-inactive (&optional arg)
14442 "Insert an inactive time stamp.
14443 An inactive time stamp is enclosed in square brackets instead of angle
14444 brackets. It is inactive in the sense that it does not trigger agenda entries,
14445 does not link to the calendar and cannot be changed with the S-cursor keys.
14446 So these are more for recording a certain time/date."
14447 (interactive "P")
14448 (org-time-stamp arg 'inactive))
14450 (defvar org-date-ovl (make-overlay 1 1))
14451 (overlay-put org-date-ovl 'face 'org-warning)
14452 (org-detach-overlay org-date-ovl)
14454 (defvar org-ans1) ; dynamically scoped parameter
14455 (defvar org-ans2) ; dynamically scoped parameter
14457 (defvar org-plain-time-of-day-regexp) ; defined below
14459 (defvar org-overriding-default-time nil) ; dynamically scoped
14460 (defvar org-read-date-overlay nil)
14461 (defvar org-dcst nil) ; dynamically scoped
14462 (defvar org-read-date-history nil)
14463 (defvar org-read-date-final-answer nil)
14464 (defvar org-read-date-analyze-futurep nil)
14465 (defvar org-read-date-analyze-forced-year nil)
14467 (defun org-read-date (&optional with-time to-time from-string prompt
14468 default-time default-input)
14469 "Read a date, possibly a time, and make things smooth for the user.
14470 The prompt will suggest to enter an ISO date, but you can also enter anything
14471 which will at least partially be understood by `parse-time-string'.
14472 Unrecognized parts of the date will default to the current day, month, year,
14473 hour and minute. If this command is called to replace a timestamp at point,
14474 of to enter the second timestamp of a range, the default time is taken
14475 from the existing stamp. Furthermore, the command prefers the future,
14476 so if you are giving a date where the year is not given, and the day-month
14477 combination is already past in the current year, it will assume you
14478 mean next year. For details, see the manual. A few examples:
14480 3-2-5 --> 2003-02-05
14481 feb 15 --> currentyear-02-15
14482 2/15 --> currentyear-02-15
14483 sep 12 9 --> 2009-09-12
14484 12:45 --> today 12:45
14485 22 sept 0:34 --> currentyear-09-22 0:34
14486 12 --> currentyear-currentmonth-12
14487 Fri --> nearest Friday (today or later)
14488 etc.
14490 Furthermore you can specify a relative date by giving, as the *first* thing
14491 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
14492 change in days weeks, months, years.
14493 With a single plus or minus, the date is relative to today. With a double
14494 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
14495 +4d --> four days from today
14496 +4 --> same as above
14497 +2w --> two weeks from today
14498 ++5 --> five days from default date
14500 The function understands only English month and weekday abbreviations,
14501 but this can be configured with the variables `parse-time-months' and
14502 `parse-time-weekdays'.
14504 While prompting, a calendar is popped up - you can also select the
14505 date with the mouse (button 1). The calendar shows a period of three
14506 months. To scroll it to other months, use the keys `>' and `<'.
14507 If you don't like the calendar, turn it off with
14508 \(setq org-read-date-popup-calendar nil)
14510 With optional argument TO-TIME, the date will immediately be converted
14511 to an internal time.
14512 With an optional argument WITH-TIME, the prompt will suggest to also
14513 insert a time. Note that when WITH-TIME is not set, you can still
14514 enter a time, and this function will inform the calling routine about
14515 this change. The calling routine may then choose to change the format
14516 used to insert the time stamp into the buffer to include the time.
14517 With optional argument FROM-STRING, read from this string instead from
14518 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
14519 the time/date that is used for everything that is not specified by the
14520 user."
14521 (require 'parse-time)
14522 (let* ((org-time-stamp-rounding-minutes
14523 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
14524 (org-dcst org-display-custom-times)
14525 (ct (org-current-time))
14526 (def (or org-overriding-default-time default-time ct))
14527 (defdecode (decode-time def))
14528 (dummy (progn
14529 (when (< (nth 2 defdecode) org-extend-today-until)
14530 (setcar (nthcdr 2 defdecode) -1)
14531 (setcar (nthcdr 1 defdecode) 59)
14532 (setq def (apply 'encode-time defdecode)
14533 defdecode (decode-time def)))))
14534 (calendar-frame-setup nil)
14535 (calendar-setup nil)
14536 (calendar-move-hook nil)
14537 (calendar-view-diary-initially-flag nil)
14538 (calendar-view-holidays-initially-flag nil)
14539 (timestr (format-time-string
14540 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
14541 (prompt (concat (if prompt (concat prompt " ") "")
14542 (format "Date+time [%s]: " timestr)))
14543 ans (org-ans0 "") org-ans1 org-ans2 final)
14545 (cond
14546 (from-string (setq ans from-string))
14547 (org-read-date-popup-calendar
14548 (save-excursion
14549 (save-window-excursion
14550 (calendar)
14551 (unwind-protect
14552 (progn
14553 (calendar-forward-day (- (time-to-days def)
14554 (calendar-absolute-from-gregorian
14555 (calendar-current-date))))
14556 (org-eval-in-calendar nil t)
14557 (let* ((old-map (current-local-map))
14558 (map (copy-keymap calendar-mode-map))
14559 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
14560 (org-defkey map (kbd "RET") 'org-calendar-select)
14561 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
14562 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
14563 (org-defkey minibuffer-local-map [(meta shift left)]
14564 (lambda () (interactive)
14565 (org-eval-in-calendar '(calendar-backward-month 1))))
14566 (org-defkey minibuffer-local-map [(meta shift right)]
14567 (lambda () (interactive)
14568 (org-eval-in-calendar '(calendar-forward-month 1))))
14569 (org-defkey minibuffer-local-map [(meta shift up)]
14570 (lambda () (interactive)
14571 (org-eval-in-calendar '(calendar-backward-year 1))))
14572 (org-defkey minibuffer-local-map [(meta shift down)]
14573 (lambda () (interactive)
14574 (org-eval-in-calendar '(calendar-forward-year 1))))
14575 (org-defkey minibuffer-local-map [?\e (shift left)]
14576 (lambda () (interactive)
14577 (org-eval-in-calendar '(calendar-backward-month 1))))
14578 (org-defkey minibuffer-local-map [?\e (shift right)]
14579 (lambda () (interactive)
14580 (org-eval-in-calendar '(calendar-forward-month 1))))
14581 (org-defkey minibuffer-local-map [?\e (shift up)]
14582 (lambda () (interactive)
14583 (org-eval-in-calendar '(calendar-backward-year 1))))
14584 (org-defkey minibuffer-local-map [?\e (shift down)]
14585 (lambda () (interactive)
14586 (org-eval-in-calendar '(calendar-forward-year 1))))
14587 (org-defkey minibuffer-local-map [(shift up)]
14588 (lambda () (interactive)
14589 (org-eval-in-calendar '(calendar-backward-week 1))))
14590 (org-defkey minibuffer-local-map [(shift down)]
14591 (lambda () (interactive)
14592 (org-eval-in-calendar '(calendar-forward-week 1))))
14593 (org-defkey minibuffer-local-map [(shift left)]
14594 (lambda () (interactive)
14595 (org-eval-in-calendar '(calendar-backward-day 1))))
14596 (org-defkey minibuffer-local-map [(shift right)]
14597 (lambda () (interactive)
14598 (org-eval-in-calendar '(calendar-forward-day 1))))
14599 (org-defkey minibuffer-local-map ">"
14600 (lambda () (interactive)
14601 (org-eval-in-calendar '(scroll-calendar-left 1))))
14602 (org-defkey minibuffer-local-map "<"
14603 (lambda () (interactive)
14604 (org-eval-in-calendar '(scroll-calendar-right 1))))
14605 (org-defkey minibuffer-local-map "\C-v"
14606 (lambda () (interactive)
14607 (org-eval-in-calendar
14608 '(calendar-scroll-left-three-months 1))))
14609 (org-defkey minibuffer-local-map "\M-v"
14610 (lambda () (interactive)
14611 (org-eval-in-calendar
14612 '(calendar-scroll-right-three-months 1))))
14613 (run-hooks 'org-read-date-minibuffer-setup-hook)
14614 (unwind-protect
14615 (progn
14616 (use-local-map map)
14617 (add-hook 'post-command-hook 'org-read-date-display)
14618 (setq org-ans0 (read-string prompt default-input
14619 'org-read-date-history nil))
14620 ;; org-ans0: from prompt
14621 ;; org-ans1: from mouse click
14622 ;; org-ans2: from calendar motion
14623 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
14624 (remove-hook 'post-command-hook 'org-read-date-display)
14625 (use-local-map old-map)
14626 (when org-read-date-overlay
14627 (delete-overlay org-read-date-overlay)
14628 (setq org-read-date-overlay nil)))))
14629 (bury-buffer "*Calendar*")))))
14631 (t ; Naked prompt only
14632 (unwind-protect
14633 (setq ans (read-string prompt default-input
14634 'org-read-date-history timestr))
14635 (when org-read-date-overlay
14636 (delete-overlay org-read-date-overlay)
14637 (setq org-read-date-overlay nil)))))
14639 (setq final (org-read-date-analyze ans def defdecode))
14641 (when org-read-date-analyze-forced-year
14642 (message "Year was forced into %s"
14643 (if org-read-date-force-compatible-dates
14644 "compatible range (1970-2037)"
14645 "range representable on this machine"))
14646 (ding))
14648 ;; One round trip to get rid of 34th of August and stuff like that....
14649 (setq final (decode-time (apply 'encode-time final)))
14651 (setq org-read-date-final-answer ans)
14653 (if to-time
14654 (apply 'encode-time final)
14655 (if (and (boundp 'org-time-was-given) org-time-was-given)
14656 (format "%04d-%02d-%02d %02d:%02d"
14657 (nth 5 final) (nth 4 final) (nth 3 final)
14658 (nth 2 final) (nth 1 final))
14659 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
14661 (defvar def)
14662 (defvar defdecode)
14663 (defvar with-time)
14664 (defun org-read-date-display ()
14665 "Display the current date prompt interpretation in the minibuffer."
14666 (when org-read-date-display-live
14667 (when org-read-date-overlay
14668 (delete-overlay org-read-date-overlay))
14669 (let ((p (point)))
14670 (end-of-line 1)
14671 (while (not (equal (buffer-substring
14672 (max (point-min) (- (point) 4)) (point))
14673 " "))
14674 (insert " "))
14675 (goto-char p))
14676 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
14677 " " (or org-ans1 org-ans2)))
14678 (org-end-time-was-given nil)
14679 (f (org-read-date-analyze ans def defdecode))
14680 (fmts (if org-dcst
14681 org-time-stamp-custom-formats
14682 org-time-stamp-formats))
14683 (fmt (if (or with-time
14684 (and (boundp 'org-time-was-given) org-time-was-given))
14685 (cdr fmts)
14686 (car fmts)))
14687 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
14688 (when (and org-end-time-was-given
14689 (string-match org-plain-time-of-day-regexp txt))
14690 (setq txt (concat (substring txt 0 (match-end 0)) "-"
14691 org-end-time-was-given
14692 (substring txt (match-end 0)))))
14693 (when org-read-date-analyze-futurep
14694 (setq txt (concat txt " (=>F)")))
14695 (setq org-read-date-overlay
14696 (make-overlay (1- (point-at-eol)) (point-at-eol)))
14697 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
14699 (defun org-read-date-analyze (ans def defdecode)
14700 "Analyze the combined answer of the date prompt."
14701 ;; FIXME: cleanup and comment
14702 (let ((nowdecode (decode-time (current-time)))
14703 delta deltan deltaw deltadef year month day
14704 hour minute second wday pm h2 m2 tl wday1
14705 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
14706 (setq org-read-date-analyze-futurep nil
14707 org-read-date-analyze-forced-year nil)
14708 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
14709 (setq ans "+0"))
14711 (when (setq delta (org-read-date-get-relative ans (current-time) def))
14712 (setq ans (replace-match "" t t ans)
14713 deltan (car delta)
14714 deltaw (nth 1 delta)
14715 deltadef (nth 2 delta)))
14717 ;; Check if there is an iso week date in there
14718 ;; If yes, store the info and postpone interpreting it until the rest
14719 ;; of the parsing is done
14720 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
14721 (setq iso-year (if (match-end 1)
14722 (org-small-year-to-year
14723 (string-to-number (match-string 1 ans))))
14724 iso-weekday (if (match-end 3)
14725 (string-to-number (match-string 3 ans)))
14726 iso-week (string-to-number (match-string 2 ans)))
14727 (setq ans (replace-match "" t t ans)))
14729 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
14730 (when (string-match
14731 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
14732 (setq year (if (match-end 2)
14733 (string-to-number (match-string 2 ans))
14734 (progn (setq kill-year t)
14735 (string-to-number (format-time-string "%Y"))))
14736 month (string-to-number (match-string 3 ans))
14737 day (string-to-number (match-string 4 ans)))
14738 (if (< year 100) (setq year (+ 2000 year)))
14739 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
14740 t nil ans)))
14742 ;; Help matching dottet european dates
14743 (when (string-match
14744 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\. ?\\([1-9][0-9][0-9][0-9]\\)?" ans)
14745 (setq year (if (match-end 3)
14746 (string-to-number (match-string 3 ans))
14747 (progn (setq kill-year t)
14748 (string-to-number (format-time-string "%Y"))))
14749 day (string-to-number (match-string 1 ans))
14750 month (string-to-number (match-string 2 ans))
14751 ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
14752 t nil ans)))
14754 ;; Help matching american dates, like 5/30 or 5/30/7
14755 (when (string-match
14756 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
14757 (setq year (if (match-end 4)
14758 (string-to-number (match-string 4 ans))
14759 (progn (setq kill-year t)
14760 (string-to-number (format-time-string "%Y"))))
14761 month (string-to-number (match-string 1 ans))
14762 day (string-to-number (match-string 2 ans)))
14763 (if (< year 100) (setq year (+ 2000 year)))
14764 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
14765 t nil ans)))
14766 ;; Help matching am/pm times, because `parse-time-string' does not do that.
14767 ;; If there is a time with am/pm, and *no* time without it, we convert
14768 ;; so that matching will be successful.
14769 (loop for i from 1 to 2 do ; twice, for end time as well
14770 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
14771 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
14772 (setq hour (string-to-number (match-string 1 ans))
14773 minute (if (match-end 3)
14774 (string-to-number (match-string 3 ans))
14776 pm (equal ?p
14777 (string-to-char (downcase (match-string 4 ans)))))
14778 (if (and (= hour 12) (not pm))
14779 (setq hour 0)
14780 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
14781 (setq ans (replace-match (format "%02d:%02d" hour minute)
14782 t t ans))))
14784 ;; Check if a time range is given as a duration
14785 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
14786 (setq hour (string-to-number (match-string 1 ans))
14787 h2 (+ hour (string-to-number (match-string 3 ans)))
14788 minute (string-to-number (match-string 2 ans))
14789 m2 (+ minute (if (match-end 5) (string-to-number
14790 (match-string 5 ans))0)))
14791 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
14792 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
14793 t t ans)))
14795 ;; Check if there is a time range
14796 (when (boundp 'org-end-time-was-given)
14797 (setq org-time-was-given nil)
14798 (when (and (string-match org-plain-time-of-day-regexp ans)
14799 (match-end 8))
14800 (setq org-end-time-was-given (match-string 8 ans))
14801 (setq ans (concat (substring ans 0 (match-beginning 7))
14802 (substring ans (match-end 7))))))
14804 (setq tl (parse-time-string ans)
14805 day (or (nth 3 tl) (nth 3 defdecode))
14806 month (or (nth 4 tl)
14807 (if (and org-read-date-prefer-future
14808 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
14809 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
14810 (nth 4 defdecode)))
14811 year (or (and (not kill-year) (nth 5 tl))
14812 (if (and org-read-date-prefer-future
14813 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
14814 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
14815 (nth 5 defdecode)))
14816 hour (or (nth 2 tl) (nth 2 defdecode))
14817 minute (or (nth 1 tl) (nth 1 defdecode))
14818 second (or (nth 0 tl) 0)
14819 wday (nth 6 tl))
14821 (when (and (eq org-read-date-prefer-future 'time)
14822 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
14823 (equal day (nth 3 nowdecode))
14824 (equal month (nth 4 nowdecode))
14825 (equal year (nth 5 nowdecode))
14826 (nth 2 tl)
14827 (or (< (nth 2 tl) (nth 2 nowdecode))
14828 (and (= (nth 2 tl) (nth 2 nowdecode))
14829 (nth 1 tl)
14830 (< (nth 1 tl) (nth 1 nowdecode)))))
14831 (setq day (1+ day)
14832 futurep t))
14834 ;; Special date definitions below
14835 (cond
14836 (iso-week
14837 ;; There was an iso week
14838 (require 'cal-iso)
14839 (setq futurep nil)
14840 (setq year (or iso-year year)
14841 day (or iso-weekday wday 1)
14842 wday nil ; to make sure that the trigger below does not match
14843 iso-date (calendar-gregorian-from-absolute
14844 (calendar-absolute-from-iso
14845 (list iso-week day year))))
14846 ; FIXME: Should we also push ISO weeks into the future?
14847 ; (when (and org-read-date-prefer-future
14848 ; (not iso-year)
14849 ; (< (calendar-absolute-from-gregorian iso-date)
14850 ; (time-to-days (current-time))))
14851 ; (setq year (1+ year)
14852 ; iso-date (calendar-gregorian-from-absolute
14853 ; (calendar-absolute-from-iso
14854 ; (list iso-week day year)))))
14855 (setq month (car iso-date)
14856 year (nth 2 iso-date)
14857 day (nth 1 iso-date)))
14858 (deltan
14859 (setq futurep nil)
14860 (unless deltadef
14861 (let ((now (decode-time (current-time))))
14862 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
14863 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
14864 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
14865 ((equal deltaw "m") (setq month (+ month deltan)))
14866 ((equal deltaw "y") (setq year (+ year deltan)))))
14867 ((and wday (not (nth 3 tl)))
14868 (setq futurep nil)
14869 ;; Weekday was given, but no day, so pick that day in the week
14870 ;; on or after the derived date.
14871 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
14872 (unless (equal wday wday1)
14873 (setq day (+ day (% (- wday wday1 -7) 7))))))
14874 (if (and (boundp 'org-time-was-given)
14875 (nth 2 tl))
14876 (setq org-time-was-given t))
14877 (if (< year 100) (setq year (+ 2000 year)))
14878 ;; Check of the date is representable
14879 (if org-read-date-force-compatible-dates
14880 (progn
14881 (if (< year 1970)
14882 (setq year 1970 org-read-date-analyze-forced-year t))
14883 (if (> year 2037)
14884 (setq year 2037 org-read-date-analyze-forced-year t)))
14885 (condition-case nil
14886 (ignore (encode-time second minute hour day month year))
14887 (error
14888 (setq year (nth 5 defdecode))
14889 (setq org-read-date-analyze-forced-year t))))
14890 (setq org-read-date-analyze-futurep futurep)
14891 (list second minute hour day month year)))
14893 (defvar parse-time-weekdays)
14895 (defun org-read-date-get-relative (s today default)
14896 "Check string S for special relative date string.
14897 TODAY and DEFAULT are internal times, for today and for a default.
14898 Return shift list (N what def-flag)
14899 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
14900 N is the number of WHATs to shift.
14901 DEF-FLAG is t when a double ++ or -- indicates shift relative to
14902 the DEFAULT date rather than TODAY."
14903 (when (and
14904 (string-match
14905 (concat
14906 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
14907 "\\([0-9]+\\)?"
14908 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
14909 "\\([ \t]\\|$\\)") s)
14910 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
14911 (let* ((dir (if (> (match-end 1) (match-beginning 1))
14912 (string-to-char (substring (match-string 1 s) -1))
14913 ?+))
14914 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
14915 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
14916 (what (if (match-end 3) (match-string 3 s) "d"))
14917 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
14918 (date (if rel default today))
14919 (wday (nth 6 (decode-time date)))
14920 delta)
14921 (if wday1
14922 (progn
14923 (setq delta (mod (+ 7 (- wday1 wday)) 7))
14924 (if (= dir ?-) (setq delta (- delta 7)))
14925 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
14926 (list delta "d" rel))
14927 (list (* n (if (= dir ?-) -1 1)) what rel)))))
14929 (defun org-order-calendar-date-args (arg1 arg2 arg3)
14930 "Turn a user-specified date into the internal representation.
14931 The internal representation needed by the calendar is (month day year).
14932 This is a wrapper to handle the brain-dead convention in calendar that
14933 user function argument order change dependent on argument order."
14934 (if (boundp 'calendar-date-style)
14935 (cond
14936 ((eq calendar-date-style 'american)
14937 (list arg1 arg2 arg3))
14938 ((eq calendar-date-style 'european)
14939 (list arg2 arg1 arg3))
14940 ((eq calendar-date-style 'iso)
14941 (list arg2 arg3 arg1)))
14942 (with-no-warnings ;; european-calendar-style is obsolete as of version 23.1
14943 (if (org-bound-and-true-p european-calendar-style)
14944 (list arg2 arg1 arg3)
14945 (list arg1 arg2 arg3)))))
14947 (defun org-eval-in-calendar (form &optional keepdate)
14948 "Eval FORM in the calendar window and return to current window.
14949 Also, store the cursor date in variable org-ans2."
14950 (let ((sf (selected-frame))
14951 (sw (selected-window)))
14952 (select-window (get-buffer-window "*Calendar*" t))
14953 (eval form)
14954 (when (and (not keepdate) (calendar-cursor-to-date))
14955 (let* ((date (calendar-cursor-to-date))
14956 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
14957 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
14958 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
14959 (select-window sw)
14960 (org-select-frame-set-input-focus sf)))
14962 (defun org-calendar-select ()
14963 "Return to `org-read-date' with the date currently selected.
14964 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
14965 (interactive)
14966 (when (calendar-cursor-to-date)
14967 (let* ((date (calendar-cursor-to-date))
14968 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
14969 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
14970 (if (active-minibuffer-window) (exit-minibuffer))))
14972 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
14973 "Insert a date stamp for the date given by the internal TIME.
14974 WITH-HM means use the stamp format that includes the time of the day.
14975 INACTIVE means use square brackets instead of angular ones, so that the
14976 stamp will not contribute to the agenda.
14977 PRE and POST are optional strings to be inserted before and after the
14978 stamp.
14979 The command returns the inserted time stamp."
14980 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
14981 stamp)
14982 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
14983 (insert-before-markers (or pre ""))
14984 (when (listp extra)
14985 (setq extra (car extra))
14986 (if (and (stringp extra)
14987 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
14988 (setq extra (format "-%02d:%02d"
14989 (string-to-number (match-string 1 extra))
14990 (string-to-number (match-string 2 extra))))
14991 (setq extra nil)))
14992 (when extra
14993 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
14994 (insert-before-markers (setq stamp (format-time-string fmt time)))
14995 (insert-before-markers (or post ""))
14996 (setq org-last-inserted-timestamp stamp)))
14998 (defun org-toggle-time-stamp-overlays ()
14999 "Toggle the use of custom time stamp formats."
15000 (interactive)
15001 (setq org-display-custom-times (not org-display-custom-times))
15002 (unless org-display-custom-times
15003 (let ((p (point-min)) (bmp (buffer-modified-p)))
15004 (while (setq p (next-single-property-change p 'display))
15005 (if (and (get-text-property p 'display)
15006 (eq (get-text-property p 'face) 'org-date))
15007 (remove-text-properties
15008 p (setq p (next-single-property-change p 'display))
15009 '(display t))))
15010 (set-buffer-modified-p bmp)))
15011 (if (featurep 'xemacs)
15012 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
15013 (org-restart-font-lock)
15014 (setq org-table-may-need-update t)
15015 (if org-display-custom-times
15016 (message "Time stamps are overlayed with custom format")
15017 (message "Time stamp overlays removed")))
15019 (defun org-display-custom-time (beg end)
15020 "Overlay modified time stamp format over timestamp between BEG and END."
15021 (let* ((ts (buffer-substring beg end))
15022 t1 w1 with-hm tf time str w2 (off 0))
15023 (save-match-data
15024 (setq t1 (org-parse-time-string ts t))
15025 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)?\\'" ts)
15026 (setq off (- (match-end 0) (match-beginning 0)))))
15027 (setq end (- end off))
15028 (setq w1 (- end beg)
15029 with-hm (and (nth 1 t1) (nth 2 t1))
15030 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
15031 time (org-fix-decoded-time t1)
15032 str (org-add-props
15033 (format-time-string
15034 (substring tf 1 -1) (apply 'encode-time time))
15035 nil 'mouse-face 'highlight)
15036 w2 (length str))
15037 (if (not (= w2 w1))
15038 (add-text-properties (1+ beg) (+ 2 beg)
15039 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
15040 (if (featurep 'xemacs)
15041 (progn
15042 (put-text-property beg end 'invisible t)
15043 (put-text-property beg end 'end-glyph (make-glyph str)))
15044 (put-text-property beg end 'display str))))
15046 (defun org-translate-time (string)
15047 "Translate all timestamps in STRING to custom format.
15048 But do this only if the variable `org-display-custom-times' is set."
15049 (when org-display-custom-times
15050 (save-match-data
15051 (let* ((start 0)
15052 (re org-ts-regexp-both)
15053 t1 with-hm inactive tf time str beg end)
15054 (while (setq start (string-match re string start))
15055 (setq beg (match-beginning 0)
15056 end (match-end 0)
15057 t1 (save-match-data
15058 (org-parse-time-string (substring string beg end) t))
15059 with-hm (and (nth 1 t1) (nth 2 t1))
15060 inactive (equal (substring string beg (1+ beg)) "[")
15061 tf (funcall (if with-hm 'cdr 'car)
15062 org-time-stamp-custom-formats)
15063 time (org-fix-decoded-time t1)
15064 str (format-time-string
15065 (concat
15066 (if inactive "[" "<") (substring tf 1 -1)
15067 (if inactive "]" ">"))
15068 (apply 'encode-time time))
15069 string (replace-match str t t string)
15070 start (+ start (length str)))))))
15071 string)
15073 (defun org-fix-decoded-time (time)
15074 "Set 0 instead of nil for the first 6 elements of time.
15075 Don't touch the rest."
15076 (let ((n 0))
15077 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
15079 (defun org-days-to-time (timestamp-string)
15080 "Difference between TIMESTAMP-STRING and now in days."
15081 (- (time-to-days (org-time-string-to-time timestamp-string))
15082 (time-to-days (current-time))))
15084 (defun org-deadline-close (timestamp-string &optional ndays)
15085 "Is the time in TIMESTAMP-STRING close to the current date?"
15086 (setq ndays (or ndays (org-get-wdays timestamp-string)))
15087 (and (< (org-days-to-time timestamp-string) ndays)
15088 (not (org-entry-is-done-p))))
15090 (defun org-get-wdays (ts)
15091 "Get the deadline lead time appropriate for timestring TS."
15092 (cond
15093 ((<= org-deadline-warning-days 0)
15094 ;; 0 or negative, enforce this value no matter what
15095 (- org-deadline-warning-days))
15096 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\| \\)" ts)
15097 ;; lead time is specified.
15098 (floor (* (string-to-number (match-string 1 ts))
15099 (cdr (assoc (match-string 2 ts)
15100 '(("d" . 1) ("w" . 7)
15101 ("m" . 30.4) ("y" . 365.25)))))))
15102 ;; go for the default.
15103 (t org-deadline-warning-days)))
15105 (defun org-calendar-select-mouse (ev)
15106 "Return to `org-read-date' with the date currently selected.
15107 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15108 (interactive "e")
15109 (mouse-set-point ev)
15110 (when (calendar-cursor-to-date)
15111 (let* ((date (calendar-cursor-to-date))
15112 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15113 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15114 (if (active-minibuffer-window) (exit-minibuffer))))
15116 (defun org-check-deadlines (ndays)
15117 "Check if there are any deadlines due or past due.
15118 A deadline is considered due if it happens within `org-deadline-warning-days'
15119 days from today's date. If the deadline appears in an entry marked DONE,
15120 it is not shown. The prefix arg NDAYS can be used to test that many
15121 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
15122 (interactive "P")
15123 (let* ((org-warn-days
15124 (cond
15125 ((equal ndays '(4)) 100000)
15126 (ndays (prefix-numeric-value ndays))
15127 (t (abs org-deadline-warning-days))))
15128 (case-fold-search nil)
15129 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
15130 (callback
15131 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
15133 (message "%d deadlines past-due or due within %d days"
15134 (org-occur regexp nil callback)
15135 org-warn-days)))
15137 (defun org-check-before-date (date)
15138 "Check if there are deadlines or scheduled entries before DATE."
15139 (interactive (list (org-read-date)))
15140 (let ((case-fold-search nil)
15141 (regexp (concat "\\<\\(" org-deadline-string
15142 "\\|" org-scheduled-string
15143 "\\) *<\\([^>]+\\)>"))
15144 (callback
15145 (lambda () (time-less-p
15146 (org-time-string-to-time (match-string 2))
15147 (org-time-string-to-time date)))))
15148 (message "%d entries before %s"
15149 (org-occur regexp nil callback) date)))
15151 (defun org-check-after-date (date)
15152 "Check if there are deadlines or scheduled entries after DATE."
15153 (interactive (list (org-read-date)))
15154 (let ((case-fold-search nil)
15155 (regexp (concat "\\<\\(" org-deadline-string
15156 "\\|" org-scheduled-string
15157 "\\) *<\\([^>]+\\)>"))
15158 (callback
15159 (lambda () (not
15160 (time-less-p
15161 (org-time-string-to-time (match-string 2))
15162 (org-time-string-to-time date))))))
15163 (message "%d entries after %s"
15164 (org-occur regexp nil callback) date)))
15166 (defun org-evaluate-time-range (&optional to-buffer)
15167 "Evaluate a time range by computing the difference between start and end.
15168 Normally the result is just printed in the echo area, but with prefix arg
15169 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
15170 If the time range is actually in a table, the result is inserted into the
15171 next column.
15172 For time difference computation, a year is assumed to be exactly 365
15173 days in order to avoid rounding problems."
15174 (interactive "P")
15176 (org-clock-update-time-maybe)
15177 (save-excursion
15178 (unless (org-at-date-range-p t)
15179 (goto-char (point-at-bol))
15180 (re-search-forward org-tr-regexp-both (point-at-eol) t))
15181 (if (not (org-at-date-range-p t))
15182 (error "Not at a time-stamp range, and none found in current line")))
15183 (let* ((ts1 (match-string 1))
15184 (ts2 (match-string 2))
15185 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
15186 (match-end (match-end 0))
15187 (time1 (org-time-string-to-time ts1))
15188 (time2 (org-time-string-to-time ts2))
15189 (t1 (org-float-time time1))
15190 (t2 (org-float-time time2))
15191 (diff (abs (- t2 t1)))
15192 (negative (< (- t2 t1) 0))
15193 ;; (ys (floor (* 365 24 60 60)))
15194 (ds (* 24 60 60))
15195 (hs (* 60 60))
15196 (fy "%dy %dd %02d:%02d")
15197 (fy1 "%dy %dd")
15198 (fd "%dd %02d:%02d")
15199 (fd1 "%dd")
15200 (fh "%02d:%02d")
15201 y d h m align)
15202 (if havetime
15203 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
15205 d (floor (/ diff ds)) diff (mod diff ds)
15206 h (floor (/ diff hs)) diff (mod diff hs)
15207 m (floor (/ diff 60)))
15208 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
15210 d (floor (+ (/ diff ds) 0.5))
15211 h 0 m 0))
15212 (if (not to-buffer)
15213 (message "%s" (org-make-tdiff-string y d h m))
15214 (if (org-at-table-p)
15215 (progn
15216 (goto-char match-end)
15217 (setq align t)
15218 (and (looking-at " *|") (goto-char (match-end 0))))
15219 (goto-char match-end))
15220 (if (looking-at
15221 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
15222 (replace-match ""))
15223 (if negative (insert " -"))
15224 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
15225 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
15226 (insert " " (format fh h m))))
15227 (if align (org-table-align))
15228 (message "Time difference inserted")))))
15230 (defun org-make-tdiff-string (y d h m)
15231 (let ((fmt "")
15232 (l nil))
15233 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
15234 l (push y l)))
15235 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
15236 l (push d l)))
15237 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
15238 l (push h l)))
15239 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
15240 l (push m l)))
15241 (apply 'format fmt (nreverse l))))
15243 (defun org-time-string-to-time (s)
15244 (apply 'encode-time (org-parse-time-string s)))
15245 (defun org-time-string-to-seconds (s)
15246 (org-float-time (org-time-string-to-time s)))
15248 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
15249 "Convert a time stamp to an absolute day number.
15250 If there is a specifier for a cyclic time stamp, get the closest date to
15251 DAYNR.
15252 PREFER and SHOW-ALL are passed through to `org-closest-date'.
15253 The variable date is bound by the calendar when this is called."
15254 (cond
15255 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
15256 (if (org-diary-sexp-entry (match-string 1 s) "" date)
15257 daynr
15258 (+ daynr 1000)))
15259 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
15260 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
15261 (time-to-days (current-time))) (match-string 0 s)
15262 prefer show-all))
15263 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
15265 (defun org-days-to-iso-week (days)
15266 "Return the iso week number."
15267 (require 'cal-iso)
15268 (car (calendar-iso-from-absolute days)))
15270 (defun org-small-year-to-year (year)
15271 "Convert 2-digit years into 4-digit years.
15272 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
15273 The year 2000 cannot be abbreviated. Any year larger than 99
15274 is returned unchanged."
15275 (if (< year 38)
15276 (setq year (+ 2000 year))
15277 (if (< year 100)
15278 (setq year (+ 1900 year))))
15279 year)
15281 (defun org-time-from-absolute (d)
15282 "Return the time corresponding to date D.
15283 D may be an absolute day number, or a calendar-type list (month day year)."
15284 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
15285 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
15287 (defun org-calendar-holiday ()
15288 "List of holidays, for Diary display in Org-mode."
15289 (require 'holidays)
15290 (let ((hl (funcall
15291 (if (fboundp 'calendar-check-holidays)
15292 'calendar-check-holidays 'check-calendar-holidays) date)))
15293 (if hl (mapconcat 'identity hl "; "))))
15295 (defun org-diary-sexp-entry (sexp entry date)
15296 "Process a SEXP diary ENTRY for DATE."
15297 (require 'diary-lib)
15298 (let ((result (if calendar-debug-sexp
15299 (let ((stack-trace-on-error t))
15300 (eval (car (read-from-string sexp))))
15301 (condition-case nil
15302 (eval (car (read-from-string sexp)))
15303 (error
15304 (beep)
15305 (message "Bad sexp at line %d in %s: %s"
15306 (org-current-line)
15307 (buffer-file-name) sexp)
15308 (sleep-for 2))))))
15309 (cond ((stringp result) (split-string result "; "))
15310 ((and (consp result)
15311 (not (consp (cdr result)))
15312 (stringp (cdr result))) (cdr result))
15313 ((and (consp result)
15314 (stringp (car result))) result)
15315 (result entry)
15316 (t nil))))
15318 (defun org-diary-to-ical-string (frombuf)
15319 "Get iCalendar entries from diary entries in buffer FROMBUF.
15320 This uses the icalendar.el library."
15321 (let* ((tmpdir (if (featurep 'xemacs)
15322 (temp-directory)
15323 temporary-file-directory))
15324 (tmpfile (make-temp-name
15325 (expand-file-name "orgics" tmpdir)))
15326 buf rtn b e)
15327 (with-current-buffer frombuf
15328 (icalendar-export-region (point-min) (point-max) tmpfile)
15329 (setq buf (find-buffer-visiting tmpfile))
15330 (set-buffer buf)
15331 (goto-char (point-min))
15332 (if (re-search-forward "^BEGIN:VEVENT" nil t)
15333 (setq b (match-beginning 0)))
15334 (goto-char (point-max))
15335 (if (re-search-backward "^END:VEVENT" nil t)
15336 (setq e (match-end 0)))
15337 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
15338 (kill-buffer buf)
15339 (delete-file tmpfile)
15340 rtn))
15342 (defun org-closest-date (start current change prefer show-all)
15343 "Find the date closest to CURRENT that is consistent with START and CHANGE.
15344 When PREFER is `past', return a date that is either CURRENT or past.
15345 When PREFER is `future', return a date that is either CURRENT or future.
15346 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
15347 ;; Make the proper lists from the dates
15348 (catch 'exit
15349 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
15350 dn dw sday cday n1 n2 n0
15351 d m y y1 y2 date1 date2 nmonths nm ny m2)
15353 (setq start (org-date-to-gregorian start)
15354 current (org-date-to-gregorian
15355 (if show-all
15356 current
15357 (time-to-days (current-time))))
15358 sday (calendar-absolute-from-gregorian start)
15359 cday (calendar-absolute-from-gregorian current))
15361 (if (<= cday sday) (throw 'exit sday))
15363 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
15364 (setq dn (string-to-number (match-string 1 change))
15365 dw (cdr (assoc (match-string 2 change) a1)))
15366 (error "Invalid change specifier: %s" change))
15367 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
15368 (cond
15369 ((eq dw 'day)
15370 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
15371 n2 (+ n1 dn)))
15372 ((eq dw 'year)
15373 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
15374 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
15375 (setq date1 (list m d y1)
15376 n1 (calendar-absolute-from-gregorian date1)
15377 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
15378 n2 (calendar-absolute-from-gregorian date2)))
15379 ((eq dw 'month)
15380 ;; approx number of month between the two dates
15381 (setq nmonths (floor (/ (- cday sday) 30.436875)))
15382 ;; How often does dn fit in there?
15383 (setq d (nth 1 start) m (car start) y (nth 2 start)
15384 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
15385 m (+ m nm)
15386 ny (floor (/ m 12))
15387 y (+ y ny)
15388 m (- m (* ny 12)))
15389 (while (> m 12) (setq m (- m 12) y (1+ y)))
15390 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
15391 (setq m2 (+ m dn) y2 y)
15392 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
15393 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
15394 (while (<= n2 cday)
15395 (setq n1 n2 m m2 y y2)
15396 (setq m2 (+ m dn) y2 y)
15397 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
15398 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
15399 ;; Make sure n1 is the earlier date
15400 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
15401 (if show-all
15402 (cond
15403 ((eq prefer 'past) (if (= cday n2) n2 n1))
15404 ((eq prefer 'future) (if (= cday n1) n1 n2))
15405 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
15406 (cond
15407 ((eq prefer 'past) (if (= cday n2) n2 n1))
15408 ((eq prefer 'future) (if (= cday n1) n1 n2))
15409 (t (if (= cday n1) n1 n2)))))))
15411 (defun org-date-to-gregorian (date)
15412 "Turn any specification of DATE into a Gregorian date for the calendar."
15413 (cond ((integerp date) (calendar-gregorian-from-absolute date))
15414 ((and (listp date) (= (length date) 3)) date)
15415 ((stringp date)
15416 (setq date (org-parse-time-string date))
15417 (list (nth 4 date) (nth 3 date) (nth 5 date)))
15418 ((listp date)
15419 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
15421 (defun org-parse-time-string (s &optional nodefault)
15422 "Parse the standard Org-mode time string.
15423 This should be a lot faster than the normal `parse-time-string'.
15424 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
15425 hour and minute fields will be nil if not given."
15426 (if (string-match org-ts-regexp0 s)
15427 (list 0
15428 (if (or (match-beginning 8) (not nodefault))
15429 (string-to-number (or (match-string 8 s) "0")))
15430 (if (or (match-beginning 7) (not nodefault))
15431 (string-to-number (or (match-string 7 s) "0")))
15432 (string-to-number (match-string 4 s))
15433 (string-to-number (match-string 3 s))
15434 (string-to-number (match-string 2 s))
15435 nil nil nil)
15436 (error "Not a standard Org-mode time string: %s" s)))
15438 (defun org-timestamp-up (&optional arg)
15439 "Increase the date item at the cursor by one.
15440 If the cursor is on the year, change the year. If it is on the month or
15441 the day, change that.
15442 With prefix ARG, change by that many units."
15443 (interactive "p")
15444 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
15446 (defun org-timestamp-down (&optional arg)
15447 "Decrease the date item at the cursor by one.
15448 If the cursor is on the year, change the year. If it is on the month or
15449 the day, change that.
15450 With prefix ARG, change by that many units."
15451 (interactive "p")
15452 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
15454 (defun org-timestamp-up-day (&optional arg)
15455 "Increase the date in the time stamp by one day.
15456 With prefix ARG, change that many days."
15457 (interactive "p")
15458 (if (and (not (org-at-timestamp-p t))
15459 (org-on-heading-p))
15460 (org-todo 'up)
15461 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
15463 (defun org-timestamp-down-day (&optional arg)
15464 "Decrease the date in the time stamp by one day.
15465 With prefix ARG, change that many days."
15466 (interactive "p")
15467 (if (and (not (org-at-timestamp-p t))
15468 (org-on-heading-p))
15469 (org-todo 'down)
15470 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
15472 (defun org-at-timestamp-p (&optional inactive-ok)
15473 "Determine if the cursor is in or at a timestamp."
15474 (interactive)
15475 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
15476 (pos (point))
15477 (ans (or (looking-at tsr)
15478 (save-excursion
15479 (skip-chars-backward "^[<\n\r\t")
15480 (if (> (point) (point-min)) (backward-char 1))
15481 (and (looking-at tsr)
15482 (> (- (match-end 0) pos) -1))))))
15483 (and ans
15484 (boundp 'org-ts-what)
15485 (setq org-ts-what
15486 (cond
15487 ((= pos (match-beginning 0)) 'bracket)
15488 ((= pos (1- (match-end 0))) 'bracket)
15489 ((org-pos-in-match-range pos 2) 'year)
15490 ((org-pos-in-match-range pos 3) 'month)
15491 ((org-pos-in-match-range pos 7) 'hour)
15492 ((org-pos-in-match-range pos 8) 'minute)
15493 ((or (org-pos-in-match-range pos 4)
15494 (org-pos-in-match-range pos 5)) 'day)
15495 ((and (> pos (or (match-end 8) (match-end 5)))
15496 (< pos (match-end 0)))
15497 (- pos (or (match-end 8) (match-end 5))))
15498 (t 'day))))
15499 ans))
15501 (defun org-toggle-timestamp-type ()
15502 "Toggle the type (<active> or [inactive]) of a time stamp."
15503 (interactive)
15504 (when (org-at-timestamp-p t)
15505 (let ((beg (match-beginning 0)) (end (match-end 0))
15506 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
15507 (save-excursion
15508 (goto-char beg)
15509 (while (re-search-forward "[][<>]" end t)
15510 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
15511 t t)))
15512 (message "Timestamp is now %sactive"
15513 (if (equal (char-after beg) ?<) "" "in")))))
15515 (defun org-timestamp-change (n &optional what updown)
15516 "Change the date in the time stamp at point.
15517 The date will be changed by N times WHAT. WHAT can be `day', `month',
15518 `year', `minute', `second'. If WHAT is not given, the cursor position
15519 in the timestamp determines what will be changed."
15520 (let ((pos (point))
15521 with-hm inactive
15522 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
15523 org-ts-what
15524 extra rem
15525 ts time time0)
15526 (if (not (org-at-timestamp-p t))
15527 (error "Not at a timestamp"))
15528 (if (and (not what) (eq org-ts-what 'bracket))
15529 (org-toggle-timestamp-type)
15530 (if (and (not what) (not (eq org-ts-what 'day))
15531 org-display-custom-times
15532 (get-text-property (point) 'display)
15533 (not (get-text-property (1- (point)) 'display)))
15534 (setq org-ts-what 'day))
15535 (setq org-ts-what (or what org-ts-what)
15536 inactive (= (char-after (match-beginning 0)) ?\[)
15537 ts (match-string 0))
15538 (replace-match "")
15539 (if (string-match
15540 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)*\\)[]>]"
15542 (setq extra (match-string 1 ts)))
15543 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
15544 (setq with-hm t))
15545 (setq time0 (org-parse-time-string ts))
15546 (when (and updown
15547 (eq org-ts-what 'minute)
15548 (not current-prefix-arg))
15549 ;; This looks like s-up and s-down. Change by one rounding step.
15550 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
15551 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
15552 (setcar (cdr time0) (+ (nth 1 time0)
15553 (if (> n 0) (- rem) (- dm rem))))))
15554 (setq time
15555 (encode-time (or (car time0) 0)
15556 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
15557 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
15558 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
15559 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
15560 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
15561 (nthcdr 6 time0)))
15562 (when (and (member org-ts-what '(hour minute))
15563 extra
15564 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
15565 (setq extra (org-modify-ts-extra
15566 extra
15567 (if (eq org-ts-what 'hour) 2 5)
15568 n dm)))
15569 (when (integerp org-ts-what)
15570 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
15571 (if (eq what 'calendar)
15572 (let ((cal-date (org-get-date-from-calendar)))
15573 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
15574 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
15575 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
15576 (setcar time0 (or (car time0) 0))
15577 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
15578 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
15579 (setq time (apply 'encode-time time0))))
15580 (setq org-last-changed-timestamp
15581 (org-insert-time-stamp time with-hm inactive nil nil extra))
15582 (org-clock-update-time-maybe)
15583 (goto-char pos)
15584 ;; Try to recenter the calendar window, if any
15585 (if (and org-calendar-follow-timestamp-change
15586 (get-buffer-window "*Calendar*" t)
15587 (memq org-ts-what '(day month year)))
15588 (org-recenter-calendar (time-to-days time))))))
15590 (defun org-modify-ts-extra (s pos n dm)
15591 "Change the different parts of the lead-time and repeat fields in timestamp."
15592 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
15593 ng h m new rem)
15594 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
15595 (cond
15596 ((or (org-pos-in-match-range pos 2)
15597 (org-pos-in-match-range pos 3))
15598 (setq m (string-to-number (match-string 3 s))
15599 h (string-to-number (match-string 2 s)))
15600 (if (org-pos-in-match-range pos 2)
15601 (setq h (+ h n))
15602 (setq n (* dm (org-no-warnings (signum n))))
15603 (when (not (= 0 (setq rem (% m dm))))
15604 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
15605 (setq m (+ m n)))
15606 (if (< m 0) (setq m (+ m 60) h (1- h)))
15607 (if (> m 59) (setq m (- m 60) h (1+ h)))
15608 (setq h (min 24 (max 0 h)))
15609 (setq ng 1 new (format "-%02d:%02d" h m)))
15610 ((org-pos-in-match-range pos 6)
15611 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
15612 ((org-pos-in-match-range pos 5)
15613 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
15615 ((org-pos-in-match-range pos 9)
15616 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
15617 ((org-pos-in-match-range pos 8)
15618 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
15620 (when ng
15621 (setq s (concat
15622 (substring s 0 (match-beginning ng))
15624 (substring s (match-end ng))))))
15627 (defun org-recenter-calendar (date)
15628 "If the calendar is visible, recenter it to DATE."
15629 (let* ((win (selected-window))
15630 (cwin (get-buffer-window "*Calendar*" t))
15631 (calendar-move-hook nil))
15632 (when cwin
15633 (select-window cwin)
15634 (calendar-goto-date (if (listp date) date
15635 (calendar-gregorian-from-absolute date)))
15636 (select-window win))))
15638 (defun org-goto-calendar (&optional arg)
15639 "Go to the Emacs calendar at the current date.
15640 If there is a time stamp in the current line, go to that date.
15641 A prefix ARG can be used to force the current date."
15642 (interactive "P")
15643 (let ((tsr org-ts-regexp) diff
15644 (calendar-move-hook nil)
15645 (calendar-view-holidays-initially-flag nil)
15646 (calendar-view-diary-initially-flag nil))
15647 (if (or (org-at-timestamp-p)
15648 (save-excursion
15649 (beginning-of-line 1)
15650 (looking-at (concat ".*" tsr))))
15651 (let ((d1 (time-to-days (current-time)))
15652 (d2 (time-to-days
15653 (org-time-string-to-time (match-string 1)))))
15654 (setq diff (- d2 d1))))
15655 (calendar)
15656 (calendar-goto-today)
15657 (if (and diff (not arg)) (calendar-forward-day diff))))
15659 (defun org-get-date-from-calendar ()
15660 "Return a list (month day year) of date at point in calendar."
15661 (with-current-buffer "*Calendar*"
15662 (save-match-data
15663 (calendar-cursor-to-date))))
15665 (defun org-date-from-calendar ()
15666 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
15667 If there is already a time stamp at the cursor position, update it."
15668 (interactive)
15669 (if (org-at-timestamp-p t)
15670 (org-timestamp-change 0 'calendar)
15671 (let ((cal-date (org-get-date-from-calendar)))
15672 (org-insert-time-stamp
15673 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
15675 (defun org-minutes-to-hh:mm-string (m)
15676 "Compute H:MM from a number of minutes."
15677 (let ((h (/ m 60)))
15678 (setq m (- m (* 60 h)))
15679 (format org-time-clocksum-format h m)))
15681 (defun org-hh:mm-string-to-minutes (s)
15682 "Convert a string H:MM to a number of minutes.
15683 If the string is just a number, interpret it as minutes.
15684 In fact, the first hh:mm or number in the string will be taken,
15685 there can be extra stuff in the string.
15686 If no number is found, the return value is 0."
15687 (cond
15688 ((integerp s) s)
15689 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
15690 (+ (* (string-to-number (match-string 1 s)) 60)
15691 (string-to-number (match-string 2 s))))
15692 ((string-match "\\([0-9]+\\)" s)
15693 (string-to-number (match-string 1 s)))
15694 (t 0)))
15696 (defcustom org-effort-durations
15697 `(("h" . 60)
15698 ("d" . ,(* 60 8))
15699 ("w" . ,(* 60 8 5))
15700 ("m" . ,(* 60 8 5 4))
15701 ("y" . ,(* 60 8 5 40)))
15702 "Conversion factor to minutes for an effort modifier.
15704 Each entry has the form (MODIFIER . MINUTES).
15706 In an effort string, a number followed by MODIFIER is multiplied
15707 by the specified number of MINUTES to obtain an effort in
15708 minutes.
15710 For example, if the value of this variable is ((\"hours\" . 60)), then an
15711 effort string \"2hours\" is equivalent to 120 minutes."
15712 :group 'org-agenda
15713 :type '(alist :key-type (string :tag "Modifier")
15714 :value-type (number :tag "Minutes")))
15716 (defun org-duration-string-to-minutes (s)
15717 "Convert a duration string S to minutes.
15719 A bare number is interpreted as minutes, modifiers can be set by
15720 customizing `org-effort-durations' (which see).
15722 Entries containing a colon are interpreted as H:MM by
15723 `org-hh:mm-string-to-minutes'."
15724 (let ((result 0)
15725 (re (concat "\\([0-9]+\\) *\\("
15726 (regexp-opt (mapcar 'car org-effort-durations))
15727 "\\)")))
15728 (while (string-match re s)
15729 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
15730 (string-to-number (match-string 1 s))))
15731 (setq s (replace-match "" nil t s)))
15732 (incf result (org-hh:mm-string-to-minutes s))
15733 result))
15735 ;;;; Files
15737 (defun org-save-all-org-buffers ()
15738 "Save all Org-mode buffers without user confirmation."
15739 (interactive)
15740 (message "Saving all Org-mode buffers...")
15741 (save-some-buffers t 'org-mode-p)
15742 (when (featurep 'org-id) (org-id-locations-save))
15743 (message "Saving all Org-mode buffers... done"))
15745 (defun org-revert-all-org-buffers ()
15746 "Revert all Org-mode buffers.
15747 Prompt for confirmation when there are unsaved changes.
15748 Be sure you know what you are doing before letting this function
15749 overwrite your changes.
15751 This function is useful in a setup where one tracks org files
15752 with a version control system, to revert on one machine after pulling
15753 changes from another. I believe the procedure must be like this:
15755 1. M-x org-save-all-org-buffers
15756 2. Pull changes from the other machine, resolve conflicts
15757 3. M-x org-revert-all-org-buffers"
15758 (interactive)
15759 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
15760 (error "Abort"))
15761 (save-excursion
15762 (save-window-excursion
15763 (mapc
15764 (lambda (b)
15765 (when (and (with-current-buffer b (org-mode-p))
15766 (with-current-buffer b buffer-file-name))
15767 (switch-to-buffer b)
15768 (revert-buffer t 'no-confirm)))
15769 (buffer-list))
15770 (when (and (featurep 'org-id) org-id-track-globally)
15771 (org-id-locations-load)))))
15773 ;;;; Agenda files
15775 ;;;###autoload
15776 (defun org-switchb (&optional arg)
15777 "Switch between Org buffers.
15778 With a prefix argument, restrict available to files.
15779 With two prefix arguments, restrict available buffers to agenda files.
15781 Defaults to `iswitchb' for buffer name completion.
15782 Set `org-completion-use-ido' to make it use ido instead."
15783 (interactive "P")
15784 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
15785 ((equal arg '(16)) (org-buffer-list 'agenda))
15786 (t (org-buffer-list))))
15787 (org-completion-use-iswitchb org-completion-use-iswitchb)
15788 (org-completion-use-ido org-completion-use-ido))
15789 (unless (or org-completion-use-ido org-completion-use-iswitchb)
15790 (setq org-completion-use-iswitchb t))
15791 (switch-to-buffer
15792 (org-icompleting-read "Org buffer: "
15793 (mapcar 'list (mapcar 'buffer-name blist))
15794 nil t))))
15796 ;;; Define some older names previously used for this functionality
15797 ;;;###autoload
15798 (defalias 'org-ido-switchb 'org-switchb)
15799 ;;;###autoload
15800 (defalias 'org-iswitchb 'org-switchb)
15802 (defun org-buffer-list (&optional predicate exclude-tmp)
15803 "Return a list of Org buffers.
15804 PREDICATE can be `export', `files' or `agenda'.
15806 export restrict the list to Export buffers.
15807 files restrict the list to buffers visiting Org files.
15808 agenda restrict the list to buffers visiting agenda files.
15810 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
15811 (let* ((bfn nil)
15812 (agenda-files (and (eq predicate 'agenda)
15813 (mapcar 'file-truename (org-agenda-files t))))
15814 (filter
15815 (cond
15816 ((eq predicate 'files)
15817 (lambda (b) (with-current-buffer b (org-mode-p))))
15818 ((eq predicate 'export)
15819 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
15820 ((eq predicate 'agenda)
15821 (lambda (b)
15822 (with-current-buffer b
15823 (and (org-mode-p)
15824 (setq bfn (buffer-file-name b))
15825 (member (file-truename bfn) agenda-files)))))
15826 (t (lambda (b) (with-current-buffer b
15827 (or (org-mode-p)
15828 (string-match "\*Org .*Export"
15829 (buffer-name b)))))))))
15830 (delq nil
15831 (mapcar
15832 (lambda(b)
15833 (if (and (funcall filter b)
15834 (or (not exclude-tmp)
15835 (not (string-match "tmp" (buffer-name b)))))
15837 nil))
15838 (buffer-list)))))
15840 (defun org-agenda-files (&optional unrestricted archives)
15841 "Get the list of agenda files.
15842 Optional UNRESTRICTED means return the full list even if a restriction
15843 is currently in place.
15844 When ARCHIVES is t, include all archive files that are really being
15845 used by the agenda files. If ARCHIVE is `ifmode', do this only if
15846 `org-agenda-archives-mode' is t."
15847 (let ((files
15848 (cond
15849 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
15850 ((stringp org-agenda-files) (org-read-agenda-file-list))
15851 ((listp org-agenda-files) org-agenda-files)
15852 (t (error "Invalid value of `org-agenda-files'")))))
15853 (setq files (apply 'append
15854 (mapcar (lambda (f)
15855 (if (file-directory-p f)
15856 (directory-files
15857 f t org-agenda-file-regexp)
15858 (list f)))
15859 files)))
15860 (when org-agenda-skip-unavailable-files
15861 (setq files (delq nil
15862 (mapcar (function
15863 (lambda (file)
15864 (and (file-readable-p file) file)))
15865 files))))
15866 (when (or (eq archives t)
15867 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
15868 (setq files (org-add-archive-files files)))
15869 files))
15871 (defun org-agenda-file-p (&optional file)
15872 "Return non-nil, if FILE is an agenda file.
15873 If FILE is omitted, use the file associated with the current
15874 buffer."
15875 (member (or file (buffer-file-name))
15876 (org-agenda-files t)))
15878 (defun org-edit-agenda-file-list ()
15879 "Edit the list of agenda files.
15880 Depending on setup, this either uses customize to edit the variable
15881 `org-agenda-files', or it visits the file that is holding the list. In the
15882 latter case, the buffer is set up in a way that saving it automatically kills
15883 the buffer and restores the previous window configuration."
15884 (interactive)
15885 (if (stringp org-agenda-files)
15886 (let ((cw (current-window-configuration)))
15887 (find-file org-agenda-files)
15888 (org-set-local 'org-window-configuration cw)
15889 (org-add-hook 'after-save-hook
15890 (lambda ()
15891 (set-window-configuration
15892 (prog1 org-window-configuration
15893 (kill-buffer (current-buffer))))
15894 (org-install-agenda-files-menu)
15895 (message "New agenda file list installed"))
15896 nil 'local)
15897 (message "%s" (substitute-command-keys
15898 "Edit list and finish with \\[save-buffer]")))
15899 (customize-variable 'org-agenda-files)))
15901 (defun org-store-new-agenda-file-list (list)
15902 "Set new value for the agenda file list and save it correctly."
15903 (if (stringp org-agenda-files)
15904 (let ((fe (org-read-agenda-file-list t)) b u)
15905 (while (setq b (find-buffer-visiting org-agenda-files))
15906 (kill-buffer b))
15907 (with-temp-file org-agenda-files
15908 (insert
15909 (mapconcat
15910 (lambda (f) ;; Keep un-expanded entries.
15911 (if (setq u (assoc f fe))
15912 (cdr u)
15914 list "\n")
15915 "\n")))
15916 (let ((org-mode-hook nil) (org-inhibit-startup t)
15917 (org-insert-mode-line-in-empty-file nil))
15918 (setq org-agenda-files list)
15919 (customize-save-variable 'org-agenda-files org-agenda-files))))
15921 (defun org-read-agenda-file-list (&optional pair-with-expansion)
15922 "Read the list of agenda files from a file.
15923 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
15924 filenames, used by `org-store-new-agenda-file-list' to write back
15925 un-expanded file names."
15926 (when (file-directory-p org-agenda-files)
15927 (error "`org-agenda-files' cannot be a single directory"))
15928 (when (stringp org-agenda-files)
15929 (with-temp-buffer
15930 (insert-file-contents org-agenda-files)
15931 (mapcar
15932 (lambda (f)
15933 (let ((e (expand-file-name (substitute-in-file-name f)
15934 org-directory)))
15935 (if pair-with-expansion
15936 (cons e f)
15937 e)))
15938 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
15940 ;;;###autoload
15941 (defun org-cycle-agenda-files ()
15942 "Cycle through the files in `org-agenda-files'.
15943 If the current buffer visits an agenda file, find the next one in the list.
15944 If the current buffer does not, find the first agenda file."
15945 (interactive)
15946 (let* ((fs (org-agenda-files t))
15947 (files (append fs (list (car fs))))
15948 (tcf (if buffer-file-name (file-truename buffer-file-name)))
15949 file)
15950 (unless files (error "No agenda files"))
15951 (catch 'exit
15952 (while (setq file (pop files))
15953 (if (equal (file-truename file) tcf)
15954 (when (car files)
15955 (find-file (car files))
15956 (throw 'exit t))))
15957 (find-file (car fs)))
15958 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
15960 (defun org-agenda-file-to-front (&optional to-end)
15961 "Move/add the current file to the top of the agenda file list.
15962 If the file is not present in the list, it is added to the front. If it is
15963 present, it is moved there. With optional argument TO-END, add/move to the
15964 end of the list."
15965 (interactive "P")
15966 (let ((org-agenda-skip-unavailable-files nil)
15967 (file-alist (mapcar (lambda (x)
15968 (cons (file-truename x) x))
15969 (org-agenda-files t)))
15970 (ctf (file-truename buffer-file-name))
15971 x had)
15972 (setq x (assoc ctf file-alist) had x)
15974 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
15975 (if to-end
15976 (setq file-alist (append (delq x file-alist) (list x)))
15977 (setq file-alist (cons x (delq x file-alist))))
15978 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
15979 (org-install-agenda-files-menu)
15980 (message "File %s to %s of agenda file list"
15981 (if had "moved" "added") (if to-end "end" "front"))))
15983 (defun org-remove-file (&optional file)
15984 "Remove current file from the list of files in variable `org-agenda-files'.
15985 These are the files which are being checked for agenda entries.
15986 Optional argument FILE means use this file instead of the current."
15987 (interactive)
15988 (let* ((org-agenda-skip-unavailable-files nil)
15989 (file (or file buffer-file-name))
15990 (true-file (file-truename file))
15991 (afile (abbreviate-file-name file))
15992 (files (delq nil (mapcar
15993 (lambda (x)
15994 (if (equal true-file
15995 (file-truename x))
15996 nil x))
15997 (org-agenda-files t)))))
15998 (if (not (= (length files) (length (org-agenda-files t))))
15999 (progn
16000 (org-store-new-agenda-file-list files)
16001 (org-install-agenda-files-menu)
16002 (message "Removed file: %s" afile))
16003 (message "File was not in list: %s (not removed)" afile))))
16005 (defun org-file-menu-entry (file)
16006 (vector file (list 'find-file file) t))
16008 (defun org-check-agenda-file (file)
16009 "Make sure FILE exists. If not, ask user what to do."
16010 (when (not (file-exists-p file))
16011 (message "non-existent agenda file %s. [R]emove from list or [A]bort?"
16012 (abbreviate-file-name file))
16013 (let ((r (downcase (read-char-exclusive))))
16014 (cond
16015 ((equal r ?r)
16016 (org-remove-file file)
16017 (throw 'nextfile t))
16018 (t (error "Abort"))))))
16020 (defun org-get-agenda-file-buffer (file)
16021 "Get a buffer visiting FILE. If the buffer needs to be created, add
16022 it to the list of buffers which might be released later."
16023 (let ((buf (org-find-base-buffer-visiting file)))
16024 (if buf
16025 buf ; just return it
16026 ;; Make a new buffer and remember it
16027 (setq buf (find-file-noselect file))
16028 (if buf (push buf org-agenda-new-buffers))
16029 buf)))
16031 (defun org-release-buffers (blist)
16032 "Release all buffers in list, asking the user for confirmation when needed.
16033 When a buffer is unmodified, it is just killed. When modified, it is saved
16034 \(if the user agrees) and then killed."
16035 (let (buf file)
16036 (while (setq buf (pop blist))
16037 (setq file (buffer-file-name buf))
16038 (when (and (buffer-modified-p buf)
16039 file
16040 (y-or-n-p (format "Save file %s? " file)))
16041 (with-current-buffer buf (save-buffer)))
16042 (kill-buffer buf))))
16044 (defun org-prepare-agenda-buffers (files)
16045 "Create buffers for all agenda files, protect archived trees and comments."
16046 (interactive)
16047 (let ((pa '(:org-archived t))
16048 (pc '(:org-comment t))
16049 (pall '(:org-archived t :org-comment t))
16050 (inhibit-read-only t)
16051 (rea (concat ":" org-archive-tag ":"))
16052 bmp file re)
16053 (save-excursion
16054 (save-restriction
16055 (while (setq file (pop files))
16056 (catch 'nextfile
16057 (if (bufferp file)
16058 (set-buffer file)
16059 (org-check-agenda-file file)
16060 (set-buffer (org-get-agenda-file-buffer file)))
16061 (widen)
16062 (setq bmp (buffer-modified-p))
16063 (org-refresh-category-properties)
16064 (setq org-todo-keywords-for-agenda
16065 (append org-todo-keywords-for-agenda org-todo-keywords-1))
16066 (setq org-done-keywords-for-agenda
16067 (append org-done-keywords-for-agenda org-done-keywords))
16068 (setq org-todo-keyword-alist-for-agenda
16069 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
16070 (setq org-drawers-for-agenda
16071 (append org-drawers-for-agenda org-drawers))
16072 (setq org-tag-alist-for-agenda
16073 (append org-tag-alist-for-agenda org-tag-alist))
16075 (save-excursion
16076 (remove-text-properties (point-min) (point-max) pall)
16077 (when org-agenda-skip-archived-trees
16078 (goto-char (point-min))
16079 (while (re-search-forward rea nil t)
16080 (if (org-on-heading-p t)
16081 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
16082 (goto-char (point-min))
16083 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
16084 (while (re-search-forward re nil t)
16085 (add-text-properties
16086 (match-beginning 0) (org-end-of-subtree t) pc)))
16087 (set-buffer-modified-p bmp)))))
16088 (setq org-todo-keywords-for-agenda
16089 (org-uniquify org-todo-keywords-for-agenda))
16090 (setq org-todo-keyword-alist-for-agenda
16091 (org-uniquify org-todo-keyword-alist-for-agenda)
16092 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
16094 ;;;; Embedded LaTeX
16096 (defvar org-cdlatex-mode-map (make-sparse-keymap)
16097 "Keymap for the minor `org-cdlatex-mode'.")
16099 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
16100 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
16101 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
16102 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
16103 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
16105 (defvar org-cdlatex-texmathp-advice-is-done nil
16106 "Flag remembering if we have applied the advice to texmathp already.")
16108 (define-minor-mode org-cdlatex-mode
16109 "Toggle the minor `org-cdlatex-mode'.
16110 This mode supports entering LaTeX environment and math in LaTeX fragments
16111 in Org-mode.
16112 \\{org-cdlatex-mode-map}"
16113 nil " OCDL" nil
16114 (when org-cdlatex-mode (require 'cdlatex))
16115 (unless org-cdlatex-texmathp-advice-is-done
16116 (setq org-cdlatex-texmathp-advice-is-done t)
16117 (defadvice texmathp (around org-math-always-on activate)
16118 "Always return t in org-mode buffers.
16119 This is because we want to insert math symbols without dollars even outside
16120 the LaTeX math segments. If Orgmode thinks that point is actually inside
16121 an embedded LaTeX fragment, let texmathp do its job.
16122 \\[org-cdlatex-mode-map]"
16123 (interactive)
16124 (let (p)
16125 (cond
16126 ((not (org-mode-p)) ad-do-it)
16127 ((eq this-command 'cdlatex-math-symbol)
16128 (setq ad-return-value t
16129 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
16131 (let ((p (org-inside-LaTeX-fragment-p)))
16132 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
16133 (setq ad-return-value t
16134 texmathp-why '("Org-mode embedded math" . 0))
16135 (if p ad-do-it)))))))))
16137 (defun turn-on-org-cdlatex ()
16138 "Unconditionally turn on `org-cdlatex-mode'."
16139 (org-cdlatex-mode 1))
16141 (defun org-inside-LaTeX-fragment-p ()
16142 "Test if point is inside a LaTeX fragment.
16143 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
16144 sequence appearing also before point.
16145 Even though the matchers for math are configurable, this function assumes
16146 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
16147 delimiters are skipped when they have been removed by customization.
16148 The return value is nil, or a cons cell with the delimiter and the
16149 position of this delimiter.
16151 This function does a reasonably good job, but can locally be fooled by
16152 for example currency specifications. For example it will assume being in
16153 inline math after \"$22.34\". The LaTeX fragment formatter will only format
16154 fragments that are properly closed, but during editing, we have to live
16155 with the uncertainty caused by missing closing delimiters. This function
16156 looks only before point, not after."
16157 (catch 'exit
16158 (let ((pos (point))
16159 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
16160 (lim (progn
16161 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
16162 (point)))
16163 dd-on str (start 0) m re)
16164 (goto-char pos)
16165 (when dodollar
16166 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
16167 re (nth 1 (assoc "$" org-latex-regexps)))
16168 (while (string-match re str start)
16169 (cond
16170 ((= (match-end 0) (length str))
16171 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
16172 ((= (match-end 0) (- (length str) 5))
16173 (throw 'exit nil))
16174 (t (setq start (match-end 0))))))
16175 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
16176 (goto-char pos)
16177 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
16178 (and (match-beginning 2) (throw 'exit nil))
16179 ;; count $$
16180 (while (re-search-backward "\\$\\$" lim t)
16181 (setq dd-on (not dd-on)))
16182 (goto-char pos)
16183 (if dd-on (cons "$$" m))))))
16185 (defun org-inside-latex-macro-p ()
16186 "Is point inside a LaTeX macro or its arguments?"
16187 (save-match-data
16188 (org-in-regexp
16189 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
16191 (defun org-try-cdlatex-tab ()
16192 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
16193 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
16194 - inside a LaTeX fragment, or
16195 - after the first word in a line, where an abbreviation expansion could
16196 insert a LaTeX environment."
16197 (when org-cdlatex-mode
16198 (cond
16199 ((save-excursion
16200 (skip-chars-backward "a-zA-Z0-9*")
16201 (skip-chars-backward " \t")
16202 (bolp))
16203 (cdlatex-tab) t)
16204 ((org-inside-LaTeX-fragment-p)
16205 (cdlatex-tab) t)
16206 (t nil))))
16208 (defun org-cdlatex-underscore-caret (&optional arg)
16209 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
16210 Revert to the normal definition outside of these fragments."
16211 (interactive "P")
16212 (if (org-inside-LaTeX-fragment-p)
16213 (call-interactively 'cdlatex-sub-superscript)
16214 (let (org-cdlatex-mode)
16215 (call-interactively (key-binding (vector last-input-event))))))
16217 (defun org-cdlatex-math-modify (&optional arg)
16218 "Execute `cdlatex-math-modify' in LaTeX fragments.
16219 Revert to the normal definition outside of these fragments."
16220 (interactive "P")
16221 (if (org-inside-LaTeX-fragment-p)
16222 (call-interactively 'cdlatex-math-modify)
16223 (let (org-cdlatex-mode)
16224 (call-interactively (key-binding (vector last-input-event))))))
16226 (defvar org-latex-fragment-image-overlays nil
16227 "List of overlays carrying the images of latex fragments.")
16228 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
16230 (defun org-remove-latex-fragment-image-overlays ()
16231 "Remove all overlays with LaTeX fragment images in current buffer."
16232 (mapc 'delete-overlay org-latex-fragment-image-overlays)
16233 (setq org-latex-fragment-image-overlays nil))
16235 (defun org-preview-latex-fragment (&optional subtree)
16236 "Preview the LaTeX fragment at point, or all locally or globally.
16237 If the cursor is in a LaTeX fragment, create the image and overlay
16238 it over the source code. If there is no fragment at point, display
16239 all fragments in the current text, from one headline to the next. With
16240 prefix SUBTREE, display all fragments in the current subtree. With a
16241 double prefix arg \\[universal-argument] \\[universal-argument], or when \
16242 the cursor is before the first headline,
16243 display all fragments in the buffer.
16244 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
16245 (interactive "P")
16246 (org-remove-latex-fragment-image-overlays)
16247 (save-excursion
16248 (save-restriction
16249 (let (beg end at msg)
16250 (cond
16251 ((or (equal subtree '(16))
16252 (not (save-excursion
16253 (re-search-backward (concat "^" outline-regexp) nil t))))
16254 (setq beg (point-min) end (point-max)
16255 msg "Creating images for buffer...%s"))
16256 ((equal subtree '(4))
16257 (org-back-to-heading)
16258 (setq beg (point) end (org-end-of-subtree t)
16259 msg "Creating images for subtree...%s"))
16261 (if (setq at (org-inside-LaTeX-fragment-p))
16262 (goto-char (max (point-min) (- (cdr at) 2)))
16263 (org-back-to-heading))
16264 (setq beg (point) end (progn (outline-next-heading) (point))
16265 msg (if at "Creating image...%s"
16266 "Creating images for entry...%s"))))
16267 (message msg "")
16268 (narrow-to-region beg end)
16269 (goto-char beg)
16270 (org-format-latex
16271 (concat "ltxpng/" (file-name-sans-extension
16272 (file-name-nondirectory
16273 buffer-file-name)))
16274 default-directory 'overlays msg at 'forbuffer 'dvipng)
16275 (message msg "done. Use `C-c C-c' to remove images.")))))
16277 (defvar org-latex-regexps
16278 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
16279 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
16280 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
16281 ("$1" "\\([^$]\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
16282 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
16283 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
16284 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
16285 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
16286 "Regular expressions for matching embedded LaTeX.")
16288 (defvar org-export-have-math nil) ;; dynamic scoping
16289 (defun org-format-latex (prefix &optional dir overlays msg at
16290 forbuffer processing-type)
16291 "Replace LaTeX fragments with links to an image, and produce images.
16292 Some of the options can be changed using the variable
16293 `org-format-latex-options'."
16294 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
16295 (let* ((prefixnodir (file-name-nondirectory prefix))
16296 (absprefix (expand-file-name prefix dir))
16297 (todir (file-name-directory absprefix))
16298 (opt org-format-latex-options)
16299 (matchers (plist-get opt :matchers))
16300 (re-list org-latex-regexps)
16301 (org-format-latex-header-extra
16302 (plist-get (org-infile-export-plist) :latex-header-extra))
16303 (cnt 0) txt hash link beg end re e checkdir
16304 executables-checked string
16305 m n block linkfile movefile ov)
16306 ;; Check the different regular expressions
16307 (while (setq e (pop re-list))
16308 (setq m (car e) re (nth 1 e) n (nth 2 e)
16309 block (if (nth 3 e) "\n\n" ""))
16310 (when (member m matchers)
16311 (goto-char (point-min))
16312 (while (re-search-forward re nil t)
16313 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
16314 (not (get-text-property (match-beginning n)
16315 'org-protected))
16316 (or (not overlays)
16317 (not (eq (get-char-property (match-beginning n)
16318 'org-overlay-type)
16319 'org-latex-overlay))))
16320 (setq org-export-have-math t)
16321 (cond
16322 ((eq processing-type 'verbatim)
16323 ;; Leave the text verbatim, just protect it
16324 (add-text-properties (match-beginning n) (match-end n)
16325 '(org-protected t)))
16326 ((eq processing-type 'mathjax)
16327 ;; Prepare for MathJax processing
16328 (setq string (match-string n))
16329 (if (member m '("$" "$1"))
16330 (save-excursion
16331 (delete-region (match-beginning n) (match-end n))
16332 (goto-char (match-beginning n))
16333 (insert (org-add-props (concat "\\(" (substring string 1 -1)
16334 "\\)")
16335 '(org-protected t))))
16336 (add-text-properties (match-beginning n) (match-end n)
16337 '(org-protected t))))
16338 ((or (eq processing-type 'dvipng) t)
16339 ;; Process to an image
16340 (setq txt (match-string n)
16341 beg (match-beginning n) end (match-end n)
16342 cnt (1+ cnt))
16343 (let (print-length print-level) ; make sure full list is printed
16344 (setq hash (sha1 (prin1-to-string
16345 (list org-format-latex-header
16346 org-format-latex-header-extra
16347 org-export-latex-default-packages-alist
16348 org-export-latex-packages-alist
16349 org-format-latex-options
16350 forbuffer txt)))
16351 linkfile (format "%s_%s.png" prefix hash)
16352 movefile (format "%s_%s.png" absprefix hash)))
16353 (setq link (concat block "[[file:" linkfile "]]" block))
16354 (if msg (message msg cnt))
16355 (goto-char beg)
16356 (unless checkdir ; make sure the directory exists
16357 (setq checkdir t)
16358 (or (file-directory-p todir) (make-directory todir t)))
16360 (unless executables-checked
16361 (org-check-external-command
16362 "latex" "needed to convert LaTeX fragments to images")
16363 (org-check-external-command
16364 "dvipng" "needed to convert LaTeX fragments to images")
16365 (setq executables-checked t))
16367 (unless (file-exists-p movefile)
16368 (org-create-formula-image
16369 txt movefile opt forbuffer))
16370 (if overlays
16371 (progn
16372 (mapc (lambda (o)
16373 (if (eq (overlay-get o 'org-overlay-type)
16374 'org-latex-overlay)
16375 (delete-overlay o)))
16376 (overlays-in beg end))
16377 (setq ov (make-overlay beg end))
16378 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
16379 (if (featurep 'xemacs)
16380 (progn
16381 (overlay-put ov 'invisible t)
16382 (overlay-put
16383 ov 'end-glyph
16384 (make-glyph (vector 'png :file movefile))))
16385 (overlay-put
16386 ov 'display
16387 (list 'image :type 'png :file movefile :ascent 'center)))
16388 (push ov org-latex-fragment-image-overlays)
16389 (goto-char end))
16390 (delete-region beg end)
16391 (insert (org-add-props link
16392 (list 'org-latex-src
16393 (replace-regexp-in-string
16394 "\"" "" txt)))))))))))))
16396 ;; This function borrows from Ganesh Swami's latex2png.el
16397 (defun org-create-formula-image (string tofile options buffer)
16398 "This calls dvipng."
16399 (require 'org-latex)
16400 (let* ((tmpdir (if (featurep 'xemacs)
16401 (temp-directory)
16402 temporary-file-directory))
16403 (texfilebase (make-temp-name
16404 (expand-file-name "orgtex" tmpdir)))
16405 (texfile (concat texfilebase ".tex"))
16406 (dvifile (concat texfilebase ".dvi"))
16407 (pngfile (concat texfilebase ".png"))
16408 (fnh (if (featurep 'xemacs)
16409 (font-height (get-face-font 'default))
16410 (face-attribute 'default :height nil)))
16411 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
16412 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
16413 (fg (or (plist-get options (if buffer :foreground :html-foreground))
16414 "Black"))
16415 (bg (or (plist-get options (if buffer :background :html-background))
16416 "Transparent")))
16417 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
16418 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
16419 (with-temp-file texfile
16420 (insert (org-splice-latex-header
16421 org-format-latex-header
16422 org-export-latex-default-packages-alist
16423 org-export-latex-packages-alist t
16424 org-format-latex-header-extra))
16425 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")
16426 (require 'org-latex)
16427 (org-export-latex-fix-inputenc))
16428 (let ((dir default-directory))
16429 (condition-case nil
16430 (progn
16431 (cd tmpdir)
16432 (call-process "latex" nil nil nil texfile))
16433 (error nil))
16434 (cd dir))
16435 (if (not (file-exists-p dvifile))
16436 (progn (message "Failed to create dvi file from %s" texfile) nil)
16437 (condition-case nil
16438 (call-process "dvipng" nil nil nil
16439 "-fg" fg "-bg" bg
16440 "-D" dpi
16441 ;;"-x" scale "-y" scale
16442 "-T" "tight"
16443 "-o" pngfile
16444 dvifile)
16445 (error nil))
16446 (if (not (file-exists-p pngfile))
16447 (if org-format-latex-signal-error
16448 (error "Failed to create png file from %s" texfile)
16449 (message "Failed to create png file from %s" texfile)
16450 nil)
16451 ;; Use the requested file name and clean up
16452 (copy-file pngfile tofile 'replace)
16453 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
16454 (delete-file (concat texfilebase e)))
16455 pngfile))))
16457 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
16458 "Fill a LaTeX header template TPL.
16459 In the template, the following place holders will be recognized:
16461 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
16462 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
16463 [PACKAGES] \\usepackage statements for PKG
16464 [NO-PACKAGES] do not include PKG
16465 [EXTRA] the string EXTRA
16466 [NO-EXTRA] do not include EXTRA
16468 For backward compatibility, if both the positive and the negative place
16469 holder is missing, the positive one (without the \"NO-\") will be
16470 assumed to be present at the end of the template.
16471 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
16472 EXTRA is a string.
16473 SNIPPETS-P indicates if this is run to create snippet images for HTML."
16474 (let (rpl (end ""))
16475 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
16476 (setq rpl (if (or (match-end 1) (not def-pkg))
16477 "" (org-latex-packages-to-string def-pkg snippets-p t))
16478 tpl (replace-match rpl t t tpl))
16479 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
16481 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
16482 (setq rpl (if (or (match-end 1) (not pkg))
16483 "" (org-latex-packages-to-string pkg snippets-p t))
16484 tpl (replace-match rpl t t tpl))
16485 (if pkg (setq end
16486 (concat end "\n"
16487 (org-latex-packages-to-string pkg snippets-p)))))
16489 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
16490 (setq rpl (if (or (match-end 1) (not extra))
16491 "" (concat extra "\n"))
16492 tpl (replace-match rpl t t tpl))
16493 (if (and extra (string-match "\\S-" extra))
16494 (setq end (concat end "\n" extra))))
16496 (if (string-match "\\S-" end)
16497 (concat tpl "\n" end)
16498 tpl)))
16500 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
16501 "Turn an alist of packages into a string with the \\usepackage macros."
16502 (setq pkg (mapconcat (lambda(p)
16503 (cond
16504 ((stringp p) p)
16505 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
16506 (format "%% Package %s omitted" (cadr p)))
16507 ((equal "" (car p))
16508 (format "\\usepackage{%s}" (cadr p)))
16510 (format "\\usepackage[%s]{%s}"
16511 (car p) (cadr p)))))
16513 "\n"))
16514 (if newline (concat pkg "\n") pkg))
16516 (defun org-dvipng-color (attr)
16517 "Return an rgb color specification for dvipng."
16518 (apply 'format "rgb %s %s %s"
16519 (mapcar 'org-normalize-color
16520 (color-values (face-attribute 'default attr nil)))))
16522 (defun org-normalize-color (value)
16523 "Return string to be used as color value for an RGB component."
16524 (format "%g" (/ value 65535.0)))
16526 ;; Image display
16529 (defvar org-inline-image-overlays nil)
16530 (make-variable-buffer-local 'org-inline-image-overlays)
16532 (defun org-toggle-inline-images (&optional include-linked)
16533 "Toggle the display of inline images.
16534 INCLUDE-LINKED is passed to `org-display-inline-images'."
16535 (interactive "P")
16536 (if org-inline-image-overlays
16537 (progn
16538 (org-remove-inline-images)
16539 (message "Inline image display turned off"))
16540 (org-display-inline-images include-linked)
16541 (if org-inline-image-overlays
16542 (message "%d images displayed inline"
16543 (length org-inline-image-overlays))
16544 (message "No images to display inline"))))
16546 (defun org-display-inline-images (&optional include-linked refresh beg end)
16547 "Display inline images.
16548 Normally only links without a description part are inlined, because this
16549 is how it will work for export. When INCLUDE-LINKED is set, also links
16550 with a description part will be inlined. This can be nice for a quick
16551 look at those images, but it does not reflect what exported files will look
16552 like.
16553 When REFRESH is set, refresh existing images between BEG and END.
16554 This will create new image displays only if necessary.
16555 BEG and END default to the buffer boundaries."
16556 (interactive "P")
16557 (unless refresh
16558 (org-remove-inline-images)
16559 (if (fboundp 'clear-image-cache) (clear-image-cache)))
16560 (save-excursion
16561 (save-restriction
16562 (widen)
16563 (setq beg (or beg (point-min)) end (or end (point-max)))
16564 (goto-char (point-min))
16565 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
16566 (substring (org-image-file-name-regexp) 0 -2)
16567 "\\)\\]" (if include-linked "" "\\]")))
16568 old file ov img)
16569 (while (re-search-forward re end t)
16570 (setq old (get-char-property-and-overlay (match-beginning 1)
16571 'org-image-overlay))
16572 (setq file (expand-file-name
16573 (concat (or (match-string 3) "") (match-string 4))))
16574 (when (file-exists-p file)
16575 (if (and (car-safe old) refresh)
16576 (image-refresh (overlay-get (cdr old) 'display))
16577 (setq img (save-match-data (create-image file)))
16578 (when img
16579 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
16580 (overlay-put ov 'display img)
16581 (overlay-put ov 'face 'default)
16582 (overlay-put ov 'org-image-overlay t)
16583 (overlay-put ov 'modification-hooks
16584 (list 'org-display-inline-modification-hook))
16585 (push ov org-inline-image-overlays)))))))))
16587 (defun org-display-inline-modification-hook (ov after beg end &optional len)
16588 "Remove inline-display overlay if a corresponding region is modified."
16589 (let ((inhibit-modification-hooks t))
16590 (when (and ov after)
16591 (delete ov org-inline-image-overlays)
16592 (delete-overlay ov))))
16594 (defun org-remove-inline-images ()
16595 "Remove inline display of images."
16596 (interactive)
16597 (mapc 'delete-overlay org-inline-image-overlays)
16598 (setq org-inline-image-overlays nil))
16600 ;;;; Key bindings
16602 ;; Make `C-c C-x' a prefix key
16603 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
16605 ;; TAB key with modifiers
16606 (org-defkey org-mode-map "\C-i" 'org-cycle)
16607 (org-defkey org-mode-map [(tab)] 'org-cycle)
16608 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
16609 (org-defkey org-mode-map [(meta tab)] 'pcomplete)
16610 (org-defkey org-mode-map "\M-\t" 'pcomplete)
16611 (org-defkey org-mode-map "\M-\C-i" 'pcomplete)
16612 ;; The following line is necessary under Suse GNU/Linux
16613 (unless (featurep 'xemacs)
16614 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
16615 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
16616 (define-key org-mode-map [backtab] 'org-shifttab)
16618 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
16619 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
16620 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
16622 ;; Cursor keys with modifiers
16623 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
16624 (org-defkey org-mode-map [(meta right)] 'org-metaright)
16625 (org-defkey org-mode-map [(meta up)] 'org-metaup)
16626 (org-defkey org-mode-map [(meta down)] 'org-metadown)
16628 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
16629 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
16630 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
16631 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
16633 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
16634 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
16635 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
16636 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
16638 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
16639 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
16641 ;; Babel keys
16642 (define-key org-mode-map org-babel-key-prefix org-babel-map)
16643 (mapc (lambda (pair)
16644 (define-key org-babel-map (car pair) (cdr pair)))
16645 org-babel-key-bindings)
16647 ;;; Extra keys for tty access.
16648 ;; We only set them when really needed because otherwise the
16649 ;; menus don't show the simple keys
16651 (when (or org-use-extra-keys
16652 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
16653 (not window-system))
16654 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
16655 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
16656 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
16657 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
16658 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
16659 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
16660 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
16661 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
16662 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
16663 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
16664 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
16665 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
16666 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
16667 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
16668 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
16669 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
16670 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
16671 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
16672 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
16673 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
16674 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
16675 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
16676 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
16677 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
16678 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
16679 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
16680 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
16681 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
16683 ;; All the other keys
16685 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
16686 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
16687 (if (boundp 'narrow-map)
16688 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
16689 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
16690 (if (boundp 'narrow-map)
16691 (org-defkey narrow-map "b" 'org-narrow-to-block)
16692 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
16693 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-same-level)
16694 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-same-level)
16695 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
16696 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
16697 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
16698 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
16699 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
16700 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
16701 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
16702 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
16703 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
16704 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
16705 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
16706 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
16707 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
16708 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
16709 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
16710 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
16711 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
16712 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
16713 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
16714 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
16715 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
16716 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
16717 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
16718 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
16719 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
16720 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
16721 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
16722 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
16723 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
16724 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
16725 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
16726 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
16727 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
16728 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
16729 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
16730 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
16731 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
16732 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
16733 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
16734 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
16735 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
16736 (org-defkey org-mode-map "\C-c^" 'org-sort)
16737 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
16738 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
16739 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
16740 (org-defkey org-mode-map "\C-m" 'org-return)
16741 (org-defkey org-mode-map "\C-j" 'org-return-indent)
16742 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
16743 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
16744 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
16745 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
16746 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
16747 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
16748 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
16749 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
16750 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
16751 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
16752 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
16753 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
16754 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
16755 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
16756 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
16757 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
16758 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
16759 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
16760 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
16761 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
16762 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
16764 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
16765 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
16766 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
16767 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
16769 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
16770 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
16771 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
16772 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
16773 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
16774 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
16775 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
16776 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
16777 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
16778 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
16779 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
16780 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
16781 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
16782 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
16783 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
16784 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
16785 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
16786 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
16788 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
16789 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
16790 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
16791 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
16792 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
16794 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
16796 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
16798 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
16799 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
16801 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
16804 (when (featurep 'xemacs)
16805 (org-defkey org-mode-map 'button3 'popup-mode-menu))
16808 (defconst org-speed-commands-default
16810 ("Outline Navigation")
16811 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
16812 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
16813 ("f" . (org-speed-move-safe 'org-forward-same-level))
16814 ("b" . (org-speed-move-safe 'org-backward-same-level))
16815 ("u" . (org-speed-move-safe 'outline-up-heading))
16816 ("j" . org-goto)
16817 ("g" . (org-refile t))
16818 ("Outline Visibility")
16819 ("c" . org-cycle)
16820 ("C" . org-shifttab)
16821 (" " . org-display-outline-path)
16822 ("Outline Structure Editing")
16823 ("U" . org-shiftmetaup)
16824 ("D" . org-shiftmetadown)
16825 ("r" . org-metaright)
16826 ("l" . org-metaleft)
16827 ("R" . org-shiftmetaright)
16828 ("L" . org-shiftmetaleft)
16829 ("i" . (progn (forward-char 1) (call-interactively
16830 'org-insert-heading-respect-content)))
16831 ("^" . org-sort)
16832 ("w" . org-refile)
16833 ("a" . org-archive-subtree-default-with-confirmation)
16834 ("." . org-mark-subtree)
16835 ("Clock Commands")
16836 ("I" . org-clock-in)
16837 ("O" . org-clock-out)
16838 ("Meta Data Editing")
16839 ("t" . org-todo)
16840 ("0" . (org-priority ?\ ))
16841 ("1" . (org-priority ?A))
16842 ("2" . (org-priority ?B))
16843 ("3" . (org-priority ?C))
16844 (";" . org-set-tags-command)
16845 ("e" . org-set-effort)
16846 ("Agenda Views etc")
16847 ("v" . org-agenda)
16848 ("/" . org-sparse-tree)
16849 ("Misc")
16850 ("o" . org-open-at-point)
16851 ("?" . org-speed-command-help)
16852 ("<" . (org-agenda-set-restriction-lock 'subtree))
16853 (">" . (org-agenda-remove-restriction-lock))
16855 "The default speed commands.")
16857 (defun org-print-speed-command (e)
16858 (if (> (length (car e)) 1)
16859 (progn
16860 (princ "\n")
16861 (princ (car e))
16862 (princ "\n")
16863 (princ (make-string (length (car e)) ?-))
16864 (princ "\n"))
16865 (princ (car e))
16866 (princ " ")
16867 (if (symbolp (cdr e))
16868 (princ (symbol-name (cdr e)))
16869 (prin1 (cdr e)))
16870 (princ "\n")))
16872 (defun org-speed-command-help ()
16873 "Show the available speed commands."
16874 (interactive)
16875 (if (not org-use-speed-commands)
16876 (error "Speed commands are not activated, customize `org-use-speed-commands'")
16877 (with-output-to-temp-buffer "*Help*"
16878 (princ "User-defined Speed commands\n===========================\n")
16879 (mapc 'org-print-speed-command org-speed-commands-user)
16880 (princ "\n")
16881 (princ "Built-in Speed commands\n=======================\n")
16882 (mapc 'org-print-speed-command org-speed-commands-default))
16883 (with-current-buffer "*Help*"
16884 (setq truncate-lines t))))
16886 (defun org-speed-move-safe (cmd)
16887 "Execute CMD, but make sure that the cursor always ends up in a headline.
16888 If not, return to the original position and throw an error."
16889 (interactive)
16890 (let ((pos (point)))
16891 (call-interactively cmd)
16892 (unless (and (bolp) (org-on-heading-p))
16893 (goto-char pos)
16894 (error "Boundary reached while executing %s" cmd))))
16896 (defvar org-self-insert-command-undo-counter 0)
16898 (defvar org-table-auto-blank-field) ; defined in org-table.el
16899 (defvar org-speed-command nil)
16901 (defun org-speed-command-default-hook (keys)
16902 "Hook for activating single-letter speed commands.
16903 `org-speed-commands-default' specifies a minimal command set. Use
16904 `org-speed-commands-user' for further customization."
16905 (when (or (and (bolp) (looking-at outline-regexp))
16906 (and (functionp org-use-speed-commands)
16907 (funcall org-use-speed-commands)))
16908 (cdr (assoc keys (append org-speed-commands-user
16909 org-speed-commands-default)))))
16911 (defun org-babel-speed-command-hook (keys)
16912 "Hook for activating single-letter code block commands."
16913 (when (and (bolp) (looking-at org-babel-src-block-regexp))
16914 (cdr (assoc keys org-babel-key-bindings))))
16916 (defcustom org-speed-command-hook
16917 '(org-speed-command-default-hook org-babel-speed-command-hook)
16918 "Hook for activating speed commands at strategic locations.
16919 Hook functions are called in sequence until a valid handler is
16920 found.
16922 Each hook takes a single argument, a user-pressed command key
16923 which is also a `self-insert-command' from the global map.
16925 Within the hook, examine the cursor position and the command key
16926 and return nil or a valid handler as appropriate. Handler could
16927 be one of an interactive command, a function, or a form.
16929 Set `org-use-speed-commands' to non-nil value to enable this
16930 hook. The default setting is `org-speed-command-default-hook'."
16931 :group 'org-structure
16932 :type 'hook)
16934 (defun org-self-insert-command (N)
16935 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
16936 If the cursor is in a table looking at whitespace, the whitespace is
16937 overwritten, and the table is not marked as requiring realignment."
16938 (interactive "p")
16939 (cond
16940 ((and org-use-speed-commands
16941 (setq org-speed-command
16942 (run-hook-with-args-until-success
16943 'org-speed-command-hook (this-command-keys))))
16944 (cond
16945 ((commandp org-speed-command)
16946 (setq this-command org-speed-command)
16947 (call-interactively org-speed-command))
16948 ((functionp org-speed-command)
16949 (funcall org-speed-command))
16950 ((and org-speed-command (listp org-speed-command))
16951 (eval org-speed-command))
16952 (t (let (org-use-speed-commands)
16953 (call-interactively 'org-self-insert-command)))))
16954 ((and
16955 (org-table-p)
16956 (progn
16957 ;; check if we blank the field, and if that triggers align
16958 (and (featurep 'org-table) org-table-auto-blank-field
16959 (member last-command
16960 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
16961 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
16962 ;; got extra space, this field does not determine column width
16963 (let (org-table-may-need-update) (org-table-blank-field))
16964 ;; no extra space, this field may determine column width
16965 (org-table-blank-field)))
16967 (eq N 1)
16968 (looking-at "[^|\n]* |"))
16969 (let (org-table-may-need-update)
16970 (goto-char (1- (match-end 0)))
16971 (delete-char -1)
16972 (goto-char (match-beginning 0))
16973 (self-insert-command N)))
16975 (setq org-table-may-need-update t)
16976 (self-insert-command N)
16977 (org-fix-tags-on-the-fly)
16978 (if org-self-insert-cluster-for-undo
16979 (if (not (eq last-command 'org-self-insert-command))
16980 (setq org-self-insert-command-undo-counter 1)
16981 (if (>= org-self-insert-command-undo-counter 20)
16982 (setq org-self-insert-command-undo-counter 1)
16983 (and (> org-self-insert-command-undo-counter 0)
16984 buffer-undo-list (listp buffer-undo-list)
16985 (not (cadr buffer-undo-list)) ; remove nil entry
16986 (setcdr buffer-undo-list (cddr buffer-undo-list)))
16987 (setq org-self-insert-command-undo-counter
16988 (1+ org-self-insert-command-undo-counter))))))))
16990 (defun org-fix-tags-on-the-fly ()
16991 (when (and (equal (char-after (point-at-bol)) ?*)
16992 (org-on-heading-p))
16993 (org-align-tags-here org-tags-column)))
16995 (defun org-delete-backward-char (N)
16996 "Like `delete-backward-char', insert whitespace at field end in tables.
16997 When deleting backwards, in tables this function will insert whitespace in
16998 front of the next \"|\" separator, to keep the table aligned. The table will
16999 still be marked for re-alignment if the field did fill the entire column,
17000 because, in this case the deletion might narrow the column."
17001 (interactive "p")
17002 (if (and (org-table-p)
17003 (eq N 1)
17004 (string-match "|" (buffer-substring (point-at-bol) (point)))
17005 (looking-at ".*?|"))
17006 (let ((pos (point))
17007 (noalign (looking-at "[^|\n\r]* |"))
17008 (c org-table-may-need-update))
17009 (backward-delete-char N)
17010 (if (not overwrite-mode)
17011 (progn
17012 (skip-chars-forward "^|")
17013 (insert " ")
17014 (goto-char (1- pos))))
17015 ;; noalign: if there were two spaces at the end, this field
17016 ;; does not determine the width of the column.
17017 (if noalign (setq org-table-may-need-update c)))
17018 (backward-delete-char N)
17019 (org-fix-tags-on-the-fly)))
17021 (defun org-delete-char (N)
17022 "Like `delete-char', but insert whitespace at field end in tables.
17023 When deleting characters, in tables this function will insert whitespace in
17024 front of the next \"|\" separator, to keep the table aligned. The table will
17025 still be marked for re-alignment if the field did fill the entire column,
17026 because, in this case the deletion might narrow the column."
17027 (interactive "p")
17028 (if (and (org-table-p)
17029 (not (bolp))
17030 (not (= (char-after) ?|))
17031 (eq N 1))
17032 (if (looking-at ".*?|")
17033 (let ((pos (point))
17034 (noalign (looking-at "[^|\n\r]* |"))
17035 (c org-table-may-need-update))
17036 (replace-match (concat
17037 (substring (match-string 0) 1 -1)
17038 " |"))
17039 (goto-char pos)
17040 ;; noalign: if there were two spaces at the end, this field
17041 ;; does not determine the width of the column.
17042 (if noalign (setq org-table-may-need-update c)))
17043 (delete-char N))
17044 (delete-char N)
17045 (org-fix-tags-on-the-fly)))
17047 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
17048 (put 'org-self-insert-command 'delete-selection t)
17049 (put 'orgtbl-self-insert-command 'delete-selection t)
17050 (put 'org-delete-char 'delete-selection 'supersede)
17051 (put 'org-delete-backward-char 'delete-selection 'supersede)
17052 (put 'org-yank 'delete-selection 'yank)
17054 ;; Make `flyspell-mode' delay after some commands
17055 (put 'org-self-insert-command 'flyspell-delayed t)
17056 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
17057 (put 'org-delete-char 'flyspell-delayed t)
17058 (put 'org-delete-backward-char 'flyspell-delayed t)
17060 ;; Make pabbrev-mode expand after org-mode commands
17061 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
17062 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
17064 ;; How to do this: Measure non-white length of current string
17065 ;; If equal to column width, we should realign.
17067 (defun org-remap (map &rest commands)
17068 "In MAP, remap the functions given in COMMANDS.
17069 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
17070 (let (new old)
17071 (while commands
17072 (setq old (pop commands) new (pop commands))
17073 (if (fboundp 'command-remapping)
17074 (org-defkey map (vector 'remap old) new)
17075 (substitute-key-definition old new map global-map)))))
17077 (when (eq org-enable-table-editor 'optimized)
17078 ;; If the user wants maximum table support, we need to hijack
17079 ;; some standard editing functions
17080 (org-remap org-mode-map
17081 'self-insert-command 'org-self-insert-command
17082 'delete-char 'org-delete-char
17083 'delete-backward-char 'org-delete-backward-char)
17084 (org-defkey org-mode-map "|" 'org-force-self-insert))
17086 (defvar org-ctrl-c-ctrl-c-hook nil
17087 "Hook for functions attaching themselves to `C-c C-c'.
17088 This can be used to add additional functionality to the C-c C-c key which
17089 executes context-dependent commands.
17090 Each function will be called with no arguments. The function must check
17091 if the context is appropriate for it to act. If yes, it should do its
17092 thing and then return a non-nil value. If the context is wrong,
17093 just do nothing and return nil.")
17095 (defvar org-tab-first-hook nil
17096 "Hook for functions to attach themselves to TAB.
17097 See `org-ctrl-c-ctrl-c-hook' for more information.
17098 This hook runs as the first action when TAB is pressed, even before
17099 `org-cycle' messes around with the `outline-regexp' to cater for
17100 inline tasks and plain list item folding.
17101 If any function in this hook returns t, any other actions that
17102 would have been caused by TAB (such as table field motion or visibility
17103 cycling) will not occur.")
17105 (defvar org-tab-after-check-for-table-hook nil
17106 "Hook for functions to attach themselves to TAB.
17107 See `org-ctrl-c-ctrl-c-hook' for more information.
17108 This hook runs after it has been established that the cursor is not in a
17109 table, but before checking if the cursor is in a headline or if global cycling
17110 should be done.
17111 If any function in this hook returns t, not other actions like visibility
17112 cycling will be done.")
17114 (defvar org-tab-after-check-for-cycling-hook nil
17115 "Hook for functions to attach themselves to TAB.
17116 See `org-ctrl-c-ctrl-c-hook' for more information.
17117 This hook runs after it has been established that not table field motion and
17118 not visibility should be done because of current context. This is probably
17119 the place where a package like yasnippets can hook in.")
17121 (defvar org-tab-before-tab-emulation-hook nil
17122 "Hook for functions to attach themselves to TAB.
17123 See `org-ctrl-c-ctrl-c-hook' for more information.
17124 This hook runs after every other options for TAB have been exhausted, but
17125 before indentation and \t insertion takes place.")
17127 (defvar org-metaleft-hook nil
17128 "Hook for functions attaching themselves to `M-left'.
17129 See `org-ctrl-c-ctrl-c-hook' for more information.")
17130 (defvar org-metaright-hook nil
17131 "Hook for functions attaching themselves to `M-right'.
17132 See `org-ctrl-c-ctrl-c-hook' for more information.")
17133 (defvar org-metaup-hook nil
17134 "Hook for functions attaching themselves to `M-up'.
17135 See `org-ctrl-c-ctrl-c-hook' for more information.")
17136 (defvar org-metadown-hook nil
17137 "Hook for functions attaching themselves to `M-down'.
17138 See `org-ctrl-c-ctrl-c-hook' for more information.")
17139 (defvar org-shiftmetaleft-hook nil
17140 "Hook for functions attaching themselves to `M-S-left'.
17141 See `org-ctrl-c-ctrl-c-hook' for more information.")
17142 (defvar org-shiftmetaright-hook nil
17143 "Hook for functions attaching themselves to `M-S-right'.
17144 See `org-ctrl-c-ctrl-c-hook' for more information.")
17145 (defvar org-shiftmetaup-hook nil
17146 "Hook for functions attaching themselves to `M-S-up'.
17147 See `org-ctrl-c-ctrl-c-hook' for more information.")
17148 (defvar org-shiftmetadown-hook nil
17149 "Hook for functions attaching themselves to `M-S-down'.
17150 See `org-ctrl-c-ctrl-c-hook' for more information.")
17151 (defvar org-metareturn-hook nil
17152 "Hook for functions attaching themselves to `M-RET'.
17153 See `org-ctrl-c-ctrl-c-hook' for more information.")
17154 (defvar org-shiftup-hook nil
17155 "Hook for functions attaching themselves to `S-up'.
17156 See `org-ctrl-c-ctrl-c-hook' for more information.")
17157 (defvar org-shiftup-final-hook nil
17158 "Hook for functions attaching themselves to `S-up'.
17159 This one runs after all other options except shift-select have been excluded.
17160 See `org-ctrl-c-ctrl-c-hook' for more information.")
17161 (defvar org-shiftdown-hook nil
17162 "Hook for functions attaching themselves to `S-down'.
17163 See `org-ctrl-c-ctrl-c-hook' for more information.")
17164 (defvar org-shiftdown-final-hook nil
17165 "Hook for functions attaching themselves to `S-down'.
17166 This one runs after all other options except shift-select have been excluded.
17167 See `org-ctrl-c-ctrl-c-hook' for more information.")
17168 (defvar org-shiftleft-hook nil
17169 "Hook for functions attaching themselves to `S-left'.
17170 See `org-ctrl-c-ctrl-c-hook' for more information.")
17171 (defvar org-shiftleft-final-hook nil
17172 "Hook for functions attaching themselves to `S-left'.
17173 This one runs after all other options except shift-select have been excluded.
17174 See `org-ctrl-c-ctrl-c-hook' for more information.")
17175 (defvar org-shiftright-hook nil
17176 "Hook for functions attaching themselves to `S-right'.
17177 See `org-ctrl-c-ctrl-c-hook' for more information.")
17178 (defvar org-shiftright-final-hook nil
17179 "Hook for functions attaching themselves to `S-right'.
17180 This one runs after all other options except shift-select have been excluded.
17181 See `org-ctrl-c-ctrl-c-hook' for more information.")
17183 (defun org-modifier-cursor-error ()
17184 "Throw an error, a modified cursor command was applied in wrong context."
17185 (error "This command is active in special context like tables, headlines or items"))
17187 (defun org-shiftselect-error ()
17188 "Throw an error because Shift-Cursor command was applied in wrong context."
17189 (if (and (boundp 'shift-select-mode) shift-select-mode)
17190 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
17191 (error "This command works only in special context like headlines or timestamps")))
17193 (defun org-call-for-shift-select (cmd)
17194 (let ((this-command-keys-shift-translated t))
17195 (call-interactively cmd)))
17197 (defun org-shifttab (&optional arg)
17198 "Global visibility cycling or move to previous table field.
17199 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
17200 on context.
17201 See the individual commands for more information."
17202 (interactive "P")
17203 (cond
17204 ((org-at-table-p) (call-interactively 'org-table-previous-field))
17205 ((integerp arg)
17206 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
17207 (message "Content view to level: %d" arg)
17208 (org-content (prefix-numeric-value arg2))
17209 (setq org-cycle-global-status 'overview)))
17210 (t (call-interactively 'org-global-cycle))))
17212 (defun org-shiftmetaleft ()
17213 "Promote subtree or delete table column.
17214 Calls `org-promote-subtree', `org-outdent-item',
17215 or `org-table-delete-column', depending on context.
17216 See the individual commands for more information."
17217 (interactive)
17218 (cond
17219 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
17220 ((org-at-table-p) (call-interactively 'org-table-delete-column))
17221 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
17222 ((org-at-item-p) (call-interactively 'org-outdent-item-tree))
17223 (t (org-modifier-cursor-error))))
17225 (defun org-shiftmetaright ()
17226 "Demote subtree or insert table column.
17227 Calls `org-demote-subtree', `org-indent-item',
17228 or `org-table-insert-column', depending on context.
17229 See the individual commands for more information."
17230 (interactive)
17231 (cond
17232 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
17233 ((org-at-table-p) (call-interactively 'org-table-insert-column))
17234 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
17235 ((org-at-item-p) (call-interactively 'org-indent-item-tree))
17236 (t (org-modifier-cursor-error))))
17238 (defun org-shiftmetaup (&optional arg)
17239 "Move subtree up or kill table row.
17240 Calls `org-move-subtree-up' or `org-table-kill-row' or
17241 `org-move-item-up' depending on context. See the individual commands
17242 for more information."
17243 (interactive "P")
17244 (cond
17245 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
17246 ((org-at-table-p) (call-interactively 'org-table-kill-row))
17247 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
17248 ((org-at-item-p) (call-interactively 'org-move-item-up))
17249 (t (org-modifier-cursor-error))))
17251 (defun org-shiftmetadown (&optional arg)
17252 "Move subtree down or insert table row.
17253 Calls `org-move-subtree-down' or `org-table-insert-row' or
17254 `org-move-item-down', depending on context. See the individual
17255 commands for more information."
17256 (interactive "P")
17257 (cond
17258 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
17259 ((org-at-table-p) (call-interactively 'org-table-insert-row))
17260 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
17261 ((org-at-item-p) (call-interactively 'org-move-item-down))
17262 (t (org-modifier-cursor-error))))
17264 (defsubst org-hidden-tree-error ()
17265 (error
17266 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
17268 (defun org-metaleft (&optional arg)
17269 "Promote heading or move table column to left.
17270 Calls `org-do-promote' or `org-table-move-column', depending on context.
17271 With no specific context, calls the Emacs default `backward-word'.
17272 See the individual commands for more information."
17273 (interactive "P")
17274 (cond
17275 ((run-hook-with-args-until-success 'org-metaleft-hook))
17276 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
17277 ((org-with-limited-levels
17278 (or (org-on-heading-p)
17279 (and (org-region-active-p)
17280 (save-excursion
17281 (goto-char (region-beginning))
17282 (org-on-heading-p)))))
17283 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
17284 (call-interactively 'org-do-promote))
17285 ;; At an inline task.
17286 ((org-on-heading-p)
17287 (call-interactively 'org-inlinetask-promote))
17288 ((or (org-at-item-p)
17289 (and (org-region-active-p)
17290 (save-excursion
17291 (goto-char (region-beginning))
17292 (org-at-item-p))))
17293 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
17294 (call-interactively 'org-outdent-item))
17295 (t (call-interactively 'backward-word))))
17297 (defun org-metaright (&optional arg)
17298 "Demote subtree or move table column to right.
17299 Calls `org-do-demote' or `org-table-move-column', depending on context.
17300 With no specific context, calls the Emacs default `forward-word'.
17301 See the individual commands for more information."
17302 (interactive "P")
17303 (cond
17304 ((run-hook-with-args-until-success 'org-metaright-hook))
17305 ((org-at-table-p) (call-interactively 'org-table-move-column))
17306 ((org-with-limited-levels
17307 (or (org-on-heading-p)
17308 (and (org-region-active-p)
17309 (save-excursion
17310 (goto-char (region-beginning))
17311 (org-on-heading-p)))))
17312 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
17313 (call-interactively 'org-do-demote))
17314 ;; At an inline task.
17315 ((org-on-heading-p)
17316 (call-interactively 'org-inlinetask-demote))
17317 ((or (org-at-item-p)
17318 (and (org-region-active-p)
17319 (save-excursion
17320 (goto-char (region-beginning))
17321 (org-at-item-p))))
17322 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
17323 (call-interactively 'org-indent-item))
17324 (t (call-interactively 'forward-word))))
17326 (defun org-check-for-hidden (what)
17327 "Check if there are hidden headlines/items in the current visual line.
17328 WHAT can be either `headlines' or `items'. If the current line is
17329 an outline or item heading and it has a folded subtree below it,
17330 this function returns t, nil otherwise."
17331 (let ((re (cond
17332 ((eq what 'headlines) (concat "^" org-outline-regexp))
17333 ((eq what 'items) (org-item-beginning-re))
17334 (t (error "This should not happen"))))
17335 beg end)
17336 (save-excursion
17337 (catch 'exit
17338 (unless (org-region-active-p)
17339 (setq beg (point-at-bol))
17340 (beginning-of-line 2)
17341 (while (and (not (eobp)) ;; this is like `next-line'
17342 (get-char-property (1- (point)) 'invisible))
17343 (beginning-of-line 2))
17344 (setq end (point))
17345 (goto-char beg)
17346 (goto-char (point-at-eol))
17347 (setq end (max end (point)))
17348 (while (re-search-forward re end t)
17349 (if (get-char-property (match-beginning 0) 'invisible)
17350 (throw 'exit t))))
17351 nil))))
17353 (defun org-metaup (&optional arg)
17354 "Move subtree up or move table row up.
17355 Calls `org-move-subtree-up' or `org-table-move-row' or
17356 `org-move-item-up', depending on context. See the individual commands
17357 for more information."
17358 (interactive "P")
17359 (cond
17360 ((run-hook-with-args-until-success 'org-metaup-hook))
17361 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
17362 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
17363 ((org-at-item-p) (call-interactively 'org-move-item-up))
17364 (t (transpose-lines 1) (beginning-of-line -1))))
17366 (defun org-metadown (&optional arg)
17367 "Move subtree down or move table row down.
17368 Calls `org-move-subtree-down' or `org-table-move-row' or
17369 `org-move-item-down', depending on context. See the individual
17370 commands for more information."
17371 (interactive "P")
17372 (cond
17373 ((run-hook-with-args-until-success 'org-metadown-hook))
17374 ((org-at-table-p) (call-interactively 'org-table-move-row))
17375 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
17376 ((org-at-item-p) (call-interactively 'org-move-item-down))
17377 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
17379 (defun org-shiftup (&optional arg)
17380 "Increase item in timestamp or increase priority of current headline.
17381 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
17382 depending on context. See the individual commands for more information."
17383 (interactive "P")
17384 (cond
17385 ((run-hook-with-args-until-success 'org-shiftup-hook))
17386 ((and org-support-shift-select (org-region-active-p))
17387 (org-call-for-shift-select 'previous-line))
17388 ((org-at-timestamp-p t)
17389 (call-interactively (if org-edit-timestamp-down-means-later
17390 'org-timestamp-down 'org-timestamp-up)))
17391 ((and (not (eq org-support-shift-select 'always))
17392 org-enable-priority-commands
17393 (org-on-heading-p))
17394 (call-interactively 'org-priority-up))
17395 ((and (not org-support-shift-select) (org-at-item-p))
17396 (call-interactively 'org-previous-item))
17397 ((org-clocktable-try-shift 'up arg))
17398 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
17399 (org-support-shift-select
17400 (org-call-for-shift-select 'previous-line))
17401 (t (org-shiftselect-error))))
17403 (defun org-shiftdown (&optional arg)
17404 "Decrease item in timestamp or decrease priority of current headline.
17405 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
17406 depending on context. See the individual commands for more information."
17407 (interactive "P")
17408 (cond
17409 ((run-hook-with-args-until-success 'org-shiftdown-hook))
17410 ((and org-support-shift-select (org-region-active-p))
17411 (org-call-for-shift-select 'next-line))
17412 ((org-at-timestamp-p t)
17413 (call-interactively (if org-edit-timestamp-down-means-later
17414 'org-timestamp-up 'org-timestamp-down)))
17415 ((and (not (eq org-support-shift-select 'always))
17416 org-enable-priority-commands
17417 (org-on-heading-p))
17418 (call-interactively 'org-priority-down))
17419 ((and (not org-support-shift-select) (org-at-item-p))
17420 (call-interactively 'org-next-item))
17421 ((org-clocktable-try-shift 'down arg))
17422 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
17423 (org-support-shift-select
17424 (org-call-for-shift-select 'next-line))
17425 (t (org-shiftselect-error))))
17427 (defun org-shiftright (&optional arg)
17428 "Cycle the thing at point or in the current line, depending on context.
17429 Depending on context, this does one of the following:
17431 - switch a timestamp at point one day into the future
17432 - on a headline, switch to the next TODO keyword.
17433 - on an item, switch entire list to the next bullet type
17434 - on a property line, switch to the next allowed value
17435 - on a clocktable definition line, move time block into the future"
17436 (interactive "P")
17437 (cond
17438 ((run-hook-with-args-until-success 'org-shiftright-hook))
17439 ((and org-support-shift-select (org-region-active-p))
17440 (org-call-for-shift-select 'forward-char))
17441 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
17442 ((and (not (eq org-support-shift-select 'always))
17443 (org-on-heading-p))
17444 (let ((org-inhibit-logging
17445 (not org-treat-S-cursor-todo-selection-as-state-change))
17446 (org-inhibit-blocking
17447 (not org-treat-S-cursor-todo-selection-as-state-change)))
17448 (org-call-with-arg 'org-todo 'right)))
17449 ((or (and org-support-shift-select
17450 (not (eq org-support-shift-select 'always))
17451 (org-at-item-bullet-p))
17452 (and (not org-support-shift-select) (org-at-item-p)))
17453 (org-call-with-arg 'org-cycle-list-bullet nil))
17454 ((and (not (eq org-support-shift-select 'always))
17455 (org-at-property-p))
17456 (call-interactively 'org-property-next-allowed-value))
17457 ((org-clocktable-try-shift 'right arg))
17458 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
17459 (org-support-shift-select
17460 (org-call-for-shift-select 'forward-char))
17461 (t (org-shiftselect-error))))
17463 (defun org-shiftleft (&optional arg)
17464 "Cycle the thing at point or in the current line, depending on context.
17465 Depending on context, this does one of the following:
17467 - switch a timestamp at point one day into the past
17468 - on a headline, switch to the previous TODO keyword.
17469 - on an item, switch entire list to the previous bullet type
17470 - on a property line, switch to the previous allowed value
17471 - on a clocktable definition line, move time block into the past"
17472 (interactive "P")
17473 (cond
17474 ((run-hook-with-args-until-success 'org-shiftleft-hook))
17475 ((and org-support-shift-select (org-region-active-p))
17476 (org-call-for-shift-select 'backward-char))
17477 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
17478 ((and (not (eq org-support-shift-select 'always))
17479 (org-on-heading-p))
17480 (let ((org-inhibit-logging
17481 (not org-treat-S-cursor-todo-selection-as-state-change))
17482 (org-inhibit-blocking
17483 (not org-treat-S-cursor-todo-selection-as-state-change)))
17484 (org-call-with-arg 'org-todo 'left)))
17485 ((or (and org-support-shift-select
17486 (not (eq org-support-shift-select 'always))
17487 (org-at-item-bullet-p))
17488 (and (not org-support-shift-select) (org-at-item-p)))
17489 (org-call-with-arg 'org-cycle-list-bullet 'previous))
17490 ((and (not (eq org-support-shift-select 'always))
17491 (org-at-property-p))
17492 (call-interactively 'org-property-previous-allowed-value))
17493 ((org-clocktable-try-shift 'left arg))
17494 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
17495 (org-support-shift-select
17496 (org-call-for-shift-select 'backward-char))
17497 (t (org-shiftselect-error))))
17499 (defun org-shiftcontrolright ()
17500 "Switch to next TODO set."
17501 (interactive)
17502 (cond
17503 ((and org-support-shift-select (org-region-active-p))
17504 (org-call-for-shift-select 'forward-word))
17505 ((and (not (eq org-support-shift-select 'always))
17506 (org-on-heading-p))
17507 (org-call-with-arg 'org-todo 'nextset))
17508 (org-support-shift-select
17509 (org-call-for-shift-select 'forward-word))
17510 (t (org-shiftselect-error))))
17512 (defun org-shiftcontrolleft ()
17513 "Switch to previous TODO set."
17514 (interactive)
17515 (cond
17516 ((and org-support-shift-select (org-region-active-p))
17517 (org-call-for-shift-select 'backward-word))
17518 ((and (not (eq org-support-shift-select 'always))
17519 (org-on-heading-p))
17520 (org-call-with-arg 'org-todo 'previousset))
17521 (org-support-shift-select
17522 (org-call-for-shift-select 'backward-word))
17523 (t (org-shiftselect-error))))
17525 (defun org-ctrl-c-ret ()
17526 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
17527 (interactive)
17528 (cond
17529 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
17530 (t (call-interactively 'org-insert-heading))))
17532 (defun org-copy-special ()
17533 "Copy region in table or copy current subtree.
17534 Calls `org-table-copy' or `org-copy-subtree', depending on context.
17535 See the individual commands for more information."
17536 (interactive)
17537 (call-interactively
17538 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
17540 (defun org-cut-special ()
17541 "Cut region in table or cut current subtree.
17542 Calls `org-table-copy' or `org-cut-subtree', depending on context.
17543 See the individual commands for more information."
17544 (interactive)
17545 (call-interactively
17546 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
17548 (defun org-paste-special (arg)
17549 "Paste rectangular region into table, or past subtree relative to level.
17550 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
17551 See the individual commands for more information."
17552 (interactive "P")
17553 (if (org-at-table-p)
17554 (org-table-paste-rectangle)
17555 (org-paste-subtree arg)))
17557 (defun org-edit-special (&optional arg)
17558 "Call a special editor for the stuff at point.
17559 When at a table, call the formula editor with `org-table-edit-formulas'.
17560 When at the first line of an src example, call `org-edit-src-code'.
17561 When in an #+include line, visit the include file. Otherwise call
17562 `ffap' to visit the file at point."
17563 (interactive)
17564 ;; possibly prep session before editing source
17565 (when arg
17566 (let* ((info (org-babel-get-src-block-info))
17567 (lang (nth 0 info))
17568 (params (nth 2 info))
17569 (session (cdr (assoc :session params))))
17570 (when (and info session) ;; we are in a source-code block with a session
17571 (funcall
17572 (intern (concat "org-babel-prep-session:" lang)) session params))))
17573 (cond ;; proceed with `org-edit-special'
17574 ((save-excursion
17575 (beginning-of-line 1)
17576 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
17577 (find-file (org-trim (match-string 1))))
17578 ((org-edit-src-code))
17579 ((org-edit-fixed-width-region))
17580 ((org-at-table.el-p)
17581 (org-edit-src-code))
17582 ((or (org-at-table-p)
17583 (save-excursion
17584 (beginning-of-line 1)
17585 (looking-at "[ \t]*#\\+TBLFM:")))
17586 (call-interactively 'org-table-edit-formulas))
17587 (t (call-interactively 'ffap))))
17589 (defun org-ctrl-c-ctrl-c (&optional arg)
17590 "Set tags in headline, or update according to changed information at point.
17592 This command does many different things, depending on context:
17594 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
17595 this is what we do.
17597 - If the cursor is on a statistics cookie, update it.
17599 - If the cursor is in a headline, prompt for tags and insert them
17600 into the current line, aligned to `org-tags-column'. When called
17601 with prefix arg, realign all tags in the current buffer.
17603 - If the cursor is in one of the special #+KEYWORD lines, this
17604 triggers scanning the buffer for these lines and updating the
17605 information.
17607 - If the cursor is inside a table, realign the table. This command
17608 works even if the automatic table editor has been turned off.
17610 - If the cursor is on a #+TBLFM line, re-apply the formulas to
17611 the entire table.
17613 - If the cursor is at a footnote reference or definition, jump to
17614 the corresponding definition or references, respectively.
17616 - If the cursor is a the beginning of a dynamic block, update it.
17618 - If the current buffer is a capture buffer, close note and file it.
17620 - If the cursor is on a <<<target>>>, update radio targets and
17621 corresponding links in this buffer.
17623 - If the cursor is on a numbered item in a plain list, renumber the
17624 ordered list.
17626 - If the cursor is on a checkbox, toggle it.
17628 - If the cursor is on a code block, evaluate it. The variable
17629 `org-confirm-babel-evaluate' can be used to control prompting
17630 before code block evaluation, by default every code block
17631 evaluation requires confirmation. Code block evaluation can be
17632 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
17633 (interactive "P")
17634 (let ((org-enable-table-editor t))
17635 (cond
17636 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
17637 org-occur-highlights
17638 org-latex-fragment-image-overlays)
17639 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
17640 (org-remove-occur-highlights)
17641 (org-remove-latex-fragment-image-overlays)
17642 (message "Temporary highlights/overlays removed from current buffer"))
17643 ((and (local-variable-p 'org-finish-function (current-buffer))
17644 (fboundp org-finish-function))
17645 (funcall org-finish-function))
17646 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
17647 ((or (looking-at org-property-start-re)
17648 (org-at-property-p))
17649 (call-interactively 'org-property-action))
17650 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
17651 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
17652 (or (org-on-heading-p) (org-at-item-p)))
17653 (call-interactively 'org-update-statistics-cookies))
17654 ((org-on-heading-p) (call-interactively 'org-set-tags))
17655 ((org-at-table.el-p)
17656 (message "Use C-c ' to edit table.el tables"))
17657 ((org-at-table-p)
17658 (org-table-maybe-eval-formula)
17659 (if arg
17660 (call-interactively 'org-table-recalculate)
17661 (org-table-maybe-recalculate-line))
17662 (call-interactively 'org-table-align)
17663 (orgtbl-send-table 'maybe))
17664 ((or (org-footnote-at-reference-p)
17665 (org-footnote-at-definition-p))
17666 (call-interactively 'org-footnote-action))
17667 ((org-at-item-checkbox-p)
17668 ;; Cursor at a checkbox: repair list and update checkboxes. Send
17669 ;; list only if at top item.
17670 (let* ((cbox (match-string 1))
17671 (struct (org-list-struct))
17672 (old-struct (copy-tree struct))
17673 (parents (org-list-parents-alist struct))
17674 (prevs (org-list-prevs-alist struct))
17675 (orderedp (org-entry-get nil "ORDERED"))
17676 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
17677 block-item)
17678 ;; Use a light version of `org-toggle-checkbox' to avoid
17679 ;; computing list structure twice.
17680 (org-list-set-checkbox (point-at-bol) struct
17681 (cond
17682 ((equal arg '(16)) "[-]")
17683 ((equal arg '(4)) nil)
17684 ((equal "[X]" cbox) "[ ]")
17685 (t "[X]")))
17686 (org-list-struct-fix-ind struct parents)
17687 (org-list-struct-fix-bul struct prevs)
17688 (setq block-item
17689 (org-list-struct-fix-box struct parents prevs orderedp))
17690 (when block-item
17691 (message
17692 "Checkboxes were removed due to unchecked box at line %d"
17693 (org-current-line block-item)))
17694 (org-list-struct-apply-struct struct old-struct)
17695 (org-update-checkbox-count-maybe)
17696 (when firstp (org-list-send-list 'maybe))))
17697 ((org-at-item-p)
17698 ;; Cursor at an item: repair list. Do checkbox related actions
17699 ;; only if function was called with an argument. Send list only
17700 ;; if at top item.
17701 (let* ((struct (org-list-struct))
17702 (old-struct (copy-tree struct))
17703 (parents (org-list-parents-alist struct))
17704 (prevs (org-list-prevs-alist struct))
17705 (firstp (= (org-list-get-top-point struct) (point-at-bol))))
17706 (org-list-struct-fix-ind struct parents)
17707 (org-list-struct-fix-bul struct prevs)
17708 (when arg
17709 (org-list-set-checkbox (point-at-bol) struct "[ ]")
17710 (org-list-struct-fix-box struct parents prevs))
17711 (org-list-struct-apply-struct struct old-struct)
17712 (when arg (org-update-checkbox-count-maybe))
17713 (when firstp (org-list-send-list 'maybe))))
17714 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
17715 ;; Dynamic block
17716 (beginning-of-line 1)
17717 (save-excursion (org-update-dblock)))
17718 ((save-excursion
17719 (beginning-of-line 1)
17720 (looking-at "[ \t]*#\\+\\([A-Z]+\\)"))
17721 (cond
17722 ((equal (match-string 1) "TBLFM")
17723 ;; Recalculate the table before this line
17724 (save-excursion
17725 (beginning-of-line 1)
17726 (skip-chars-backward " \r\n\t")
17727 (if (org-at-table-p)
17728 (org-call-with-arg 'org-table-recalculate (or arg t)))))
17730 (let ((org-inhibit-startup-visibility-stuff t)
17731 (org-startup-align-all-tables nil))
17732 (org-save-outline-visibility 'use-markers (org-mode-restart)))
17733 (message "Local setup has been refreshed"))))
17734 ((org-clock-update-time-maybe))
17735 (t (error "C-c C-c can do nothing useful at this location")))))
17737 (defun org-mode-restart ()
17738 "Restart Org-mode, to scan again for special lines.
17739 Also updates the keyword regular expressions."
17740 (interactive)
17741 (org-mode)
17742 (message "Org-mode restarted"))
17744 (defun org-kill-note-or-show-branches ()
17745 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
17746 (interactive)
17747 (if (not org-finish-function)
17748 (progn
17749 (hide-subtree)
17750 (call-interactively 'show-branches))
17751 (let ((org-note-abort t))
17752 (funcall org-finish-function))))
17754 (defun org-return (&optional indent)
17755 "Goto next table row or insert a newline.
17756 Calls `org-table-next-row' or `newline', depending on context.
17757 See the individual commands for more information."
17758 (interactive)
17759 (cond
17760 ((bobp) (if indent (newline-and-indent) (newline)))
17761 ((org-at-table-p)
17762 (org-table-justify-field-maybe)
17763 (call-interactively 'org-table-next-row))
17764 ;; when `newline-and-indent' is called within a list, make sure
17765 ;; text moved stays inside the item.
17766 ((and (org-in-item-p) indent)
17767 (if (and (org-at-item-p) (>= (point) (match-end 0)))
17768 (progn
17769 (newline)
17770 (org-indent-line-to (length (match-string 0))))
17771 (let ((ind (org-get-indentation)))
17772 (newline)
17773 (if (org-looking-back org-list-end-re)
17774 (org-indent-line-function)
17775 (org-indent-line-to ind)))))
17776 ((and org-return-follows-link
17777 (eq (get-text-property (point) 'face) 'org-link))
17778 (call-interactively 'org-open-at-point))
17779 ((and (org-at-heading-p)
17780 (looking-at
17781 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
17782 (org-show-entry)
17783 (end-of-line 1)
17784 (newline))
17785 (t (if indent (newline-and-indent) (newline)))))
17787 (defun org-return-indent ()
17788 "Goto next table row or insert a newline and indent.
17789 Calls `org-table-next-row' or `newline-and-indent', depending on
17790 context. See the individual commands for more information."
17791 (interactive)
17792 (org-return t))
17794 (defun org-ctrl-c-star ()
17795 "Compute table, or change heading status of lines.
17796 Calls `org-table-recalculate' or `org-toggle-heading',
17797 depending on context."
17798 (interactive)
17799 (cond
17800 ((org-at-table-p)
17801 (call-interactively 'org-table-recalculate))
17803 ;; Convert all lines in region to list items
17804 (call-interactively 'org-toggle-heading))))
17806 (defun org-ctrl-c-minus ()
17807 "Insert separator line in table or modify bullet status of line.
17808 Also turns a plain line or a region of lines into list items.
17809 Calls `org-table-insert-hline', `org-toggle-item', or
17810 `org-cycle-list-bullet', depending on context."
17811 (interactive)
17812 (cond
17813 ((org-at-table-p)
17814 (call-interactively 'org-table-insert-hline))
17815 ((org-region-active-p)
17816 (call-interactively 'org-toggle-item))
17817 ((org-in-item-p)
17818 (call-interactively 'org-cycle-list-bullet))
17820 (call-interactively 'org-toggle-item))))
17822 (defun org-toggle-item (arg)
17823 "Convert headings or normal lines to items, items to normal lines.
17824 If there is no active region, only the current line is considered.
17826 If the first non blank line in the region is an headline, convert
17827 all headlines to items, shifting text accordingly.
17829 If it is an item, convert all items to normal lines.
17831 If it is normal text, change region into an item. With a prefix
17832 argument ARG, change each line in region into an item."
17833 (interactive "P")
17834 (let ((shift-text
17835 (function
17836 ;; Shift text in current section to IND, from point to END.
17837 ;; The function leaves point to END line.
17838 (lambda (ind end)
17839 (let ((min-i 1000) (end (copy-marker end)))
17840 ;; First determine the minimum indentation (MIN-I) of
17841 ;; the text.
17842 (save-excursion
17843 (catch 'exit
17844 (while (< (point) end)
17845 (let ((i (org-get-indentation)))
17846 (cond
17847 ;; Skip blank lines and inline tasks.
17848 ((looking-at "^[ \t]*$"))
17849 ((looking-at "^\\*+ "))
17850 ;; We can't find less than 0 indentation.
17851 ((zerop i) (throw 'exit (setq min-i 0)))
17852 ((< i min-i) (setq min-i i))))
17853 (forward-line))))
17854 ;; Then indent each line so that a line indented to
17855 ;; MIN-I becomes indented to IND. Ignore blank lines
17856 ;; and inline tasks in the process.
17857 (let ((delta (- ind min-i)))
17858 (while (< (point) end)
17859 (unless (or (looking-at "^[ \t]*$")
17860 (looking-at "^\\*+ "))
17861 (org-indent-line-to (+ (org-get-indentation) delta)))
17862 (forward-line)))))))
17863 (skip-blanks
17864 (function
17865 ;; Return beginning of first non-blank line, starting from
17866 ;; line at POS.
17867 (lambda (pos)
17868 (save-excursion
17869 (goto-char pos)
17870 (skip-chars-forward " \r\t\n")
17871 (point-at-bol)))))
17872 beg end)
17873 ;; Determine boundaries of changes.
17874 (if (org-region-active-p)
17875 (setq beg (funcall skip-blanks (region-beginning))
17876 end (copy-marker (region-end)))
17877 (setq beg (funcall skip-blanks (point-at-bol))
17878 end (copy-marker (point-at-eol))))
17879 ;; Depending on the starting line, choose an action on the text
17880 ;; between BEG and END.
17881 (org-with-limited-levels
17882 (save-excursion
17883 (goto-char beg)
17884 (cond
17885 ;; Case 1. Start at an item: de-itemize. Note that it only
17886 ;; happens when a region is active: `org-ctrl-c-minus'
17887 ;; would call `org-cycle-list-bullet' otherwise.
17888 ((org-at-item-p)
17889 (while (< (point) end)
17890 (when (org-at-item-p)
17891 (skip-chars-forward " \t")
17892 (delete-region (point) (match-end 0)))
17893 (forward-line)))
17894 ;; Case 2. Start at an heading: convert to items.
17895 ((org-on-heading-p)
17896 (let* ((bul (org-list-bullet-string "-"))
17897 (bul-len (length bul))
17898 ;; Indentation of the first heading. It should be
17899 ;; relative to the indentation of its parent, if any.
17900 (start-ind (save-excursion
17901 (cond
17902 ((not org-adapt-indentation) 0)
17903 ((not (outline-previous-heading)) 0)
17904 (t (length (match-string 0))))))
17905 ;; Level of first heading. Further headings will be
17906 ;; compared to it to determine hierarchy in the list.
17907 (ref-level (org-reduced-level (org-outline-level))))
17908 (while (< (point) end)
17909 (let* ((level (org-reduced-level (org-outline-level)))
17910 (delta (max 0 (- level ref-level))))
17911 ;; If current headline is less indented than the first
17912 ;; one, set it as reference, in order to preserve
17913 ;; subtrees.
17914 (when (< level ref-level) (setq ref-level level))
17915 (replace-match bul t t)
17916 (org-indent-line-to (+ start-ind (* delta bul-len)))
17917 ;; Ensure all text down to END (or SECTION-END) belongs
17918 ;; to the newly created item.
17919 (let ((section-end (save-excursion
17920 (or (outline-next-heading) (point)))))
17921 (forward-line)
17922 (funcall shift-text
17923 (+ start-ind (* (1+ delta) bul-len))
17924 (min end section-end)))))))
17925 ;; Case 3. Normal line with ARG: turn each non-item line into
17926 ;; an item.
17927 (arg
17928 (while (< (point) end)
17929 (unless (or (org-on-heading-p) (org-at-item-p))
17930 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
17931 (replace-match
17932 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
17933 (forward-line)))
17934 ;; Case 4. Normal line without ARG: make the first line of
17935 ;; region an item, and shift indentation of others
17936 ;; lines to set them as item's body.
17937 (t (let* ((bul (org-list-bullet-string "-"))
17938 (bul-len (length bul))
17939 (ref-ind (org-get-indentation)))
17940 (skip-chars-forward " \t")
17941 (insert bul)
17942 (forward-line)
17943 (while (< (point) end)
17944 ;; Ensure that lines less indented than first one
17945 ;; still get included in item body.
17946 (funcall shift-text
17947 (+ ref-ind bul-len)
17948 (min end (save-excursion (or (outline-next-heading)
17949 (point)))))
17950 (forward-line)))))))))
17952 (defun org-toggle-heading (&optional nstars)
17953 "Convert headings to normal text, or items or text to headings.
17954 If there is no active region, only the current line is considered.
17956 If the first non blank line is an headline, remove the stars from
17957 all headlines in the region.
17959 If it is a plain list item, turn all plain list items into headings.
17961 If it is a normal line, turn each and every normal line (i.e. not
17962 an heading or an item) in the region into a heading.
17964 When converting a line into a heading, the number of stars is chosen
17965 such that the lines become children of the current entry. However,
17966 when a prefix argument is given, its value determines the number of
17967 stars to add."
17968 (interactive "P")
17969 (let ((skip-blanks
17970 (function
17971 ;; Return beginning of first non-blank line, starting from
17972 ;; line at POS.
17973 (lambda (pos)
17974 (save-excursion
17975 (goto-char pos)
17976 (skip-chars-forward " \r\t\n")
17977 (point-at-bol)))))
17978 beg end)
17979 ;; Determine boundaries of changes. If region ends at a bol, do
17980 ;; not consider the last line to be in the region.
17981 (if (org-region-active-p)
17982 (setq beg (funcall skip-blanks (region-beginning))
17983 end (copy-marker (save-excursion
17984 (goto-char (region-end))
17985 (if (bolp) (point) (point-at-eol)))))
17986 (setq beg (funcall skip-blanks (point-at-bol))
17987 end (copy-marker (point-at-eol))))
17988 ;; Ensure inline tasks don't count as headings.
17989 (org-with-limited-levels
17990 (save-excursion
17991 (goto-char beg)
17992 (cond
17993 ;; Case 1. Started at an heading: de-star headings.
17994 ((org-on-heading-p)
17995 (while (< (point) end)
17996 (when (org-on-heading-p t)
17997 (looking-at outline-regexp) (replace-match ""))
17998 (forward-line)))
17999 ;; Case 2. Started at an item: change items into headlines.
18000 ;; One star will be added by `org-list-to-subtree'.
18001 ((org-at-item-p)
18002 (let* ((stars (make-string
18003 (if nstars
18004 ;; subtract the star that will be added again by
18005 ;; `org-list-to-subtree'
18006 (1- (prefix-numeric-value current-prefix-arg))
18007 (or (org-current-level) 0))
18008 ?*))
18009 (add-stars
18010 (cond (nstars "") ; stars from prefix only
18011 ((equal stars "") "") ; before first heading
18012 (org-odd-levels-only "*") ; inside heading, odd
18013 (t "")))) ; inside heading, oddeven
18014 (while (< (point) end)
18015 (when (org-at-item-p)
18016 ;; Pay attention to cases when region ends before list.
18017 (let* ((struct (org-list-struct))
18018 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
18019 (save-restriction
18020 (narrow-to-region (point) list-end)
18021 (insert
18022 (org-list-to-subtree
18023 (org-list-parse-list t)
18024 '(:istart (concat stars add-stars (funcall get-stars depth))
18025 :icount (concat stars add-stars (funcall get-stars depth))))))))
18026 (forward-line))))
18027 ;; Case 3. Started at normal text: make every line an heading,
18028 ;; skipping headlines and items.
18029 (t (let* ((stars (make-string
18030 (if nstars
18031 (prefix-numeric-value current-prefix-arg)
18032 (or (org-current-level) 0))
18033 ?*))
18034 (add-stars
18035 (cond (nstars "") ; stars from prefix only
18036 ((equal stars "") "*") ; before first heading
18037 (org-odd-levels-only "**") ; inside heading, odd
18038 (t "*"))) ; inside heading, oddeven
18039 (rpl (concat stars add-stars " ")))
18040 (while (< (point) end)
18041 (when (and (not (org-on-heading-p)) (not (org-at-item-p))
18042 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
18043 (replace-match (concat rpl (match-string 2))))
18044 (forward-line)))))))))
18046 (defun org-meta-return (&optional arg)
18047 "Insert a new heading or wrap a region in a table.
18048 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
18049 See the individual commands for more information."
18050 (interactive "P")
18051 (cond
18052 ((run-hook-with-args-until-success 'org-metareturn-hook))
18053 ((org-at-table-p)
18054 (call-interactively 'org-table-wrap-region))
18055 (t (call-interactively 'org-insert-heading))))
18057 ;;; Menu entries
18059 ;; Define the Org-mode menus
18060 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
18061 '("Tbl"
18062 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
18063 ["Next Field" org-cycle (org-at-table-p)]
18064 ["Previous Field" org-shifttab (org-at-table-p)]
18065 ["Next Row" org-return (org-at-table-p)]
18066 "--"
18067 ["Blank Field" org-table-blank-field (org-at-table-p)]
18068 ["Edit Field" org-table-edit-field (org-at-table-p)]
18069 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
18070 "--"
18071 ("Column"
18072 ["Move Column Left" org-metaleft (org-at-table-p)]
18073 ["Move Column Right" org-metaright (org-at-table-p)]
18074 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
18075 ["Insert Column" org-shiftmetaright (org-at-table-p)])
18076 ("Row"
18077 ["Move Row Up" org-metaup (org-at-table-p)]
18078 ["Move Row Down" org-metadown (org-at-table-p)]
18079 ["Delete Row" org-shiftmetaup (org-at-table-p)]
18080 ["Insert Row" org-shiftmetadown (org-at-table-p)]
18081 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
18082 "--"
18083 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
18084 ("Rectangle"
18085 ["Copy Rectangle" org-copy-special (org-at-table-p)]
18086 ["Cut Rectangle" org-cut-special (org-at-table-p)]
18087 ["Paste Rectangle" org-paste-special (org-at-table-p)]
18088 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
18089 "--"
18090 ("Calculate"
18091 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
18092 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
18093 ["Edit Formulas" org-edit-special (org-at-table-p)]
18094 "--"
18095 ["Recalculate line" org-table-recalculate (org-at-table-p)]
18096 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
18097 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
18098 "--"
18099 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
18100 "--"
18101 ["Sum Column/Rectangle" org-table-sum
18102 (or (org-at-table-p) (org-region-active-p))]
18103 ["Which Column?" org-table-current-column (org-at-table-p)])
18104 ["Debug Formulas"
18105 org-table-toggle-formula-debugger
18106 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
18107 ["Show Col/Row Numbers"
18108 org-table-toggle-coordinate-overlays
18109 :style toggle
18110 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
18111 "--"
18112 ["Create" org-table-create (and (not (org-at-table-p))
18113 org-enable-table-editor)]
18114 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
18115 ["Import from File" org-table-import (not (org-at-table-p))]
18116 ["Export to File" org-table-export (org-at-table-p)]
18117 "--"
18118 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
18120 (easy-menu-define org-org-menu org-mode-map "Org menu"
18121 '("Org"
18122 ("Show/Hide"
18123 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
18124 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
18125 ["Sparse Tree..." org-sparse-tree t]
18126 ["Reveal Context" org-reveal t]
18127 ["Show All" show-all t]
18128 "--"
18129 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
18130 "--"
18131 ["New Heading" org-insert-heading t]
18132 ("Navigate Headings"
18133 ["Up" outline-up-heading t]
18134 ["Next" outline-next-visible-heading t]
18135 ["Previous" outline-previous-visible-heading t]
18136 ["Next Same Level" outline-forward-same-level t]
18137 ["Previous Same Level" outline-backward-same-level t]
18138 "--"
18139 ["Jump" org-goto t])
18140 ("Edit Structure"
18141 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
18142 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
18143 "--"
18144 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
18145 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
18146 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
18147 "--"
18148 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
18149 "--"
18150 ["Promote Heading" org-metaleft (not (org-at-table-p))]
18151 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
18152 ["Demote Heading" org-metaright (not (org-at-table-p))]
18153 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
18154 "--"
18155 ["Sort Region/Children" org-sort (not (org-at-table-p))]
18156 "--"
18157 ["Convert to odd levels" org-convert-to-odd-levels t]
18158 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
18159 ("Editing"
18160 ["Emphasis..." org-emphasize t]
18161 ["Edit Source Example" org-edit-special t]
18162 "--"
18163 ["Footnote new/jump" org-footnote-action t]
18164 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
18165 ("Archive"
18166 ["Archive (default method)" org-archive-subtree-default t]
18167 "--"
18168 ["Move Subtree to Archive file" org-advertized-archive-subtree t]
18169 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
18170 ["Move subtree to Archive sibling" org-archive-to-archive-sibling t]
18172 "--"
18173 ("Hyperlinks"
18174 ["Store Link (Global)" org-store-link t]
18175 ["Find existing link to here" org-occur-link-in-agenda-files t]
18176 ["Insert Link" org-insert-link t]
18177 ["Follow Link" org-open-at-point t]
18178 "--"
18179 ["Next link" org-next-link t]
18180 ["Previous link" org-previous-link t]
18181 "--"
18182 ["Descriptive Links"
18183 (progn (add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
18184 :style radio
18185 :selected (member '(org-link) buffer-invisibility-spec)]
18186 ["Literal Links"
18187 (progn
18188 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
18189 :style radio
18190 :selected (not (member '(org-link) buffer-invisibility-spec))])
18191 "--"
18192 ("TODO Lists"
18193 ["TODO/DONE/-" org-todo t]
18194 ("Select keyword"
18195 ["Next keyword" org-shiftright (org-on-heading-p)]
18196 ["Previous keyword" org-shiftleft (org-on-heading-p)]
18197 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
18198 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
18199 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
18200 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
18201 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
18202 "--"
18203 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
18204 :selected org-enforce-todo-dependencies :style toggle :active t]
18205 "Settings for tree at point"
18206 ["Do Children sequentially" org-toggle-ordered-property :style radio
18207 :selected (org-entry-get nil "ORDERED")
18208 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
18209 ["Do Children parallel" org-toggle-ordered-property :style radio
18210 :selected (not (org-entry-get nil "ORDERED"))
18211 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
18212 "--"
18213 ["Set Priority" org-priority t]
18214 ["Priority Up" org-shiftup t]
18215 ["Priority Down" org-shiftdown t]
18216 "--"
18217 ["Get news from all feeds" org-feed-update-all t]
18218 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
18219 ["Customize feeds" (customize-variable 'org-feed-alist) t])
18220 ("TAGS and Properties"
18221 ["Set Tags" org-set-tags-command t]
18222 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
18223 "--"
18224 ["Set property" org-set-property t]
18225 ["Column view of properties" org-columns t]
18226 ["Insert Column View DBlock" org-insert-columns-dblock t])
18227 ("Dates and Scheduling"
18228 ["Timestamp" org-time-stamp t]
18229 ["Timestamp (inactive)" org-time-stamp-inactive t]
18230 ("Change Date"
18231 ["1 Day Later" org-shiftright t]
18232 ["1 Day Earlier" org-shiftleft t]
18233 ["1 ... Later" org-shiftup t]
18234 ["1 ... Earlier" org-shiftdown t])
18235 ["Compute Time Range" org-evaluate-time-range t]
18236 ["Schedule Item" org-schedule t]
18237 ["Deadline" org-deadline t]
18238 "--"
18239 ["Custom time format" org-toggle-time-stamp-overlays
18240 :style radio :selected org-display-custom-times]
18241 "--"
18242 ["Goto Calendar" org-goto-calendar t]
18243 ["Date from Calendar" org-date-from-calendar t]
18244 "--"
18245 ["Start/Restart Timer" org-timer-start t]
18246 ["Pause/Continue Timer" org-timer-pause-or-continue t]
18247 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
18248 ["Insert Timer String" org-timer t]
18249 ["Insert Timer Item" org-timer-item t])
18250 ("Logging work"
18251 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
18252 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
18253 ["Clock out" org-clock-out t]
18254 ["Clock cancel" org-clock-cancel t]
18255 "--"
18256 ["Mark as default task" org-clock-mark-default-task t]
18257 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
18258 ["Goto running clock" org-clock-goto t]
18259 "--"
18260 ["Display times" org-clock-display t]
18261 ["Create clock table" org-clock-report t]
18262 "--"
18263 ["Record DONE time"
18264 (progn (setq org-log-done (not org-log-done))
18265 (message "Switching to %s will %s record a timestamp"
18266 (car org-done-keywords)
18267 (if org-log-done "automatically" "not")))
18268 :style toggle :selected org-log-done])
18269 "--"
18270 ["Agenda Command..." org-agenda t]
18271 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
18272 ("File List for Agenda")
18273 ("Special views current file"
18274 ["TODO Tree" org-show-todo-tree t]
18275 ["Check Deadlines" org-check-deadlines t]
18276 ["Timeline" org-timeline t]
18277 ["Tags/Property tree" org-match-sparse-tree t])
18278 "--"
18279 ["Export/Publish..." org-export t]
18280 ("LaTeX"
18281 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
18282 :selected org-cdlatex-mode]
18283 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
18284 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
18285 ["Modify math symbol" org-cdlatex-math-modify
18286 (org-inside-LaTeX-fragment-p)]
18287 ["Insert citation" org-reftex-citation t]
18288 "--"
18289 ["Template for BEAMER" org-insert-beamer-options-template t])
18290 "--"
18291 ("MobileOrg"
18292 ["Push Files and Views" org-mobile-push t]
18293 ["Get Captured and Flagged" org-mobile-pull t]
18294 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
18295 "--"
18296 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
18297 "--"
18298 ("Documentation"
18299 ["Show Version" org-version t]
18300 ["Info Documentation" org-info t])
18301 ("Customize"
18302 ["Browse Org Group" org-customize t]
18303 "--"
18304 ["Expand This Menu" org-create-customize-menu
18305 (fboundp 'customize-menu-create)])
18306 ["Send bug report" org-submit-bug-report t]
18307 "--"
18308 ("Refresh/Reload"
18309 ["Refresh setup current buffer" org-mode-restart t]
18310 ["Reload Org (after update)" org-reload t]
18311 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
18314 (defun org-info (&optional node)
18315 "Read documentation for Org-mode in the info system.
18316 With optional NODE, go directly to that node."
18317 (interactive)
18318 (info (format "(org)%s" (or node ""))))
18320 ;;;###autoload
18321 (defun org-submit-bug-report ()
18322 "Submit a bug report on Org-mode via mail.
18324 Don't hesitate to report any problems or inaccurate documentation.
18326 If you don't have setup sending mail from (X)Emacs, please copy the
18327 output buffer into your mail program, as it gives us important
18328 information about your Org-mode version and configuration."
18329 (interactive)
18330 (require 'reporter)
18331 (org-load-modules-maybe)
18332 (org-require-autoloaded-modules)
18333 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
18334 (reporter-submit-bug-report
18335 "emacs-orgmode@gnu.org"
18336 (org-version)
18337 (let (list)
18338 (save-window-excursion
18339 (switch-to-buffer (get-buffer-create "*Warn about privacy*"))
18340 (delete-other-windows)
18341 (erase-buffer)
18342 (insert "You are about to submit a bug report to the Org-mode mailing list.
18344 We would like to add your full Org-mode and Outline configuration to the
18345 bug report. This greatly simplifies the work of the maintainer and
18346 other experts on the mailing list.
18348 HOWEVER, some variables you have customized may contain private
18349 information. The names of customers, colleagues, or friends, might
18350 appear in the form of file names, tags, todo states, or search strings.
18351 If you answer yes to the prompt, you might want to check and remove
18352 such private information before sending the email.")
18353 (add-text-properties (point-min) (point-max) '(face org-warning))
18354 (when (yes-or-no-p "Include your Org-mode configuration ")
18355 (mapatoms
18356 (lambda (v)
18357 (and (boundp v)
18358 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
18359 (or (and (symbol-value v)
18360 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
18361 (and
18362 (get v 'custom-type) (get v 'standard-value)
18363 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
18364 (push v list)))))
18365 (kill-buffer (get-buffer "*Warn about privacy*"))
18366 list))
18367 nil nil
18368 "Remember to cover the basics, that is, what you expected to happen and
18369 what in fact did happen. You don't know how to make a good report? See
18371 http://orgmode.org/manual/Feedback.html#Feedback
18373 Your bug report will be posted to the Org-mode mailing list.
18374 ------------------------------------------------------------------------")
18375 (save-excursion
18376 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
18377 (replace-match "\\1Bug: \\3 [\\2]")))))
18380 (defun org-install-agenda-files-menu ()
18381 (let ((bl (buffer-list)))
18382 (save-excursion
18383 (while bl
18384 (set-buffer (pop bl))
18385 (if (org-mode-p) (setq bl nil)))
18386 (when (org-mode-p)
18387 (easy-menu-change
18388 '("Org") "File List for Agenda"
18389 (append
18390 (list
18391 ["Edit File List" (org-edit-agenda-file-list) t]
18392 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
18393 ["Remove Current File from List" org-remove-file t]
18394 ["Cycle through agenda files" org-cycle-agenda-files t]
18395 ["Occur in all agenda files" org-occur-in-agenda-files t]
18396 "--")
18397 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
18399 ;;;; Documentation
18401 ;;;###autoload
18402 (defun org-require-autoloaded-modules ()
18403 (interactive)
18404 (mapc 'require
18405 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
18406 org-docbook org-exp org-html org-icalendar
18407 org-id org-latex
18408 org-publish org-remember org-table
18409 org-timer org-xoxo)))
18411 ;;;###autoload
18412 (defun org-reload (&optional uncompiled)
18413 "Reload all org lisp files.
18414 With prefix arg UNCOMPILED, load the uncompiled versions."
18415 (interactive "P")
18416 (require 'find-func)
18417 (let* ((file-re "^\\(org\\|orgtbl\\)\\(\\.el\\|-.*\\.el\\)")
18418 (dir-org (file-name-directory (org-find-library-name "org")))
18419 (dir-org-contrib (ignore-errors
18420 (file-name-directory
18421 (org-find-library-name "org-contribdir"))))
18422 (babel-files
18423 (mapcar (lambda (el) (concat "ob" (when el (format "-%s" el)) ".el"))
18424 (append (list nil "comint" "eval" "exp" "keys"
18425 "lob" "ref" "table" "tangle")
18426 (delq nil
18427 (mapcar
18428 (lambda (lang)
18429 (when (cdr lang) (symbol-name (car lang))))
18430 org-babel-load-languages)))))
18431 (files
18432 (append (directory-files dir-org t file-re)
18433 babel-files
18434 (and dir-org-contrib
18435 (directory-files dir-org-contrib t file-re))))
18436 (remove-re (concat (if (featurep 'xemacs)
18437 "org-colview" "org-colview-xemacs")
18438 "\\'")))
18439 (setq files (mapcar 'file-name-sans-extension files))
18440 (setq files (mapcar
18441 (lambda (x) (if (string-match remove-re x) nil x))
18442 files))
18443 (setq files (delq nil files))
18444 (mapc
18445 (lambda (f)
18446 (when (featurep (intern (file-name-nondirectory f)))
18447 (if (and (not uncompiled)
18448 (file-exists-p (concat f ".elc")))
18449 (load (concat f ".elc") nil nil t)
18450 (load (concat f ".el") nil nil t))))
18451 files))
18452 (org-version))
18454 ;;;###autoload
18455 (defun org-customize ()
18456 "Call the customize function with org as argument."
18457 (interactive)
18458 (org-load-modules-maybe)
18459 (org-require-autoloaded-modules)
18460 (customize-browse 'org))
18462 (defun org-create-customize-menu ()
18463 "Create a full customization menu for Org-mode, insert it into the menu."
18464 (interactive)
18465 (org-load-modules-maybe)
18466 (org-require-autoloaded-modules)
18467 (if (fboundp 'customize-menu-create)
18468 (progn
18469 (easy-menu-change
18470 '("Org") "Customize"
18471 `(["Browse Org group" org-customize t]
18472 "--"
18473 ,(customize-menu-create 'org)
18474 ["Set" Custom-set t]
18475 ["Save" Custom-save t]
18476 ["Reset to Current" Custom-reset-current t]
18477 ["Reset to Saved" Custom-reset-saved t]
18478 ["Reset to Standard Settings" Custom-reset-standard t]))
18479 (message "\"Org\"-menu now contains full customization menu"))
18480 (error "Cannot expand menu (outdated version of cus-edit.el)")))
18482 ;;;; Miscellaneous stuff
18484 ;;; Generally useful functions
18486 (defun org-get-at-bol (property)
18487 "Get text property PROPERTY at beginning of line."
18488 (get-text-property (point-at-bol) property))
18490 (defun org-find-text-property-in-string (prop s)
18491 "Return the first non-nil value of property PROP in string S."
18492 (or (get-text-property 0 prop s)
18493 (get-text-property (or (next-single-property-change 0 prop s) 0)
18494 prop s)))
18496 (defun org-display-warning (message) ;; Copied from Emacs-Muse
18497 "Display the given MESSAGE as a warning."
18498 (if (fboundp 'display-warning)
18499 (display-warning 'org message
18500 (if (featurep 'xemacs) 'warning :warning))
18501 (let ((buf (get-buffer-create "*Org warnings*")))
18502 (with-current-buffer buf
18503 (goto-char (point-max))
18504 (insert "Warning (Org): " message)
18505 (unless (bolp)
18506 (newline)))
18507 (display-buffer buf)
18508 (sit-for 0))))
18510 (defun org-eval (form)
18511 "Eval FORM and return result."
18512 (condition-case error
18513 (eval form)
18514 (error (format "%%![Error: %s]" error))))
18516 (defun org-in-commented-line ()
18517 "Is point in a line starting with `#'?"
18518 (equal (char-after (point-at-bol)) ?#))
18520 (defun org-in-indented-comment-line ()
18521 "Is point in a line starting with `#' after some white space?"
18522 (save-excursion
18523 (save-match-data
18524 (goto-char (point-at-bol))
18525 (looking-at "[ \t]*#"))))
18527 (defun org-in-verbatim-emphasis ()
18528 (save-match-data
18529 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
18531 (defun org-goto-marker-or-bmk (marker &optional bookmark)
18532 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
18533 (if (and marker (marker-buffer marker)
18534 (buffer-live-p (marker-buffer marker)))
18535 (progn
18536 (switch-to-buffer (marker-buffer marker))
18537 (if (or (> marker (point-max)) (< marker (point-min)))
18538 (widen))
18539 (goto-char marker)
18540 (org-show-context 'org-goto))
18541 (if bookmark
18542 (bookmark-jump bookmark)
18543 (error "Cannot find location"))))
18545 (defun org-quote-csv-field (s)
18546 "Quote field for inclusion in CSV material."
18547 (if (string-match "[\",]" s)
18548 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
18551 (defun org-force-self-insert (N)
18552 "Needed to enforce self-insert under remapping."
18553 (interactive "p")
18554 (self-insert-command N))
18556 (defun org-string-width (s)
18557 "Compute width of string, ignoring invisible characters.
18558 This ignores character with invisibility property `org-link', and also
18559 characters with property `org-cwidth', because these will become invisible
18560 upon the next fontification round."
18561 (let (b l)
18562 (when (or (eq t buffer-invisibility-spec)
18563 (assq 'org-link buffer-invisibility-spec))
18564 (while (setq b (text-property-any 0 (length s)
18565 'invisible 'org-link s))
18566 (setq s (concat (substring s 0 b)
18567 (substring s (or (next-single-property-change
18568 b 'invisible s) (length s)))))))
18569 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
18570 (setq s (concat (substring s 0 b)
18571 (substring s (or (next-single-property-change
18572 b 'org-cwidth s) (length s))))))
18573 (setq l (string-width s) b -1)
18574 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
18575 (setq l (- l (get-text-property b 'org-dwidth-n s))))
18578 (defun org-shorten-string (s maxlength)
18579 "Shorten string S so tht it is no longer than MAXLENGTH characters.
18580 If the string is shorter or has length MAXLENGTH, just return the
18581 original string. If it is longer, the functions finds a space in the
18582 string, breaks this string off at that locations and adds three dots
18583 as ellipsis. Including the ellipsis, the string will not be longer
18584 than MAXLENGTH. If finding a good breaking point in the string does
18585 not work, the string is just chopped off in the middle of a word
18586 if necessary."
18587 (if (<= (length s) maxlength)
18589 (let* ((n (max (- maxlength 4) 1))
18590 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
18591 (if (string-match re s)
18592 (concat (match-string 1 s) "...")
18593 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
18595 (defun org-get-indentation (&optional line)
18596 "Get the indentation of the current line, interpreting tabs.
18597 When LINE is given, assume it represents a line and compute its indentation."
18598 (if line
18599 (if (string-match "^ *" (org-remove-tabs line))
18600 (match-end 0))
18601 (save-excursion
18602 (beginning-of-line 1)
18603 (skip-chars-forward " \t")
18604 (current-column))))
18606 (defun org-get-string-indentation (s)
18607 "What indentation has S due to SPACE and TAB at the beginning of the string?"
18608 (let ((n -1) (i 0) (w tab-width) c)
18609 (catch 'exit
18610 (while (< (setq n (1+ n)) (length s))
18611 (setq c (aref s n))
18612 (cond ((= c ?\ ) (setq i (1+ i)))
18613 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
18614 (t (throw 'exit t)))))
18617 (defun org-remove-tabs (s &optional width)
18618 "Replace tabulators in S with spaces.
18619 Assumes that s is a single line, starting in column 0."
18620 (setq width (or width tab-width))
18621 (while (string-match "\t" s)
18622 (setq s (replace-match
18623 (make-string
18624 (- (* width (/ (+ (match-beginning 0) width) width))
18625 (match-beginning 0)) ?\ )
18626 t t s)))
18629 (defun org-fix-indentation (line ind)
18630 "Fix indentation in LINE.
18631 IND is a cons cell with target and minimum indentation.
18632 If the current indentation in LINE is smaller than the minimum,
18633 leave it alone. If it is larger than ind, set it to the target."
18634 (let* ((l (org-remove-tabs line))
18635 (i (org-get-indentation l))
18636 (i1 (car ind)) (i2 (cdr ind)))
18637 (if (>= i i2) (setq l (substring line i2)))
18638 (if (> i1 0)
18639 (concat (make-string i1 ?\ ) l)
18640 l)))
18642 (defun org-remove-indentation (code &optional n)
18643 "Remove the maximum common indentation from the lines in CODE.
18644 N may optionally be the number of spaces to remove."
18645 (with-temp-buffer
18646 (insert code)
18647 (org-do-remove-indentation n)
18648 (buffer-string)))
18650 (defun org-do-remove-indentation (&optional n)
18651 "Remove the maximum common indentation from the buffer."
18652 (untabify (point-min) (point-max))
18653 (let ((min 10000) re)
18654 (if n
18655 (setq min n)
18656 (goto-char (point-min))
18657 (while (re-search-forward "^ *[^ \n]" nil t)
18658 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
18659 (unless (or (= min 0) (= min 10000))
18660 (setq re (format "^ \\{%d\\}" min))
18661 (goto-char (point-min))
18662 (while (re-search-forward re nil t)
18663 (replace-match "")
18664 (end-of-line 1))
18665 min)))
18667 (defun org-fill-template (template alist)
18668 "Find each %key of ALIST in TEMPLATE and replace it."
18669 (let ((case-fold-search nil)
18670 entry key value)
18671 (setq alist (sort (copy-sequence alist)
18672 (lambda (a b) (< (length (car a)) (length (car b))))))
18673 (while (setq entry (pop alist))
18674 (setq template
18675 (replace-regexp-in-string
18676 (concat "%" (regexp-quote (car entry)))
18677 (cdr entry) template t t)))
18678 template))
18680 (defun org-base-buffer (buffer)
18681 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
18682 (if (not buffer)
18683 buffer
18684 (or (buffer-base-buffer buffer)
18685 buffer)))
18687 (defun org-trim (s)
18688 "Remove whitespace at beginning and end of string."
18689 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
18690 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
18693 (defun org-wrap (string &optional width lines)
18694 "Wrap string to either a number of lines, or a width in characters.
18695 If WIDTH is non-nil, the string is wrapped to that width, however many lines
18696 that costs. If there is a word longer than WIDTH, the text is actually
18697 wrapped to the length of that word.
18698 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
18699 many lines, whatever width that takes.
18700 The return value is a list of lines, without newlines at the end."
18701 (let* ((words (org-split-string string "[ \t\n]+"))
18702 (maxword (apply 'max (mapcar 'org-string-width words)))
18703 w ll)
18704 (cond (width
18705 (org-do-wrap words (max maxword width)))
18706 (lines
18707 (setq w maxword)
18708 (setq ll (org-do-wrap words maxword))
18709 (if (<= (length ll) lines)
18711 (setq ll words)
18712 (while (> (length ll) lines)
18713 (setq w (1+ w))
18714 (setq ll (org-do-wrap words w)))
18715 ll))
18716 (t (error "Cannot wrap this")))))
18718 (defun org-do-wrap (words width)
18719 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
18720 (let (lines line)
18721 (while words
18722 (setq line (pop words))
18723 (while (and words (< (+ (length line) (length (car words))) width))
18724 (setq line (concat line " " (pop words))))
18725 (setq lines (push line lines)))
18726 (nreverse lines)))
18728 (defun org-split-string (string &optional separators)
18729 "Splits STRING into substrings at SEPARATORS.
18730 No empty strings are returned if there are matches at the beginning
18731 and end of string."
18732 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
18733 (start 0)
18734 notfirst
18735 (list nil))
18736 (while (and (string-match rexp string
18737 (if (and notfirst
18738 (= start (match-beginning 0))
18739 (< start (length string)))
18740 (1+ start) start))
18741 (< (match-beginning 0) (length string)))
18742 (setq notfirst t)
18743 (or (eq (match-beginning 0) 0)
18744 (and (eq (match-beginning 0) (match-end 0))
18745 (eq (match-beginning 0) start))
18746 (setq list
18747 (cons (substring string start (match-beginning 0))
18748 list)))
18749 (setq start (match-end 0)))
18750 (or (eq start (length string))
18751 (setq list
18752 (cons (substring string start)
18753 list)))
18754 (nreverse list)))
18756 (defun org-quote-vert (s)
18757 "Replace \"|\" with \"\\vert\"."
18758 (while (string-match "|" s)
18759 (setq s (replace-match "\\vert" t t s)))
18762 (defun org-uuidgen-p (s)
18763 "Is S an ID created by UUIDGEN?"
18764 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
18766 (defun org-context ()
18767 "Return a list of contexts of the current cursor position.
18768 If several contexts apply, all are returned.
18769 Each context entry is a list with a symbol naming the context, and
18770 two positions indicating start and end of the context. Possible
18771 contexts are:
18773 :headline anywhere in a headline
18774 :headline-stars on the leading stars in a headline
18775 :todo-keyword on a TODO keyword (including DONE) in a headline
18776 :tags on the TAGS in a headline
18777 :priority on the priority cookie in a headline
18778 :item on the first line of a plain list item
18779 :item-bullet on the bullet/number of a plain list item
18780 :checkbox on the checkbox in a plain list item
18781 :table in an org-mode table
18782 :table-special on a special filed in a table
18783 :table-table in a table.el table
18784 :link on a hyperlink
18785 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
18786 :target on a <<target>>
18787 :radio-target on a <<<radio-target>>>
18788 :latex-fragment on a LaTeX fragment
18789 :latex-preview on a LaTeX fragment with overlayed preview image
18791 This function expects the position to be visible because it uses font-lock
18792 faces as a help to recognize the following contexts: :table-special, :link,
18793 and :keyword."
18794 (let* ((f (get-text-property (point) 'face))
18795 (faces (if (listp f) f (list f)))
18796 (p (point)) clist o)
18797 ;; First the large context
18798 (cond
18799 ((org-on-heading-p t)
18800 (push (list :headline (point-at-bol) (point-at-eol)) clist)
18801 (when (progn
18802 (beginning-of-line 1)
18803 (looking-at org-todo-line-tags-regexp))
18804 (push (org-point-in-group p 1 :headline-stars) clist)
18805 (push (org-point-in-group p 2 :todo-keyword) clist)
18806 (push (org-point-in-group p 4 :tags) clist))
18807 (goto-char p)
18808 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
18809 (if (looking-at "\\[#[A-Z0-9]\\]")
18810 (push (org-point-in-group p 0 :priority) clist)))
18812 ((org-at-item-p)
18813 (push (org-point-in-group p 2 :item-bullet) clist)
18814 (push (list :item (point-at-bol)
18815 (save-excursion (org-end-of-item) (point)))
18816 clist)
18817 (and (org-at-item-checkbox-p)
18818 (push (org-point-in-group p 0 :checkbox) clist)))
18820 ((org-at-table-p)
18821 (push (list :table (org-table-begin) (org-table-end)) clist)
18822 (if (memq 'org-formula faces)
18823 (push (list :table-special
18824 (previous-single-property-change p 'face)
18825 (next-single-property-change p 'face)) clist)))
18826 ((org-at-table-p 'any)
18827 (push (list :table-table) clist)))
18828 (goto-char p)
18830 ;; Now the small context
18831 (cond
18832 ((org-at-timestamp-p)
18833 (push (org-point-in-group p 0 :timestamp) clist))
18834 ((memq 'org-link faces)
18835 (push (list :link
18836 (previous-single-property-change p 'face)
18837 (next-single-property-change p 'face)) clist))
18838 ((memq 'org-special-keyword faces)
18839 (push (list :keyword
18840 (previous-single-property-change p 'face)
18841 (next-single-property-change p 'face)) clist))
18842 ((org-on-target-p)
18843 (push (org-point-in-group p 0 :target) clist)
18844 (goto-char (1- (match-beginning 0)))
18845 (if (looking-at org-radio-target-regexp)
18846 (push (org-point-in-group p 0 :radio-target) clist))
18847 (goto-char p))
18848 ((setq o (car (delq nil
18849 (mapcar
18850 (lambda (x)
18851 (if (memq x org-latex-fragment-image-overlays) x))
18852 (overlays-at (point))))))
18853 (push (list :latex-fragment
18854 (overlay-start o) (overlay-end o)) clist)
18855 (push (list :latex-preview
18856 (overlay-start o) (overlay-end o)) clist))
18857 ((org-inside-LaTeX-fragment-p)
18858 ;; FIXME: positions wrong.
18859 (push (list :latex-fragment (point) (point)) clist)))
18861 (setq clist (nreverse (delq nil clist)))
18862 clist))
18864 ;; FIXME: Compare with at-regexp-p Do we need both?
18865 (defun org-in-regexp (re &optional nlines visually)
18866 "Check if point is inside a match of regexp.
18867 Normally only the current line is checked, but you can include NLINES extra
18868 lines both before and after point into the search.
18869 If VISUALLY is set, require that the cursor is not after the match but
18870 really on, so that the block visually is on the match."
18871 (catch 'exit
18872 (let ((pos (point))
18873 (eol (point-at-eol (+ 1 (or nlines 0))))
18874 (inc (if visually 1 0)))
18875 (save-excursion
18876 (beginning-of-line (- 1 (or nlines 0)))
18877 (while (re-search-forward re eol t)
18878 (if (and (<= (match-beginning 0) pos)
18879 (>= (+ inc (match-end 0)) pos))
18880 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
18882 (defun org-at-regexp-p (regexp)
18883 "Is point inside a match of REGEXP in the current line?"
18884 (catch 'exit
18885 (save-excursion
18886 (let ((pos (point)) (end (point-at-eol)))
18887 (beginning-of-line 1)
18888 (while (re-search-forward regexp end t)
18889 (if (and (<= (match-beginning 0) pos)
18890 (>= (match-end 0) pos))
18891 (throw 'exit t)))
18892 nil))))
18894 (defun org-in-regexps-block-p (start-re end-re &optional bound)
18895 "Return t if the current point is between matches of START-RE and END-RE.
18896 This will also return t if point is on one of the two matches or
18897 in an unfinished block. END-RE can be a string or a form
18898 returning a string.
18900 An optional third argument bounds the search for START-RE. It
18901 defaults to previous heading or `point-min'."
18902 (let ((pos (point))
18903 (limit (or bound (save-excursion (outline-previous-heading)))))
18904 (save-excursion
18905 ;; we're on a block when point is on start-re...
18906 (or (org-at-regexp-p start-re)
18907 ;; ... or start-re can be found above...
18908 (and (re-search-backward start-re limit t)
18909 ;; ... but no end-re between start-re and point.
18910 (not (re-search-forward (eval end-re) pos t)))))))
18912 (defun org-occur-in-agenda-files (regexp &optional nlines)
18913 "Call `multi-occur' with buffers for all agenda files."
18914 (interactive "sOrg-files matching: \np")
18915 (let* ((files (org-agenda-files))
18916 (tnames (mapcar 'file-truename files))
18917 (extra org-agenda-text-search-extra-files)
18919 (when (eq (car extra) 'agenda-archives)
18920 (setq extra (cdr extra))
18921 (setq files (org-add-archive-files files)))
18922 (while (setq f (pop extra))
18923 (unless (member (file-truename f) tnames)
18924 (add-to-list 'files f 'append)
18925 (add-to-list 'tnames (file-truename f) 'append)))
18926 (multi-occur
18927 (mapcar (lambda (x)
18928 (with-current-buffer
18929 (or (get-file-buffer x) (find-file-noselect x))
18930 (widen)
18931 (current-buffer)))
18932 files)
18933 regexp)))
18935 (if (boundp 'occur-mode-find-occurrence-hook)
18936 ;; Emacs 23
18937 (add-hook 'occur-mode-find-occurrence-hook
18938 (lambda ()
18939 (when (org-mode-p)
18940 (org-reveal))))
18941 ;; Emacs 22
18942 (defadvice occur-mode-goto-occurrence
18943 (after org-occur-reveal activate)
18944 (and (org-mode-p) (org-reveal)))
18945 (defadvice occur-mode-goto-occurrence-other-window
18946 (after org-occur-reveal activate)
18947 (and (org-mode-p) (org-reveal)))
18948 (defadvice occur-mode-display-occurrence
18949 (after org-occur-reveal activate)
18950 (when (org-mode-p)
18951 (let ((pos (occur-mode-find-occurrence)))
18952 (with-current-buffer (marker-buffer pos)
18953 (save-excursion
18954 (goto-char pos)
18955 (org-reveal)))))))
18957 (defun org-occur-link-in-agenda-files ()
18958 "Create a link and search for it in the agendas.
18959 The link is not stored in `org-stored-links', it is just created
18960 for the search purpose."
18961 (interactive)
18962 (let ((link (condition-case nil
18963 (org-store-link nil)
18964 (error "Unable to create a link to here"))))
18965 (org-occur-in-agenda-files (regexp-quote link))))
18967 (defun org-uniquify (list)
18968 "Remove duplicate elements from LIST."
18969 (let (res)
18970 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
18971 res))
18973 (defun org-delete-all (elts list)
18974 "Remove all elements in ELTS from LIST."
18975 (while elts
18976 (setq list (delete (pop elts) list)))
18977 list)
18979 (defun org-count (cl-item cl-seq)
18980 "Count the number of occurrences of ITEM in SEQ.
18981 Taken from `count' in cl-seq.el with all keyword arguments removed."
18982 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
18983 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
18984 (while (< cl-start cl-end)
18985 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
18986 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
18987 (setq cl-start (1+ cl-start)))
18988 cl-count))
18990 (defun org-remove-if (predicate seq)
18991 "Remove everything from SEQ that fulfills PREDICATE."
18992 (let (res e)
18993 (while seq
18994 (setq e (pop seq))
18995 (if (not (funcall predicate e)) (push e res)))
18996 (nreverse res)))
18998 (defun org-remove-if-not (predicate seq)
18999 "Remove everything from SEQ that does not fulfill PREDICATE."
19000 (let (res e)
19001 (while seq
19002 (setq e (pop seq))
19003 (if (funcall predicate e) (push e res)))
19004 (nreverse res)))
19006 (defun org-back-over-empty-lines ()
19007 "Move backwards over whitespace, to the beginning of the first empty line.
19008 Returns the number of empty lines passed."
19009 (let ((pos (point)))
19010 (if (cdr (assoc 'heading org-blank-before-new-entry))
19011 (skip-chars-backward " \t\n\r")
19012 (forward-line -1))
19013 (beginning-of-line 2)
19014 (goto-char (min (point) pos))
19015 (count-lines (point) pos)))
19017 (defun org-skip-whitespace ()
19018 (skip-chars-forward " \t\n\r"))
19020 (defun org-point-in-group (point group &optional context)
19021 "Check if POINT is in match-group GROUP.
19022 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
19023 match. If the match group does not exist or point is not inside it,
19024 return nil."
19025 (and (match-beginning group)
19026 (>= point (match-beginning group))
19027 (<= point (match-end group))
19028 (if context
19029 (list context (match-beginning group) (match-end group))
19030 t)))
19032 (defun org-switch-to-buffer-other-window (&rest args)
19033 "Switch to buffer in a second window on the current frame.
19034 In particular, do not allow pop-up frames.
19035 Returns the newly created buffer."
19036 (let (pop-up-frames special-display-buffer-names special-display-regexps
19037 special-display-function)
19038 (apply 'switch-to-buffer-other-window args)))
19040 (defun org-combine-plists (&rest plists)
19041 "Create a single property list from all plists in PLISTS.
19042 The process starts by copying the first list, and then setting properties
19043 from the other lists. Settings in the last list are the most significant
19044 ones and overrule settings in the other lists."
19045 (let ((rtn (copy-sequence (pop plists)))
19046 p v ls)
19047 (while plists
19048 (setq ls (pop plists))
19049 (while ls
19050 (setq p (pop ls) v (pop ls))
19051 (setq rtn (plist-put rtn p v))))
19052 rtn))
19054 (defun org-move-line-down (arg)
19055 "Move the current line down. With prefix argument, move it past ARG lines."
19056 (interactive "p")
19057 (let ((col (current-column))
19058 beg end pos)
19059 (beginning-of-line 1) (setq beg (point))
19060 (beginning-of-line 2) (setq end (point))
19061 (beginning-of-line (+ 1 arg))
19062 (setq pos (move-marker (make-marker) (point)))
19063 (insert (delete-and-extract-region beg end))
19064 (goto-char pos)
19065 (org-move-to-column col)))
19067 (defun org-move-line-up (arg)
19068 "Move the current line up. With prefix argument, move it past ARG lines."
19069 (interactive "p")
19070 (let ((col (current-column))
19071 beg end pos)
19072 (beginning-of-line 1) (setq beg (point))
19073 (beginning-of-line 2) (setq end (point))
19074 (beginning-of-line (- arg))
19075 (setq pos (move-marker (make-marker) (point)))
19076 (insert (delete-and-extract-region beg end))
19077 (goto-char pos)
19078 (org-move-to-column col)))
19080 (defun org-replace-escapes (string table)
19081 "Replace %-escapes in STRING with values in TABLE.
19082 TABLE is an association list with keys like \"%a\" and string values.
19083 The sequences in STRING may contain normal field width and padding information,
19084 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
19085 so values can contain further %-escapes if they are define later in TABLE."
19086 (let ((tbl (copy-alist table))
19087 (case-fold-search nil)
19088 (pchg 0)
19089 e re rpl)
19090 (while (setq e (pop tbl))
19091 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
19092 (when (and (cdr e) (string-match re (cdr e)))
19093 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
19094 (safe "SREF"))
19095 (add-text-properties 0 3 (list 'sref sref) safe)
19096 (setcdr e (replace-match safe t t (cdr e)))))
19097 (while (string-match re string)
19098 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
19099 (cdr e)))
19100 (setq string (replace-match rpl t t string))))
19101 (while (setq pchg (next-property-change pchg string))
19102 (let ((sref (get-text-property pchg 'sref string)))
19103 (when (and sref (string-match "SREF" string pchg))
19104 (setq string (replace-match sref t t string)))))
19105 string))
19107 (defun org-sublist (list start end)
19108 "Return a section of LIST, from START to END.
19109 Counting starts at 1."
19110 (let (rtn (c start))
19111 (setq list (nthcdr (1- start) list))
19112 (while (and list (<= c end))
19113 (push (pop list) rtn)
19114 (setq c (1+ c)))
19115 (nreverse rtn)))
19117 (defun org-find-base-buffer-visiting (file)
19118 "Like `find-buffer-visiting' but always return the base buffer and
19119 not an indirect buffer."
19120 (let ((buf (or (get-file-buffer file)
19121 (find-buffer-visiting file))))
19122 (if buf
19123 (or (buffer-base-buffer buf) buf)
19124 nil)))
19126 (defun org-image-file-name-regexp (&optional extensions)
19127 "Return regexp matching the file names of images.
19128 If EXTENSIONS is given, only match these."
19129 (if (and (not extensions) (fboundp 'image-file-name-regexp))
19130 (image-file-name-regexp)
19131 (let ((image-file-name-extensions
19132 (or extensions
19133 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
19134 "xbm" "xpm" "pbm" "pgm" "ppm"))))
19135 (concat "\\."
19136 (regexp-opt (nconc (mapcar 'upcase
19137 image-file-name-extensions)
19138 image-file-name-extensions)
19140 "\\'"))))
19142 (defun org-file-image-p (file &optional extensions)
19143 "Return non-nil if FILE is an image."
19144 (save-match-data
19145 (string-match (org-image-file-name-regexp extensions) file)))
19147 (defun org-get-cursor-date ()
19148 "Return the date at cursor in as a time.
19149 This works in the calendar and in the agenda, anywhere else it just
19150 returns the current time."
19151 (let (date day defd)
19152 (cond
19153 ((eq major-mode 'calendar-mode)
19154 (setq date (calendar-cursor-to-date)
19155 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
19156 ((eq major-mode 'org-agenda-mode)
19157 (setq day (get-text-property (point) 'day))
19158 (if day
19159 (setq date (calendar-gregorian-from-absolute day)
19160 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
19161 (nth 2 date))))))
19162 (or defd (current-time))))
19164 (defvar org-agenda-action-marker (make-marker)
19165 "Marker pointing to the entry for the next agenda action.")
19167 (defun org-mark-entry-for-agenda-action ()
19168 "Mark the current entry as target of an agenda action.
19169 Agenda actions are actions executed from the agenda with the key `k',
19170 which make use of the date at the cursor."
19171 (interactive)
19172 (move-marker org-agenda-action-marker
19173 (save-excursion (org-back-to-heading t) (point))
19174 (current-buffer))
19175 (message
19176 "Entry marked for action; press `k' at desired date in agenda or calendar"))
19178 (defun org-mark-subtree ()
19179 "Mark the current subtree.
19180 This puts point at the start of the current subtree, and mark at the end.
19182 If point is in an inline task, mark that task instead."
19183 (interactive)
19184 (let ((inline-task-p
19185 (and (featurep 'org-inlinetask)
19186 (org-inlinetask-in-task-p)))
19187 (beg))
19188 ;; Get beginning of subtree
19189 (cond
19190 (inline-task-p (org-inlinetask-goto-beginning))
19191 ((org-at-heading-p) (beginning-of-line))
19192 (t (org-with-limited-levels (outline-previous-visible-heading 1))))
19193 (setq beg (point))
19194 ;; Get end of it
19195 (if inline-task-p
19196 (org-inlinetask-goto-end)
19197 (org-end-of-subtree))
19198 ;; Mark zone
19199 (push-mark (point) nil t)
19200 (goto-char beg)))
19202 ;;; Paragraph filling stuff.
19203 ;; We want this to be just right, so use the full arsenal.
19205 (defun org-indent-line-function ()
19206 "Indent line depending on context."
19207 (interactive)
19208 (let* ((pos (point))
19209 (itemp (org-at-item-p))
19210 (case-fold-search t)
19211 (org-drawer-regexp (or org-drawer-regexp "\000"))
19212 (inline-task-p (and (featurep 'org-inlinetask)
19213 (org-inlinetask-in-task-p)))
19214 (inline-re (and inline-task-p
19215 (org-inlinetask-outline-regexp)))
19216 column)
19217 (beginning-of-line 1)
19218 (cond
19219 ;; Comments
19220 ((looking-at "# ") (setq column 0))
19221 ;; Headings
19222 ((looking-at "\\*+ ") (setq column 0))
19223 ;; Included files
19224 ((looking-at "#\\+include:") (setq column 0))
19225 ;; Footnote definition
19226 ((looking-at org-footnote-definition-re) (setq column 0))
19227 ;; Literal examples
19228 ((looking-at "[ \t]*:[ \t]")
19229 (setq column (org-get-indentation))) ; do nothing
19230 ;; Lists
19231 ((ignore-errors (goto-char (org-in-item-p)))
19232 (setq column (if itemp
19233 (org-get-indentation)
19234 (org-list-item-body-column (point))))
19235 (goto-char pos))
19236 ;; Drawers
19237 ((and (looking-at "[ \t]*:END:")
19238 (save-excursion (re-search-backward org-drawer-regexp nil t)))
19239 (save-excursion
19240 (goto-char (1- (match-beginning 1)))
19241 (setq column (current-column))))
19242 ;; Special blocks
19243 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
19244 (save-excursion
19245 (re-search-backward
19246 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
19247 (setq column (org-get-indentation (match-string 0))))
19248 ((and (not (looking-at "[ \t]*#\\+begin_"))
19249 (org-in-regexps-block-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
19250 (save-excursion
19251 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
19252 (setq column
19253 (if (equal (downcase (match-string 1)) "src")
19254 ;; src blocks: let `org-edit-src-exit' handle them
19255 (org-get-indentation)
19256 (org-get-indentation (match-string 0)))))
19257 ;; This line has nothing special, look at the previous relevant
19258 ;; line to compute indentation
19260 (beginning-of-line 0)
19261 (while (and (not (bobp))
19262 (not (looking-at org-drawer-regexp))
19263 ;; When point started in an inline task, do not move
19264 ;; above task starting line.
19265 (not (and inline-task-p (looking-at inline-re)))
19266 ;; Skip drawers, blocks, empty lines, verbatim,
19267 ;; comments, tables, footnotes definitions, lists,
19268 ;; inline tasks.
19269 (or (and (looking-at "[ \t]*:END:")
19270 (re-search-backward org-drawer-regexp nil t))
19271 (and (looking-at "[ \t]*#\\+end_")
19272 (re-search-backward "[ \t]*#\\+begin_"nil t))
19273 (looking-at "[ \t]*[\n:#|]")
19274 (looking-at org-footnote-definition-re)
19275 (and (ignore-errors (goto-char (org-in-item-p)))
19276 (goto-char
19277 (org-list-get-top-point (org-list-struct))))
19278 (and (not inline-task-p)
19279 (featurep 'org-inlinetask)
19280 (org-inlinetask-in-task-p)
19281 (or (org-inlinetask-goto-beginning) t))))
19282 (beginning-of-line 0))
19283 (cond
19284 ;; There was an heading above.
19285 ((looking-at "\\*+[ \t]+")
19286 (if (not org-adapt-indentation)
19287 (setq column 0)
19288 (goto-char (match-end 0))
19289 (setq column (current-column))))
19290 ;; A drawer had started and is unfinished
19291 ((looking-at org-drawer-regexp)
19292 (goto-char (1- (match-beginning 1)))
19293 (setq column (current-column)))
19294 ;; Else, nothing noticeable found: get indentation and go on.
19295 (t (setq column (org-get-indentation))))))
19296 ;; Now apply indentation and move cursor accordingly
19297 (goto-char pos)
19298 (if (<= (current-column) (current-indentation))
19299 (org-indent-line-to column)
19300 (save-excursion (org-indent-line-to column)))
19301 ;; Special polishing for properties, see `org-property-format'
19302 (setq column (current-column))
19303 (beginning-of-line 1)
19304 (if (looking-at
19305 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
19306 (replace-match (concat (match-string 1)
19307 (format org-property-format
19308 (match-string 2) (match-string 3)))
19309 t t))
19310 (org-move-to-column column)))
19312 (defvar org-adaptive-fill-regexp-backup adaptive-fill-regexp
19313 "Variable to store copy of `adaptive-fill-regexp'.
19314 Since `adaptive-fill-regexp' is set to never match, we need to
19315 store a backup of its value before entering `org-mode' so that
19316 the functionality can be provided as a fall-back.")
19318 (defun org-set-autofill-regexps ()
19319 (interactive)
19320 ;; In the paragraph separator we include headlines, because filling
19321 ;; text in a line directly attached to a headline would otherwise
19322 ;; fill the headline as well.
19323 (org-set-local 'comment-start-skip "^#+[ \t]*")
19324 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|#]")
19325 ;; The paragraph starter includes hand-formatted lists.
19326 (org-set-local
19327 'paragraph-start
19328 (concat
19329 "\f" "\\|"
19330 "[ ]*$" "\\|"
19331 "\\*+ " "\\|"
19332 "[ \t]*#" "\\|"
19333 (org-item-re) "\\|"
19334 "[ \t]*[:|]" "\\|"
19335 "\\$\\$" "\\|"
19336 "\\\\\\(begin\\|end\\|[][]\\)"))
19337 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
19338 ;; But only if the user has not turned off tables or fixed-width regions
19339 (org-set-local
19340 'auto-fill-inhibit-regexp
19341 (concat "\\*+ \\|#\\+"
19342 "\\|[ \t]*" org-keyword-time-regexp
19343 (if (or org-enable-table-editor org-enable-fixed-width-editor)
19344 (concat
19345 "\\|[ \t]*["
19346 (if org-enable-table-editor "|" "")
19347 (if org-enable-fixed-width-editor ":" "")
19348 "]"))))
19349 ;; We use our own fill-paragraph function, to make sure that tables
19350 ;; and fixed-width regions are not wrapped. That function will pass
19351 ;; through to `fill-paragraph' when appropriate.
19352 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
19353 ;; Prevent auto-fill from inserting unwanted new items.
19354 (org-set-local 'fill-nobreak-predicate
19355 (if (memq 'org-fill-item-nobreak-p fill-nobreak-predicate)
19356 fill-nobreak-predicate
19357 (cons 'org-fill-item-nobreak-p fill-nobreak-predicate)))
19358 ;; Adaptive filling: To get full control, first make sure that
19359 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
19360 (unless (local-variable-p 'adaptive-fill-regexp (current-buffer))
19361 (org-set-local 'org-adaptive-fill-regexp-backup
19362 adaptive-fill-regexp))
19363 (org-set-local 'adaptive-fill-regexp "\000")
19364 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
19365 (org-set-local 'adaptive-fill-function
19366 'org-adaptive-fill-function)
19367 (org-set-local
19368 'align-mode-rules-list
19369 '((org-in-buffer-settings
19370 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
19371 (modes . '(org-mode))))))
19373 (defun org-fill-item-nobreak-p ()
19374 "Non-nil when a line break at point would insert a new item."
19375 (and (looking-at (org-item-re)) (org-list-in-valid-context-p)))
19377 (defun org-fill-paragraph (&optional justify)
19378 "Re-align a table, pass through to fill-paragraph if no table."
19379 (let ((table-p (org-at-table-p))
19380 (table.el-p (org-at-table.el-p))
19381 (itemp (org-in-item-p)))
19382 (cond ((and (equal (char-after (point-at-bol)) ?*)
19383 (save-excursion (goto-char (point-at-bol))
19384 (looking-at outline-regexp)))
19385 t) ; skip headlines
19386 (table.el-p t) ; skip table.el tables
19387 (table-p (org-table-align) t) ; align Org tables
19388 (itemp ; align text in items
19389 (let* ((struct (save-excursion (goto-char itemp)
19390 (org-list-struct)))
19391 (parents (org-list-parents-alist struct))
19392 (children (org-list-get-children itemp struct parents))
19393 beg end prev next prefix)
19394 ;; Determine in which part of item point is: before
19395 ;; first child, after last child, between two
19396 ;; sub-lists, or simply in item if there's no child.
19397 (cond
19398 ((not children)
19399 (setq prefix (make-string (org-list-item-body-column itemp) ?\ )
19400 beg itemp
19401 end (org-list-get-item-end itemp struct)))
19402 ((< (point) (setq next (car children)))
19403 (setq prefix (make-string (org-list-item-body-column itemp) ?\ )
19404 beg itemp
19405 end next))
19406 ((> (point) (setq prev (car (last children))))
19407 (setq beg (org-list-get-item-end prev struct)
19408 end (org-list-get-item-end itemp struct)
19409 prefix (save-excursion
19410 (goto-char beg)
19411 (skip-chars-forward " \t")
19412 (make-string (current-column) ?\ ))))
19413 (t (catch 'exit
19414 (while (setq next (pop children))
19415 (if (> (point) next)
19416 (setq prev next)
19417 (setq beg (org-list-get-item-end prev struct)
19418 end next
19419 prefix (save-excursion
19420 (goto-char beg)
19421 (skip-chars-forward " \t")
19422 (make-string (current-column) ?\ )))
19423 (throw 'exit nil))))))
19424 ;; Use `fill-paragraph' with buffer narrowed to item
19425 ;; without any child, and with our computed PREFIX.
19426 (flet ((fill-context-prefix (from to &optional flr) prefix))
19427 (save-restriction
19428 (narrow-to-region beg end)
19429 (save-excursion (fill-paragraph justify)))) t))
19430 ;; Special case where point is not in a list but is on
19431 ;; a paragraph adjacent to a list: make sure this paragraph
19432 ;; doesn't get merged with the end of the list by narrowing
19433 ;; buffer first.
19434 ((save-excursion (forward-paragraph -1)
19435 (setq itemp (org-in-item-p)))
19436 (let ((struct (save-excursion (goto-char itemp)
19437 (org-list-struct))))
19438 (save-restriction
19439 (narrow-to-region (org-list-get-bottom-point struct)
19440 (save-excursion (forward-paragraph 1)
19441 (point)))
19442 (fill-paragraph justify) t)))
19443 ;; Else simply call `fill-paragraph'.
19444 (t nil))))
19446 ;; For reference, this is the default value of adaptive-fill-regexp
19447 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
19449 (defun org-adaptive-fill-function ()
19450 "Return a fill prefix for org-mode files."
19451 (let (itemp)
19452 (save-excursion
19453 (cond
19454 ;; Comment line
19455 ((looking-at "#[ \t]+")
19456 (match-string-no-properties 0))
19457 ;; Plain list item
19458 ((org-at-item-p)
19459 (make-string (org-list-item-body-column (point-at-bol)) ?\ ))
19460 ;; Point is in a list after `backward-paragraph': original
19461 ;; point wasn't in the list, or filling would have been taken
19462 ;; care of by `org-auto-fill-function', but the list and the
19463 ;; real paragraph are not separated by a blank line. Thus, move
19464 ;; point after the list to go back to real paragraph and
19465 ;; determine fill-prefix.
19466 ((setq itemp (org-in-item-p))
19467 (goto-char itemp)
19468 (let* ((struct (org-list-struct))
19469 (bottom (org-list-get-bottom-point struct)))
19470 (goto-char bottom)
19471 (make-string (org-get-indentation) ?\ )))
19472 ;; Other text
19473 ((looking-at org-adaptive-fill-regexp-backup)
19474 (match-string-no-properties 0))))))
19476 (defun org-auto-fill-function ()
19477 "Auto-fill function."
19478 (let (itemp prefix)
19479 ;; When in a list, compute an appropriate fill-prefix and make
19480 ;; sure it will be used by `do-auto-fill'.
19481 (if (setq itemp (org-in-item-p))
19482 (progn
19483 (setq prefix (make-string (org-list-item-body-column itemp) ?\ ))
19484 (flet ((fill-context-prefix (from to &optional flr) prefix))
19485 (do-auto-fill)))
19486 ;; Else just use `do-auto-fill'.
19487 (do-auto-fill))))
19489 ;;; Other stuff.
19491 (defun org-toggle-fixed-width-section (arg)
19492 "Toggle the fixed-width export.
19493 If there is no active region, the QUOTE keyword at the current headline is
19494 inserted or removed. When present, it causes the text between this headline
19495 and the next to be exported as fixed-width text, and unmodified.
19496 If there is an active region, this command adds or removes a colon as the
19497 first character of this line. If the first character of a line is a colon,
19498 this line is also exported in fixed-width font."
19499 (interactive "P")
19500 (let* ((cc 0)
19501 (regionp (org-region-active-p))
19502 (beg (if regionp (region-beginning) (point)))
19503 (end (if regionp (region-end)))
19504 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
19505 (case-fold-search nil)
19506 (re "[ \t]*\\(: \\)")
19507 off)
19508 (if regionp
19509 (save-excursion
19510 (goto-char beg)
19511 (setq cc (current-column))
19512 (beginning-of-line 1)
19513 (setq off (looking-at re))
19514 (while (> nlines 0)
19515 (setq nlines (1- nlines))
19516 (beginning-of-line 1)
19517 (cond
19518 (arg
19519 (org-move-to-column cc t)
19520 (insert ": \n")
19521 (forward-line -1))
19522 ((and off (looking-at re))
19523 (replace-match "" t t nil 1))
19524 ((not off) (org-move-to-column cc t) (insert ": ")))
19525 (forward-line 1)))
19526 (save-excursion
19527 (org-back-to-heading)
19528 (if (looking-at (concat outline-regexp
19529 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
19530 (replace-match "" t t nil 1)
19531 (if (looking-at outline-regexp)
19532 (progn
19533 (goto-char (match-end 0))
19534 (insert org-quote-string " "))))))))
19536 (defun org-reftex-citation ()
19537 "Use reftex-citation to insert a citation into the buffer.
19538 This looks for a line like
19540 #+BIBLIOGRAPHY: foo plain option:-d
19542 and derives from it that foo.bib is the bibliography file relevant
19543 for this document. It then installs the necessary environment for RefTeX
19544 to work in this buffer and calls `reftex-citation' to insert a citation
19545 into the buffer.
19547 Export of such citations to both LaTeX and HTML is handled by the contributed
19548 package org-exp-bibtex by Taru Karttunen."
19549 (interactive)
19550 (let ((reftex-docstruct-symbol 'rds)
19551 (reftex-cite-format "\\cite{%l}")
19552 rds bib)
19553 (save-excursion
19554 (save-restriction
19555 (widen)
19556 (let ((case-fold-search t)
19557 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
19558 (if (not (save-excursion
19559 (or (re-search-forward re nil t)
19560 (re-search-backward re nil t))))
19561 (error "No bibliography defined in file")
19562 (setq bib (concat (match-string 1) ".bib")
19563 rds (list (list 'bib bib)))))))
19564 (call-interactively 'reftex-citation)))
19566 ;;;; Functions extending outline functionality
19568 (defun org-beginning-of-line (&optional arg)
19569 "Go to the beginning of the current line. If that is invisible, continue
19570 to a visible line beginning. This makes the function of C-a more intuitive.
19571 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
19572 first attempt, and only move to after the tags when the cursor is already
19573 beyond the end of the headline."
19574 (interactive "P")
19575 (let ((pos (point))
19576 (special (if (consp org-special-ctrl-a/e)
19577 (car org-special-ctrl-a/e)
19578 org-special-ctrl-a/e))
19579 refpos)
19580 (if (org-bound-and-true-p line-move-visual)
19581 (beginning-of-visual-line 1)
19582 (beginning-of-line 1))
19583 (if (and arg (fboundp 'move-beginning-of-line))
19584 (call-interactively 'move-beginning-of-line)
19585 (if (bobp)
19587 (backward-char 1)
19588 (if (org-truely-invisible-p)
19589 (while (and (not (bobp)) (org-truely-invisible-p))
19590 (backward-char 1)
19591 (beginning-of-line 1))
19592 (forward-char 1))))
19593 (when special
19594 (cond
19595 ((and (looking-at org-complex-heading-regexp)
19596 (= (char-after (match-end 1)) ?\ ))
19597 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
19598 (point-at-eol)))
19599 (goto-char
19600 (if (eq special t)
19601 (cond ((> pos refpos) refpos)
19602 ((= pos (point)) refpos)
19603 (t (point)))
19604 (cond ((> pos (point)) (point))
19605 ((not (eq last-command this-command)) (point))
19606 (t refpos)))))
19607 ((org-at-item-p)
19608 (goto-char
19609 (if (eq special t)
19610 (cond ((> pos (match-end 0)) (match-end 0))
19611 ((= pos (point)) (match-end 0))
19612 (t (point)))
19613 (cond ((> pos (point)) (point))
19614 ((not (eq last-command this-command)) (point))
19615 (t (match-end 0))))))))
19616 (org-no-warnings
19617 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
19619 (defun org-end-of-line (&optional arg)
19620 "Go to the end of the line.
19621 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
19622 first attempt, and only move to after the tags when the cursor is already
19623 beyond the end of the headline."
19624 (interactive "P")
19625 (let ((special (if (consp org-special-ctrl-a/e)
19626 (cdr org-special-ctrl-a/e)
19627 org-special-ctrl-a/e)))
19628 (if (or (not special)
19629 (not (org-on-heading-p))
19630 arg)
19631 (call-interactively
19632 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
19633 ((fboundp 'move-end-of-line) 'move-end-of-line)
19634 (t 'end-of-line)))
19635 (let ((pos (point)))
19636 (beginning-of-line 1)
19637 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
19638 (if (eq special t)
19639 (if (or (< pos (match-beginning 1))
19640 (= pos (match-end 0)))
19641 (goto-char (match-beginning 1))
19642 (goto-char (match-end 0)))
19643 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
19644 (goto-char (match-end 0))
19645 (goto-char (match-beginning 1))))
19646 (call-interactively (if (fboundp 'move-end-of-line)
19647 'move-end-of-line
19648 'end-of-line)))))
19649 (org-no-warnings
19650 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
19652 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
19653 (define-key org-mode-map "\C-e" 'org-end-of-line)
19655 (defun org-backward-sentence (&optional arg)
19656 "Go to beginning of sentence, or beginning of table field.
19657 This will call `backward-sentence' or `org-table-beginning-of-field',
19658 depending on context."
19659 (interactive "P")
19660 (cond
19661 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
19662 (t (call-interactively 'backward-sentence))))
19664 (defun org-forward-sentence (&optional arg)
19665 "Go to end of sentence, or end of table field.
19666 This will call `forward-sentence' or `org-table-end-of-field',
19667 depending on context."
19668 (interactive "P")
19669 (cond
19670 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
19671 (t (call-interactively 'forward-sentence))))
19673 (define-key org-mode-map "\M-a" 'org-backward-sentence)
19674 (define-key org-mode-map "\M-e" 'org-forward-sentence)
19676 (defun org-kill-line (&optional arg)
19677 "Kill line, to tags or end of line."
19678 (interactive "P")
19679 (cond
19680 ((or (not org-special-ctrl-k)
19681 (bolp)
19682 (not (org-on-heading-p)))
19683 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
19684 org-ctrl-k-protect-subtree)
19685 (if (or (eq org-ctrl-k-protect-subtree 'error)
19686 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
19687 (error "C-k aborted - would kill hidden subtree")))
19688 (call-interactively 'kill-line))
19689 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
19690 (kill-region (point) (match-beginning 1))
19691 (org-set-tags nil t))
19692 (t (kill-region (point) (point-at-eol)))))
19694 (define-key org-mode-map "\C-k" 'org-kill-line)
19696 (defun org-yank (&optional arg)
19697 "Yank. If the kill is a subtree, treat it specially.
19698 This command will look at the current kill and check if is a single
19699 subtree, or a series of subtrees[1]. If it passes the test, and if the
19700 cursor is at the beginning of a line or after the stars of a currently
19701 empty headline, then the yank is handled specially. How exactly depends
19702 on the value of the following variables, both set by default.
19704 org-yank-folded-subtrees
19705 When set, the subtree(s) will be folded after insertion, but only
19706 if doing so would now swallow text after the yanked text.
19708 org-yank-adjusted-subtrees
19709 When set, the subtree will be promoted or demoted in order to
19710 fit into the local outline tree structure, which means that the level
19711 will be adjusted so that it becomes the smaller one of the two
19712 *visible* surrounding headings.
19714 Any prefix to this command will cause `yank' to be called directly with
19715 no special treatment. In particular, a simple \\[universal-argument] prefix \
19716 will just
19717 plainly yank the text as it is.
19719 \[1] The test checks if the first non-white line is a heading
19720 and if there are no other headings with fewer stars."
19721 (interactive "P")
19722 (org-yank-generic 'yank arg))
19724 (defun org-yank-generic (command arg)
19725 "Perform some yank-like command.
19727 This function implements the behavior described in the `org-yank'
19728 documentation. However, it has been generalized to work for any
19729 interactive command with similar behavior."
19731 ;; pretend to be command COMMAND
19732 (setq this-command command)
19734 (if arg
19735 (call-interactively command)
19737 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
19738 (and (org-kill-is-subtree-p)
19739 (or (bolp)
19740 (and (looking-at "[ \t]*$")
19741 (string-match
19742 "\\`\\*+\\'"
19743 (buffer-substring (point-at-bol) (point)))))))
19744 swallowp)
19745 (cond
19746 ((and subtreep org-yank-folded-subtrees)
19747 (let ((beg (point))
19748 end)
19749 (if (and subtreep org-yank-adjusted-subtrees)
19750 (org-paste-subtree nil nil 'for-yank)
19751 (call-interactively command))
19753 (setq end (point))
19754 (goto-char beg)
19755 (when (and (bolp) subtreep
19756 (not (setq swallowp
19757 (org-yank-folding-would-swallow-text beg end))))
19758 (or (looking-at outline-regexp)
19759 (re-search-forward (concat "^" outline-regexp) end t))
19760 (while (and (< (point) end) (looking-at outline-regexp))
19761 (hide-subtree)
19762 (org-cycle-show-empty-lines 'folded)
19763 (condition-case nil
19764 (outline-forward-same-level 1)
19765 (error (goto-char end)))))
19766 (when swallowp
19767 (message
19768 "Inserted text not folded because that would swallow text"))
19770 (goto-char end)
19771 (skip-chars-forward " \t\n\r")
19772 (beginning-of-line 1)
19773 (push-mark beg 'nomsg)))
19774 ((and subtreep org-yank-adjusted-subtrees)
19775 (let ((beg (point-at-bol)))
19776 (org-paste-subtree nil nil 'for-yank)
19777 (push-mark beg 'nomsg)))
19779 (call-interactively command))))))
19781 (defun org-yank-folding-would-swallow-text (beg end)
19782 "Would hide-subtree at BEG swallow any text after END?"
19783 (let (level)
19784 (save-excursion
19785 (goto-char beg)
19786 (when (or (looking-at outline-regexp)
19787 (re-search-forward (concat "^" outline-regexp) end t))
19788 (setq level (org-outline-level)))
19789 (goto-char end)
19790 (skip-chars-forward " \t\r\n\v\f")
19791 (if (or (eobp)
19792 (and (bolp) (looking-at org-outline-regexp)
19793 (<= (org-outline-level) level)))
19794 nil ; Nothing would be swallowed
19795 t)))) ; something would swallow
19797 (define-key org-mode-map "\C-y" 'org-yank)
19799 (defun org-truely-invisible-p ()
19800 "Check if point is at a character currently not visible.
19801 This version does not only check the character property, but also
19802 `visible-mode'."
19803 ;; Early versions of noutline don't have `outline-invisible-p'.
19804 (if (org-bound-and-true-p visible-mode)
19806 (outline-invisible-p)))
19808 (defun org-invisible-p2 ()
19809 "Check if point is at a character currently not visible."
19810 (save-excursion
19811 (if (and (eolp) (not (bobp))) (backward-char 1))
19812 ;; Early versions of noutline don't have `outline-invisible-p'.
19813 (outline-invisible-p)))
19815 (defun org-back-to-heading (&optional invisible-ok)
19816 "Call `outline-back-to-heading', but provide a better error message."
19817 (condition-case nil
19818 (outline-back-to-heading invisible-ok)
19819 (error (error "Before first headline at position %d in buffer %s"
19820 (point) (current-buffer)))))
19822 (defun org-beginning-of-defun ()
19823 "Go to the beginning of the subtree, i.e. back to the heading."
19824 (org-back-to-heading))
19825 (defun org-end-of-defun ()
19826 "Go to the end of the subtree."
19827 (org-end-of-subtree nil t))
19829 (defun org-before-first-heading-p ()
19830 "Before first heading?"
19831 (save-excursion
19832 (end-of-line)
19833 (null (re-search-backward "^\\*+ " nil t))))
19835 (defun org-on-heading-p (&optional ignored)
19836 (outline-on-heading-p t))
19837 (defun org-at-heading-p (&optional ignored)
19838 (outline-on-heading-p t))
19840 (defun org-point-at-end-of-empty-headline ()
19841 "If point is at the end of an empty headline, return t, else nil.
19842 If the heading only contains a TODO keyword, it is still still considered
19843 empty."
19844 (and (looking-at "[ \t]*$")
19845 (save-excursion
19846 (beginning-of-line 1)
19847 (let ((case-fold-search nil))
19848 (looking-at (concat "^\\(\\*+\\)[ \t]+\\(" org-todo-regexp
19849 "\\)?[ \t]*$"))))))
19850 (defun org-at-heading-or-item-p ()
19851 (or (org-on-heading-p) (org-at-item-p)))
19853 (defun org-on-target-p ()
19854 (or (org-in-regexp org-radio-target-regexp)
19855 (org-in-regexp org-target-regexp)))
19857 (defun org-up-heading-all (arg)
19858 "Move to the heading line of which the present line is a subheading.
19859 This function considers both visible and invisible heading lines.
19860 With argument, move up ARG levels."
19861 (if (fboundp 'outline-up-heading-all)
19862 (outline-up-heading-all arg) ; emacs 21 version of outline.el
19863 (outline-up-heading arg t))) ; emacs 22 version of outline.el
19865 (defun org-up-heading-safe ()
19866 "Move to the heading line of which the present line is a subheading.
19867 This version will not throw an error. It will return the level of the
19868 headline found, or nil if no higher level is found.
19870 Also, this function will be a lot faster than `outline-up-heading',
19871 because it relies on stars being the outline starters. This can really
19872 make a significant difference in outlines with very many siblings."
19873 (let (start-level re)
19874 (org-back-to-heading t)
19875 (setq start-level (funcall outline-level))
19876 (if (equal start-level 1)
19878 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
19879 (if (re-search-backward re nil t)
19880 (funcall outline-level)))))
19882 (defun org-first-sibling-p ()
19883 "Is this heading the first child of its parents?"
19884 (interactive)
19885 (let ((re (concat "^" outline-regexp))
19886 level l)
19887 (unless (org-at-heading-p t)
19888 (error "Not at a heading"))
19889 (setq level (funcall outline-level))
19890 (save-excursion
19891 (if (not (re-search-backward re nil t))
19893 (setq l (funcall outline-level))
19894 (< l level)))))
19896 (defun org-goto-sibling (&optional previous)
19897 "Goto the next sibling, even if it is invisible.
19898 When PREVIOUS is set, go to the previous sibling instead. Returns t
19899 when a sibling was found. When none is found, return nil and don't
19900 move point."
19901 (let ((fun (if previous 're-search-backward 're-search-forward))
19902 (pos (point))
19903 (re (concat "^" outline-regexp))
19904 level l)
19905 (when (condition-case nil (org-back-to-heading t) (error nil))
19906 (setq level (funcall outline-level))
19907 (catch 'exit
19908 (or previous (forward-char 1))
19909 (while (funcall fun re nil t)
19910 (setq l (funcall outline-level))
19911 (when (< l level) (goto-char pos) (throw 'exit nil))
19912 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
19913 (goto-char pos)
19914 nil))))
19916 (defun org-show-siblings ()
19917 "Show all siblings of the current headline."
19918 (save-excursion
19919 (while (org-goto-sibling) (org-flag-heading nil)))
19920 (save-excursion
19921 (while (org-goto-sibling 'previous)
19922 (org-flag-heading nil))))
19924 (defun org-goto-first-child ()
19925 "Goto the first child, even if it is invisible.
19926 Return t when a child was found. Otherwise don't move point and
19927 return nil."
19928 (let (level (pos (point)) (re (concat "^" outline-regexp)))
19929 (when (condition-case nil (org-back-to-heading t) (error nil))
19930 (setq level (outline-level))
19931 (forward-char 1)
19932 (if (and (re-search-forward re nil t) (> (outline-level) level))
19933 (progn (goto-char (match-beginning 0)) t)
19934 (goto-char pos) nil))))
19936 (defun org-show-hidden-entry ()
19937 "Show an entry where even the heading is hidden."
19938 (save-excursion
19939 (org-show-entry)))
19941 (defun org-flag-heading (flag &optional entry)
19942 "Flag the current heading. FLAG non-nil means make invisible.
19943 When ENTRY is non-nil, show the entire entry."
19944 (save-excursion
19945 (org-back-to-heading t)
19946 ;; Check if we should show the entire entry
19947 (if entry
19948 (progn
19949 (org-show-entry)
19950 (save-excursion
19951 (and (outline-next-heading)
19952 (org-flag-heading nil))))
19953 (outline-flag-region (max (point-min) (1- (point)))
19954 (save-excursion (outline-end-of-heading) (point))
19955 flag))))
19957 (defun org-get-next-sibling ()
19958 "Move to next heading of the same level, and return point.
19959 If there is no such heading, return nil.
19960 This is like outline-next-sibling, but invisible headings are ok."
19961 (let ((level (funcall outline-level)))
19962 (outline-next-heading)
19963 (while (and (not (eobp)) (> (funcall outline-level) level))
19964 (outline-next-heading))
19965 (if (or (eobp) (< (funcall outline-level) level))
19967 (point))))
19969 (defun org-get-last-sibling ()
19970 "Move to previous heading of the same level, and return point.
19971 If there is no such heading, return nil."
19972 (let ((opoint (point))
19973 (level (funcall outline-level)))
19974 (outline-previous-heading)
19975 (when (and (/= (point) opoint) (outline-on-heading-p t))
19976 (while (and (> (funcall outline-level) level)
19977 (not (bobp)))
19978 (outline-previous-heading))
19979 (if (< (funcall outline-level) level)
19981 (point)))))
19983 (defun org-end-of-subtree (&optional invisible-OK to-heading)
19984 ;; This contains an exact copy of the original function, but it uses
19985 ;; `org-back-to-heading', to make it work also in invisible
19986 ;; trees. And is uses an invisible-OK argument.
19987 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
19988 ;; Furthermore, when used inside Org, finding the end of a large subtree
19989 ;; with many children and grandchildren etc, this can be much faster
19990 ;; than the outline version.
19991 (org-back-to-heading invisible-OK)
19992 (let ((first t)
19993 (level (funcall outline-level)))
19994 (if (and (org-mode-p) (< level 1000))
19995 ;; A true heading (not a plain list item), in Org-mode
19996 ;; This means we can easily find the end by looking
19997 ;; only for the right number of stars. Using a regexp to do
19998 ;; this is so much faster than using a Lisp loop.
19999 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
20000 (forward-char 1)
20001 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
20002 ;; something else, do it the slow way
20003 (while (and (not (eobp))
20004 (or first (> (funcall outline-level) level)))
20005 (setq first nil)
20006 (outline-next-heading)))
20007 (unless to-heading
20008 (if (memq (preceding-char) '(?\n ?\^M))
20009 (progn
20010 ;; Go to end of line before heading
20011 (forward-char -1)
20012 (if (memq (preceding-char) '(?\n ?\^M))
20013 ;; leave blank line before heading
20014 (forward-char -1))))))
20015 (point))
20017 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
20018 "Use Org version in org-mode, for dramatic speed-up."
20019 (if (org-mode-p)
20020 (progn
20021 (org-end-of-subtree nil t)
20022 (unless (eobp) (backward-char 1)))
20023 ad-do-it))
20025 (defun org-end-of-meta-data-and-drawers ()
20026 "Jump to the first text after meta data and drawers in the current entry.
20027 This will move over empty lines, lines with planning time stamps,
20028 clocking lines, and drawers."
20029 (org-back-to-heading t)
20030 (let ((end (save-excursion (outline-next-heading) (point)))
20031 (re (concat "[ \t]*$"
20032 "\\|"
20033 "\\(" org-drawer-regexp "\\)" ; group 1 are drawers
20034 "\\|"
20035 "\\([ \t]*\\(" org-keyword-time-regexp "\\)\\)")))
20036 (forward-line 1)
20037 (while (looking-at (concat "[ \t]*\\(" org-keyword-time-regexp "\\)"))
20038 (if (not (match-end 1))
20039 ;; empty or planning line
20040 (forward-line 1)
20041 ;; a drawer, find the end
20042 (re-search-forward "^[ \t]*:END:" end 'move)
20043 (forward-line 1)))
20044 (point)))
20046 (defun org-forward-same-level (arg &optional invisible-ok)
20047 "Move forward to the arg'th subheading at same level as this one.
20048 Stop at the first and last subheadings of a superior heading.
20049 Normally this only looks at visible headings, but when INVISIBLE-OK is non-nil
20050 it wil also look at invisible ones."
20051 (interactive "p")
20052 (org-back-to-heading invisible-ok)
20053 (org-on-heading-p)
20054 (let* ((level (- (match-end 0) (match-beginning 0) 1))
20055 (re (format "^\\*\\{1,%d\\} " level))
20057 (forward-char 1)
20058 (while (> arg 0)
20059 (while (and (re-search-forward re nil 'move)
20060 (setq l (- (match-end 0) (match-beginning 0) 1))
20061 (= l level)
20062 (not invisible-ok)
20063 (progn (backward-char 1) (outline-invisible-p)))
20064 (if (< l level) (setq arg 1)))
20065 (setq arg (1- arg)))
20066 (beginning-of-line 1)))
20068 (defun org-backward-same-level (arg &optional invisible-ok)
20069 "Move backward to the arg'th subheading at same level as this one.
20070 Stop at the first and last subheadings of a superior heading."
20071 (interactive "p")
20072 (org-back-to-heading)
20073 (org-on-heading-p)
20074 (let* ((level (- (match-end 0) (match-beginning 0) 1))
20075 (re (format "^\\*\\{1,%d\\} " level))
20077 (while (> arg 0)
20078 (while (and (re-search-backward re nil 'move)
20079 (setq l (- (match-end 0) (match-beginning 0) 1))
20080 (= l level)
20081 (not invisible-ok)
20082 (outline-invisible-p))
20083 (if (< l level) (setq arg 1)))
20084 (setq arg (1- arg)))))
20086 (defun org-show-subtree ()
20087 "Show everything after this heading at deeper levels."
20088 (outline-flag-region
20089 (point)
20090 (save-excursion
20091 (org-end-of-subtree t t))
20092 nil))
20094 (defun org-show-entry ()
20095 "Show the body directly following this heading.
20096 Show the heading too, if it is currently invisible."
20097 (interactive)
20098 (save-excursion
20099 (condition-case nil
20100 (progn
20101 (org-back-to-heading t)
20102 (outline-flag-region
20103 (max (point-min) (1- (point)))
20104 (save-excursion
20105 (if (re-search-forward
20106 (concat "[\r\n]\\(" outline-regexp "\\)") nil t)
20107 (match-beginning 1)
20108 (point-max)))
20109 nil)
20110 (org-cycle-hide-drawers 'children))
20111 (error nil))))
20113 (defun org-make-options-regexp (kwds &optional extra)
20114 "Make a regular expression for keyword lines."
20115 (concat
20117 "#?[ \t]*\\+\\("
20118 (mapconcat 'regexp-quote kwds "\\|")
20119 (if extra (concat "\\|" extra))
20120 "\\):[ \t]*"
20121 "\\(.*\\)"))
20123 ;; Make isearch reveal the necessary context
20124 (defun org-isearch-end ()
20125 "Reveal context after isearch exits."
20126 (when isearch-success ; only if search was successful
20127 (if (featurep 'xemacs)
20128 ;; Under XEmacs, the hook is run in the correct place,
20129 ;; we directly show the context.
20130 (org-show-context 'isearch)
20131 ;; In Emacs the hook runs *before* restoring the overlays.
20132 ;; So we have to use a one-time post-command-hook to do this.
20133 ;; (Emacs 22 has a special variable, see function `org-mode')
20134 (unless (and (boundp 'isearch-mode-end-hook-quit)
20135 isearch-mode-end-hook-quit)
20136 ;; Only when the isearch was not quitted.
20137 (org-add-hook 'post-command-hook 'org-isearch-post-command
20138 'append 'local)))))
20140 (defun org-isearch-post-command ()
20141 "Remove self from hook, and show context."
20142 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
20143 (org-show-context 'isearch))
20146 ;;;; Integration with and fixes for other packages
20148 ;;; Imenu support
20150 (defvar org-imenu-markers nil
20151 "All markers currently used by Imenu.")
20152 (make-variable-buffer-local 'org-imenu-markers)
20154 (defun org-imenu-new-marker (&optional pos)
20155 "Return a new marker for use by Imenu, and remember the marker."
20156 (let ((m (make-marker)))
20157 (move-marker m (or pos (point)))
20158 (push m org-imenu-markers)
20161 (defun org-imenu-get-tree ()
20162 "Produce the index for Imenu."
20163 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
20164 (setq org-imenu-markers nil)
20165 (let* ((n org-imenu-depth)
20166 (re (concat "^" outline-regexp))
20167 (subs (make-vector (1+ n) nil))
20168 (last-level 0)
20169 m level head)
20170 (save-excursion
20171 (save-restriction
20172 (widen)
20173 (goto-char (point-max))
20174 (while (re-search-backward re nil t)
20175 (setq level (org-reduced-level (funcall outline-level)))
20176 (when (<= level n)
20177 (looking-at org-complex-heading-regexp)
20178 (setq head (org-link-display-format
20179 (org-match-string-no-properties 4))
20180 m (org-imenu-new-marker))
20181 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
20182 (if (>= level last-level)
20183 (push (cons head m) (aref subs level))
20184 (push (cons head (aref subs (1+ level))) (aref subs level))
20185 (loop for i from (1+ level) to n do (aset subs i nil)))
20186 (setq last-level level)))))
20187 (aref subs 1)))
20189 (eval-after-load "imenu"
20190 '(progn
20191 (add-hook 'imenu-after-jump-hook
20192 (lambda ()
20193 (if (org-mode-p)
20194 (org-show-context 'org-goto))))))
20196 (defun org-link-display-format (link)
20197 "Replace a link with either the description, or the link target
20198 if no description is present"
20199 (save-match-data
20200 (if (string-match org-bracket-link-analytic-regexp link)
20201 (replace-match (if (match-end 5)
20202 (match-string 5 link)
20203 (concat (match-string 1 link)
20204 (match-string 3 link)))
20205 nil t link)
20206 link)))
20208 ;; Speedbar support
20210 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
20211 "Overlay marking the agenda restriction line in speedbar.")
20212 (overlay-put org-speedbar-restriction-lock-overlay
20213 'face 'org-agenda-restriction-lock)
20214 (overlay-put org-speedbar-restriction-lock-overlay
20215 'help-echo "Agendas are currently limited to this item.")
20216 (org-detach-overlay org-speedbar-restriction-lock-overlay)
20218 (defun org-speedbar-set-agenda-restriction ()
20219 "Restrict future agenda commands to the location at point in speedbar.
20220 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
20221 (interactive)
20222 (require 'org-agenda)
20223 (let (p m tp np dir txt)
20224 (cond
20225 ((setq p (text-property-any (point-at-bol) (point-at-eol)
20226 'org-imenu t))
20227 (setq m (get-text-property p 'org-imenu-marker))
20228 (with-current-buffer (marker-buffer m)
20229 (goto-char m)
20230 (org-agenda-set-restriction-lock 'subtree)))
20231 ((setq p (text-property-any (point-at-bol) (point-at-eol)
20232 'speedbar-function 'speedbar-find-file))
20233 (setq tp (previous-single-property-change
20234 (1+ p) 'speedbar-function)
20235 np (next-single-property-change
20236 tp 'speedbar-function)
20237 dir (speedbar-line-directory)
20238 txt (buffer-substring-no-properties (or tp (point-min))
20239 (or np (point-max))))
20240 (with-current-buffer (find-file-noselect
20241 (let ((default-directory dir))
20242 (expand-file-name txt)))
20243 (unless (org-mode-p)
20244 (error "Cannot restrict to non-Org-mode file"))
20245 (org-agenda-set-restriction-lock 'file)))
20246 (t (error "Don't know how to restrict Org-mode's agenda")))
20247 (move-overlay org-speedbar-restriction-lock-overlay
20248 (point-at-bol) (point-at-eol))
20249 (setq current-prefix-arg nil)
20250 (org-agenda-maybe-redo)))
20252 (eval-after-load "speedbar"
20253 '(progn
20254 (speedbar-add-supported-extension ".org")
20255 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
20256 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
20257 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
20258 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
20259 (add-hook 'speedbar-visiting-tag-hook
20260 (lambda () (and (org-mode-p) (org-show-context 'org-goto))))))
20262 ;;; Fixes and Hacks for problems with other packages
20264 ;; Make flyspell not check words in links, to not mess up our keymap
20265 (defun org-mode-flyspell-verify ()
20266 "Don't let flyspell put overlays at active buttons, or on
20267 {todo,all-time,additional-option-like}-keywords."
20268 (let ((pos (max (1- (point)) (point-min)))
20269 (word (thing-at-point 'word)))
20270 (and (not (get-text-property pos 'keymap))
20271 (not (get-text-property pos 'org-no-flyspell))
20272 (not (member word org-todo-keywords-1))
20273 (not (member word org-all-time-keywords))
20274 (not (member word org-additional-option-like-keywords)))))
20276 (defun org-remove-flyspell-overlays-in (beg end)
20277 "Remove flyspell overlays in region."
20278 (and (org-bound-and-true-p flyspell-mode)
20279 (fboundp 'flyspell-delete-region-overlays)
20280 (flyspell-delete-region-overlays beg end))
20281 (add-text-properties beg end '(org-no-flyspell t)))
20283 ;; Make `bookmark-jump' shows the jump location if it was hidden.
20284 (eval-after-load "bookmark"
20285 '(if (boundp 'bookmark-after-jump-hook)
20286 ;; We can use the hook
20287 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
20288 ;; Hook not available, use advice
20289 (defadvice bookmark-jump (after org-make-visible activate)
20290 "Make the position visible."
20291 (org-bookmark-jump-unhide))))
20293 ;; Make sure saveplace shows the location if it was hidden
20294 (eval-after-load "saveplace"
20295 '(defadvice save-place-find-file-hook (after org-make-visible activate)
20296 "Make the position visible."
20297 (org-bookmark-jump-unhide)))
20299 ;; Make sure ecb shows the location if it was hidden
20300 (eval-after-load "ecb"
20301 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
20302 "Make hierarchy visible when jumping into location from ECB tree buffer."
20303 (if (org-mode-p)
20304 (org-show-context))))
20306 (defun org-bookmark-jump-unhide ()
20307 "Unhide the current position, to show the bookmark location."
20308 (and (org-mode-p)
20309 (or (outline-invisible-p)
20310 (save-excursion (goto-char (max (point-min) (1- (point))))
20311 (outline-invisible-p)))
20312 (org-show-context 'bookmark-jump)))
20314 ;; Make session.el ignore our circular variable
20315 (eval-after-load "session"
20316 '(add-to-list 'session-globals-exclude 'org-mark-ring))
20318 ;;;; Experimental code
20320 (defun org-closed-in-range ()
20321 "Sparse tree of items closed in a certain time range.
20322 Still experimental, may disappear in the future."
20323 (interactive)
20324 ;; Get the time interval from the user.
20325 (let* ((time1 (org-float-time
20326 (org-read-date nil 'to-time nil "Starting date: ")))
20327 (time2 (org-float-time
20328 (org-read-date nil 'to-time nil "End date:")))
20329 ;; callback function
20330 (callback (lambda ()
20331 (let ((time
20332 (org-float-time
20333 (apply 'encode-time
20334 (org-parse-time-string
20335 (match-string 1))))))
20336 ;; check if time in interval
20337 (and (>= time time1) (<= time time2))))))
20338 ;; make tree, check each match with the callback
20339 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
20341 ;;;; Finish up
20343 (provide 'org)
20345 (run-hooks 'org-load-hook)
20347 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
20349 ;;; org.el ends here