library-of-babel: adding vc-log by Luke Crook
[org-mode/org-jambu.git] / lisp / org.el
blobe652ff1ce58bae855a76ab6a9ee5d18971de697e
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 "C" C)
154 (const :tag "R" R)
155 (const :tag "Asymptote" asymptote)
156 (const :tag "Calc" calc)
157 (const :tag "Clojure" clojure)
158 (const :tag "CSS" css)
159 (const :tag "Ditaa" ditaa)
160 (const :tag "Dot" dot)
161 (const :tag "Emacs Lisp" emacs-lisp)
162 (const :tag "Gnuplot" gnuplot)
163 (const :tag "Haskell" haskell)
164 (const :tag "Javascript" js)
165 (const :tag "Latex" latex)
166 (const :tag "Ledger" ledger)
167 (const :tag "Maxima" maxima)
168 (const :tag "Matlab" matlab)
169 (const :tag "Mscgen" mscgen)
170 (const :tag "Ocaml" ocaml)
171 (const :tag "Octave" octave)
172 (const :tag "Org" org)
173 (const :tag "Perl" perl)
174 (const :tag "PlantUML" plantuml)
175 (const :tag "Python" python)
176 (const :tag "Ruby" ruby)
177 (const :tag "Sass" sass)
178 (const :tag "Scheme" scheme)
179 (const :tag "Screen" screen)
180 (const :tag "Shell Script" sh)
181 (const :tag "Sql" sql)
182 (const :tag "Sqlite" sqlite))
183 :value-type (boolean :tag "Activate" :value t)))
185 ;;;; Customization variables
186 (defcustom org-clone-delete-id nil
187 "Remove ID property of clones of a subtree.
188 When non-nil, clones of a subtree don't inherit the ID property.
189 Otherwise they inherit the ID property with a new unique
190 identifier."
191 :type 'boolean
192 :group 'org-id)
194 ;;; Version
196 (defconst org-version "7.5"
197 "The version number of the file org.el.")
199 (defun org-version (&optional here)
200 "Show the org-mode version in the echo area.
201 With prefix arg HERE, insert it at point."
202 (interactive "P")
203 (let* ((origin default-directory)
204 (version org-version)
205 (git-version)
206 (dir (concat (file-name-directory (locate-library "org")) "../" )))
207 (when (and (file-exists-p (expand-file-name ".git" dir))
208 (executable-find "git"))
209 (unwind-protect
210 (progn
211 (cd dir)
212 (when (eql 0 (shell-command "git describe --abbrev=4 HEAD"))
213 (with-current-buffer "*Shell Command Output*"
214 (goto-char (point-min))
215 (setq git-version (buffer-substring (point) (point-at-eol))))
216 (subst-char-in-string ?- ?. git-version t)
217 (when (string-match "\\S-"
218 (shell-command-to-string
219 "git diff-index --name-only HEAD --"))
220 (setq git-version (concat git-version ".dirty")))
221 (setq version (concat version " (" git-version ")"))))
222 (cd origin)))
223 (setq version (format "Org-mode version %s" version))
224 (if here (insert version))
225 (message version)))
227 ;;; Compatibility constants
229 ;;; The custom variables
231 (defgroup org nil
232 "Outline-based notes management and organizer."
233 :tag "Org"
234 :group 'outlines
235 :group 'calendar)
237 (defcustom org-mode-hook nil
238 "Mode hook for Org-mode, run after the mode was turned on."
239 :group 'org
240 :type 'hook)
242 (defcustom org-load-hook nil
243 "Hook that is run after org.el has been loaded."
244 :group 'org
245 :type 'hook)
247 (defvar org-modules) ; defined below
248 (defvar org-modules-loaded nil
249 "Have the modules been loaded already?")
251 (defun org-load-modules-maybe (&optional force)
252 "Load all extensions listed in `org-modules'."
253 (when (or force (not org-modules-loaded))
254 (mapc (lambda (ext)
255 (condition-case nil (require ext)
256 (error (message "Problems while trying to load feature `%s'" ext))))
257 org-modules)
258 (setq org-modules-loaded t)))
260 (defun org-set-modules (var value)
261 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
262 (set var value)
263 (when (featurep 'org)
264 (org-load-modules-maybe 'force)))
266 (when (org-bound-and-true-p org-modules)
267 (let ((a (member 'org-infojs org-modules)))
268 (and a (setcar a 'org-jsinfo))))
270 (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)
271 "Modules that should always be loaded together with org.el.
272 If a description starts with <C>, the file is not part of Emacs
273 and loading it will require that you have downloaded and properly installed
274 the org-mode distribution.
276 You can also use this system to load external packages (i.e. neither Org
277 core modules, nor modules from the CONTRIB directory). Just add symbols
278 to the end of the list. If the package is called org-xyz.el, then you need
279 to add the symbol `xyz', and the package must have a call to
281 (provide 'org-xyz)"
282 :group 'org
283 :set 'org-set-modules
284 :type
285 '(set :greedy t
286 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
287 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
288 (const :tag " crypt: Encryption of subtrees" org-crypt)
289 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
290 (const :tag " docview: Links to doc-view buffers" org-docview)
291 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
292 (const :tag " id: Global IDs for identifying entries" org-id)
293 (const :tag " info: Links to Info nodes" org-info)
294 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
295 (const :tag " habit: Track your consistency with habits" org-habit)
296 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
297 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
298 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
299 (const :tag " mew Links to Mew folders/messages" org-mew)
300 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
301 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
302 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
303 (const :tag " special-blocks: Turn blocks into LaTeX envs and HTML divs" org-special-blocks)
304 (const :tag " vm: Links to VM folders/messages" org-vm)
305 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
306 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
307 (const :tag " mouse: Additional mouse support" org-mouse)
308 (const :tag " TaskJuggler: Export tasks to a TaskJuggler project" org-taskjuggler)
310 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
311 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
312 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
313 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
314 (const :tag "C collector: Collect properties into tables" org-collector)
315 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
316 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
317 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
318 (const :tag "C eval: Include command output as text" org-eval)
319 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
320 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
321 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
322 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
323 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
325 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
327 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
328 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
329 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
330 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
331 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
332 (const :tag "C mac-link-grabber Grab links and URLs from various Mac applications" org-mac-link-grabber)
333 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
334 (const :tag "C mtags: Support for muse-like tags" org-mtags)
335 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
336 (const :tag "C registry: A registry for Org-mode links" org-registry)
337 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
338 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
339 (const :tag "C secretary: Team management with org-mode" org-secretary)
340 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
341 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
342 (const :tag "C track: Keep up with Org-mode development" org-track)
343 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
344 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
345 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
347 (defcustom org-support-shift-select nil
348 "Non-nil means make shift-cursor commands select text when possible.
350 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys start
351 selecting a region, or enlarge regions started in this way.
352 In Org-mode, in special contexts, these same keys are used for other
353 purposes, important enough to compete with shift selection. Org tries
354 to balance these needs by supporting `shift-select-mode' outside these
355 special contexts, under control of this variable.
357 The default of this variable is nil, to avoid confusing behavior. Shifted
358 cursor keys will then execute Org commands in the following contexts:
359 - on a headline, changing TODO state (left/right) and priority (up/down)
360 - on a time stamp, changing the time
361 - in a plain list item, changing the bullet type
362 - in a property definition line, switching between allowed values
363 - in the BEGIN line of a clock table (changing the time block).
364 Outside these contexts, the commands will throw an error.
366 When this variable is t and the cursor is not in a special context,
367 Org-mode will support shift-selection for making and enlarging regions.
368 To make this more effective, the bullet cycling will no longer happen
369 anywhere in an item line, but only if the cursor is exactly on the bullet.
371 If you set this variable to the symbol `always', then the keys
372 will not be special in headlines, property lines, and item lines, to make
373 shift selection work there as well. If this is what you want, you can
374 use the following alternative commands: `C-c C-t' and `C-c ,' to
375 change TODO state and priority, `C-u C-u C-c C-t' can be used to switch
376 TODO sets, `C-c -' to cycle item bullet types, and properties can be
377 edited by hand or in column view.
379 However, when the cursor is on a timestamp, shift-cursor commands
380 will still edit the time stamp - this is just too good to give up.
382 XEmacs user should have this variable set to nil, because shift-select-mode
383 is Emacs 23 only."
384 :group 'org
385 :type '(choice
386 (const :tag "Never" nil)
387 (const :tag "When outside special context" t)
388 (const :tag "Everywhere except timestamps" always)))
390 (defgroup org-startup nil
391 "Options concerning startup of Org-mode."
392 :tag "Org Startup"
393 :group 'org)
395 (defcustom org-startup-folded t
396 "Non-nil means entering Org-mode will switch to OVERVIEW.
397 This can also be configured on a per-file basis by adding one of
398 the following lines anywhere in the buffer:
400 #+STARTUP: fold (or `overview', this is equivalent)
401 #+STARTUP: nofold (or `showall', this is equivalent)
402 #+STARTUP: content
403 #+STARTUP: showeverything"
404 :group 'org-startup
405 :type '(choice
406 (const :tag "nofold: show all" nil)
407 (const :tag "fold: overview" t)
408 (const :tag "content: all headlines" content)
409 (const :tag "show everything, even drawers" showeverything)))
411 (defcustom org-startup-truncated t
412 "Non-nil means entering Org-mode will set `truncate-lines'.
413 This is useful since some lines containing links can be very long and
414 uninteresting. Also tables look terrible when wrapped."
415 :group 'org-startup
416 :type 'boolean)
418 (defcustom org-startup-indented nil
419 "Non-nil means turn on `org-indent-mode' on startup.
420 This can also be configured on a per-file basis by adding one of
421 the following lines anywhere in the buffer:
423 #+STARTUP: indent
424 #+STARTUP: noindent"
425 :group 'org-structure
426 :type '(choice
427 (const :tag "Not" nil)
428 (const :tag "Globally (slow on startup in large files)" t)))
430 (defcustom org-use-sub-superscripts t
431 "Non-nil means interpret \"_\" and \"^\" for export.
432 When this option is turned on, you can use TeX-like syntax for sub- and
433 superscripts. Several characters after \"_\" or \"^\" will be
434 considered as a single item - so grouping with {} is normally not
435 needed. For example, the following things will be parsed as single
436 sub- or superscripts.
438 10^24 or 10^tau several digits will be considered 1 item.
439 10^-12 or 10^-tau a leading sign with digits or a word
440 x^2-y^3 will be read as x^2 - y^3, because items are
441 terminated by almost any nonword/nondigit char.
442 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
444 Still, ambiguity is possible - so when in doubt use {} to enclose the
445 sub/superscript. If you set this variable to the symbol `{}',
446 the braces are *required* in order to trigger interpretations as
447 sub/superscript. This can be helpful in documents that need \"_\"
448 frequently in plain text.
450 Not all export backends support this, but HTML does.
452 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
453 :group 'org-startup
454 :group 'org-export-translation
455 :type '(choice
456 (const :tag "Always interpret" t)
457 (const :tag "Only with braces" {})
458 (const :tag "Never interpret" nil)))
460 (if (fboundp 'defvaralias)
461 (defvaralias 'org-export-with-sub-superscripts 'org-use-sub-superscripts))
464 (defcustom org-startup-with-beamer-mode nil
465 "Non-nil means turn on `org-beamer-mode' on startup.
466 This can also be configured on a per-file basis by adding one of
467 the following lines anywhere in the buffer:
469 #+STARTUP: beamer"
470 :group 'org-startup
471 :type 'boolean)
473 (defcustom org-startup-align-all-tables nil
474 "Non-nil means align all tables when visiting a file.
475 This is useful when the column width in tables is forced with <N> cookies
476 in table fields. Such tables will look correct only after the first re-align.
477 This can also be configured on a per-file basis by adding one of
478 the following lines anywhere in the buffer:
479 #+STARTUP: align
480 #+STARTUP: noalign"
481 :group 'org-startup
482 :type 'boolean)
484 (defcustom org-startup-with-inline-images nil
485 "Non-nil means show inline images when loading a new Org file.
486 This can also be configured on a per-file basis by adding one of
487 the following lines anywhere in the buffer:
488 #+STARTUP: inlineimages
489 #+STARTUP: noinlineimages"
490 :group 'org-startup
491 :type 'boolean)
493 (defcustom org-insert-mode-line-in-empty-file nil
494 "Non-nil means insert the first line setting Org-mode in empty files.
495 When the function `org-mode' is called interactively in an empty file, this
496 normally means that the file name does not automatically trigger Org-mode.
497 To ensure that the file will always be in Org-mode in the future, a
498 line enforcing Org-mode will be inserted into the buffer, if this option
499 has been set."
500 :group 'org-startup
501 :type 'boolean)
503 (defcustom org-replace-disputed-keys nil
504 "Non-nil means use alternative key bindings for some keys.
505 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
506 These keys are also used by other packages like shift-selection-mode'
507 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
508 If you want to use Org-mode together with one of these other modes,
509 or more generally if you would like to move some Org-mode commands to
510 other keys, set this variable and configure the keys with the variable
511 `org-disputed-keys'.
513 This option is only relevant at load-time of Org-mode, and must be set
514 *before* org.el is loaded. Changing it requires a restart of Emacs to
515 become effective."
516 :group 'org-startup
517 :type 'boolean)
519 (defcustom org-use-extra-keys nil
520 "Non-nil means use extra key sequence definitions for certain commands.
521 This happens automatically if you run XEmacs or if `window-system'
522 is nil. This variable lets you do the same manually. You must
523 set it before loading org.
525 Example: on Carbon Emacs 22 running graphically, with an external
526 keyboard on a Powerbook, the default way of setting M-left might
527 not work for either Alt or ESC. Setting this variable will make
528 it work for ESC."
529 :group 'org-startup
530 :type 'boolean)
532 (if (fboundp 'defvaralias)
533 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
535 (defcustom org-disputed-keys
536 '(([(shift up)] . [(meta p)])
537 ([(shift down)] . [(meta n)])
538 ([(shift left)] . [(meta -)])
539 ([(shift right)] . [(meta +)])
540 ([(control shift right)] . [(meta shift +)])
541 ([(control shift left)] . [(meta shift -)]))
542 "Keys for which Org-mode and other modes compete.
543 This is an alist, cars are the default keys, second element specifies
544 the alternative to use when `org-replace-disputed-keys' is t.
546 Keys can be specified in any syntax supported by `define-key'.
547 The value of this option takes effect only at Org-mode's startup,
548 therefore you'll have to restart Emacs to apply it after changing."
549 :group 'org-startup
550 :type 'alist)
552 (defun org-key (key)
553 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
554 Or return the original if not disputed.
555 Also apply the translations defined in `org-xemacs-key-equivalents'."
556 (when org-replace-disputed-keys
557 (let* ((nkey (key-description key))
558 (x (org-find-if (lambda (x)
559 (equal (key-description (car x)) nkey))
560 org-disputed-keys)))
561 (setq key (if x (cdr x) key))))
562 (when (featurep 'xemacs)
563 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
564 key)
566 (defun org-find-if (predicate seq)
567 (catch 'exit
568 (while seq
569 (if (funcall predicate (car seq))
570 (throw 'exit (car seq))
571 (pop seq)))))
573 (defun org-defkey (keymap key def)
574 "Define a key, possibly translated, as returned by `org-key'."
575 (define-key keymap (org-key key) def))
577 (defcustom org-ellipsis nil
578 "The ellipsis to use in the Org-mode outline.
579 When nil, just use the standard three dots. When a string, use that instead,
580 When a face, use the standard 3 dots, but with the specified face.
581 The change affects only Org-mode (which will then use its own display table).
582 Changing this requires executing `M-x org-mode' in a buffer to become
583 effective."
584 :group 'org-startup
585 :type '(choice (const :tag "Default" nil)
586 (face :tag "Face" :value org-warning)
587 (string :tag "String" :value "...#")))
589 (defvar org-display-table nil
590 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
592 (defgroup org-keywords nil
593 "Keywords in Org-mode."
594 :tag "Org Keywords"
595 :group 'org)
597 (defcustom org-deadline-string "DEADLINE:"
598 "String to mark deadline entries.
599 A deadline is this string, followed by a time stamp. Should be a word,
600 terminated by a colon. You can insert a schedule keyword and
601 a timestamp with \\[org-deadline].
602 Changes become only effective after restarting Emacs."
603 :group 'org-keywords
604 :type 'string)
606 (defcustom org-scheduled-string "SCHEDULED:"
607 "String to mark scheduled TODO entries.
608 A schedule is this string, followed by a time stamp. Should be a word,
609 terminated by a colon. You can insert a schedule keyword and
610 a timestamp with \\[org-schedule].
611 Changes become only effective after restarting Emacs."
612 :group 'org-keywords
613 :type 'string)
615 (defcustom org-closed-string "CLOSED:"
616 "String used as the prefix for timestamps logging closing a TODO entry."
617 :group 'org-keywords
618 :type 'string)
620 (defcustom org-clock-string "CLOCK:"
621 "String used as prefix for timestamps clocking work hours on an item."
622 :group 'org-keywords
623 :type 'string)
625 (defcustom org-comment-string "COMMENT"
626 "Entries starting with this keyword will never be exported.
627 An entry can be toggled between COMMENT and normal with
628 \\[org-toggle-comment].
629 Changes become only effective after restarting Emacs."
630 :group 'org-keywords
631 :type 'string)
633 (defcustom org-quote-string "QUOTE"
634 "Entries starting with this keyword will be exported in fixed-width font.
635 Quoting applies only to the text in the entry following the headline, and does
636 not extend beyond the next headline, even if that is lower level.
637 An entry can be toggled between QUOTE and normal with
638 \\[org-toggle-fixed-width-section]."
639 :group 'org-keywords
640 :type 'string)
642 (defconst org-repeat-re
643 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)"
644 "Regular expression for specifying repeated events.
645 After a match, group 1 contains the repeat expression.")
647 (defgroup org-structure nil
648 "Options concerning the general structure of Org-mode files."
649 :tag "Org Structure"
650 :group 'org)
652 (defgroup org-reveal-location nil
653 "Options about how to make context of a location visible."
654 :tag "Org Reveal Location"
655 :group 'org-structure)
657 (defconst org-context-choice
658 '(choice
659 (const :tag "Always" t)
660 (const :tag "Never" nil)
661 (repeat :greedy t :tag "Individual contexts"
662 (cons
663 (choice :tag "Context"
664 (const agenda)
665 (const org-goto)
666 (const occur-tree)
667 (const tags-tree)
668 (const link-search)
669 (const mark-goto)
670 (const bookmark-jump)
671 (const isearch)
672 (const default))
673 (boolean))))
674 "Contexts for the reveal options.")
676 (defcustom org-show-hierarchy-above '((default . t))
677 "Non-nil means show full hierarchy when revealing a location.
678 Org-mode often shows locations in an org-mode file which might have
679 been invisible before. When this is set, the hierarchy of headings
680 above the exposed location is shown.
681 Turning this off for example for sparse trees makes them very compact.
682 Instead of t, this can also be an alist specifying this option for different
683 contexts. Valid contexts are
684 agenda when exposing an entry from the agenda
685 org-goto when using the command `org-goto' on key C-c C-j
686 occur-tree when using the command `org-occur' on key C-c /
687 tags-tree when constructing a sparse tree based on tags matches
688 link-search when exposing search matches associated with a link
689 mark-goto when exposing the jump goal of a mark
690 bookmark-jump when exposing a bookmark location
691 isearch when exiting from an incremental search
692 default default for all contexts not set explicitly"
693 :group 'org-reveal-location
694 :type org-context-choice)
696 (defcustom org-show-following-heading '((default . nil))
697 "Non-nil means show following heading when revealing a location.
698 Org-mode often shows locations in an org-mode file which might have
699 been invisible before. When this is set, the heading following the
700 match is shown.
701 Turning this off for example for sparse trees makes them very compact,
702 but makes it harder to edit the location of the match. In such a case,
703 use the command \\[org-reveal] to show more context.
704 Instead of t, this can also be an alist specifying this option for different
705 contexts. See `org-show-hierarchy-above' for valid contexts."
706 :group 'org-reveal-location
707 :type org-context-choice)
709 (defcustom org-show-siblings '((default . nil) (isearch t))
710 "Non-nil means show all sibling heading when revealing a location.
711 Org-mode often shows locations in an org-mode file which might have
712 been invisible before. When this is set, the sibling of the current entry
713 heading are all made visible. If `org-show-hierarchy-above' is t,
714 the same happens on each level of the hierarchy above the current entry.
716 By default this is on for the isearch context, off for all other contexts.
717 Turning this off for example for sparse trees makes them very compact,
718 but makes it harder to edit the location of the match. In such a case,
719 use the command \\[org-reveal] to show more context.
720 Instead of t, this can also be an alist specifying this option for different
721 contexts. See `org-show-hierarchy-above' for valid contexts."
722 :group 'org-reveal-location
723 :type org-context-choice)
725 (defcustom org-show-entry-below '((default . nil))
726 "Non-nil means show the entry below a headline when revealing a location.
727 Org-mode often shows locations in an org-mode file which might have
728 been invisible before. When this is set, the text below the headline that is
729 exposed is also shown.
731 By default this is off for all contexts.
732 Instead of t, this can also be an alist specifying this option for different
733 contexts. See `org-show-hierarchy-above' for valid contexts."
734 :group 'org-reveal-location
735 :type org-context-choice)
737 (defcustom org-indirect-buffer-display 'other-window
738 "How should indirect tree buffers be displayed?
739 This applies to indirect buffers created with the commands
740 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
741 Valid values are:
742 current-window Display in the current window
743 other-window Just display in another window.
744 dedicated-frame Create one new frame, and re-use it each time.
745 new-frame Make a new frame each time. Note that in this case
746 previously-made indirect buffers are kept, and you need to
747 kill these buffers yourself."
748 :group 'org-structure
749 :group 'org-agenda-windows
750 :type '(choice
751 (const :tag "In current window" current-window)
752 (const :tag "In current frame, other window" other-window)
753 (const :tag "Each time a new frame" new-frame)
754 (const :tag "One dedicated frame" dedicated-frame)))
756 (defcustom org-use-speed-commands nil
757 "Non-nil means activate single letter commands at beginning of a headline.
758 This may also be a function to test for appropriate locations where speed
759 commands should be active."
760 :group 'org-structure
761 :type '(choice
762 (const :tag "Never" nil)
763 (const :tag "At beginning of headline stars" t)
764 (function)))
766 (defcustom org-speed-commands-user nil
767 "Alist of additional speed commands.
768 This list will be checked before `org-speed-commands-default'
769 when the variable `org-use-speed-commands' is non-nil
770 and when the cursor is at the beginning of a headline.
771 The car if each entry is a string with a single letter, which must
772 be assigned to `self-insert-command' in the global map.
773 The cdr is either a command to be called interactively, a function
774 to be called, or a form to be evaluated.
775 An entry that is just a list with a single string will be interpreted
776 as a descriptive headline that will be added when listing the speed
777 commands in the Help buffer using the `?' speed command."
778 :group 'org-structure
779 :type '(repeat :value ("k" . ignore)
780 (choice :value ("k" . ignore)
781 (list :tag "Descriptive Headline" (string :tag "Headline"))
782 (cons :tag "Letter and Command"
783 (string :tag "Command letter")
784 (choice
785 (function)
786 (sexp))))))
788 (defgroup org-cycle nil
789 "Options concerning visibility cycling in Org-mode."
790 :tag "Org Cycle"
791 :group 'org-structure)
793 (defcustom org-cycle-skip-children-state-if-no-children t
794 "Non-nil means skip CHILDREN state in entries that don't have any."
795 :group 'org-cycle
796 :type 'boolean)
798 (defcustom org-cycle-max-level nil
799 "Maximum level which should still be subject to visibility cycling.
800 Levels higher than this will, for cycling, be treated as text, not a headline.
801 When `org-odd-levels-only' is set, a value of N in this variable actually
802 means 2N-1 stars as the limiting headline.
803 When nil, cycle all levels.
804 Note that the limiting level of cycling is also influenced by
805 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
806 `org-inlinetask-min-level' is, cycling will be limited to levels one less
807 than its value."
808 :group 'org-cycle
809 :type '(choice
810 (const :tag "No limit" nil)
811 (integer :tag "Maximum level")))
813 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK")
814 "Names of drawers. Drawers are not opened by cycling on the headline above.
815 Drawers only open with a TAB on the drawer line itself. A drawer looks like
816 this:
817 :DRAWERNAME:
818 .....
819 :END:
820 The drawer \"PROPERTIES\" is special for capturing properties through
821 the property API.
823 Drawers can be defined on the per-file basis with a line like:
825 #+DRAWERS: HIDDEN STATE PROPERTIES"
826 :group 'org-structure
827 :group 'org-cycle
828 :type '(repeat (string :tag "Drawer Name")))
830 (defcustom org-hide-block-startup nil
831 "Non-nil means entering Org-mode will fold all blocks.
832 This can also be set in on a per-file basis with
834 #+STARTUP: hideblocks
835 #+STARTUP: showblocks"
836 :group 'org-startup
837 :group 'org-cycle
838 :type 'boolean)
840 (defcustom org-cycle-global-at-bob nil
841 "Cycle globally if cursor is at beginning of buffer and not at a headline.
842 This makes it possible to do global cycling without having to use S-TAB or
843 \\[universal-argument] TAB. For this special case to work, the first line \
844 of the buffer
845 must not be a headline - it may be empty or some other text. When used in
846 this way, `org-cycle-hook' is disables temporarily, to make sure the
847 cursor stays at the beginning of the buffer.
848 When this option is nil, don't do anything special at the beginning
849 of the buffer."
850 :group 'org-cycle
851 :type 'boolean)
853 (defcustom org-cycle-level-after-item/entry-creation t
854 "Non-nil means cycle entry level or item indentation in new empty entries.
856 When the cursor is at the end of an empty headline, i.e with only stars
857 and maybe a TODO keyword, TAB will then switch the entry to become a child,
858 and then all possible ancestor states, before returning to the original state.
859 This makes data entry extremely fast: M-RET to create a new headline,
860 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
862 When the cursor is at the end of an empty plain list item, one TAB will
863 make it a subitem, two or more tabs will back up to make this an item
864 higher up in the item hierarchy."
865 :group 'org-cycle
866 :type 'boolean)
868 (defcustom org-cycle-emulate-tab t
869 "Where should `org-cycle' emulate TAB.
870 nil Never
871 white Only in completely white lines
872 whitestart Only at the beginning of lines, before the first non-white char
873 t Everywhere except in headlines
874 exc-hl-bol Everywhere except at the start of a headline
875 If TAB is used in a place where it does not emulate TAB, the current subtree
876 visibility is cycled."
877 :group 'org-cycle
878 :type '(choice (const :tag "Never" nil)
879 (const :tag "Only in completely white lines" white)
880 (const :tag "Before first char in a line" whitestart)
881 (const :tag "Everywhere except in headlines" t)
882 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
885 (defcustom org-cycle-separator-lines 2
886 "Number of empty lines needed to keep an empty line between collapsed trees.
887 If you leave an empty line between the end of a subtree and the following
888 headline, this empty line is hidden when the subtree is folded.
889 Org-mode will leave (exactly) one empty line visible if the number of
890 empty lines is equal or larger to the number given in this variable.
891 So the default 2 means at least 2 empty lines after the end of a subtree
892 are needed to produce free space between a collapsed subtree and the
893 following headline.
895 If the number is negative, and the number of empty lines is at least -N,
896 all empty lines are shown.
898 Special case: when 0, never leave empty lines in collapsed view."
899 :group 'org-cycle
900 :type 'integer)
901 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
903 (defcustom org-pre-cycle-hook nil
904 "Hook that is run before visibility cycling is happening.
905 The function(s) in this hook must accept a single argument which indicates
906 the new state that will be set right after running this hook. The
907 argument is a symbol. Before a global state change, it can have the values
908 `overview', `content', or `all'. Before a local state change, it can have
909 the values `folded', `children', or `subtree'."
910 :group 'org-cycle
911 :type 'hook)
913 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
914 org-cycle-hide-drawers
915 org-cycle-show-empty-lines
916 org-optimize-window-after-visibility-change)
917 "Hook that is run after `org-cycle' has changed the buffer visibility.
918 The function(s) in this hook must accept a single argument which indicates
919 the new state that was set by the most recent `org-cycle' command. The
920 argument is a symbol. After a global state change, it can have the values
921 `overview', `content', or `all'. After a local state change, it can have
922 the values `folded', `children', or `subtree'."
923 :group 'org-cycle
924 :type 'hook)
926 (defgroup org-edit-structure nil
927 "Options concerning structure editing in Org-mode."
928 :tag "Org Edit Structure"
929 :group 'org-structure)
931 (defcustom org-odd-levels-only nil
932 "Non-nil means skip even levels and only use odd levels for the outline.
933 This has the effect that two stars are being added/taken away in
934 promotion/demotion commands. It also influences how levels are
935 handled by the exporters.
936 Changing it requires restart of `font-lock-mode' to become effective
937 for fontification also in regions already fontified.
938 You may also set this on a per-file basis by adding one of the following
939 lines to the buffer:
941 #+STARTUP: odd
942 #+STARTUP: oddeven"
943 :group 'org-edit-structure
944 :group 'org-appearance
945 :type 'boolean)
947 (defcustom org-adapt-indentation t
948 "Non-nil means adapt indentation to outline node level.
950 When this variable is set, Org assumes that you write outlines by
951 indenting text in each node to align with the headline (after the stars).
952 The following issues are influenced by this variable:
954 - When this is set and the *entire* text in an entry is indented, the
955 indentation is increased by one space in a demotion command, and
956 decreased by one in a promotion command. If any line in the entry
957 body starts with text at column 0, indentation is not changed at all.
959 - Property drawers and planning information is inserted indented when
960 this variable s set. When nil, they will not be indented.
962 - TAB indents a line relative to context. The lines below a headline
963 will be indented when this variable is set.
965 Note that this is all about true indentation, by adding and removing
966 space characters. See also `org-indent.el' which does level-dependent
967 indentation in a virtual way, i.e. at display time in Emacs."
968 :group 'org-edit-structure
969 :type 'boolean)
971 (defcustom org-special-ctrl-a/e nil
972 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
974 When t, `C-a' will bring back the cursor to the beginning of the
975 headline text, i.e. after the stars and after a possible TODO keyword.
976 In an item, this will be the position after the bullet.
977 When the cursor is already at that position, another `C-a' will bring
978 it to the beginning of the line.
980 `C-e' will jump to the end of the headline, ignoring the presence of tags
981 in the headline. A second `C-e' will then jump to the true end of the
982 line, after any tags. This also means that, when this variable is
983 non-nil, `C-e' also will never jump beyond the end of the heading of a
984 folded section, i.e. not after the ellipses.
986 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
987 going to the true line boundary first. Only a directly following, identical
988 keypress will bring the cursor to the special positions.
990 This may also be a cons cell where the behavior for `C-a' and `C-e' is
991 set separately."
992 :group 'org-edit-structure
993 :type '(choice
994 (const :tag "off" nil)
995 (const :tag "on: after stars/bullet and before tags first" t)
996 (const :tag "reversed: true line boundary first" reversed)
997 (cons :tag "Set C-a and C-e separately"
998 (choice :tag "Special C-a"
999 (const :tag "off" nil)
1000 (const :tag "on: after stars/bullet first" t)
1001 (const :tag "reversed: before stars/bullet first" reversed))
1002 (choice :tag "Special C-e"
1003 (const :tag "off" nil)
1004 (const :tag "on: before tags first" t)
1005 (const :tag "reversed: after tags first" reversed)))))
1006 (if (fboundp 'defvaralias)
1007 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
1009 (defcustom org-special-ctrl-k nil
1010 "Non-nil means `C-k' will behave specially in headlines.
1011 When nil, `C-k' will call the default `kill-line' command.
1012 When t, the following will happen while the cursor is in the headline:
1014 - When the cursor is at the beginning of a headline, kill the entire
1015 line and possible the folded subtree below the line.
1016 - When in the middle of the headline text, kill the headline up to the tags.
1017 - When after the headline text, kill the tags."
1018 :group 'org-edit-structure
1019 :type 'boolean)
1021 (defcustom org-ctrl-k-protect-subtree nil
1022 "Non-nil means, do not delete a hidden subtree with C-k.
1023 When set to the symbol `error', simply throw an error when C-k is
1024 used to kill (part-of) a headline that has hidden text behind it.
1025 Any other non-nil value will result in a query to the user, if it is
1026 OK to kill that hidden subtree. When nil, kill without remorse."
1027 :group 'org-edit-structure
1028 :type '(choice
1029 (const :tag "Do not protect hidden subtrees" nil)
1030 (const :tag "Protect hidden subtrees with a security query" t)
1031 (const :tag "Never kill a hidden subtree with C-k" error)))
1033 (defcustom org-yank-folded-subtrees t
1034 "Non-nil means when yanking subtrees, fold them.
1035 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1036 it starts with a heading and all other headings in it are either children
1037 or siblings, then fold all the subtrees. However, do this only if no
1038 text after the yank would be swallowed into a folded tree by this action."
1039 :group 'org-edit-structure
1040 :type 'boolean)
1042 (defcustom org-yank-adjusted-subtrees nil
1043 "Non-nil means when yanking subtrees, adjust the level.
1044 With this setting, `org-paste-subtree' is used to insert the subtree, see
1045 this function for details."
1046 :group 'org-edit-structure
1047 :type 'boolean)
1049 (defcustom org-M-RET-may-split-line '((default . t))
1050 "Non-nil means M-RET will split the line at the cursor position.
1051 When nil, it will go to the end of the line before making a
1052 new line.
1053 You may also set this option in a different way for different
1054 contexts. Valid contexts are:
1056 headline when creating a new headline
1057 item when creating a new item
1058 table in a table field
1059 default the value to be used for all contexts not explicitly
1060 customized"
1061 :group 'org-structure
1062 :group 'org-table
1063 :type '(choice
1064 (const :tag "Always" t)
1065 (const :tag "Never" nil)
1066 (repeat :greedy t :tag "Individual contexts"
1067 (cons
1068 (choice :tag "Context"
1069 (const headline)
1070 (const item)
1071 (const table)
1072 (const default))
1073 (boolean)))))
1076 (defcustom org-insert-heading-respect-content nil
1077 "Non-nil means insert new headings after the current subtree.
1078 When nil, the new heading is created directly after the current line.
1079 The commands \\[org-insert-heading-respect-content] and
1080 \\[org-insert-todo-heading-respect-content] turn this variable on
1081 for the duration of the command."
1082 :group 'org-structure
1083 :type 'boolean)
1085 (defcustom org-blank-before-new-entry '((heading . auto)
1086 (plain-list-item . auto))
1087 "Should `org-insert-heading' leave a blank line before new heading/item?
1088 The value is an alist, with `heading' and `plain-list-item' as car,
1089 and a boolean flag as cdr. The cdr may also be the symbol `auto', and then
1090 Org will look at the surrounding headings/items and try to make an
1091 intelligent decision whether to insert a blank line or not.
1093 For plain lists, if the variable `org-empty-line-terminates-plain-lists' is
1094 set, the setting here is ignored and no empty line is inserted, to avoid
1095 breaking the list structure."
1096 :group 'org-edit-structure
1097 :type '(list
1098 (cons (const heading)
1099 (choice (const :tag "Never" nil)
1100 (const :tag "Always" t)
1101 (const :tag "Auto" auto)))
1102 (cons (const plain-list-item)
1103 (choice (const :tag "Never" nil)
1104 (const :tag "Always" t)
1105 (const :tag "Auto" auto)))))
1107 (defcustom org-numbered-action-format "TODO Action #%d "
1108 "Default structure of the headling of a new action.
1109 %d will become the number of the action."
1110 :group 'org-edit-structure
1111 :type 'string)
1113 (defcustom org-insert-heading-hook nil
1114 "Hook being run after inserting a new heading."
1115 :group 'org-edit-structure
1116 :type 'hook)
1118 (defcustom org-enable-fixed-width-editor t
1119 "Non-nil means lines starting with \":\" are treated as fixed-width.
1120 This currently only means they are never auto-wrapped.
1121 When nil, such lines will be treated like ordinary lines.
1122 See also the QUOTE keyword."
1123 :group 'org-edit-structure
1124 :type 'boolean)
1126 (defcustom org-goto-auto-isearch t
1127 "Non-nil means typing characters in `org-goto' starts incremental search."
1128 :group 'org-edit-structure
1129 :type 'boolean)
1131 (defgroup org-sparse-trees nil
1132 "Options concerning sparse trees in Org-mode."
1133 :tag "Org Sparse Trees"
1134 :group 'org-structure)
1136 (defcustom org-highlight-sparse-tree-matches t
1137 "Non-nil means highlight all matches that define a sparse tree.
1138 The highlights will automatically disappear the next time the buffer is
1139 changed by an edit command."
1140 :group 'org-sparse-trees
1141 :type 'boolean)
1143 (defcustom org-remove-highlights-with-change t
1144 "Non-nil means any change to the buffer will remove temporary highlights.
1145 Such highlights are created by `org-occur' and `org-clock-display'.
1146 When nil, `C-c C-c needs to be used to get rid of the highlights.
1147 The highlights created by `org-preview-latex-fragment' always need
1148 `C-c C-c' to be removed."
1149 :group 'org-sparse-trees
1150 :group 'org-time
1151 :type 'boolean)
1154 (defcustom org-occur-hook '(org-first-headline-recenter)
1155 "Hook that is run after `org-occur' has constructed a sparse tree.
1156 This can be used to recenter the window to show as much of the structure
1157 as possible."
1158 :group 'org-sparse-trees
1159 :type 'hook)
1161 (defgroup org-imenu-and-speedbar nil
1162 "Options concerning imenu and speedbar in Org-mode."
1163 :tag "Org Imenu and Speedbar"
1164 :group 'org-structure)
1166 (defcustom org-imenu-depth 2
1167 "The maximum level for Imenu access to Org-mode headlines.
1168 This also applied for speedbar access."
1169 :group 'org-imenu-and-speedbar
1170 :type 'integer)
1172 (defgroup org-table nil
1173 "Options concerning tables in Org-mode."
1174 :tag "Org Table"
1175 :group 'org)
1177 (defcustom org-enable-table-editor 'optimized
1178 "Non-nil means lines starting with \"|\" are handled by the table editor.
1179 When nil, such lines will be treated like ordinary lines.
1181 When equal to the symbol `optimized', the table editor will be optimized to
1182 do the following:
1183 - Automatic overwrite mode in front of whitespace in table fields.
1184 This makes the structure of the table stay in tact as long as the edited
1185 field does not exceed the column width.
1186 - Minimize the number of realigns. Normally, the table is aligned each time
1187 TAB or RET are pressed to move to another field. With optimization this
1188 happens only if changes to a field might have changed the column width.
1189 Optimization requires replacing the functions `self-insert-command',
1190 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1191 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1192 very good at guessing when a re-align will be necessary, but you can always
1193 force one with \\[org-ctrl-c-ctrl-c].
1195 If you would like to use the optimized version in Org-mode, but the
1196 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1198 This variable can be used to turn on and off the table editor during a session,
1199 but in order to toggle optimization, a restart is required.
1201 See also the variable `org-table-auto-blank-field'."
1202 :group 'org-table
1203 :type '(choice
1204 (const :tag "off" nil)
1205 (const :tag "on" t)
1206 (const :tag "on, optimized" optimized)))
1208 (defcustom org-self-insert-cluster-for-undo t
1209 "Non-nil means cluster self-insert commands for undo when possible.
1210 If this is set, then, like in the Emacs command loop, 20 consecutive
1211 characters will be undone together.
1212 This is configurable, because there is some impact on typing performance."
1213 :group 'org-table
1214 :type 'boolean)
1216 (defcustom org-table-tab-recognizes-table.el t
1217 "Non-nil means TAB will automatically notice a table.el table.
1218 When it sees such a table, it moves point into it and - if necessary -
1219 calls `table-recognize-table'."
1220 :group 'org-table-editing
1221 :type 'boolean)
1223 (defgroup org-link nil
1224 "Options concerning links in Org-mode."
1225 :tag "Org Link"
1226 :group 'org)
1228 (defvar org-link-abbrev-alist-local nil
1229 "Buffer-local version of `org-link-abbrev-alist', which see.
1230 The value of this is taken from the #+LINK lines.")
1231 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1233 (defcustom org-link-abbrev-alist nil
1234 "Alist of link abbreviations.
1235 The car of each element is a string, to be replaced at the start of a link.
1236 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1237 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1239 [[linkkey:tag][description]]
1241 The 'linkkey' must be a word word, starting with a letter, followed
1242 by letters, numbers, '-' or '_'.
1244 If REPLACE is a string, the tag will simply be appended to create the link.
1245 If the string contains \"%s\", the tag will be inserted there. Alternatively,
1246 the placeholder \"%h\" will cause a url-encoded version of the tag to
1247 be inserted at that point (see the function `url-hexify-string').
1249 REPLACE may also be a function that will be called with the tag as the
1250 only argument to create the link, which should be returned as a string.
1252 See the manual for examples."
1253 :group 'org-link
1254 :type '(repeat
1255 (cons
1256 (string :tag "Protocol")
1257 (choice
1258 (string :tag "Format")
1259 (function)))))
1261 (defcustom org-descriptive-links t
1262 "Non-nil means hide link part and only show description of bracket links.
1263 Bracket links are like [[link][description]]. This variable sets the initial
1264 state in new org-mode buffers. The setting can then be toggled on a
1265 per-buffer basis from the Org->Hyperlinks menu."
1266 :group 'org-link
1267 :type 'boolean)
1269 (defcustom org-link-file-path-type 'adaptive
1270 "How the path name in file links should be stored.
1271 Valid values are:
1273 relative Relative to the current directory, i.e. the directory of the file
1274 into which the link is being inserted.
1275 absolute Absolute path, if possible with ~ for home directory.
1276 noabbrev Absolute path, no abbreviation of home directory.
1277 adaptive Use relative path for files in the current directory and sub-
1278 directories of it. For other files, use an absolute path."
1279 :group 'org-link
1280 :type '(choice
1281 (const relative)
1282 (const absolute)
1283 (const noabbrev)
1284 (const adaptive)))
1286 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1287 "Types of links that should be activated in Org-mode files.
1288 This is a list of symbols, each leading to the activation of a certain link
1289 type. In principle, it does not hurt to turn on most link types - there may
1290 be a small gain when turning off unused link types. The types are:
1292 bracket The recommended [[link][description]] or [[link]] links with hiding.
1293 angle Links in angular brackets that may contain whitespace like
1294 <bbdb:Carsten Dominik>.
1295 plain Plain links in normal text, no whitespace, like http://google.com.
1296 radio Text that is matched by a radio target, see manual for details.
1297 tag Tag settings in a headline (link to tag search).
1298 date Time stamps (link to calendar).
1299 footnote Footnote labels.
1301 Changing this variable requires a restart of Emacs to become effective."
1302 :group 'org-link
1303 :type '(set :greedy t
1304 (const :tag "Double bracket links" bracket)
1305 (const :tag "Angular bracket links" angle)
1306 (const :tag "Plain text links" plain)
1307 (const :tag "Radio target matches" radio)
1308 (const :tag "Tags" tag)
1309 (const :tag "Timestamps" date)
1310 (const :tag "Footnotes" footnote)))
1312 (defcustom org-make-link-description-function nil
1313 "Function to use to generate link descriptions from links.
1314 If nil the link location will be used. This function must take
1315 two parameters; the first is the link and the second the
1316 description `org-insert-link' has generated, and should return the
1317 description to use."
1318 :group 'org-link
1319 :type 'function)
1321 (defgroup org-link-store nil
1322 "Options concerning storing links in Org-mode."
1323 :tag "Org Store Link"
1324 :group 'org-link)
1326 (defcustom org-email-link-description-format "Email %c: %.30s"
1327 "Format of the description part of a link to an email or usenet message.
1328 The following %-escapes will be replaced by corresponding information:
1330 %F full \"From\" field
1331 %f name, taken from \"From\" field, address if no name
1332 %T full \"To\" field
1333 %t first name in \"To\" field, address if no name
1334 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1335 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1336 %s subject
1337 %d date
1338 %m message-id.
1340 You may use normal field width specification between the % and the letter.
1341 This is for example useful to limit the length of the subject.
1343 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1344 :group 'org-link-store
1345 :type 'string)
1347 (defcustom org-from-is-user-regexp
1348 (let (r1 r2)
1349 (when (and user-mail-address (not (string= user-mail-address "")))
1350 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1351 (when (and user-full-name (not (string= user-full-name "")))
1352 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1353 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1354 "Regexp matched against the \"From:\" header of an email or usenet message.
1355 It should match if the message is from the user him/herself."
1356 :group 'org-link-store
1357 :type 'regexp)
1359 (defcustom org-link-to-org-use-id 'create-if-interactive-and-no-custom-id
1360 "Non-nil means storing a link to an Org file will use entry IDs.
1362 Note that before this variable is even considered, org-id must be loaded,
1363 so please customize `org-modules' and turn it on.
1365 The variable can have the following values:
1367 t Create an ID if needed to make a link to the current entry.
1369 create-if-interactive
1370 If `org-store-link' is called directly (interactively, as a user
1371 command), do create an ID to support the link. But when doing the
1372 job for remember, only use the ID if it already exists. The
1373 purpose of this setting is to avoid proliferation of unwanted
1374 IDs, just because you happen to be in an Org file when you
1375 call `org-remember' that automatically and preemptively
1376 creates a link. If you do want to get an ID link in a remember
1377 template to an entry not having an ID, create it first by
1378 explicitly creating a link to it, using `C-c C-l' first.
1380 create-if-interactive-and-no-custom-id
1381 Like create-if-interactive, but do not create an ID if there is
1382 a CUSTOM_ID property defined in the entry. This is the default.
1384 use-existing
1385 Use existing ID, do not create one.
1387 nil Never use an ID to make a link, instead link using a text search for
1388 the headline text."
1389 :group 'org-link-store
1390 :type '(choice
1391 (const :tag "Create ID to make link" t)
1392 (const :tag "Create if storing link interactively"
1393 create-if-interactive)
1394 (const :tag "Create if storing link interactively and no CUSTOM_ID is present"
1395 create-if-interactive-and-no-custom-id)
1396 (const :tag "Only use existing" use-existing)
1397 (const :tag "Do not use ID to create link" nil)))
1399 (defcustom org-context-in-file-links t
1400 "Non-nil means file links from `org-store-link' contain context.
1401 A search string will be added to the file name with :: as separator and
1402 used to find the context when the link is activated by the command
1403 `org-open-at-point'. When this option is t, the entire active region
1404 will be placed in the search string of the file link. If set to a
1405 positive integer, only the first n lines of context will be stored.
1407 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1408 negates this setting for the duration of the command."
1409 :group 'org-link-store
1410 :type '(choice boolean integer))
1412 (defcustom org-keep-stored-link-after-insertion nil
1413 "Non-nil means keep link in list for entire session.
1415 The command `org-store-link' adds a link pointing to the current
1416 location to an internal list. These links accumulate during a session.
1417 The command `org-insert-link' can be used to insert links into any
1418 Org-mode file (offering completion for all stored links). When this
1419 option is nil, every link which has been inserted once using \\[org-insert-link]
1420 will be removed from the list, to make completing the unused links
1421 more efficient."
1422 :group 'org-link-store
1423 :type 'boolean)
1425 (defgroup org-link-follow nil
1426 "Options concerning following links in Org-mode."
1427 :tag "Org Follow Link"
1428 :group 'org-link)
1430 (defcustom org-link-translation-function nil
1431 "Function to translate links with different syntax to Org syntax.
1432 This can be used to translate links created for example by the Planner
1433 or emacs-wiki packages to Org syntax.
1434 The function must accept two parameters, a TYPE containing the link
1435 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1436 which is everything after the link protocol. It should return a cons
1437 with possibly modified values of type and path.
1438 Org contains a function for this, so if you set this variable to
1439 `org-translate-link-from-planner', you should be able follow many
1440 links created by planner."
1441 :group 'org-link-follow
1442 :type 'function)
1444 (defcustom org-follow-link-hook nil
1445 "Hook that is run after a link has been followed."
1446 :group 'org-link-follow
1447 :type 'hook)
1449 (defcustom org-tab-follows-link nil
1450 "Non-nil means on links TAB will follow the link.
1451 Needs to be set before org.el is loaded.
1452 This really should not be used, it does not make sense, and the
1453 implementation is bad."
1454 :group 'org-link-follow
1455 :type 'boolean)
1457 (defcustom org-return-follows-link nil
1458 "Non-nil means on links RET will follow the link."
1459 :group 'org-link-follow
1460 :type 'boolean)
1462 (defcustom org-mouse-1-follows-link
1463 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1464 "Non-nil means mouse-1 on a link will follow the link.
1465 A longer mouse click will still set point. Does not work on XEmacs.
1466 Needs to be set before org.el is loaded."
1467 :group 'org-link-follow
1468 :type 'boolean)
1470 (defcustom org-mark-ring-length 4
1471 "Number of different positions to be recorded in the ring.
1472 Changing this requires a restart of Emacs to work correctly."
1473 :group 'org-link-follow
1474 :type 'integer)
1476 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1477 "Non-nil means internal links in Org files must exactly match a headline.
1478 When nil, the link search tries to match a phrase with all words
1479 in the search text."
1480 :group 'org-link-follow
1481 :type '(choice
1482 (const :tag "Use fuzy text search" nil)
1483 (const :tag "Match only exact headline" t)
1484 (const :tag "Match extact headline or query to create it"
1485 query-to-create)))
1487 (defcustom org-link-frame-setup
1488 '((vm . vm-visit-folder-other-frame)
1489 (gnus . org-gnus-no-new-news)
1490 (file . find-file-other-window)
1491 (wl . wl-other-frame))
1492 "Setup the frame configuration for following links.
1493 When following a link with Emacs, it may often be useful to display
1494 this link in another window or frame. This variable can be used to
1495 set this up for the different types of links.
1496 For VM, use any of
1497 `vm-visit-folder'
1498 `vm-visit-folder-other-window'
1499 `vm-visit-folder-other-frame'
1500 For Gnus, use any of
1501 `gnus'
1502 `gnus-other-frame'
1503 `org-gnus-no-new-news'
1504 For FILE, use any of
1505 `find-file'
1506 `find-file-other-window'
1507 `find-file-other-frame'
1508 For Wanderlust use any of
1509 `wl'
1510 `wl-other-frame'
1511 For the calendar, use the variable `calendar-setup'.
1512 For BBDB, it is currently only possible to display the matches in
1513 another window."
1514 :group 'org-link-follow
1515 :type '(list
1516 (cons (const vm)
1517 (choice
1518 (const vm-visit-folder)
1519 (const vm-visit-folder-other-window)
1520 (const vm-visit-folder-other-frame)))
1521 (cons (const gnus)
1522 (choice
1523 (const gnus)
1524 (const gnus-other-frame)
1525 (const org-gnus-no-new-news)))
1526 (cons (const file)
1527 (choice
1528 (const find-file)
1529 (const find-file-other-window)
1530 (const find-file-other-frame)))
1531 (cons (const wl)
1532 (choice
1533 (const wl)
1534 (const wl-other-frame)))))
1536 (defcustom org-display-internal-link-with-indirect-buffer nil
1537 "Non-nil means use indirect buffer to display infile links.
1538 Activating internal links (from one location in a file to another location
1539 in the same file) normally just jumps to the location. When the link is
1540 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1541 is displayed in
1542 another window. When this option is set, the other window actually displays
1543 an indirect buffer clone of the current buffer, to avoid any visibility
1544 changes to the current buffer."
1545 :group 'org-link-follow
1546 :type 'boolean)
1548 (defcustom org-open-non-existing-files nil
1549 "Non-nil means `org-open-file' will open non-existing files.
1550 When nil, an error will be generated.
1551 This variable applies only to external applications because they
1552 might choke on non-existing files. If the link is to a file that
1553 will be opened in Emacs, the variable is ignored."
1554 :group 'org-link-follow
1555 :type 'boolean)
1557 (defcustom org-open-directory-means-index-dot-org nil
1558 "Non-nil means a link to a directory really means to index.org.
1559 When nil, following a directory link will run dired or open a finder/explorer
1560 window on that directory."
1561 :group 'org-link-follow
1562 :type 'boolean)
1564 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1565 "Function and arguments to call for following mailto links.
1566 This is a list with the first element being a Lisp function, and the
1567 remaining elements being arguments to the function. In string arguments,
1568 %a will be replaced by the address, and %s will be replaced by the subject
1569 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1570 :group 'org-link-follow
1571 :type '(choice
1572 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1573 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1574 (const :tag "message-mail" (message-mail "%a" "%s"))
1575 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1577 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1578 "Non-nil means ask for confirmation before executing shell links.
1579 Shell links can be dangerous: just think about a link
1581 [[shell:rm -rf ~/*][Google Search]]
1583 This link would show up in your Org-mode document as \"Google Search\",
1584 but really it would remove your entire home directory.
1585 Therefore we advise against setting this variable to nil.
1586 Just change it to `y-or-n-p' if you want to confirm with a
1587 single keystroke rather than having to type \"yes\"."
1588 :group 'org-link-follow
1589 :type '(choice
1590 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1591 (const :tag "with y-or-n (faster)" y-or-n-p)
1592 (const :tag "no confirmation (dangerous)" nil)))
1593 (put 'org-confirm-shell-link-function
1594 'safe-local-variable
1595 '(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1597 (defcustom org-confirm-shell-link-not-regexp ""
1598 "A regexp to skip confirmation for shell links."
1599 :group 'org-link-follow
1600 :type 'regexp)
1602 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1603 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1604 Elisp links can be dangerous: just think about a link
1606 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1608 This link would show up in your Org-mode document as \"Google Search\",
1609 but really it would remove your entire home directory.
1610 Therefore we advise against setting this variable to nil.
1611 Just change it to `y-or-n-p' if you want to confirm with a
1612 single keystroke rather than having to type \"yes\"."
1613 :group 'org-link-follow
1614 :type '(choice
1615 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1616 (const :tag "with y-or-n (faster)" y-or-n-p)
1617 (const :tag "no confirmation (dangerous)" nil)))
1618 (put 'org-confirm-shell-link-function
1619 'safe-local-variable
1620 '(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1622 (defcustom org-confirm-elisp-link-not-regexp ""
1623 "A regexp to skip confirmation for Elisp links."
1624 :group 'org-link-follow
1625 :type 'regexp)
1627 (defconst org-file-apps-defaults-gnu
1628 '((remote . emacs)
1629 (system . mailcap)
1630 (t . mailcap))
1631 "Default file applications on a UNIX or GNU/Linux system.
1632 See `org-file-apps'.")
1634 (defconst org-file-apps-defaults-macosx
1635 '((remote . emacs)
1636 (t . "open %s")
1637 (system . "open %s")
1638 ("ps.gz" . "gv %s")
1639 ("eps.gz" . "gv %s")
1640 ("dvi" . "xdvi %s")
1641 ("fig" . "xfig %s"))
1642 "Default file applications on a MacOS X system.
1643 The system \"open\" is known as a default, but we use X11 applications
1644 for some files for which the OS does not have a good default.
1645 See `org-file-apps'.")
1647 (defconst org-file-apps-defaults-windowsnt
1648 (list
1649 '(remote . emacs)
1650 (cons t
1651 (list (if (featurep 'xemacs)
1652 'mswindows-shell-execute
1653 'w32-shell-execute)
1654 "open" 'file))
1655 (cons 'system
1656 (list (if (featurep 'xemacs)
1657 'mswindows-shell-execute
1658 'w32-shell-execute)
1659 "open" 'file)))
1660 "Default file applications on a Windows NT system.
1661 The system \"open\" is used for most files.
1662 See `org-file-apps'.")
1664 (defcustom org-file-apps
1666 (auto-mode . emacs)
1667 ("\\.mm\\'" . default)
1668 ("\\.x?html?\\'" . default)
1669 ("\\.pdf\\'" . default)
1671 "External applications for opening `file:path' items in a document.
1672 Org-mode uses system defaults for different file types, but
1673 you can use this variable to set the application for a given file
1674 extension. The entries in this list are cons cells where the car identifies
1675 files and the cdr the corresponding command. Possible values for the
1676 file identifier are
1677 \"string\" A string as a file identifier can be interpreted in different
1678 ways, depending on its contents:
1680 - Alphanumeric characters only:
1681 Match links with this file extension.
1682 Example: (\"pdf\" . \"evince %s\")
1683 to open PDFs with evince.
1685 - Regular expression: Match links where the
1686 filename matches the regexp. If you want to
1687 use groups here, use shy groups.
1689 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1690 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1691 to open *.html and *.xhtml with firefox.
1693 - Regular expression which contains (non-shy) groups:
1694 Match links where the whole link, including \"::\", and
1695 anything after that, matches the regexp.
1696 In a custom command string, %1, %2, etc. are replaced with
1697 the parts of the link that were matched by the groups.
1698 For backwards compatibility, if a command string is given
1699 that does not use any of the group matches, this case is
1700 handled identically to the second one (i.e. match against
1701 file name only).
1702 In a custom lisp form, you can access the group matches with
1703 (match-string n link).
1705 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1706 to open [[file:document.pdf::5]] with evince at page 5.
1708 `directory' Matches a directory
1709 `remote' Matches a remote file, accessible through tramp or efs.
1710 Remote files most likely should be visited through Emacs
1711 because external applications cannot handle such paths.
1712 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1713 so all files Emacs knows how to handle. Using this with
1714 command `emacs' will open most files in Emacs. Beware that this
1715 will also open html files inside Emacs, unless you add
1716 (\"html\" . default) to the list as well.
1717 t Default for files not matched by any of the other options.
1718 `system' The system command to open files, like `open' on Windows
1719 and Mac OS X, and mailcap under GNU/Linux. This is the command
1720 that will be selected if you call `C-c C-o' with a double
1721 \\[universal-argument] \\[universal-argument] prefix.
1723 Possible values for the command are:
1724 `emacs' The file will be visited by the current Emacs process.
1725 `default' Use the default application for this file type, which is the
1726 association for t in the list, most likely in the system-specific
1727 part.
1728 This can be used to overrule an unwanted setting in the
1729 system-specific variable.
1730 `system' Use the system command for opening files, like \"open\".
1731 This command is specified by the entry whose car is `system'.
1732 Most likely, the system-specific version of this variable
1733 does define this command, but you can overrule/replace it
1734 here.
1735 string A command to be executed by a shell; %s will be replaced
1736 by the path to the file.
1737 sexp A Lisp form which will be evaluated. The file path will
1738 be available in the Lisp variable `file'.
1739 For more examples, see the system specific constants
1740 `org-file-apps-defaults-macosx'
1741 `org-file-apps-defaults-windowsnt'
1742 `org-file-apps-defaults-gnu'."
1743 :group 'org-link-follow
1744 :type '(repeat
1745 (cons (choice :value ""
1746 (string :tag "Extension")
1747 (const :tag "System command to open files" system)
1748 (const :tag "Default for unrecognized files" t)
1749 (const :tag "Remote file" remote)
1750 (const :tag "Links to a directory" directory)
1751 (const :tag "Any files that have Emacs modes"
1752 auto-mode))
1753 (choice :value ""
1754 (const :tag "Visit with Emacs" emacs)
1755 (const :tag "Use default" default)
1756 (const :tag "Use the system command" system)
1757 (string :tag "Command")
1758 (sexp :tag "Lisp form")))))
1762 (defgroup org-refile nil
1763 "Options concerning refiling entries in Org-mode."
1764 :tag "Org Refile"
1765 :group 'org)
1767 (defcustom org-directory "~/org"
1768 "Directory with org files.
1769 This is just a default location to look for Org files. There is no need
1770 at all to put your files into this directory. It is only used in the
1771 following situations:
1773 1. When a remember template specifies a target file that is not an
1774 absolute path. The path will then be interpreted relative to
1775 `org-directory'
1776 2. When a remember note is filed away in an interactive way (when exiting the
1777 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1778 with `org-directory' as the default path."
1779 :group 'org-refile
1780 :group 'org-remember
1781 :type 'directory)
1783 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1784 "Default target for storing notes.
1785 Used as a fall back file for org-remember.el and org-capture.el, for
1786 templates that do not specify a target file."
1787 :group 'org-refile
1788 :group 'org-remember
1789 :type '(choice
1790 (const :tag "Default from remember-data-file" nil)
1791 file))
1793 (defcustom org-goto-interface 'outline
1794 "The default interface to be used for `org-goto'.
1795 Allowed values are:
1796 outline The interface shows an outline of the relevant file
1797 and the correct heading is found by moving through
1798 the outline or by searching with incremental search.
1799 outline-path-completion Headlines in the current buffer are offered via
1800 completion. This is the interface also used by
1801 the refile command."
1802 :group 'org-refile
1803 :type '(choice
1804 (const :tag "Outline" outline)
1805 (const :tag "Outline-path-completion" outline-path-completion)))
1807 (defcustom org-goto-max-level 5
1808 "Maximum target level when running `org-goto' with refile interface."
1809 :group 'org-refile
1810 :type 'integer)
1812 (defcustom org-reverse-note-order nil
1813 "Non-nil means store new notes at the beginning of a file or entry.
1814 When nil, new notes will be filed to the end of a file or entry.
1815 This can also be a list with cons cells of regular expressions that
1816 are matched against file names, and values."
1817 :group 'org-remember
1818 :group 'org-refile
1819 :type '(choice
1820 (const :tag "Reverse always" t)
1821 (const :tag "Reverse never" nil)
1822 (repeat :tag "By file name regexp"
1823 (cons regexp boolean))))
1825 (defcustom org-log-refile nil
1826 "Information to record when a task is refiled.
1828 Possible values are:
1830 nil Don't add anything
1831 time Add a time stamp to the task
1832 note Prompt for a note and add it with template `org-log-note-headings'
1834 This option can also be set with on a per-file-basis with
1836 #+STARTUP: nologrefile
1837 #+STARTUP: logrefile
1838 #+STARTUP: lognoterefile
1840 You can have local logging settings for a subtree by setting the LOGGING
1841 property to one or more of these keywords.
1843 When bulk-refiling from the agenda, the value `note' is forbidden and
1844 will temporarily be changed to `time'."
1845 :group 'org-refile
1846 :group 'org-progress
1847 :type '(choice
1848 (const :tag "No logging" nil)
1849 (const :tag "Record timestamp" time)
1850 (const :tag "Record timestamp with note." note)))
1852 (defcustom org-refile-targets nil
1853 "Targets for refiling entries with \\[org-refile].
1854 This is list of cons cells. Each cell contains:
1855 - a specification of the files to be considered, either a list of files,
1856 or a symbol whose function or variable value will be used to retrieve
1857 a file name or a list of file names. If you use `org-agenda-files' for
1858 that, all agenda files will be scanned for targets. Nil means consider
1859 headings in the current buffer.
1860 - A specification of how to find candidate refile targets. This may be
1861 any of:
1862 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1863 This tag has to be present in all target headlines, inheritance will
1864 not be considered.
1865 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1866 todo keyword.
1867 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1868 headlines that are refiling targets.
1869 - a cons cell (:level . N). Any headline of level N is considered a target.
1870 Note that, when `org-odd-levels-only' is set, level corresponds to
1871 order in hierarchy, not to the number of stars.
1872 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1873 Note that, when `org-odd-levels-only' is set, level corresponds to
1874 order in hierarchy, not to the number of stars.
1876 You can set the variable `org-refile-target-verify-function' to a function
1877 to verify each headline found by the simple criteria above.
1879 When this variable is nil, all top-level headlines in the current buffer
1880 are used, equivalent to the value `((nil . (:level . 1))'."
1881 :group 'org-refile
1882 :type '(repeat
1883 (cons
1884 (choice :value org-agenda-files
1885 (const :tag "All agenda files" org-agenda-files)
1886 (const :tag "Current buffer" nil)
1887 (function) (variable) (file))
1888 (choice :tag "Identify target headline by"
1889 (cons :tag "Specific tag" (const :value :tag) (string))
1890 (cons :tag "TODO keyword" (const :value :todo) (string))
1891 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1892 (cons :tag "Level number" (const :value :level) (integer))
1893 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1895 (defcustom org-refile-target-verify-function nil
1896 "Function to verify if the headline at point should be a refile target.
1897 The function will be called without arguments, with point at the
1898 beginning of the headline. It should return t and leave point
1899 where it is if the headline is a valid target for refiling.
1901 If the target should not be selected, the function must return nil.
1902 In addition to this, it may move point to a place from where the search
1903 should be continued. For example, the function may decide that the entire
1904 subtree of the current entry should be excluded and move point to the end
1905 of the subtree."
1906 :group 'org-refile
1907 :type 'function)
1909 (defcustom org-refile-use-cache nil
1910 "Non-nil means cache refile targets to speed up the process.
1911 The cache for a particular file will be updated automatically when
1912 the buffer has been killed, or when any of the marker used for flagging
1913 refile targets no longer points at a live buffer.
1914 If you have added new entries to a buffer that might themselves be targets,
1915 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
1916 find that easier, `C-u C-u C-u C-c C-w'."
1917 :group 'org-refile
1918 :type 'boolean)
1920 (defcustom org-refile-use-outline-path nil
1921 "Non-nil means provide refile targets as paths.
1922 So a level 3 headline will be available as level1/level2/level3.
1924 When the value is `file', also include the file name (without directory)
1925 into the path. In this case, you can also stop the completion after
1926 the file name, to get entries inserted as top level in the file.
1928 When `full-file-path', include the full file path."
1929 :group 'org-refile
1930 :type '(choice
1931 (const :tag "Not" nil)
1932 (const :tag "Yes" t)
1933 (const :tag "Start with file name" file)
1934 (const :tag "Start with full file path" full-file-path)))
1936 (defcustom org-outline-path-complete-in-steps t
1937 "Non-nil means complete the outline path in hierarchical steps.
1938 When Org-mode uses the refile interface to select an outline path
1939 \(see variable `org-refile-use-outline-path'), the completion of
1940 the path can be done is a single go, or if can be done in steps down
1941 the headline hierarchy. Going in steps is probably the best if you
1942 do not use a special completion package like `ido' or `icicles'.
1943 However, when using these packages, going in one step can be very
1944 fast, while still showing the whole path to the entry."
1945 :group 'org-refile
1946 :type 'boolean)
1948 (defcustom org-refile-allow-creating-parent-nodes nil
1949 "Non-nil means allow to create new nodes as refile targets.
1950 New nodes are then created by adding \"/new node name\" to the completion
1951 of an existing node. When the value of this variable is `confirm',
1952 new node creation must be confirmed by the user (recommended)
1953 When nil, the completion must match an existing entry.
1955 Note that, if the new heading is not seen by the criteria
1956 listed in `org-refile-targets', multiple instances of the same
1957 heading would be created by trying again to file under the new
1958 heading."
1959 :group 'org-refile
1960 :type '(choice
1961 (const :tag "Never" nil)
1962 (const :tag "Always" t)
1963 (const :tag "Prompt for confirmation" confirm)))
1965 (defgroup org-todo nil
1966 "Options concerning TODO items in Org-mode."
1967 :tag "Org TODO"
1968 :group 'org)
1970 (defgroup org-progress nil
1971 "Options concerning Progress logging in Org-mode."
1972 :tag "Org Progress"
1973 :group 'org-time)
1975 (defvar org-todo-interpretation-widgets
1977 (:tag "Sequence (cycling hits every state)" sequence)
1978 (:tag "Type (cycling directly to DONE)" type))
1979 "The available interpretation symbols for customizing `org-todo-keywords'.
1980 Interested libraries should add to this list.")
1982 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1983 "List of TODO entry keyword sequences and their interpretation.
1984 \\<org-mode-map>This is a list of sequences.
1986 Each sequence starts with a symbol, either `sequence' or `type',
1987 indicating if the keywords should be interpreted as a sequence of
1988 action steps, or as different types of TODO items. The first
1989 keywords are states requiring action - these states will select a headline
1990 for inclusion into the global TODO list Org-mode produces. If one of
1991 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
1992 signify that no further action is necessary. If \"|\" is not found,
1993 the last keyword is treated as the only DONE state of the sequence.
1995 The command \\[org-todo] cycles an entry through these states, and one
1996 additional state where no keyword is present. For details about this
1997 cycling, see the manual.
1999 TODO keywords and interpretation can also be set on a per-file basis with
2000 the special #+SEQ_TODO and #+TYP_TODO lines.
2002 Each keyword can optionally specify a character for fast state selection
2003 \(in combination with the variable `org-use-fast-todo-selection')
2004 and specifiers for state change logging, using the same syntax
2005 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
2006 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2007 indicates to record a time stamp each time this state is selected.
2009 Each keyword may also specify if a timestamp or a note should be
2010 recorded when entering or leaving the state, by adding additional
2011 characters in the parenthesis after the keyword. This looks like this:
2012 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2013 record only the time of the state change. With X and Y being either
2014 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2015 Y when leaving the state if and only if the *target* state does not
2016 define X. You may omit any of the fast-selection key or X or /Y,
2017 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2019 For backward compatibility, this variable may also be just a list
2020 of keywords - in this case the interpretation (sequence or type) will be
2021 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2022 :group 'org-todo
2023 :group 'org-keywords
2024 :type '(choice
2025 (repeat :tag "Old syntax, just keywords"
2026 (string :tag "Keyword"))
2027 (repeat :tag "New syntax"
2028 (cons
2029 (choice
2030 :tag "Interpretation"
2031 ;;Quick and dirty way to see
2032 ;;`org-todo-interpretations'. This takes the
2033 ;;place of item arguments
2034 :convert-widget
2035 (lambda (widget)
2036 (widget-put widget
2037 :args (mapcar
2038 #'(lambda (x)
2039 (widget-convert
2040 (cons 'const x)))
2041 org-todo-interpretation-widgets))
2042 widget))
2043 (repeat
2044 (string :tag "Keyword"))))))
2046 (defvar org-todo-keywords-1 nil
2047 "All TODO and DONE keywords active in a buffer.")
2048 (make-variable-buffer-local 'org-todo-keywords-1)
2049 (defvar org-todo-keywords-for-agenda nil)
2050 (defvar org-done-keywords-for-agenda nil)
2051 (defvar org-drawers-for-agenda nil)
2052 (defvar org-todo-keyword-alist-for-agenda nil)
2053 (defvar org-tag-alist-for-agenda nil)
2054 (defvar org-agenda-contributing-files nil)
2055 (defvar org-not-done-keywords nil)
2056 (make-variable-buffer-local 'org-not-done-keywords)
2057 (defvar org-done-keywords nil)
2058 (make-variable-buffer-local 'org-done-keywords)
2059 (defvar org-todo-heads nil)
2060 (make-variable-buffer-local 'org-todo-heads)
2061 (defvar org-todo-sets nil)
2062 (make-variable-buffer-local 'org-todo-sets)
2063 (defvar org-todo-log-states nil)
2064 (make-variable-buffer-local 'org-todo-log-states)
2065 (defvar org-todo-kwd-alist nil)
2066 (make-variable-buffer-local 'org-todo-kwd-alist)
2067 (defvar org-todo-key-alist nil)
2068 (make-variable-buffer-local 'org-todo-key-alist)
2069 (defvar org-todo-key-trigger nil)
2070 (make-variable-buffer-local 'org-todo-key-trigger)
2072 (defcustom org-todo-interpretation 'sequence
2073 "Controls how TODO keywords are interpreted.
2074 This variable is in principle obsolete and is only used for
2075 backward compatibility, if the interpretation of todo keywords is
2076 not given already in `org-todo-keywords'. See that variable for
2077 more information."
2078 :group 'org-todo
2079 :group 'org-keywords
2080 :type '(choice (const sequence)
2081 (const type)))
2083 (defcustom org-use-fast-todo-selection t
2084 "Non-nil means use the fast todo selection scheme with C-c C-t.
2085 This variable describes if and under what circumstances the cycling
2086 mechanism for TODO keywords will be replaced by a single-key, direct
2087 selection scheme.
2089 When nil, fast selection is never used.
2091 When the symbol `prefix', it will be used when `org-todo' is called with
2092 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
2093 in an agenda buffer.
2095 When t, fast selection is used by default. In this case, the prefix
2096 argument forces cycling instead.
2098 In all cases, the special interface is only used if access keys have actually
2099 been assigned by the user, i.e. if keywords in the configuration are followed
2100 by a letter in parenthesis, like TODO(t)."
2101 :group 'org-todo
2102 :type '(choice
2103 (const :tag "Never" nil)
2104 (const :tag "By default" t)
2105 (const :tag "Only with C-u C-c C-t" prefix)))
2107 (defcustom org-provide-todo-statistics t
2108 "Non-nil means update todo statistics after insert and toggle.
2109 ALL-HEADLINES means update todo statistics by including headlines
2110 with no TODO keyword as well, counting them as not done.
2111 A list of TODO keywords means the same, but skip keywords that are
2112 not in this list.
2114 When this is set, todo statistics is updated in the parent of the
2115 current entry each time a todo state is changed."
2116 :group 'org-todo
2117 :type '(choice
2118 (const :tag "Yes, only for TODO entries" t)
2119 (const :tag "Yes, including all entries" 'all-headlines)
2120 (repeat :tag "Yes, for TODOs in this list"
2121 (string :tag "TODO keyword"))
2122 (other :tag "No TODO statistics" nil)))
2124 (defcustom org-hierarchical-todo-statistics t
2125 "Non-nil means TODO statistics covers just direct children.
2126 When nil, all entries in the subtree are considered.
2127 This has only an effect if `org-provide-todo-statistics' is set.
2128 To set this to nil for only a single subtree, use a COOKIE_DATA
2129 property and include the word \"recursive\" into the value."
2130 :group 'org-todo
2131 :type 'boolean)
2133 (defcustom org-after-todo-state-change-hook nil
2134 "Hook which is run after the state of a TODO item was changed.
2135 The new state (a string with a TODO keyword, or nil) is available in the
2136 Lisp variable `state'."
2137 :group 'org-todo
2138 :type 'hook)
2140 (defvar org-blocker-hook nil
2141 "Hook for functions that are allowed to block a state change.
2143 Each function gets as its single argument a property list, see
2144 `org-trigger-hook' for more information about this list.
2146 If any of the functions in this hook returns nil, the state change
2147 is blocked.")
2149 (defvar org-trigger-hook nil
2150 "Hook for functions that are triggered by a state change.
2152 Each function gets as its single argument a property list with at least
2153 the following elements:
2155 (:type type-of-change :position pos-at-entry-start
2156 :from old-state :to new-state)
2158 Depending on the type, more properties may be present.
2160 This mechanism is currently implemented for:
2162 TODO state changes
2163 ------------------
2164 :type todo-state-change
2165 :from previous state (keyword as a string), or nil, or a symbol
2166 'todo' or 'done', to indicate the general type of state.
2167 :to new state, like in :from")
2169 (defcustom org-enforce-todo-dependencies nil
2170 "Non-nil means undone TODO entries will block switching the parent to DONE.
2171 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2172 be blocked if any prior sibling is not yet done.
2173 Finally, if the parent is blocked because of ordered siblings of its own,
2174 the child will also be blocked.
2175 This variable needs to be set before org.el is loaded, and you need to
2176 restart Emacs after a change to make the change effective. The only way
2177 to change is while Emacs is running is through the customize interface."
2178 :set (lambda (var val)
2179 (set var val)
2180 (if val
2181 (add-hook 'org-blocker-hook
2182 'org-block-todo-from-children-or-siblings-or-parent)
2183 (remove-hook 'org-blocker-hook
2184 'org-block-todo-from-children-or-siblings-or-parent)))
2185 :group 'org-todo
2186 :type 'boolean)
2188 (defcustom org-enforce-todo-checkbox-dependencies nil
2189 "Non-nil means unchecked boxes will block switching the parent to DONE.
2190 When this is nil, checkboxes have no influence on switching TODO states.
2191 When non-nil, you first need to check off all check boxes before the TODO
2192 entry can be switched to DONE.
2193 This variable needs to be set before org.el is loaded, and you need to
2194 restart Emacs after a change to make the change effective. The only way
2195 to change is while Emacs is running is through the customize interface."
2196 :set (lambda (var val)
2197 (set var val)
2198 (if val
2199 (add-hook 'org-blocker-hook
2200 'org-block-todo-from-checkboxes)
2201 (remove-hook 'org-blocker-hook
2202 'org-block-todo-from-checkboxes)))
2203 :group 'org-todo
2204 :type 'boolean)
2206 (defcustom org-treat-insert-todo-heading-as-state-change nil
2207 "Non-nil means inserting a TODO heading is treated as state change.
2208 So when the command \\[org-insert-todo-heading] is used, state change
2209 logging will apply if appropriate. When nil, the new TODO item will
2210 be inserted directly, and no logging will take place."
2211 :group 'org-todo
2212 :type 'boolean)
2214 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2215 "Non-nil means switching TODO states with S-cursor counts as state change.
2216 This is the default behavior. However, setting this to nil allows a
2217 convenient way to select a TODO state and bypass any logging associated
2218 with that."
2219 :group 'org-todo
2220 :type 'boolean)
2222 (defcustom org-todo-state-tags-triggers nil
2223 "Tag changes that should be triggered by TODO state changes.
2224 This is a list. Each entry is
2226 (state-change (tag . flag) .......)
2228 State-change can be a string with a state, and empty string to indicate the
2229 state that has no TODO keyword, or it can be one of the symbols `todo'
2230 or `done', meaning any not-done or done state, respectively."
2231 :group 'org-todo
2232 :group 'org-tags
2233 :type '(repeat
2234 (cons (choice :tag "When changing to"
2235 (const :tag "Not-done state" todo)
2236 (const :tag "Done state" done)
2237 (string :tag "State"))
2238 (repeat
2239 (cons :tag "Tag action"
2240 (string :tag "Tag")
2241 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2243 (defcustom org-log-done nil
2244 "Information to record when a task moves to the DONE state.
2246 Possible values are:
2248 nil Don't add anything, just change the keyword
2249 time Add a time stamp to the task
2250 note Prompt for a note and add it with template `org-log-note-headings'
2252 This option can also be set with on a per-file-basis with
2254 #+STARTUP: nologdone
2255 #+STARTUP: logdone
2256 #+STARTUP: lognotedone
2258 You can have local logging settings for a subtree by setting the LOGGING
2259 property to one or more of these keywords."
2260 :group 'org-todo
2261 :group 'org-progress
2262 :type '(choice
2263 (const :tag "No logging" nil)
2264 (const :tag "Record CLOSED timestamp" time)
2265 (const :tag "Record CLOSED timestamp with note." note)))
2267 ;; Normalize old uses of org-log-done.
2268 (cond
2269 ((eq org-log-done t) (setq org-log-done 'time))
2270 ((and (listp org-log-done) (memq 'done org-log-done))
2271 (setq org-log-done 'note)))
2273 (defcustom org-log-reschedule nil
2274 "Information to record when the scheduling date of a tasks is modified.
2276 Possible values are:
2278 nil Don't add anything, just change the date
2279 time Add a time stamp to the task
2280 note Prompt for a note and add it with template `org-log-note-headings'
2282 This option can also be set with on a per-file-basis with
2284 #+STARTUP: nologreschedule
2285 #+STARTUP: logreschedule
2286 #+STARTUP: lognotereschedule"
2287 :group 'org-todo
2288 :group 'org-progress
2289 :type '(choice
2290 (const :tag "No logging" nil)
2291 (const :tag "Record timestamp" time)
2292 (const :tag "Record timestamp with note." note)))
2294 (defcustom org-log-redeadline nil
2295 "Information to record when the deadline date of a tasks is modified.
2297 Possible values are:
2299 nil Don't add anything, just change the date
2300 time Add a time stamp to the task
2301 note Prompt for a note and add it with template `org-log-note-headings'
2303 This option can also be set with on a per-file-basis with
2305 #+STARTUP: nologredeadline
2306 #+STARTUP: logredeadline
2307 #+STARTUP: lognoteredeadline
2309 You can have local logging settings for a subtree by setting the LOGGING
2310 property to one or more of these keywords."
2311 :group 'org-todo
2312 :group 'org-progress
2313 :type '(choice
2314 (const :tag "No logging" nil)
2315 (const :tag "Record timestamp" time)
2316 (const :tag "Record timestamp with note." note)))
2318 (defcustom org-log-note-clock-out nil
2319 "Non-nil means record a note when clocking out of an item.
2320 This can also be configured on a per-file basis by adding one of
2321 the following lines anywhere in the buffer:
2323 #+STARTUP: lognoteclock-out
2324 #+STARTUP: nolognoteclock-out"
2325 :group 'org-todo
2326 :group 'org-progress
2327 :type 'boolean)
2329 (defcustom org-log-done-with-time t
2330 "Non-nil means the CLOSED time stamp will contain date and time.
2331 When nil, only the date will be recorded."
2332 :group 'org-progress
2333 :type 'boolean)
2335 (defcustom org-log-note-headings
2336 '((done . "CLOSING NOTE %t")
2337 (state . "State %-12s from %-12S %t")
2338 (note . "Note taken on %t")
2339 (reschedule . "Rescheduled from %S on %t")
2340 (delschedule . "Not scheduled, was %S on %t")
2341 (redeadline . "New deadline from %S on %t")
2342 (deldeadline . "Removed deadline, was %S on %t")
2343 (refile . "Refiled on %t")
2344 (clock-out . ""))
2345 "Headings for notes added to entries.
2346 The value is an alist, with the car being a symbol indicating the note
2347 context, and the cdr is the heading to be used. The heading may also be the
2348 empty string.
2349 %t in the heading will be replaced by a time stamp.
2350 %T will be an active time stamp instead the default inactive one
2351 %s will be replaced by the new TODO state, in double quotes.
2352 %S will be replaced by the old TODO state, in double quotes.
2353 %u will be replaced by the user name.
2354 %U will be replaced by the full user name.
2356 In fact, it is not a good idea to change the `state' entry, because
2357 agenda log mode depends on the format of these entries."
2358 :group 'org-todo
2359 :group 'org-progress
2360 :type '(list :greedy t
2361 (cons (const :tag "Heading when closing an item" done) string)
2362 (cons (const :tag
2363 "Heading when changing todo state (todo sequence only)"
2364 state) string)
2365 (cons (const :tag "Heading when just taking a note" note) string)
2366 (cons (const :tag "Heading when clocking out" clock-out) string)
2367 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2368 (cons (const :tag "Heading when rescheduling" reschedule) string)
2369 (cons (const :tag "Heading when changing deadline" redeadline) string)
2370 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2371 (cons (const :tag "Heading when refiling" refile) string)))
2373 (unless (assq 'note org-log-note-headings)
2374 (push '(note . "%t") org-log-note-headings))
2376 (defcustom org-log-into-drawer nil
2377 "Non-nil means insert state change notes and time stamps into a drawer.
2378 When nil, state changes notes will be inserted after the headline and
2379 any scheduling and clock lines, but not inside a drawer.
2381 The value of this variable should be the name of the drawer to use.
2382 LOGBOOK is proposed at the default drawer for this purpose, you can
2383 also set this to a string to define the drawer of your choice.
2385 A value of t is also allowed, representing \"LOGBOOK\".
2387 If this variable is set, `org-log-state-notes-insert-after-drawers'
2388 will be ignored.
2390 You can set the property LOG_INTO_DRAWER to overrule this setting for
2391 a subtree."
2392 :group 'org-todo
2393 :group 'org-progress
2394 :type '(choice
2395 (const :tag "Not into a drawer" nil)
2396 (const :tag "LOGBOOK" t)
2397 (string :tag "Other")))
2399 (if (fboundp 'defvaralias)
2400 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2402 (defun org-log-into-drawer ()
2403 "Return the value of `org-log-into-drawer', but let properties overrule.
2404 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2405 used instead of the default value."
2406 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit)))
2407 (cond
2408 ((or (not p) (equal p "nil")) org-log-into-drawer)
2409 ((equal p "t") "LOGBOOK")
2410 (t p))))
2412 (defcustom org-log-state-notes-insert-after-drawers nil
2413 "Non-nil means insert state change notes after any drawers in entry.
2414 Only the drawers that *immediately* follow the headline and the
2415 deadline/scheduled line are skipped.
2416 When nil, insert notes right after the heading and perhaps the line
2417 with deadline/scheduling if present.
2419 This variable will have no effect if `org-log-into-drawer' is
2420 set."
2421 :group 'org-todo
2422 :group 'org-progress
2423 :type 'boolean)
2425 (defcustom org-log-states-order-reversed t
2426 "Non-nil means the latest state note will be directly after heading.
2427 When nil, the state change notes will be ordered according to time."
2428 :group 'org-todo
2429 :group 'org-progress
2430 :type 'boolean)
2432 (defcustom org-todo-repeat-to-state nil
2433 "The TODO state to which a repeater should return the repeating task.
2434 By default this is the first task in a TODO sequence, or the previous state
2435 in a TODO_TYP set. But you can specify another task here.
2436 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2437 :group 'org-todo
2438 :type '(choice (const :tag "Head of sequence" nil)
2439 (string :tag "Specific state")))
2441 (defcustom org-log-repeat 'time
2442 "Non-nil means record moving through the DONE state when triggering repeat.
2443 An auto-repeating task is immediately switched back to TODO when
2444 marked DONE. If you are not logging state changes (by adding \"@\"
2445 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2446 record a closing note, there will be no record of the task moving
2447 through DONE. This variable forces taking a note anyway.
2449 nil Don't force a record
2450 time Record a time stamp
2451 note Record a note
2453 This option can also be set with on a per-file-basis with
2455 #+STARTUP: logrepeat
2456 #+STARTUP: lognoterepeat
2457 #+STARTUP: nologrepeat
2459 You can have local logging settings for a subtree by setting the LOGGING
2460 property to one or more of these keywords."
2461 :group 'org-todo
2462 :group 'org-progress
2463 :type '(choice
2464 (const :tag "Don't force a record" nil)
2465 (const :tag "Force recording the DONE state" time)
2466 (const :tag "Force recording a note with the DONE state" note)))
2469 (defgroup org-priorities nil
2470 "Priorities in Org-mode."
2471 :tag "Org Priorities"
2472 :group 'org-todo)
2474 (defcustom org-enable-priority-commands t
2475 "Non-nil means priority commands are active.
2476 When nil, these commands will be disabled, so that you never accidentally
2477 set a priority."
2478 :group 'org-priorities
2479 :type 'boolean)
2481 (defcustom org-highest-priority ?A
2482 "The highest priority of TODO items. A character like ?A, ?B etc.
2483 Must have a smaller ASCII number than `org-lowest-priority'."
2484 :group 'org-priorities
2485 :type 'character)
2487 (defcustom org-lowest-priority ?C
2488 "The lowest priority of TODO items. A character like ?A, ?B etc.
2489 Must have a larger ASCII number than `org-highest-priority'."
2490 :group 'org-priorities
2491 :type 'character)
2493 (defcustom org-default-priority ?B
2494 "The default priority of TODO items.
2495 This is the priority an item get if no explicit priority is given."
2496 :group 'org-priorities
2497 :type 'character)
2499 (defcustom org-priority-start-cycle-with-default t
2500 "Non-nil means start with default priority when starting to cycle.
2501 When this is nil, the first step in the cycle will be (depending on the
2502 command used) one higher or lower that the default priority."
2503 :group 'org-priorities
2504 :type 'boolean)
2506 (defcustom org-get-priority-function nil
2507 "Function to extract the priority from a string.
2508 The string is normally the headline. If this is nil Org computes the
2509 priority from the priority cookie like [#A] in the headline. It returns
2510 an integer, increasing by 1000 for each priority level.
2511 The user can set a different function here, which should take a string
2512 as an argument and return the numeric priority."
2513 :group 'org-priorities
2514 :type 'function)
2516 (defgroup org-time nil
2517 "Options concerning time stamps and deadlines in Org-mode."
2518 :tag "Org Time"
2519 :group 'org)
2521 (defcustom org-insert-labeled-timestamps-at-point nil
2522 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2523 When nil, these labeled time stamps are forces into the second line of an
2524 entry, just after the headline. When scheduling from the global TODO list,
2525 the time stamp will always be forced into the second line."
2526 :group 'org-time
2527 :type 'boolean)
2529 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2530 "Formats for `format-time-string' which are used for time stamps.
2531 It is not recommended to change this constant.")
2533 (defcustom org-time-stamp-rounding-minutes '(0 5)
2534 "Number of minutes to round time stamps to.
2535 These are two values, the first applies when first creating a time stamp.
2536 The second applies when changing it with the commands `S-up' and `S-down'.
2537 When changing the time stamp, this means that it will change in steps
2538 of N minutes, as given by the second value.
2540 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2541 numbers should be factors of 60, so for example 5, 10, 15.
2543 When this is larger than 1, you can still force an exact time stamp by using
2544 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2545 and by using a prefix arg to `S-up/down' to specify the exact number
2546 of minutes to shift."
2547 :group 'org-time
2548 :get '(lambda (var) ; Make sure both elements are there
2549 (if (integerp (default-value var))
2550 (list (default-value var) 5)
2551 (default-value var)))
2552 :type '(list
2553 (integer :tag "when inserting times")
2554 (integer :tag "when modifying times")))
2556 ;; Normalize old customizations of this variable.
2557 (when (integerp org-time-stamp-rounding-minutes)
2558 (setq org-time-stamp-rounding-minutes
2559 (list org-time-stamp-rounding-minutes
2560 org-time-stamp-rounding-minutes)))
2562 (defcustom org-display-custom-times nil
2563 "Non-nil means overlay custom formats over all time stamps.
2564 The formats are defined through the variable `org-time-stamp-custom-formats'.
2565 To turn this on on a per-file basis, insert anywhere in the file:
2566 #+STARTUP: customtime"
2567 :group 'org-time
2568 :set 'set-default
2569 :type 'sexp)
2570 (make-variable-buffer-local 'org-display-custom-times)
2572 (defcustom org-time-stamp-custom-formats
2573 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2574 "Custom formats for time stamps. See `format-time-string' for the syntax.
2575 These are overlayed over the default ISO format if the variable
2576 `org-display-custom-times' is set. Time like %H:%M should be at the
2577 end of the second format. The custom formats are also honored by export
2578 commands, if custom time display is turned on at the time of export."
2579 :group 'org-time
2580 :type 'sexp)
2582 (defun org-time-stamp-format (&optional long inactive)
2583 "Get the right format for a time string."
2584 (let ((f (if long (cdr org-time-stamp-formats)
2585 (car org-time-stamp-formats))))
2586 (if inactive
2587 (concat "[" (substring f 1 -1) "]")
2588 f)))
2590 (defcustom org-time-clocksum-format "%d:%02d"
2591 "The format string used when creating CLOCKSUM lines.
2592 This is also used when org-mode generates a time duration."
2593 :group 'org-time
2594 :type 'string)
2596 (defcustom org-time-clocksum-use-fractional nil
2597 "If non-nil, \\[org-clock-display] uses fractional times.
2598 org-mode generates a time duration."
2599 :group 'org-time
2600 :type 'boolean)
2602 (defcustom org-time-clocksum-fractional-format "%.2f"
2603 "The format string used when creating CLOCKSUM lines, or when
2604 org-mode generates a time duration."
2605 :group 'org-time
2606 :type 'string)
2608 (defcustom org-deadline-warning-days 14
2609 "No. of days before expiration during which a deadline becomes active.
2610 This variable governs the display in sparse trees and in the agenda.
2611 When 0 or negative, it means use this number (the absolute value of it)
2612 even if a deadline has a different individual lead time specified.
2614 Custom commands can set this variable in the options section."
2615 :group 'org-time
2616 :group 'org-agenda-daily/weekly
2617 :type 'integer)
2619 (defcustom org-read-date-prefer-future t
2620 "Non-nil means assume future for incomplete date input from user.
2621 This affects the following situations:
2622 1. The user gives a month but not a year.
2623 For example, if it is April and you enter \"feb 2\", this will be read
2624 as Feb 2, *next* year. \"May 5\", however, will be this year.
2625 2. The user gives a day, but no month.
2626 For example, if today is the 15th, and you enter \"3\", Org-mode will
2627 read this as the third of *next* month. However, if you enter \"17\",
2628 it will be considered as *this* month.
2630 If you set this variable to the symbol `time', then also the following
2631 will work:
2633 3. If the user gives a time, but no day. If the time is before now,
2634 to will be interpreted as tomorrow.
2636 Currently none of this works for ISO week specifications.
2638 When this option is nil, the current day, month and year will always be
2639 used as defaults.
2641 See also `org-agenda-jump-prefer-future'."
2642 :group 'org-time
2643 :type '(choice
2644 (const :tag "Never" nil)
2645 (const :tag "Check month and day" t)
2646 (const :tag "Check month, day, and time" time)))
2648 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
2649 "Should the agenda jump command prefer the future for incomplete dates?
2650 The default is to do the same as configured in `org-read-date-prefer-future'.
2651 But you can also set a deviating value here.
2652 This may t or nil, or the symbol `org-read-date-prefer-future'."
2653 :group 'org-agenda
2654 :group 'org-time
2655 :type '(choice
2656 (const :tag "Use org-read-date-prefer-future"
2657 org-read-date-prefer-future)
2658 (const :tag "Never" nil)
2659 (const :tag "Always" t)))
2661 (defcustom org-read-date-force-compatible-dates t
2662 "Should date/time prompt force dates that are guaranteed to work in Emacs?
2664 Depending on the system Emacs is running on, certain dates cannot
2665 be represented with the type used internally to represent time.
2666 Dates between 1970-1-1 and 2038-1-1 can always be represented
2667 correctly. Some systems allow for earlier dates, some for later,
2668 some for both. One way to find out it to insert any date into an
2669 Org buffer, putting the cursor on the year and hitting S-up and
2670 S-down to test the range.
2672 When this variable is set to t, the date/time prompt will not let
2673 you specify dates outside the 1970-2037 range, so it is certain that
2674 these dates will work in whatever version of Emacs you are
2675 running, and also that you can move a file from one Emacs implementation
2676 to another. WHenever Org is forcing the year for you, it will display
2677 a message and beep.
2679 When this variable is nil, Org will check if the date is
2680 representable in the specific Emacs implementation you are using.
2681 If not, it will force a year, usually the current year, and beep
2682 to remind you. Currently this setting is not recommended because
2683 the likelihood that you will open your Org files in an Emacs that
2684 has limited date range is not negligible.
2686 A workaround for this problem is to use diary sexp dates for time
2687 stamps outside of this range."
2688 :group 'org-time
2689 :type 'boolean)
2691 (defcustom org-read-date-display-live t
2692 "Non-nil means display current interpretation of date prompt live.
2693 This display will be in an overlay, in the minibuffer."
2694 :group 'org-time
2695 :type 'boolean)
2697 (defcustom org-read-date-popup-calendar t
2698 "Non-nil means pop up a calendar when prompting for a date.
2699 In the calendar, the date can be selected with mouse-1. However, the
2700 minibuffer will also be active, and you can simply enter the date as well.
2701 When nil, only the minibuffer will be available."
2702 :group 'org-time
2703 :type 'boolean)
2704 (if (fboundp 'defvaralias)
2705 (defvaralias 'org-popup-calendar-for-date-prompt
2706 'org-read-date-popup-calendar))
2708 (defcustom org-read-date-minibuffer-setup-hook nil
2709 "Hook to be used to set up keys for the date/time interface.
2710 Add key definitions to `minibuffer-local-map', which will be a temporary
2711 copy."
2712 :group 'org-time
2713 :type 'hook)
2715 (defcustom org-extend-today-until 0
2716 "The hour when your day really ends. Must be an integer.
2717 This has influence for the following applications:
2718 - When switching the agenda to \"today\". It it is still earlier than
2719 the time given here, the day recognized as TODAY is actually yesterday.
2720 - When a date is read from the user and it is still before the time given
2721 here, the current date and time will be assumed to be yesterday, 23:59.
2722 Also, timestamps inserted in remember templates follow this rule.
2724 IMPORTANT: This is a feature whose implementation is and likely will
2725 remain incomplete. Really, it is only here because past midnight seems to
2726 be the favorite working time of John Wiegley :-)"
2727 :group 'org-time
2728 :type 'integer)
2730 (defcustom org-edit-timestamp-down-means-later nil
2731 "Non-nil means S-down will increase the time in a time stamp.
2732 When nil, S-up will increase."
2733 :group 'org-time
2734 :type 'boolean)
2736 (defcustom org-calendar-follow-timestamp-change t
2737 "Non-nil means make the calendar window follow timestamp changes.
2738 When a timestamp is modified and the calendar window is visible, it will be
2739 moved to the new date."
2740 :group 'org-time
2741 :type 'boolean)
2743 (defgroup org-tags nil
2744 "Options concerning tags in Org-mode."
2745 :tag "Org Tags"
2746 :group 'org)
2748 (defcustom org-tag-alist nil
2749 "List of tags allowed in Org-mode files.
2750 When this list is nil, Org-mode will base TAG input on what is already in the
2751 buffer.
2752 The value of this variable is an alist, the car of each entry must be a
2753 keyword as a string, the cdr may be a character that is used to select
2754 that tag through the fast-tag-selection interface.
2755 See the manual for details."
2756 :group 'org-tags
2757 :type '(repeat
2758 (choice
2759 (cons (string :tag "Tag name")
2760 (character :tag "Access char"))
2761 (list :tag "Start radio group"
2762 (const :startgroup)
2763 (option (string :tag "Group description")))
2764 (list :tag "End radio group"
2765 (const :endgroup)
2766 (option (string :tag "Group description")))
2767 (const :tag "New line" (:newline)))))
2769 (defcustom org-tag-persistent-alist nil
2770 "List of tags that will always appear in all Org-mode files.
2771 This is in addition to any in buffer settings or customizations
2772 of `org-tag-alist'.
2773 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2774 The value of this variable is an alist, the car of each entry must be a
2775 keyword as a string, the cdr may be a character that is used to select
2776 that tag through the fast-tag-selection interface.
2777 See the manual for details.
2778 To disable these tags on a per-file basis, insert anywhere in the file:
2779 #+STARTUP: noptag"
2780 :group 'org-tags
2781 :type '(repeat
2782 (choice
2783 (cons (string :tag "Tag name")
2784 (character :tag "Access char"))
2785 (const :tag "Start radio group" (:startgroup))
2786 (const :tag "End radio group" (:endgroup))
2787 (const :tag "New line" (:newline)))))
2789 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
2790 "If non-nil, always offer completion for all tags of all agenda files.
2791 Instead of customizing this variable directly, you might want to
2792 set it locally for capture buffers, because there no list of
2793 tags in that file can be created dynamically (there are none).
2795 (add-hook 'org-capture-mode-hook
2796 (lambda ()
2797 (set (make-local-variable
2798 'org-complete-tags-always-offer-all-agenda-tags)
2799 t)))"
2800 :group 'org-tags
2801 :type 'boolean)
2803 (defvar org-file-tags nil
2804 "List of tags that can be inherited by all entries in the file.
2805 The tags will be inherited if the variable `org-use-tag-inheritance'
2806 says they should be.
2807 This variable is populated from #+FILETAGS lines.")
2809 (defcustom org-use-fast-tag-selection 'auto
2810 "Non-nil means use fast tag selection scheme.
2811 This is a special interface to select and deselect tags with single keys.
2812 When nil, fast selection is never used.
2813 When the symbol `auto', fast selection is used if and only if selection
2814 characters for tags have been configured, either through the variable
2815 `org-tag-alist' or through a #+TAGS line in the buffer.
2816 When t, fast selection is always used and selection keys are assigned
2817 automatically if necessary."
2818 :group 'org-tags
2819 :type '(choice
2820 (const :tag "Always" t)
2821 (const :tag "Never" nil)
2822 (const :tag "When selection characters are configured" 'auto)))
2824 (defcustom org-fast-tag-selection-single-key nil
2825 "Non-nil means fast tag selection exits after first change.
2826 When nil, you have to press RET to exit it.
2827 During fast tag selection, you can toggle this flag with `C-c'.
2828 This variable can also have the value `expert'. In this case, the window
2829 displaying the tags menu is not even shown, until you press C-c again."
2830 :group 'org-tags
2831 :type '(choice
2832 (const :tag "No" nil)
2833 (const :tag "Yes" t)
2834 (const :tag "Expert" expert)))
2836 (defvar org-fast-tag-selection-include-todo nil
2837 "Non-nil means fast tags selection interface will also offer TODO states.
2838 This is an undocumented feature, you should not rely on it.")
2840 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2841 "The column to which tags should be indented in a headline.
2842 If this number is positive, it specifies the column. If it is negative,
2843 it means that the tags should be flushright to that column. For example,
2844 -80 works well for a normal 80 character screen."
2845 :group 'org-tags
2846 :type 'integer)
2848 (defcustom org-auto-align-tags t
2849 "Non-nil means realign tags after pro/demotion of TODO state change.
2850 These operations change the length of a headline and therefore shift
2851 the tags around. With this options turned on, after each such operation
2852 the tags are again aligned to `org-tags-column'."
2853 :group 'org-tags
2854 :type 'boolean)
2856 (defcustom org-use-tag-inheritance t
2857 "Non-nil means tags in levels apply also for sublevels.
2858 When nil, only the tags directly given in a specific line apply there.
2859 This may also be a list of tags that should be inherited, or a regexp that
2860 matches tags that should be inherited. Additional control is possible
2861 with the variable `org-tags-exclude-from-inheritance' which gives an
2862 explicit list of tags to be excluded from inheritance., even if the value of
2863 `org-use-tag-inheritance' would select it for inheritance.
2865 If this option is t, a match early-on in a tree can lead to a large
2866 number of matches in the subtree when constructing the agenda or creating
2867 a sparse tree. If you only want to see the first match in a tree during
2868 a search, check out the variable `org-tags-match-list-sublevels'."
2869 :group 'org-tags
2870 :type '(choice
2871 (const :tag "Not" nil)
2872 (const :tag "Always" t)
2873 (repeat :tag "Specific tags" (string :tag "Tag"))
2874 (regexp :tag "Tags matched by regexp")))
2876 (defcustom org-tags-exclude-from-inheritance nil
2877 "List of tags that should never be inherited.
2878 This is a way to exclude a few tags from inheritance. For way to do
2879 the opposite, to actively allow inheritance for selected tags,
2880 see the variable `org-use-tag-inheritance'."
2881 :group 'org-tags
2882 :type '(repeat (string :tag "Tag")))
2884 (defun org-tag-inherit-p (tag)
2885 "Check if TAG is one that should be inherited."
2886 (cond
2887 ((member tag org-tags-exclude-from-inheritance) nil)
2888 ((eq org-use-tag-inheritance t) t)
2889 ((not org-use-tag-inheritance) nil)
2890 ((stringp org-use-tag-inheritance)
2891 (string-match org-use-tag-inheritance tag))
2892 ((listp org-use-tag-inheritance)
2893 (member tag org-use-tag-inheritance))
2894 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
2896 (defcustom org-tags-match-list-sublevels t
2897 "Non-nil means list also sublevels of headlines matching a search.
2898 This variable applies to tags/property searches, and also to stuck
2899 projects because this search is based on a tags match as well.
2901 When set to the symbol `indented', sublevels are indented with
2902 leading dots.
2904 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2905 the sublevels of a headline matching a tag search often also match
2906 the same search. Listing all of them can create very long lists.
2907 Setting this variable to nil causes subtrees of a match to be skipped.
2909 This variable is semi-obsolete and probably should always be true. It
2910 is better to limit inheritance to certain tags using the variables
2911 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
2912 :group 'org-tags
2913 :type '(choice
2914 (const :tag "No, don't list them" nil)
2915 (const :tag "Yes, do list them" t)
2916 (const :tag "List them, indented with leading dots" indented)))
2918 (defcustom org-tags-sort-function nil
2919 "When set, tags are sorted using this function as a comparator."
2920 :group 'org-tags
2921 :type '(choice
2922 (const :tag "No sorting" nil)
2923 (const :tag "Alphabetical" string<)
2924 (const :tag "Reverse alphabetical" string>)
2925 (function :tag "Custom function" nil)))
2927 (defvar org-tags-history nil
2928 "History of minibuffer reads for tags.")
2929 (defvar org-last-tags-completion-table nil
2930 "The last used completion table for tags.")
2931 (defvar org-after-tags-change-hook nil
2932 "Hook that is run after the tags in a line have changed.")
2934 (defgroup org-properties nil
2935 "Options concerning properties in Org-mode."
2936 :tag "Org Properties"
2937 :group 'org)
2939 (defcustom org-property-format "%-10s %s"
2940 "How property key/value pairs should be formatted by `indent-line'.
2941 When `indent-line' hits a property definition, it will format the line
2942 according to this format, mainly to make sure that the values are
2943 lined-up with respect to each other."
2944 :group 'org-properties
2945 :type 'string)
2947 (defcustom org-use-property-inheritance nil
2948 "Non-nil means properties apply also for sublevels.
2950 This setting is chiefly used during property searches. Turning it on can
2951 cause significant overhead when doing a search, which is why it is not
2952 on by default.
2954 When nil, only the properties directly given in the current entry count.
2955 When t, every property is inherited. The value may also be a list of
2956 properties that should have inheritance, or a regular expression matching
2957 properties that should be inherited.
2959 However, note that some special properties use inheritance under special
2960 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2961 and the properties ending in \"_ALL\" when they are used as descriptor
2962 for valid values of a property.
2964 Note for programmers:
2965 When querying an entry with `org-entry-get', you can control if inheritance
2966 should be used. By default, `org-entry-get' looks only at the local
2967 properties. You can request inheritance by setting the inherit argument
2968 to t (to force inheritance) or to `selective' (to respect the setting
2969 in this variable)."
2970 :group 'org-properties
2971 :type '(choice
2972 (const :tag "Not" nil)
2973 (const :tag "Always" t)
2974 (repeat :tag "Specific properties" (string :tag "Property"))
2975 (regexp :tag "Properties matched by regexp")))
2977 (defun org-property-inherit-p (property)
2978 "Check if PROPERTY is one that should be inherited."
2979 (cond
2980 ((eq org-use-property-inheritance t) t)
2981 ((not org-use-property-inheritance) nil)
2982 ((stringp org-use-property-inheritance)
2983 (string-match org-use-property-inheritance property))
2984 ((listp org-use-property-inheritance)
2985 (member property org-use-property-inheritance))
2986 (t (error "Invalid setting of `org-use-property-inheritance'"))))
2988 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2989 "The default column format, if no other format has been defined.
2990 This variable can be set on the per-file basis by inserting a line
2992 #+COLUMNS: %25ITEM ....."
2993 :group 'org-properties
2994 :type 'string)
2996 (defcustom org-columns-ellipses ".."
2997 "The ellipses to be used when a field in column view is truncated.
2998 When this is the empty string, as many characters as possible are shown,
2999 but then there will be no visual indication that the field has been truncated.
3000 When this is a string of length N, the last N characters of a truncated
3001 field are replaced by this string. If the column is narrower than the
3002 ellipses string, only part of the ellipses string will be shown."
3003 :group 'org-properties
3004 :type 'string)
3006 (defcustom org-columns-modify-value-for-display-function nil
3007 "Function that modifies values for display in column view.
3008 For example, it can be used to cut out a certain part from a time stamp.
3009 The function must take 2 arguments:
3011 column-title The title of the column (*not* the property name)
3012 value The value that should be modified.
3014 The function should return the value that should be displayed,
3015 or nil if the normal value should be used."
3016 :group 'org-properties
3017 :type 'function)
3019 (defcustom org-effort-property "Effort"
3020 "The property that is being used to keep track of effort estimates.
3021 Effort estimates given in this property need to have the format H:MM."
3022 :group 'org-properties
3023 :group 'org-progress
3024 :type '(string :tag "Property"))
3026 (defconst org-global-properties-fixed
3027 '(("VISIBILITY_ALL" . "folded children content all")
3028 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3029 "List of property/value pairs that can be inherited by any entry.
3031 These are fixed values, for the preset properties. The user variable
3032 that can be used to add to this list is `org-global-properties'.
3034 The entries in this list are cons cells where the car is a property
3035 name and cdr is a string with the value. If the value represents
3036 multiple items like an \"_ALL\" property, separate the items by
3037 spaces.")
3039 (defcustom org-global-properties nil
3040 "List of property/value pairs that can be inherited by any entry.
3042 This list will be combined with the constant `org-global-properties-fixed'.
3044 The entries in this list are cons cells where the car is a property
3045 name and cdr is a string with the value.
3047 You can set buffer-local values for the same purpose in the variable
3048 `org-file-properties' this by adding lines like
3050 #+PROPERTY: NAME VALUE"
3051 :group 'org-properties
3052 :type '(repeat
3053 (cons (string :tag "Property")
3054 (string :tag "Value"))))
3056 (defvar org-file-properties nil
3057 "List of property/value pairs that can be inherited by any entry.
3058 Valid for the current buffer.
3059 This variable is populated from #+PROPERTY lines.")
3060 (make-variable-buffer-local 'org-file-properties)
3062 (defgroup org-agenda nil
3063 "Options concerning agenda views in Org-mode."
3064 :tag "Org Agenda"
3065 :group 'org)
3067 (defvar org-category nil
3068 "Variable used by org files to set a category for agenda display.
3069 Such files should use a file variable to set it, for example
3071 # -*- mode: org; org-category: \"ELisp\"
3073 or contain a special line
3075 #+CATEGORY: ELisp
3077 If the file does not specify a category, then file's base name
3078 is used instead.")
3079 (make-variable-buffer-local 'org-category)
3080 (put 'org-category 'safe-local-variable '(lambda (x) (or (symbolp x) (stringp x))))
3082 (defcustom org-agenda-files nil
3083 "The files to be used for agenda display.
3084 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3085 \\[org-remove-file]. You can also use customize to edit the list.
3087 If an entry is a directory, all files in that directory that are matched by
3088 `org-agenda-file-regexp' will be part of the file list.
3090 If the value of the variable is not a list but a single file name, then
3091 the list of agenda files is actually stored and maintained in that file, one
3092 agenda file per line. In this file paths can be given relative to
3093 `org-directory'. Tilde expansion and environment variable substitution
3094 are also made."
3095 :group 'org-agenda
3096 :type '(choice
3097 (repeat :tag "List of files and directories" file)
3098 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3100 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3101 "Regular expression to match files for `org-agenda-files'.
3102 If any element in the list in that variable contains a directory instead
3103 of a normal file, all files in that directory that are matched by this
3104 regular expression will be included."
3105 :group 'org-agenda
3106 :type 'regexp)
3108 (defcustom org-agenda-text-search-extra-files nil
3109 "List of extra files to be searched by text search commands.
3110 These files will be search in addition to the agenda files by the
3111 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3112 Note that these files will only be searched for text search commands,
3113 not for the other agenda views like todo lists, tag searches or the weekly
3114 agenda. This variable is intended to list notes and possibly archive files
3115 that should also be searched by these two commands.
3116 In fact, if the first element in the list is the symbol `agenda-archives',
3117 than all archive files of all agenda files will be added to the search
3118 scope."
3119 :group 'org-agenda
3120 :type '(set :greedy t
3121 (const :tag "Agenda Archives" agenda-archives)
3122 (repeat :inline t (file))))
3124 (if (fboundp 'defvaralias)
3125 (defvaralias 'org-agenda-multi-occur-extra-files
3126 'org-agenda-text-search-extra-files))
3128 (defcustom org-agenda-skip-unavailable-files nil
3129 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3130 A nil value means to remove them, after a query, from the list."
3131 :group 'org-agenda
3132 :type 'boolean)
3134 (defcustom org-calendar-to-agenda-key [?c]
3135 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3136 The command `org-calendar-goto-agenda' will be bound to this key. The
3137 default is the character `c' because then `c' can be used to switch back and
3138 forth between agenda and calendar."
3139 :group 'org-agenda
3140 :type 'sexp)
3142 (defcustom org-calendar-agenda-action-key [?k]
3143 "The key to be installed in `calendar-mode-map' for agenda-action.
3144 The command `org-agenda-action' will be bound to this key. The
3145 default is the character `k' because we use the same key in the agenda."
3146 :group 'org-agenda
3147 :type 'sexp)
3149 (defcustom org-calendar-insert-diary-entry-key [?i]
3150 "The key to be installed in `calendar-mode-map' for adding diary entries.
3151 This option is irrelevant until `org-agenda-diary-file' has been configured
3152 to point to an Org-mode file. When that is the case, the command
3153 `org-agenda-diary-entry' will be bound to the key given here, by default
3154 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3155 if you want to continue doing this, you need to change this to a different
3156 key."
3157 :group 'org-agenda
3158 :type 'sexp)
3160 (defcustom org-agenda-diary-file 'diary-file
3161 "File to which to add new entries with the `i' key in agenda and calendar.
3162 When this is the symbol `diary-file', the functionality in the Emacs
3163 calendar will be used to add entries to the `diary-file'. But when this
3164 points to a file, `org-agenda-diary-entry' will be used instead."
3165 :group 'org-agenda
3166 :type '(choice
3167 (const :tag "The standard Emacs diary file" diary-file)
3168 (file :tag "Special Org file diary entries")))
3170 (eval-after-load "calendar"
3171 '(progn
3172 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3173 'org-calendar-goto-agenda)
3174 (org-defkey calendar-mode-map org-calendar-agenda-action-key
3175 'org-agenda-action)
3176 (add-hook 'calendar-mode-hook
3177 (lambda ()
3178 (unless (eq org-agenda-diary-file 'diary-file)
3179 (define-key calendar-mode-map
3180 org-calendar-insert-diary-entry-key
3181 'org-agenda-diary-entry))))))
3183 (defgroup org-latex nil
3184 "Options for embedding LaTeX code into Org-mode."
3185 :tag "Org LaTeX"
3186 :group 'org)
3188 (defcustom org-format-latex-options
3189 '(:foreground default :background default :scale 1.0
3190 :html-foreground "Black" :html-background "Transparent"
3191 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3192 "Options for creating images from LaTeX fragments.
3193 This is a property list with the following properties:
3194 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3195 `default' means use the foreground of the default face.
3196 :background the background color, or \"Transparent\".
3197 `default' means use the background of the default face.
3198 :scale a scaling factor for the size of the images, to get more pixels
3199 :html-foreground, :html-background, :html-scale
3200 the same numbers for HTML export.
3201 :matchers a list indicating which matchers should be used to
3202 find LaTeX fragments. Valid members of this list are:
3203 \"begin\" find environments
3204 \"$1\" find single characters surrounded by $.$
3205 \"$\" find math expressions surrounded by $...$
3206 \"$$\" find math expressions surrounded by $$....$$
3207 \"\\(\" find math expressions surrounded by \\(...\\)
3208 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3209 :group 'org-latex
3210 :type 'plist)
3212 (defcustom org-format-latex-signal-error t
3213 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3214 When nil, just push out a message."
3215 :group 'org-latex
3216 :type 'boolean)
3218 (defcustom org-format-latex-header "\\documentclass{article}
3219 \\usepackage[usenames]{color}
3220 \\usepackage{amsmath}
3221 \\usepackage[mathscr]{eucal}
3222 \\pagestyle{empty} % do not remove
3223 \[PACKAGES]
3224 \[DEFAULT-PACKAGES]
3225 % The settings below are copied from fullpage.sty
3226 \\setlength{\\textwidth}{\\paperwidth}
3227 \\addtolength{\\textwidth}{-3cm}
3228 \\setlength{\\oddsidemargin}{1.5cm}
3229 \\addtolength{\\oddsidemargin}{-2.54cm}
3230 \\setlength{\\evensidemargin}{\\oddsidemargin}
3231 \\setlength{\\textheight}{\\paperheight}
3232 \\addtolength{\\textheight}{-\\headheight}
3233 \\addtolength{\\textheight}{-\\headsep}
3234 \\addtolength{\\textheight}{-\\footskip}
3235 \\addtolength{\\textheight}{-3cm}
3236 \\setlength{\\topmargin}{1.5cm}
3237 \\addtolength{\\topmargin}{-2.54cm}"
3238 "The document header used for processing LaTeX fragments.
3239 It is imperative that this header make sure that no page number
3240 appears on the page. The package defined in the variables
3241 `org-export-latex-default-packages-alist' and `org-export-latex-packages-alist'
3242 will either replace the placeholder \"[PACKAGES]\" in this header, or they
3243 will be appended."
3244 :group 'org-latex
3245 :type 'string)
3247 (defvar org-format-latex-header-extra nil)
3249 (defun org-set-packages-alist (var val)
3250 "Set the packages alist and make sure it has 3 elements per entry."
3251 (set var (mapcar (lambda (x)
3252 (if (and (consp x) (= (length x) 2))
3253 (list (car x) (nth 1 x) t)
3255 val)))
3257 (defun org-get-packages-alist (var)
3259 "Get the packages alist and make sure it has 3 elements per entry."
3260 (mapcar (lambda (x)
3261 (if (and (consp x) (= (length x) 2))
3262 (list (car x) (nth 1 x) t)
3264 (default-value var)))
3266 ;; The following variables are defined here because is it also used
3267 ;; when formatting latex fragments. Originally it was part of the
3268 ;; LaTeX exporter, which is why the name includes "export".
3269 (defcustom org-export-latex-default-packages-alist
3270 '(("AUTO" "inputenc" t)
3271 ("T1" "fontenc" t)
3272 ("" "fixltx2e" nil)
3273 ("" "graphicx" t)
3274 ("" "longtable" nil)
3275 ("" "float" nil)
3276 ("" "wrapfig" nil)
3277 ("" "soul" t)
3278 ("" "textcomp" t)
3279 ("" "marvosym" t)
3280 ("" "wasysym" t)
3281 ("" "latexsym" t)
3282 ("" "amssymb" t)
3283 ("" "hyperref" nil)
3284 "\\tolerance=1000"
3286 "Alist of default packages to be inserted in the header.
3287 Change this only if one of the packages here causes an incompatibility
3288 with another package you are using.
3289 The packages in this list are needed by one part or another of Org-mode
3290 to function properly.
3292 - inputenc, fontenc: for basic font and character selection
3293 - textcomp, marvosymb, wasysym, latexsym, amssym: for various symbols used
3294 for interpreting the entities in `org-entities'. You can skip some of these
3295 packages if you don't use any of the symbols in it.
3296 - graphicx: for including images
3297 - float, wrapfig: for figure placement
3298 - longtable: for long tables
3299 - hyperref: for cross references
3301 Therefore you should not modify this variable unless you know what you
3302 are doing. The one reason to change it anyway is that you might be loading
3303 some other package that conflicts with one of the default packages.
3304 Each cell is of the format \( \"options\" \"package\" snippet-flag\).
3305 If SNIPPET-FLAG is t, the package also needs to be included when
3306 compiling LaTeX snippets into images for inclusion into HTML."
3307 :group 'org-export-latex
3308 :set 'org-set-packages-alist
3309 :get 'org-get-packages-alist
3310 :type '(repeat
3311 (choice
3312 (list :tag "options/package pair"
3313 (string :tag "options")
3314 (string :tag "package")
3315 (boolean :tag "Snippet"))
3316 (string :tag "A line of LaTeX"))))
3318 (defcustom org-export-latex-packages-alist nil
3319 "Alist of packages to be inserted in every LaTeX header.
3320 These will be inserted after `org-export-latex-default-packages-alist'.
3321 Each cell is of the format \( \"options\" \"package\" snippet-flag \).
3322 SNIPPET-FLAG, when t, indicates that this package is also needed when
3323 turning LaTeX snippets into images for inclusion into HTML.
3324 Make sure that you only list packages here which:
3325 - you want in every file
3326 - do not conflict with the default packages in
3327 `org-export-latex-default-packages-alist'
3328 - do not conflict with the setup in `org-format-latex-header'."
3329 :group 'org-export-latex
3330 :set 'org-set-packages-alist
3331 :get 'org-get-packages-alist
3332 :type '(repeat
3333 (choice
3334 (list :tag "options/package pair"
3335 (string :tag "options")
3336 (string :tag "package")
3337 (boolean :tag "Snippet"))
3338 (string :tag "A line of LaTeX"))))
3341 (defgroup org-appearance nil
3342 "Settings for Org-mode appearance."
3343 :tag "Org Appearance"
3344 :group 'org)
3346 (defcustom org-level-color-stars-only nil
3347 "Non-nil means fontify only the stars in each headline.
3348 When nil, the entire headline is fontified.
3349 Changing it requires restart of `font-lock-mode' to become effective
3350 also in regions already fontified."
3351 :group 'org-appearance
3352 :type 'boolean)
3354 (defcustom org-hide-leading-stars nil
3355 "Non-nil means hide the first N-1 stars in a headline.
3356 This works by using the face `org-hide' for these stars. This
3357 face is white for a light background, and black for a dark
3358 background. You may have to customize the face `org-hide' to
3359 make this work.
3360 Changing it requires restart of `font-lock-mode' to become effective
3361 also in regions already fontified.
3362 You may also set this on a per-file basis by adding one of the following
3363 lines to the buffer:
3365 #+STARTUP: hidestars
3366 #+STARTUP: showstars"
3367 :group 'org-appearance
3368 :type 'boolean)
3370 (defcustom org-hidden-keywords nil
3371 "List of symbols corresponding to keywords to be hidden the org buffer.
3372 For example, a value '(title) for this list will make the document's title
3373 appear in the buffer without the initial #+TITLE: keyword."
3374 :group 'org-appearance
3375 :type '(set (const :tag "#+AUTHOR" author)
3376 (const :tag "#+DATE" date)
3377 (const :tag "#+EMAIL" email)
3378 (const :tag "#+TITLE" title)))
3380 (defcustom org-fontify-done-headline nil
3381 "Non-nil means change the face of a headline if it is marked DONE.
3382 Normally, only the TODO/DONE keyword indicates the state of a headline.
3383 When this is non-nil, the headline after the keyword is set to the
3384 `org-headline-done' as an additional indication."
3385 :group 'org-appearance
3386 :type 'boolean)
3388 (defcustom org-fontify-emphasized-text t
3389 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3390 Changing this variable requires a restart of Emacs to take effect."
3391 :group 'org-appearance
3392 :type 'boolean)
3394 (defcustom org-fontify-whole-heading-line nil
3395 "Non-nil means fontify the whole line for headings.
3396 This is useful when setting a background color for the
3397 org-level-* faces."
3398 :group 'org-appearance
3399 :type 'boolean)
3401 (defcustom org-highlight-latex-fragments-and-specials nil
3402 "Non-nil means fontify what is treated specially by the exporters."
3403 :group 'org-appearance
3404 :type 'boolean)
3406 (defcustom org-hide-emphasis-markers nil
3407 "Non-nil mean font-lock should hide the emphasis marker characters."
3408 :group 'org-appearance
3409 :type 'boolean)
3411 (defcustom org-pretty-entities nil
3412 "Non-nil means show entities as UTF8 characters.
3413 When nil, the \\name form remains in the buffer."
3414 :group 'org-appearance
3415 :type 'boolean)
3417 (defcustom org-pretty-entities-include-sub-superscripts t
3418 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3419 :group 'org-appearance
3420 :type 'boolean)
3422 (defvar org-emph-re nil
3423 "Regular expression for matching emphasis.
3424 After a match, the match groups contain these elements:
3425 0 The match of the full regular expression, including the characters
3426 before and after the proper match
3427 1 The character before the proper match, or empty at beginning of line
3428 2 The proper match, including the leading and trailing markers
3429 3 The leading marker like * or /, indicating the type of highlighting
3430 4 The text between the emphasis markers, not including the markers
3431 5 The character after the match, empty at the end of a line")
3432 (defvar org-verbatim-re nil
3433 "Regular expression for matching verbatim text.")
3434 (defvar org-emphasis-regexp-components) ; defined just below
3435 (defvar org-emphasis-alist) ; defined just below
3436 (defun org-set-emph-re (var val)
3437 "Set variable and compute the emphasis regular expression."
3438 (set var val)
3439 (when (and (boundp 'org-emphasis-alist)
3440 (boundp 'org-emphasis-regexp-components)
3441 org-emphasis-alist org-emphasis-regexp-components)
3442 (let* ((e org-emphasis-regexp-components)
3443 (pre (car e))
3444 (post (nth 1 e))
3445 (border (nth 2 e))
3446 (body (nth 3 e))
3447 (nl (nth 4 e))
3448 (body1 (concat body "*?"))
3449 (markers (mapconcat 'car org-emphasis-alist ""))
3450 (vmarkers (mapconcat
3451 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3452 org-emphasis-alist "")))
3453 ;; make sure special characters appear at the right position in the class
3454 (if (string-match "\\^" markers)
3455 (setq markers (concat (replace-match "" t t markers) "^")))
3456 (if (string-match "-" markers)
3457 (setq markers (concat (replace-match "" t t markers) "-")))
3458 (if (string-match "\\^" vmarkers)
3459 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3460 (if (string-match "-" vmarkers)
3461 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3462 (if (> nl 0)
3463 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3464 (int-to-string nl) "\\}")))
3465 ;; Make the regexp
3466 (setq org-emph-re
3467 (concat "\\([" pre "]\\|^\\)"
3468 "\\("
3469 "\\([" markers "]\\)"
3470 "\\("
3471 "[^" border "]\\|"
3472 "[^" border "]"
3473 body1
3474 "[^" border "]"
3475 "\\)"
3476 "\\3\\)"
3477 "\\([" post "]\\|$\\)"))
3478 (setq org-verbatim-re
3479 (concat "\\([" pre "]\\|^\\)"
3480 "\\("
3481 "\\([" vmarkers "]\\)"
3482 "\\("
3483 "[^" border "]\\|"
3484 "[^" border "]"
3485 body1
3486 "[^" border "]"
3487 "\\)"
3488 "\\3\\)"
3489 "\\([" post "]\\|$\\)")))))
3491 (defcustom org-emphasis-regexp-components
3492 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
3493 "Components used to build the regular expression for emphasis.
3494 This is a list with five entries. Terminology: In an emphasis string
3495 like \" *strong word* \", we call the initial space PREMATCH, the final
3496 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3497 and \"trong wor\" is the body. The different components in this variable
3498 specify what is allowed/forbidden in each part:
3500 pre Chars allowed as prematch. Beginning of line will be allowed too.
3501 post Chars allowed as postmatch. End of line will be allowed too.
3502 border The chars *forbidden* as border characters.
3503 body-regexp A regexp like \".\" to match a body character. Don't use
3504 non-shy groups here, and don't allow newline here.
3505 newline The maximum number of newlines allowed in an emphasis exp.
3507 Use customize to modify this, or restart Emacs after changing it."
3508 :group 'org-appearance
3509 :set 'org-set-emph-re
3510 :type '(list
3511 (sexp :tag "Allowed chars in pre ")
3512 (sexp :tag "Allowed chars in post ")
3513 (sexp :tag "Forbidden chars in border ")
3514 (sexp :tag "Regexp for body ")
3515 (integer :tag "number of newlines allowed")
3516 (option (boolean :tag "Please ignore this button"))))
3518 (defcustom org-emphasis-alist
3519 `(("*" bold "<b>" "</b>")
3520 ("/" italic "<i>" "</i>")
3521 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
3522 ("=" org-code "<code>" "</code>" verbatim)
3523 ("~" org-verbatim "<code>" "</code>" verbatim)
3524 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
3525 "<del>" "</del>")
3527 "Special syntax for emphasized text.
3528 Text starting and ending with a special character will be emphasized, for
3529 example *bold*, _underlined_ and /italic/. This variable sets the marker
3530 characters, the face to be used by font-lock for highlighting in Org-mode
3531 Emacs buffers, and the HTML tags to be used for this.
3532 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
3533 For DocBook export, see the variable `org-export-docbook-emphasis-alist'.
3534 Use customize to modify this, or restart Emacs after changing it."
3535 :group 'org-appearance
3536 :set 'org-set-emph-re
3537 :type '(repeat
3538 (list
3539 (string :tag "Marker character")
3540 (choice
3541 (face :tag "Font-lock-face")
3542 (plist :tag "Face property list"))
3543 (string :tag "HTML start tag")
3544 (string :tag "HTML end tag")
3545 (option (const verbatim)))))
3547 (defvar org-protecting-blocks
3548 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
3549 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
3550 This is needed for font-lock setup.")
3552 ;;; Miscellaneous options
3554 (defgroup org-completion nil
3555 "Completion in Org-mode."
3556 :tag "Org Completion"
3557 :group 'org)
3559 (defcustom org-completion-use-ido nil
3560 "Non-nil means use ido completion wherever possible.
3561 Note that `ido-mode' must be active for this variable to be relevant.
3562 If you decide to turn this variable on, you might well want to turn off
3563 `org-outline-path-complete-in-steps'.
3564 See also `org-completion-use-iswitchb'."
3565 :group 'org-completion
3566 :type 'boolean)
3568 (defcustom org-completion-use-iswitchb nil
3569 "Non-nil means use iswitchb completion wherever possible.
3570 Note that `iswitchb-mode' must be active for this variable to be relevant.
3571 If you decide to turn this variable on, you might well want to turn off
3572 `org-outline-path-complete-in-steps'.
3573 Note that this variable has only an effect if `org-completion-use-ido' is nil."
3574 :group 'org-completion
3575 :type 'boolean)
3577 (defcustom org-completion-fallback-command 'hippie-expand
3578 "The expansion command called by \\[pcomplete] in normal context.
3579 Normal means, no org-mode-specific context."
3580 :group 'org-completion
3581 :type 'function)
3583 ;;; Functions and variables from their packages
3584 ;; Declared here to avoid compiler warnings
3586 ;; XEmacs only
3587 (defvar outline-mode-menu-heading)
3588 (defvar outline-mode-menu-show)
3589 (defvar outline-mode-menu-hide)
3590 (defvar zmacs-regions) ; XEmacs regions
3592 ;; Emacs only
3593 (defvar mark-active)
3595 ;; Various packages
3596 (declare-function calendar-absolute-from-iso "cal-iso" (date))
3597 (declare-function calendar-forward-day "cal-move" (arg))
3598 (declare-function calendar-goto-date "cal-move" (date))
3599 (declare-function calendar-goto-today "cal-move" ())
3600 (declare-function calendar-iso-from-absolute "cal-iso" (date))
3601 (defvar calc-embedded-close-formula)
3602 (defvar calc-embedded-open-formula)
3603 (declare-function cdlatex-tab "ext:cdlatex" ())
3604 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3605 (defvar font-lock-unfontify-region-function)
3606 (declare-function iswitchb-read-buffer "iswitchb"
3607 (prompt &optional default require-match start matches-set))
3608 (defvar iswitchb-temp-buflist)
3609 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
3610 (defvar org-agenda-tags-todo-honor-ignore-options)
3611 (declare-function org-agenda-skip "org-agenda" ())
3612 (declare-function
3613 org-format-agenda-item "org-agenda"
3614 (extra txt &optional category tags dotime noprefix remove-re habitp))
3615 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
3616 (declare-function org-agenda-change-all-lines "org-agenda"
3617 (newhead hdmarker &optional fixface just-this))
3618 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
3619 (declare-function org-agenda-maybe-redo "org-agenda" ())
3620 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
3621 (beg end))
3622 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
3623 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
3624 "org-agenda" (&optional end))
3625 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
3626 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
3627 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
3628 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
3629 (declare-function org-indent-mode "org-indent" (&optional arg))
3630 (declare-function parse-time-string "parse-time" (string))
3631 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
3632 (declare-function org-export-latex-fix-inputenc "org-latex" ())
3633 (declare-function orgtbl-send-table "org-table" (&optional maybe))
3634 (defvar remember-data-file)
3635 (defvar texmathp-why)
3636 (declare-function speedbar-line-directory "speedbar" (&optional depth))
3637 (declare-function table--at-cell-p "table" (position &optional object at-column))
3639 (defvar w3m-current-url)
3640 (defvar w3m-current-title)
3642 (defvar org-latex-regexps)
3644 ;;; Autoload and prepare some org modules
3646 ;; Some table stuff that needs to be defined here, because it is used
3647 ;; by the functions setting up org-mode or checking for table context.
3649 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
3650 "Detect an org-type or table-type table.")
3651 (defconst org-table-line-regexp "^[ \t]*|"
3652 "Detect an org-type table line.")
3653 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
3654 "Detect an org-type table line.")
3655 (defconst org-table-hline-regexp "^[ \t]*|-"
3656 "Detect an org-type table hline.")
3657 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
3658 "Detect a table-type table hline.")
3659 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
3660 "Detect the first line outside a table when searching from within it.
3661 This works for both table types.")
3663 ;; Autoload the functions in org-table.el that are needed by functions here.
3665 (eval-and-compile
3666 (org-autoload "org-table"
3667 '(org-table-align org-table-begin org-table-blank-field
3668 org-table-convert org-table-convert-region org-table-copy-down
3669 org-table-copy-region org-table-create
3670 org-table-create-or-convert-from-region
3671 org-table-create-with-table.el org-table-current-dline
3672 org-table-cut-region org-table-delete-column org-table-edit-field
3673 org-table-edit-formulas org-table-end org-table-eval-formula
3674 org-table-export org-table-field-info
3675 org-table-get-stored-formulas org-table-goto-column
3676 org-table-hline-and-move org-table-import org-table-insert-column
3677 org-table-insert-hline org-table-insert-row org-table-iterate
3678 org-table-justify-field-maybe org-table-kill-row
3679 org-table-maybe-eval-formula org-table-maybe-recalculate-line
3680 org-table-move-column org-table-move-column-left
3681 org-table-move-column-right org-table-move-row
3682 org-table-move-row-down org-table-move-row-up
3683 org-table-next-field org-table-next-row org-table-paste-rectangle
3684 org-table-previous-field org-table-recalculate
3685 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
3686 org-table-toggle-coordinate-overlays
3687 org-table-toggle-formula-debugger org-table-wrap-region
3688 orgtbl-mode turn-on-orgtbl org-table-to-lisp
3689 orgtbl-to-generic orgtbl-to-tsv orgtbl-to-csv orgtbl-to-latex
3690 orgtbl-to-orgtbl orgtbl-to-html orgtbl-to-texinfo)))
3692 (defun org-at-table-p (&optional table-type)
3693 "Return t if the cursor is inside an org-type table.
3694 If TABLE-TYPE is non-nil, also check for table.el-type tables."
3695 (if org-enable-table-editor
3696 (save-excursion
3697 (beginning-of-line 1)
3698 (looking-at (if table-type org-table-any-line-regexp
3699 org-table-line-regexp)))
3700 nil))
3701 (defsubst org-table-p () (org-at-table-p))
3703 (defun org-at-table.el-p ()
3704 "Return t if and only if we are at a table.el table."
3705 (and (org-at-table-p 'any)
3706 (save-excursion
3707 (goto-char (org-table-begin 'any))
3708 (looking-at org-table1-hline-regexp))))
3709 (defun org-table-recognize-table.el ()
3710 "If there is a table.el table nearby, recognize it and move into it."
3711 (if org-table-tab-recognizes-table.el
3712 (if (org-at-table.el-p)
3713 (progn
3714 (beginning-of-line 1)
3715 (if (looking-at org-table-dataline-regexp)
3717 (if (looking-at org-table1-hline-regexp)
3718 (progn
3719 (beginning-of-line 2)
3720 (if (looking-at org-table-any-border-regexp)
3721 (beginning-of-line -1)))))
3722 (if (re-search-forward "|" (org-table-end t) t)
3723 (progn
3724 (require 'table)
3725 (if (table--at-cell-p (point))
3727 (message "recognizing table.el table...")
3728 (table-recognize-table)
3729 (message "recognizing table.el table...done")))
3730 (error "This should not happen"))
3732 nil)
3733 nil))
3735 (defun org-at-table-hline-p ()
3736 "Return t if the cursor is inside a hline in a table."
3737 (if org-enable-table-editor
3738 (save-excursion
3739 (beginning-of-line 1)
3740 (looking-at org-table-hline-regexp))
3741 nil))
3743 (defvar org-table-clean-did-remove-column nil)
3745 (defun org-table-map-tables (function &optional quietly)
3746 "Apply FUNCTION to the start of all tables in the buffer."
3747 (save-excursion
3748 (save-restriction
3749 (widen)
3750 (goto-char (point-min))
3751 (while (re-search-forward org-table-any-line-regexp nil t)
3752 (unless quietly
3753 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
3754 (beginning-of-line 1)
3755 (when (looking-at org-table-line-regexp)
3756 (save-excursion (funcall function))
3757 (or (looking-at org-table-line-regexp)
3758 (forward-char 1)))
3759 (re-search-forward org-table-any-border-regexp nil 1))))
3760 (unless quietly (message "Mapping tables: done")))
3762 ;; Declare and autoload functions from org-exp.el & Co
3764 (declare-function org-default-export-plist "org-exp")
3765 (declare-function org-infile-export-plist "org-exp")
3766 (declare-function org-get-current-options "org-exp")
3767 (eval-and-compile
3768 (org-autoload "org-exp"
3769 '(org-export org-export-visible
3770 org-insert-export-options-template
3771 org-table-clean-before-export))
3772 (org-autoload "org-ascii"
3773 '(org-export-as-ascii org-export-ascii-preprocess
3774 org-export-as-ascii-to-buffer org-replace-region-by-ascii
3775 org-export-region-as-ascii))
3776 (org-autoload "org-latex"
3777 '(org-export-as-latex-batch org-export-as-latex-to-buffer
3778 org-replace-region-by-latex org-export-region-as-latex
3779 org-export-as-latex org-export-as-pdf
3780 org-export-as-pdf-and-open))
3781 (org-autoload "org-html"
3782 '(org-export-as-html-and-open
3783 org-export-as-html-batch org-export-as-html-to-buffer
3784 org-replace-region-by-html org-export-region-as-html
3785 org-export-as-html))
3786 (org-autoload "org-docbook"
3787 '(org-export-as-docbook-batch org-export-as-docbook-to-buffer
3788 org-replace-region-by-docbook org-export-region-as-docbook
3789 org-export-as-docbook-pdf org-export-as-docbook-pdf-and-open
3790 org-export-as-docbook))
3791 (org-autoload "org-icalendar"
3792 '(org-export-icalendar-this-file
3793 org-export-icalendar-all-agenda-files
3794 org-export-icalendar-combine-agenda-files))
3795 (org-autoload "org-xoxo" '(org-export-as-xoxo))
3796 (org-autoload "org-beamer" '(org-beamer-mode org-beamer-sectioning)))
3798 ;; Declare and autoload functions from org-agenda.el
3800 (eval-and-compile
3801 (org-autoload "org-agenda"
3802 '(org-agenda org-agenda-list org-search-view
3803 org-todo-list org-tags-view org-agenda-list-stuck-projects
3804 org-diary org-agenda-to-appt
3805 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
3807 ;; Autoload org-remember
3809 (eval-and-compile
3810 (org-autoload "org-remember"
3811 '(org-remember-insinuate org-remember-annotation
3812 org-remember-apply-template org-remember org-remember-handler)))
3814 (eval-and-compile
3815 (org-autoload "org-capture"
3816 '(org-capture org-capture-insert-template-here
3817 org-capture-import-remember-templates)))
3819 ;; Autoload org-clock.el
3821 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
3822 (beg end))
3823 (declare-function org-clock-update-mode-line "org-clock" ())
3824 (declare-function org-resolve-clocks "org-clock"
3825 (&optional also-non-dangling-p prompt last-valid))
3826 (defvar org-clock-start-time)
3827 (defvar org-clock-marker (make-marker)
3828 "Marker recording the last clock-in.")
3829 (defvar org-clock-hd-marker (make-marker)
3830 "Marker recording the last clock-in, but the headline position.")
3831 (defvar org-clock-heading ""
3832 "The heading of the current clock entry.")
3833 (defun org-clock-is-active ()
3834 "Return non-nil if clock is currently running.
3835 The return value is actually the clock marker."
3836 (marker-buffer org-clock-marker))
3838 (eval-and-compile
3839 (org-autoload
3840 "org-clock"
3841 '(org-clock-in org-clock-out org-clock-cancel
3842 org-clock-goto org-clock-sum org-clock-display
3843 org-clock-remove-overlays org-clock-report
3844 org-clocktable-shift org-dblock-write:clocktable
3845 org-get-clocktable org-resolve-clocks)))
3847 (defun org-clock-update-time-maybe ()
3848 "If this is a CLOCK line, update it and return t.
3849 Otherwise, return nil."
3850 (interactive)
3851 (save-excursion
3852 (beginning-of-line 1)
3853 (skip-chars-forward " \t")
3854 (when (looking-at org-clock-string)
3855 (let ((re (concat "[ \t]*" org-clock-string
3856 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
3857 "\\([ \t]*=>.*\\)?\\)?"))
3858 ts te h m s neg)
3859 (cond
3860 ((not (looking-at re))
3861 nil)
3862 ((not (match-end 2))
3863 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3864 (> org-clock-marker (point))
3865 (<= org-clock-marker (point-at-eol)))
3866 ;; The clock is running here
3867 (setq org-clock-start-time
3868 (apply 'encode-time
3869 (org-parse-time-string (match-string 1))))
3870 (org-clock-update-mode-line)))
3872 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
3873 (end-of-line 1)
3874 (setq ts (match-string 1)
3875 te (match-string 3))
3876 (setq s (- (org-float-time
3877 (apply 'encode-time (org-parse-time-string te)))
3878 (org-float-time
3879 (apply 'encode-time (org-parse-time-string ts))))
3880 neg (< s 0)
3881 s (abs s)
3882 h (floor (/ s 3600))
3883 s (- s (* 3600 h))
3884 m (floor (/ s 60))
3885 s (- s (* 60 s)))
3886 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
3887 t))))))
3889 (defun org-check-running-clock ()
3890 "Check if the current buffer contains the running clock.
3891 If yes, offer to stop it and to save the buffer with the changes."
3892 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3893 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
3894 (buffer-name))))
3895 (org-clock-out)
3896 (when (y-or-n-p "Save changed buffer?")
3897 (save-buffer))))
3899 (defun org-clocktable-try-shift (dir n)
3900 "Check if this line starts a clock table, if yes, shift the time block."
3901 (when (org-match-line "#\\+BEGIN: clocktable\\>")
3902 (org-clocktable-shift dir n)))
3904 ;; Autoload org-timer.el
3906 (eval-and-compile
3907 (org-autoload
3908 "org-timer"
3909 '(org-timer-start org-timer org-timer-item
3910 org-timer-change-times-in-region
3911 org-timer-set-timer
3912 org-timer-reset-timers
3913 org-timer-show-remaining-time)))
3915 ;; Autoload org-feed.el
3917 (eval-and-compile
3918 (org-autoload
3919 "org-feed"
3920 '(org-feed-update org-feed-update-all org-feed-goto-inbox)))
3923 ;; Autoload org-indent.el
3925 ;; Define the variable already here, to make sure we have it.
3926 (defvar org-indent-mode nil
3927 "Non-nil if Org-Indent mode is enabled.
3928 Use the command `org-indent-mode' to change this variable.")
3930 (eval-and-compile
3931 (org-autoload
3932 "org-indent"
3933 '(org-indent-mode)))
3935 ;; Autoload org-mobile.el
3937 (eval-and-compile
3938 (org-autoload
3939 "org-mobile"
3940 '(org-mobile-push org-mobile-pull org-mobile-create-sumo-agenda)))
3942 ;; Autoload archiving code
3943 ;; The stuff that is needed for cycling and tags has to be defined here.
3945 (defgroup org-archive nil
3946 "Options concerning archiving in Org-mode."
3947 :tag "Org Archive"
3948 :group 'org-structure)
3950 (defcustom org-archive-location "%s_archive::"
3951 "The location where subtrees should be archived.
3953 The value of this variable is a string, consisting of two parts,
3954 separated by a double-colon. The first part is a filename and
3955 the second part is a headline.
3957 When the filename is omitted, archiving happens in the same file.
3958 %s in the filename will be replaced by the current file
3959 name (without the directory part). Archiving to a different file
3960 is useful to keep archived entries from contributing to the
3961 Org-mode Agenda.
3963 The archived entries will be filed as subtrees of the specified
3964 headline. When the headline is omitted, the subtrees are simply
3965 filed away at the end of the file, as top-level entries. Also in
3966 the heading you can use %s to represent the file name, this can be
3967 useful when using the same archive for a number of different files.
3969 Here are a few examples:
3970 \"%s_archive::\"
3971 If the current file is Projects.org, archive in file
3972 Projects.org_archive, as top-level trees. This is the default.
3974 \"::* Archived Tasks\"
3975 Archive in the current file, under the top-level headline
3976 \"* Archived Tasks\".
3978 \"~/org/archive.org::\"
3979 Archive in file ~/org/archive.org (absolute path), as top-level trees.
3981 \"~/org/archive.org::From %s\"
3982 Archive in file ~/org/archive.org (absolute path), under headlines
3983 \"From FILENAME\" where file name is the current file name.
3985 \"basement::** Finished Tasks\"
3986 Archive in file ./basement (relative path), as level 3 trees
3987 below the level 2 heading \"** Finished Tasks\".
3989 You may set this option on a per-file basis by adding to the buffer a
3990 line like
3992 #+ARCHIVE: basement::** Finished Tasks
3994 You may also define it locally for a subtree by setting an ARCHIVE property
3995 in the entry. If such a property is found in an entry, or anywhere up
3996 the hierarchy, it will be used."
3997 :group 'org-archive
3998 :type 'string)
4000 (defcustom org-archive-tag "ARCHIVE"
4001 "The tag that marks a subtree as archived.
4002 An archived subtree does not open during visibility cycling, and does
4003 not contribute to the agenda listings.
4004 After changing this, font-lock must be restarted in the relevant buffers to
4005 get the proper fontification."
4006 :group 'org-archive
4007 :group 'org-keywords
4008 :type 'string)
4010 (defcustom org-agenda-skip-archived-trees t
4011 "Non-nil means the agenda will skip any items located in archived trees.
4012 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4013 variable is no longer recommended, you should leave it at the value t.
4014 Instead, use the key `v' to cycle the archives-mode in the agenda."
4015 :group 'org-archive
4016 :group 'org-agenda-skip
4017 :type 'boolean)
4019 (defcustom org-columns-skip-archived-trees t
4020 "Non-nil means ignore archived trees when creating column view."
4021 :group 'org-archive
4022 :group 'org-properties
4023 :type 'boolean)
4025 (defcustom org-cycle-open-archived-trees nil
4026 "Non-nil means `org-cycle' will open archived trees.
4027 An archived tree is a tree marked with the tag ARCHIVE.
4028 When nil, archived trees will stay folded. You can still open them with
4029 normal outline commands like `show-all', but not with the cycling commands."
4030 :group 'org-archive
4031 :group 'org-cycle
4032 :type 'boolean)
4034 (defcustom org-sparse-tree-open-archived-trees nil
4035 "Non-nil means sparse tree construction shows matches in archived trees.
4036 When nil, matches in these trees are highlighted, but the trees are kept in
4037 collapsed state."
4038 :group 'org-archive
4039 :group 'org-sparse-trees
4040 :type 'boolean)
4042 (defun org-cycle-hide-archived-subtrees (state)
4043 "Re-hide all archived subtrees after a visibility state change."
4044 (when (and (not org-cycle-open-archived-trees)
4045 (not (memq state '(overview folded))))
4046 (save-excursion
4047 (let* ((globalp (memq state '(contents all)))
4048 (beg (if globalp (point-min) (point)))
4049 (end (if globalp (point-max) (org-end-of-subtree t))))
4050 (org-hide-archived-subtrees beg end)
4051 (goto-char beg)
4052 (if (looking-at (concat ".*:" org-archive-tag ":"))
4053 (message "%s" (substitute-command-keys
4054 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4056 (defun org-force-cycle-archived ()
4057 "Cycle subtree even if it is archived."
4058 (interactive)
4059 (setq this-command 'org-cycle)
4060 (let ((org-cycle-open-archived-trees t))
4061 (call-interactively 'org-cycle)))
4063 (defun org-hide-archived-subtrees (beg end)
4064 "Re-hide all archived subtrees after a visibility state change."
4065 (save-excursion
4066 (let* ((re (concat ":" org-archive-tag ":")))
4067 (goto-char beg)
4068 (while (re-search-forward re end t)
4069 (when (org-on-heading-p)
4070 (org-flag-subtree t)
4071 (org-end-of-subtree t))))))
4073 (defun org-flag-subtree (flag)
4074 (save-excursion
4075 (org-back-to-heading t)
4076 (outline-end-of-heading)
4077 (outline-flag-region (point)
4078 (progn (org-end-of-subtree t) (point))
4079 flag)))
4081 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4083 (eval-and-compile
4084 (org-autoload "org-archive"
4085 '(org-add-archive-files org-archive-subtree
4086 org-archive-to-archive-sibling org-toggle-archive-tag
4087 org-archive-subtree-default
4088 org-archive-subtree-default-with-confirmation)))
4090 ;; Autoload Column View Code
4092 (declare-function org-columns-number-to-string "org-colview")
4093 (declare-function org-columns-get-format-and-top-level "org-colview")
4094 (declare-function org-columns-compute "org-colview")
4096 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4097 '(org-columns-number-to-string org-columns-get-format-and-top-level
4098 org-columns-compute org-agenda-columns org-columns-remove-overlays
4099 org-columns org-insert-columns-dblock org-dblock-write:columnview))
4101 ;; Autoload ID code
4103 (declare-function org-id-store-link "org-id")
4104 (declare-function org-id-locations-load "org-id")
4105 (declare-function org-id-locations-save "org-id")
4106 (defvar org-id-track-globally)
4107 (org-autoload "org-id"
4108 '(org-id-get-create org-id-new org-id-copy org-id-get
4109 org-id-get-with-outline-path-completion
4110 org-id-get-with-outline-drilling org-id-store-link
4111 org-id-goto org-id-find org-id-store-link))
4113 ;; Autoload Plotting Code
4115 (org-autoload "org-plot"
4116 '(org-plot/gnuplot))
4118 ;;; Variables for pre-computed regular expressions, all buffer local
4120 (defvar org-drawer-regexp nil
4121 "Matches first line of a hidden block.")
4122 (make-variable-buffer-local 'org-drawer-regexp)
4123 (defvar org-todo-regexp nil
4124 "Matches any of the TODO state keywords.")
4125 (make-variable-buffer-local 'org-todo-regexp)
4126 (defvar org-not-done-regexp nil
4127 "Matches any of the TODO state keywords except the last one.")
4128 (make-variable-buffer-local 'org-not-done-regexp)
4129 (defvar org-not-done-heading-regexp nil
4130 "Matches a TODO headline that is not done.")
4131 (make-variable-buffer-local 'org-not-done-regexp)
4132 (defvar org-todo-line-regexp nil
4133 "Matches a headline and puts TODO state into group 2 if present.")
4134 (make-variable-buffer-local 'org-todo-line-regexp)
4135 (defvar org-complex-heading-regexp nil
4136 "Matches a headline and puts everything into groups:
4137 group 1: the stars
4138 group 2: The todo keyword, maybe
4139 group 3: Priority cookie
4140 group 4: True headline
4141 group 5: Tags")
4142 (make-variable-buffer-local 'org-complex-heading-regexp)
4143 (defvar org-complex-heading-regexp-format nil
4144 "Printf format to make regexp to match an exact headline.
4145 This regexp will match the headline of any node which hase the exact
4146 headline text that is put into the format, but may have any TODO state,
4147 priority and tags.")
4148 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4149 (defvar org-todo-line-tags-regexp nil
4150 "Matches a headline and puts TODO state into group 2 if present.
4151 Also put tags into group 4 if tags are present.")
4152 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4153 (defvar org-nl-done-regexp nil
4154 "Matches newline followed by a headline with the DONE keyword.")
4155 (make-variable-buffer-local 'org-nl-done-regexp)
4156 (defvar org-looking-at-done-regexp nil
4157 "Matches the DONE keyword a point.")
4158 (make-variable-buffer-local 'org-looking-at-done-regexp)
4159 (defvar org-ds-keyword-length 12
4160 "Maximum length of the Deadline and SCHEDULED keywords.")
4161 (make-variable-buffer-local 'org-ds-keyword-length)
4162 (defvar org-deadline-regexp nil
4163 "Matches the DEADLINE keyword.")
4164 (make-variable-buffer-local 'org-deadline-regexp)
4165 (defvar org-deadline-time-regexp nil
4166 "Matches the DEADLINE keyword together with a time stamp.")
4167 (make-variable-buffer-local 'org-deadline-time-regexp)
4168 (defvar org-deadline-line-regexp nil
4169 "Matches the DEADLINE keyword and the rest of the line.")
4170 (make-variable-buffer-local 'org-deadline-line-regexp)
4171 (defvar org-scheduled-regexp nil
4172 "Matches the SCHEDULED keyword.")
4173 (make-variable-buffer-local 'org-scheduled-regexp)
4174 (defvar org-scheduled-time-regexp nil
4175 "Matches the SCHEDULED keyword together with a time stamp.")
4176 (make-variable-buffer-local 'org-scheduled-time-regexp)
4177 (defvar org-closed-time-regexp nil
4178 "Matches the CLOSED keyword together with a time stamp.")
4179 (make-variable-buffer-local 'org-closed-time-regexp)
4181 (defvar org-keyword-time-regexp nil
4182 "Matches any of the 4 keywords, together with the time stamp.")
4183 (make-variable-buffer-local 'org-keyword-time-regexp)
4184 (defvar org-keyword-time-not-clock-regexp nil
4185 "Matches any of the 3 keywords, together with the time stamp.")
4186 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4187 (defvar org-maybe-keyword-time-regexp nil
4188 "Matches a timestamp, possibly preceded by a keyword.")
4189 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4190 (defvar org-planning-or-clock-line-re nil
4191 "Matches a line with planning or clock info.")
4192 (make-variable-buffer-local 'org-planning-or-clock-line-re)
4193 (defvar org-all-time-keywords nil
4194 "List of time keywords.")
4195 (make-variable-buffer-local 'org-all-time-keywords)
4197 (defconst org-plain-time-of-day-regexp
4198 (concat
4199 "\\(\\<[012]?[0-9]"
4200 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4201 "\\(--?"
4202 "\\(\\<[012]?[0-9]"
4203 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4204 "\\)?")
4205 "Regular expression to match a plain time or time range.
4206 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4207 groups carry important information:
4208 0 the full match
4209 1 the first time, range or not
4210 8 the second time, if it is a range.")
4212 (defconst org-plain-time-extension-regexp
4213 (concat
4214 "\\(\\<[012]?[0-9]"
4215 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4216 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4217 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4218 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4219 groups carry important information:
4220 0 the full match
4221 7 hours of duration
4222 9 minutes of duration")
4224 (defconst org-stamp-time-of-day-regexp
4225 (concat
4226 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4227 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4228 "\\(--?"
4229 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4230 "Regular expression to match a timestamp time or time range.
4231 After a match, the following groups carry important information:
4232 0 the full match
4233 1 date plus weekday, for back referencing to make sure both times are on the same day
4234 2 the first time, range or not
4235 4 the second time, if it is a range.")
4237 (defconst org-startup-options
4238 '(("fold" org-startup-folded t)
4239 ("overview" org-startup-folded t)
4240 ("nofold" org-startup-folded nil)
4241 ("showall" org-startup-folded nil)
4242 ("showeverything" org-startup-folded showeverything)
4243 ("content" org-startup-folded content)
4244 ("indent" org-startup-indented t)
4245 ("noindent" org-startup-indented nil)
4246 ("hidestars" org-hide-leading-stars t)
4247 ("showstars" org-hide-leading-stars nil)
4248 ("odd" org-odd-levels-only t)
4249 ("oddeven" org-odd-levels-only nil)
4250 ("align" org-startup-align-all-tables t)
4251 ("noalign" org-startup-align-all-tables nil)
4252 ("inlineimages" org-startup-with-inline-images t)
4253 ("noinlineimages" org-startup-with-inline-images nil)
4254 ("customtime" org-display-custom-times t)
4255 ("logdone" org-log-done time)
4256 ("lognotedone" org-log-done note)
4257 ("nologdone" org-log-done nil)
4258 ("lognoteclock-out" org-log-note-clock-out t)
4259 ("nolognoteclock-out" org-log-note-clock-out nil)
4260 ("logrepeat" org-log-repeat state)
4261 ("lognoterepeat" org-log-repeat note)
4262 ("nologrepeat" org-log-repeat nil)
4263 ("logreschedule" org-log-reschedule time)
4264 ("lognotereschedule" org-log-reschedule note)
4265 ("nologreschedule" org-log-reschedule nil)
4266 ("logredeadline" org-log-redeadline time)
4267 ("lognoteredeadline" org-log-redeadline note)
4268 ("nologredeadline" org-log-redeadline nil)
4269 ("logrefile" org-log-refile time)
4270 ("lognoterefile" org-log-refile note)
4271 ("nologrefile" org-log-refile nil)
4272 ("fninline" org-footnote-define-inline t)
4273 ("nofninline" org-footnote-define-inline nil)
4274 ("fnlocal" org-footnote-section nil)
4275 ("fnauto" org-footnote-auto-label t)
4276 ("fnprompt" org-footnote-auto-label nil)
4277 ("fnconfirm" org-footnote-auto-label confirm)
4278 ("fnplain" org-footnote-auto-label plain)
4279 ("fnadjust" org-footnote-auto-adjust t)
4280 ("nofnadjust" org-footnote-auto-adjust nil)
4281 ("constcgs" constants-unit-system cgs)
4282 ("constSI" constants-unit-system SI)
4283 ("noptag" org-tag-persistent-alist nil)
4284 ("hideblocks" org-hide-block-startup t)
4285 ("nohideblocks" org-hide-block-startup nil)
4286 ("beamer" org-startup-with-beamer-mode t)
4287 ("entitiespretty" org-pretty-entities t)
4288 ("entitiesplain" org-pretty-entities nil))
4289 "Variable associated with STARTUP options for org-mode.
4290 Each element is a list of three items: The startup options as written
4291 in the #+STARTUP line, the corresponding variable, and the value to
4292 set this variable to if the option is found. An optional forth element PUSH
4293 means to push this value onto the list in the variable.")
4295 (defun org-set-regexps-and-options ()
4296 "Precompute regular expressions for current buffer."
4297 (when (org-mode-p)
4298 (org-set-local 'org-todo-kwd-alist nil)
4299 (org-set-local 'org-todo-key-alist nil)
4300 (org-set-local 'org-todo-key-trigger nil)
4301 (org-set-local 'org-todo-keywords-1 nil)
4302 (org-set-local 'org-done-keywords nil)
4303 (org-set-local 'org-todo-heads nil)
4304 (org-set-local 'org-todo-sets nil)
4305 (org-set-local 'org-todo-log-states nil)
4306 (org-set-local 'org-file-properties nil)
4307 (org-set-local 'org-file-tags nil)
4308 (let ((re (org-make-options-regexp
4309 '("CATEGORY" "TODO" "COLUMNS"
4310 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
4311 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE" "LATEX_CLASS"
4312 "OPTIONS")
4313 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4314 (splitre "[ \t]+")
4315 (scripts org-use-sub-superscripts)
4316 kwds kws0 kwsa key log value cat arch tags const links hw dws
4317 tail sep kws1 prio props ftags drawers beamer-p
4318 ext-setup-or-nil setup-contents (start 0))
4319 (save-excursion
4320 (save-restriction
4321 (widen)
4322 (goto-char (point-min))
4323 (while (or (and ext-setup-or-nil
4324 (string-match re ext-setup-or-nil start)
4325 (setq start (match-end 0)))
4326 (and (setq ext-setup-or-nil nil start 0)
4327 (re-search-forward re nil t)))
4328 (setq key (upcase (match-string 1 ext-setup-or-nil))
4329 value (org-match-string-no-properties 2 ext-setup-or-nil))
4330 (if (stringp value) (setq value (org-trim value)))
4331 (cond
4332 ((equal key "CATEGORY")
4333 (setq cat value))
4334 ((member key '("SEQ_TODO" "TODO"))
4335 (push (cons 'sequence (org-split-string value splitre)) kwds))
4336 ((equal key "TYP_TODO")
4337 (push (cons 'type (org-split-string value splitre)) kwds))
4338 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4339 ;; general TODO-like setup
4340 (push (cons (intern (downcase (match-string 1 key)))
4341 (org-split-string value splitre)) kwds))
4342 ((equal key "TAGS")
4343 (setq tags (append tags (if tags '("\\n") nil)
4344 (org-split-string value splitre))))
4345 ((equal key "COLUMNS")
4346 (org-set-local 'org-columns-default-format value))
4347 ((equal key "LINK")
4348 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4349 (push (cons (match-string 1 value)
4350 (org-trim (match-string 2 value)))
4351 links)))
4352 ((equal key "PRIORITIES")
4353 (setq prio (org-split-string value " +")))
4354 ((equal key "PROPERTY")
4355 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4356 (push (cons (match-string 1 value) (match-string 2 value))
4357 props)))
4358 ((equal key "FILETAGS")
4359 (when (string-match "\\S-" value)
4360 (setq ftags
4361 (append
4362 ftags
4363 (apply 'append
4364 (mapcar (lambda (x) (org-split-string x ":"))
4365 (org-split-string value)))))))
4366 ((equal key "DRAWERS")
4367 (setq drawers (org-split-string value splitre)))
4368 ((equal key "CONSTANTS")
4369 (setq const (append const (org-split-string value splitre))))
4370 ((equal key "STARTUP")
4371 (let ((opts (org-split-string value splitre))
4372 l var val)
4373 (while (setq l (pop opts))
4374 (when (setq l (assoc l org-startup-options))
4375 (setq var (nth 1 l) val (nth 2 l))
4376 (if (not (nth 3 l))
4377 (set (make-local-variable var) val)
4378 (if (not (listp (symbol-value var)))
4379 (set (make-local-variable var) nil))
4380 (set (make-local-variable var) (symbol-value var))
4381 (add-to-list var val))))))
4382 ((equal key "ARCHIVE")
4383 (setq arch value)
4384 (remove-text-properties 0 (length arch)
4385 '(face t fontified t) arch))
4386 ((equal key "LATEX_CLASS")
4387 (setq beamer-p (equal value "beamer")))
4388 ((equal key "OPTIONS")
4389 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4390 (setq scripts (read (match-string 2 value)))))
4391 ((equal key "SETUPFILE")
4392 (setq setup-contents (org-file-contents
4393 (expand-file-name
4394 (org-remove-double-quotes value))
4395 'noerror))
4396 (if (not ext-setup-or-nil)
4397 (setq ext-setup-or-nil setup-contents start 0)
4398 (setq ext-setup-or-nil
4399 (concat (substring ext-setup-or-nil 0 start)
4400 "\n" setup-contents "\n"
4401 (substring ext-setup-or-nil start)))))
4402 ))))
4403 (org-set-local 'org-use-sub-superscripts scripts)
4404 (when cat
4405 (org-set-local 'org-category (intern cat))
4406 (push (cons "CATEGORY" cat) props))
4407 (when prio
4408 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4409 (setq prio (mapcar 'string-to-char prio))
4410 (org-set-local 'org-highest-priority (nth 0 prio))
4411 (org-set-local 'org-lowest-priority (nth 1 prio))
4412 (org-set-local 'org-default-priority (nth 2 prio)))
4413 (and props (org-set-local 'org-file-properties (nreverse props)))
4414 (and ftags (org-set-local 'org-file-tags
4415 (mapcar 'org-add-prop-inherited ftags)))
4416 (and drawers (org-set-local 'org-drawers drawers))
4417 (and arch (org-set-local 'org-archive-location arch))
4418 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4419 ;; Process the TODO keywords
4420 (unless kwds
4421 ;; Use the global values as if they had been given locally.
4422 (setq kwds (default-value 'org-todo-keywords))
4423 (if (stringp (car kwds))
4424 (setq kwds (list (cons org-todo-interpretation
4425 (default-value 'org-todo-keywords)))))
4426 (setq kwds (reverse kwds)))
4427 (setq kwds (nreverse kwds))
4428 (let (inter kws kw)
4429 (while (setq kws (pop kwds))
4430 (let ((kws (or
4431 (run-hook-with-args-until-success
4432 'org-todo-setup-filter-hook kws)
4433 kws)))
4434 (setq inter (pop kws) sep (member "|" kws)
4435 kws0 (delete "|" (copy-sequence kws))
4436 kwsa nil
4437 kws1 (mapcar
4438 (lambda (x)
4439 ;; 1 2
4440 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4441 (progn
4442 (setq kw (match-string 1 x)
4443 key (and (match-end 2) (match-string 2 x))
4444 log (org-extract-log-state-settings x))
4445 (push (cons kw (and key (string-to-char key))) kwsa)
4446 (and log (push log org-todo-log-states))
4448 (error "Invalid TODO keyword %s" x)))
4449 kws0)
4450 kwsa (if kwsa (append '((:startgroup))
4451 (nreverse kwsa)
4452 '((:endgroup))))
4453 hw (car kws1)
4454 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4455 tail (list inter hw (car dws) (org-last dws))))
4456 (add-to-list 'org-todo-heads hw 'append)
4457 (push kws1 org-todo-sets)
4458 (setq org-done-keywords (append org-done-keywords dws nil))
4459 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4460 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4461 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4462 (setq org-todo-sets (nreverse org-todo-sets)
4463 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4464 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4465 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4466 ;; Process the constants
4467 (when const
4468 (let (e cst)
4469 (while (setq e (pop const))
4470 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4471 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4472 (setq org-table-formula-constants-local cst)))
4474 ;; Process the tags.
4475 (when tags
4476 (let (e tgs)
4477 (while (setq e (pop tags))
4478 (cond
4479 ((equal e "{") (push '(:startgroup) tgs))
4480 ((equal e "}") (push '(:endgroup) tgs))
4481 ((equal e "\\n") (push '(:newline) tgs))
4482 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4483 (push (cons (match-string 1 e)
4484 (string-to-char (match-string 2 e)))
4485 tgs))
4486 (t (push (list e) tgs))))
4487 (org-set-local 'org-tag-alist nil)
4488 (while (setq e (pop tgs))
4489 (or (and (stringp (car e))
4490 (assoc (car e) org-tag-alist))
4491 (push e org-tag-alist)))))
4493 ;; Compute the regular expressions and other local variables
4494 (if (not org-done-keywords)
4495 (setq org-done-keywords (and org-todo-keywords-1
4496 (list (org-last org-todo-keywords-1)))))
4497 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4498 (length org-scheduled-string)
4499 (length org-clock-string)
4500 (length org-closed-string)))
4501 org-drawer-regexp
4502 (concat "^[ \t]*:\\("
4503 (mapconcat 'regexp-quote org-drawers "\\|")
4504 "\\):[ \t]*$")
4505 org-not-done-keywords
4506 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4507 org-todo-regexp
4508 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
4509 "\\|") "\\)\\>")
4510 org-not-done-regexp
4511 (concat "\\<\\("
4512 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4513 "\\)\\>")
4514 org-not-done-heading-regexp
4515 (concat "^\\(\\*+\\)[ \t]+\\("
4516 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4517 "\\)\\>")
4518 org-todo-line-regexp
4519 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4520 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4521 "\\)\\>\\)?[ \t]*\\(.*\\)")
4522 org-complex-heading-regexp
4523 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4524 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4525 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
4526 "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
4527 org-complex-heading-regexp-format
4528 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4529 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4530 "\\)\\>\\)?"
4531 "\\(?:[ \t]*\\(\\[#.\\]\\)\\)?"
4532 "\\(?:[ \t]*\\(?:\\[[0-9%%/]+\\]\\)\\)?" ;; stats cookie
4533 "[ \t]*\\(%s\\)"
4534 "\\(?:[ \t]*\\(?:\\[[0-9%%/]+\\]\\)\\)?" ;; stats cookie
4535 "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?[ \t]*$")
4536 org-nl-done-regexp
4537 (concat "\n\\*+[ \t]+"
4538 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
4539 "\\)" "\\>")
4540 org-todo-line-tags-regexp
4541 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4542 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4543 (org-re
4544 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@#%]+:[ \t]*\\)?$\\)"))
4545 org-looking-at-done-regexp
4546 (concat "^" "\\(?:"
4547 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
4548 "\\>")
4549 org-deadline-regexp (concat "\\<" org-deadline-string)
4550 org-deadline-time-regexp
4551 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4552 org-deadline-line-regexp
4553 (concat "\\<\\(" org-deadline-string "\\).*")
4554 org-scheduled-regexp
4555 (concat "\\<" org-scheduled-string)
4556 org-scheduled-time-regexp
4557 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4558 org-closed-time-regexp
4559 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4560 org-keyword-time-regexp
4561 (concat "\\<\\(" org-scheduled-string
4562 "\\|" org-deadline-string
4563 "\\|" org-closed-string
4564 "\\|" org-clock-string "\\)"
4565 " *[[<]\\([^]>]+\\)[]>]")
4566 org-keyword-time-not-clock-regexp
4567 (concat "\\<\\(" org-scheduled-string
4568 "\\|" org-deadline-string
4569 "\\|" org-closed-string
4570 "\\)"
4571 " *[[<]\\([^]>]+\\)[]>]")
4572 org-maybe-keyword-time-regexp
4573 (concat "\\(\\<\\(" org-scheduled-string
4574 "\\|" org-deadline-string
4575 "\\|" org-closed-string
4576 "\\|" org-clock-string "\\)\\)?"
4577 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4578 org-planning-or-clock-line-re
4579 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
4580 "\\|" org-deadline-string
4581 "\\|" org-closed-string "\\|" org-clock-string
4582 "\\)\\>\\)")
4583 org-all-time-keywords
4584 (mapcar (lambda (w) (substring w 0 -1))
4585 (list org-scheduled-string org-deadline-string
4586 org-clock-string org-closed-string))
4588 (org-compute-latex-and-specials-regexp)
4589 (org-set-font-lock-defaults))))
4591 (defun org-file-contents (file &optional noerror)
4592 "Return the contents of FILE, as a string."
4593 (if (or (not file)
4594 (not (file-readable-p file)))
4595 (if noerror
4596 (progn
4597 (message "Cannot read file \"%s\"" file)
4598 (ding) (sit-for 2)
4600 (error "Cannot read file \"%s\"" file))
4601 (with-temp-buffer
4602 (insert-file-contents file)
4603 (buffer-string))))
4605 (defun org-extract-log-state-settings (x)
4606 "Extract the log state setting from a TODO keyword string.
4607 This will extract info from a string like \"WAIT(w@/!)\"."
4608 (let (kw key log1 log2)
4609 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4610 (setq kw (match-string 1 x)
4611 key (and (match-end 2) (match-string 2 x))
4612 log1 (and (match-end 3) (match-string 3 x))
4613 log2 (and (match-end 4) (match-string 4 x)))
4614 (and (or log1 log2)
4615 (list kw
4616 (and log1 (if (equal log1 "!") 'time 'note))
4617 (and log2 (if (equal log2 "!") 'time 'note)))))))
4619 (defun org-remove-keyword-keys (list)
4620 "Remove a pair of parenthesis at the end of each string in LIST."
4621 (mapcar (lambda (x)
4622 (if (string-match "(.*)$" x)
4623 (substring x 0 (match-beginning 0))
4625 list))
4627 (defun org-assign-fast-keys (alist)
4628 "Assign fast keys to a keyword-key alist.
4629 Respect keys that are already there."
4630 (let (new e (alt ?0))
4631 (while (setq e (pop alist))
4632 (if (or (memq (car e) '(:newline :endgroup :startgroup))
4633 (cdr e)) ;; Key already assigned.
4634 (push e new)
4635 (let ((clist (string-to-list (downcase (car e))))
4636 (used (append new alist)))
4637 (when (= (car clist) ?@)
4638 (pop clist))
4639 (while (and clist (rassoc (car clist) used))
4640 (pop clist))
4641 (unless clist
4642 (while (rassoc alt used)
4643 (incf alt)))
4644 (push (cons (car e) (or (car clist) alt)) new))))
4645 (nreverse new)))
4647 ;;; Some variables used in various places
4649 (defvar org-window-configuration nil
4650 "Used in various places to store a window configuration.")
4651 (defvar org-selected-window nil
4652 "Used in various places to store a window configuration.")
4653 (defvar org-finish-function nil
4654 "Function to be called when `C-c C-c' is used.
4655 This is for getting out of special buffers like remember.")
4658 ;; FIXME: Occasionally check by commenting these, to make sure
4659 ;; no other functions uses these, forgetting to let-bind them.
4660 (defvar entry)
4661 (defvar last-state)
4662 (defvar date)
4664 ;; Defined somewhere in this file, but used before definition.
4665 (defvar org-entities) ;; defined in org-entities.el
4666 (defvar org-struct-menu)
4667 (defvar org-org-menu)
4668 (defvar org-tbl-menu)
4670 ;;;; Define the Org-mode
4672 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4673 (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"))
4676 ;; We use a before-change function to check if a table might need
4677 ;; an update.
4678 (defvar org-table-may-need-update t
4679 "Indicates that a table might need an update.
4680 This variable is set by `org-before-change-function'.
4681 `org-table-align' sets it back to nil.")
4682 (defun org-before-change-function (beg end)
4683 "Every change indicates that a table might need an update."
4684 (setq org-table-may-need-update t))
4685 (defvar org-mode-map)
4686 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4687 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
4688 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4689 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
4690 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
4691 (defvar org-table-buffer-is-an nil)
4692 (defconst org-outline-regexp "\\*+ ")
4694 ;;;###autoload
4695 (define-derived-mode org-mode outline-mode "Org"
4696 "Outline-based notes management and organizer, alias
4697 \"Carsten's outline-mode for keeping track of everything.\"
4699 Org-mode develops organizational tasks around a NOTES file which
4700 contains information about projects as plain text. Org-mode is
4701 implemented on top of outline-mode, which is ideal to keep the content
4702 of large files well structured. It supports ToDo items, deadlines and
4703 time stamps, which magically appear in the diary listing of the Emacs
4704 calendar. Tables are easily created with a built-in table editor.
4705 Plain text URL-like links connect to websites, emails (VM), Usenet
4706 messages (Gnus), BBDB entries, and any files related to the project.
4707 For printing and sharing of notes, an Org-mode file (or a part of it)
4708 can be exported as a structured ASCII or HTML file.
4710 The following commands are available:
4712 \\{org-mode-map}"
4714 ;; Get rid of Outline menus, they are not needed
4715 ;; Need to do this here because define-derived-mode sets up
4716 ;; the keymap so late. Still, it is a waste to call this each time
4717 ;; we switch another buffer into org-mode.
4718 (if (featurep 'xemacs)
4719 (when (boundp 'outline-mode-menu-heading)
4720 ;; Assume this is Greg's port, it uses easymenu
4721 (easy-menu-remove outline-mode-menu-heading)
4722 (easy-menu-remove outline-mode-menu-show)
4723 (easy-menu-remove outline-mode-menu-hide))
4724 (define-key org-mode-map [menu-bar headings] 'undefined)
4725 (define-key org-mode-map [menu-bar hide] 'undefined)
4726 (define-key org-mode-map [menu-bar show] 'undefined))
4728 (org-load-modules-maybe)
4729 (easy-menu-add org-org-menu)
4730 (easy-menu-add org-tbl-menu)
4731 (org-install-agenda-files-menu)
4732 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
4733 (add-to-invisibility-spec '(org-cwidth))
4734 (add-to-invisibility-spec '(org-hide-block . t))
4735 (when (featurep 'xemacs)
4736 (org-set-local 'line-move-ignore-invisible t))
4737 (org-set-local 'outline-regexp org-outline-regexp)
4738 (org-set-local 'outline-level 'org-outline-level)
4739 (when (and org-ellipsis
4740 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
4741 (fboundp 'make-glyph-code))
4742 (unless org-display-table
4743 (setq org-display-table (make-display-table)))
4744 (set-display-table-slot
4745 org-display-table 4
4746 (vconcat (mapcar
4747 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
4748 org-ellipsis)))
4749 (if (stringp org-ellipsis) org-ellipsis "..."))))
4750 (setq buffer-display-table org-display-table))
4751 (org-set-regexps-and-options)
4752 (when (and org-tag-faces (not org-tags-special-faces-re))
4753 ;; tag faces set outside customize.... force initialization.
4754 (org-set-tag-faces 'org-tag-faces org-tag-faces))
4755 ;; Calc embedded
4756 (org-set-local 'calc-embedded-open-mode "# ")
4757 (modify-syntax-entry ?@ "w")
4758 (if org-startup-truncated (setq truncate-lines t))
4759 (org-set-local 'font-lock-unfontify-region-function
4760 'org-unfontify-region)
4761 ;; Activate before-change-function
4762 (org-set-local 'org-table-may-need-update t)
4763 (org-add-hook 'before-change-functions 'org-before-change-function nil
4764 'local)
4765 ;; Check for running clock before killing a buffer
4766 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
4767 ;; Paragraphs and auto-filling
4768 (org-set-autofill-regexps)
4769 (setq indent-line-function 'org-indent-line-function)
4770 (org-update-radio-target-regexp)
4771 ;; Beginning/end of defun
4772 (org-set-local 'beginning-of-defun-function 'org-beginning-of-defun)
4773 (org-set-local 'end-of-defun-function 'org-end-of-defun)
4774 ;; Next error for sparse trees
4775 (org-set-local 'next-error-function 'org-occur-next-match)
4776 ;; Make sure dependence stuff works reliably, even for users who set it
4777 ;; too late :-(
4778 (if org-enforce-todo-dependencies
4779 (add-hook 'org-blocker-hook
4780 'org-block-todo-from-children-or-siblings-or-parent)
4781 (remove-hook 'org-blocker-hook
4782 'org-block-todo-from-children-or-siblings-or-parent))
4783 (if org-enforce-todo-checkbox-dependencies
4784 (add-hook 'org-blocker-hook
4785 'org-block-todo-from-checkboxes)
4786 (remove-hook 'org-blocker-hook
4787 'org-block-todo-from-checkboxes))
4789 ;; Comment characters
4790 (org-set-local 'comment-start "#")
4791 (org-set-local 'comment-padding " ")
4793 ;; Align options lines
4794 (org-set-local
4795 'align-mode-rules-list
4796 '((org-in-buffer-settings
4797 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
4798 (modes . '(org-mode)))))
4800 ;; Imenu
4801 (org-set-local 'imenu-create-index-function
4802 'org-imenu-get-tree)
4804 ;; Make isearch reveal context
4805 (if (or (featurep 'xemacs)
4806 (not (boundp 'outline-isearch-open-invisible-function)))
4807 ;; Emacs 21 and XEmacs make use of the hook
4808 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
4809 ;; Emacs 22 deals with this through a special variable
4810 (org-set-local 'outline-isearch-open-invisible-function
4811 (lambda (&rest ignore) (org-show-context 'isearch))))
4813 ;; Turn on org-beamer-mode?
4814 (and org-startup-with-beamer-mode (org-beamer-mode 1))
4816 ;; Setup the pcomplete hooks
4817 (set (make-local-variable 'pcomplete-command-completion-function)
4818 'org-pcomplete-initial)
4819 (set (make-local-variable 'pcomplete-command-name-function)
4820 'org-command-at-point)
4821 (set (make-local-variable 'pcomplete-default-completion-function)
4822 'ignore)
4823 (set (make-local-variable 'pcomplete-parse-arguments-function)
4824 'org-parse-arguments)
4825 (set (make-local-variable 'pcomplete-termination-string) "")
4827 ;; If empty file that did not turn on org-mode automatically, make it to.
4828 (if (and org-insert-mode-line-in-empty-file
4829 (interactive-p)
4830 (= (point-min) (point-max)))
4831 (insert "# -*- mode: org -*-\n\n"))
4832 (unless org-inhibit-startup
4833 (when org-startup-align-all-tables
4834 (let ((bmp (buffer-modified-p)))
4835 (org-table-map-tables 'org-table-align 'quietly)
4836 (set-buffer-modified-p bmp)))
4837 (when org-startup-with-inline-images
4838 (org-display-inline-images))
4839 (when org-startup-indented
4840 (require 'org-indent)
4841 (org-indent-mode 1))
4842 (unless org-inhibit-startup-visibility-stuff
4843 (org-set-startup-visibility))))
4845 (when (fboundp 'abbrev-table-put)
4846 (abbrev-table-put org-mode-abbrev-table
4847 :parents (list text-mode-abbrev-table)))
4849 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
4851 (defun org-current-time ()
4852 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
4853 (if (> (car org-time-stamp-rounding-minutes) 1)
4854 (let ((r (car org-time-stamp-rounding-minutes))
4855 (time (decode-time)))
4856 (apply 'encode-time
4857 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
4858 (nthcdr 2 time))))
4859 (current-time)))
4861 (defun org-today ()
4862 "Return today date, considering `org-extend-today-until'."
4863 (time-to-days
4864 (time-subtract (current-time)
4865 (list 0 (* 3600 org-extend-today-until) 0))))
4867 ;;;; Font-Lock stuff, including the activators
4869 (defvar org-mouse-map (make-sparse-keymap))
4870 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
4871 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
4872 (when org-mouse-1-follows-link
4873 (org-defkey org-mouse-map [follow-link] 'mouse-face))
4874 (when org-tab-follows-link
4875 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
4876 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
4878 (require 'font-lock)
4880 (defconst org-non-link-chars "]\t\n\r<>")
4881 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
4882 "shell" "elisp" "doi" "message"))
4883 (defvar org-link-types-re nil
4884 "Matches a link that has a url-like prefix like \"http:\"")
4885 (defvar org-link-re-with-space nil
4886 "Matches a link with spaces, optional angular brackets around it.")
4887 (defvar org-link-re-with-space2 nil
4888 "Matches a link with spaces, optional angular brackets around it.")
4889 (defvar org-link-re-with-space3 nil
4890 "Matches a link with spaces, only for internal part in bracket links.")
4891 (defvar org-angle-link-re nil
4892 "Matches link with angular brackets, spaces are allowed.")
4893 (defvar org-plain-link-re nil
4894 "Matches plain link, without spaces.")
4895 (defvar org-bracket-link-regexp nil
4896 "Matches a link in double brackets.")
4897 (defvar org-bracket-link-analytic-regexp nil
4898 "Regular expression used to analyze links.
4899 Here is what the match groups contain after a match:
4900 1: http:
4901 2: http
4902 3: path
4903 4: [desc]
4904 5: desc")
4905 (defvar org-bracket-link-analytic-regexp++ nil
4906 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
4907 (defvar org-any-link-re nil
4908 "Regular expression matching any link.")
4910 (defcustom org-match-sexp-depth 3
4911 "Number of stacked braces for sub/superscript matching.
4912 This has to be set before loading org.el to be effective."
4913 :group 'org-export-translation ; ??????????????????????????/
4914 :type 'integer)
4916 (defun org-create-multibrace-regexp (left right n)
4917 "Create a regular expression which will match a balanced sexp.
4918 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
4919 as single character strings.
4920 The regexp returned will match the entire expression including the
4921 delimiters. It will also define a single group which contains the
4922 match except for the outermost delimiters. The maximum depth of
4923 stacked delimiters is N. Escaping delimiters is not possible."
4924 (let* ((nothing (concat "[^" left right "]*?"))
4925 (or "\\|")
4926 (re nothing)
4927 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
4928 (while (> n 1)
4929 (setq n (1- n)
4930 re (concat re or next)
4931 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
4932 (concat left "\\(" re "\\)" right)))
4934 (defvar org-match-substring-regexp
4935 (concat
4936 "\\([^\\]\\)\\([_^]\\)\\("
4937 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
4938 "\\|"
4939 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
4940 "\\|"
4941 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
4942 "The regular expression matching a sub- or superscript.")
4944 (defvar org-match-substring-with-braces-regexp
4945 (concat
4946 "\\([^\\]\\)\\([_^]\\)\\("
4947 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
4948 "\\)")
4949 "The regular expression matching a sub- or superscript, forcing braces.")
4951 (defun org-make-link-regexps ()
4952 "Update the link regular expressions.
4953 This should be called after the variable `org-link-types' has changed."
4954 (setq org-link-types-re
4955 (concat
4956 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
4957 org-link-re-with-space
4958 (concat
4959 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4960 "\\([^" org-non-link-chars " ]"
4961 "[^" org-non-link-chars "]*"
4962 "[^" org-non-link-chars " ]\\)>?")
4963 org-link-re-with-space2
4964 (concat
4965 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4966 "\\([^" org-non-link-chars " ]"
4967 "[^\t\n\r]*"
4968 "[^" org-non-link-chars " ]\\)>?")
4969 org-link-re-with-space3
4970 (concat
4971 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4972 "\\([^" org-non-link-chars " ]"
4973 "[^\t\n\r]*\\)")
4974 org-angle-link-re
4975 (concat
4976 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4977 "\\([^" org-non-link-chars " ]"
4978 "[^" org-non-link-chars "]*"
4979 "\\)>")
4980 org-plain-link-re
4981 (concat
4982 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4983 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
4984 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
4985 org-bracket-link-regexp
4986 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
4987 org-bracket-link-analytic-regexp
4988 (concat
4989 "\\[\\["
4990 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
4991 "\\([^]]+\\)"
4992 "\\]"
4993 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4994 "\\]")
4995 org-bracket-link-analytic-regexp++
4996 (concat
4997 "\\[\\["
4998 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
4999 "\\([^]]+\\)"
5000 "\\]"
5001 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5002 "\\]")
5003 org-any-link-re
5004 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5005 org-angle-link-re "\\)\\|\\("
5006 org-plain-link-re "\\)")))
5008 (org-make-link-regexps)
5010 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
5011 "Regular expression for fast time stamp matching.")
5012 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
5013 "Regular expression for fast time stamp matching.")
5014 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5015 "Regular expression matching time strings for analysis.
5016 This one does not require the space after the date, so it can be used
5017 on a string that terminates immediately after the date.")
5018 (defconst org-ts-regexp1 "\\(\\([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 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5021 "Regular expression matching time stamps, with groups.")
5022 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5023 "Regular expression matching time stamps (also [..]), with groups.")
5024 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5025 "Regular expression matching a time stamp range.")
5026 (defconst org-tr-regexp-both
5027 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5028 "Regular expression matching a time stamp range.")
5029 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5030 org-ts-regexp "\\)?")
5031 "Regular expression matching a time stamp or time stamp range.")
5032 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5033 org-ts-regexp-both "\\)?")
5034 "Regular expression matching a time stamp or time stamp range.
5035 The time stamps may be either active or inactive.")
5037 (defvar org-emph-face nil)
5039 (defun org-do-emphasis-faces (limit)
5040 "Run through the buffer and add overlays to links."
5041 (let (rtn a)
5042 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5043 (if (not (= (char-after (match-beginning 3))
5044 (char-after (match-beginning 4))))
5045 (progn
5046 (setq rtn t)
5047 (setq a (assoc (match-string 3) org-emphasis-alist))
5048 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5049 'face
5050 (nth 1 a))
5051 (and (nth 4 a)
5052 (org-remove-flyspell-overlays-in
5053 (match-beginning 0) (match-end 0)))
5054 (add-text-properties (match-beginning 2) (match-end 2)
5055 '(font-lock-multiline t org-emphasis t))
5056 (when org-hide-emphasis-markers
5057 (add-text-properties (match-end 4) (match-beginning 5)
5058 '(invisible org-link))
5059 (add-text-properties (match-beginning 3) (match-end 3)
5060 '(invisible org-link)))))
5061 (backward-char 1))
5062 rtn))
5064 (defun org-emphasize (&optional char)
5065 "Insert or change an emphasis, i.e. a font like bold or italic.
5066 If there is an active region, change that region to a new emphasis.
5067 If there is no region, just insert the marker characters and position
5068 the cursor between them.
5069 CHAR should be either the marker character, or the first character of the
5070 HTML tag associated with that emphasis. If CHAR is a space, the means
5071 to remove the emphasis of the selected region.
5072 If char is not given (for example in an interactive call) it
5073 will be prompted for."
5074 (interactive)
5075 (let ((eal org-emphasis-alist) e det
5076 (erc org-emphasis-regexp-components)
5077 (prompt "")
5078 (string "") beg end move tag c s)
5079 (if (org-region-active-p)
5080 (setq beg (region-beginning) end (region-end)
5081 string (buffer-substring beg end))
5082 (setq move t))
5084 (while (setq e (pop eal))
5085 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5086 c (aref tag 0))
5087 (push (cons c (string-to-char (car e))) det)
5088 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5089 (substring tag 1)))))
5090 (setq det (nreverse det))
5091 (unless char
5092 (message "%s" (concat "Emphasis marker or tag:" prompt))
5093 (setq char (read-char-exclusive)))
5094 (setq char (or (cdr (assoc char det)) char))
5095 (if (equal char ?\ )
5096 (setq s "" move nil)
5097 (unless (assoc (char-to-string char) org-emphasis-alist)
5098 (error "No such emphasis marker: \"%c\"" char))
5099 (setq s (char-to-string char)))
5100 (while (and (> (length string) 1)
5101 (equal (substring string 0 1) (substring string -1))
5102 (assoc (substring string 0 1) org-emphasis-alist))
5103 (setq string (substring string 1 -1)))
5104 (setq string (concat s string s))
5105 (if beg (delete-region beg end))
5106 (unless (or (bolp)
5107 (string-match (concat "[" (nth 0 erc) "\n]")
5108 (char-to-string (char-before (point)))))
5109 (insert " "))
5110 (unless (or (eobp)
5111 (string-match (concat "[" (nth 1 erc) "\n]")
5112 (char-to-string (char-after (point)))))
5113 (insert " ") (backward-char 1))
5114 (insert string)
5115 (and move (backward-char 1))))
5117 (defconst org-nonsticky-props
5118 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
5120 (defsubst org-rear-nonsticky-at (pos)
5121 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5123 (defun org-activate-plain-links (limit)
5124 "Run through the buffer and add overlays to links."
5125 (catch 'exit
5126 (let (f)
5127 (if (re-search-forward org-plain-link-re limit t)
5128 (progn
5129 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5130 (setq f (get-text-property (match-beginning 0) 'face))
5131 (if (or (eq f 'org-tag)
5132 (and (listp f) (memq 'org-tag f)))
5134 (add-text-properties (match-beginning 0) (match-end 0)
5135 (list 'mouse-face 'highlight
5136 'face 'org-link
5137 'keymap org-mouse-map))
5138 (org-rear-nonsticky-at (match-end 0)))
5139 t)))))
5141 (defun org-activate-code (limit)
5142 (if (re-search-forward "^[ \t]*\\(: .*\n?\\)" limit t)
5143 (progn
5144 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5145 (remove-text-properties (match-beginning 0) (match-end 0)
5146 '(display t invisible t intangible t))
5147 t)))
5149 (defcustom org-src-fontify-natively nil
5150 "When non-nil, fontify code in code blocks."
5151 :type 'boolean
5152 :group 'org-appearance
5153 :group 'org-babel)
5155 (defun org-fontify-meta-lines-and-blocks (limit)
5156 "Fontify #+ lines and blocks, in the correct ways."
5157 (let ((case-fold-search t))
5158 (if (re-search-forward
5159 "^\\([ \t]*#\\+\\(\\([a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5160 limit t)
5161 (let ((beg (match-beginning 0))
5162 (block-start (match-end 0))
5163 (block-end nil)
5164 (lang (match-string 7))
5165 (beg1 (line-beginning-position 2))
5166 (dc1 (downcase (match-string 2)))
5167 (dc3 (downcase (match-string 3)))
5168 end end1 quoting block-type)
5169 (cond
5170 ((member dc1 '("html:" "ascii:" "latex:" "docbook:"))
5171 ;; a single line of backend-specific content
5172 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5173 (remove-text-properties (match-beginning 0) (match-end 0)
5174 '(display t invisible t intangible t))
5175 (add-text-properties (match-beginning 1) (match-end 3)
5176 '(font-lock-fontified t face org-meta-line))
5177 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5178 '(font-lock-fontified t face org-block))
5179 ; for backend-specific code
5181 ((and (match-end 4) (equal dc3 "begin"))
5182 ;; Truly a block
5183 (setq block-type (downcase (match-string 5))
5184 quoting (member block-type org-protecting-blocks))
5185 (when (re-search-forward
5186 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5187 nil t) ;; on purpose, we look further than LIMIT
5188 (setq end (match-end 0) end1 (1- (match-beginning 0)))
5189 (setq block-end (match-beginning 0))
5190 (when quoting
5191 (remove-text-properties beg end
5192 '(display t invisible t intangible t)))
5193 (add-text-properties
5194 beg end
5195 '(font-lock-fontified t font-lock-multiline t))
5196 (add-text-properties beg beg1 '(face org-meta-line))
5197 (add-text-properties end1 (+ end 1) '(face org-meta-line))
5198 ; for end_src
5199 (cond
5200 ((and lang org-src-fontify-natively)
5201 (org-src-font-lock-fontify-block lang block-start block-end)
5202 (overlay-put (make-overlay beg1 block-end)
5203 'face 'org-block-background))
5204 (quoting
5205 (add-text-properties beg1 (+ end1 1) '(face org-block)))
5206 ; end of source block
5207 ((not org-fontify-quote-and-verse-blocks))
5208 ((string= block-type "quote")
5209 (add-text-properties beg1 (1+ end1) '(face org-quote)))
5210 ((string= block-type "verse")
5211 (add-text-properties beg1 (1+ end1) '(face org-verse))))
5212 (add-text-properties beg beg1 '(face org-block-begin-line))
5213 (add-text-properties (1+ end) (1+ end1) '(face org-block-end-line))
5215 ((member dc1 '("title:" "author:" "email:" "date:"))
5216 (add-text-properties
5217 beg (match-end 3)
5218 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5219 '(font-lock-fontified t invisible t)
5220 '(font-lock-fontified t face org-document-info-keyword)))
5221 (add-text-properties
5222 (match-beginning 6) (match-end 6)
5223 (if (string-equal dc1 "title:")
5224 '(font-lock-fontified t face org-document-title)
5225 '(font-lock-fontified t face org-document-info))))
5226 ((not (member (char-after beg) '(?\ ?\t)))
5227 ;; just any other in-buffer setting, but not indented
5228 (add-text-properties
5229 beg (1+ (match-end 0))
5230 '(font-lock-fontified t face org-meta-line))
5232 ((or (member dc1 '("begin:" "end:" "caption:" "label:"
5233 "orgtbl:" "tblfm:" "tblname:" "result:"
5234 "results:" "source:" "srcname:" "call:"))
5235 (and (match-end 4) (equal dc3 "attr")))
5236 (add-text-properties
5237 beg (match-end 0)
5238 '(font-lock-fontified t face org-meta-line))
5240 ((member dc3 '(" " ""))
5241 (add-text-properties
5242 beg (match-end 0)
5243 '(font-lock-fontified t face font-lock-comment-face)))
5244 (t nil))))))
5246 (defun org-activate-angle-links (limit)
5247 "Run through the buffer and add overlays to links."
5248 (if (re-search-forward org-angle-link-re limit t)
5249 (progn
5250 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5251 (add-text-properties (match-beginning 0) (match-end 0)
5252 (list 'mouse-face 'highlight
5253 'keymap org-mouse-map))
5254 (org-rear-nonsticky-at (match-end 0))
5255 t)))
5257 (defun org-activate-footnote-links (limit)
5258 "Run through the buffer and add overlays to links."
5259 (if (re-search-forward "\\(^\\|[^][]\\)\\(\\[\\([0-9]+\\]\\|fn:[^ \t\r\n:]+?[]:]\\)\\)"
5260 limit t)
5261 (progn
5262 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5263 (add-text-properties (match-beginning 2) (match-end 2)
5264 (list 'mouse-face 'highlight
5265 'keymap org-mouse-map
5266 'help-echo
5267 (if (= (point-at-bol) (match-beginning 2))
5268 "Footnote definition"
5269 "Footnote reference")
5271 (org-rear-nonsticky-at (match-end 2))
5272 t)))
5274 (defun org-activate-bracket-links (limit)
5275 "Run through the buffer and add overlays to bracketed links."
5276 (if (re-search-forward org-bracket-link-regexp limit t)
5277 (let* ((help (concat "LINK: "
5278 (org-match-string-no-properties 1)))
5279 ;; FIXME: above we should remove the escapes.
5280 ;; but that requires another match, protecting match data,
5281 ;; a lot of overhead for font-lock.
5282 (ip (org-maybe-intangible
5283 (list 'invisible 'org-link
5284 'keymap org-mouse-map 'mouse-face 'highlight
5285 'font-lock-multiline t 'help-echo help)))
5286 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5287 'font-lock-multiline t 'help-echo help)))
5288 ;; We need to remove the invisible property here. Table narrowing
5289 ;; may have made some of this invisible.
5290 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5291 (remove-text-properties (match-beginning 0) (match-end 0)
5292 '(invisible nil))
5293 (if (match-end 3)
5294 (progn
5295 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5296 (org-rear-nonsticky-at (match-beginning 3))
5297 (add-text-properties (match-beginning 3) (match-end 3) vp)
5298 (org-rear-nonsticky-at (match-end 3))
5299 (add-text-properties (match-end 3) (match-end 0) ip)
5300 (org-rear-nonsticky-at (match-end 0)))
5301 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5302 (org-rear-nonsticky-at (match-beginning 1))
5303 (add-text-properties (match-beginning 1) (match-end 1) vp)
5304 (org-rear-nonsticky-at (match-end 1))
5305 (add-text-properties (match-end 1) (match-end 0) ip)
5306 (org-rear-nonsticky-at (match-end 0)))
5307 t)))
5309 (defun org-activate-dates (limit)
5310 "Run through the buffer and add overlays to dates."
5311 (if (re-search-forward org-tsr-regexp-both limit t)
5312 (progn
5313 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5314 (add-text-properties (match-beginning 0) (match-end 0)
5315 (list 'mouse-face 'highlight
5316 'keymap org-mouse-map))
5317 (org-rear-nonsticky-at (match-end 0))
5318 (when org-display-custom-times
5319 (if (match-end 3)
5320 (org-display-custom-time (match-beginning 3) (match-end 3)))
5321 (org-display-custom-time (match-beginning 1) (match-end 1)))
5322 t)))
5324 (defvar org-target-link-regexp nil
5325 "Regular expression matching radio targets in plain text.")
5326 (make-variable-buffer-local 'org-target-link-regexp)
5327 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5328 "Regular expression matching a link target.")
5329 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5330 "Regular expression matching a radio target.")
5331 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5332 "Regular expression matching any target.")
5334 (defun org-activate-target-links (limit)
5335 "Run through the buffer and add overlays to target matches."
5336 (when org-target-link-regexp
5337 (let ((case-fold-search t))
5338 (if (re-search-forward org-target-link-regexp limit t)
5339 (progn
5340 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5341 (add-text-properties (match-beginning 0) (match-end 0)
5342 (list 'mouse-face 'highlight
5343 'keymap org-mouse-map
5344 'help-echo "Radio target link"
5345 'org-linked-text t))
5346 (org-rear-nonsticky-at (match-end 0))
5347 t)))))
5349 (defun org-update-radio-target-regexp ()
5350 "Find all radio targets in this file and update the regular expression."
5351 (interactive)
5352 (when (memq 'radio org-activate-links)
5353 (setq org-target-link-regexp
5354 (org-make-target-link-regexp (org-all-targets 'radio)))
5355 (org-restart-font-lock)))
5357 (defun org-hide-wide-columns (limit)
5358 (let (s e)
5359 (setq s (text-property-any (point) (or limit (point-max))
5360 'org-cwidth t))
5361 (when s
5362 (setq e (next-single-property-change s 'org-cwidth))
5363 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5364 (goto-char e)
5365 t)))
5367 (defvar org-latex-and-specials-regexp nil
5368 "Regular expression for highlighting export special stuff.")
5369 (defvar org-match-substring-regexp)
5370 (defvar org-match-substring-with-braces-regexp)
5372 ;; This should be with the exporter code, but we also use if for font-locking
5373 (defconst org-export-html-special-string-regexps
5374 '(("\\\\-" . "&shy;")
5375 ("---\\([^-]\\)" . "&mdash;\\1")
5376 ("--\\([^-]\\)" . "&ndash;\\1")
5377 ("\\.\\.\\." . "&hellip;"))
5378 "Regular expressions for special string conversion.")
5381 (defun org-compute-latex-and-specials-regexp ()
5382 "Compute regular expression for stuff treated specially by exporters."
5383 (if (not org-highlight-latex-fragments-and-specials)
5384 (org-set-local 'org-latex-and-specials-regexp nil)
5385 (require 'org-exp)
5386 (let*
5387 ((matchers (plist-get org-format-latex-options :matchers))
5388 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5389 org-latex-regexps)))
5390 (org-export-allow-BIND nil)
5391 (options (org-combine-plists (org-default-export-plist)
5392 (org-infile-export-plist)))
5393 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5394 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5395 (org-export-with-TeX-macros (plist-get options :TeX-macros))
5396 (org-export-html-expand (plist-get options :expand-quoted-html))
5397 (org-export-with-special-strings (plist-get options :special-strings))
5398 (re-sub
5399 (cond
5400 ((equal org-export-with-sub-superscripts '{})
5401 (list org-match-substring-with-braces-regexp))
5402 (org-export-with-sub-superscripts
5403 (list org-match-substring-regexp))
5404 (t nil)))
5405 (re-latex
5406 (if org-export-with-LaTeX-fragments
5407 (mapcar (lambda (x) (nth 1 x)) latexs)))
5408 (re-macros
5409 (if org-export-with-TeX-macros
5410 (list (concat "\\\\"
5411 (regexp-opt
5412 (append
5414 (delq nil
5415 (mapcar 'car-safe
5416 (append org-entities-user
5417 org-entities)))
5418 (if (boundp 'org-latex-entities)
5419 (mapcar (lambda (x)
5420 (or (car-safe x) x))
5421 org-latex-entities)
5422 nil))
5423 'words))) ; FIXME
5425 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5426 (re-special (if org-export-with-special-strings
5427 (mapcar (lambda (x) (car x))
5428 org-export-html-special-string-regexps)))
5429 (re-rest
5430 (delq nil
5431 (list
5432 (if org-export-html-expand "@<[^>\n]+>")
5433 ))))
5434 (org-set-local
5435 'org-latex-and-specials-regexp
5436 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5437 re-rest) "\\|")))))
5439 (defun org-do-latex-and-special-faces (limit)
5440 "Run through the buffer and add overlays to links."
5441 (when org-latex-and-specials-regexp
5442 (let (rtn d)
5443 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5444 limit t))
5445 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5446 'face))
5447 '(org-code org-verbatim underline)))
5448 (progn
5449 (setq rtn t
5450 d (cond ((member (char-after (1+ (match-beginning 0)))
5451 '(?_ ?^)) 1)
5452 (t 0)))
5453 (font-lock-prepend-text-property
5454 (+ d (match-beginning 0)) (match-end 0)
5455 'face 'org-latex-and-export-specials)
5456 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5457 '(font-lock-multiline t)))))
5458 rtn)))
5460 (defun org-restart-font-lock ()
5461 "Restart `font-lock-mode', to force refontification."
5462 (when (and (boundp 'font-lock-mode) font-lock-mode)
5463 (font-lock-mode -1)
5464 (font-lock-mode 1)))
5466 (defun org-all-targets (&optional radio)
5467 "Return a list of all targets in this file.
5468 With optional argument RADIO, only find radio targets."
5469 (let ((re (if radio org-radio-target-regexp org-target-regexp))
5470 rtn)
5471 (save-excursion
5472 (goto-char (point-min))
5473 (while (re-search-forward re nil t)
5474 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
5475 rtn)))
5477 (defun org-make-target-link-regexp (targets)
5478 "Make regular expression matching all strings in TARGETS.
5479 The regular expression finds the targets also if there is a line break
5480 between words."
5481 (and targets
5482 (concat
5483 "\\<\\("
5484 (mapconcat
5485 (lambda (x)
5486 (setq x (regexp-quote x))
5487 (while (string-match " +" x)
5488 (setq x (replace-match "\\s-+" t t x)))
5490 targets
5491 "\\|")
5492 "\\)\\>")))
5494 (defun org-activate-tags (limit)
5495 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
5496 (progn
5497 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5498 (add-text-properties (match-beginning 1) (match-end 1)
5499 (list 'mouse-face 'highlight
5500 'keymap org-mouse-map))
5501 (org-rear-nonsticky-at (match-end 1))
5502 t)))
5504 (defun org-outline-level ()
5505 "Compute the outline level of the heading at point.
5506 This function assumes that the cursor is at the beginning of a line matched
5507 by `outline-regexp'. Otherwise it returns garbage.
5508 If this is called at a normal headline, the level is the number of stars.
5509 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
5510 (save-excursion
5511 (looking-at outline-regexp)
5512 (1- (- (match-end 0) (match-beginning 0)))))
5514 (defvar org-font-lock-keywords nil)
5516 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
5517 "Regular expression matching a property line.")
5519 (defvar org-font-lock-hook nil
5520 "Functions to be called for special font lock stuff.")
5522 (defvar org-font-lock-set-keywords-hook nil
5523 "Functions that can manipulate `org-font-lock-extra-keywords'.
5524 This is calles after `org-font-lock-extra-keywords' is defined, but before
5525 it is installed to be used by font lock. This can be useful if something
5526 needs to be inserted at a specific position in the font-lock sequence.")
5528 (defun org-font-lock-hook (limit)
5529 (run-hook-with-args 'org-font-lock-hook limit))
5531 (defun org-set-font-lock-defaults ()
5532 (let* ((em org-fontify-emphasized-text)
5533 (lk org-activate-links)
5534 (org-font-lock-extra-keywords
5535 (list
5536 ;; Call the hook
5537 '(org-font-lock-hook)
5538 ;; Headlines
5539 `(,(if org-fontify-whole-heading-line
5540 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
5541 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
5542 (1 (org-get-level-face 1))
5543 (2 (org-get-level-face 2))
5544 (3 (org-get-level-face 3)))
5545 ;; Table lines
5546 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5547 (1 'org-table t))
5548 ;; Table internals
5549 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5550 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5551 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5552 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
5553 ;; Drawers
5554 (list org-drawer-regexp '(0 'org-special-keyword t))
5555 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5556 ;; Properties
5557 (list org-property-re
5558 '(1 'org-special-keyword t)
5559 '(3 'org-property-value t))
5560 ;; Links
5561 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5562 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5563 (if (memq 'plain lk) '(org-activate-plain-links))
5564 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5565 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5566 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5567 (if (memq 'footnote lk) '(org-activate-footnote-links
5568 (2 'org-footnote t)))
5569 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5570 '(org-hide-wide-columns (0 nil append))
5571 ;; TODO lines
5572 (list (concat "^\\*+[ \t]+" org-todo-regexp "\\([ \t]\\|$\\)")
5573 '(1 (org-get-todo-face 1) t))
5574 ;; DONE
5575 (if org-fontify-done-headline
5576 (list (concat "^[*]+ +\\<\\("
5577 (mapconcat 'regexp-quote org-done-keywords "\\|")
5578 "\\)\\(.*\\)")
5579 '(2 'org-headline-done t))
5580 nil)
5581 ;; Priorities
5582 '(org-font-lock-add-priority-faces)
5583 ;; Tags
5584 '(org-font-lock-add-tag-faces)
5585 ;; Special keywords
5586 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5587 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5588 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5589 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5590 ;; Emphasis
5591 (if em
5592 (if (featurep 'xemacs)
5593 '(org-do-emphasis-faces (0 nil append))
5594 '(org-do-emphasis-faces)))
5595 ;; Checkboxes
5596 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
5597 1 'org-checkbox prepend)
5598 (if (cdr (assq 'checkbox org-list-automatic-rules))
5599 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5600 (0 (org-get-checkbox-statistics-face) t)))
5601 ;; Description list items
5602 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\)[ \t]+\\(.*? ::\\)"
5603 2 'bold prepend)
5604 ;; ARCHIVEd headings
5605 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
5606 '(1 'org-archived prepend))
5607 ;; Specials
5608 '(org-do-latex-and-special-faces)
5609 '(org-fontify-entities)
5610 '(org-raise-scripts)
5611 ;; Code
5612 '(org-activate-code (1 'org-code t))
5613 ;; COMMENT
5614 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
5615 "\\|" org-quote-string "\\)\\>")
5616 '(1 'org-special-keyword t))
5617 '("^#.*" (0 'font-lock-comment-face t))
5618 ;; Blocks and meta lines
5619 '(org-fontify-meta-lines-and-blocks)
5621 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5622 (run-hooks 'org-font-lock-set-keywords-hook)
5623 ;; Now set the full font-lock-keywords
5624 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5625 (org-set-local 'font-lock-defaults
5626 '(org-font-lock-keywords t nil nil backward-paragraph))
5627 (kill-local-variable 'font-lock-keywords) nil))
5629 (defun org-toggle-pretty-entities ()
5630 "Toggle the composition display of entities as UTF8 characters."
5631 (interactive)
5632 (org-set-local 'org-pretty-entities (not org-pretty-entities))
5633 (org-restart-font-lock)
5634 (if org-pretty-entities
5635 (message "Entities are displayed as UTF8 characers")
5636 (save-restriction
5637 (widen)
5638 (org-decompose-region (point-min) (point-max))
5639 (message "Entities are displayed plain"))))
5641 (defun org-fontify-entities (limit)
5642 "Find an entity to fontify."
5643 (let (ee)
5644 (when org-pretty-entities
5645 (catch 'match
5646 (while (re-search-forward
5647 "\\\\\\([a-zA-Z][a-zA-Z0-9]*\\)\\($\\|[^[:alnum:]\n]\\)"
5648 limit t)
5649 (if (and (not (org-in-indented-comment-line))
5650 (setq ee (org-entity-get (match-string 1)))
5651 (= (length (nth 6 ee)) 1))
5652 (progn
5653 (add-text-properties
5654 (match-beginning 0) (match-end 1)
5655 (list 'font-lock-fontified t))
5656 (compose-region (match-beginning 0) (match-end 1)
5657 (nth 6 ee) nil)
5658 (backward-char 1)
5659 (throw 'match t))))
5660 nil))))
5662 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
5663 "Fontify string S like in Org-mode."
5664 (with-temp-buffer
5665 (insert s)
5666 (let ((org-odd-levels-only odd-levels))
5667 (org-mode)
5668 (font-lock-fontify-buffer)
5669 (buffer-string))))
5671 (defvar org-m nil)
5672 (defvar org-l nil)
5673 (defvar org-f nil)
5674 (defun org-get-level-face (n)
5675 "Get the right face for match N in font-lock matching of headlines."
5676 (setq org-l (- (match-end 2) (match-beginning 1) 1))
5677 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
5678 (if org-cycle-level-faces
5679 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
5680 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
5681 (cond
5682 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
5683 ((eq n 2) org-f)
5684 (t (if org-level-color-stars-only nil org-f))))
5687 (defun org-get-todo-face (kwd)
5688 "Get the right face for a TODO keyword KWD.
5689 If KWD is a number, get the corresponding match group."
5690 (if (numberp kwd) (setq kwd (match-string kwd)))
5691 (or (org-face-from-face-or-color
5692 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
5693 (and (member kwd org-done-keywords) 'org-done)
5694 'org-todo))
5696 (defun org-face-from-face-or-color (context inherit face-or-color)
5697 "Create a face list that inherits INHERIT, but sets the foreground color.
5698 When FACE-OR-COLOR is not a string, just return it."
5699 (if (stringp face-or-color)
5700 (list :inherit inherit
5701 (cdr (assoc context org-faces-easy-properties))
5702 face-or-color)
5703 face-or-color))
5705 (defun org-font-lock-add-tag-faces (limit)
5706 "Add the special tag faces."
5707 (when (and org-tag-faces org-tags-special-faces-re)
5708 (while (re-search-forward org-tags-special-faces-re limit t)
5709 (add-text-properties (match-beginning 1) (match-end 1)
5710 (list 'face (org-get-tag-face 1)
5711 'font-lock-fontified t))
5712 (backward-char 1))))
5714 (defun org-font-lock-add-priority-faces (limit)
5715 "Add the special priority faces."
5716 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
5717 (add-text-properties
5718 (match-beginning 0) (match-end 0)
5719 (list 'face (or (org-face-from-face-or-color
5720 'priority 'org-special-keyword
5721 (cdr (assoc (char-after (match-beginning 1))
5722 org-priority-faces)))
5723 'org-special-keyword)
5724 'font-lock-fontified t))))
5726 (defun org-get-tag-face (kwd)
5727 "Get the right face for a TODO keyword KWD.
5728 If KWD is a number, get the corresponding match group."
5729 (if (numberp kwd) (setq kwd (match-string kwd)))
5730 (or (org-face-from-face-or-color
5731 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
5732 'org-tag))
5734 (defun org-unfontify-region (beg end &optional maybe_loudly)
5735 "Remove fontification and activation overlays from links."
5736 (font-lock-default-unfontify-region beg end)
5737 (let* ((buffer-undo-list t)
5738 (inhibit-read-only t) (inhibit-point-motion-hooks t)
5739 (inhibit-modification-hooks t)
5740 deactivate-mark buffer-file-name buffer-file-truename)
5741 (org-decompose-region beg end)
5742 (remove-text-properties
5743 beg end
5744 (if org-indent-mode
5745 ;; also remove line-prefix and wrap-prefix properties
5746 '(mouse-face t keymap t org-linked-text t
5747 invisible t intangible t
5748 line-prefix t wrap-prefix t
5749 org-no-flyspell t org-emphasis t)
5750 '(mouse-face t keymap t org-linked-text t
5751 invisible t intangible t
5752 org-no-flyspell t org-emphasis t)))
5753 (org-remove-font-lock-display-properties beg end)))
5755 (defconst org-script-display '(((raise -0.3) (height 0.7))
5756 ((raise 0.3) (height 0.7))
5757 ((raise -0.5))
5758 ((raise 0.5)))
5759 "Display properties for showing superscripts and subscripts.")
5761 (defun org-remove-font-lock-display-properties (beg end)
5762 "Remove specific display properties that have been added by font lock.
5763 The will remove the raise properties that are used to show superscripts
5764 and subscripts."
5765 (let (next prop)
5766 (while (< beg end)
5767 (setq next (next-single-property-change beg 'display nil end)
5768 prop (get-text-property beg 'display))
5769 (if (member prop org-script-display)
5770 (put-text-property beg next 'display nil))
5771 (setq beg next))))
5773 (defun org-raise-scripts (limit)
5774 "Add raise properties to sub/superscripts."
5775 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
5776 (if (re-search-forward
5777 (if (eq org-use-sub-superscripts t)
5778 org-match-substring-regexp
5779 org-match-substring-with-braces-regexp)
5780 limit t)
5781 (let* ((pos (point)) table-p comment-p
5782 (mpos (match-beginning 3))
5783 (emph-p (get-text-property mpos 'org-emphasis))
5784 (link-p (get-text-property mpos 'mouse-face))
5785 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
5786 (goto-char (point-at-bol))
5787 (setq table-p (org-looking-at-p org-table-dataline-regexp)
5788 comment-p (org-looking-at-p "[ \t]*#"))
5789 (goto-char pos)
5790 ;; FIXME: Should we go back one character here, for a_b^c
5791 ;; (goto-char (1- pos)) ;????????????????????
5792 (if (or comment-p emph-p link-p keyw-p)
5794 (put-text-property (match-beginning 3) (match-end 0)
5795 'display
5796 (if (equal (char-after (match-beginning 2)) ?^)
5797 (nth (if table-p 3 1) org-script-display)
5798 (nth (if table-p 2 0) org-script-display)))
5799 (add-text-properties (match-beginning 2) (match-end 2)
5800 (list 'invisible t
5801 'org-dwidth t 'org-dwidth-n 1))
5802 (if (and (eq (char-after (match-beginning 3)) ?{)
5803 (eq (char-before (match-end 3)) ?}))
5804 (progn
5805 (add-text-properties
5806 (match-beginning 3) (1+ (match-beginning 3))
5807 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
5808 (add-text-properties
5809 (1- (match-end 3)) (match-end 3)
5810 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
5811 t)))))
5813 ;;;; Visibility cycling, including org-goto and indirect buffer
5815 ;;; Cycling
5817 (defvar org-cycle-global-status nil)
5818 (make-variable-buffer-local 'org-cycle-global-status)
5819 (defvar org-cycle-subtree-status nil)
5820 (make-variable-buffer-local 'org-cycle-subtree-status)
5822 ;;;###autoload
5824 (defvar org-inlinetask-min-level)
5826 (defun org-cycle (&optional arg)
5827 "TAB-action and visibility cycling for Org-mode.
5829 This is the command invoked in Org-mode by the TAB key. Its main purpose
5830 is outline visibility cycling, but it also invokes other actions
5831 in special contexts.
5833 - When this function is called with a prefix argument, rotate the entire
5834 buffer through 3 states (global cycling)
5835 1. OVERVIEW: Show only top-level headlines.
5836 2. CONTENTS: Show all headlines of all levels, but no body text.
5837 3. SHOW ALL: Show everything.
5838 When called with two `C-u C-u' prefixes, switch to the startup visibility,
5839 determined by the variable `org-startup-folded', and by any VISIBILITY
5840 properties in the buffer.
5841 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
5842 including any drawers.
5844 - When inside a table, re-align the table and move to the next field.
5846 - When point is at the beginning of a headline, rotate the subtree started
5847 by this line through 3 different states (local cycling)
5848 1. FOLDED: Only the main headline is shown.
5849 2. CHILDREN: The main headline and the direct children are shown.
5850 From this state, you can move to one of the children
5851 and zoom in further.
5852 3. SUBTREE: Show the entire subtree, including body text.
5853 If there is no subtree, switch directly from CHILDREN to FOLDED.
5855 - When point is at the beginning of an empty headline and the variable
5856 `org-cycle-level-after-item/entry-creation' is set, cycle the level
5857 of the headline by demoting and promoting it to likely levels. This
5858 speeds up creation document structure by pressing TAB once or several
5859 times right after creating a new headline.
5861 - When there is a numeric prefix, go up to a heading with level ARG, do
5862 a `show-subtree' and return to the previous cursor position. If ARG
5863 is negative, go up that many levels.
5865 - When point is not at the beginning of a headline, execute the global
5866 binding for TAB, which is re-indenting the line. See the option
5867 `org-cycle-emulate-tab' for details.
5869 - Special case: if point is at the beginning of the buffer and there is
5870 no headline in line 1, this function will act as if called with prefix arg
5871 (C-u TAB, same as S-TAB) also when called without prefix arg.
5872 But only if also the variable `org-cycle-global-at-bob' is t."
5873 (interactive "P")
5874 (org-load-modules-maybe)
5875 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
5876 (and org-cycle-level-after-item/entry-creation
5877 (or (org-cycle-level)
5878 (org-cycle-item-indentation))))
5879 (let* ((limit-level
5880 (or org-cycle-max-level
5881 (and (boundp 'org-inlinetask-min-level)
5882 org-inlinetask-min-level
5883 (1- org-inlinetask-min-level))))
5884 (nstars (and limit-level
5885 (if org-odd-levels-only
5886 (and limit-level (1- (* limit-level 2)))
5887 limit-level)))
5888 (outline-regexp
5889 (if (not (org-mode-p))
5890 outline-regexp
5891 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
5892 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
5893 (not (looking-at outline-regexp))))
5894 (org-cycle-hook
5895 (if bob-special
5896 (delq 'org-optimize-window-after-visibility-change
5897 (copy-sequence org-cycle-hook))
5898 org-cycle-hook))
5899 (pos (point)))
5901 (if (or bob-special (equal arg '(4)))
5902 ;; special case: use global cycling
5903 (setq arg t))
5905 (cond
5907 ((equal arg '(16))
5908 (setq last-command 'dummy)
5909 (org-set-startup-visibility)
5910 (message "Startup visibility, plus VISIBILITY properties"))
5912 ((equal arg '(64))
5913 (show-all)
5914 (message "Entire buffer visible, including drawers"))
5916 ;; Table: enter it or move to the next field.
5917 ((org-at-table-p 'any)
5918 (if (org-at-table.el-p)
5919 (message "Use C-c ' to edit table.el tables")
5920 (if arg (org-table-edit-field t)
5921 (org-table-justify-field-maybe)
5922 (call-interactively 'org-table-next-field))))
5924 ((run-hook-with-args-until-success
5925 'org-tab-after-check-for-table-hook))
5927 ;; Global cycling: delegate to `org-cycle-internal-global'.
5928 ((eq arg t) (org-cycle-internal-global))
5930 ;; Drawers: delegate to `org-flag-drawer'.
5931 ((and org-drawers org-drawer-regexp
5932 (save-excursion
5933 (beginning-of-line 1)
5934 (looking-at org-drawer-regexp)))
5935 (org-flag-drawer ; toggle block visibility
5936 (not (get-char-property (match-end 0) 'invisible))))
5938 ;; Show-subtree, ARG levels up from here.
5939 ((integerp arg)
5940 (save-excursion
5941 (org-back-to-heading)
5942 (outline-up-heading (if (< arg 0) (- arg)
5943 (- (funcall outline-level) arg)))
5944 (org-show-subtree)))
5946 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
5947 ((and (featurep 'org-inlinetask)
5948 (org-inlinetask-at-task-p)
5949 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
5950 (org-inlinetask-toggle-visibility))
5952 ;; At an item/headline: delegate to `org-cycle-internal-local'.
5953 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
5954 (save-excursion (beginning-of-line 1)
5955 (looking-at outline-regexp)))
5956 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
5957 (org-cycle-internal-local))
5959 ;; From there: TAB emulation and template completion.
5960 (buffer-read-only (org-back-to-heading))
5962 ((run-hook-with-args-until-success
5963 'org-tab-after-check-for-cycling-hook))
5965 ((org-try-structure-completion))
5967 ((org-try-cdlatex-tab))
5969 ((run-hook-with-args-until-success
5970 'org-tab-before-tab-emulation-hook))
5972 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
5973 (or (not (bolp))
5974 (not (looking-at outline-regexp))))
5975 (call-interactively (global-key-binding "\t")))
5977 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
5978 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
5979 (or (and (eq org-cycle-emulate-tab 'white)
5980 (= (match-end 0) (point-at-eol)))
5981 (and (eq org-cycle-emulate-tab 'whitestart)
5982 (>= (match-end 0) pos))))
5984 (eq org-cycle-emulate-tab t))
5985 (call-interactively (global-key-binding "\t")))
5987 (t (save-excursion
5988 (org-back-to-heading)
5989 (org-cycle)))))))
5991 (defun org-cycle-internal-global ()
5992 "Do the global cycling action."
5993 (cond
5994 ((and (eq last-command this-command)
5995 (eq org-cycle-global-status 'overview))
5996 ;; We just created the overview - now do table of contents
5997 ;; This can be slow in very large buffers, so indicate action
5998 (run-hook-with-args 'org-pre-cycle-hook 'contents)
5999 (message "CONTENTS...")
6000 (org-content)
6001 (message "CONTENTS...done")
6002 (setq org-cycle-global-status 'contents)
6003 (run-hook-with-args 'org-cycle-hook 'contents))
6005 ((and (eq last-command this-command)
6006 (eq org-cycle-global-status 'contents))
6007 ;; We just showed the table of contents - now show everything
6008 (run-hook-with-args 'org-pre-cycle-hook 'all)
6009 (show-all)
6010 (message "SHOW ALL")
6011 (setq org-cycle-global-status 'all)
6012 (run-hook-with-args 'org-cycle-hook 'all))
6015 ;; Default action: go to overview
6016 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6017 (org-overview)
6018 (message "OVERVIEW")
6019 (setq org-cycle-global-status 'overview)
6020 (run-hook-with-args 'org-cycle-hook 'overview))))
6022 (defun org-cycle-internal-local ()
6023 "Do the local cycling action."
6024 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6025 ;; First, determine end of headline (EOH), end of subtree or item
6026 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6027 (save-excursion
6028 (if (org-at-item-p)
6029 (progn
6030 (beginning-of-line)
6031 (setq struct (org-list-struct))
6032 (setq eoh (point-at-eol))
6033 (setq eos (org-list-get-item-end-before-blank (point) struct))
6034 (setq has-children (org-list-has-child-p (point) struct)))
6035 (org-back-to-heading)
6036 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6037 (setq eos (save-excursion
6038 (org-end-of-subtree t)
6039 (unless (eobp)
6040 (skip-chars-forward " \t\n"))
6041 (if (eobp) (point) (1- (point)))))
6042 (setq has-children
6043 (or (save-excursion
6044 (let ((level (funcall outline-level)))
6045 (outline-next-heading)
6046 (and (org-at-heading-p t)
6047 (> (funcall outline-level) level))))
6048 (save-excursion
6049 (org-list-search-forward (org-item-beginning-re) eos t)))))
6050 ;; Determine end invisible part of buffer (EOL)
6051 (beginning-of-line 2)
6052 ;; XEmacs doesn't have `next-single-char-property-change'
6053 (if (featurep 'xemacs)
6054 (while (and (not (eobp)) ;; this is like `next-line'
6055 (get-char-property (1- (point)) 'invisible))
6056 (beginning-of-line 2))
6057 (while (and (not (eobp)) ;; this is like `next-line'
6058 (get-char-property (1- (point)) 'invisible))
6059 (goto-char (next-single-char-property-change (point) 'invisible))
6060 (and (eolp) (beginning-of-line 2))))
6061 (setq eol (point)))
6062 ;; Find out what to do next and set `this-command'
6063 (cond
6064 ((= eos eoh)
6065 ;; Nothing is hidden behind this heading
6066 (run-hook-with-args 'org-pre-cycle-hook 'empty)
6067 (message "EMPTY ENTRY")
6068 (setq org-cycle-subtree-status nil)
6069 (save-excursion
6070 (goto-char eos)
6071 (outline-next-heading)
6072 (if (outline-invisible-p) (org-flag-heading nil))))
6073 ((and (or (>= eol eos)
6074 (not (string-match "\\S-" (buffer-substring eol eos))))
6075 (or has-children
6076 (not (setq children-skipped
6077 org-cycle-skip-children-state-if-no-children))))
6078 ;; Entire subtree is hidden in one line: children view
6079 (run-hook-with-args 'org-pre-cycle-hook 'children)
6080 (if (org-at-item-p)
6081 (org-list-set-item-visibility (point-at-bol) struct 'children)
6082 (org-show-entry)
6083 (show-children)
6084 ;; Fold every list in subtree to top-level items.
6085 (when (eq org-cycle-include-plain-lists 'integrate)
6086 (save-excursion
6087 (org-back-to-heading)
6088 (while (org-list-search-forward (org-item-beginning-re) eos t)
6089 (beginning-of-line 1)
6090 (let* ((struct (org-list-struct))
6091 (prevs (org-list-prevs-alist struct))
6092 (end (org-list-get-bottom-point struct)))
6093 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6094 (org-list-get-all-items (point) struct prevs))
6095 (goto-char end))))))
6096 (message "CHILDREN")
6097 (save-excursion
6098 (goto-char eos)
6099 (outline-next-heading)
6100 (if (outline-invisible-p) (org-flag-heading nil)))
6101 (setq org-cycle-subtree-status 'children)
6102 (run-hook-with-args 'org-cycle-hook 'children))
6103 ((or children-skipped
6104 (and (eq last-command this-command)
6105 (eq org-cycle-subtree-status 'children)))
6106 ;; We just showed the children, or no children are there,
6107 ;; now show everything.
6108 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
6109 (outline-flag-region eoh eos nil)
6110 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6111 (setq org-cycle-subtree-status 'subtree)
6112 (run-hook-with-args 'org-cycle-hook 'subtree))
6114 ;; Default action: hide the subtree.
6115 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6116 (outline-flag-region eoh eos t)
6117 (message "FOLDED")
6118 (setq org-cycle-subtree-status 'folded)
6119 (run-hook-with-args 'org-cycle-hook 'folded)))))
6121 ;;;###autoload
6122 (defun org-global-cycle (&optional arg)
6123 "Cycle the global visibility. For details see `org-cycle'.
6124 With \\[universal-argument] prefix arg, switch to startup visibility.
6125 With a numeric prefix, show all headlines up to that level."
6126 (interactive "P")
6127 (let ((org-cycle-include-plain-lists
6128 (if (org-mode-p) org-cycle-include-plain-lists nil)))
6129 (cond
6130 ((integerp arg)
6131 (show-all)
6132 (hide-sublevels arg)
6133 (setq org-cycle-global-status 'contents))
6134 ((equal arg '(4))
6135 (org-set-startup-visibility)
6136 (message "Startup visibility, plus VISIBILITY properties."))
6138 (org-cycle '(4))))))
6140 (defun org-set-startup-visibility ()
6141 "Set the visibility required by startup options and properties."
6142 (cond
6143 ((eq org-startup-folded t)
6144 (org-cycle '(4)))
6145 ((eq org-startup-folded 'content)
6146 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6147 (org-cycle '(4)) (org-cycle '(4)))))
6148 (unless (eq org-startup-folded 'showeverything)
6149 (if org-hide-block-startup (org-hide-block-all))
6150 (org-set-visibility-according-to-property 'no-cleanup)
6151 (org-cycle-hide-archived-subtrees 'all)
6152 (org-cycle-hide-drawers 'all)
6153 (org-cycle-show-empty-lines t)))
6155 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6156 "Switch subtree visibilities according to :VISIBILITY: property."
6157 (interactive)
6158 (let (org-show-entry-below state)
6159 (save-excursion
6160 (goto-char (point-min))
6161 (while (re-search-forward
6162 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6163 nil t)
6164 (setq state (match-string 1))
6165 (save-excursion
6166 (org-back-to-heading t)
6167 (hide-subtree)
6168 (org-reveal)
6169 (cond
6170 ((equal state '("fold" "folded"))
6171 (hide-subtree))
6172 ((equal state "children")
6173 (org-show-hidden-entry)
6174 (show-children))
6175 ((equal state "content")
6176 (save-excursion
6177 (save-restriction
6178 (org-narrow-to-subtree)
6179 (org-content))))
6180 ((member state '("all" "showall"))
6181 (show-subtree)))))
6182 (unless no-cleanup
6183 (org-cycle-hide-archived-subtrees 'all)
6184 (org-cycle-hide-drawers 'all)
6185 (org-cycle-show-empty-lines 'all)))))
6187 (defun org-overview ()
6188 "Switch to overview mode, showing only top-level headlines.
6189 Really, this shows all headlines with level equal or greater than the level
6190 of the first headline in the buffer. This is important, because if the
6191 first headline is not level one, then (hide-sublevels 1) gives confusing
6192 results."
6193 (interactive)
6194 (let ((level (save-excursion
6195 (goto-char (point-min))
6196 (if (re-search-forward (concat "^" outline-regexp) nil t)
6197 (progn
6198 (goto-char (match-beginning 0))
6199 (funcall outline-level))))))
6200 (and level (hide-sublevels level))))
6202 (defun org-content (&optional arg)
6203 "Show all headlines in the buffer, like a table of contents.
6204 With numerical argument N, show content up to level N."
6205 (interactive "P")
6206 (save-excursion
6207 ;; Visit all headings and show their offspring
6208 (and (integerp arg) (org-overview))
6209 (goto-char (point-max))
6210 (catch 'exit
6211 (while (and (progn (condition-case nil
6212 (outline-previous-visible-heading 1)
6213 (error (goto-char (point-min))))
6215 (looking-at outline-regexp))
6216 (if (integerp arg)
6217 (show-children (1- arg))
6218 (show-branches))
6219 (if (bobp) (throw 'exit nil))))))
6222 (defun org-optimize-window-after-visibility-change (state)
6223 "Adjust the window after a change in outline visibility.
6224 This function is the default value of the hook `org-cycle-hook'."
6225 (when (get-buffer-window (current-buffer))
6226 (cond
6227 ((eq state 'content) nil)
6228 ((eq state 'all) nil)
6229 ((eq state 'folded) nil)
6230 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6231 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6233 (defun org-remove-empty-overlays-at (pos)
6234 "Remove outline overlays that do not contain non-white stuff."
6235 (mapc
6236 (lambda (o)
6237 (and (eq 'outline (overlay-get o 'invisible))
6238 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6239 (overlay-end o))))
6240 (delete-overlay o)))
6241 (overlays-at pos)))
6243 (defun org-clean-visibility-after-subtree-move ()
6244 "Fix visibility issues after moving a subtree."
6245 ;; First, find a reasonable region to look at:
6246 ;; Start two siblings above, end three below
6247 (let* ((beg (save-excursion
6248 (and (org-get-last-sibling)
6249 (org-get-last-sibling))
6250 (point)))
6251 (end (save-excursion
6252 (and (org-get-next-sibling)
6253 (org-get-next-sibling)
6254 (org-get-next-sibling))
6255 (if (org-at-heading-p)
6256 (point-at-eol)
6257 (point))))
6258 (level (looking-at "\\*+"))
6259 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6260 (save-excursion
6261 (save-restriction
6262 (narrow-to-region beg end)
6263 (when re
6264 ;; Properly fold already folded siblings
6265 (goto-char (point-min))
6266 (while (re-search-forward re nil t)
6267 (if (and (not (outline-invisible-p))
6268 (save-excursion
6269 (goto-char (point-at-eol)) (outline-invisible-p)))
6270 (hide-entry))))
6271 (org-cycle-show-empty-lines 'overview)
6272 (org-cycle-hide-drawers 'overview)))))
6274 (defun org-cycle-show-empty-lines (state)
6275 "Show empty lines above all visible headlines.
6276 The region to be covered depends on STATE when called through
6277 `org-cycle-hook'. Lisp program can use t for STATE to get the
6278 entire buffer covered. Note that an empty line is only shown if there
6279 are at least `org-cycle-separator-lines' empty lines before the headline."
6280 (when (not (= org-cycle-separator-lines 0))
6281 (save-excursion
6282 (let* ((n (abs org-cycle-separator-lines))
6283 (re (cond
6284 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6285 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6286 (t (let ((ns (number-to-string (- n 2))))
6287 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6288 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6289 beg end b e)
6290 (cond
6291 ((memq state '(overview contents t))
6292 (setq beg (point-min) end (point-max)))
6293 ((memq state '(children folded))
6294 (setq beg (point) end (progn (org-end-of-subtree t t)
6295 (beginning-of-line 2)
6296 (point)))))
6297 (when beg
6298 (goto-char beg)
6299 (while (re-search-forward re end t)
6300 (unless (get-char-property (match-end 1) 'invisible)
6301 (setq e (match-end 1))
6302 (if (< org-cycle-separator-lines 0)
6303 (setq b (save-excursion
6304 (goto-char (match-beginning 0))
6305 (org-back-over-empty-lines)
6306 (if (save-excursion
6307 (goto-char (max (point-min) (1- (point))))
6308 (org-on-heading-p))
6309 (1- (point))
6310 (point))))
6311 (setq b (match-beginning 1)))
6312 (outline-flag-region b e nil)))))))
6313 ;; Never hide empty lines at the end of the file.
6314 (save-excursion
6315 (goto-char (point-max))
6316 (outline-previous-heading)
6317 (outline-end-of-heading)
6318 (if (and (looking-at "[ \t\n]+")
6319 (= (match-end 0) (point-max)))
6320 (outline-flag-region (point) (match-end 0) nil))))
6322 (defun org-show-empty-lines-in-parent ()
6323 "Move to the parent and re-show empty lines before visible headlines."
6324 (save-excursion
6325 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6326 (org-cycle-show-empty-lines context))))
6328 (defun org-files-list ()
6329 "Return `org-agenda-files' list, plus all open org-mode files.
6330 This is useful for operations that need to scan all of a user's
6331 open and agenda-wise Org files."
6332 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6333 (dolist (buf (buffer-list))
6334 (with-current-buffer buf
6335 (if (and (org-mode-p) (buffer-file-name))
6336 (let ((file (expand-file-name (buffer-file-name))))
6337 (unless (member file files)
6338 (push file files))))))
6339 files))
6341 (defsubst org-entry-beginning-position ()
6342 "Return the beginning position of the current entry."
6343 (save-excursion (outline-back-to-heading t) (point)))
6345 (defsubst org-entry-end-position ()
6346 "Return the end position of the current entry."
6347 (save-excursion (outline-next-heading) (point)))
6349 (defun org-cycle-hide-drawers (state)
6350 "Re-hide all drawers after a visibility state change."
6351 (when (and (org-mode-p)
6352 (not (memq state '(overview folded contents))))
6353 (save-excursion
6354 (let* ((globalp (memq state '(contents all)))
6355 (beg (if globalp (point-min) (point)))
6356 (end (if globalp (point-max)
6357 (if (eq state 'children)
6358 (save-excursion (outline-next-heading) (point))
6359 (org-end-of-subtree t)))))
6360 (goto-char beg)
6361 (while (re-search-forward org-drawer-regexp end t)
6362 (org-flag-drawer t))))))
6364 (defun org-flag-drawer (flag)
6365 (save-excursion
6366 (beginning-of-line 1)
6367 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6368 (let ((b (match-end 0))
6369 (outline-regexp org-outline-regexp))
6370 (if (re-search-forward
6371 "^[ \t]*:END:"
6372 (save-excursion (outline-next-heading) (point)) t)
6373 (outline-flag-region b (point-at-eol) flag)
6374 (error ":END: line missing at position %s" b))))))
6376 (defun org-subtree-end-visible-p ()
6377 "Is the end of the current subtree visible?"
6378 (pos-visible-in-window-p
6379 (save-excursion (org-end-of-subtree t) (point))))
6381 (defun org-first-headline-recenter (&optional N)
6382 "Move cursor to the first headline and recenter the headline.
6383 Optional argument N means put the headline into the Nth line of the window."
6384 (goto-char (point-min))
6385 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
6386 (beginning-of-line)
6387 (recenter (prefix-numeric-value N))))
6389 ;;; Saving and restoring visibility
6391 (defun org-outline-overlay-data (&optional use-markers)
6392 "Return a list of the locations of all outline overlays.
6393 These are overlays with the `invisible' property value `outline'.
6394 The return value is a list of cons cells, with start and stop
6395 positions for each overlay.
6396 If USE-MARKERS is set, return the positions as markers."
6397 (let (beg end)
6398 (save-excursion
6399 (save-restriction
6400 (widen)
6401 (delq nil
6402 (mapcar (lambda (o)
6403 (when (eq (overlay-get o 'invisible) 'outline)
6404 (setq beg (overlay-start o)
6405 end (overlay-end o))
6406 (and beg end (> end beg)
6407 (if use-markers
6408 (cons (move-marker (make-marker) beg)
6409 (move-marker (make-marker) end))
6410 (cons beg end)))))
6411 (overlays-in (point-min) (point-max))))))))
6413 (defun org-set-outline-overlay-data (data)
6414 "Create visibility overlays for all positions in DATA.
6415 DATA should have been made by `org-outline-overlay-data'."
6416 (let (o)
6417 (save-excursion
6418 (save-restriction
6419 (widen)
6420 (show-all)
6421 (mapc (lambda (c)
6422 (setq o (make-overlay (car c) (cdr c)))
6423 (overlay-put o 'invisible 'outline))
6424 data)))))
6426 ;;; Folding of blocks
6428 (defconst org-block-regexp
6429 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
6430 "Regular expression for hiding blocks.")
6432 (defvar org-hide-block-overlays nil
6433 "Overlays hiding blocks.")
6434 (make-variable-buffer-local 'org-hide-block-overlays)
6436 (defun org-block-map (function &optional start end)
6437 "Call FUNCTION at the head of all source blocks in the current buffer.
6438 Optional arguments START and END can be used to limit the range."
6439 (let ((start (or start (point-min)))
6440 (end (or end (point-max))))
6441 (save-excursion
6442 (goto-char start)
6443 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
6444 (save-excursion
6445 (save-match-data
6446 (goto-char (match-beginning 0))
6447 (funcall function)))))))
6449 (defun org-hide-block-toggle-all ()
6450 "Toggle the visibility of all blocks in the current buffer."
6451 (org-block-map #'org-hide-block-toggle))
6453 (defun org-hide-block-all ()
6454 "Fold all blocks in the current buffer."
6455 (interactive)
6456 (org-show-block-all)
6457 (org-block-map #'org-hide-block-toggle-maybe))
6459 (defun org-show-block-all ()
6460 "Unfold all blocks in the current buffer."
6461 (interactive)
6462 (mapc 'delete-overlay org-hide-block-overlays)
6463 (setq org-hide-block-overlays nil))
6465 (defun org-hide-block-toggle-maybe ()
6466 "Toggle visibility of block at point."
6467 (interactive)
6468 (let ((case-fold-search t))
6469 (if (save-excursion
6470 (beginning-of-line 1)
6471 (looking-at org-block-regexp))
6472 (progn (org-hide-block-toggle)
6473 t) ;; to signal that we took action
6474 nil))) ;; to signal that we did not
6476 (defun org-hide-block-toggle (&optional force)
6477 "Toggle the visibility of the current block."
6478 (interactive)
6479 (save-excursion
6480 (beginning-of-line)
6481 (if (re-search-forward org-block-regexp nil t)
6482 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
6483 (end (match-end 0)) ;; end of entire body
6485 (if (memq t (mapcar (lambda (overlay)
6486 (eq (overlay-get overlay 'invisible)
6487 'org-hide-block))
6488 (overlays-at start)))
6489 (if (or (not force) (eq force 'off))
6490 (mapc (lambda (ov)
6491 (when (member ov org-hide-block-overlays)
6492 (setq org-hide-block-overlays
6493 (delq ov org-hide-block-overlays)))
6494 (when (eq (overlay-get ov 'invisible)
6495 'org-hide-block)
6496 (delete-overlay ov)))
6497 (overlays-at start)))
6498 (setq ov (make-overlay start end))
6499 (overlay-put ov 'invisible 'org-hide-block)
6500 ;; make the block accessible to isearch
6501 (overlay-put
6502 ov 'isearch-open-invisible
6503 (lambda (ov)
6504 (when (member ov org-hide-block-overlays)
6505 (setq org-hide-block-overlays
6506 (delq ov org-hide-block-overlays)))
6507 (when (eq (overlay-get ov 'invisible)
6508 'org-hide-block)
6509 (delete-overlay ov))))
6510 (push ov org-hide-block-overlays)))
6511 (error "Not looking at a source block"))))
6513 ;; org-tab-after-check-for-cycling-hook
6514 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
6515 ;; Remove overlays when changing major mode
6516 (add-hook 'org-mode-hook
6517 (lambda () (org-add-hook 'change-major-mode-hook
6518 'org-show-block-all 'append 'local)))
6520 ;;; Org-goto
6522 (defvar org-goto-window-configuration nil)
6523 (defvar org-goto-marker nil)
6524 (defvar org-goto-map
6525 (let ((map (make-sparse-keymap)))
6526 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
6527 (while (setq cmd (pop cmds))
6528 (substitute-key-definition cmd cmd map global-map)))
6529 (suppress-keymap map)
6530 (org-defkey map "\C-m" 'org-goto-ret)
6531 (org-defkey map [(return)] 'org-goto-ret)
6532 (org-defkey map [(left)] 'org-goto-left)
6533 (org-defkey map [(right)] 'org-goto-right)
6534 (org-defkey map [(control ?g)] 'org-goto-quit)
6535 (org-defkey map "\C-i" 'org-cycle)
6536 (org-defkey map [(tab)] 'org-cycle)
6537 (org-defkey map [(down)] 'outline-next-visible-heading)
6538 (org-defkey map [(up)] 'outline-previous-visible-heading)
6539 (if org-goto-auto-isearch
6540 (if (fboundp 'define-key-after)
6541 (define-key-after map [t] 'org-goto-local-auto-isearch)
6542 nil)
6543 (org-defkey map "q" 'org-goto-quit)
6544 (org-defkey map "n" 'outline-next-visible-heading)
6545 (org-defkey map "p" 'outline-previous-visible-heading)
6546 (org-defkey map "f" 'outline-forward-same-level)
6547 (org-defkey map "b" 'outline-backward-same-level)
6548 (org-defkey map "u" 'outline-up-heading))
6549 (org-defkey map "/" 'org-occur)
6550 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
6551 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
6552 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
6553 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
6554 (org-defkey map "\C-c\C-u" 'outline-up-heading)
6555 map))
6557 (defconst org-goto-help
6558 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
6559 RET=jump to location [Q]uit and return to previous location
6560 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
6562 (defvar org-goto-start-pos) ; dynamically scoped parameter
6564 ;; FIXME: Docstring does not mention both interfaces
6565 (defun org-goto (&optional alternative-interface)
6566 "Look up a different location in the current file, keeping current visibility.
6568 When you want look-up or go to a different location in a document, the
6569 fastest way is often to fold the entire buffer and then dive into the tree.
6570 This method has the disadvantage, that the previous location will be folded,
6571 which may not be what you want.
6573 This command works around this by showing a copy of the current buffer
6574 in an indirect buffer, in overview mode. You can dive into the tree in
6575 that copy, use org-occur and incremental search to find a location.
6576 When pressing RET or `Q', the command returns to the original buffer in
6577 which the visibility is still unchanged. After RET is will also jump to
6578 the location selected in the indirect buffer and expose the
6579 the headline hierarchy above."
6580 (interactive "P")
6581 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
6582 (org-refile-use-outline-path t)
6583 (org-refile-target-verify-function nil)
6584 (interface
6585 (if (not alternative-interface)
6586 org-goto-interface
6587 (if (eq org-goto-interface 'outline)
6588 'outline-path-completion
6589 'outline)))
6590 (org-goto-start-pos (point))
6591 (selected-point
6592 (if (eq interface 'outline)
6593 (car (org-get-location (current-buffer) org-goto-help))
6594 (let ((pa (org-refile-get-location "Goto")))
6595 (org-refile-check-position pa)
6596 (nth 3 pa)))))
6597 (if selected-point
6598 (progn
6599 (org-mark-ring-push org-goto-start-pos)
6600 (goto-char selected-point)
6601 (if (or (outline-invisible-p) (org-invisible-p2))
6602 (org-show-context 'org-goto)))
6603 (message "Quit"))))
6605 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
6606 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
6607 (defvar org-goto-local-auto-isearch-map) ; defined below
6609 (defun org-get-location (buf help)
6610 "Let the user select a location in the Org-mode buffer BUF.
6611 This function uses a recursive edit. It returns the selected position
6612 or nil."
6613 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
6614 (isearch-hide-immediately nil)
6615 (isearch-search-fun-function
6616 (lambda () 'org-goto-local-search-headings))
6617 (org-goto-selected-point org-goto-exit-command)
6618 (pop-up-frames nil)
6619 (special-display-buffer-names nil)
6620 (special-display-regexps nil)
6621 (special-display-function nil))
6622 (save-excursion
6623 (save-window-excursion
6624 (delete-other-windows)
6625 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
6626 (switch-to-buffer
6627 (condition-case nil
6628 (make-indirect-buffer (current-buffer) "*org-goto*")
6629 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
6630 (with-output-to-temp-buffer "*Help*"
6631 (princ help))
6632 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
6633 (setq buffer-read-only nil)
6634 (let ((org-startup-truncated t)
6635 (org-startup-folded nil)
6636 (org-startup-align-all-tables nil))
6637 (org-mode)
6638 (org-overview))
6639 (setq buffer-read-only t)
6640 (if (and (boundp 'org-goto-start-pos)
6641 (integer-or-marker-p org-goto-start-pos))
6642 (let ((org-show-hierarchy-above t)
6643 (org-show-siblings t)
6644 (org-show-following-heading t))
6645 (goto-char org-goto-start-pos)
6646 (and (outline-invisible-p) (org-show-context)))
6647 (goto-char (point-min)))
6648 (let (org-special-ctrl-a/e) (org-beginning-of-line))
6649 (message "Select location and press RET")
6650 (use-local-map org-goto-map)
6651 (recursive-edit)
6653 (kill-buffer "*org-goto*")
6654 (cons org-goto-selected-point org-goto-exit-command)))
6656 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
6657 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
6658 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
6659 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
6661 (defun org-goto-local-search-headings (string bound noerror)
6662 "Search and make sure that any matches are in headlines."
6663 (catch 'return
6664 (while (if isearch-forward
6665 (search-forward string bound noerror)
6666 (search-backward string bound noerror))
6667 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
6668 (and (member :headline context)
6669 (not (member :tags context))))
6670 (throw 'return (point))))))
6672 (defun org-goto-local-auto-isearch ()
6673 "Start isearch."
6674 (interactive)
6675 (goto-char (point-min))
6676 (let ((keys (this-command-keys)))
6677 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
6678 (isearch-mode t)
6679 (isearch-process-search-char (string-to-char keys)))))
6681 (defun org-goto-ret (&optional arg)
6682 "Finish `org-goto' by going to the new location."
6683 (interactive "P")
6684 (setq org-goto-selected-point (point)
6685 org-goto-exit-command 'return)
6686 (throw 'exit nil))
6688 (defun org-goto-left ()
6689 "Finish `org-goto' by going to the new location."
6690 (interactive)
6691 (if (org-on-heading-p)
6692 (progn
6693 (beginning-of-line 1)
6694 (setq org-goto-selected-point (point)
6695 org-goto-exit-command 'left)
6696 (throw 'exit nil))
6697 (error "Not on a heading")))
6699 (defun org-goto-right ()
6700 "Finish `org-goto' by going to the new location."
6701 (interactive)
6702 (if (org-on-heading-p)
6703 (progn
6704 (setq org-goto-selected-point (point)
6705 org-goto-exit-command 'right)
6706 (throw 'exit nil))
6707 (error "Not on a heading")))
6709 (defun org-goto-quit ()
6710 "Finish `org-goto' without cursor motion."
6711 (interactive)
6712 (setq org-goto-selected-point nil)
6713 (setq org-goto-exit-command 'quit)
6714 (throw 'exit nil))
6716 ;;; Indirect buffer display of subtrees
6718 (defvar org-indirect-dedicated-frame nil
6719 "This is the frame being used for indirect tree display.")
6720 (defvar org-last-indirect-buffer nil)
6722 (defun org-tree-to-indirect-buffer (&optional arg)
6723 "Create indirect buffer and narrow it to current subtree.
6724 With numerical prefix ARG, go up to this level and then take that tree.
6725 If ARG is negative, go up that many levels.
6726 If `org-indirect-buffer-display' is not `new-frame', the command removes the
6727 indirect buffer previously made with this command, to avoid proliferation of
6728 indirect buffers. However, when you call the command with a \
6729 \\[universal-argument] prefix, or
6730 when `org-indirect-buffer-display' is `new-frame', the last buffer
6731 is kept so that you can work with several indirect buffers at the same time.
6732 If `org-indirect-buffer-display' is `dedicated-frame', the \
6733 \\[universal-argument] prefix also
6734 requests that a new frame be made for the new buffer, so that the dedicated
6735 frame is not changed."
6736 (interactive "P")
6737 (let ((cbuf (current-buffer))
6738 (cwin (selected-window))
6739 (pos (point))
6740 beg end level heading ibuf)
6741 (save-excursion
6742 (org-back-to-heading t)
6743 (when (numberp arg)
6744 (setq level (org-outline-level))
6745 (if (< arg 0) (setq arg (+ level arg)))
6746 (while (> (setq level (org-outline-level)) arg)
6747 (outline-up-heading 1 t)))
6748 (setq beg (point)
6749 heading (org-get-heading))
6750 (org-end-of-subtree t t)
6751 (if (org-on-heading-p) (backward-char 1))
6752 (setq end (point)))
6753 (if (and (buffer-live-p org-last-indirect-buffer)
6754 (not (eq org-indirect-buffer-display 'new-frame))
6755 (not arg))
6756 (kill-buffer org-last-indirect-buffer))
6757 (setq ibuf (org-get-indirect-buffer cbuf)
6758 org-last-indirect-buffer ibuf)
6759 (cond
6760 ((or (eq org-indirect-buffer-display 'new-frame)
6761 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
6762 (select-frame (make-frame))
6763 (delete-other-windows)
6764 (switch-to-buffer ibuf)
6765 (org-set-frame-title heading))
6766 ((eq org-indirect-buffer-display 'dedicated-frame)
6767 (raise-frame
6768 (select-frame (or (and org-indirect-dedicated-frame
6769 (frame-live-p org-indirect-dedicated-frame)
6770 org-indirect-dedicated-frame)
6771 (setq org-indirect-dedicated-frame (make-frame)))))
6772 (delete-other-windows)
6773 (switch-to-buffer ibuf)
6774 (org-set-frame-title (concat "Indirect: " heading)))
6775 ((eq org-indirect-buffer-display 'current-window)
6776 (switch-to-buffer ibuf))
6777 ((eq org-indirect-buffer-display 'other-window)
6778 (pop-to-buffer ibuf))
6779 (t (error "Invalid value")))
6780 (if (featurep 'xemacs)
6781 (save-excursion (org-mode) (turn-on-font-lock)))
6782 (narrow-to-region beg end)
6783 (show-all)
6784 (goto-char pos)
6785 (and (window-live-p cwin) (select-window cwin))))
6787 (defun org-get-indirect-buffer (&optional buffer)
6788 (setq buffer (or buffer (current-buffer)))
6789 (let ((n 1) (base (buffer-name buffer)) bname)
6790 (while (buffer-live-p
6791 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
6792 (setq n (1+ n)))
6793 (condition-case nil
6794 (make-indirect-buffer buffer bname 'clone)
6795 (error (make-indirect-buffer buffer bname)))))
6797 (defun org-set-frame-title (title)
6798 "Set the title of the current frame to the string TITLE."
6799 ;; FIXME: how to name a single frame in XEmacs???
6800 (unless (featurep 'xemacs)
6801 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
6803 ;;;; Structure editing
6805 ;;; Inserting headlines
6807 (defun org-previous-line-empty-p ()
6808 (save-excursion
6809 (and (not (bobp))
6810 (or (beginning-of-line 0) t)
6811 (save-match-data
6812 (looking-at "[ \t]*$")))))
6814 (defun org-insert-heading (&optional force-heading invisible-ok)
6815 "Insert a new heading or item with same depth at point.
6816 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
6817 If point is at the beginning of a headline, insert a sibling before the
6818 current headline. If point is not at the beginning, split the line,
6819 create the new headline with the text in the current line after point
6820 \(but see also the variable `org-M-RET-may-split-line').
6822 When INVISIBLE-OK is set, stop at invisible headlines when going back.
6823 This is important for non-interactive uses of the command."
6824 (interactive "P")
6825 (if (or (= (buffer-size) 0)
6826 (and (not (save-excursion
6827 (and (ignore-errors (org-back-to-heading invisible-ok))
6828 (org-on-heading-p))))
6829 (not (org-in-item-p))))
6830 (progn
6831 (insert "\n* ")
6832 (run-hooks 'org-insert-heading-hook))
6833 (when (or force-heading (not (org-insert-item)))
6834 (let* ((empty-line-p nil)
6835 (level nil)
6836 (on-heading (org-on-heading-p))
6837 (head (save-excursion
6838 (condition-case nil
6839 (progn
6840 (org-back-to-heading invisible-ok)
6841 (when (and (not on-heading)
6842 (featurep 'org-inlinetask)
6843 (integerp org-inlinetask-min-level)
6844 (>= (length (match-string 0))
6845 org-inlinetask-min-level))
6846 ;; Find a heading level before the inline task
6847 (while (and (setq level (org-up-heading-safe))
6848 (>= level org-inlinetask-min-level)))
6849 (if (org-on-heading-p)
6850 (org-back-to-heading invisible-ok)
6851 (error "This should not happen")))
6852 (setq empty-line-p (org-previous-line-empty-p))
6853 (match-string 0))
6854 (error "*"))))
6855 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
6856 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
6857 pos hide-previous previous-pos)
6858 (cond
6859 ((and (org-on-heading-p) (bolp)
6860 (or (bobp)
6861 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
6862 ;; insert before the current line
6863 (open-line (if blank 2 1)))
6864 ((and (bolp)
6865 (not org-insert-heading-respect-content)
6866 (or (bobp)
6867 (save-excursion
6868 (backward-char 1) (not (outline-invisible-p)))))
6869 ;; insert right here
6870 nil)
6872 ;; somewhere in the line
6873 (save-excursion
6874 (setq previous-pos (point-at-bol))
6875 (end-of-line)
6876 (setq hide-previous (outline-invisible-p)))
6877 (and org-insert-heading-respect-content (org-show-subtree))
6878 (let ((split
6879 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
6880 (save-excursion
6881 (let ((p (point)))
6882 (goto-char (point-at-bol))
6883 (and (looking-at org-complex-heading-regexp)
6884 (> p (match-beginning 4)))))))
6885 tags pos)
6886 (cond
6887 (org-insert-heading-respect-content
6888 (org-end-of-subtree nil t)
6889 (when (featurep 'org-inlinetask)
6890 (while (and (not (eobp))
6891 (looking-at "\\(\\*+\\)[ \t]+")
6892 (>= (length (match-string 1))
6893 org-inlinetask-min-level))
6894 (org-end-of-subtree nil t)))
6895 (or (bolp) (newline))
6896 (or (org-previous-line-empty-p)
6897 (and blank (newline)))
6898 (open-line 1))
6899 ((org-on-heading-p)
6900 (when hide-previous
6901 (show-children)
6902 (org-show-entry))
6903 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
6904 (setq tags (and (match-end 2) (match-string 2)))
6905 (and (match-end 1)
6906 (delete-region (match-beginning 1) (match-end 1)))
6907 (setq pos (point-at-bol))
6908 (or split (end-of-line 1))
6909 (delete-horizontal-space)
6910 (if (string-match "\\`\\*+\\'"
6911 (buffer-substring (point-at-bol) (point)))
6912 (insert " "))
6913 (newline (if blank 2 1))
6914 (when tags
6915 (save-excursion
6916 (goto-char pos)
6917 (end-of-line 1)
6918 (insert " " tags)
6919 (org-set-tags nil 'align))))
6921 (or split (end-of-line 1))
6922 (newline (if blank 2 1)))))))
6923 (insert head) (just-one-space)
6924 (setq pos (point))
6925 (end-of-line 1)
6926 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
6927 (when (and org-insert-heading-respect-content hide-previous)
6928 (save-excursion
6929 (goto-char previous-pos)
6930 (hide-subtree)))
6931 (run-hooks 'org-insert-heading-hook)))))
6933 (defun org-new-numbered-action (&optional inline)
6934 "Insert a new numbered action, using `org-numbered-action-format'.
6935 With prefix argument, insert an inline task."
6936 (interactive "P")
6937 (let* ((num (let ((re "\\`#\\([0-9]+\\)\\'"))
6938 (1+ (apply 'max 0
6939 (mapcar
6940 (lambda (e)
6941 (if (string-match re (car e))
6942 (string-to-number (match-string 1 (car e)))
6944 (org-get-buffer-tags))))))
6945 (tag (concat "#" (number-to-string num))))
6946 (if inline
6947 (org-inlinetask-insert-task)
6948 (org-insert-heading nil 'force))
6949 (unless (eql (char-before) ?\ ) (insert " "))
6950 (insert (format org-numbered-action-format num))
6951 (org-toggle-tag tag 'on)
6952 (if (= (point-max) (point-at-bol))
6953 (save-excursion (goto-char (point-at-eol)) (insert "\n")))
6954 (unless (eql (char-before) ?\ ) (insert " "))))
6956 (defun org-get-heading (&optional no-tags)
6957 "Return the heading of the current entry, without the stars."
6958 (save-excursion
6959 (org-back-to-heading t)
6960 (if (looking-at
6961 (if no-tags
6962 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@#%]+:[ \t]*\\)?$")
6963 "\\*+[ \t]+\\([^\r\n]*\\)"))
6964 (match-string 1) "")))
6966 (defun org-heading-components ()
6967 "Return the components of the current heading.
6968 This is a list with the following elements:
6969 - the level as an integer
6970 - the reduced level, different if `org-odd-levels-only' is set.
6971 - the TODO keyword, or nil
6972 - the priority character, like ?A, or nil if no priority is given
6973 - the headline text itself, or the tags string if no headline text
6974 - the tags string, or nil."
6975 (save-excursion
6976 (org-back-to-heading t)
6977 (if (let (case-fold-search) (looking-at org-complex-heading-regexp))
6978 (list (length (match-string 1))
6979 (org-reduced-level (length (match-string 1)))
6980 (org-match-string-no-properties 2)
6981 (and (match-end 3) (aref (match-string 3) 2))
6982 (org-match-string-no-properties 4)
6983 (org-match-string-no-properties 5)))))
6985 (defun org-get-entry ()
6986 "Get the entry text, after heading, entire subtree."
6987 (save-excursion
6988 (org-back-to-heading t)
6989 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
6991 (defun org-insert-heading-after-current ()
6992 "Insert a new heading with same level as current, after current subtree."
6993 (interactive)
6994 (org-back-to-heading)
6995 (org-insert-heading)
6996 (org-move-subtree-down)
6997 (end-of-line 1))
6999 (defun org-insert-heading-respect-content ()
7000 (interactive)
7001 (let ((org-insert-heading-respect-content t))
7002 (org-insert-heading t)))
7004 (defun org-insert-todo-heading-respect-content (&optional force-state)
7005 (interactive "P")
7006 (let ((org-insert-heading-respect-content t))
7007 (org-insert-todo-heading force-state t)))
7009 (defun org-insert-todo-heading (arg &optional force-heading)
7010 "Insert a new heading with the same level and TODO state as current heading.
7011 If the heading has no TODO state, or if the state is DONE, use the first
7012 state (TODO by default). Also with prefix arg, force first state."
7013 (interactive "P")
7014 (when (or force-heading (not (org-insert-item 'checkbox)))
7015 (org-insert-heading force-heading)
7016 (save-excursion
7017 (org-back-to-heading)
7018 (outline-previous-heading)
7019 (looking-at org-todo-line-regexp))
7020 (let*
7021 ((new-mark-x
7022 (if (or arg
7023 (not (match-beginning 2))
7024 (member (match-string 2) org-done-keywords))
7025 (car org-todo-keywords-1)
7026 (match-string 2)))
7027 (new-mark
7029 (run-hook-with-args-until-success
7030 'org-todo-get-default-hook new-mark-x nil)
7031 new-mark-x)))
7032 (beginning-of-line 1)
7033 (and (looking-at "\\*+ ") (goto-char (match-end 0))
7034 (if org-treat-insert-todo-heading-as-state-change
7035 (org-todo new-mark)
7036 (insert new-mark " "))))
7037 (when org-provide-todo-statistics
7038 (org-update-parent-todo-statistics))))
7040 (defun org-insert-subheading (arg)
7041 "Insert a new subheading and demote it.
7042 Works for outline headings and for plain lists alike."
7043 (interactive "P")
7044 (org-insert-heading arg)
7045 (cond
7046 ((org-on-heading-p) (org-do-demote))
7047 ((org-at-item-p) (org-indent-item))))
7049 (defun org-insert-todo-subheading (arg)
7050 "Insert a new subheading with TODO keyword or checkbox and demote it.
7051 Works for outline headings and for plain lists alike."
7052 (interactive "P")
7053 (org-insert-todo-heading arg)
7054 (cond
7055 ((org-on-heading-p) (org-do-demote))
7056 ((org-at-item-p) (org-indent-item))))
7058 ;;; Promotion and Demotion
7060 (defvar org-after-demote-entry-hook nil
7061 "Hook run after an entry has been demoted.
7062 The cursor will be at the beginning of the entry.
7063 When a subtree is being demoted, the hook will be called for each node.")
7065 (defvar org-after-promote-entry-hook nil
7066 "Hook run after an entry has been promoted.
7067 The cursor will be at the beginning of the entry.
7068 When a subtree is being promoted, the hook will be called for each node.")
7070 (defun org-promote-subtree ()
7071 "Promote the entire subtree.
7072 See also `org-promote'."
7073 (interactive)
7074 (save-excursion
7075 (org-with-limited-levels (org-map-tree 'org-promote)))
7076 (org-fix-position-after-promote))
7078 (defun org-demote-subtree ()
7079 "Demote the entire subtree. See `org-demote'.
7080 See also `org-promote'."
7081 (interactive)
7082 (save-excursion
7083 (org-with-limited-levels (org-map-tree 'org-demote)))
7084 (org-fix-position-after-promote))
7087 (defun org-do-promote ()
7088 "Promote the current heading higher up the tree.
7089 If the region is active in `transient-mark-mode', promote all headings
7090 in the region."
7091 (interactive)
7092 (save-excursion
7093 (if (org-region-active-p)
7094 (org-map-region 'org-promote (region-beginning) (region-end))
7095 (org-promote)))
7096 (org-fix-position-after-promote))
7098 (defun org-do-demote ()
7099 "Demote the current heading lower down the tree.
7100 If the region is active in `transient-mark-mode', demote all headings
7101 in the region."
7102 (interactive)
7103 (save-excursion
7104 (if (org-region-active-p)
7105 (org-map-region 'org-demote (region-beginning) (region-end))
7106 (org-demote)))
7107 (org-fix-position-after-promote))
7109 (defun org-fix-position-after-promote ()
7110 "Make sure that after pro/demotion cursor position is right."
7111 (let ((pos (point)))
7112 (when (save-excursion
7113 (beginning-of-line 1)
7114 (looking-at org-todo-line-regexp)
7115 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7116 (cond ((eobp) (insert " "))
7117 ((eolp) (insert " "))
7118 ((equal (char-after) ?\ ) (forward-char 1))))))
7120 (defun org-current-level ()
7121 "Return the level of the current entry, or nil if before the first headline.
7122 The level is the number of stars at the beginning of the headline."
7123 (save-excursion
7124 (org-with-limited-levels
7125 (ignore-errors
7126 (org-back-to-heading t)
7127 (funcall outline-level)))))
7129 (defun org-get-previous-line-level ()
7130 "Return the outline depth of the last headline before the current line.
7131 Returns 0 for the first headline in the buffer, and nil if before the
7132 first headline."
7133 (let ((current-level (org-current-level))
7134 (prev-level (when (> (line-number-at-pos) 1)
7135 (save-excursion
7136 (beginning-of-line 0)
7137 (org-current-level)))))
7138 (cond ((null current-level) nil) ; Before first headline
7139 ((null prev-level) 0) ; At first headline
7140 (prev-level))))
7142 (defun org-reduced-level (l)
7143 "Compute the effective level of a heading.
7144 This takes into account the setting of `org-odd-levels-only'."
7145 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
7147 (defun org-level-increment ()
7148 "Return the number of stars that will be added or removed at a
7149 time to headlines when structure editing, based on the value of
7150 `org-odd-levels-only'."
7151 (if org-odd-levels-only 2 1))
7153 (defun org-get-valid-level (level &optional change)
7154 "Rectify a level change under the influence of `org-odd-levels-only'
7155 LEVEL is a current level, CHANGE is by how much the level should be
7156 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7157 even level numbers will become the next higher odd number."
7158 (if org-odd-levels-only
7159 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7160 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7161 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7162 (max 1 (+ level (or change 0)))))
7164 (if (boundp 'define-obsolete-function-alias)
7165 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7166 (define-obsolete-function-alias 'org-get-legal-level
7167 'org-get-valid-level)
7168 (define-obsolete-function-alias 'org-get-legal-level
7169 'org-get-valid-level "23.1")))
7171 (defun org-promote ()
7172 "Promote the current heading higher up the tree.
7173 If the region is active in `transient-mark-mode', promote all headings
7174 in the region."
7175 (org-back-to-heading t)
7176 (let* ((level (save-match-data (funcall outline-level)))
7177 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7178 (diff (abs (- level (length up-head) -1))))
7179 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
7180 (replace-match up-head nil t)
7181 ;; Fixup tag positioning
7182 (and org-auto-align-tags (org-set-tags nil t))
7183 (if org-adapt-indentation (org-fixup-indentation (- diff)))
7184 (run-hooks 'org-after-promote-entry-hook)))
7186 (defun org-demote ()
7187 "Demote the current heading lower down the tree.
7188 If the region is active in `transient-mark-mode', demote all headings
7189 in the region."
7190 (org-back-to-heading t)
7191 (let* ((level (save-match-data (funcall outline-level)))
7192 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7193 (diff (abs (- level (length down-head) -1))))
7194 (replace-match down-head nil t)
7195 ;; Fixup tag positioning
7196 (and org-auto-align-tags (org-set-tags nil t))
7197 (if org-adapt-indentation (org-fixup-indentation diff))
7198 (run-hooks 'org-after-demote-entry-hook)))
7200 (defun org-cycle-level ()
7201 "Cycle the level of an empty headline through possible states.
7202 This goes first to child, then to parent, level, then up the hierarchy.
7203 After top level, it switches back to sibling level."
7204 (interactive)
7205 (let ((org-adapt-indentation nil))
7206 (when (org-point-at-end-of-empty-headline)
7207 (setq this-command 'org-cycle-level) ; Only needed for caching
7208 (let ((cur-level (org-current-level))
7209 (prev-level (org-get-previous-line-level)))
7210 (cond
7211 ;; If first headline in file, promote to top-level.
7212 ((= prev-level 0)
7213 (loop repeat (/ (- cur-level 1) (org-level-increment))
7214 do (org-do-promote)))
7215 ;; If same level as prev, demote one.
7216 ((= prev-level cur-level)
7217 (org-do-demote))
7218 ;; If parent is top-level, promote to top level if not already.
7219 ((= prev-level 1)
7220 (loop repeat (/ (- cur-level 1) (org-level-increment))
7221 do (org-do-promote)))
7222 ;; If top-level, return to prev-level.
7223 ((= cur-level 1)
7224 (loop repeat (/ (- prev-level 1) (org-level-increment))
7225 do (org-do-demote)))
7226 ;; If less than prev-level, promote one.
7227 ((< cur-level prev-level)
7228 (org-do-promote))
7229 ;; If deeper than prev-level, promote until higher than
7230 ;; prev-level.
7231 ((> cur-level prev-level)
7232 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7233 do (org-do-promote))))
7234 t))))
7236 (defun org-map-tree (fun)
7237 "Call FUN for every heading underneath the current one."
7238 (org-back-to-heading)
7239 (let ((level (funcall outline-level)))
7240 (save-excursion
7241 (funcall fun)
7242 (while (and (progn
7243 (outline-next-heading)
7244 (> (funcall outline-level) level))
7245 (not (eobp)))
7246 (funcall fun)))))
7248 (defun org-map-region (fun beg end)
7249 "Call FUN for every heading between BEG and END."
7250 (let ((org-ignore-region t))
7251 (save-excursion
7252 (setq end (copy-marker end))
7253 (goto-char beg)
7254 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
7255 (< (point) end))
7256 (funcall fun))
7257 (while (and (progn
7258 (outline-next-heading)
7259 (< (point) end))
7260 (not (eobp)))
7261 (funcall fun)))))
7263 (defun org-fixup-indentation (diff)
7264 "Change the indentation in the current entry by DIFF.
7265 However, if any line in the current entry has no indentation, or if it
7266 would end up with no indentation after the change, nothing at all is done."
7267 (save-excursion
7268 (let ((end (save-excursion (outline-next-heading)
7269 (point-marker)))
7270 (prohibit (if (> diff 0)
7271 "^\\S-"
7272 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7273 col)
7274 (unless (save-excursion (end-of-line 1)
7275 (re-search-forward prohibit end t))
7276 (while (and (< (point) end)
7277 (re-search-forward "^[ \t]+" end t))
7278 (goto-char (match-end 0))
7279 (setq col (current-column))
7280 (if (< diff 0) (replace-match ""))
7281 (org-indent-to-column (+ diff col))))
7282 (move-marker end nil))))
7284 (defun org-convert-to-odd-levels ()
7285 "Convert an org-mode file with all levels allowed to one with odd levels.
7286 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7287 level 5 etc."
7288 (interactive)
7289 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7290 (let ((outline-regexp org-outline-regexp)
7291 (outline-level 'org-outline-level)
7292 (org-odd-levels-only nil) n)
7293 (save-excursion
7294 (goto-char (point-min))
7295 (while (re-search-forward "^\\*\\*+ " nil t)
7296 (setq n (- (length (match-string 0)) 2))
7297 (while (>= (setq n (1- n)) 0)
7298 (org-demote))
7299 (end-of-line 1))))))
7301 (defun org-convert-to-oddeven-levels ()
7302 "Convert an org-mode file with only odd levels to one with odd/even levels.
7303 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7304 file contains a section with an even level, conversion would
7305 destroy the structure of the file. An error is signaled in this
7306 case."
7307 (interactive)
7308 (goto-char (point-min))
7309 ;; First check if there are no even levels
7310 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7311 (org-show-context t)
7312 (error "Not all levels are odd in this file. Conversion not possible"))
7313 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
7314 (let ((outline-regexp org-outline-regexp)
7315 (outline-level 'org-outline-level)
7316 (org-odd-levels-only nil) n)
7317 (save-excursion
7318 (goto-char (point-min))
7319 (while (re-search-forward "^\\*\\*+ " nil t)
7320 (setq n (/ (1- (length (match-string 0))) 2))
7321 (while (>= (setq n (1- n)) 0)
7322 (org-promote))
7323 (end-of-line 1))))))
7325 (defun org-tr-level (n)
7326 "Make N odd if required."
7327 (if org-odd-levels-only (1+ (/ n 2)) n))
7329 ;;; Vertical tree motion, cutting and pasting of subtrees
7331 (defun org-move-subtree-up (&optional arg)
7332 "Move the current subtree up past ARG headlines of the same level."
7333 (interactive "p")
7334 (org-move-subtree-down (- (prefix-numeric-value arg))))
7336 (defun org-move-subtree-down (&optional arg)
7337 "Move the current subtree down past ARG headlines of the same level."
7338 (interactive "p")
7339 (setq arg (prefix-numeric-value arg))
7340 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
7341 'org-get-last-sibling))
7342 (ins-point (make-marker))
7343 (cnt (abs arg))
7344 (col (current-column))
7345 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
7346 ;; Select the tree
7347 (org-back-to-heading)
7348 (setq beg0 (point))
7349 (save-excursion
7350 (setq ne-beg (org-back-over-empty-lines))
7351 (setq beg (point)))
7352 (save-match-data
7353 (save-excursion (outline-end-of-heading)
7354 (setq folded (outline-invisible-p)))
7355 (outline-end-of-subtree))
7356 (outline-next-heading)
7357 (setq ne-end (org-back-over-empty-lines))
7358 (setq end (point))
7359 (goto-char beg0)
7360 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
7361 ;; include less whitespace
7362 (save-excursion
7363 (goto-char beg)
7364 (forward-line (- ne-beg ne-end))
7365 (setq beg (point))))
7366 ;; Find insertion point, with error handling
7367 (while (> cnt 0)
7368 (or (and (funcall movfunc) (looking-at outline-regexp))
7369 (progn (goto-char beg0)
7370 (error "Cannot move past superior level or buffer limit")))
7371 (setq cnt (1- cnt)))
7372 (if (> arg 0)
7373 ;; Moving forward - still need to move over subtree
7374 (progn (org-end-of-subtree t t)
7375 (save-excursion
7376 (org-back-over-empty-lines)
7377 (or (bolp) (newline)))))
7378 (setq ne-ins (org-back-over-empty-lines))
7379 (move-marker ins-point (point))
7380 (setq txt (buffer-substring beg end))
7381 (org-save-markers-in-region beg end)
7382 (delete-region beg end)
7383 (org-remove-empty-overlays-at beg)
7384 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
7385 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
7386 (and (not (bolp)) (looking-at "\n") (forward-char 1))
7387 (let ((bbb (point)))
7388 (insert-before-markers txt)
7389 (org-reinstall-markers-in-region bbb)
7390 (move-marker ins-point bbb))
7391 (or (bolp) (insert "\n"))
7392 (setq ins-end (point))
7393 (goto-char ins-point)
7394 (org-skip-whitespace)
7395 (when (and (< arg 0)
7396 (org-first-sibling-p)
7397 (> ne-ins ne-beg))
7398 ;; Move whitespace back to beginning
7399 (save-excursion
7400 (goto-char ins-end)
7401 (let ((kill-whole-line t))
7402 (kill-line (- ne-ins ne-beg)) (point)))
7403 (insert (make-string (- ne-ins ne-beg) ?\n)))
7404 (move-marker ins-point nil)
7405 (if folded
7406 (hide-subtree)
7407 (org-show-entry)
7408 (show-children)
7409 (org-cycle-hide-drawers 'children))
7410 (org-clean-visibility-after-subtree-move)
7411 ;; move back to the initial column we were at
7412 (move-to-column col)))
7414 (defvar org-subtree-clip ""
7415 "Clipboard for cut and paste of subtrees.
7416 This is actually only a copy of the kill, because we use the normal kill
7417 ring. We need it to check if the kill was created by `org-copy-subtree'.")
7419 (defvar org-subtree-clip-folded nil
7420 "Was the last copied subtree folded?
7421 This is used to fold the tree back after pasting.")
7423 (defun org-cut-subtree (&optional n)
7424 "Cut the current subtree into the clipboard.
7425 With prefix arg N, cut this many sequential subtrees.
7426 This is a short-hand for marking the subtree and then cutting it."
7427 (interactive "p")
7428 (org-copy-subtree n 'cut))
7430 (defun org-copy-subtree (&optional n cut force-store-markers)
7431 "Cut the current subtree into the clipboard.
7432 With prefix arg N, cut this many sequential subtrees.
7433 This is a short-hand for marking the subtree and then copying it.
7434 If CUT is non-nil, actually cut the subtree.
7435 If FORCE-STORE-MARKERS is non-nil, store the relative locations
7436 of some markers in the region, even if CUT is non-nil. This is
7437 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
7438 (interactive "p")
7439 (let (beg end folded (beg0 (point)))
7440 (if (interactive-p)
7441 (org-back-to-heading nil) ; take what looks like a subtree
7442 (org-back-to-heading t)) ; take what is really there
7443 (org-back-over-empty-lines)
7444 (setq beg (point))
7445 (skip-chars-forward " \t\r\n")
7446 (save-match-data
7447 (save-excursion (outline-end-of-heading)
7448 (setq folded (outline-invisible-p)))
7449 (condition-case nil
7450 (org-forward-same-level (1- n) t)
7451 (error nil))
7452 (org-end-of-subtree t t))
7453 (org-back-over-empty-lines)
7454 (setq end (point))
7455 (goto-char beg0)
7456 (when (> end beg)
7457 (setq org-subtree-clip-folded folded)
7458 (when (or cut force-store-markers)
7459 (org-save-markers-in-region beg end))
7460 (if cut (kill-region beg end) (copy-region-as-kill beg end))
7461 (setq org-subtree-clip (current-kill 0))
7462 (message "%s: Subtree(s) with %d characters"
7463 (if cut "Cut" "Copied")
7464 (length org-subtree-clip)))))
7466 (defun org-paste-subtree (&optional level tree for-yank)
7467 "Paste the clipboard as a subtree, with modification of headline level.
7468 The entire subtree is promoted or demoted in order to match a new headline
7469 level.
7471 If the cursor is at the beginning of a headline, the same level as
7472 that headline is used to paste the tree
7474 If not, the new level is derived from the *visible* headings
7475 before and after the insertion point, and taken to be the inferior headline
7476 level of the two. So if the previous visible heading is level 3 and the
7477 next is level 4 (or vice versa), level 4 will be used for insertion.
7478 This makes sure that the subtree remains an independent subtree and does
7479 not swallow low level entries.
7481 You can also force a different level, either by using a numeric prefix
7482 argument, or by inserting the heading marker by hand. For example, if the
7483 cursor is after \"*****\", then the tree will be shifted to level 5.
7485 If optional TREE is given, use this text instead of the kill ring.
7487 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
7488 move back over whitespace before inserting, and move point to the end of
7489 the inserted text when done."
7490 (interactive "P")
7491 (setq tree (or tree (and kill-ring (current-kill 0))))
7492 (unless (org-kill-is-subtree-p tree)
7493 (error "%s"
7494 (substitute-command-keys
7495 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
7496 (let* ((visp (not (outline-invisible-p)))
7497 (txt tree)
7498 (^re (concat "^\\(" outline-regexp "\\)"))
7499 (re (concat "\\(" outline-regexp "\\)"))
7500 (^re_ (concat "\\(\\*+\\)[ \t]*"))
7502 (old-level (if (string-match ^re txt)
7503 (- (match-end 0) (match-beginning 0) 1)
7504 -1))
7505 (force-level (cond (level (prefix-numeric-value level))
7506 ((and (looking-at "[ \t]*$")
7507 (string-match
7508 ^re_ (buffer-substring
7509 (point-at-bol) (point))))
7510 (- (match-end 1) (match-beginning 1)))
7511 ((and (bolp)
7512 (looking-at org-outline-regexp))
7513 (- (match-end 0) (point) 1))
7514 (t nil)))
7515 (previous-level (save-excursion
7516 (condition-case nil
7517 (progn
7518 (outline-previous-visible-heading 1)
7519 (if (looking-at re)
7520 (- (match-end 0) (match-beginning 0) 1)
7522 (error 1))))
7523 (next-level (save-excursion
7524 (condition-case nil
7525 (progn
7526 (or (looking-at outline-regexp)
7527 (outline-next-visible-heading 1))
7528 (if (looking-at re)
7529 (- (match-end 0) (match-beginning 0) 1)
7531 (error 1))))
7532 (new-level (or force-level (max previous-level next-level)))
7533 (shift (if (or (= old-level -1)
7534 (= new-level -1)
7535 (= old-level new-level))
7537 (- new-level old-level)))
7538 (delta (if (> shift 0) -1 1))
7539 (func (if (> shift 0) 'org-demote 'org-promote))
7540 (org-odd-levels-only nil)
7541 beg end newend)
7542 ;; Remove the forced level indicator
7543 (if force-level
7544 (delete-region (point-at-bol) (point)))
7545 ;; Paste
7546 (beginning-of-line 1)
7547 (unless for-yank (org-back-over-empty-lines))
7548 (setq beg (point))
7549 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
7550 (insert-before-markers txt)
7551 (unless (string-match "\n\\'" txt) (insert "\n"))
7552 (setq newend (point))
7553 (org-reinstall-markers-in-region beg)
7554 (setq end (point))
7555 (goto-char beg)
7556 (skip-chars-forward " \t\n\r")
7557 (setq beg (point))
7558 (if (and (outline-invisible-p) visp)
7559 (save-excursion (outline-show-heading)))
7560 ;; Shift if necessary
7561 (unless (= shift 0)
7562 (save-restriction
7563 (narrow-to-region beg end)
7564 (while (not (= shift 0))
7565 (org-map-region func (point-min) (point-max))
7566 (setq shift (+ delta shift)))
7567 (goto-char (point-min))
7568 (setq newend (point-max))))
7569 (when (or (interactive-p) for-yank)
7570 (message "Clipboard pasted as level %d subtree" new-level))
7571 (if (and (not for-yank) ; in this case, org-yank will decide about folding
7572 kill-ring
7573 (eq org-subtree-clip (current-kill 0))
7574 org-subtree-clip-folded)
7575 ;; The tree was folded before it was killed/copied
7576 (hide-subtree))
7577 (and for-yank (goto-char newend))))
7579 (defun org-kill-is-subtree-p (&optional txt)
7580 "Check if the current kill is an outline subtree, or a set of trees.
7581 Returns nil if kill does not start with a headline, or if the first
7582 headline level is not the largest headline level in the tree.
7583 So this will actually accept several entries of equal levels as well,
7584 which is OK for `org-paste-subtree'.
7585 If optional TXT is given, check this string instead of the current kill."
7586 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
7587 (start-level (and kill
7588 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
7589 org-outline-regexp "\\)")
7590 kill)
7591 (- (match-end 2) (match-beginning 2) 1)))
7592 (re (concat "^" org-outline-regexp))
7593 (start (1+ (or (match-beginning 2) -1))))
7594 (if (not start-level)
7595 (progn
7596 nil) ;; does not even start with a heading
7597 (catch 'exit
7598 (while (setq start (string-match re kill (1+ start)))
7599 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
7600 (throw 'exit nil)))
7601 t))))
7603 (defun org-collect-todos-in-subtree ()
7604 "Collect all TODO items in the current subtree into a flat list."
7605 (interactive)
7606 (let ((buf (get-buffer-create "Org TODO Collect"))
7607 (cnt 0))
7608 (with-current-buffer buf (erase-buffer) (org-mode))
7609 (save-excursion
7610 (save-restriction
7611 (org-narrow-to-subtree)
7612 (goto-char (point-min))
7613 (while (re-search-forward org-complex-heading-regexp nil t)
7614 (when (and (match-end 2)
7615 (member (match-string 2) org-not-done-keywords))
7616 (setq beg (match-beginning 0)
7617 cnt (1+ cnt))
7618 (org-end-of-subtree t t)
7619 (setq end (point))
7620 (copy-region-as-kill beg end)
7621 (with-current-buffer buf
7622 (org-paste-subtree 1)
7623 (or (bolp) (insert "\n"))
7624 (set-buffer-modified-p nil))))))
7625 (with-current-buffer buf
7626 (kill-region (point-min) (point-max)))
7627 (kill-buffer buf)
7628 (message "Collected %d TODO items as flat list into the kill buffer" cnt)))
7630 (defvar org-markers-to-move nil
7631 "Markers that should be moved with a cut-and-paste operation.
7632 Those markers are stored together with their positions relative to
7633 the start of the region.")
7635 (defun org-save-markers-in-region (beg end)
7636 "Check markers in region.
7637 If these markers are between BEG and END, record their position relative
7638 to BEG, so that after moving the block of text, we can put the markers back
7639 into place.
7640 This function gets called just before an entry or tree gets cut from the
7641 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
7642 called immediately, to move the markers with the entries."
7643 (setq org-markers-to-move nil)
7644 (when (featurep 'org-clock)
7645 (org-clock-save-markers-for-cut-and-paste beg end))
7646 (when (featurep 'org-agenda)
7647 (org-agenda-save-markers-for-cut-and-paste beg end)))
7649 (defun org-check-and-save-marker (marker beg end)
7650 "Check if MARKER is between BEG and END.
7651 If yes, remember the marker and the distance to BEG."
7652 (when (and (marker-buffer marker)
7653 (equal (marker-buffer marker) (current-buffer)))
7654 (if (and (>= marker beg) (< marker end))
7655 (push (cons marker (- marker beg)) org-markers-to-move))))
7657 (defun org-reinstall-markers-in-region (beg)
7658 "Move all remembered markers to their position relative to BEG."
7659 (mapc (lambda (x)
7660 (move-marker (car x) (+ beg (cdr x))))
7661 org-markers-to-move)
7662 (setq org-markers-to-move nil))
7664 (defun org-narrow-to-subtree ()
7665 "Narrow buffer to the current subtree."
7666 (interactive)
7667 (save-excursion
7668 (save-match-data
7669 (org-with-limited-levels
7670 (narrow-to-region
7671 (progn (org-back-to-heading t) (point))
7672 (progn (org-end-of-subtree t t)
7673 (if (and (org-on-heading-p) (not (eobp))) (backward-char 1))
7674 (point)))))))
7676 (defun org-narrow-to-block ()
7677 "Narrow buffer to the current block."
7678 (interactive)
7679 (let ((bstart "^[ \t]*#\\+begin")
7680 (bend "[ \t]*#\\+end")
7681 (case-fold-search t) ;; allow #+BEGIN
7682 b_start b_end)
7683 (if (org-in-regexps-block-p bstart bend)
7684 (progn
7685 (save-excursion (re-search-backward bstart nil t)
7686 (setq b_start (match-beginning 0)))
7687 (save-excursion (re-search-forward bend nil t)
7688 (setq b_end (match-end 0)))
7689 (narrow-to-region b_start b_end))
7690 (error "Not in a block"))))
7692 (eval-when-compile
7693 (defvar org-property-drawer-re))
7695 (defvar org-property-start-re) ;; defined below
7696 (defun org-clone-subtree-with-time-shift (n &optional shift)
7697 "Clone the task (subtree) at point N times.
7698 The clones will be inserted as siblings.
7700 In interactive use, the user will be prompted for the number of
7701 clones to be produced, and for a time SHIFT, which may be a
7702 repeater as used in time stamps, for example `+3d'.
7704 When a valid repeater is given and the entry contains any time
7705 stamps, the clones will become a sequence in time, with time
7706 stamps in the subtree shifted for each clone produced. If SHIFT
7707 is nil or the empty string, time stamps will be left alone. The
7708 ID property of the original subtree is removed.
7710 If the original subtree did contain time stamps with a repeater,
7711 the following will happen:
7712 - the repeater will be removed in each clone
7713 - an additional clone will be produced, with the current, unshifted
7714 date(s) in the entry.
7715 - the original entry will be placed *after* all the clones, with
7716 repeater intact.
7717 - the start days in the repeater in the original entry will be shifted
7718 to past the last clone.
7719 I this way you can spell out a number of instances of a repeating task,
7720 and still retain the repeater to cover future instances of the task."
7721 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
7722 (let (beg end template task idprop
7723 shift-n shift-what doshift nmin nmax (n-no-remove -1))
7724 (if (not (and (integerp n) (> n 0)))
7725 (error "Invalid number of replications %s" n))
7726 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
7727 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
7728 shift)))
7729 (error "Invalid shift specification %s" shift))
7730 (when doshift
7731 (setq shift-n (string-to-number (match-string 1 shift))
7732 shift-what (cdr (assoc (match-string 2 shift)
7733 '(("d" . day) ("w" . week)
7734 ("m" . month) ("y" . year))))))
7735 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
7736 (setq nmin 1 nmax n)
7737 (org-back-to-heading t)
7738 (setq beg (point))
7739 (setq idprop (org-entry-get nil "ID"))
7740 (org-end-of-subtree t t)
7741 (or (bolp) (insert "\n"))
7742 (setq end (point))
7743 (setq template (buffer-substring beg end))
7744 (when (and doshift
7745 (string-match "<[^<>\n]+ \\+[0-9]+[dwmy][^<>\n]*>" template))
7746 (delete-region beg end)
7747 (setq end beg)
7748 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
7749 (goto-char end)
7750 (loop for n from nmin to nmax do
7751 ;; prepare clone
7752 (with-temp-buffer
7753 (insert template)
7754 (org-mode)
7755 (goto-char (point-min))
7756 (and idprop (if org-clone-delete-id
7757 (org-entry-delete nil "ID")
7758 (org-id-get-create t)))
7759 (while (re-search-forward org-property-start-re nil t)
7760 (org-remove-empty-drawer-at "PROPERTIES" (point)))
7761 (goto-char (point-min))
7762 (when doshift
7763 (while (re-search-forward org-ts-regexp-both nil t)
7764 (org-timestamp-change (* n shift-n) shift-what))
7765 (unless (= n n-no-remove)
7766 (goto-char (point-min))
7767 (while (re-search-forward org-ts-regexp nil t)
7768 (save-excursion
7769 (goto-char (match-beginning 0))
7770 (if (looking-at "<[^<>\n]+\\( +\\+[0-9]+[dwmy]\\)")
7771 (delete-region (match-beginning 1) (match-end 1)))))))
7772 (setq task (buffer-string)))
7773 (insert task))
7774 (goto-char beg)))
7776 ;;; Outline Sorting
7778 (defun org-sort (with-case)
7779 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
7780 Optional argument WITH-CASE means sort case-sensitively.
7781 With a double prefix argument, also remove duplicate entries."
7782 (interactive "P")
7783 (cond
7784 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
7785 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
7787 (org-call-with-arg 'org-sort-entries with-case))))
7789 (defun org-sort-remove-invisible (s)
7790 (remove-text-properties 0 (length s) org-rm-props s)
7791 (while (string-match org-bracket-link-regexp s)
7792 (setq s (replace-match (if (match-end 2)
7793 (match-string 3 s)
7794 (match-string 1 s)) t t s)))
7797 (defvar org-priority-regexp) ; defined later in the file
7799 (defvar org-after-sorting-entries-or-items-hook nil
7800 "Hook that is run after a bunch of entries or items have been sorted.
7801 When children are sorted, the cursor is in the parent line when this
7802 hook gets called. When a region or a plain list is sorted, the cursor
7803 will be in the first entry of the sorted region/list.")
7805 (defun org-sort-entries
7806 (&optional with-case sorting-type getkey-func compare-func property)
7807 "Sort entries on a certain level of an outline tree.
7808 If there is an active region, the entries in the region are sorted.
7809 Else, if the cursor is before the first entry, sort the top-level items.
7810 Else, the children of the entry at point are sorted.
7812 Sorting can be alphabetically, numerically, by date/time as given by
7813 a time stamp, by a property or by priority.
7815 The command prompts for the sorting type unless it has been given to the
7816 function through the SORTING-TYPE argument, which needs to be a character,
7817 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F). Here is the
7818 precise meaning of each character:
7820 n Numerically, by converting the beginning of the entry/item to a number.
7821 a Alphabetically, ignoring the TODO keyword and the priority, if any.
7822 t By date/time, either the first active time stamp in the entry, or, if
7823 none exist, by the first inactive one.
7824 s By the scheduled date/time.
7825 d By deadline date/time.
7826 c By creation time, which is assumed to be the first inactive time stamp
7827 at the beginning of a line.
7828 p By priority according to the cookie.
7829 r By the value of a property.
7831 Capital letters will reverse the sort order.
7833 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
7834 called with point at the beginning of the record. It must return either
7835 a string or a number that should serve as the sorting key for that record.
7837 Comparing entries ignores case by default. However, with an optional argument
7838 WITH-CASE, the sorting considers case as well."
7839 (interactive "P")
7840 (let ((case-func (if with-case 'identity 'downcase))
7841 start beg end stars re re2
7842 txt what tmp)
7843 ;; Find beginning and end of region to sort
7844 (cond
7845 ((org-region-active-p)
7846 ;; we will sort the region
7847 (setq end (region-end)
7848 what "region")
7849 (goto-char (region-beginning))
7850 (if (not (org-on-heading-p)) (outline-next-heading))
7851 (setq start (point)))
7852 ((or (org-on-heading-p)
7853 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
7854 ;; we will sort the children of the current headline
7855 (org-back-to-heading)
7856 (setq start (point)
7857 end (progn (org-end-of-subtree t t)
7858 (or (bolp) (insert "\n"))
7859 (org-back-over-empty-lines)
7860 (point))
7861 what "children")
7862 (goto-char start)
7863 (show-subtree)
7864 (outline-next-heading))
7866 ;; we will sort the top-level entries in this file
7867 (goto-char (point-min))
7868 (or (org-on-heading-p) (outline-next-heading))
7869 (setq start (point))
7870 (goto-char (point-max))
7871 (beginning-of-line 1)
7872 (when (looking-at ".*?\\S-")
7873 ;; File ends in a non-white line
7874 (end-of-line 1)
7875 (insert "\n"))
7876 (setq end (point-max))
7877 (setq what "top-level")
7878 (goto-char start)
7879 (show-all)))
7881 (setq beg (point))
7882 (if (>= beg end) (error "Nothing to sort"))
7884 (looking-at "\\(\\*+\\)")
7885 (setq stars (match-string 1)
7886 re (concat "^" (regexp-quote stars) " +")
7887 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
7888 txt (buffer-substring beg end))
7889 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
7890 (if (and (not (equal stars "*")) (string-match re2 txt))
7891 (error "Region to sort contains a level above the first entry"))
7893 (unless sorting-type
7894 (message
7895 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
7896 [t]ime [s]cheduled [d]eadline [c]reated
7897 A/N/T/S/D/C/P/O/F means reversed:"
7898 what)
7899 (setq sorting-type (read-char-exclusive))
7901 (and (= (downcase sorting-type) ?f)
7902 (setq getkey-func
7903 (org-icompleting-read "Sort using function: "
7904 obarray 'fboundp t nil nil))
7905 (setq getkey-func (intern getkey-func)))
7907 (and (= (downcase sorting-type) ?r)
7908 (setq property
7909 (org-icompleting-read "Property: "
7910 (mapcar 'list (org-buffer-property-keys t))
7911 nil t))))
7913 (message "Sorting entries...")
7915 (save-restriction
7916 (narrow-to-region start end)
7917 (let ((dcst (downcase sorting-type))
7918 (case-fold-search nil)
7919 (now (current-time)))
7920 (sort-subr
7921 (/= dcst sorting-type)
7922 ;; This function moves to the beginning character of the "record" to
7923 ;; be sorted.
7924 (lambda nil
7925 (if (re-search-forward re nil t)
7926 (goto-char (match-beginning 0))
7927 (goto-char (point-max))))
7928 ;; This function moves to the last character of the "record" being
7929 ;; sorted.
7930 (lambda nil
7931 (save-match-data
7932 (condition-case nil
7933 (outline-forward-same-level 1)
7934 (error
7935 (goto-char (point-max))))))
7936 ;; This function returns the value that gets sorted against.
7937 (lambda nil
7938 (cond
7939 ((= dcst ?n)
7940 (if (looking-at org-complex-heading-regexp)
7941 (string-to-number (match-string 4))
7942 nil))
7943 ((= dcst ?a)
7944 (if (looking-at org-complex-heading-regexp)
7945 (funcall case-func (match-string 4))
7946 nil))
7947 ((= dcst ?t)
7948 (let ((end (save-excursion (outline-next-heading) (point))))
7949 (if (or (re-search-forward org-ts-regexp end t)
7950 (re-search-forward org-ts-regexp-both end t))
7951 (org-time-string-to-seconds (match-string 0))
7952 (org-float-time now))))
7953 ((= dcst ?c)
7954 (let ((end (save-excursion (outline-next-heading) (point))))
7955 (if (re-search-forward
7956 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
7957 end t)
7958 (org-time-string-to-seconds (match-string 0))
7959 (org-float-time now))))
7960 ((= dcst ?s)
7961 (let ((end (save-excursion (outline-next-heading) (point))))
7962 (if (re-search-forward org-scheduled-time-regexp end t)
7963 (org-time-string-to-seconds (match-string 1))
7964 (org-float-time now))))
7965 ((= dcst ?d)
7966 (let ((end (save-excursion (outline-next-heading) (point))))
7967 (if (re-search-forward org-deadline-time-regexp end t)
7968 (org-time-string-to-seconds (match-string 1))
7969 (org-float-time now))))
7970 ((= dcst ?p)
7971 (if (re-search-forward org-priority-regexp (point-at-eol) t)
7972 (string-to-char (match-string 2))
7973 org-default-priority))
7974 ((= dcst ?r)
7975 (or (org-entry-get nil property) ""))
7976 ((= dcst ?o)
7977 (if (looking-at org-complex-heading-regexp)
7978 (- 9999 (length (member (match-string 2)
7979 org-todo-keywords-1)))))
7980 ((= dcst ?f)
7981 (if getkey-func
7982 (progn
7983 (setq tmp (funcall getkey-func))
7984 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
7985 tmp)
7986 (error "Invalid key function `%s'" getkey-func)))
7987 (t (error "Invalid sorting type `%c'" sorting-type))))
7989 (cond
7990 ((= dcst ?a) 'string<)
7991 ((= dcst ?f) compare-func)
7992 ((member dcst '(?p ?t ?s ?d ?c)) '<)
7993 (t nil)))))
7994 (run-hooks 'org-after-sorting-entries-or-items-hook)
7995 (message "Sorting entries...done")))
7997 (defun org-do-sort (table what &optional with-case sorting-type)
7998 "Sort TABLE of WHAT according to SORTING-TYPE.
7999 The user will be prompted for the SORTING-TYPE if the call to this
8000 function does not specify it. WHAT is only for the prompt, to indicate
8001 what is being sorted. The sorting key will be extracted from
8002 the car of the elements of the table.
8003 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8004 (unless sorting-type
8005 (message
8006 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
8007 what)
8008 (setq sorting-type (read-char-exclusive)))
8009 (let ((dcst (downcase sorting-type))
8010 extractfun comparefun)
8011 ;; Define the appropriate functions
8012 (cond
8013 ((= dcst ?n)
8014 (setq extractfun 'string-to-number
8015 comparefun (if (= dcst sorting-type) '< '>)))
8016 ((= dcst ?a)
8017 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8018 (lambda(x) (downcase (org-sort-remove-invisible x))))
8019 comparefun (if (= dcst sorting-type)
8020 'string<
8021 (lambda (a b) (and (not (string< a b))
8022 (not (string= a b)))))))
8023 ((= dcst ?t)
8024 (setq extractfun
8025 (lambda (x)
8026 (if (or (string-match org-ts-regexp x)
8027 (string-match org-ts-regexp-both x))
8028 (org-float-time
8029 (org-time-string-to-time (match-string 0 x)))
8031 comparefun (if (= dcst sorting-type) '< '>)))
8032 (t (error "Invalid sorting type `%c'" sorting-type)))
8034 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8035 table)
8036 (lambda (a b) (funcall comparefun (car a) (car b))))))
8039 ;;; The orgstruct minor mode
8041 ;; Define a minor mode which can be used in other modes in order to
8042 ;; integrate the org-mode structure editing commands.
8044 ;; This is really a hack, because the org-mode structure commands use
8045 ;; keys which normally belong to the major mode. Here is how it
8046 ;; works: The minor mode defines all the keys necessary to operate the
8047 ;; structure commands, but wraps the commands into a function which
8048 ;; tests if the cursor is currently at a headline or a plain list
8049 ;; item. If that is the case, the structure command is used,
8050 ;; temporarily setting many Org-mode variables like regular
8051 ;; expressions for filling etc. However, when any of those keys is
8052 ;; used at a different location, function uses `key-binding' to look
8053 ;; up if the key has an associated command in another currently active
8054 ;; keymap (minor modes, major mode, global), and executes that
8055 ;; command. There might be problems if any of the keys is otherwise
8056 ;; used as a prefix key.
8058 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
8059 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
8060 ;; addresses this by checking explicitly for both bindings.
8062 (defvar orgstruct-mode-map (make-sparse-keymap)
8063 "Keymap for the minor `orgstruct-mode'.")
8065 (defvar org-local-vars nil
8066 "List of local variables, for use by `orgstruct-mode'.")
8068 ;;;###autoload
8069 (define-minor-mode orgstruct-mode
8070 "Toggle the minor mode `orgstruct-mode'.
8071 This mode is for using Org-mode structure commands in other
8072 modes. The following keys behave as if Org-mode were active, if
8073 the cursor is on a headline, or on a plain list item (both as
8074 defined by Org-mode).
8076 M-up Move entry/item up
8077 M-down Move entry/item down
8078 M-left Promote
8079 M-right Demote
8080 M-S-up Move entry/item up
8081 M-S-down Move entry/item down
8082 M-S-left Promote subtree
8083 M-S-right Demote subtree
8084 M-q Fill paragraph and items like in Org-mode
8085 C-c ^ Sort entries
8086 C-c - Cycle list bullet
8087 TAB Cycle item visibility
8088 M-RET Insert new heading/item
8089 S-M-RET Insert new TODO heading / Checkbox item
8090 C-c C-c Set tags / toggle checkbox"
8091 nil " OrgStruct" nil
8092 (org-load-modules-maybe)
8093 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
8095 ;;;###autoload
8096 (defun turn-on-orgstruct ()
8097 "Unconditionally turn on `orgstruct-mode'."
8098 (orgstruct-mode 1))
8100 (defun orgstruct++-mode (&optional arg)
8101 "Toggle `orgstruct-mode', the enhanced version of it.
8102 In addition to setting orgstruct-mode, this also exports all indentation
8103 and autofilling variables from org-mode into the buffer. It will also
8104 recognize item context in multiline items.
8105 Note that turning off orgstruct-mode will *not* remove the
8106 indentation/paragraph settings. This can only be done by refreshing the
8107 major mode, for example with \\[normal-mode]."
8108 (interactive "P")
8109 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8110 (if (< arg 1)
8111 (orgstruct-mode -1)
8112 (orgstruct-mode 1)
8113 (let (var val)
8114 (mapc
8115 (lambda (x)
8116 (when (string-match
8117 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
8118 (symbol-name (car x)))
8119 (setq var (car x) val (nth 1 x))
8120 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8121 org-local-vars)
8122 (org-set-local 'orgstruct-is-++ t))))
8124 (defvar orgstruct-is-++ nil
8125 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8126 (make-variable-buffer-local 'orgstruct-is-++)
8128 ;;;###autoload
8129 (defun turn-on-orgstruct++ ()
8130 "Unconditionally turn on `orgstruct++-mode'."
8131 (orgstruct++-mode 1))
8133 (defun orgstruct-error ()
8134 "Error when there is no default binding for a structure key."
8135 (interactive)
8136 (error "This key has no function outside structure elements"))
8138 (defun orgstruct-setup ()
8139 "Setup orgstruct keymaps."
8140 (let ((nfunc 0)
8141 (bindings
8142 (list
8143 '([(meta up)] org-metaup)
8144 '([(meta down)] org-metadown)
8145 '([(meta left)] org-metaleft)
8146 '([(meta right)] org-metaright)
8147 '([(meta shift up)] org-shiftmetaup)
8148 '([(meta shift down)] org-shiftmetadown)
8149 '([(meta shift left)] org-shiftmetaleft)
8150 '([(meta shift right)] org-shiftmetaright)
8151 '([?\e (up)] org-metaup)
8152 '([?\e (down)] org-metadown)
8153 '([?\e (left)] org-metaleft)
8154 '([?\e (right)] org-metaright)
8155 '([?\e (shift up)] org-shiftmetaup)
8156 '([?\e (shift down)] org-shiftmetadown)
8157 '([?\e (shift left)] org-shiftmetaleft)
8158 '([?\e (shift right)] org-shiftmetaright)
8159 '([(shift up)] org-shiftup)
8160 '([(shift down)] org-shiftdown)
8161 '([(shift left)] org-shiftleft)
8162 '([(shift right)] org-shiftright)
8163 '("\C-c\C-c" org-ctrl-c-ctrl-c)
8164 '("\M-q" fill-paragraph)
8165 '("\C-c^" org-sort)
8166 '("\C-c-" org-cycle-list-bullet)))
8167 elt key fun cmd)
8168 (while (setq elt (pop bindings))
8169 (setq nfunc (1+ nfunc))
8170 (setq key (org-key (car elt))
8171 fun (nth 1 elt)
8172 cmd (orgstruct-make-binding fun nfunc key))
8173 (org-defkey orgstruct-mode-map key cmd))
8175 ;; Special treatment needed for TAB and RET
8176 (org-defkey orgstruct-mode-map [(tab)]
8177 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
8178 (org-defkey orgstruct-mode-map "\C-i"
8179 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
8181 (org-defkey orgstruct-mode-map "\M-\C-m"
8182 (orgstruct-make-binding 'org-insert-heading 105
8183 "\M-\C-m" [(meta return)]))
8184 (org-defkey orgstruct-mode-map [(meta return)]
8185 (orgstruct-make-binding 'org-insert-heading 106
8186 [(meta return)] "\M-\C-m"))
8188 (org-defkey orgstruct-mode-map [(shift meta return)]
8189 (orgstruct-make-binding 'org-insert-todo-heading 107
8190 [(meta return)] "\M-\C-m"))
8192 (org-defkey orgstruct-mode-map "\e\C-m"
8193 (orgstruct-make-binding 'org-insert-heading 108
8194 "\e\C-m" [?\e (return)]))
8195 (org-defkey orgstruct-mode-map [?\e (return)]
8196 (orgstruct-make-binding 'org-insert-heading 109
8197 [?\e (return)] "\e\C-m"))
8198 (org-defkey orgstruct-mode-map [?\e (shift return)]
8199 (orgstruct-make-binding 'org-insert-todo-heading 110
8200 [?\e (return)] "\e\C-m"))
8202 (unless org-local-vars
8203 (setq org-local-vars (org-get-local-variables)))
8207 (defun orgstruct-make-binding (fun n &rest keys)
8208 "Create a function for binding in the structure minor mode.
8209 FUN is the command to call inside a table. N is used to create a unique
8210 command name. KEYS are keys that should be checked in for a command
8211 to execute outside of tables."
8212 (eval
8213 (list 'defun
8214 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
8215 '(arg)
8216 (concat "In Structure, run `" (symbol-name fun) "'.\n"
8217 "Outside of structure, run the binding of `"
8218 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
8219 "'.")
8220 '(interactive "p")
8221 (list 'if
8222 `(org-context-p 'headline 'item
8223 (and orgstruct-is-++
8224 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
8225 'item-body))
8226 (list 'org-run-like-in-org-mode (list 'quote fun))
8227 (list 'let '(orgstruct-mode)
8228 (list 'call-interactively
8229 (append '(or)
8230 (mapcar (lambda (k)
8231 (list 'key-binding k))
8232 keys)
8233 '('orgstruct-error))))))))
8235 (defun org-context-p (&rest contexts)
8236 "Check if local context is any of CONTEXTS.
8237 Possible values in the list of contexts are `table', `headline', and `item'."
8238 (let ((pos (point)))
8239 (goto-char (point-at-bol))
8240 (prog1 (or (and (memq 'table contexts)
8241 (looking-at "[ \t]*|"))
8242 (and (memq 'headline contexts)
8243 ;;????????? (looking-at "\\*+"))
8244 (looking-at outline-regexp))
8245 (and (memq 'item contexts)
8246 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
8247 (and (memq 'item-body contexts)
8248 (org-in-item-p)))
8249 (goto-char pos))))
8251 (defun org-get-local-variables ()
8252 "Return a list of all local variables in an org-mode buffer."
8253 (let (varlist)
8254 (with-current-buffer (get-buffer-create "*Org tmp*")
8255 (erase-buffer)
8256 (org-mode)
8257 (setq varlist (buffer-local-variables)))
8258 (kill-buffer "*Org tmp*")
8259 (delq nil
8260 (mapcar
8261 (lambda (x)
8262 (setq x
8263 (if (symbolp x)
8264 (list x)
8265 (list (car x) (list 'quote (cdr x)))))
8266 (if (string-match
8267 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
8268 (symbol-name (car x)))
8269 x nil))
8270 varlist))))
8272 (defun org-clone-local-variables (from-buffer &optional regexp)
8273 "Clone local variables from FROM-BUFFER.
8274 Optional argument REGEXP selects variables to clone."
8275 (mapc
8276 (lambda (pair)
8277 (and (symbolp (car pair))
8278 (or (null regexp)
8279 (string-match regexp (symbol-name (car pair))))
8280 (set (make-local-variable (car pair))
8281 (cdr pair))))
8282 (buffer-local-variables from-buffer)))
8284 ;;;###autoload
8285 (defun org-run-like-in-org-mode (cmd)
8286 "Run a command, pretending that the current buffer is in Org-mode.
8287 This will temporarily bind local variables that are typically bound in
8288 Org-mode to the values they have in Org-mode, and then interactively
8289 call CMD."
8290 (org-load-modules-maybe)
8291 (unless org-local-vars
8292 (setq org-local-vars (org-get-local-variables)))
8293 (eval (list 'let org-local-vars
8294 (list 'call-interactively (list 'quote cmd)))))
8296 ;;;; Archiving
8298 (defun org-get-category (&optional pos force-refresh)
8299 "Get the category applying to position POS."
8300 (if force-refresh (org-refresh-category-properties))
8301 (let ((pos (or pos (point))))
8302 (or (get-text-property pos 'org-category)
8303 (progn (org-refresh-category-properties)
8304 (get-text-property pos 'org-category)))))
8306 (defun org-refresh-category-properties ()
8307 "Refresh category text properties in the buffer."
8308 (let ((def-cat (cond
8309 ((null org-category)
8310 (if buffer-file-name
8311 (file-name-sans-extension
8312 (file-name-nondirectory buffer-file-name))
8313 "???"))
8314 ((symbolp org-category) (symbol-name org-category))
8315 (t org-category)))
8316 beg end cat pos optionp)
8317 (org-unmodified
8318 (save-excursion
8319 (save-restriction
8320 (widen)
8321 (goto-char (point-min))
8322 (put-text-property (point) (point-max) 'org-category def-cat)
8323 (while (re-search-forward
8324 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8325 (setq pos (match-end 0)
8326 optionp (equal (char-after (match-beginning 0)) ?#)
8327 cat (org-trim (match-string 2)))
8328 (if optionp
8329 (setq beg (point-at-bol) end (point-max))
8330 (org-back-to-heading t)
8331 (setq beg (point) end (org-end-of-subtree t t)))
8332 (put-text-property beg end 'org-category cat)
8333 (goto-char pos)))))))
8336 ;;;; Link Stuff
8338 ;;; Link abbreviations
8340 (defun org-link-expand-abbrev (link)
8341 "Apply replacements as defined in `org-link-abbrev-alist."
8342 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
8343 (let* ((key (match-string 1 link))
8344 (as (or (assoc key org-link-abbrev-alist-local)
8345 (assoc key org-link-abbrev-alist)))
8346 (tag (and (match-end 2) (match-string 3 link)))
8347 rpl)
8348 (if (not as)
8349 link
8350 (setq rpl (cdr as))
8351 (cond
8352 ((symbolp rpl) (funcall rpl tag))
8353 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
8354 ((string-match "%h" rpl)
8355 (replace-match (url-hexify-string (or tag "")) t t rpl))
8356 (t (concat rpl tag)))))
8357 link))
8359 ;;; Storing and inserting links
8361 (defvar org-insert-link-history nil
8362 "Minibuffer history for links inserted with `org-insert-link'.")
8364 (defvar org-stored-links nil
8365 "Contains the links stored with `org-store-link'.")
8367 (defvar org-store-link-plist nil
8368 "Plist with info about the most recently link created with `org-store-link'.")
8370 (defvar org-link-protocols nil
8371 "Link protocols added to Org-mode using `org-add-link-type'.")
8373 (defvar org-store-link-functions nil
8374 "List of functions that are called to create and store a link.
8375 Each function will be called in turn until one returns a non-nil
8376 value. Each function should check if it is responsible for creating
8377 this link (for example by looking at the major mode).
8378 If not, it must exit and return nil.
8379 If yes, it should return a non-nil value after a calling
8380 `org-store-link-props' with a list of properties and values.
8381 Special properties are:
8383 :type The link prefix, like \"http\". This must be given.
8384 :link The link, like \"http://www.astro.uva.nl/~dominik\".
8385 This is obligatory as well.
8386 :description Optional default description for the second pair
8387 of brackets in an Org-mode link. The user can still change
8388 this when inserting this link into an Org-mode buffer.
8390 In addition to these, any additional properties can be specified
8391 and then used in remember templates.")
8393 (defun org-add-link-type (type &optional follow export)
8394 "Add TYPE to the list of `org-link-types'.
8395 Re-compute all regular expressions depending on `org-link-types'
8397 FOLLOW and EXPORT are two functions.
8399 FOLLOW should take the link path as the single argument and do whatever
8400 is necessary to follow the link, for example find a file or display
8401 a mail message.
8403 EXPORT should format the link path for export to one of the export formats.
8404 It should be a function accepting three arguments:
8406 path the path of the link, the text after the prefix (like \"http:\")
8407 desc the description of the link, if any, or a description added by
8408 org-export-normalize-links if there is none
8409 format the export format, a symbol like `html' or `latex' or `ascii'..
8411 The function may use the FORMAT information to return different values
8412 depending on the format. The return value will be put literally into
8413 the exported file. If the return value is nil, this means Org should
8414 do what it normally does with links which do not have EXPORT defined.
8416 Org-mode has a built-in default for exporting links. If you are happy with
8417 this default, there is no need to define an export function for the link
8418 type. For a simple example of an export function, see `org-bbdb.el'."
8419 (add-to-list 'org-link-types type t)
8420 (org-make-link-regexps)
8421 (if (assoc type org-link-protocols)
8422 (setcdr (assoc type org-link-protocols) (list follow export))
8423 (push (list type follow export) org-link-protocols)))
8425 (defvar org-agenda-buffer-name)
8427 ;;;###autoload
8428 (defun org-store-link (arg)
8429 "\\<org-mode-map>Store an org-link to the current location.
8430 This link is added to `org-stored-links' and can later be inserted
8431 into an org-buffer with \\[org-insert-link].
8433 For some link types, a prefix arg is interpreted:
8434 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
8435 For file links, arg negates `org-context-in-file-links'."
8436 (interactive "P")
8437 (org-load-modules-maybe)
8438 (setq org-store-link-plist nil) ; reset
8439 (org-with-limited-levels
8440 (let (link cpltxt desc description search txt custom-id agenda-link)
8441 (cond
8443 ((run-hook-with-args-until-success 'org-store-link-functions)
8444 (setq link (plist-get org-store-link-plist :link)
8445 desc (or (plist-get org-store-link-plist :description) link)))
8447 ((equal (buffer-name) "*Org Edit Src Example*")
8448 (let (label gc)
8449 (while (or (not label)
8450 (save-excursion
8451 (save-restriction
8452 (widen)
8453 (goto-char (point-min))
8454 (re-search-forward
8455 (regexp-quote (format org-coderef-label-format label))
8456 nil t))))
8457 (when label (message "Label exists already") (sit-for 2))
8458 (setq label (read-string "Code line label: " label)))
8459 (end-of-line 1)
8460 (setq link (format org-coderef-label-format label))
8461 (setq gc (- 79 (length link)))
8462 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
8463 (insert link)
8464 (setq link (concat "(" label ")") desc nil)))
8466 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
8467 ;; We are in the agenda, link to referenced location
8468 (let ((m (or (get-text-property (point) 'org-hd-marker)
8469 (get-text-property (point) 'org-marker))))
8470 (when m
8471 (org-with-point-at m
8472 (setq agenda-link
8473 (if (interactive-p)
8474 (call-interactively 'org-store-link)
8475 (org-store-link nil)))))))
8477 ((eq major-mode 'calendar-mode)
8478 (let ((cd (calendar-cursor-to-date)))
8479 (setq link
8480 (format-time-string
8481 (car org-time-stamp-formats)
8482 (apply 'encode-time
8483 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
8484 nil nil nil))))
8485 (org-store-link-props :type "calendar" :date cd)))
8487 ((eq major-mode 'w3-mode)
8488 (setq cpltxt (if (and (buffer-name)
8489 (not (string-match "Untitled" (buffer-name))))
8490 (buffer-name)
8491 (url-view-url t))
8492 link (org-make-link (url-view-url t)))
8493 (org-store-link-props :type "w3" :url (url-view-url t)))
8495 ((eq major-mode 'w3m-mode)
8496 (setq cpltxt (or w3m-current-title w3m-current-url)
8497 link (org-make-link w3m-current-url))
8498 (org-store-link-props :type "w3m" :url (url-view-url t)))
8500 ((setq search (run-hook-with-args-until-success
8501 'org-create-file-search-functions))
8502 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
8503 "::" search))
8504 (setq cpltxt (or description link)))
8506 ((eq major-mode 'image-mode)
8507 (setq cpltxt (concat "file:"
8508 (abbreviate-file-name buffer-file-name))
8509 link (org-make-link cpltxt))
8510 (org-store-link-props :type "image" :file buffer-file-name))
8512 ((eq major-mode 'dired-mode)
8513 ;; link to the file in the current line
8514 (let ((file (dired-get-filename nil t)))
8515 (setq file (if file
8516 (abbreviate-file-name
8517 (expand-file-name (dired-get-filename nil t)))
8518 ;; otherwise, no file so use current directory.
8519 default-directory))
8520 (setq cpltxt (concat "file:" file)
8521 link (org-make-link cpltxt))))
8523 ((and (buffer-file-name (buffer-base-buffer)) (org-mode-p))
8524 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
8525 (cond
8526 ((org-in-regexp "<<\\(.*?\\)>>")
8527 (setq cpltxt
8528 (concat "file:"
8529 (abbreviate-file-name
8530 (buffer-file-name (buffer-base-buffer)))
8531 "::" (match-string 1))
8532 link (org-make-link cpltxt)))
8533 ((and (featurep 'org-id)
8534 (or (eq org-link-to-org-use-id t)
8535 (and (eq org-link-to-org-use-id 'create-if-interactive)
8536 (interactive-p))
8537 (and (eq org-link-to-org-use-id 'create-if-interactive-and-no-custom-id)
8538 (interactive-p)
8539 (not custom-id))
8540 (and org-link-to-org-use-id
8541 (org-entry-get nil "ID"))))
8542 ;; We can make a link using the ID.
8543 (setq link (condition-case nil
8544 (prog1 (org-id-store-link)
8545 (setq desc (plist-get org-store-link-plist
8546 :description)))
8547 (error
8548 ;; probably before first headline, link to file only
8549 (concat "file:"
8550 (abbreviate-file-name
8551 (buffer-file-name (buffer-base-buffer))))))))
8553 ;; Just link to current headline
8554 (setq cpltxt (concat "file:"
8555 (abbreviate-file-name
8556 (buffer-file-name (buffer-base-buffer)))))
8557 ;; Add a context search string
8558 (when (org-xor org-context-in-file-links arg)
8559 (setq txt (cond
8560 ((org-on-heading-p) nil)
8561 ((org-region-active-p)
8562 (buffer-substring (region-beginning) (region-end)))
8563 (t nil)))
8564 (when (or (null txt) (string-match "\\S-" txt))
8565 (setq cpltxt
8566 (concat cpltxt "::"
8567 (condition-case nil
8568 (org-make-org-heading-search-string txt)
8569 (error "")))
8570 desc (or (nth 4 (ignore-errors
8571 (org-heading-components))) "NONE"))))
8572 (if (string-match "::\\'" cpltxt)
8573 (setq cpltxt (substring cpltxt 0 -2)))
8574 (setq link (org-make-link cpltxt)))))
8576 ((buffer-file-name (buffer-base-buffer))
8577 ;; Just link to this file here.
8578 (setq cpltxt (concat "file:"
8579 (abbreviate-file-name
8580 (buffer-file-name (buffer-base-buffer)))))
8581 ;; Add a context string
8582 (when (org-xor org-context-in-file-links arg)
8583 (setq txt (if (org-region-active-p)
8584 (buffer-substring (region-beginning) (region-end))
8585 (buffer-substring (point-at-bol) (point-at-eol))))
8586 ;; Only use search option if there is some text.
8587 (when (string-match "\\S-" txt)
8588 (setq cpltxt
8589 (concat cpltxt "::" (org-make-org-heading-search-string txt))
8590 desc "NONE")))
8591 (setq link (org-make-link cpltxt)))
8593 ((interactive-p)
8594 (error "Cannot link to a buffer which is not visiting a file"))
8596 (t (setq link nil)))
8598 (if (consp link) (setq cpltxt (car link) link (cdr link)))
8599 (setq link (or link cpltxt)
8600 desc (or desc cpltxt))
8601 (if (equal desc "NONE") (setq desc nil))
8603 (if (and (or (interactive-p) executing-kbd-macro) link)
8604 (progn
8605 (setq org-stored-links
8606 (cons (list link desc) org-stored-links))
8607 (message "Stored: %s" (or desc link))
8608 (when custom-id
8609 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
8610 "::#" custom-id))
8611 (setq org-stored-links
8612 (cons (list link desc) org-stored-links))))
8613 (or agenda-link (and link (org-make-link-string link desc)))))))
8615 (defun org-store-link-props (&rest plist)
8616 "Store link properties, extract names and addresses."
8617 (let (x adr)
8618 (when (setq x (plist-get plist :from))
8619 (setq adr (mail-extract-address-components x))
8620 (setq plist (plist-put plist :fromname (car adr)))
8621 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
8622 (when (setq x (plist-get plist :to))
8623 (setq adr (mail-extract-address-components x))
8624 (setq plist (plist-put plist :toname (car adr)))
8625 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
8626 (let ((from (plist-get plist :from))
8627 (to (plist-get plist :to)))
8628 (when (and from to org-from-is-user-regexp)
8629 (setq plist
8630 (plist-put plist :fromto
8631 (if (string-match org-from-is-user-regexp from)
8632 (concat "to %t")
8633 (concat "from %f"))))))
8634 (setq org-store-link-plist plist))
8636 (defun org-add-link-props (&rest plist)
8637 "Add these properties to the link property list."
8638 (let (key value)
8639 (while plist
8640 (setq key (pop plist) value (pop plist))
8641 (setq org-store-link-plist
8642 (plist-put org-store-link-plist key value)))))
8644 (defun org-email-link-description (&optional fmt)
8645 "Return the description part of an email link.
8646 This takes information from `org-store-link-plist' and formats it
8647 according to FMT (default from `org-email-link-description-format')."
8648 (setq fmt (or fmt org-email-link-description-format))
8649 (let* ((p org-store-link-plist)
8650 (to (plist-get p :toaddress))
8651 (from (plist-get p :fromaddress))
8652 (table
8653 (list
8654 (cons "%c" (plist-get p :fromto))
8655 (cons "%F" (plist-get p :from))
8656 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
8657 (cons "%T" (plist-get p :to))
8658 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
8659 (cons "%s" (plist-get p :subject))
8660 (cons "%d" (plist-get p :date))
8661 (cons "%m" (plist-get p :message-id)))))
8662 (when (string-match "%c" fmt)
8663 ;; Check if the user wrote this message
8664 (if (and org-from-is-user-regexp from to
8665 (save-match-data (string-match org-from-is-user-regexp from)))
8666 (setq fmt (replace-match "to %t" t t fmt))
8667 (setq fmt (replace-match "from %f" t t fmt))))
8668 (org-replace-escapes fmt table)))
8670 (defun org-make-org-heading-search-string (&optional string heading)
8671 "Make search string for STRING or current headline."
8672 (interactive)
8673 (let ((s (or string (org-get-heading)))
8674 (lines org-context-in-file-links))
8675 (unless (and string (not heading))
8676 ;; We are using a headline, clean up garbage in there.
8677 (if (string-match org-todo-regexp s)
8678 (setq s (replace-match "" t t s)))
8679 (if (string-match (org-re ":[[:alnum:]_@#%:]+:[ \t]*$") s)
8680 (setq s (replace-match "" t t s)))
8681 (setq s (org-trim s))
8682 (if (string-match (concat "^\\(" org-quote-string "\\|"
8683 org-comment-string "\\)") s)
8684 (setq s (replace-match "" t t s)))
8685 (while (string-match org-ts-regexp s)
8686 (setq s (replace-match "" t t s))))
8687 (or string (setq s (concat "*" s))) ; Add * for headlines
8688 (when (and string (integerp lines) (> lines 0))
8689 (let ((slines (org-split-string s "\n")))
8690 (when (< lines (length slines))
8691 (setq s (mapconcat
8692 'identity
8693 (reverse (nthcdr (- (length slines) lines)
8694 (reverse slines))) "\n")))))
8695 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
8697 (defun org-make-link (&rest strings)
8698 "Concatenate STRINGS."
8699 (apply 'concat strings))
8701 (defun org-make-link-string (link &optional description)
8702 "Make a link with brackets, consisting of LINK and DESCRIPTION."
8703 (unless (string-match "\\S-" link)
8704 (error "Empty link"))
8705 (when (and description
8706 (stringp description)
8707 (not (string-match "\\S-" description)))
8708 (setq description nil))
8709 (when (stringp description)
8710 ;; Remove brackets from the description, they are fatal.
8711 (while (string-match "\\[" description)
8712 (setq description (replace-match "{" t t description)))
8713 (while (string-match "\\]" description)
8714 (setq description (replace-match "}" t t description))))
8715 (when (equal (org-link-escape link) description)
8716 ;; No description needed, it is identical
8717 (setq description nil))
8718 (when (and (not description)
8719 (not (equal link (org-link-escape link))))
8720 (setq description (org-extract-attributes link)))
8721 (setq link (if (string-match org-link-types-re link)
8722 (concat (match-string 1 link)
8723 (org-link-escape (substring link (match-end 1))))
8724 (org-link-escape link)))
8725 (concat "[[" link "]"
8726 (if description (concat "[" description "]") "")
8727 "]"))
8729 (defconst org-link-escape-chars
8730 '(?\ ?\[ ?\] ?\; ?\= ?\+)
8731 "List of characters that should be escaped in link.
8732 This is the list that is used for internal purposes.")
8734 (defvar org-url-encoding-use-url-hexify nil)
8736 (defconst org-link-escape-chars-browser
8737 '(?\ )
8738 "List of escapes for characters that are problematic in links.
8739 This is the list that is used before handing over to the browser.")
8741 (defun org-link-escape (text &optional table merge)
8742 "Return percent escaped representation of TEXT.
8743 TEXT is a string with the text to escape.
8744 Optional argument TABLE is a list with characters that should be
8745 escaped. When nil, `org-link-escape-chars' is used.
8746 If optional argument MERGE is set, merge TABLE into
8747 `org-link-escape-chars'."
8748 (if (and org-url-encoding-use-url-hexify (not table))
8749 (url-hexify-string text)
8750 (cond
8751 ((and table merge)
8752 (mapc (lambda (defchr)
8753 (unless (member defchr table)
8754 (setq table (cons defchr table)))) org-link-escape-chars))
8755 ((null table)
8756 (setq table org-link-escape-chars)))
8757 (mapconcat
8758 (lambda (char)
8759 (if (or (member char table)
8760 (< char 32) (= char 37) (> char 126))
8761 (mapconcat (lambda (sequence-element)
8762 (format "%%%.2X" sequence-element))
8763 (or (encode-coding-char char 'utf-8)
8764 (error "Unable to percent escape character: %s"
8765 (char-to-string char))) "")
8766 (char-to-string char))) text "")))
8768 (defun org-link-unescape (str)
8769 "Unhex hexified unicode strings as returned from the JavaScript function
8770 encodeURIComponent. E.g. `%C3%B6' is the german Umlaut `ö'."
8771 (unless (and (null str) (string= "" str))
8772 (let ((pos 0) (case-fold-search t) unhexed)
8773 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
8774 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
8775 (setq str (replace-match unhexed t t str))
8776 (setq pos (+ pos (length unhexed))))))
8777 str)
8779 (defun org-link-unescape-compound (hex)
8780 "Unhexify unicode hex-chars. E.g. `%C3%B6' is the German Umlaut `ö'.
8781 Note: this function also decodes single byte encodings like
8782 `%E1' (\"á\") if not followed by another `%[A-F0-9]{2}' group."
8783 (save-match-data
8784 (let* ((bytes (cdr (split-string hex "%")))
8785 (ret "")
8786 (eat 0)
8787 (sum 0))
8788 (while bytes
8789 (let* ((val (string-to-number (pop bytes) 16))
8790 (shift-xor
8791 (if (= 0 eat)
8792 (cond
8793 ((>= val 252) (cons 6 252))
8794 ((>= val 248) (cons 5 248))
8795 ((>= val 240) (cons 4 240))
8796 ((>= val 224) (cons 3 224))
8797 ((>= val 192) (cons 2 192))
8798 (t (cons 0 0)))
8799 (cons 6 128))))
8800 (if (>= val 192) (setq eat (car shift-xor)))
8801 (setq val (logxor val (cdr shift-xor)))
8802 (setq sum (+ (lsh sum (car shift-xor)) val))
8803 (if (> eat 0) (setq eat (- eat 1)))
8804 (cond
8805 ((= 0 eat) ;multi byte
8806 (setq ret (concat ret (org-char-to-string sum)))
8807 (setq sum 0))
8808 ((not bytes) ; single byte(s)
8809 (setq ret (org-link-unescape-single-byte-sequence hex))))
8810 )) ;; end (while bytes
8811 ret )))
8813 (defun org-link-unescape-single-byte-sequence (hex)
8814 "Unhexify hex-encoded single byte character sequences."
8815 (mapconcat (lambda (byte)
8816 (char-to-string (string-to-number byte 16)))
8817 (cdr (split-string hex "%")) ""))
8819 (defun org-xor (a b)
8820 "Exclusive or."
8821 (if a (not b) b))
8823 (defun org-fixup-message-id-for-http (s)
8824 "Replace special characters in a message id, so it can be used in an http query."
8825 (when (string-match "%" s)
8826 (setq s (mapconcat (lambda (c)
8827 (if (eq c ?%)
8828 "%25"
8829 (char-to-string c)))
8830 s "")))
8831 (while (string-match "<" s)
8832 (setq s (replace-match "%3C" t t s)))
8833 (while (string-match ">" s)
8834 (setq s (replace-match "%3E" t t s)))
8835 (while (string-match "@" s)
8836 (setq s (replace-match "%40" t t s)))
8839 ;;;###autoload
8840 (defun org-insert-link-global ()
8841 "Insert a link like Org-mode does.
8842 This command can be called in any mode to insert a link in Org-mode syntax."
8843 (interactive)
8844 (org-load-modules-maybe)
8845 (org-run-like-in-org-mode 'org-insert-link))
8847 (defun org-insert-link (&optional complete-file link-location)
8848 "Insert a link. At the prompt, enter the link.
8850 Completion can be used to insert any of the link protocol prefixes like
8851 http or ftp in use.
8853 The history can be used to select a link previously stored with
8854 `org-store-link'. When the empty string is entered (i.e. if you just
8855 press RET at the prompt), the link defaults to the most recently
8856 stored link. As SPC triggers completion in the minibuffer, you need to
8857 use M-SPC or C-q SPC to force the insertion of a space character.
8859 You will also be prompted for a description, and if one is given, it will
8860 be displayed in the buffer instead of the link.
8862 If there is already a link at point, this command will allow you to edit link
8863 and description parts.
8865 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
8866 be selected using completion. The path to the file will be relative to the
8867 current directory if the file is in the current directory or a subdirectory.
8868 Otherwise, the link will be the absolute path as completed in the minibuffer
8869 \(i.e. normally ~/path/to/file). You can configure this behavior using the
8870 option `org-link-file-path-type'.
8872 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
8873 the current directory or below.
8875 With three \\[universal-argument] prefixes, negate the meaning of
8876 `org-keep-stored-link-after-insertion'.
8878 If `org-make-link-description-function' is non-nil, this function will be
8879 called with the link target, and the result will be the default
8880 link description.
8882 If the LINK-LOCATION parameter is non-nil, this value will be
8883 used as the link location instead of reading one interactively."
8884 (interactive "P")
8885 (let* ((wcf (current-window-configuration))
8886 (region (if (org-region-active-p)
8887 (buffer-substring (region-beginning) (region-end))))
8888 (remove (and region (list (region-beginning) (region-end))))
8889 (desc region)
8890 tmphist ; byte-compile incorrectly complains about this
8891 (link link-location)
8892 entry file all-prefixes)
8893 (cond
8894 (link-location) ; specified by arg, just use it.
8895 ((org-in-regexp org-bracket-link-regexp 1)
8896 ;; We do have a link at point, and we are going to edit it.
8897 (setq remove (list (match-beginning 0) (match-end 0)))
8898 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
8899 (setq link (read-string "Link: "
8900 (org-link-unescape
8901 (org-match-string-no-properties 1)))))
8902 ((or (org-in-regexp org-angle-link-re)
8903 (org-in-regexp org-plain-link-re))
8904 ;; Convert to bracket link
8905 (setq remove (list (match-beginning 0) (match-end 0))
8906 link (read-string "Link: "
8907 (org-remove-angle-brackets (match-string 0)))))
8908 ((member complete-file '((4) (16)))
8909 ;; Completing read for file names.
8910 (setq link (org-file-complete-link complete-file)))
8912 ;; Read link, with completion for stored links.
8913 (with-output-to-temp-buffer "*Org Links*"
8914 (princ "Insert a link.
8915 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
8916 (when org-stored-links
8917 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
8918 (princ (mapconcat
8919 (lambda (x)
8920 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
8921 (reverse org-stored-links) "\n"))))
8922 (let ((cw (selected-window)))
8923 (select-window (get-buffer-window "*Org Links*" 'visible))
8924 (setq truncate-lines t)
8925 (unless (pos-visible-in-window-p (point-max))
8926 (org-fit-window-to-buffer))
8927 (and (window-live-p cw) (select-window cw)))
8928 ;; Fake a link history, containing the stored links.
8929 (setq tmphist (append (mapcar 'car org-stored-links)
8930 org-insert-link-history))
8931 (setq all-prefixes (append (mapcar 'car org-link-abbrev-alist-local)
8932 (mapcar 'car org-link-abbrev-alist)
8933 org-link-types))
8934 (unwind-protect
8935 (progn
8936 (setq link
8937 (let ((org-completion-use-ido nil)
8938 (org-completion-use-iswitchb nil))
8939 (org-completing-read
8940 "Link: "
8941 (append
8942 (mapcar (lambda (x) (list (concat x ":")))
8943 all-prefixes)
8944 (mapcar 'car org-stored-links))
8945 nil nil nil
8946 'tmphist
8947 (car (car org-stored-links)))))
8948 (if (not (string-match "\\S-" link))
8949 (error "No link selected"))
8950 (if (or (member link all-prefixes)
8951 (and (equal ":" (substring link -1))
8952 (member (substring link 0 -1) all-prefixes)
8953 (setq link (substring link 0 -1))))
8954 (setq link (org-link-try-special-completion link))))
8955 (set-window-configuration wcf)
8956 (kill-buffer "*Org Links*"))
8957 (setq entry (assoc link org-stored-links))
8958 (or entry (push link org-insert-link-history))
8959 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
8960 (not org-keep-stored-link-after-insertion))
8961 (setq org-stored-links (delq (assoc link org-stored-links)
8962 org-stored-links)))
8963 (setq desc (or desc (nth 1 entry)))))
8965 (if (string-match org-plain-link-re link)
8966 ;; URL-like link, normalize the use of angular brackets.
8967 (setq link (org-make-link (org-remove-angle-brackets link))))
8969 ;; Check if we are linking to the current file with a search option
8970 ;; If yes, simplify the link by using only the search option.
8971 (when (and buffer-file-name
8972 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
8973 (let* ((path (match-string 1 link))
8974 (case-fold-search nil)
8975 (search (match-string 2 link)))
8976 (save-match-data
8977 (if (equal (file-truename buffer-file-name) (file-truename path))
8978 ;; We are linking to this same file, with a search option
8979 (setq link search)))))
8981 ;; Check if we can/should use a relative path. If yes, simplify the link
8982 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
8983 (let* ((type (match-string 1 link))
8984 (path (match-string 2 link))
8985 (origpath path)
8986 (case-fold-search nil))
8987 (cond
8988 ((or (eq org-link-file-path-type 'absolute)
8989 (equal complete-file '(16)))
8990 (setq path (abbreviate-file-name (expand-file-name path))))
8991 ((eq org-link-file-path-type 'noabbrev)
8992 (setq path (expand-file-name path)))
8993 ((eq org-link-file-path-type 'relative)
8994 (setq path (file-relative-name path)))
8996 (save-match-data
8997 (if (string-match (concat "^" (regexp-quote
8998 (expand-file-name
8999 (file-name-as-directory
9000 default-directory))))
9001 (expand-file-name path))
9002 ;; We are linking a file with relative path name.
9003 (setq path (substring (expand-file-name path)
9004 (match-end 0)))
9005 (setq path (abbreviate-file-name (expand-file-name path)))))))
9006 (setq link (concat type path))
9007 (if (equal desc origpath)
9008 (setq desc path))))
9010 (if org-make-link-description-function
9011 (setq desc (funcall org-make-link-description-function link desc)))
9013 (setq desc (read-string "Description: " desc))
9014 (unless (string-match "\\S-" desc) (setq desc nil))
9015 (if remove (apply 'delete-region remove))
9016 (insert (org-make-link-string link desc))))
9018 (defun org-link-try-special-completion (type)
9019 "If there is completion support for link type TYPE, offer it."
9020 (let ((fun (intern (concat "org-" type "-complete-link"))))
9021 (if (functionp fun)
9022 (funcall fun)
9023 (read-string "Link (no completion support): " (concat type ":")))))
9025 (defun org-file-complete-link (&optional arg)
9026 "Create a file link using completion."
9027 (let (file link)
9028 (setq file (read-file-name "File: "))
9029 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9030 (pwd1 (file-name-as-directory (abbreviate-file-name
9031 (expand-file-name ".")))))
9032 (cond
9033 ((equal arg '(16))
9034 (setq link (org-make-link
9035 "file:"
9036 (abbreviate-file-name (expand-file-name file)))))
9037 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9038 (setq link (org-make-link "file:" (match-string 1 file))))
9039 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9040 (expand-file-name file))
9041 (setq link (org-make-link
9042 "file:" (match-string 1 (expand-file-name file)))))
9043 (t (setq link (org-make-link "file:" file)))))
9044 link))
9046 (defun org-completing-read (&rest args)
9047 "Completing-read with SPACE being a normal character."
9048 (let ((minibuffer-local-completion-map
9049 (copy-keymap minibuffer-local-completion-map)))
9050 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
9051 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
9052 (apply 'org-icompleting-read args)))
9054 (defun org-completing-read-no-i (&rest args)
9055 (let (org-completion-use-ido org-completion-use-iswitchb)
9056 (apply 'org-completing-read args)))
9058 (defun org-iswitchb-completing-read (prompt choices &rest args)
9059 "Use iswitch as a completing-read replacement to choose from choices.
9060 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
9061 from."
9062 (let* ((iswitchb-use-virtual-buffers nil)
9063 (iswitchb-make-buflist-hook
9064 (lambda ()
9065 (setq iswitchb-temp-buflist choices))))
9066 (iswitchb-read-buffer prompt)))
9068 (defun org-icompleting-read (&rest args)
9069 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
9070 (org-without-partial-completion
9071 (if (and org-completion-use-ido
9072 (fboundp 'ido-completing-read)
9073 (boundp 'ido-mode) ido-mode
9074 (listp (second args)))
9075 (let ((ido-enter-matching-directory nil))
9076 (apply 'ido-completing-read (concat (car args))
9077 (if (consp (car (nth 1 args)))
9078 (mapcar 'car (nth 1 args))
9079 (nth 1 args))
9080 (cddr args)))
9081 (if (and org-completion-use-iswitchb
9082 (boundp 'iswitchb-mode) iswitchb-mode
9083 (listp (second args)))
9084 (apply 'org-iswitchb-completing-read (concat (car args))
9085 (if (consp (car (nth 1 args)))
9086 (mapcar 'car (nth 1 args))
9087 (nth 1 args))
9088 (cddr args))
9089 (apply 'completing-read args)))))
9091 (defun org-extract-attributes (s)
9092 "Extract the attributes cookie from a string and set as text property."
9093 (let (a attr (start 0) key value)
9094 (save-match-data
9095 (when (string-match "{{\\([^}]+\\)}}$" s)
9096 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
9097 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
9098 (setq key (match-string 1 a) value (match-string 2 a)
9099 start (match-end 0)
9100 attr (plist-put attr (intern key) value))))
9101 (org-add-props s nil 'org-attr attr))
9104 (defun org-extract-attributes-from-string (tag)
9105 (let (key value attr)
9106 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
9107 (setq key (match-string 1 tag) value (match-string 2 tag)
9108 tag (replace-match "" t t tag)
9109 attr (plist-put attr (intern key) value)))
9110 (cons tag attr)))
9112 (defun org-attributes-to-string (plist)
9113 "Format a property list into an HTML attribute list."
9114 (let ((s "") key value)
9115 (while plist
9116 (setq key (pop plist) value (pop plist))
9117 (and value
9118 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
9121 ;;; Opening/following a link
9123 (defvar org-link-search-failed nil)
9125 (defvar org-open-link-functions nil
9126 "Hook for functions finding a plain text link.
9127 These functions must take a single argument, the link content.
9128 They will be called for links that look like [[link text][description]]
9129 when LINK TEXT does not have a protocol like \"http:\" and does not look
9130 like a filename (e.g. \"./blue.png\").
9132 These functions will be called *before* Org attempts to resolve the
9133 link by doing text searches in the current buffer - so if you want a
9134 link \"[[target]]\" to still find \"<<target>>\", your function should
9135 handle this as a special case.
9137 When the function does handle the link, it must return a non-nil value.
9138 If it decides that it is not responsible for this link, it must return
9139 nil to indicate that that Org-mode can continue with other options
9140 like exact and fuzzy text search.")
9142 (defun org-next-link ()
9143 "Move forward to the next link.
9144 If the link is in hidden text, expose it."
9145 (interactive)
9146 (when (and org-link-search-failed (eq this-command last-command))
9147 (goto-char (point-min))
9148 (message "Link search wrapped back to beginning of buffer"))
9149 (setq org-link-search-failed nil)
9150 (let* ((pos (point))
9151 (ct (org-context))
9152 (a (assoc :link ct)))
9153 (if a (goto-char (nth 2 a)))
9154 (if (re-search-forward org-any-link-re nil t)
9155 (progn
9156 (goto-char (match-beginning 0))
9157 (if (outline-invisible-p) (org-show-context)))
9158 (goto-char pos)
9159 (setq org-link-search-failed t)
9160 (error "No further link found"))))
9162 (defun org-previous-link ()
9163 "Move backward to the previous link.
9164 If the link is in hidden text, expose it."
9165 (interactive)
9166 (when (and org-link-search-failed (eq this-command last-command))
9167 (goto-char (point-max))
9168 (message "Link search wrapped back to end of buffer"))
9169 (setq org-link-search-failed nil)
9170 (let* ((pos (point))
9171 (ct (org-context))
9172 (a (assoc :link ct)))
9173 (if a (goto-char (nth 1 a)))
9174 (if (re-search-backward org-any-link-re nil t)
9175 (progn
9176 (goto-char (match-beginning 0))
9177 (if (outline-invisible-p) (org-show-context)))
9178 (goto-char pos)
9179 (setq org-link-search-failed t)
9180 (error "No further link found"))))
9182 (defun org-translate-link (s)
9183 "Translate a link string if a translation function has been defined."
9184 (if (and org-link-translation-function
9185 (fboundp org-link-translation-function)
9186 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
9187 (progn
9188 (setq s (funcall org-link-translation-function
9189 (match-string 1) (match-string 2)))
9190 (concat (car s) ":" (cdr s)))
9193 (defun org-translate-link-from-planner (type path)
9194 "Translate a link from Emacs Planner syntax so that Org can follow it.
9195 This is still an experimental function, your mileage may vary."
9196 (cond
9197 ((member type '("http" "https" "news" "ftp"))
9198 ;; standard Internet links are the same.
9199 nil)
9200 ((and (equal type "irc") (string-match "^//" path))
9201 ;; Planner has two / at the beginning of an irc link, we have 1.
9202 ;; We should have zero, actually....
9203 (setq path (substring path 1)))
9204 ((and (equal type "lisp") (string-match "^/" path))
9205 ;; Planner has a slash, we do not.
9206 (setq type "elisp" path (substring path 1)))
9207 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9208 ;; A typical message link. Planner has the id after the final slash,
9209 ;; we separate it with a hash mark
9210 (setq path (concat (match-string 1 path) "#"
9211 (org-remove-angle-brackets (match-string 2 path)))))
9213 (cons type path))
9215 (defun org-find-file-at-mouse (ev)
9216 "Open file link or URL at mouse."
9217 (interactive "e")
9218 (mouse-set-point ev)
9219 (org-open-at-point 'in-emacs))
9221 (defun org-open-at-mouse (ev)
9222 "Open file link or URL at mouse."
9223 (interactive "e")
9224 (mouse-set-point ev)
9225 (if (eq major-mode 'org-agenda-mode)
9226 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
9227 (org-open-at-point))
9229 (defvar org-window-config-before-follow-link nil
9230 "The window configuration before following a link.
9231 This is saved in case the need arises to restore it.")
9233 (defvar org-open-link-marker (make-marker)
9234 "Marker pointing to the location where `org-open-at-point; was called.")
9236 ;;;###autoload
9237 (defun org-open-at-point-global ()
9238 "Follow a link like Org-mode does.
9239 This command can be called in any mode to follow a link that has
9240 Org-mode syntax."
9241 (interactive)
9242 (org-run-like-in-org-mode 'org-open-at-point))
9244 ;;;###autoload
9245 (defun org-open-link-from-string (s &optional arg reference-buffer)
9246 "Open a link in the string S, as if it was in Org-mode."
9247 (interactive "sLink: \nP")
9248 (let ((reference-buffer (or reference-buffer (current-buffer))))
9249 (with-temp-buffer
9250 (let ((org-inhibit-startup t))
9251 (org-mode)
9252 (insert s)
9253 (goto-char (point-min))
9254 (when reference-buffer
9255 (setq org-link-abbrev-alist-local
9256 (with-current-buffer reference-buffer
9257 org-link-abbrev-alist-local)))
9258 (org-open-at-point arg reference-buffer)))))
9260 (defvar org-open-at-point-functions nil
9261 "Hook that is run when following a link at point.
9263 Functions in this hook must return t if they identify and follow
9264 a link at point. If they don't find anything interesting at point,
9265 they must return nil.")
9267 (defun org-open-at-point (&optional arg reference-buffer)
9268 "Open link at or after point.
9269 If there is no link at point, this function will search forward up to
9270 the end of the current line.
9271 Normally, files will be opened by an appropriate application. If the
9272 optional prefix argument ARG is non-nil, Emacs will visit the file.
9273 With a double prefix argument, try to open outside of Emacs, in the
9274 application the system uses for this file type."
9275 (interactive "P")
9276 ;; if in a code block, then open the block's results
9277 (unless (call-interactively #'org-babel-open-src-block-result)
9278 (org-load-modules-maybe)
9279 (move-marker org-open-link-marker (point))
9280 (setq org-window-config-before-follow-link (current-window-configuration))
9281 (org-remove-occur-highlights nil nil t)
9282 (cond
9283 ((and (org-on-heading-p)
9284 (not (org-in-regexp
9285 (concat org-plain-link-re "\\|"
9286 org-bracket-link-regexp "\\|"
9287 org-angle-link-re "\\|"
9288 "[ \t]:[^ \t\n]+:[ \t]*$")))
9289 (not (get-text-property (point) 'org-linked-text)))
9290 (or (org-offer-links-in-entry arg)
9291 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
9292 ((run-hook-with-args-until-success 'org-open-at-point-functions))
9293 ((org-at-timestamp-p t) (org-follow-timestamp-link))
9294 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
9295 (not (org-in-regexp org-bracket-link-regexp)))
9296 (org-footnote-action))
9298 (let (type path link line search (pos (point)))
9299 (catch 'match
9300 (save-excursion
9301 (skip-chars-forward "^]\n\r")
9302 (when (org-in-regexp org-bracket-link-regexp 1)
9303 (setq link (org-extract-attributes
9304 (org-link-unescape (org-match-string-no-properties 1))))
9305 (while (string-match " *\n *" link)
9306 (setq link (replace-match " " t t link)))
9307 (setq link (org-link-expand-abbrev link))
9308 (cond
9309 ((or (file-name-absolute-p link)
9310 (string-match "^\\.\\.?/" link))
9311 (setq type "file" path link))
9312 ((string-match org-link-re-with-space3 link)
9313 (setq type (match-string 1 link) path (match-string 2 link)))
9314 (t (setq type "thisfile" path link)))
9315 (throw 'match t)))
9317 (when (get-text-property (point) 'org-linked-text)
9318 (setq type "thisfile"
9319 pos (if (get-text-property (1+ (point)) 'org-linked-text)
9320 (1+ (point)) (point))
9321 path (buffer-substring
9322 (or (previous-single-property-change pos 'org-linked-text)
9323 (point-min))
9324 (or (next-single-property-change pos 'org-linked-text)
9325 (point-max))))
9326 (throw 'match t))
9328 (save-excursion
9329 (when (or (org-in-regexp org-angle-link-re)
9330 (org-in-regexp org-plain-link-re))
9331 (setq type (match-string 1) path (match-string 2))
9332 (throw 'match t)))
9333 (save-excursion
9334 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
9335 (setq type "tags"
9336 path (match-string 1))
9337 (while (string-match ":" path)
9338 (setq path (replace-match "+" t t path)))
9339 (throw 'match t)))
9340 (when (org-in-regexp "<\\([^><\n]+\\)>")
9341 (setq type "tree-match"
9342 path (match-string 1))
9343 (throw 'match t)))
9344 (unless path
9345 (error "No link found"))
9347 ;; switch back to reference buffer
9348 ;; needed when if called in a temporary buffer through
9349 ;; org-open-link-from-string
9350 (with-current-buffer (or reference-buffer (current-buffer))
9352 ;; Remove any trailing spaces in path
9353 (if (string-match " +\\'" path)
9354 (setq path (replace-match "" t t path)))
9355 (if (and org-link-translation-function
9356 (fboundp org-link-translation-function))
9357 ;; Check if we need to translate the link
9358 (let ((tmp (funcall org-link-translation-function type path)))
9359 (setq type (car tmp) path (cdr tmp))))
9361 (cond
9363 ((assoc type org-link-protocols)
9364 (funcall (nth 1 (assoc type org-link-protocols)) path))
9366 ((equal type "mailto")
9367 (let ((cmd (car org-link-mailto-program))
9368 (args (cdr org-link-mailto-program)) args1
9369 (address path) (subject "") a)
9370 (if (string-match "\\(.*\\)::\\(.*\\)" path)
9371 (setq address (match-string 1 path)
9372 subject (org-link-escape (match-string 2 path))))
9373 (while args
9374 (cond
9375 ((not (stringp (car args))) (push (pop args) args1))
9376 (t (setq a (pop args))
9377 (if (string-match "%a" a)
9378 (setq a (replace-match address t t a)))
9379 (if (string-match "%s" a)
9380 (setq a (replace-match subject t t a)))
9381 (push a args1))))
9382 (apply cmd (nreverse args1))))
9384 ((member type '("http" "https" "ftp" "news"))
9385 (browse-url (concat type ":" (org-link-escape
9386 path org-link-escape-chars-browser))))
9388 ((string= type "doi")
9389 (browse-url (concat "http://dx.doi.org/"
9390 (org-link-escape
9391 path org-link-escape-chars-browser))))
9393 ((member type '("message"))
9394 (browse-url (concat type ":" path)))
9396 ((string= type "tags")
9397 (org-tags-view arg path))
9399 ((string= type "tree-match")
9400 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
9402 ((string= type "file")
9403 (if (string-match "::\\([0-9]+\\)\\'" path)
9404 (setq line (string-to-number (match-string 1 path))
9405 path (substring path 0 (match-beginning 0)))
9406 (if (string-match "::\\(.+\\)\\'" path)
9407 (setq search (match-string 1 path)
9408 path (substring path 0 (match-beginning 0)))))
9409 (if (string-match "[*?{]" (file-name-nondirectory path))
9410 (dired path)
9411 (org-open-file path arg line search)))
9413 ((string= type "shell")
9414 (let ((cmd path))
9415 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
9416 (string-match org-confirm-shell-link-not-regexp cmd))
9417 (not org-confirm-shell-link-function)
9418 (funcall org-confirm-shell-link-function
9419 (format "Execute \"%s\" in shell? "
9420 (org-add-props cmd nil
9421 'face 'org-warning))))
9422 (progn
9423 (message "Executing %s" cmd)
9424 (shell-command cmd))
9425 (error "Abort"))))
9427 ((string= type "elisp")
9428 (let ((cmd path))
9429 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
9430 (string-match org-confirm-elisp-link-not-regexp cmd))
9431 (not org-confirm-elisp-link-function)
9432 (funcall org-confirm-elisp-link-function
9433 (format "Execute \"%s\" as elisp? "
9434 (org-add-props cmd nil
9435 'face 'org-warning))))
9436 (message "%s => %s" cmd
9437 (if (equal (string-to-char cmd) ?\()
9438 (eval (read cmd))
9439 (call-interactively (read cmd))))
9440 (error "Abort"))))
9442 ((and (string= type "thisfile")
9443 (run-hook-with-args-until-success
9444 'org-open-link-functions path)))
9446 ((string= type "thisfile")
9447 (if arg
9448 (switch-to-buffer-other-window
9449 (org-get-buffer-for-internal-link (current-buffer)))
9450 (org-mark-ring-push))
9451 (let ((cmd `(org-link-search
9452 ,path
9453 ,(cond ((equal arg '(4)) ''occur)
9454 ((equal arg '(16)) ''org-occur)
9455 (t nil))
9456 ,pos)))
9457 (condition-case nil (eval cmd)
9458 (error (progn (widen) (eval cmd))))))
9461 (browse-url-at-point)))))))
9462 (move-marker org-open-link-marker nil)
9463 (run-hook-with-args 'org-follow-link-hook)))
9465 (defun org-offer-links-in-entry (&optional nth zero)
9466 "Offer links in the current entry and follow the selected link.
9467 If there is only one link, follow it immediately as well.
9468 If NTH is an integer, immediately pick the NTH link found.
9469 If ZERO is a string, check also this string for a link, and if
9470 there is one, offer it as link number zero."
9471 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
9472 "\\(" org-angle-link-re "\\)\\|"
9473 "\\(" org-plain-link-re "\\)"))
9474 (cnt ?0)
9475 (in-emacs (if (integerp nth) nil nth))
9476 have-zero end links link c)
9477 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
9478 (push (match-string 0 zero) links)
9479 (setq cnt (1- cnt) have-zero t))
9480 (save-excursion
9481 (org-back-to-heading t)
9482 (setq end (save-excursion (outline-next-heading) (point)))
9483 (while (re-search-forward re end t)
9484 (push (match-string 0) links))
9485 (setq links (org-uniquify (reverse links))))
9487 (cond
9488 ((null links)
9489 (message "No links"))
9490 ((equal (length links) 1)
9491 (setq link (list (car links))))
9492 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
9493 (setq link (nth (if have-zero nth (1- nth)) links)))
9494 (t ; we have to select a link
9495 (save-excursion
9496 (save-window-excursion
9497 (delete-other-windows)
9498 (with-output-to-temp-buffer "*Select Link*"
9499 (mapc (lambda (l)
9500 (if (not (string-match org-bracket-link-regexp l))
9501 (princ (format "[%c] %s\n" (incf cnt)
9502 (org-remove-angle-brackets l)))
9503 (if (match-end 3)
9504 (princ (format "[%c] %s (%s)\n" (incf cnt)
9505 (match-string 3 l) (match-string 1 l)))
9506 (princ (format "[%c] %s\n" (incf cnt)
9507 (match-string 1 l))))))
9508 links))
9509 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
9510 (message "Select link to open, RET to open all:")
9511 (setq c (read-char-exclusive))
9512 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
9513 (when (equal c ?q) (error "Abort"))
9514 (if (equal c ?\C-m)
9515 (setq link links)
9516 (setq nth (- c ?0))
9517 (if have-zero (setq nth (1+ nth)))
9518 (unless (and (integerp nth) (>= (length links) nth))
9519 (error "Invalid link selection"))
9520 (setq link (list (nth (1- nth) links))))))
9521 (if link
9522 (let ((buf (current-buffer)))
9523 (dolist (l link)
9524 (org-open-link-from-string l in-emacs buf))
9526 nil)))
9528 ;; Add special file links that specify the way of opening
9530 (org-add-link-type "file+sys" 'org-open-file-with-system)
9531 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
9532 (defun org-open-file-with-system (path)
9533 "Open file at PATH using the system way of opening it."
9534 (org-open-file path 'system))
9535 (defun org-open-file-with-emacs (path)
9536 "Open file at PATH in Emacs."
9537 (org-open-file path 'emacs))
9538 (defun org-remove-file-link-modifiers ()
9539 "Remove the file link modifiers in `file+sys:' and `file+emacs:' links."
9540 (goto-char (point-min))
9541 (while (re-search-forward "\\<file\\+\\(sys\\|emacs\\):" nil t)
9542 (org-if-unprotected
9543 (replace-match "file:" t t))))
9544 (eval-after-load "org-exp"
9545 '(add-hook 'org-export-preprocess-before-normalizing-links-hook
9546 'org-remove-file-link-modifiers))
9548 ;;;; Time estimates
9550 (defun org-get-effort (&optional pom)
9551 "Get the effort estimate for the current entry."
9552 (org-entry-get pom org-effort-property))
9554 ;;; File search
9556 (defvar org-create-file-search-functions nil
9557 "List of functions to construct the right search string for a file link.
9558 These functions are called in turn with point at the location to
9559 which the link should point.
9561 A function in the hook should first test if it would like to
9562 handle this file type, for example by checking the `major-mode'
9563 or the file extension. If it decides not to handle this file, it
9564 should just return nil to give other functions a chance. If it
9565 does handle the file, it must return the search string to be used
9566 when following the link. The search string will be part of the
9567 file link, given after a double colon, and `org-open-at-point'
9568 will automatically search for it. If special measures must be
9569 taken to make the search successful, another function should be
9570 added to the companion hook `org-execute-file-search-functions',
9571 which see.
9573 A function in this hook may also use `setq' to set the variable
9574 `description' to provide a suggestion for the descriptive text to
9575 be used for this link when it gets inserted into an Org-mode
9576 buffer with \\[org-insert-link].")
9578 (defvar org-execute-file-search-functions nil
9579 "List of functions to execute a file search triggered by a link.
9581 Functions added to this hook must accept a single argument, the
9582 search string that was part of the file link, the part after the
9583 double colon. The function must first check if it would like to
9584 handle this search, for example by checking the `major-mode' or
9585 the file extension. If it decides not to handle this search, it
9586 should just return nil to give other functions a chance. If it
9587 does handle the search, it must return a non-nil value to keep
9588 other functions from trying.
9590 Each function can access the current prefix argument through the
9591 variable `current-prefix-argument'. Note that a single prefix is
9592 used to force opening a link in Emacs, so it may be good to only
9593 use a numeric or double prefix to guide the search function.
9595 In case this is needed, a function in this hook can also restore
9596 the window configuration before `org-open-at-point' was called using:
9598 (set-window-configuration org-window-config-before-follow-link)")
9600 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
9601 (defun org-link-search (s &optional type avoid-pos)
9602 "Search for a link search option.
9603 If S is surrounded by forward slashes, it is interpreted as a
9604 regular expression. In org-mode files, this will create an `org-occur'
9605 sparse tree. In ordinary files, `occur' will be used to list matches.
9606 If the current buffer is in `dired-mode', grep will be used to search
9607 in all files. If AVOID-POS is given, ignore matches near that position."
9608 (let ((case-fold-search t)
9609 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
9610 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
9611 (append '(("") (" ") ("\t") ("\n"))
9612 org-emphasis-alist)
9613 "\\|") "\\)"))
9614 (pos (point))
9615 (pre nil) (post nil)
9616 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
9617 (cond
9618 ;; First check if there are any special search functions
9619 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
9620 ;; Now try the builtin stuff
9621 ((and (equal (string-to-char s0) ?#)
9622 (> (length s0) 1)
9623 (save-excursion
9624 (goto-char (point-min))
9625 (and
9626 (re-search-forward
9627 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
9628 (setq type 'dedicated
9629 pos (match-beginning 0))))
9630 ;; There is an exact target for this
9631 (goto-char pos)
9632 (org-back-to-heading t)))
9633 ((save-excursion
9634 (goto-char (point-min))
9635 (and
9636 (re-search-forward
9637 (concat "<<" (regexp-quote s0) ">>") nil t)
9638 (setq type 'dedicated
9639 pos (match-beginning 0))))
9640 ;; There is an exact target for this
9641 (goto-char pos))
9642 ((and (string-match "^(\\(.*\\))$" s0)
9643 (save-excursion
9644 (goto-char (point-min))
9645 (and
9646 (re-search-forward
9647 (concat "[^[]" (regexp-quote
9648 (format org-coderef-label-format
9649 (match-string 1 s0))))
9650 nil t)
9651 (setq type 'dedicated
9652 pos (1+ (match-beginning 0))))))
9653 ;; There is a coderef target for this
9654 (goto-char pos))
9655 ((string-match "^/\\(.*\\)/$" s)
9656 ;; A regular expression
9657 (cond
9658 ((org-mode-p)
9659 (org-occur (match-string 1 s)))
9660 ;;((eq major-mode 'dired-mode)
9661 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
9662 (t (org-do-occur (match-string 1 s)))))
9663 ((and (org-mode-p) org-link-search-must-match-exact-headline)
9664 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
9665 (goto-char (point-min))
9666 (cond
9667 ((let (case-fold-search)
9668 (re-search-forward (format org-complex-heading-regexp-format
9669 (regexp-quote s))
9670 nil t))
9671 ;; OK, found a match
9672 (setq type 'dedicated)
9673 (goto-char (match-beginning 0)))
9674 ((and (not org-link-search-inhibit-query)
9675 (eq org-link-search-must-match-exact-headline 'query-to-create)
9676 (y-or-n-p "No match - create this as a new heading? "))
9677 (goto-char (point-max))
9678 (or (bolp) (newline))
9679 (insert "* " s "\n")
9680 (beginning-of-line 0))
9682 (goto-char pos)
9683 (error "No match"))))
9685 ;; A normal search string
9686 (when (equal (string-to-char s) ?*)
9687 ;; Anchor on headlines, post may include tags.
9688 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
9689 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
9690 s (substring s 1)))
9691 (remove-text-properties
9692 0 (length s)
9693 '(face nil mouse-face nil keymap nil fontified nil) s)
9694 ;; Make a series of regular expressions to find a match
9695 (setq words (org-split-string s "[ \n\r\t]+")
9697 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
9698 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
9699 "\\)" markers)
9700 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
9701 re2a (concat "[ \t\r\n]" re2a_)
9702 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
9703 re4 (concat "[^a-zA-Z_]" re4_)
9705 re1 (concat pre re2 post)
9706 re3 (concat pre (if pre re4_ re4) post)
9707 re5 (concat pre ".*" re4)
9708 re2 (concat pre re2)
9709 re2a (concat pre (if pre re2a_ re2a))
9710 re4 (concat pre (if pre re4_ re4))
9711 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
9712 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
9713 re5 "\\)"
9715 (cond
9716 ((eq type 'org-occur) (org-occur reall))
9717 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
9718 (t (goto-char (point-min))
9719 (setq type 'fuzzy)
9720 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
9721 (org-search-not-self 1 re1 nil t)
9722 (org-search-not-self 1 re2 nil t)
9723 (org-search-not-self 1 re2a nil t)
9724 (org-search-not-self 1 re3 nil t)
9725 (org-search-not-self 1 re4 nil t)
9726 (org-search-not-self 1 re5 nil t)
9728 (goto-char (match-beginning 1))
9729 (goto-char pos)
9730 (error "No match"))))))
9731 (and (org-mode-p) (org-show-context 'link-search))
9732 type))
9734 (defun org-search-not-self (group &rest args)
9735 "Execute `re-search-forward', but only accept matches that do not
9736 enclose the position of `org-open-link-marker'."
9737 (let ((m org-open-link-marker))
9738 (catch 'exit
9739 (while (apply 're-search-forward args)
9740 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
9741 (goto-char (match-end group))
9742 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
9743 (> (match-beginning 0) (marker-position m))
9744 (< (match-end 0) (marker-position m)))
9745 (save-match-data
9746 (or (not (org-in-regexp
9747 org-bracket-link-analytic-regexp 1))
9748 (not (match-end 4)) ; no description
9749 (and (<= (match-beginning 4) (point))
9750 (>= (match-end 4) (point))))))
9751 (throw 'exit (point))))))))
9753 (defun org-get-buffer-for-internal-link (buffer)
9754 "Return a buffer to be used for displaying the link target of internal links."
9755 (cond
9756 ((not org-display-internal-link-with-indirect-buffer)
9757 buffer)
9758 ((string-match "(Clone)$" (buffer-name buffer))
9759 (message "Buffer is already a clone, not making another one")
9760 ;; we also do not modify visibility in this case
9761 buffer)
9762 (t ; make a new indirect buffer for displaying the link
9763 (let* ((bn (buffer-name buffer))
9764 (ibn (concat bn "(Clone)"))
9765 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
9766 (with-current-buffer ib (org-overview))
9767 ib))))
9769 (defun org-do-occur (regexp &optional cleanup)
9770 "Call the Emacs command `occur'.
9771 If CLEANUP is non-nil, remove the printout of the regular expression
9772 in the *Occur* buffer. This is useful if the regex is long and not useful
9773 to read."
9774 (occur regexp)
9775 (when cleanup
9776 (let ((cwin (selected-window)) win beg end)
9777 (when (setq win (get-buffer-window "*Occur*"))
9778 (select-window win))
9779 (goto-char (point-min))
9780 (when (re-search-forward "match[a-z]+" nil t)
9781 (setq beg (match-end 0))
9782 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
9783 (setq end (1- (match-beginning 0)))))
9784 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
9785 (goto-char (point-min))
9786 (select-window cwin))))
9788 ;;; The mark ring for links jumps
9790 (defvar org-mark-ring nil
9791 "Mark ring for positions before jumps in Org-mode.")
9792 (defvar org-mark-ring-last-goto nil
9793 "Last position in the mark ring used to go back.")
9794 ;; Fill and close the ring
9795 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
9796 (loop for i from 1 to org-mark-ring-length do
9797 (push (make-marker) org-mark-ring))
9798 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
9799 org-mark-ring)
9801 (defun org-mark-ring-push (&optional pos buffer)
9802 "Put the current position or POS into the mark ring and rotate it."
9803 (interactive)
9804 (setq pos (or pos (point)))
9805 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
9806 (move-marker (car org-mark-ring)
9807 (or pos (point))
9808 (or buffer (current-buffer)))
9809 (message "%s"
9810 (substitute-command-keys
9811 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
9813 (defun org-mark-ring-goto (&optional n)
9814 "Jump to the previous position in the mark ring.
9815 With prefix arg N, jump back that many stored positions. When
9816 called several times in succession, walk through the entire ring.
9817 Org-mode commands jumping to a different position in the current file,
9818 or to another Org-mode file, automatically push the old position
9819 onto the ring."
9820 (interactive "p")
9821 (let (p m)
9822 (if (eq last-command this-command)
9823 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
9824 (setq p org-mark-ring))
9825 (setq org-mark-ring-last-goto p)
9826 (setq m (car p))
9827 (switch-to-buffer (marker-buffer m))
9828 (goto-char m)
9829 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
9831 (defun org-remove-angle-brackets (s)
9832 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
9833 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
9835 (defun org-add-angle-brackets (s)
9836 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
9837 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
9839 (defun org-remove-double-quotes (s)
9840 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
9841 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
9844 ;;; Following specific links
9846 (defun org-follow-timestamp-link ()
9847 (cond
9848 ((org-at-date-range-p t)
9849 (let ((org-agenda-start-on-weekday)
9850 (t1 (match-string 1))
9851 (t2 (match-string 2)))
9852 (setq t1 (time-to-days (org-time-string-to-time t1))
9853 t2 (time-to-days (org-time-string-to-time t2)))
9854 (org-agenda-list nil t1 (1+ (- t2 t1)))))
9855 ((org-at-timestamp-p t)
9856 (org-agenda-list nil (time-to-days (org-time-string-to-time
9857 (substring (match-string 1) 0 10)))
9859 (t (error "This should not happen"))))
9862 ;;; Following file links
9863 (defvar org-wait nil)
9864 (defun org-open-file (path &optional in-emacs line search)
9865 "Open the file at PATH.
9866 First, this expands any special file name abbreviations. Then the
9867 configuration variable `org-file-apps' is checked if it contains an
9868 entry for this file type, and if yes, the corresponding command is launched.
9870 If no application is found, Emacs simply visits the file.
9872 With optional prefix argument IN-EMACS, Emacs will visit the file.
9873 With a double \\[universal-argument] \\[universal-argument] \
9874 prefix arg, Org tries to avoid opening in Emacs
9875 and to use an external application to visit the file.
9877 Optional LINE specifies a line to go to, optional SEARCH a string
9878 to search for. If LINE or SEARCH is given, the file will be
9879 opened in Emacs, unless an entry from org-file-apps that makes
9880 use of groups in a regexp matches.
9881 If the file does not exist, an error is thrown."
9882 (let* ((file (if (equal path "")
9883 buffer-file-name
9884 (substitute-in-file-name (expand-file-name path))))
9885 (file-apps (append org-file-apps (org-default-apps)))
9886 (apps (org-remove-if
9887 'org-file-apps-entry-match-against-dlink-p file-apps))
9888 (apps-dlink (org-remove-if-not
9889 'org-file-apps-entry-match-against-dlink-p file-apps))
9890 (remp (and (assq 'remote apps) (org-file-remote-p file)))
9891 (dirp (if remp nil (file-directory-p file)))
9892 (file (if (and dirp org-open-directory-means-index-dot-org)
9893 (concat (file-name-as-directory file) "index.org")
9894 file))
9895 (a-m-a-p (assq 'auto-mode apps))
9896 (dfile (downcase file))
9897 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
9898 (link (cond ((and (eq line nil)
9899 (eq search nil))
9900 file)
9901 (line
9902 (concat file "::" (number-to-string line)))
9903 (search
9904 (concat file "::" search))))
9905 (dlink (downcase link))
9906 (old-buffer (current-buffer))
9907 (old-pos (point))
9908 (old-mode major-mode)
9909 ext cmd link-match-data)
9910 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
9911 (setq ext (match-string 1 dfile))
9912 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
9913 (setq ext (match-string 1 dfile))))
9914 (cond
9915 ((member in-emacs '((16) system))
9916 (setq cmd (cdr (assoc 'system apps))))
9917 (in-emacs (setq cmd 'emacs))
9919 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
9920 (and dirp (cdr (assoc 'directory apps)))
9921 ; first, try matching against apps-dlink
9922 ; if we get a match here, store the match data for later
9923 (let ((match (assoc-default dlink apps-dlink
9924 'string-match)))
9925 (if match
9926 (progn (setq link-match-data (match-data))
9927 match)
9928 (progn (setq in-emacs (or in-emacs line search))
9929 nil))) ; if we have no match in apps-dlink,
9930 ; always open the file in emacs if line or search
9931 ; is given (for backwards compatibility)
9932 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
9933 'string-match)
9934 (cdr (assoc ext apps))
9935 (cdr (assoc t apps))))))
9936 (when (eq cmd 'system)
9937 (setq cmd (cdr (assoc 'system apps))))
9938 (when (eq cmd 'default)
9939 (setq cmd (cdr (assoc t apps))))
9940 (when (eq cmd 'mailcap)
9941 (require 'mailcap)
9942 (mailcap-parse-mailcaps)
9943 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
9944 (command (mailcap-mime-info mime-type)))
9945 (if (stringp command)
9946 (setq cmd command)
9947 (setq cmd 'emacs))))
9948 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
9949 (not (file-exists-p file))
9950 (not org-open-non-existing-files))
9951 (error "No such file: %s" file))
9952 (cond
9953 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
9954 ;; Remove quotes around the file name - we'll use shell-quote-argument.
9955 (while (string-match "['\"]%s['\"]" cmd)
9956 (setq cmd (replace-match "%s" t t cmd)))
9957 (while (string-match "%s" cmd)
9958 (setq cmd (replace-match
9959 (save-match-data
9960 (shell-quote-argument
9961 (convert-standard-filename file)))
9962 t t cmd)))
9964 ;; Replace "%1", "%2" etc. in command with group matches from regex
9965 (save-match-data
9966 (let ((match-index 1)
9967 (number-of-groups (- (/ (length link-match-data) 2) 1)))
9968 (set-match-data link-match-data)
9969 (while (<= match-index number-of-groups)
9970 (let ((regex (concat "%" (number-to-string match-index)))
9971 (replace-with (match-string match-index dlink)))
9972 (while (string-match regex cmd)
9973 (setq cmd (replace-match replace-with t t cmd))))
9974 (setq match-index (+ match-index 1)))))
9976 (save-window-excursion
9977 (start-process-shell-command cmd nil cmd)
9978 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
9980 ((or (stringp cmd)
9981 (eq cmd 'emacs))
9982 (funcall (cdr (assq 'file org-link-frame-setup)) file)
9983 (widen)
9984 (if line (org-goto-line line)
9985 (if search (org-link-search search))))
9986 ((consp cmd)
9987 (let ((file (convert-standard-filename file)))
9988 (save-match-data
9989 (set-match-data link-match-data)
9990 (eval cmd))))
9991 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
9992 (and (org-mode-p) (eq old-mode 'org-mode)
9993 (or (not (equal old-buffer (current-buffer)))
9994 (not (equal old-pos (point))))
9995 (org-mark-ring-push old-pos old-buffer))))
9997 (defun org-file-apps-entry-match-against-dlink-p (entry)
9998 "This function returns non-nil if `entry' uses a regular
9999 expression which should be matched against the whole link by
10000 org-open-file.
10002 It assumes that is the case when the entry uses a regular
10003 expression which has at least one grouping construct and the
10004 action is either a lisp form or a command string containing
10005 '%1', i.e. using at least one subexpression match as a
10006 parameter."
10007 (let ((selector (car entry))
10008 (action (cdr entry)))
10009 (if (stringp selector)
10010 (and (> (regexp-opt-depth selector) 0)
10011 (or (and (stringp action)
10012 (string-match "%[0-9]" action))
10013 (consp action)))
10014 nil)))
10016 (defun org-default-apps ()
10017 "Return the default applications for this operating system."
10018 (cond
10019 ((eq system-type 'darwin)
10020 org-file-apps-defaults-macosx)
10021 ((eq system-type 'windows-nt)
10022 org-file-apps-defaults-windowsnt)
10023 (t org-file-apps-defaults-gnu)))
10025 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10026 "Convert extensions to regular expressions in the cars of LIST.
10027 Also, weed out any non-string entries, because the return value is used
10028 only for regexp matching.
10029 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10030 point to the symbol `emacs', indicating that the file should
10031 be opened in Emacs."
10032 (append
10033 (delq nil
10034 (mapcar (lambda (x)
10035 (if (not (stringp (car x)))
10037 (if (string-match "\\W" (car x))
10039 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10040 list))
10041 (if add-auto-mode
10042 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10044 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10045 (defun org-file-remote-p (file)
10046 "Test whether FILE specifies a location on a remote system.
10047 Return non-nil if the location is indeed remote.
10049 For example, the filename \"/user@host:/foo\" specifies a location
10050 on the system \"/user@host:\"."
10051 (cond ((fboundp 'file-remote-p)
10052 (file-remote-p file))
10053 ((fboundp 'tramp-handle-file-remote-p)
10054 (tramp-handle-file-remote-p file))
10055 ((and (boundp 'ange-ftp-name-format)
10056 (string-match (car ange-ftp-name-format) file))
10058 (t nil)))
10061 ;;;; Refiling
10063 (defun org-get-org-file ()
10064 "Read a filename, with default directory `org-directory'."
10065 (let ((default (or org-default-notes-file remember-data-file)))
10066 (read-file-name (format "File name [%s]: " default)
10067 (file-name-as-directory org-directory)
10068 default)))
10070 (defun org-notes-order-reversed-p ()
10071 "Check if the current file should receive notes in reversed order."
10072 (cond
10073 ((not org-reverse-note-order) nil)
10074 ((eq t org-reverse-note-order) t)
10075 ((not (listp org-reverse-note-order)) nil)
10076 (t (catch 'exit
10077 (let ((all org-reverse-note-order)
10078 entry)
10079 (while (setq entry (pop all))
10080 (if (string-match (car entry) buffer-file-name)
10081 (throw 'exit (cdr entry))))
10082 nil)))))
10084 (defvar org-refile-target-table nil
10085 "The list of refile targets, created by `org-refile'.")
10087 (defvar org-agenda-new-buffers nil
10088 "Buffers created to visit agenda files.")
10090 (defvar org-refile-cache nil
10091 "Cache for refile targets.")
10093 (defvar org-refile-markers nil
10094 "All the markers used for caching refile locations.")
10096 (defun org-refile-marker (pos)
10097 "Get a new refile marker, but only if caching is in use."
10098 (if (not org-refile-use-cache)
10100 (let ((m (make-marker)))
10101 (move-marker m pos)
10102 (push m org-refile-markers)
10103 m)))
10105 (defun org-refile-cache-clear ()
10106 "Clear the refile cache and disable all the markers."
10107 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
10108 (setq org-refile-markers nil)
10109 (setq org-refile-cache nil)
10110 (message "Refile cache has been cleared"))
10112 (defun org-refile-cache-check-set (set)
10113 "Check if all the markers in the cache still have live buffers."
10114 (let (marker)
10115 (catch 'exit
10116 (while (and set (setq marker (nth 3 (pop set))))
10117 ;; if org-refile-use-outline-path is 'file, marker may be nil
10118 (when (and marker (null (marker-buffer marker)))
10119 (message "not found") (sit-for 3)
10120 (throw 'exit nil)))
10121 t)))
10123 (defun org-refile-cache-put (set &rest identifiers)
10124 "Push the refile targets SET into the cache, under IDENTIFIERS."
10125 (let* ((key (sha1 (prin1-to-string identifiers)))
10126 (entry (assoc key org-refile-cache)))
10127 (if entry
10128 (setcdr entry set)
10129 (push (cons key set) org-refile-cache))))
10131 (defun org-refile-cache-get (&rest identifiers)
10132 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10133 (cond
10134 ((not org-refile-cache) nil)
10135 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10137 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10138 org-refile-cache))))
10139 (and set (org-refile-cache-check-set set) set)))))
10141 (defun org-refile-get-targets (&optional default-buffer)
10142 "Produce a table with refile targets."
10143 (let ((case-fold-search nil)
10144 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10145 (entries (or org-refile-targets '((nil . (:level . 1)))))
10146 targets tgs txt re files f desc descre fast-path-p level pos0)
10147 (message "Getting targets...")
10148 (with-current-buffer (or default-buffer (current-buffer))
10149 (while (setq entry (pop entries))
10150 (setq files (car entry) desc (cdr entry))
10151 (setq fast-path-p nil)
10152 (cond
10153 ((null files) (setq files (list (current-buffer))))
10154 ((eq files 'org-agenda-files)
10155 (setq files (org-agenda-files 'unrestricted)))
10156 ((and (symbolp files) (fboundp files))
10157 (setq files (funcall files)))
10158 ((and (symbolp files) (boundp files))
10159 (setq files (symbol-value files))))
10160 (if (stringp files) (setq files (list files)))
10161 (cond
10162 ((eq (car desc) :tag)
10163 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
10164 ((eq (car desc) :todo)
10165 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
10166 ((eq (car desc) :regexp)
10167 (setq descre (cdr desc)))
10168 ((eq (car desc) :level)
10169 (setq descre (concat "^\\*\\{" (number-to-string
10170 (if org-odd-levels-only
10171 (1- (* 2 (cdr desc)))
10172 (cdr desc)))
10173 "\\}[ \t]")))
10174 ((eq (car desc) :maxlevel)
10175 (setq fast-path-p t)
10176 (setq descre (concat "^\\*\\{1," (number-to-string
10177 (if org-odd-levels-only
10178 (1- (* 2 (cdr desc)))
10179 (cdr desc)))
10180 "\\}[ \t]")))
10181 (t (error "Bad refiling target description %s" desc)))
10182 (while (setq f (pop files))
10183 (with-current-buffer
10184 (if (bufferp f) f (org-get-agenda-file-buffer f))
10186 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
10187 (progn
10188 (if (bufferp f) (setq f (buffer-file-name
10189 (buffer-base-buffer f))))
10190 (setq f (and f (expand-file-name f)))
10191 (if (eq org-refile-use-outline-path 'file)
10192 (push (list (file-name-nondirectory f) f nil nil) tgs))
10193 (save-excursion
10194 (save-restriction
10195 (widen)
10196 (goto-char (point-min))
10197 (while (re-search-forward descre nil t)
10198 (goto-char (setq pos0 (point-at-bol)))
10199 (catch 'next
10200 (when org-refile-target-verify-function
10201 (save-match-data
10202 (or (funcall org-refile-target-verify-function)
10203 (throw 'next t))))
10204 (when (looking-at org-complex-heading-regexp)
10205 (setq level (org-reduced-level
10206 (- (match-end 1) (match-beginning 1)))
10207 txt (org-link-display-format (match-string 4))
10208 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
10209 re (format org-complex-heading-regexp-format
10210 (regexp-quote (match-string 4))))
10211 (when org-refile-use-outline-path
10212 (setq txt (mapconcat
10213 'org-protect-slash
10214 (append
10215 (if (eq org-refile-use-outline-path
10216 'file)
10217 (list (file-name-nondirectory
10218 (buffer-file-name
10219 (buffer-base-buffer))))
10220 (if (eq org-refile-use-outline-path
10221 'full-file-path)
10222 (list (buffer-file-name
10223 (buffer-base-buffer)))))
10224 (org-get-outline-path fast-path-p
10225 level txt)
10226 (list txt))
10227 "/")))
10228 (push (list txt f re (org-refile-marker (point)))
10229 tgs)))
10230 (when (= (point) pos0)
10231 ;; verification function has not moved point
10232 (goto-char (point-at-eol))))))))
10233 (when org-refile-use-cache
10234 (org-refile-cache-put tgs (buffer-file-name) descre))
10235 (setq targets (append tgs targets))
10236 ))))
10237 (message "Getting targets...done")
10238 (nreverse targets)))
10240 (defun org-protect-slash (s)
10241 (while (string-match "/" s)
10242 (setq s (replace-match "\\" t t s)))
10245 (defvar org-olpa (make-vector 20 nil))
10247 (defun org-get-outline-path (&optional fastp level heading)
10248 "Return the outline path to the current entry, as a list.
10250 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
10251 routine which makes outline path derivations for an entire file,
10252 avoiding backtracing. Refile target collection makes use of that."
10253 (if fastp
10254 (progn
10255 (if (> level 19)
10256 (error "Outline path failure, more than 19 levels"))
10257 (loop for i from level upto 19 do
10258 (aset org-olpa i nil))
10259 (prog1
10260 (delq nil (append org-olpa nil))
10261 (aset org-olpa level heading)))
10262 (let (rtn case-fold-search)
10263 (save-excursion
10264 (save-restriction
10265 (widen)
10266 (while (org-up-heading-safe)
10267 (when (looking-at org-complex-heading-regexp)
10268 (push (org-match-string-no-properties 4) rtn)))
10269 rtn)))))
10271 (defun org-format-outline-path (path &optional width prefix)
10272 "Format the outline path PATH for display.
10273 Width is the maximum number of characters that is available.
10274 Prefix is a prefix to be included in the returned string,
10275 such as the file name."
10276 (setq width (or width 79))
10277 (if prefix (setq width (- width (length prefix))))
10278 (if (not path)
10279 (or prefix "")
10280 (let* ((nsteps (length path))
10281 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
10282 (maxwidth (if (<= total-width width)
10283 10000 ;; everything fits
10284 ;; we need to shorten the level headings
10285 (/ (- width nsteps) nsteps)))
10286 (org-odd-levels-only nil)
10287 (n 0)
10288 (total (1+ (length prefix))))
10289 (setq maxwidth (max maxwidth 10))
10290 (concat prefix
10291 (mapconcat
10292 (lambda (h)
10293 (setq n (1+ n))
10294 (if (and (= n nsteps) (< maxwidth 10000))
10295 (setq maxwidth (- total-width total)))
10296 (if (< (length h) maxwidth)
10297 (progn (setq total (+ total (length h) 1)) h)
10298 (setq h (substring h 0 (- maxwidth 2))
10299 total (+ total maxwidth 1))
10300 (if (string-match "[ \t]+\\'" h)
10301 (setq h (substring h 0 (match-beginning 0))))
10302 (setq h (concat h "..")))
10303 (org-add-props h nil 'face
10304 (nth (% (1- n) org-n-level-faces)
10305 org-level-faces))
10307 path "/")))))
10309 (defun org-display-outline-path (&optional file current)
10310 "Display the current outline path in the echo area."
10311 (interactive "P")
10312 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
10313 (case-fold-search nil)
10314 (path (and (org-mode-p) (org-get-outline-path))))
10315 (if current (setq path (append path
10316 (save-excursion
10317 (org-back-to-heading t)
10318 (if (looking-at org-complex-heading-regexp)
10319 (list (match-string 4)))))))
10320 (message "%s"
10321 (org-format-outline-path
10322 path
10323 (1- (frame-width))
10324 (and file bfn (concat (file-name-nondirectory bfn) "/"))))))
10326 (defvar org-refile-history nil
10327 "History for refiling operations.")
10329 (defvar org-after-refile-insert-hook nil
10330 "Hook run after `org-refile' has inserted its stuff at the new location.
10331 Note that this is still *before* the stuff will be removed from
10332 the *old* location.")
10334 (defvar org-capture-last-stored-marker)
10335 (defun org-refile (&optional goto default-buffer rfloc)
10336 "Move the entry at point to another heading.
10337 The list of target headings is compiled using the information in
10338 `org-refile-targets', which see. This list is created before each use
10339 and will therefore always be up-to-date.
10341 At the target location, the entry is filed as a subitem of the target heading.
10342 Depending on `org-reverse-note-order', the new subitem will either be the
10343 first or the last subitem.
10345 If there is an active region, all entries in that region will be moved.
10346 However, the region must fulfill the requirement that the first heading
10347 is the first one sets the top-level of the moved text - at most siblings
10348 below it are allowed.
10350 With prefix arg GOTO, the command will only visit the target location,
10351 not actually move anything.
10352 With a double prefix arg \\[universal-argument] \\[universal-argument], \
10353 go to the location where the last refiling
10354 operation has put the subtree.
10355 With a prefix argument of `2', refile to the running clock.
10357 RFLOC can be a refile location obtained in a different way.
10359 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
10361 If you are using target caching (see `org-refile-use-cache'),
10362 You have to clear the target cache in order to find new targets.
10363 This can be done with a 0 prefix: `C-0 C-c C-w'"
10364 (interactive "P")
10365 (if (member goto '(0 (64)))
10366 (org-refile-cache-clear)
10367 (let* ((cbuf (current-buffer))
10368 (regionp (org-region-active-p))
10369 (region-start (and regionp (region-beginning)))
10370 (region-end (and regionp (region-end)))
10371 (region-length (and regionp (- region-end region-start)))
10372 (filename (buffer-file-name (buffer-base-buffer cbuf)))
10373 pos it nbuf file re level reversed)
10374 (setq last-command nil)
10375 (when regionp
10376 (goto-char region-start)
10377 (or (bolp) (goto-char (point-at-bol)))
10378 (setq region-start (point))
10379 (unless (org-kill-is-subtree-p
10380 (buffer-substring region-start region-end))
10381 (error "The region is not a (sequence of) subtree(s)")))
10382 (if (equal goto '(16))
10383 (org-refile-goto-last-stored)
10384 (when (or
10385 (and (equal goto 2)
10386 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
10387 (prog1
10388 (setq it (list (or org-clock-heading "running clock")
10389 (buffer-file-name
10390 (marker-buffer org-clock-hd-marker))
10392 (marker-position org-clock-hd-marker)))
10393 (setq goto nil)))
10394 (setq it (or rfloc
10395 (save-excursion
10396 (org-refile-get-location
10397 (if goto "Goto" "Refile to") default-buffer
10398 org-refile-allow-creating-parent-nodes)))))
10399 (setq file (nth 1 it)
10400 re (nth 2 it)
10401 pos (nth 3 it))
10402 (if (and (not goto)
10404 (equal (buffer-file-name) file)
10405 (if regionp
10406 (and (>= pos region-start)
10407 (<= pos region-end))
10408 (and (>= pos (point))
10409 (< pos (save-excursion
10410 (org-end-of-subtree t t))))))
10411 (error "Cannot refile to position inside the tree or region"))
10413 (setq nbuf (or (find-buffer-visiting file)
10414 (find-file-noselect file)))
10415 (if goto
10416 (progn
10417 (switch-to-buffer nbuf)
10418 (goto-char pos)
10419 (org-show-context 'org-goto))
10420 (if regionp
10421 (progn
10422 (org-kill-new (buffer-substring region-start region-end))
10423 (org-save-markers-in-region region-start region-end))
10424 (org-copy-subtree 1 nil t))
10425 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
10426 (find-file-noselect file)))
10427 (setq reversed (org-notes-order-reversed-p))
10428 (save-excursion
10429 (save-restriction
10430 (widen)
10431 (if pos
10432 (progn
10433 (goto-char pos)
10434 (looking-at outline-regexp)
10435 (setq level (org-get-valid-level (funcall outline-level) 1))
10436 (goto-char
10437 (if reversed
10438 (or (outline-next-heading) (point-max))
10439 (or (save-excursion (org-get-next-sibling))
10440 (org-end-of-subtree t t)
10441 (point-max)))))
10442 (setq level 1)
10443 (if (not reversed)
10444 (goto-char (point-max))
10445 (goto-char (point-min))
10446 (or (outline-next-heading) (goto-char (point-max)))))
10447 (if (not (bolp)) (newline))
10448 (org-paste-subtree level)
10449 (when org-log-refile
10450 (org-add-log-setup 'refile nil nil 'findpos
10451 org-log-refile)
10452 (unless (eq org-log-refile 'note)
10453 (save-excursion (org-add-log-note))))
10454 (and org-auto-align-tags (org-set-tags nil t))
10455 (bookmark-set "org-refile-last-stored")
10456 ;; If we are refiling for capture, make sure that the
10457 ;; last-capture pointers point here
10458 (when (org-bound-and-true-p org-refile-for-capture)
10459 (bookmark-set "org-capture-last-stored-marker")
10460 (move-marker org-capture-last-stored-marker (point)))
10461 (if (fboundp 'deactivate-mark) (deactivate-mark))
10462 (run-hooks 'org-after-refile-insert-hook))))
10463 (if regionp
10464 (delete-region (point) (+ (point) region-length))
10465 (org-cut-subtree))
10466 (when (featurep 'org-inlinetask)
10467 (org-inlinetask-remove-END-maybe))
10468 (setq org-markers-to-move nil)
10469 (message "Refiled to \"%s\" in file %s" (car it) file)))))))
10471 (defun org-refile-goto-last-stored ()
10472 "Go to the location where the last refile was stored."
10473 (interactive)
10474 (bookmark-jump "org-refile-last-stored")
10475 (message "This is the location of the last refile"))
10477 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
10478 "Prompt the user for a refile location, using PROMPT.
10479 PROMPT should not be suffixed with a colon and a space, because
10480 this function appends the default value from
10481 `org-refile-history' automatically, if that is not empty."
10482 (let ((org-refile-targets org-refile-targets)
10483 (org-refile-use-outline-path org-refile-use-outline-path))
10484 (setq org-refile-target-table (org-refile-get-targets default-buffer)))
10485 (unless org-refile-target-table
10486 (error "No refile targets"))
10487 (let* ((prompt (concat prompt
10488 (and (car org-refile-history)
10489 (concat " (default " (car org-refile-history) ")"))
10490 ": "))
10491 (cbuf (current-buffer))
10492 (partial-completion-mode nil)
10493 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
10494 (cfunc (if (and org-refile-use-outline-path
10495 org-outline-path-complete-in-steps)
10496 'org-olpath-completing-read
10497 'org-icompleting-read))
10498 (extra (if org-refile-use-outline-path "/" ""))
10499 (filename (and cfn (expand-file-name cfn)))
10500 (tbl (mapcar
10501 (lambda (x)
10502 (if (and (not (member org-refile-use-outline-path
10503 '(file full-file-path)))
10504 (not (equal filename (nth 1 x))))
10505 (cons (concat (car x) extra " ("
10506 (file-name-nondirectory (nth 1 x)) ")")
10507 (cdr x))
10508 (cons (concat (car x) extra) (cdr x))))
10509 org-refile-target-table))
10510 (completion-ignore-case t)
10511 pa answ parent-target child parent old-hist)
10512 (setq old-hist org-refile-history)
10513 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
10514 nil 'org-refile-history (car org-refile-history)))
10515 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
10516 (org-refile-check-position pa)
10517 (if pa
10518 (progn
10519 (when (or (not org-refile-history)
10520 (not (eq old-hist org-refile-history))
10521 (not (equal (car pa) (car org-refile-history))))
10522 (setq org-refile-history
10523 (cons (car pa) (if (assoc (car org-refile-history) tbl)
10524 org-refile-history
10525 (cdr org-refile-history))))
10526 (if (equal (car org-refile-history) (nth 1 org-refile-history))
10527 (pop org-refile-history)))
10529 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
10530 (progn
10531 (setq parent (match-string 1 answ)
10532 child (match-string 2 answ))
10533 (setq parent-target (or (assoc parent tbl)
10534 (assoc (concat parent "/") tbl)))
10535 (when (and parent-target
10536 (or (eq new-nodes t)
10537 (and (eq new-nodes 'confirm)
10538 (y-or-n-p (format "Create new node \"%s\"? "
10539 child)))))
10540 (org-refile-new-child parent-target child)))
10541 (error "Invalid target location")))))
10543 (defun org-refile-check-position (refile-pointer)
10544 "Check if the refile pointer matches the readline to which it points."
10545 (let* ((file (nth 1 refile-pointer))
10546 (re (nth 2 refile-pointer))
10547 (pos (nth 3 refile-pointer))
10548 buffer)
10549 (when (org-string-nw-p re)
10550 (setq buffer (if (markerp pos)
10551 (marker-buffer pos)
10552 (or (find-buffer-visiting file)
10553 (find-file-noselect file))))
10554 (with-current-buffer buffer
10555 (save-excursion
10556 (save-restriction
10557 (widen)
10558 (goto-char pos)
10559 (beginning-of-line 1)
10560 (unless (org-looking-at-p re)
10561 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
10563 (defun org-refile-new-child (parent-target child)
10564 "Use refile target PARENT-TARGET to add new CHILD below it."
10565 (unless parent-target
10566 (error "Cannot find parent for new node"))
10567 (let ((file (nth 1 parent-target))
10568 (pos (nth 3 parent-target))
10569 level)
10570 (with-current-buffer (or (find-buffer-visiting file)
10571 (find-file-noselect file))
10572 (save-excursion
10573 (save-restriction
10574 (widen)
10575 (if pos
10576 (goto-char pos)
10577 (goto-char (point-max))
10578 (if (not (bolp)) (newline)))
10579 (when (looking-at outline-regexp)
10580 (setq level (funcall outline-level))
10581 (org-end-of-subtree t t))
10582 (org-back-over-empty-lines)
10583 (insert "\n" (make-string
10584 (if pos (org-get-valid-level level 1) 1) ?*)
10585 " " child "\n")
10586 (beginning-of-line 0)
10587 (list (concat (car parent-target) "/" child) file "" (point)))))))
10589 (defun org-olpath-completing-read (prompt collection &rest args)
10590 "Read an outline path like a file name."
10591 (let ((thetable collection)
10592 (org-completion-use-ido nil) ; does not work with ido.
10593 (org-completion-use-iswitchb nil)) ; or iswitchb
10594 (apply
10595 'org-icompleting-read prompt
10596 (lambda (string predicate &optional flag)
10597 (let (rtn r f (l (length string)))
10598 (cond
10599 ((eq flag nil)
10600 ;; try completion
10601 (try-completion string thetable))
10602 ((eq flag t)
10603 ;; all-completions
10604 (setq rtn (all-completions string thetable predicate))
10605 (mapcar
10606 (lambda (x)
10607 (setq r (substring x l))
10608 (if (string-match " ([^)]*)$" x)
10609 (setq f (match-string 0 x))
10610 (setq f ""))
10611 (if (string-match "/" r)
10612 (concat string (substring r 0 (match-end 0)) f)
10614 rtn))
10615 ((eq flag 'lambda)
10616 ;; exact match?
10617 (assoc string thetable)))
10619 args)))
10621 ;;;; Dynamic blocks
10623 (defun org-find-dblock (name)
10624 "Find the first dynamic block with name NAME in the buffer.
10625 If not found, stay at current position and return nil."
10626 (let (pos)
10627 (save-excursion
10628 (goto-char (point-min))
10629 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
10630 nil t)
10631 (match-beginning 0))))
10632 (if pos (goto-char pos))
10633 pos))
10635 (defconst org-dblock-start-re
10636 "^[ \t]*#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
10637 "Matches the start line of a dynamic block, with parameters.")
10639 (defconst org-dblock-end-re "^[ \t]*#\\+END\\([: \t\r\n]\\|$\\)"
10640 "Matches the end of a dynamic block.")
10642 (defun org-create-dblock (plist)
10643 "Create a dynamic block section, with parameters taken from PLIST.
10644 PLIST must contain a :name entry which is used as name of the block."
10645 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
10646 (end-of-line 1)
10647 (newline))
10648 (let ((col (current-column))
10649 (name (plist-get plist :name)))
10650 (insert "#+BEGIN: " name)
10651 (while plist
10652 (if (eq (car plist) :name)
10653 (setq plist (cddr plist))
10654 (insert " " (prin1-to-string (pop plist)))))
10655 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
10656 (beginning-of-line -2)))
10658 (defun org-prepare-dblock ()
10659 "Prepare dynamic block for refresh.
10660 This empties the block, puts the cursor at the insert position and returns
10661 the property list including an extra property :name with the block name."
10662 (unless (looking-at org-dblock-start-re)
10663 (error "Not at a dynamic block"))
10664 (let* ((begdel (1+ (match-end 0)))
10665 (name (org-no-properties (match-string 1)))
10666 (params (append (list :name name)
10667 (read (concat "(" (match-string 3) ")")))))
10668 (save-excursion
10669 (beginning-of-line 1)
10670 (skip-chars-forward " \t")
10671 (setq params (plist-put params :indentation-column (current-column))))
10672 (unless (re-search-forward org-dblock-end-re nil t)
10673 (error "Dynamic block not terminated"))
10674 (setq params
10675 (append params
10676 (list :content (buffer-substring
10677 begdel (match-beginning 0)))))
10678 (delete-region begdel (match-beginning 0))
10679 (goto-char begdel)
10680 (open-line 1)
10681 params))
10683 (defun org-map-dblocks (&optional command)
10684 "Apply COMMAND to all dynamic blocks in the current buffer.
10685 If COMMAND is not given, use `org-update-dblock'."
10686 (let ((cmd (or command 'org-update-dblock)))
10687 (save-excursion
10688 (goto-char (point-min))
10689 (while (re-search-forward org-dblock-start-re nil t)
10690 (goto-char (match-beginning 0))
10691 (save-excursion
10692 (condition-case nil
10693 (funcall cmd)
10694 (error (message "Error during update of dynamic block"))))
10695 (unless (re-search-forward org-dblock-end-re nil t)
10696 (error "Dynamic block not terminated"))))))
10698 (defun org-dblock-update (&optional arg)
10699 "User command for updating dynamic blocks.
10700 Update the dynamic block at point. With prefix ARG, update all dynamic
10701 blocks in the buffer."
10702 (interactive "P")
10703 (if arg
10704 (org-update-all-dblocks)
10705 (or (looking-at org-dblock-start-re)
10706 (org-beginning-of-dblock))
10707 (org-update-dblock)))
10709 (defun org-update-dblock ()
10710 "Update the dynamic block at point.
10711 This means to empty the block, parse for parameters and then call
10712 the correct writing function."
10713 (interactive)
10714 (save-window-excursion
10715 (let* ((pos (point))
10716 (line (org-current-line))
10717 (params (org-prepare-dblock))
10718 (name (plist-get params :name))
10719 (indent (plist-get params :indentation-column))
10720 (cmd (intern (concat "org-dblock-write:" name))))
10721 (message "Updating dynamic block `%s' at line %d..." name line)
10722 (funcall cmd params)
10723 (message "Updating dynamic block `%s' at line %d...done" name line)
10724 (goto-char pos)
10725 (when (and indent (> indent 0))
10726 (setq indent (make-string indent ?\ ))
10727 (save-excursion
10728 (org-beginning-of-dblock)
10729 (forward-line 1)
10730 (while (not (looking-at org-dblock-end-re))
10731 (insert indent)
10732 (beginning-of-line 2))
10733 (when (looking-at org-dblock-end-re)
10734 (and (looking-at "[ \t]+")
10735 (replace-match ""))
10736 (insert indent)))))))
10738 (defun org-beginning-of-dblock ()
10739 "Find the beginning of the dynamic block at point.
10740 Error if there is no such block at point."
10741 (let ((pos (point))
10742 beg)
10743 (end-of-line 1)
10744 (if (and (re-search-backward org-dblock-start-re nil t)
10745 (setq beg (match-beginning 0))
10746 (re-search-forward org-dblock-end-re nil t)
10747 (> (match-end 0) pos))
10748 (goto-char beg)
10749 (goto-char pos)
10750 (error "Not in a dynamic block"))))
10752 (defun org-update-all-dblocks ()
10753 "Update all dynamic blocks in the buffer.
10754 This function can be used in a hook."
10755 (interactive)
10756 (when (org-mode-p)
10757 (org-map-dblocks 'org-update-dblock)))
10760 ;;;; Completion
10762 (defconst org-additional-option-like-keywords
10763 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML:"
10764 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook:"
10765 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"
10766 "LATEX_CLASS:" "LATEX_CLASS_OPTIONS:" "ATTR_LaTeX:"
10767 "BEGIN:" "END:"
10768 "ORGTBL" "TBLFM:" "TBLNAME:"
10769 "BEGIN_EXAMPLE" "END_EXAMPLE"
10770 "BEGIN_QUOTE" "END_QUOTE"
10771 "BEGIN_VERSE" "END_VERSE"
10772 "BEGIN_CENTER" "END_CENTER"
10773 "BEGIN_SRC" "END_SRC"
10774 "BEGIN_RESULT" "END_RESULT"
10775 "SOURCE:" "SRCNAME:" "FUNCTION:"
10776 "RESULTS:"
10777 "HEADER:" "HEADERS:"
10778 "BABEL:"
10779 "CATEGORY:" "COLUMNS:" "PROPERTY:"
10780 "CAPTION:" "LABEL:"
10781 "SETUPFILE:"
10782 "INCLUDE:"
10783 "BIND:"
10784 "MACRO:"))
10786 (defcustom org-structure-template-alist
10788 ("s" "#+begin_src ?\n\n#+end_src"
10789 "<src lang=\"?\">\n\n</src>")
10790 ("e" "#+begin_example\n?\n#+end_example"
10791 "<example>\n?\n</example>")
10792 ("q" "#+begin_quote\n?\n#+end_quote"
10793 "<quote>\n?\n</quote>")
10794 ("v" "#+begin_verse\n?\n#+end_verse"
10795 "<verse>\n?\n/verse>")
10796 ("c" "#+begin_center\n?\n#+end_center"
10797 "<center>\n?\n/center>")
10798 ("l" "#+begin_latex\n?\n#+end_latex"
10799 "<literal style=\"latex\">\n?\n</literal>")
10800 ("L" "#+latex: "
10801 "<literal style=\"latex\">?</literal>")
10802 ("h" "#+begin_html\n?\n#+end_html"
10803 "<literal style=\"html\">\n?\n</literal>")
10804 ("H" "#+html: "
10805 "<literal style=\"html\">?</literal>")
10806 ("a" "#+begin_ascii\n?\n#+end_ascii")
10807 ("A" "#+ascii: ")
10808 ("i" "#+include %file ?"
10809 "<include file=%file markup=\"?\">")
10811 "Structure completion elements.
10812 This is a list of abbreviation keys and values. The value gets inserted
10813 if you type `<' followed by the key and then press the completion key,
10814 usually `M-TAB'. %file will be replaced by a file name after prompting
10815 for the file using completion.
10816 There are two templates for each key, the first uses the original Org syntax,
10817 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
10818 the default when the /org-mtags.el/ module has been loaded. See also the
10819 variable `org-mtags-prefer-muse-templates'.
10820 This is an experimental feature, it is undecided if it is going to stay in."
10821 :group 'org-completion
10822 :type '(repeat
10823 (string :tag "Key")
10824 (string :tag "Template")
10825 (string :tag "Muse Template")))
10827 (defun org-try-structure-completion ()
10828 "Try to complete a structure template before point.
10829 This looks for strings like \"<e\" on an otherwise empty line and
10830 expands them."
10831 (let ((l (buffer-substring (point-at-bol) (point)))
10833 (when (and (looking-at "[ \t]*$")
10834 (string-match "^[ \t]*<\\([a-z]+\\)$"l)
10835 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
10836 (org-complete-expand-structure-template (+ -1 (point-at-bol)
10837 (match-beginning 1)) a)
10838 t)))
10840 (defun org-complete-expand-structure-template (start cell)
10841 "Expand a structure template."
10842 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
10843 (rpl (nth (if musep 2 1) cell))
10844 (ind ""))
10845 (delete-region start (point))
10846 (when (string-match "\\`#\\+" rpl)
10847 (cond
10848 ((bolp))
10849 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
10850 (setq ind (buffer-substring (point-at-bol) (point))))
10851 (t (newline))))
10852 (setq start (point))
10853 (if (string-match "%file" rpl)
10854 (setq rpl (replace-match
10855 (concat
10856 "\""
10857 (save-match-data
10858 (abbreviate-file-name (read-file-name "Include file: ")))
10859 "\"")
10860 t t rpl)))
10861 (setq rpl (mapconcat 'identity (split-string rpl "\n")
10862 (concat "\n" ind)))
10863 (insert rpl)
10864 (if (re-search-backward "\\?" start t) (delete-char 1))))
10866 ;;;; TODO, DEADLINE, Comments
10868 (defun org-toggle-comment ()
10869 "Change the COMMENT state of an entry."
10870 (interactive)
10871 (save-excursion
10872 (org-back-to-heading)
10873 (let (case-fold-search)
10874 (if (looking-at (concat outline-regexp
10875 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
10876 (replace-match "" t t nil 1)
10877 (if (looking-at outline-regexp)
10878 (progn
10879 (goto-char (match-end 0))
10880 (insert org-comment-string " ")))))))
10882 (defvar org-last-todo-state-is-todo nil
10883 "This is non-nil when the last TODO state change led to a TODO state.
10884 If the last change removed the TODO tag or switched to DONE, then
10885 this is nil.")
10887 (defvar org-setting-tags nil) ; dynamically skipped
10889 (defvar org-todo-setup-filter-hook nil
10890 "Hook for functions that pre-filter todo specs.
10891 Each function takes a todo spec and returns either nil or the spec
10892 transformed into canonical form." )
10894 (defvar org-todo-get-default-hook nil
10895 "Hook for functions that get a default item for todo.
10896 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
10897 nil or a string to be used for the todo mark." )
10899 (defvar org-agenda-headline-snapshot-before-repeat)
10901 (defun org-todo (&optional arg)
10902 "Change the TODO state of an item.
10903 The state of an item is given by a keyword at the start of the heading,
10904 like
10905 *** TODO Write paper
10906 *** DONE Call mom
10908 The different keywords are specified in the variable `org-todo-keywords'.
10909 By default the available states are \"TODO\" and \"DONE\".
10910 So for this example: when the item starts with TODO, it is changed to DONE.
10911 When it starts with DONE, the DONE is removed. And when neither TODO nor
10912 DONE are present, add TODO at the beginning of the heading.
10914 With \\[universal-argument] prefix arg, use completion to determine the new \
10915 state.
10916 With numeric prefix arg, switch to that state.
10917 With a double \\[universal-argument] prefix, switch to the next set of TODO \
10918 keywords (nextset).
10919 With a triple \\[universal-argument] prefix, circumvent any state blocking.
10921 For calling through lisp, arg is also interpreted in the following way:
10922 'none -> empty state
10923 \"\"(empty string) -> switch to empty state
10924 'done -> switch to DONE
10925 'nextset -> switch to the next set of keywords
10926 'previousset -> switch to the previous set of keywords
10927 \"WAITING\" -> switch to the specified keyword, but only if it
10928 really is a member of `org-todo-keywords'."
10929 (interactive "P")
10930 (if (equal arg '(16)) (setq arg 'nextset))
10931 (let ((org-blocker-hook org-blocker-hook)
10932 (case-fold-search nil))
10933 (when (equal arg '(64))
10934 (setq arg nil org-blocker-hook nil))
10935 (when (and org-blocker-hook
10936 (or org-inhibit-blocking
10937 (org-entry-get nil "NOBLOCKING")))
10938 (setq org-blocker-hook nil))
10939 (save-excursion
10940 (catch 'exit
10941 (org-back-to-heading t)
10942 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
10943 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|$\\)"))
10944 (looking-at " *"))
10945 (let* ((match-data (match-data))
10946 (startpos (point-at-bol))
10947 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
10948 (org-log-done org-log-done)
10949 (org-log-repeat org-log-repeat)
10950 (org-todo-log-states org-todo-log-states)
10951 (this (match-string 1))
10952 (hl-pos (match-beginning 0))
10953 (head (org-get-todo-sequence-head this))
10954 (ass (assoc head org-todo-kwd-alist))
10955 (interpret (nth 1 ass))
10956 (done-word (nth 3 ass))
10957 (final-done-word (nth 4 ass))
10958 (last-state (or this ""))
10959 (completion-ignore-case t)
10960 (member (member this org-todo-keywords-1))
10961 (tail (cdr member))
10962 (state (cond
10963 ((and org-todo-key-trigger
10964 (or (and (equal arg '(4))
10965 (eq org-use-fast-todo-selection 'prefix))
10966 (and (not arg) org-use-fast-todo-selection
10967 (not (eq org-use-fast-todo-selection
10968 'prefix)))))
10969 ;; Use fast selection
10970 (org-fast-todo-selection))
10971 ((and (equal arg '(4))
10972 (or (not org-use-fast-todo-selection)
10973 (not org-todo-key-trigger)))
10974 ;; Read a state with completion
10975 (org-icompleting-read
10976 "State: " (mapcar (lambda(x) (list x))
10977 org-todo-keywords-1)
10978 nil t))
10979 ((eq arg 'right)
10980 (if this
10981 (if tail (car tail) nil)
10982 (car org-todo-keywords-1)))
10983 ((eq arg 'left)
10984 (if (equal member org-todo-keywords-1)
10986 (if this
10987 (nth (- (length org-todo-keywords-1)
10988 (length tail) 2)
10989 org-todo-keywords-1)
10990 (org-last org-todo-keywords-1))))
10991 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
10992 (setq arg nil))) ; hack to fall back to cycling
10993 (arg
10994 ;; user or caller requests a specific state
10995 (cond
10996 ((equal arg "") nil)
10997 ((eq arg 'none) nil)
10998 ((eq arg 'done) (or done-word (car org-done-keywords)))
10999 ((eq arg 'nextset)
11000 (or (car (cdr (member head org-todo-heads)))
11001 (car org-todo-heads)))
11002 ((eq arg 'previousset)
11003 (let ((org-todo-heads (reverse org-todo-heads)))
11004 (or (car (cdr (member head org-todo-heads)))
11005 (car org-todo-heads))))
11006 ((car (member arg org-todo-keywords-1)))
11007 ((stringp arg)
11008 (error "State `%s' not valid in this file" arg))
11009 ((nth (1- (prefix-numeric-value arg))
11010 org-todo-keywords-1))))
11011 ((null member) (or head (car org-todo-keywords-1)))
11012 ((equal this final-done-word) nil) ;; -> make empty
11013 ((null tail) nil) ;; -> first entry
11014 ((memq interpret '(type priority))
11015 (if (eq this-command last-command)
11016 (car tail)
11017 (if (> (length tail) 0)
11018 (or done-word (car org-done-keywords))
11019 nil)))
11021 (car tail))))
11022 (state (or
11023 (run-hook-with-args-until-success
11024 'org-todo-get-default-hook state last-state)
11025 state))
11026 (next (if state (concat " " state " ") " "))
11027 (change-plist (list :type 'todo-state-change :from this :to state
11028 :position startpos))
11029 dolog now-done-p)
11030 (when org-blocker-hook
11031 (setq org-last-todo-state-is-todo
11032 (not (member this org-done-keywords)))
11033 (unless (save-excursion
11034 (save-match-data
11035 (org-with-wide-buffer
11036 (run-hook-with-args-until-failure
11037 'org-blocker-hook change-plist))))
11038 (if (interactive-p)
11039 (error "TODO state change from %s to %s blocked" this state)
11040 ;; fail silently
11041 (message "TODO state change from %s to %s blocked" this state)
11042 (throw 'exit nil))))
11043 (store-match-data match-data)
11044 (replace-match next t t)
11045 (unless (pos-visible-in-window-p hl-pos)
11046 (message "TODO state changed to %s" (org-trim next)))
11047 (unless head
11048 (setq head (org-get-todo-sequence-head state)
11049 ass (assoc head org-todo-kwd-alist)
11050 interpret (nth 1 ass)
11051 done-word (nth 3 ass)
11052 final-done-word (nth 4 ass)))
11053 (when (memq arg '(nextset previousset))
11054 (message "Keyword-Set %d/%d: %s"
11055 (- (length org-todo-sets) -1
11056 (length (memq (assoc state org-todo-sets) org-todo-sets)))
11057 (length org-todo-sets)
11058 (mapconcat 'identity (assoc state org-todo-sets) " ")))
11059 (setq org-last-todo-state-is-todo
11060 (not (member state org-done-keywords)))
11061 (setq now-done-p (and (member state org-done-keywords)
11062 (not (member this org-done-keywords))))
11063 (and logging (org-local-logging logging))
11064 (when (and (or org-todo-log-states org-log-done)
11065 (not (eq org-inhibit-logging t))
11066 (not (memq arg '(nextset previousset))))
11067 ;; we need to look at recording a time and note
11068 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
11069 (nth 2 (assoc this org-todo-log-states))))
11070 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
11071 (setq dolog 'time))
11072 (when (and state
11073 (member state org-not-done-keywords)
11074 (not (member this org-not-done-keywords)))
11075 ;; This is now a todo state and was not one before
11076 ;; If there was a CLOSED time stamp, get rid of it.
11077 (org-add-planning-info nil nil 'closed))
11078 (when (and now-done-p org-log-done)
11079 ;; It is now done, and it was not done before
11080 (org-add-planning-info 'closed (org-current-time))
11081 (if (and (not dolog) (eq 'note org-log-done))
11082 (org-add-log-setup 'done state this 'findpos 'note)))
11083 (when (and state dolog)
11084 ;; This is a non-nil state, and we need to log it
11085 (org-add-log-setup 'state state this 'findpos dolog)))
11086 ;; Fixup tag positioning
11087 (org-todo-trigger-tag-changes state)
11088 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
11089 (when org-provide-todo-statistics
11090 (org-update-parent-todo-statistics))
11091 (run-hooks 'org-after-todo-state-change-hook)
11092 (if (and arg (not (member state org-done-keywords)))
11093 (setq head (org-get-todo-sequence-head state)))
11094 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
11095 ;; Do we need to trigger a repeat?
11096 (when now-done-p
11097 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
11098 ;; This is for the agenda, take a snapshot of the headline.
11099 (save-match-data
11100 (setq org-agenda-headline-snapshot-before-repeat
11101 (org-get-heading))))
11102 (org-auto-repeat-maybe state))
11103 ;; Fixup cursor location if close to the keyword
11104 (if (and (outline-on-heading-p)
11105 (not (bolp))
11106 (save-excursion (beginning-of-line 1)
11107 (looking-at org-todo-line-regexp))
11108 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
11109 (progn
11110 (goto-char (or (match-end 2) (match-end 1)))
11111 (and (looking-at " ") (just-one-space))))
11112 (when org-trigger-hook
11113 (save-excursion
11114 (run-hook-with-args 'org-trigger-hook change-plist))))))))
11116 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
11117 "Block turning an entry into a TODO, using the hierarchy.
11118 This checks whether the current task should be blocked from state
11119 changes. Such blocking occurs when:
11121 1. The task has children which are not all in a completed state.
11123 2. A task has a parent with the property :ORDERED:, and there
11124 are siblings prior to the current task with incomplete
11125 status.
11127 3. The parent of the task is blocked because it has siblings that should
11128 be done first, or is child of a block grandparent TODO entry."
11130 (if (not org-enforce-todo-dependencies)
11131 t ; if locally turned off don't block
11132 (catch 'dont-block
11133 ;; If this is not a todo state change, or if this entry is already DONE,
11134 ;; do not block
11135 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11136 (member (plist-get change-plist :from)
11137 (cons 'done org-done-keywords))
11138 (member (plist-get change-plist :to)
11139 (cons 'todo org-not-done-keywords))
11140 (not (plist-get change-plist :to)))
11141 (throw 'dont-block t))
11142 ;; If this task has children, and any are undone, it's blocked
11143 (save-excursion
11144 (org-back-to-heading t)
11145 (let ((this-level (funcall outline-level)))
11146 (outline-next-heading)
11147 (let ((child-level (funcall outline-level)))
11148 (while (and (not (eobp))
11149 (> child-level this-level))
11150 ;; this todo has children, check whether they are all
11151 ;; completed
11152 (if (and (not (org-entry-is-done-p))
11153 (org-entry-is-todo-p))
11154 (throw 'dont-block nil))
11155 (outline-next-heading)
11156 (setq child-level (funcall outline-level))))))
11157 ;; Otherwise, if the task's parent has the :ORDERED: property, and
11158 ;; any previous siblings are undone, it's blocked
11159 (save-excursion
11160 (org-back-to-heading t)
11161 (let* ((pos (point))
11162 (parent-pos (and (org-up-heading-safe) (point))))
11163 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11164 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11165 (forward-line 1)
11166 (re-search-forward org-not-done-heading-regexp pos t))
11167 (throw 'dont-block nil)) ; block, there is an older sibling not done.
11168 ;; Search further up the hierarchy, to see if an anchestor is blocked
11169 (while t
11170 (goto-char parent-pos)
11171 (if (not (looking-at org-not-done-heading-regexp))
11172 (throw 'dont-block t)) ; do not block, parent is not a TODO
11173 (setq pos (point))
11174 (setq parent-pos (and (org-up-heading-safe) (point)))
11175 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11176 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11177 (forward-line 1)
11178 (re-search-forward org-not-done-heading-regexp pos t))
11179 (throw 'dont-block nil)))))))) ; block, older sibling not done.
11181 (defcustom org-track-ordered-property-with-tag nil
11182 "Should the ORDERED property also be shown as a tag?
11183 The ORDERED property decides if an entry should require subtasks to be
11184 completed in sequence. Since a property is not very visible, setting
11185 this option means that toggling the ORDERED property with the command
11186 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
11187 not relevant for the behavior, but it makes things more visible.
11189 Note that toggling the tag with tags commands will not change the property
11190 and therefore not influence behavior!
11192 This can be t, meaning the tag ORDERED should be used, It can also be a
11193 string to select a different tag for this task."
11194 :group 'org-todo
11195 :type '(choice
11196 (const :tag "No tracking" nil)
11197 (const :tag "Track with ORDERED tag" t)
11198 (string :tag "Use other tag")))
11200 (defun org-toggle-ordered-property ()
11201 "Toggle the ORDERED property of the current entry.
11202 For better visibility, you can track the value of this property with a tag.
11203 See variable `org-track-ordered-property-with-tag'."
11204 (interactive)
11205 (let* ((t1 org-track-ordered-property-with-tag)
11206 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
11207 (save-excursion
11208 (org-back-to-heading)
11209 (if (org-entry-get nil "ORDERED")
11210 (progn
11211 (org-delete-property "ORDERED")
11212 (and tag (org-toggle-tag tag 'off))
11213 (message "Subtasks can be completed in arbitrary order"))
11214 (org-entry-put nil "ORDERED" "t")
11215 (and tag (org-toggle-tag tag 'on))
11216 (message "Subtasks must be completed in sequence")))))
11218 (defvar org-blocked-by-checkboxes) ; dynamically scoped
11219 (defun org-block-todo-from-checkboxes (change-plist)
11220 "Block turning an entry into a TODO, using checkboxes.
11221 This checks whether the current task should be blocked from state
11222 changes because there are unchecked boxes in this entry."
11223 (if (not org-enforce-todo-checkbox-dependencies)
11224 t ; if locally turned off don't block
11225 (catch 'dont-block
11226 ;; If this is not a todo state change, or if this entry is already DONE,
11227 ;; do not block
11228 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11229 (member (plist-get change-plist :from)
11230 (cons 'done org-done-keywords))
11231 (member (plist-get change-plist :to)
11232 (cons 'todo org-not-done-keywords))
11233 (not (plist-get change-plist :to)))
11234 (throw 'dont-block t))
11235 ;; If this task has checkboxes that are not checked, it's blocked
11236 (save-excursion
11237 (org-back-to-heading t)
11238 (let ((beg (point)) end)
11239 (outline-next-heading)
11240 (setq end (point))
11241 (goto-char beg)
11242 (if (re-search-forward "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\)[ \t]+\\[[- ]\\]"
11243 end t)
11244 (progn
11245 (if (boundp 'org-blocked-by-checkboxes)
11246 (setq org-blocked-by-checkboxes t))
11247 (throw 'dont-block nil)))))
11248 t))) ; do not block
11250 (defun org-entry-blocked-p ()
11251 "Is the current entry blocked?"
11252 (if (org-entry-get nil "NOBLOCKING")
11253 nil ;; Never block this entry
11254 (not
11255 (run-hook-with-args-until-failure
11256 'org-blocker-hook
11257 (list :type 'todo-state-change
11258 :position (point)
11259 :from 'todo
11260 :to 'done)))))
11262 (defun org-update-statistics-cookies (all)
11263 "Update the statistics cookie, either from TODO or from checkboxes.
11264 This should be called with the cursor in a line with a statistics cookie."
11265 (interactive "P")
11266 (if all
11267 (progn
11268 (org-update-checkbox-count 'all)
11269 (org-map-entries 'org-update-parent-todo-statistics))
11270 (if (not (org-on-heading-p))
11271 (org-update-checkbox-count)
11272 (let ((pos (move-marker (make-marker) (point)))
11273 end l1 l2)
11274 (ignore-errors (org-back-to-heading t))
11275 (if (not (org-on-heading-p))
11276 (org-update-checkbox-count)
11277 (setq l1 (org-outline-level))
11278 (setq end (save-excursion
11279 (outline-next-heading)
11280 (if (org-on-heading-p) (setq l2 (org-outline-level)))
11281 (point)))
11282 (if (and (save-excursion
11283 (re-search-forward
11284 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
11285 (not (save-excursion (re-search-forward
11286 ":COOKIE_DATA:.*\\<todo\\>" end t))))
11287 (org-update-checkbox-count)
11288 (if (and l2 (> l2 l1))
11289 (progn
11290 (goto-char end)
11291 (org-update-parent-todo-statistics))
11292 (goto-char pos)
11293 (beginning-of-line 1)
11294 (while (re-search-forward
11295 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
11296 (point-at-eol) t)
11297 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
11298 (goto-char pos)
11299 (move-marker pos nil)))))
11301 (defvar org-entry-property-inherited-from) ;; defined below
11302 (defun org-update-parent-todo-statistics ()
11303 "Update any statistics cookie in the parent of the current headline.
11304 When `org-hierarchical-todo-statistics' is nil, statistics will cover
11305 the entire subtree and this will travel up the hierarchy and update
11306 statistics everywhere."
11307 (interactive)
11308 (let* ((lim 0) prop
11309 (recursive (or (not org-hierarchical-todo-statistics)
11310 (string-match
11311 "\\<recursive\\>"
11312 (or (setq prop (org-entry-get
11313 nil "COOKIE_DATA" 'inherit)) ""))))
11314 (lim (or (and prop (marker-position
11315 org-entry-property-inherited-from))
11316 lim))
11317 (first t)
11318 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
11319 level ltoggle l1 new ndel
11320 (cnt-all 0) (cnt-done 0) is-percent kwd
11321 checkbox-beg ov ovs ove cookie-present)
11322 (catch 'exit
11323 (save-excursion
11324 (beginning-of-line 1)
11325 (if (org-at-heading-p)
11326 (setq ltoggle (funcall outline-level))
11327 (error "This should not happen"))
11328 (while (and (setq level (org-up-heading-safe))
11329 (or recursive first)
11330 (>= (point) lim))
11331 (setq first nil cookie-present nil)
11332 (unless (and level
11333 (not (string-match
11334 "\\<checkbox\\>"
11335 (downcase
11336 (or (org-entry-get
11337 nil "COOKIE_DATA")
11338 "")))))
11339 (throw 'exit nil))
11340 (while (re-search-forward box-re (point-at-eol) t)
11341 (setq cnt-all 0 cnt-done 0 cookie-present t)
11342 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
11343 (save-match-data
11344 (unless (outline-next-heading) (throw 'exit nil))
11345 (while (and (looking-at org-complex-heading-regexp)
11346 (> (setq l1 (length (match-string 1))) level))
11347 (setq kwd (and (or recursive (= l1 ltoggle))
11348 (match-string 2)))
11349 (if (or (eq org-provide-todo-statistics 'all-headlines)
11350 (and (listp org-provide-todo-statistics)
11351 (or (member kwd org-provide-todo-statistics)
11352 (member kwd org-done-keywords))))
11353 (setq cnt-all (1+ cnt-all))
11354 (if (eq org-provide-todo-statistics t)
11355 (and kwd (setq cnt-all (1+ cnt-all)))))
11356 (and (member kwd org-done-keywords)
11357 (setq cnt-done (1+ cnt-done)))
11358 (outline-next-heading)))
11359 (setq new
11360 (if is-percent
11361 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
11362 (format "[%d/%d]" cnt-done cnt-all))
11363 ndel (- (match-end 0) checkbox-beg))
11364 ;; handle overlays when updating cookie from column view
11365 (when (setq ov (car (overlays-at checkbox-beg)))
11366 (setq ovs (overlay-start ov) ove (overlay-end ov))
11367 (delete-overlay ov))
11368 (goto-char checkbox-beg)
11369 (insert new)
11370 (delete-region (point) (+ (point) ndel))
11371 (when ov (move-overlay ov ovs ove)))
11372 (when cookie-present
11373 (run-hook-with-args 'org-after-todo-statistics-hook
11374 cnt-done (- cnt-all cnt-done))))))
11375 (run-hooks 'org-todo-statistics-hook)))
11377 (defvar org-after-todo-statistics-hook nil
11378 "Hook that is called after a TODO statistics cookie has been updated.
11379 Each function is called with two arguments: the number of not-done entries
11380 and the number of done entries.
11382 For example, the following function, when added to this hook, will switch
11383 an entry to DONE when all children are done, and back to TODO when new
11384 entries are set to a TODO status. Note that this hook is only called
11385 when there is a statistics cookie in the headline!
11387 (defun org-summary-todo (n-done n-not-done)
11388 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
11389 (let (org-log-done org-log-states) ; turn off logging
11390 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
11393 (defvar org-todo-statistics-hook nil
11394 "Hook that is run whenever Org thinks TODO statistics should be updated.
11395 This hook runs even if there is no statistics cookie present, in which case
11396 `org-after-todo-statistics-hook' would not run.")
11398 (defun org-todo-trigger-tag-changes (state)
11399 "Apply the changes defined in `org-todo-state-tags-triggers'."
11400 (let ((l org-todo-state-tags-triggers)
11401 changes)
11402 (when (or (not state) (equal state ""))
11403 (setq changes (append changes (cdr (assoc "" l)))))
11404 (when (and (stringp state) (> (length state) 0))
11405 (setq changes (append changes (cdr (assoc state l)))))
11406 (when (member state org-not-done-keywords)
11407 (setq changes (append changes (cdr (assoc 'todo l)))))
11408 (when (member state org-done-keywords)
11409 (setq changes (append changes (cdr (assoc 'done l)))))
11410 (dolist (c changes)
11411 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
11413 (defun org-local-logging (value)
11414 "Get logging settings from a property VALUE."
11415 (let* (words w a)
11416 ;; directly set the variables, they are already local.
11417 (setq org-log-done nil
11418 org-log-repeat nil
11419 org-todo-log-states nil)
11420 (setq words (org-split-string value))
11421 (while (setq w (pop words))
11422 (cond
11423 ((setq a (assoc w org-startup-options))
11424 (and (member (nth 1 a) '(org-log-done org-log-repeat))
11425 (set (nth 1 a) (nth 2 a))))
11426 ((setq a (org-extract-log-state-settings w))
11427 (and (member (car a) org-todo-keywords-1)
11428 (push a org-todo-log-states)))))))
11430 (defun org-get-todo-sequence-head (kwd)
11431 "Return the head of the TODO sequence to which KWD belongs.
11432 If KWD is not set, check if there is a text property remembering the
11433 right sequence."
11434 (let (p)
11435 (cond
11436 ((not kwd)
11437 (or (get-text-property (point-at-bol) 'org-todo-head)
11438 (progn
11439 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
11440 nil (point-at-eol)))
11441 (get-text-property p 'org-todo-head))))
11442 ((not (member kwd org-todo-keywords-1))
11443 (car org-todo-keywords-1))
11444 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
11446 (defun org-fast-todo-selection ()
11447 "Fast TODO keyword selection with single keys.
11448 Returns the new TODO keyword, or nil if no state change should occur."
11449 (let* ((fulltable org-todo-key-alist)
11450 (done-keywords org-done-keywords) ;; needed for the faces.
11451 (maxlen (apply 'max (mapcar
11452 (lambda (x)
11453 (if (stringp (car x)) (string-width (car x)) 0))
11454 fulltable)))
11455 (expert nil)
11456 (fwidth (+ maxlen 3 1 3))
11457 (ncol (/ (- (window-width) 4) fwidth))
11458 tg cnt e c tbl
11459 groups ingroup)
11460 (save-excursion
11461 (save-window-excursion
11462 (if expert
11463 (set-buffer (get-buffer-create " *Org todo*"))
11464 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
11465 (erase-buffer)
11466 (org-set-local 'org-done-keywords done-keywords)
11467 (setq tbl fulltable cnt 0)
11468 (while (setq e (pop tbl))
11469 (cond
11470 ((equal e '(:startgroup))
11471 (push '() groups) (setq ingroup t)
11472 (when (not (= cnt 0))
11473 (setq cnt 0)
11474 (insert "\n"))
11475 (insert "{ "))
11476 ((equal e '(:endgroup))
11477 (setq ingroup nil cnt 0)
11478 (insert "}\n"))
11479 ((equal e '(:newline))
11480 (when (not (= cnt 0))
11481 (setq cnt 0)
11482 (insert "\n")
11483 (setq e (car tbl))
11484 (while (equal (car tbl) '(:newline))
11485 (insert "\n")
11486 (setq tbl (cdr tbl)))))
11488 (setq tg (car e) c (cdr e))
11489 (if ingroup (push tg (car groups)))
11490 (setq tg (org-add-props tg nil 'face
11491 (org-get-todo-face tg)))
11492 (if (and (= cnt 0) (not ingroup)) (insert " "))
11493 (insert "[" c "] " tg (make-string
11494 (- fwidth 4 (length tg)) ?\ ))
11495 (when (= (setq cnt (1+ cnt)) ncol)
11496 (insert "\n")
11497 (if ingroup (insert " "))
11498 (setq cnt 0)))))
11499 (insert "\n")
11500 (goto-char (point-min))
11501 (if (not expert) (org-fit-window-to-buffer))
11502 (message "[a-z..]:Set [SPC]:clear")
11503 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
11504 (cond
11505 ((or (= c ?\C-g)
11506 (and (= c ?q) (not (rassoc c fulltable))))
11507 (setq quit-flag t))
11508 ((= c ?\ ) nil)
11509 ((setq e (rassoc c fulltable) tg (car e))
11511 (t (setq quit-flag t)))))))
11513 (defun org-entry-is-todo-p ()
11514 (member (org-get-todo-state) org-not-done-keywords))
11516 (defun org-entry-is-done-p ()
11517 (member (org-get-todo-state) org-done-keywords))
11519 (defun org-get-todo-state ()
11520 (save-excursion
11521 (org-back-to-heading t)
11522 (and (looking-at org-todo-line-regexp)
11523 (match-end 2)
11524 (match-string 2))))
11526 (defun org-at-date-range-p (&optional inactive-ok)
11527 "Is the cursor inside a date range?"
11528 (interactive)
11529 (save-excursion
11530 (catch 'exit
11531 (let ((pos (point)))
11532 (skip-chars-backward "^[<\r\n")
11533 (skip-chars-backward "<[")
11534 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
11535 (>= (match-end 0) pos)
11536 (throw 'exit t))
11537 (skip-chars-backward "^<[\r\n")
11538 (skip-chars-backward "<[")
11539 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
11540 (>= (match-end 0) pos)
11541 (throw 'exit t)))
11542 nil)))
11544 (defun org-get-repeat (&optional tagline)
11545 "Check if there is a deadline/schedule with repeater in this entry."
11546 (save-match-data
11547 (save-excursion
11548 (org-back-to-heading t)
11549 (and (re-search-forward (if tagline
11550 (concat tagline "\\s-*" org-repeat-re)
11551 org-repeat-re)
11552 (org-entry-end-position) t)
11553 (match-string-no-properties 1)))))
11555 (defvar org-last-changed-timestamp)
11556 (defvar org-last-inserted-timestamp)
11557 (defvar org-log-post-message)
11558 (defvar org-log-note-purpose)
11559 (defvar org-log-note-how)
11560 (defvar org-log-note-extra)
11561 (defun org-auto-repeat-maybe (done-word)
11562 "Check if the current headline contains a repeated deadline/schedule.
11563 If yes, set TODO state back to what it was and change the base date
11564 of repeating deadline/scheduled time stamps to new date.
11565 This function is run automatically after each state change to a DONE state."
11566 ;; last-state is dynamically scoped into this function
11567 (let* ((repeat (org-get-repeat))
11568 (aa (assoc last-state org-todo-kwd-alist))
11569 (interpret (nth 1 aa))
11570 (head (nth 2 aa))
11571 (whata '(("d" . day) ("m" . month) ("y" . year)))
11572 (msg "Entry repeats: ")
11573 (org-log-done nil)
11574 (org-todo-log-states nil)
11575 re type n what ts time to-state)
11576 (when repeat
11577 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
11578 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
11579 org-todo-repeat-to-state))
11580 (unless (and to-state (member to-state org-todo-keywords-1))
11581 (setq to-state (if (eq interpret 'type) last-state head)))
11582 (org-todo to-state)
11583 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
11584 (org-entry-put nil "LAST_REPEAT" (format-time-string
11585 (org-time-stamp-format t t))))
11586 (when org-log-repeat
11587 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
11588 (memq 'org-add-log-note post-command-hook))
11589 ;; OK, we are already setup for some record
11590 (if (eq org-log-repeat 'note)
11591 ;; make sure we take a note, not only a time stamp
11592 (setq org-log-note-how 'note))
11593 ;; Set up for taking a record
11594 (org-add-log-setup 'state (or done-word (car org-done-keywords))
11595 last-state
11596 'findpos org-log-repeat)))
11597 (org-back-to-heading t)
11598 (org-add-planning-info nil nil 'closed)
11599 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
11600 org-deadline-time-regexp "\\)\\|\\("
11601 org-ts-regexp "\\)"))
11602 (while (re-search-forward
11603 re (save-excursion (outline-next-heading) (point)) t)
11604 (setq type (if (match-end 1) org-scheduled-string
11605 (if (match-end 3) org-deadline-string "Plain:"))
11606 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
11607 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
11608 (setq n (string-to-number (match-string 2 ts))
11609 what (match-string 3 ts))
11610 (if (equal what "w") (setq n (* n 7) what "d"))
11611 ;; Preparation, see if we need to modify the start date for the change
11612 (when (match-end 1)
11613 (setq time (save-match-data (org-time-string-to-time ts)))
11614 (cond
11615 ((equal (match-string 1 ts) ".")
11616 ;; Shift starting date to today
11617 (org-timestamp-change
11618 (- (time-to-days (current-time)) (time-to-days time))
11619 'day))
11620 ((equal (match-string 1 ts) "+")
11621 (let ((nshiftmax 10) (nshift 0))
11622 (while (or (= nshift 0)
11623 (<= (time-to-days time)
11624 (time-to-days (current-time))))
11625 (when (= (incf nshift) nshiftmax)
11626 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
11627 (error "Abort")))
11628 (org-timestamp-change n (cdr (assoc what whata)))
11629 (org-at-timestamp-p t)
11630 (setq ts (match-string 1))
11631 (setq time (save-match-data (org-time-string-to-time ts)))))
11632 (org-timestamp-change (- n) (cdr (assoc what whata)))
11633 ;; rematch, so that we have everything in place for the real shift
11634 (org-at-timestamp-p t)
11635 (setq ts (match-string 1))
11636 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
11637 (org-timestamp-change n (cdr (assoc what whata)))
11638 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
11639 (setq org-log-post-message msg)
11640 (message "%s" msg))))
11642 (defun org-show-todo-tree (arg)
11643 "Make a compact tree which shows all headlines marked with TODO.
11644 The tree will show the lines where the regexp matches, and all higher
11645 headlines above the match.
11646 With a \\[universal-argument] prefix, prompt for a regexp to match.
11647 With a numeric prefix N, construct a sparse tree for the Nth element
11648 of `org-todo-keywords-1'."
11649 (interactive "P")
11650 (let ((case-fold-search nil)
11651 (kwd-re
11652 (cond ((null arg) org-not-done-regexp)
11653 ((equal arg '(4))
11654 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
11655 (mapcar 'list org-todo-keywords-1))))
11656 (concat "\\("
11657 (mapconcat 'identity (org-split-string kwd "|") "\\|")
11658 "\\)\\>")))
11659 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
11660 (regexp-quote (nth (1- (prefix-numeric-value arg))
11661 org-todo-keywords-1)))
11662 (t (error "Invalid prefix argument: %s" arg)))))
11663 (message "%d TODO entries found"
11664 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
11666 (defun org-deadline (&optional remove time)
11667 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
11668 With argument REMOVE, remove any deadline from the item.
11669 When TIME is set, it should be an internal time specification, and the
11670 scheduling will use the corresponding date."
11671 (interactive "P")
11672 (let* ((old-date (org-entry-get nil "DEADLINE"))
11673 (repeater (and old-date
11674 (string-match
11675 "\\([.+]+[0-9]+[dwmy]\\(?:[/ ][-+]?[0-9]+[dwmy]\\)?\\) ?"
11676 old-date)
11677 (match-string 1 old-date))))
11678 (if remove
11679 (progn
11680 (when (and old-date org-log-redeadline)
11681 (org-add-log-setup 'deldeadline nil old-date 'findpos
11682 org-log-redeadline))
11683 (org-remove-timestamp-with-keyword org-deadline-string)
11684 (message "Item no longer has a deadline."))
11685 (org-add-planning-info 'deadline time 'closed)
11686 (when (and old-date org-log-redeadline
11687 (not (equal old-date
11688 (substring org-last-inserted-timestamp 1 -1))))
11689 (org-add-log-setup 'redeadline nil old-date 'findpos
11690 org-log-redeadline))
11691 (when repeater
11692 (save-excursion
11693 (org-back-to-heading t)
11694 (when (re-search-forward (concat org-deadline-string " "
11695 org-last-inserted-timestamp)
11696 (save-excursion
11697 (outline-next-heading) (point)) t)
11698 (goto-char (1- (match-end 0)))
11699 (insert " " repeater)
11700 (setq org-last-inserted-timestamp
11701 (concat (substring org-last-inserted-timestamp 0 -1)
11702 " " repeater
11703 (substring org-last-inserted-timestamp -1))))))
11704 (message "Deadline on %s" org-last-inserted-timestamp))))
11706 (defun org-schedule (&optional remove time)
11707 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
11708 With argument REMOVE, remove any scheduling date from the item.
11709 When TIME is set, it should be an internal time specification, and the
11710 scheduling will use the corresponding date."
11711 (interactive "P")
11712 (let* ((old-date (org-entry-get nil "SCHEDULED"))
11713 (repeater (and old-date
11714 (string-match
11715 "\\([.+]+[0-9]+[dwmy]\\(?:[/ ][-+]?[0-9]+[dwmy]\\)?\\) ?"
11716 old-date)
11717 (match-string 1 old-date))))
11718 (if remove
11719 (progn
11720 (when (and old-date org-log-reschedule)
11721 (org-add-log-setup 'delschedule nil old-date 'findpos
11722 org-log-reschedule))
11723 (org-remove-timestamp-with-keyword org-scheduled-string)
11724 (message "Item is no longer scheduled."))
11725 (org-add-planning-info 'scheduled time 'closed)
11726 (when (and old-date org-log-reschedule
11727 (not (equal old-date
11728 (substring org-last-inserted-timestamp 1 -1))))
11729 (org-add-log-setup 'reschedule nil old-date 'findpos
11730 org-log-reschedule))
11731 (when repeater
11732 (save-excursion
11733 (org-back-to-heading t)
11734 (when (re-search-forward (concat org-scheduled-string " "
11735 org-last-inserted-timestamp)
11736 (save-excursion
11737 (outline-next-heading) (point)) t)
11738 (goto-char (1- (match-end 0)))
11739 (insert " " repeater)
11740 (setq org-last-inserted-timestamp
11741 (concat (substring org-last-inserted-timestamp 0 -1)
11742 " " repeater
11743 (substring org-last-inserted-timestamp -1))))))
11744 (message "Scheduled to %s" org-last-inserted-timestamp))))
11746 (defun org-get-scheduled-time (pom &optional inherit)
11747 "Get the scheduled time as a time tuple, of a format suitable
11748 for calling org-schedule with, or if there is no scheduling,
11749 returns nil."
11750 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
11751 (when time
11752 (apply 'encode-time (org-parse-time-string time)))))
11754 (defun org-get-deadline-time (pom &optional inherit)
11755 "Get the deadline as a time tuple, of a format suitable for
11756 calling org-deadline with, or if there is no scheduling, returns
11757 nil."
11758 (let ((time (org-entry-get pom "DEADLINE" inherit)))
11759 (when time
11760 (apply 'encode-time (org-parse-time-string time)))))
11762 (defun org-remove-timestamp-with-keyword (keyword)
11763 "Remove all time stamps with KEYWORD in the current entry."
11764 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
11765 beg)
11766 (save-excursion
11767 (org-back-to-heading t)
11768 (setq beg (point))
11769 (outline-next-heading)
11770 (while (re-search-backward re beg t)
11771 (replace-match "")
11772 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
11773 (equal (char-before) ?\ ))
11774 (backward-delete-char 1)
11775 (if (string-match "^[ \t]*$" (buffer-substring
11776 (point-at-bol) (point-at-eol)))
11777 (delete-region (point-at-bol)
11778 (min (point-max) (1+ (point-at-eol))))))))))
11780 (defun org-add-planning-info (what &optional time &rest remove)
11781 "Insert new timestamp with keyword in the line directly after the headline.
11782 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
11783 If non is given, the user is prompted for a date.
11784 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
11785 be removed."
11786 (interactive)
11787 (let (org-time-was-given org-end-time-was-given ts
11788 end default-time default-input)
11790 (catch 'exit
11791 (when (and (not time) (memq what '(scheduled deadline)))
11792 ;; Try to get a default date/time from existing timestamp
11793 (save-excursion
11794 (org-back-to-heading t)
11795 (setq end (save-excursion (outline-next-heading) (point)))
11796 (when (re-search-forward (if (eq what 'scheduled)
11797 org-scheduled-time-regexp
11798 org-deadline-time-regexp)
11799 end t)
11800 (setq ts (match-string 1)
11801 default-time
11802 (apply 'encode-time (org-parse-time-string ts))
11803 default-input (and ts (org-get-compact-tod ts))))))
11804 (when what
11805 ;; If necessary, get the time from the user
11806 (setq time (or time (org-read-date nil 'to-time nil nil
11807 default-time default-input))))
11809 (when (and org-insert-labeled-timestamps-at-point
11810 (member what '(scheduled deadline)))
11811 (insert
11812 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
11813 (org-insert-time-stamp time org-time-was-given
11814 nil nil nil (list org-end-time-was-given))
11815 (setq what nil))
11816 (save-excursion
11817 (save-restriction
11818 (let (col list elt ts buffer-invisibility-spec)
11819 (org-back-to-heading t)
11820 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
11821 (goto-char (match-end 1))
11822 (setq col (current-column))
11823 (goto-char (match-end 0))
11824 (if (eobp) (insert "\n") (forward-char 1))
11825 (when (and (not what)
11826 (not (looking-at
11827 (concat "[ \t]*"
11828 org-keyword-time-not-clock-regexp))))
11829 ;; Nothing to add, nothing to remove...... :-)
11830 (throw 'exit nil))
11831 (if (and (not (looking-at outline-regexp))
11832 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
11833 "[^\r\n]*"))
11834 (not (equal (match-string 1) org-clock-string)))
11835 (narrow-to-region (match-beginning 0) (match-end 0))
11836 (insert-before-markers "\n")
11837 (backward-char 1)
11838 (narrow-to-region (point) (point))
11839 (and org-adapt-indentation (org-indent-to-column col)))
11840 ;; Check if we have to remove something.
11841 (setq list (cons what remove))
11842 (while list
11843 (setq elt (pop list))
11844 (goto-char (point-min))
11845 (when (or (and (eq elt 'scheduled)
11846 (re-search-forward org-scheduled-time-regexp nil t))
11847 (and (eq elt 'deadline)
11848 (re-search-forward org-deadline-time-regexp nil t))
11849 (and (eq elt 'closed)
11850 (re-search-forward org-closed-time-regexp nil t)))
11851 (replace-match "")
11852 (if (looking-at "--+<[^>]+>") (replace-match ""))
11853 (skip-chars-backward " ")
11854 (if (looking-at " +") (replace-match ""))))
11855 (goto-char (point-max))
11856 (and org-adapt-indentation (bolp) (org-indent-to-column col))
11857 (when what
11858 (insert
11859 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
11860 (cond ((eq what 'scheduled) org-scheduled-string)
11861 ((eq what 'deadline) org-deadline-string)
11862 ((eq what 'closed) org-closed-string))
11863 " ")
11864 (setq ts (org-insert-time-stamp
11865 time
11866 (or org-time-was-given
11867 (and (eq what 'closed) org-log-done-with-time))
11868 (eq what 'closed)
11869 nil nil (list org-end-time-was-given)))
11870 (end-of-line 1))
11871 (goto-char (point-min))
11872 (widen)
11873 (if (and (looking-at "[ \t]*\n")
11874 (equal (char-before) ?\n))
11875 (delete-region (1- (point)) (point-at-eol)))
11876 ts))))))
11878 (defvar org-log-note-marker (make-marker))
11879 (defvar org-log-note-purpose nil)
11880 (defvar org-log-note-state nil)
11881 (defvar org-log-note-previous-state nil)
11882 (defvar org-log-note-how nil)
11883 (defvar org-log-note-extra nil)
11884 (defvar org-log-note-window-configuration nil)
11885 (defvar org-log-note-return-to (make-marker))
11886 (defvar org-log-post-message nil
11887 "Message to be displayed after a log note has been stored.
11888 The auto-repeater uses this.")
11890 (defun org-add-note ()
11891 "Add a note to the current entry.
11892 This is done in the same way as adding a state change note."
11893 (interactive)
11894 (org-add-log-setup 'note nil nil 'findpos nil))
11896 (defvar org-property-end-re)
11897 (defun org-add-log-setup (&optional purpose state prev-state
11898 findpos how extra)
11899 "Set up the post command hook to take a note.
11900 If this is about to TODO state change, the new state is expected in STATE.
11901 When FINDPOS is non-nil, find the correct position for the note in
11902 the current entry. If not, assume that it can be inserted at point.
11903 HOW is an indicator what kind of note should be created.
11904 EXTRA is additional text that will be inserted into the notes buffer."
11905 (let* ((org-log-into-drawer (org-log-into-drawer))
11906 (drawer (cond ((stringp org-log-into-drawer)
11907 org-log-into-drawer)
11908 (org-log-into-drawer "LOGBOOK")
11909 (t nil))))
11910 (save-restriction
11911 (save-excursion
11912 (when findpos
11913 (org-back-to-heading t)
11914 (narrow-to-region (point) (save-excursion
11915 (outline-next-heading) (point)))
11916 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
11917 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
11918 "[^\r\n]*\\)?"))
11919 (goto-char (match-end 0))
11920 (cond
11921 (drawer
11922 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
11923 nil t)
11924 (progn
11925 (goto-char (match-end 0))
11926 (or org-log-states-order-reversed
11927 (and (re-search-forward org-property-end-re nil t)
11928 (goto-char (1- (match-beginning 0))))))
11929 (insert "\n:" drawer ":\n:END:")
11930 (beginning-of-line 0)
11931 (org-indent-line-function)
11932 (beginning-of-line 2)
11933 (org-indent-line-function)
11934 (end-of-line 0)))
11935 ((and org-log-state-notes-insert-after-drawers
11936 (save-excursion
11937 (forward-line) (looking-at org-drawer-regexp)))
11938 (forward-line)
11939 (while (looking-at org-drawer-regexp)
11940 (goto-char (match-end 0))
11941 (re-search-forward org-property-end-re (point-max) t)
11942 (forward-line))
11943 (forward-line -1)))
11944 (unless org-log-states-order-reversed
11945 (and (= (char-after) ?\n) (forward-char 1))
11946 (org-skip-over-state-notes)
11947 (skip-chars-backward " \t\n\r")))
11948 (move-marker org-log-note-marker (point))
11949 (setq org-log-note-purpose purpose
11950 org-log-note-state state
11951 org-log-note-previous-state prev-state
11952 org-log-note-how how
11953 org-log-note-extra extra)
11954 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
11956 (defun org-skip-over-state-notes ()
11957 "Skip past the list of State notes in an entry."
11958 (if (looking-at "\n[ \t]*- State") (forward-char 1))
11959 (when (ignore-errors (goto-char (org-in-item-p)))
11960 (let* ((struct (org-list-struct))
11961 (prevs (org-list-prevs-alist struct)))
11962 (while (looking-at "[ \t]*- State")
11963 (goto-char (or (org-list-get-next-item (point) struct prevs)
11964 (org-list-get-item-end (point) struct)))))))
11966 (defun org-add-log-note (&optional purpose)
11967 "Pop up a window for taking a note, and add this note later at point."
11968 (remove-hook 'post-command-hook 'org-add-log-note)
11969 (setq org-log-note-window-configuration (current-window-configuration))
11970 (delete-other-windows)
11971 (move-marker org-log-note-return-to (point))
11972 (switch-to-buffer (marker-buffer org-log-note-marker))
11973 (goto-char org-log-note-marker)
11974 (org-switch-to-buffer-other-window "*Org Note*")
11975 (erase-buffer)
11976 (if (memq org-log-note-how '(time state))
11977 (let (current-prefix-arg) (org-store-log-note))
11978 (let ((org-inhibit-startup t)) (org-mode))
11979 (insert (format "# Insert note for %s.
11980 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
11981 (cond
11982 ((eq org-log-note-purpose 'clock-out) "stopped clock")
11983 ((eq org-log-note-purpose 'done) "closed todo item")
11984 ((eq org-log-note-purpose 'state)
11985 (format "state change from \"%s\" to \"%s\""
11986 (or org-log-note-previous-state "")
11987 (or org-log-note-state "")))
11988 ((eq org-log-note-purpose 'reschedule)
11989 "rescheduling")
11990 ((eq org-log-note-purpose 'delschedule)
11991 "no longer scheduled")
11992 ((eq org-log-note-purpose 'redeadline)
11993 "changing deadline")
11994 ((eq org-log-note-purpose 'deldeadline)
11995 "removing deadline")
11996 ((eq org-log-note-purpose 'refile)
11997 "refiling")
11998 ((eq org-log-note-purpose 'note)
11999 "this entry")
12000 (t (error "This should not happen")))))
12001 (if org-log-note-extra (insert org-log-note-extra))
12002 (org-set-local 'org-finish-function 'org-store-log-note)))
12004 (defvar org-note-abort nil) ; dynamically scoped
12005 (defun org-store-log-note ()
12006 "Finish taking a log note, and insert it to where it belongs."
12007 (let ((txt (buffer-string))
12008 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
12009 lines ind bul)
12010 (kill-buffer (current-buffer))
12011 (while (string-match "\\`#.*\n[ \t\n]*" txt)
12012 (setq txt (replace-match "" t t txt)))
12013 (if (string-match "\\s-+\\'" txt)
12014 (setq txt (replace-match "" t t txt)))
12015 (setq lines (org-split-string txt "\n"))
12016 (when (and note (string-match "\\S-" note))
12017 (setq note
12018 (org-replace-escapes
12019 note
12020 (list (cons "%u" (user-login-name))
12021 (cons "%U" user-full-name)
12022 (cons "%t" (format-time-string
12023 (org-time-stamp-format 'long 'inactive)
12024 (current-time)))
12025 (cons "%T" (format-time-string
12026 (org-time-stamp-format 'long nil)
12027 (current-time)))
12028 (cons "%s" (if org-log-note-state
12029 (concat "\"" org-log-note-state "\"")
12030 ""))
12031 (cons "%S" (if org-log-note-previous-state
12032 (concat "\"" org-log-note-previous-state "\"")
12033 "\"\"")))))
12034 (if lines (setq note (concat note " \\\\")))
12035 (push note lines))
12036 (when (or current-prefix-arg org-note-abort)
12037 (when org-log-into-drawer
12038 (org-remove-empty-drawer-at
12039 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
12040 org-log-note-marker))
12041 (setq lines nil))
12042 (when lines
12043 (with-current-buffer (marker-buffer org-log-note-marker)
12044 (save-excursion
12045 (goto-char org-log-note-marker)
12046 (move-marker org-log-note-marker nil)
12047 (end-of-line 1)
12048 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
12049 (setq ind (save-excursion
12050 (if (ignore-errors (goto-char (org-in-item-p)))
12051 (let ((struct (org-list-struct)))
12052 (org-list-get-ind
12053 (org-list-get-top-point struct) struct))
12054 (skip-chars-backward " \r\t\n")
12055 (cond
12056 ((and (org-at-heading-p)
12057 org-adapt-indentation)
12058 (1+ (org-current-level)))
12059 ((org-at-heading-p) 0)
12060 (t (org-get-indentation))))))
12061 (setq bul (org-list-bullet-string "-"))
12062 (org-indent-line-to ind)
12063 (insert bul (pop lines))
12064 (let ((ind-body (+ (length bul) ind)))
12065 (while lines
12066 (insert "\n")
12067 (org-indent-line-to ind-body)
12068 (insert (pop lines))))
12069 (message "Note stored")
12070 (org-back-to-heading t)
12071 (org-cycle-hide-drawers 'children)))))
12072 (set-window-configuration org-log-note-window-configuration)
12073 (with-current-buffer (marker-buffer org-log-note-return-to)
12074 (goto-char org-log-note-return-to))
12075 (move-marker org-log-note-return-to nil)
12076 (and org-log-post-message (message "%s" org-log-post-message)))
12078 (defun org-remove-empty-drawer-at (drawer pos)
12079 "Remove an empty drawer DRAWER at position POS.
12080 POS may also be a marker."
12081 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
12082 (save-excursion
12083 (save-restriction
12084 (widen)
12085 (goto-char pos)
12086 (if (org-in-regexp
12087 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
12088 (replace-match ""))))))
12090 (defun org-sparse-tree (&optional arg)
12091 "Create a sparse tree, prompt for the details.
12092 This command can create sparse trees. You first need to select the type
12093 of match used to create the tree:
12095 t Show all TODO entries.
12096 T Show entries with a specific TODO keyword.
12097 m Show entries selected by a tags/property match.
12098 p Enter a property name and its value (both with completion on existing
12099 names/values) and show entries with that property.
12100 r Show entries matching a regular expression (`/' can be used as well)
12101 d Show deadlines due within `org-deadline-warning-days'.
12102 b Show deadlines and scheduled items before a date.
12103 a Show deadlines and scheduled items after a date."
12104 (interactive "P")
12105 (let (ans kwd value)
12106 (message "Sparse tree: [r]egexp [/]regexp [t]odo [T]odo-kwd [m]atch [p]roperty\n [d]eadlines [b]efore-date [a]fter-date")
12107 (setq ans (read-char-exclusive))
12108 (cond
12109 ((equal ans ?d)
12110 (call-interactively 'org-check-deadlines))
12111 ((equal ans ?b)
12112 (call-interactively 'org-check-before-date))
12113 ((equal ans ?a)
12114 (call-interactively 'org-check-after-date))
12115 ((equal ans ?t)
12116 (org-show-todo-tree nil))
12117 ((equal ans ?T)
12118 (org-show-todo-tree '(4)))
12119 ((member ans '(?T ?m))
12120 (call-interactively 'org-match-sparse-tree))
12121 ((member ans '(?p ?P))
12122 (setq kwd (org-icompleting-read "Property: "
12123 (mapcar 'list (org-buffer-property-keys))))
12124 (setq value (org-icompleting-read "Value: "
12125 (mapcar 'list (org-property-values kwd))))
12126 (unless (string-match "\\`{.*}\\'" value)
12127 (setq value (concat "\"" value "\"")))
12128 (org-match-sparse-tree arg (concat kwd "=" value)))
12129 ((member ans '(?r ?R ?/))
12130 (call-interactively 'org-occur))
12131 (t (error "No such sparse tree command \"%c\"" ans)))))
12133 (defvar org-occur-highlights nil
12134 "List of overlays used for occur matches.")
12135 (make-variable-buffer-local 'org-occur-highlights)
12136 (defvar org-occur-parameters nil
12137 "Parameters of the active org-occur calls.
12138 This is a list, each call to org-occur pushes as cons cell,
12139 containing the regular expression and the callback, onto the list.
12140 The list can contain several entries if `org-occur' has been called
12141 several time with the KEEP-PREVIOUS argument. Otherwise, this list
12142 will only contain one set of parameters. When the highlights are
12143 removed (for example with `C-c C-c', or with the next edit (depending
12144 on `org-remove-highlights-with-change'), this variable is emptied
12145 as well.")
12146 (make-variable-buffer-local 'org-occur-parameters)
12148 (defun org-occur (regexp &optional keep-previous callback)
12149 "Make a compact tree which shows all matches of REGEXP.
12150 The tree will show the lines where the regexp matches, and all higher
12151 headlines above the match. It will also show the heading after the match,
12152 to make sure editing the matching entry is easy.
12153 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
12154 call to `org-occur' will be kept, to allow stacking of calls to this
12155 command.
12156 If CALLBACK is non-nil, it is a function which is called to confirm
12157 that the match should indeed be shown."
12158 (interactive "sRegexp: \nP")
12159 (when (equal regexp "")
12160 (error "Regexp cannot be empty"))
12161 (unless keep-previous
12162 (org-remove-occur-highlights nil nil t))
12163 (push (cons regexp callback) org-occur-parameters)
12164 (let ((cnt 0))
12165 (save-excursion
12166 (goto-char (point-min))
12167 (if (or (not keep-previous) ; do not want to keep
12168 (not org-occur-highlights)) ; no previous matches
12169 ;; hide everything
12170 (org-overview))
12171 (while (re-search-forward regexp nil t)
12172 (when (or (not callback)
12173 (save-match-data (funcall callback)))
12174 (setq cnt (1+ cnt))
12175 (when org-highlight-sparse-tree-matches
12176 (org-highlight-new-match (match-beginning 0) (match-end 0)))
12177 (org-show-context 'occur-tree))))
12178 (when org-remove-highlights-with-change
12179 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
12180 nil 'local))
12181 (unless org-sparse-tree-open-archived-trees
12182 (org-hide-archived-subtrees (point-min) (point-max)))
12183 (run-hooks 'org-occur-hook)
12184 (if (interactive-p)
12185 (message "%d match(es) for regexp %s" cnt regexp))
12186 cnt))
12188 (defun org-occur-next-match (&optional n reset)
12189 "Function for `next-error-function' to find sparse tree matches.
12190 N is the number of matches to move, when negative move backwards.
12191 RESET is entirely ignored - this function always goes back to the
12192 starting point when no match is found."
12193 (let* ((limit (if (< n 0) (point-min) (point-max)))
12194 (search-func (if (< n 0)
12195 'previous-single-char-property-change
12196 'next-single-char-property-change))
12197 (n (abs n))
12198 (pos (point))
12200 (catch 'exit
12201 (while (setq p1 (funcall search-func (point) 'org-type))
12202 (when (equal p1 limit)
12203 (goto-char pos)
12204 (error "No more matches"))
12205 (when (equal (get-char-property p1 'org-type) 'org-occur)
12206 (setq n (1- n))
12207 (when (= n 0)
12208 (goto-char p1)
12209 (throw 'exit (point))))
12210 (goto-char p1))
12211 (goto-char p1)
12212 (error "No more matches"))))
12214 (defun org-show-context (&optional key)
12215 "Make sure point and context are visible.
12216 How much context is shown depends upon the variables
12217 `org-show-hierarchy-above', `org-show-following-heading'. and
12218 `org-show-siblings'."
12219 (let ((heading-p (org-on-heading-p t))
12220 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
12221 (following-p (org-get-alist-option org-show-following-heading key))
12222 (entry-p (org-get-alist-option org-show-entry-below key))
12223 (siblings-p (org-get-alist-option org-show-siblings key)))
12224 (catch 'exit
12225 ;; Show heading or entry text
12226 (if (and heading-p (not entry-p))
12227 (org-flag-heading nil) ; only show the heading
12228 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
12229 (org-show-hidden-entry))) ; show entire entry
12230 (when following-p
12231 ;; Show next sibling, or heading below text
12232 (save-excursion
12233 (and (if heading-p (org-goto-sibling) (outline-next-heading))
12234 (org-flag-heading nil))))
12235 (when siblings-p (org-show-siblings))
12236 (when hierarchy-p
12237 ;; show all higher headings, possibly with siblings
12238 (save-excursion
12239 (while (and (condition-case nil
12240 (progn (org-up-heading-all 1) t)
12241 (error nil))
12242 (not (bobp)))
12243 (org-flag-heading nil)
12244 (when siblings-p (org-show-siblings))))))))
12246 (defvar org-reveal-start-hook nil
12247 "Hook run before revealing a location.")
12249 (defun org-reveal (&optional siblings)
12250 "Show current entry, hierarchy above it, and the following headline.
12251 This can be used to show a consistent set of context around locations
12252 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
12253 not t for the search context.
12255 With optional argument SIBLINGS, on each level of the hierarchy all
12256 siblings are shown. This repairs the tree structure to what it would
12257 look like when opened with hierarchical calls to `org-cycle'.
12258 With double optional argument \\[universal-argument] \\[universal-argument], \
12259 go to the parent and show the
12260 entire tree."
12261 (interactive "P")
12262 (run-hooks 'org-reveal-start-hook)
12263 (let ((org-show-hierarchy-above t)
12264 (org-show-following-heading t)
12265 (org-show-siblings (if siblings t org-show-siblings)))
12266 (org-show-context nil))
12267 (when (equal siblings '(16))
12268 (save-excursion
12269 (when (org-up-heading-safe)
12270 (org-show-subtree)
12271 (run-hook-with-args 'org-cycle-hook 'subtree)))))
12273 (defun org-highlight-new-match (beg end)
12274 "Highlight from BEG to END and mark the highlight is an occur headline."
12275 (let ((ov (make-overlay beg end)))
12276 (overlay-put ov 'face 'secondary-selection)
12277 (overlay-put ov 'org-type 'org-occur)
12278 (push ov org-occur-highlights)))
12280 (defun org-remove-occur-highlights (&optional beg end noremove)
12281 "Remove the occur highlights from the buffer.
12282 BEG and END are ignored. If NOREMOVE is nil, remove this function
12283 from the `before-change-functions' in the current buffer."
12284 (interactive)
12285 (unless org-inhibit-highlight-removal
12286 (mapc 'delete-overlay org-occur-highlights)
12287 (setq org-occur-highlights nil)
12288 (setq org-occur-parameters nil)
12289 (unless noremove
12290 (remove-hook 'before-change-functions
12291 'org-remove-occur-highlights 'local))))
12293 ;;;; Priorities
12295 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
12296 "Regular expression matching the priority indicator.")
12298 (defvar org-remove-priority-next-time nil)
12300 (defun org-priority-up ()
12301 "Increase the priority of the current item."
12302 (interactive)
12303 (org-priority 'up))
12305 (defun org-priority-down ()
12306 "Decrease the priority of the current item."
12307 (interactive)
12308 (org-priority 'down))
12310 (defun org-priority (&optional action)
12311 "Change the priority of an item by ARG.
12312 ACTION can be `set', `up', `down', or a character."
12313 (interactive)
12314 (unless org-enable-priority-commands
12315 (error "Priority commands are disabled"))
12316 (setq action (or action 'set))
12317 (let (current new news have remove)
12318 (save-excursion
12319 (org-back-to-heading t)
12320 (if (looking-at org-priority-regexp)
12321 (setq current (string-to-char (match-string 2))
12322 have t)
12323 (setq current org-default-priority))
12324 (cond
12325 ((eq action 'remove)
12326 (setq remove t new ?\ ))
12327 ((or (eq action 'set)
12328 (if (featurep 'xemacs) (characterp action) (integerp action)))
12329 (if (not (eq action 'set))
12330 (setq new action)
12331 (message "Priority %c-%c, SPC to remove: "
12332 org-highest-priority org-lowest-priority)
12333 (save-match-data
12334 (setq new (read-char-exclusive))))
12335 (if (and (= (upcase org-highest-priority) org-highest-priority)
12336 (= (upcase org-lowest-priority) org-lowest-priority))
12337 (setq new (upcase new)))
12338 (cond ((equal new ?\ ) (setq remove t))
12339 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
12340 (error "Priority must be between `%c' and `%c'"
12341 org-highest-priority org-lowest-priority))))
12342 ((eq action 'up)
12343 (if (and (not have) (eq last-command this-command))
12344 (setq new org-lowest-priority)
12345 (setq new (if (and org-priority-start-cycle-with-default (not have))
12346 org-default-priority (1- current)))))
12347 ((eq action 'down)
12348 (if (and (not have) (eq last-command this-command))
12349 (setq new org-highest-priority)
12350 (setq new (if (and org-priority-start-cycle-with-default (not have))
12351 org-default-priority (1+ current)))))
12352 (t (error "Invalid action")))
12353 (if (or (< (upcase new) org-highest-priority)
12354 (> (upcase new) org-lowest-priority))
12355 (setq remove t))
12356 (setq news (format "%c" new))
12357 (if have
12358 (if remove
12359 (replace-match "" t t nil 1)
12360 (replace-match news t t nil 2))
12361 (if remove
12362 (error "No priority cookie found in line")
12363 (let ((case-fold-search nil))
12364 (looking-at org-todo-line-regexp))
12365 (if (match-end 2)
12366 (progn
12367 (goto-char (match-end 2))
12368 (insert " [#" news "]"))
12369 (goto-char (match-beginning 3))
12370 (insert "[#" news "] "))))
12371 (org-preserve-lc (org-set-tags nil 'align)))
12372 (if remove
12373 (message "Priority removed")
12374 (message "Priority of current item set to %s" news))))
12376 (defun org-get-priority (s)
12377 "Find priority cookie and return priority."
12378 (if (functionp org-get-priority-function)
12379 (funcall org-get-priority-function)
12380 (save-match-data
12381 (if (not (string-match org-priority-regexp s))
12382 (* 1000 (- org-lowest-priority org-default-priority))
12383 (* 1000 (- org-lowest-priority
12384 (string-to-char (match-string 2 s))))))))
12386 ;;;; Tags
12388 (defvar org-agenda-archives-mode)
12389 (defvar org-map-continue-from nil
12390 "Position from where mapping should continue.
12391 Can be set by the action argument to `org-scan-tag's and `org-map-entries'.")
12393 (defvar org-scanner-tags nil
12394 "The current tag list while the tags scanner is running.")
12395 (defvar org-trust-scanner-tags nil
12396 "Should `org-get-tags-at' use the tags for the scanner.
12397 This is for internal dynamical scoping only.
12398 When this is non-nil, the function `org-get-tags-at' will return the value
12399 of `org-scanner-tags' instead of building the list by itself. This
12400 can lead to large speed-ups when the tags scanner is used in a file with
12401 many entries, and when the list of tags is retrieved, for example to
12402 obtain a list of properties. Building the tags list for each entry in such
12403 a file becomes an N^2 operation - but with this variable set, it scales
12404 as N.")
12406 (defun org-scan-tags (action matcher &optional todo-only)
12407 "Scan headline tags with inheritance and produce output ACTION.
12409 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
12410 or `agenda' to produce an entry list for an agenda view. It can also be
12411 a Lisp form or a function that should be called at each matched headline, in
12412 this case the return value is a list of all return values from these calls.
12414 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
12415 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
12416 only lines with a TODO keyword are included in the output."
12417 (require 'org-agenda)
12418 (let* ((re (concat "^" outline-regexp " *\\(\\<\\("
12419 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
12420 (org-re
12421 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
12422 (props (list 'face 'default
12423 'done-face 'org-agenda-done
12424 'undone-face 'default
12425 'mouse-face 'highlight
12426 'org-not-done-regexp org-not-done-regexp
12427 'org-todo-regexp org-todo-regexp
12428 'help-echo
12429 (format "mouse-2 or RET jump to org file %s"
12430 (abbreviate-file-name
12431 (or (buffer-file-name (buffer-base-buffer))
12432 (buffer-name (buffer-base-buffer)))))))
12433 (case-fold-search nil)
12434 (org-map-continue-from nil)
12435 lspos tags tags-list
12436 (tags-alist (list (cons 0 org-file-tags)))
12437 (llast 0) rtn rtn1 level category i txt
12438 todo marker entry priority)
12439 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
12440 (setq action (list 'lambda nil action)))
12441 (save-excursion
12442 (goto-char (point-min))
12443 (when (eq action 'sparse-tree)
12444 (org-overview)
12445 (org-remove-occur-highlights))
12446 (while (re-search-forward re nil t)
12447 (catch :skip
12448 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
12449 tags (if (match-end 4) (org-match-string-no-properties 4)))
12450 (goto-char (setq lspos (match-beginning 0)))
12451 (setq level (org-reduced-level (funcall outline-level))
12452 category (org-get-category))
12453 (setq i llast llast level)
12454 ;; remove tag lists from same and sublevels
12455 (while (>= i level)
12456 (when (setq entry (assoc i tags-alist))
12457 (setq tags-alist (delete entry tags-alist)))
12458 (setq i (1- i)))
12459 ;; add the next tags
12460 (when tags
12461 (setq tags (org-split-string tags ":")
12462 tags-alist
12463 (cons (cons level tags) tags-alist)))
12464 ;; compile tags for current headline
12465 (setq tags-list
12466 (if org-use-tag-inheritance
12467 (apply 'append (mapcar 'cdr (reverse tags-alist)))
12468 tags)
12469 org-scanner-tags tags-list)
12470 (when org-use-tag-inheritance
12471 (setcdr (car tags-alist)
12472 (mapcar (lambda (x)
12473 (setq x (copy-sequence x))
12474 (org-add-prop-inherited x))
12475 (cdar tags-alist))))
12476 (when (and tags org-use-tag-inheritance
12477 (or (not (eq t org-use-tag-inheritance))
12478 org-tags-exclude-from-inheritance))
12479 ;; selective inheritance, remove uninherited ones
12480 (setcdr (car tags-alist)
12481 (org-remove-uniherited-tags (cdar tags-alist))))
12482 (when (and (or (not todo-only)
12483 (and (member todo org-not-done-keywords)
12484 (or (not org-agenda-tags-todo-honor-ignore-options)
12485 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
12486 (let ((case-fold-search t)) (eval matcher))
12488 (not (member org-archive-tag tags-list))
12489 ;; we have an archive tag, should we use this anyway?
12490 (or (not org-agenda-skip-archived-trees)
12491 (and (eq action 'agenda) org-agenda-archives-mode))))
12492 (unless (eq action 'sparse-tree) (org-agenda-skip))
12494 ;; select this headline
12496 (cond
12497 ((eq action 'sparse-tree)
12498 (and org-highlight-sparse-tree-matches
12499 (org-get-heading) (match-end 0)
12500 (org-highlight-new-match
12501 (match-beginning 0) (match-beginning 1)))
12502 (org-show-context 'tags-tree))
12503 ((eq action 'agenda)
12504 (setq txt (org-format-agenda-item
12506 (concat
12507 (if (eq org-tags-match-list-sublevels 'indented)
12508 (make-string (1- level) ?.) "")
12509 (org-get-heading))
12510 category
12511 tags-list
12513 priority (org-get-priority txt))
12514 (goto-char lspos)
12515 (setq marker (org-agenda-new-marker))
12516 (org-add-props txt props
12517 'org-marker marker 'org-hd-marker marker 'org-category category
12518 'todo-state todo
12519 'priority priority 'type "tagsmatch")
12520 (push txt rtn))
12521 ((functionp action)
12522 (setq org-map-continue-from nil)
12523 (save-excursion
12524 (setq rtn1 (funcall action))
12525 (push rtn1 rtn)))
12526 (t (error "Invalid action")))
12528 ;; if we are to skip sublevels, jump to end of subtree
12529 (unless org-tags-match-list-sublevels
12530 (org-end-of-subtree t)
12531 (backward-char 1))))
12532 ;; Get the correct position from where to continue
12533 (if org-map-continue-from
12534 (goto-char org-map-continue-from)
12535 (and (= (point) lspos) (end-of-line 1)))))
12536 (when (and (eq action 'sparse-tree)
12537 (not org-sparse-tree-open-archived-trees))
12538 (org-hide-archived-subtrees (point-min) (point-max)))
12539 (nreverse rtn)))
12541 (defun org-remove-uniherited-tags (tags)
12542 "Remove all tags that are not inherited from the list TAGS."
12543 (cond
12544 ((eq org-use-tag-inheritance t)
12545 (if org-tags-exclude-from-inheritance
12546 (org-delete-all org-tags-exclude-from-inheritance tags)
12547 tags))
12548 ((not org-use-tag-inheritance) nil)
12549 ((stringp org-use-tag-inheritance)
12550 (delq nil (mapcar
12551 (lambda (x)
12552 (if (and (string-match org-use-tag-inheritance x)
12553 (not (member x org-tags-exclude-from-inheritance)))
12554 x nil))
12555 tags)))
12556 ((listp org-use-tag-inheritance)
12557 (delq nil (mapcar
12558 (lambda (x)
12559 (if (member x org-use-tag-inheritance) x nil))
12560 tags)))))
12562 (defvar todo-only) ;; dynamically scoped
12564 (defun org-match-sparse-tree (&optional todo-only match)
12565 "Create a sparse tree according to tags string MATCH.
12566 MATCH can contain positive and negative selection of tags, like
12567 \"+WORK+URGENT-WITHBOSS\".
12568 If optional argument TODO-ONLY is non-nil, only select lines that are
12569 also TODO lines."
12570 (interactive "P")
12571 (org-prepare-agenda-buffers (list (current-buffer)))
12572 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
12574 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
12576 (defvar org-cached-props nil)
12577 (defun org-cached-entry-get (pom property)
12578 (if (or (eq t org-use-property-inheritance)
12579 (and (stringp org-use-property-inheritance)
12580 (string-match org-use-property-inheritance property))
12581 (and (listp org-use-property-inheritance)
12582 (member property org-use-property-inheritance)))
12583 ;; Caching is not possible, check it directly
12584 (org-entry-get pom property 'inherit)
12585 ;; Get all properties, so that we can do complicated checks easily
12586 (cdr (assoc property (or org-cached-props
12587 (setq org-cached-props
12588 (org-entry-properties pom)))))))
12590 (defun org-global-tags-completion-table (&optional files)
12591 "Return the list of all tags in all agenda buffer/files.
12592 Optional FILES argument is a list of files to which can be used
12593 instead of the agenda files."
12594 (save-excursion
12595 (org-uniquify
12596 (delq nil
12597 (apply 'append
12598 (mapcar
12599 (lambda (file)
12600 (set-buffer (find-file-noselect file))
12601 (append (org-get-buffer-tags)
12602 (mapcar (lambda (x) (if (stringp (car-safe x))
12603 (list (car-safe x)) nil))
12604 org-tag-alist)))
12605 (if (and files (car files))
12606 files
12607 (org-agenda-files))))))))
12609 (defun org-make-tags-matcher (match)
12610 "Create the TAGS/TODO matcher form for the selection string MATCH."
12611 ;; todo-only is scoped dynamically into this function, and the function
12612 ;; may change it if the matcher asks for it.
12613 (unless match
12614 ;; Get a new match request, with completion
12615 (let ((org-last-tags-completion-table
12616 (org-global-tags-completion-table)))
12617 (setq match (org-completing-read-no-i
12618 "Match: " 'org-tags-completion-function nil nil nil
12619 'org-tags-history))))
12621 ;; Parse the string and create a lisp form
12622 (let ((match0 match)
12623 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
12624 minus tag mm
12625 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
12626 orterms term orlist re-p str-p level-p level-op time-p
12627 prop-p pn pv po gv rest)
12628 (if (string-match "/+" match)
12629 ;; match contains also a todo-matching request
12630 (progn
12631 (setq tagsmatch (substring match 0 (match-beginning 0))
12632 todomatch (substring match (match-end 0)))
12633 (if (string-match "^!" todomatch)
12634 (setq todo-only t todomatch (substring todomatch 1)))
12635 (if (string-match "^\\s-*$" todomatch)
12636 (setq todomatch nil)))
12637 ;; only matching tags
12638 (setq tagsmatch match todomatch nil))
12640 ;; Make the tags matcher
12641 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
12642 (setq tagsmatcher t)
12643 (setq orterms (org-split-string tagsmatch "|") orlist nil)
12644 (while (setq term (pop orterms))
12645 (while (and (equal (substring term -1) "\\") orterms)
12646 (setq term (concat term "|" (pop orterms)))) ; repair bad split
12647 (while (string-match re term)
12648 (setq rest (substring term (match-end 0))
12649 minus (and (match-end 1)
12650 (equal (match-string 1 term) "-"))
12651 tag (save-match-data (replace-regexp-in-string
12652 "\\\\-" "-"
12653 (match-string 2 term)))
12654 re-p (equal (string-to-char tag) ?{)
12655 level-p (match-end 4)
12656 prop-p (match-end 5)
12657 mm (cond
12658 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
12659 (level-p
12660 (setq level-op (org-op-to-function (match-string 3 term)))
12661 `(,level-op level ,(string-to-number
12662 (match-string 4 term))))
12663 (prop-p
12664 (setq pn (match-string 5 term)
12665 po (match-string 6 term)
12666 pv (match-string 7 term)
12667 re-p (equal (string-to-char pv) ?{)
12668 str-p (equal (string-to-char pv) ?\")
12669 time-p (save-match-data
12670 (string-match "^\"[[<].*[]>]\"$" pv))
12671 pv (if (or re-p str-p) (substring pv 1 -1) pv))
12672 (if time-p (setq pv (org-matcher-time pv)))
12673 (setq po (org-op-to-function po (if time-p 'time str-p)))
12674 (cond
12675 ((equal pn "CATEGORY")
12676 (setq gv '(get-text-property (point) 'org-category)))
12677 ((equal pn "TODO")
12678 (setq gv 'todo))
12680 (setq gv `(org-cached-entry-get nil ,pn))))
12681 (if re-p
12682 (if (eq po 'org<>)
12683 `(not (string-match ,pv (or ,gv "")))
12684 `(string-match ,pv (or ,gv "")))
12685 (if str-p
12686 `(,po (or ,gv "") ,pv)
12687 `(,po (string-to-number (or ,gv ""))
12688 ,(string-to-number pv) ))))
12689 (t `(member ,tag tags-list)))
12690 mm (if minus (list 'not mm) mm)
12691 term rest)
12692 (push mm tagsmatcher))
12693 (push (if (> (length tagsmatcher) 1)
12694 (cons 'and tagsmatcher)
12695 (car tagsmatcher))
12696 orlist)
12697 (setq tagsmatcher nil))
12698 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
12699 (setq tagsmatcher
12700 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
12701 ;; Make the todo matcher
12702 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
12703 (setq todomatcher t)
12704 (setq orterms (org-split-string todomatch "|") orlist nil)
12705 (while (setq term (pop orterms))
12706 (while (string-match re term)
12707 (setq minus (and (match-end 1)
12708 (equal (match-string 1 term) "-"))
12709 kwd (match-string 2 term)
12710 re-p (equal (string-to-char kwd) ?{)
12711 term (substring term (match-end 0))
12712 mm (if re-p
12713 `(string-match ,(substring kwd 1 -1) todo)
12714 (list 'equal 'todo kwd))
12715 mm (if minus (list 'not mm) mm))
12716 (push mm todomatcher))
12717 (push (if (> (length todomatcher) 1)
12718 (cons 'and todomatcher)
12719 (car todomatcher))
12720 orlist)
12721 (setq todomatcher nil))
12722 (setq todomatcher (if (> (length orlist) 1)
12723 (cons 'or orlist) (car orlist))))
12725 ;; Return the string and lisp forms of the matcher
12726 (setq matcher (if todomatcher
12727 (list 'and tagsmatcher todomatcher)
12728 tagsmatcher))
12729 (cons match0 matcher)))
12731 (defun org-op-to-function (op &optional stringp)
12732 "Turn an operator into the appropriate function."
12733 (setq op
12734 (cond
12735 ((equal op "<" ) '(< string< org-time<))
12736 ((equal op ">" ) '(> org-string> org-time>))
12737 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
12738 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
12739 ((member op '("=" "==")) '(= string= org-time=))
12740 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
12741 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
12743 (defun org<> (a b) (not (= a b)))
12744 (defun org-string<= (a b) (or (string= a b) (string< a b)))
12745 (defun org-string>= (a b) (not (string< a b)))
12746 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
12747 (defun org-string<> (a b) (not (string= a b)))
12748 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
12749 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
12750 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
12751 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
12752 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
12753 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
12754 (defun org-2ft (s)
12755 "Convert S to a floating point time.
12756 If S is already a number, just return it. If it is a string, parse
12757 it as a time string and apply `float-time' to it. If S is nil, just return 0."
12758 (cond
12759 ((numberp s) s)
12760 ((stringp s)
12761 (condition-case nil
12762 (float-time (apply 'encode-time (org-parse-time-string s)))
12763 (error 0.)))
12764 (t 0.)))
12766 (defun org-time-today ()
12767 "Time in seconds today at 0:00.
12768 Returns the float number of seconds since the beginning of the
12769 epoch to the beginning of today (00:00)."
12770 (float-time (apply 'encode-time
12771 (append '(0 0 0) (nthcdr 3 (decode-time))))))
12773 (defun org-matcher-time (s)
12774 "Interpret a time comparison value."
12775 (save-match-data
12776 (cond
12777 ((string= s "<now>") (float-time))
12778 ((string= s "<today>") (org-time-today))
12779 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
12780 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
12781 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
12782 (+ (org-time-today)
12783 (* (string-to-number (match-string 1 s))
12784 (cdr (assoc (match-string 2 s)
12785 '(("d" . 86400.0) ("w" . 604800.0)
12786 ("m" . 2678400.0) ("y" . 31557600.0)))))))
12787 (t (org-2ft s)))))
12789 (defun org-match-any-p (re list)
12790 "Does re match any element of list?"
12791 (setq list (mapcar (lambda (x) (string-match re x)) list))
12792 (delq nil list))
12794 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
12795 (defvar org-tags-overlay (make-overlay 1 1))
12796 (org-detach-overlay org-tags-overlay)
12798 (defun org-get-local-tags-at (&optional pos)
12799 "Get a list of tags defined in the current headline."
12800 (org-get-tags-at pos 'local))
12802 (defun org-get-local-tags ()
12803 "Get a list of tags defined in the current headline."
12804 (org-get-tags-at nil 'local))
12806 (defun org-get-tags-at (&optional pos local)
12807 "Get a list of all headline tags applicable at POS.
12808 POS defaults to point. If tags are inherited, the list contains
12809 the targets in the same sequence as the headlines appear, i.e.
12810 the tags of the current headline come last.
12811 When LOCAL is non-nil, only return tags from the current headline,
12812 ignore inherited ones."
12813 (interactive)
12814 (if (and org-trust-scanner-tags
12815 (or (not pos) (equal pos (point)))
12816 (not local))
12817 org-scanner-tags
12818 (let (tags ltags lastpos parent)
12819 (save-excursion
12820 (save-restriction
12821 (widen)
12822 (goto-char (or pos (point)))
12823 (save-match-data
12824 (catch 'done
12825 (condition-case nil
12826 (progn
12827 (org-back-to-heading t)
12828 (while (not (equal lastpos (point)))
12829 (setq lastpos (point))
12830 (when (looking-at
12831 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
12832 (setq ltags (org-split-string
12833 (org-match-string-no-properties 1) ":"))
12834 (when parent
12835 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
12836 (setq tags (append
12837 (if parent
12838 (org-remove-uniherited-tags ltags)
12839 ltags)
12840 tags)))
12841 (or org-use-tag-inheritance (throw 'done t))
12842 (if local (throw 'done t))
12843 (or (org-up-heading-safe) (error nil))
12844 (setq parent t)))
12845 (error nil)))))
12846 (append (org-remove-uniherited-tags org-file-tags) tags)))))
12848 (defun org-add-prop-inherited (s)
12849 (add-text-properties 0 (length s) '(inherited t) s)
12852 (defun org-toggle-tag (tag &optional onoff)
12853 "Toggle the tag TAG for the current line.
12854 If ONOFF is `on' or `off', don't toggle but set to this state."
12855 (let (res current)
12856 (save-excursion
12857 (org-back-to-heading t)
12858 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
12859 (point-at-eol) t)
12860 (progn
12861 (setq current (match-string 1))
12862 (replace-match ""))
12863 (setq current ""))
12864 (setq current (nreverse (org-split-string current ":")))
12865 (cond
12866 ((eq onoff 'on)
12867 (setq res t)
12868 (or (member tag current) (push tag current)))
12869 ((eq onoff 'off)
12870 (or (not (member tag current)) (setq current (delete tag current))))
12871 (t (if (member tag current)
12872 (setq current (delete tag current))
12873 (setq res t)
12874 (push tag current))))
12875 (end-of-line 1)
12876 (if current
12877 (progn
12878 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
12879 (org-set-tags nil t))
12880 (delete-horizontal-space))
12881 (run-hooks 'org-after-tags-change-hook))
12882 res))
12884 (defun org-align-tags-here (to-col)
12885 ;; Assumes that this is a headline
12886 (let ((pos (point)) (col (current-column)) ncol tags-l p)
12887 (beginning-of-line 1)
12888 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
12889 (< pos (match-beginning 2)))
12890 (progn
12891 (setq tags-l (- (match-end 2) (match-beginning 2)))
12892 (goto-char (match-beginning 1))
12893 (insert " ")
12894 (delete-region (point) (1+ (match-beginning 2)))
12895 (setq ncol (max (1+ (current-column))
12896 (1+ col)
12897 (if (> to-col 0)
12898 to-col
12899 (- (abs to-col) tags-l))))
12900 (setq p (point))
12901 (insert (make-string (- ncol (current-column)) ?\ ))
12902 (setq ncol (current-column))
12903 (when indent-tabs-mode (tabify p (point-at-eol)))
12904 (org-move-to-column (min ncol col) t))
12905 (goto-char pos))))
12907 (defun org-set-tags-command (&optional arg just-align)
12908 "Call the set-tags command for the current entry."
12909 (interactive "P")
12910 (if (org-on-heading-p)
12911 (org-set-tags arg just-align)
12912 (save-excursion
12913 (org-back-to-heading t)
12914 (org-set-tags arg just-align))))
12916 (defun org-set-tags-to (data)
12917 "Set the tags of the current entry to DATA, replacing the current tags.
12918 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
12919 If DATA is nil or the empty string, any tags will be removed."
12920 (interactive "sTags: ")
12921 (setq data
12922 (cond
12923 ((eq data nil) "")
12924 ((equal data "") "")
12925 ((stringp data)
12926 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
12927 ":"))
12928 ((listp data)
12929 (concat ":" (mapconcat 'identity data ":") ":"))
12930 (t nil)))
12931 (when data
12932 (save-excursion
12933 (org-back-to-heading t)
12934 (when (looking-at org-complex-heading-regexp)
12935 (if (match-end 5)
12936 (progn
12937 (goto-char (match-beginning 5))
12938 (insert data)
12939 (delete-region (point) (point-at-eol))
12940 (org-set-tags nil 'align))
12941 (goto-char (point-at-eol))
12942 (insert " " data)
12943 (org-set-tags nil 'align)))
12944 (beginning-of-line 1)
12945 (if (looking-at ".*?\\([ \t]+\\)$")
12946 (delete-region (match-beginning 1) (match-end 1))))))
12948 (defun org-align-all-tags ()
12949 "Align the tags i all headings."
12950 (interactive)
12951 (save-excursion
12952 (or (ignore-errors (org-back-to-heading t))
12953 (outline-next-heading))
12954 (if (org-on-heading-p)
12955 (org-set-tags t)
12956 (message "No headings"))))
12958 (defvar org-indent-indentation-per-level)
12959 (defun org-set-tags (&optional arg just-align)
12960 "Set the tags for the current headline.
12961 With prefix ARG, realign all tags in headings in the current buffer."
12962 (interactive "P")
12963 (let* ((re (concat "^" outline-regexp))
12964 (current (org-get-tags-string))
12965 (col (current-column))
12966 (org-setting-tags t)
12967 table current-tags inherited-tags ; computed below when needed
12968 tags p0 c0 c1 rpl di tc level)
12969 (if arg
12970 (save-excursion
12971 (goto-char (point-min))
12972 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
12973 (while (re-search-forward re nil t)
12974 (org-set-tags nil t)
12975 (end-of-line 1)))
12976 (message "All tags realigned to column %d" org-tags-column))
12977 (if just-align
12978 (setq tags current)
12979 ;; Get a new set of tags from the user
12980 (save-excursion
12981 (setq table (append org-tag-persistent-alist
12982 (or org-tag-alist (org-get-buffer-tags))
12983 (and
12984 org-complete-tags-always-offer-all-agenda-tags
12985 (org-global-tags-completion-table
12986 (org-agenda-files))))
12987 org-last-tags-completion-table table
12988 current-tags (org-split-string current ":")
12989 inherited-tags (nreverse
12990 (nthcdr (length current-tags)
12991 (nreverse (org-get-tags-at))))
12992 tags
12993 (if (or (eq t org-use-fast-tag-selection)
12994 (and org-use-fast-tag-selection
12995 (delq nil (mapcar 'cdr table))))
12996 (org-fast-tag-selection
12997 current-tags inherited-tags table
12998 (if org-fast-tag-selection-include-todo
12999 org-todo-key-alist))
13000 (let ((org-add-colon-after-tag-completion t))
13001 (org-trim
13002 (org-without-partial-completion
13003 (org-icompleting-read "Tags: "
13004 'org-tags-completion-function
13005 nil nil current 'org-tags-history)))))))
13006 (while (string-match "[-+&]+" tags)
13007 ;; No boolean logic, just a list
13008 (setq tags (replace-match ":" t t tags))))
13010 (setq tags (replace-regexp-in-string "[,]" ":" tags))
13012 (if org-tags-sort-function
13013 (setq tags (mapconcat 'identity
13014 (sort (org-split-string
13015 tags (org-re "[^[:alnum:]_@#%]+"))
13016 org-tags-sort-function) ":")))
13018 (if (string-match "\\`[\t ]*\\'" tags)
13019 (setq tags "")
13020 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
13021 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
13023 ;; Insert new tags at the correct column
13024 (beginning-of-line 1)
13025 (setq level (or (and (looking-at org-outline-regexp)
13026 (- (match-end 0) (point) 1))
13028 (cond
13029 ((and (equal current "") (equal tags "")))
13030 ((re-search-forward
13031 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
13032 (point-at-eol) t)
13033 (if (equal tags "")
13034 (setq rpl "")
13035 (goto-char (match-beginning 0))
13036 (setq c0 (current-column)
13037 ;; compute offset for the case of org-indent-mode active
13038 di (if org-indent-mode
13039 (* (1- org-indent-indentation-per-level) (1- level))
13041 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
13042 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
13043 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
13044 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
13045 (replace-match rpl t t)
13046 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
13047 tags)
13048 (t (error "Tags alignment failed")))
13049 (org-move-to-column col)
13050 (unless just-align
13051 (run-hooks 'org-after-tags-change-hook)))))
13053 (defun org-change-tag-in-region (beg end tag off)
13054 "Add or remove TAG for each entry in the region.
13055 This works in the agenda, and also in an org-mode buffer."
13056 (interactive
13057 (list (region-beginning) (region-end)
13058 (let ((org-last-tags-completion-table
13059 (if (org-mode-p)
13060 (org-get-buffer-tags)
13061 (org-global-tags-completion-table))))
13062 (org-icompleting-read
13063 "Tag: " 'org-tags-completion-function nil nil nil
13064 'org-tags-history))
13065 (progn
13066 (message "[s]et or [r]emove? ")
13067 (equal (read-char-exclusive) ?r))))
13068 (if (fboundp 'deactivate-mark) (deactivate-mark))
13069 (let ((agendap (equal major-mode 'org-agenda-mode))
13070 l1 l2 m buf pos newhead (cnt 0))
13071 (goto-char end)
13072 (setq l2 (1- (org-current-line)))
13073 (goto-char beg)
13074 (setq l1 (org-current-line))
13075 (loop for l from l1 to l2 do
13076 (org-goto-line l)
13077 (setq m (get-text-property (point) 'org-hd-marker))
13078 (when (or (and (org-mode-p) (org-on-heading-p))
13079 (and agendap m))
13080 (setq buf (if agendap (marker-buffer m) (current-buffer))
13081 pos (if agendap m (point)))
13082 (with-current-buffer buf
13083 (save-excursion
13084 (save-restriction
13085 (goto-char pos)
13086 (setq cnt (1+ cnt))
13087 (org-toggle-tag tag (if off 'off 'on))
13088 (setq newhead (org-get-heading)))))
13089 (and agendap (org-agenda-change-all-lines newhead m))))
13090 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
13092 (defun org-tags-completion-function (string predicate &optional flag)
13093 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
13094 (confirm (lambda (x) (stringp (car x)))))
13095 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
13096 (setq s1 (match-string 1 string)
13097 s2 (match-string 2 string))
13098 (setq s1 "" s2 string))
13099 (cond
13100 ((eq flag nil)
13101 ;; try completion
13102 (setq rtn (try-completion s2 ctable confirm))
13103 (if (stringp rtn)
13104 (setq rtn
13105 (concat s1 s2 (substring rtn (length s2))
13106 (if (and org-add-colon-after-tag-completion
13107 (assoc rtn ctable))
13108 ":" ""))))
13109 rtn)
13110 ((eq flag t)
13111 ;; all-completions
13112 (all-completions s2 ctable confirm)
13114 ((eq flag 'lambda)
13115 ;; exact match?
13116 (assoc s2 ctable)))
13119 (defun org-fast-tag-insert (kwd tags face &optional end)
13120 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
13121 (insert (format "%-12s" (concat kwd ":"))
13122 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
13123 (or end "")))
13125 (defun org-fast-tag-show-exit (flag)
13126 (save-excursion
13127 (org-goto-line 3)
13128 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
13129 (replace-match ""))
13130 (when flag
13131 (end-of-line 1)
13132 (org-move-to-column (- (window-width) 19) t)
13133 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
13135 (defun org-set-current-tags-overlay (current prefix)
13136 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
13137 (if (featurep 'xemacs)
13138 (org-overlay-display org-tags-overlay (concat prefix s)
13139 'secondary-selection)
13140 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
13141 (org-overlay-display org-tags-overlay (concat prefix s)))))
13143 (defvar org-last-tag-selection-key nil)
13144 (defun org-fast-tag-selection (current inherited table &optional todo-table)
13145 "Fast tag selection with single keys.
13146 CURRENT is the current list of tags in the headline, INHERITED is the
13147 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
13148 possibly with grouping information. TODO-TABLE is a similar table with
13149 TODO keywords, should these have keys assigned to them.
13150 If the keys are nil, a-z are automatically assigned.
13151 Returns the new tags string, or nil to not change the current settings."
13152 (let* ((fulltable (append table todo-table))
13153 (maxlen (apply 'max (mapcar
13154 (lambda (x)
13155 (if (stringp (car x)) (string-width (car x)) 0))
13156 fulltable)))
13157 (buf (current-buffer))
13158 (expert (eq org-fast-tag-selection-single-key 'expert))
13159 (buffer-tags nil)
13160 (fwidth (+ maxlen 3 1 3))
13161 (ncol (/ (- (window-width) 4) fwidth))
13162 (i-face 'org-done)
13163 (c-face 'org-todo)
13164 tg cnt e c char c1 c2 ntable tbl rtn
13165 ov-start ov-end ov-prefix
13166 (exit-after-next org-fast-tag-selection-single-key)
13167 (done-keywords org-done-keywords)
13168 groups ingroup)
13169 (save-excursion
13170 (beginning-of-line 1)
13171 (if (looking-at
13172 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13173 (setq ov-start (match-beginning 1)
13174 ov-end (match-end 1)
13175 ov-prefix "")
13176 (setq ov-start (1- (point-at-eol))
13177 ov-end (1+ ov-start))
13178 (skip-chars-forward "^\n\r")
13179 (setq ov-prefix
13180 (concat
13181 (buffer-substring (1- (point)) (point))
13182 (if (> (current-column) org-tags-column)
13184 (make-string (- org-tags-column (current-column)) ?\ ))))))
13185 (move-overlay org-tags-overlay ov-start ov-end)
13186 (save-window-excursion
13187 (if expert
13188 (set-buffer (get-buffer-create " *Org tags*"))
13189 (delete-other-windows)
13190 (split-window-vertically)
13191 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
13192 (erase-buffer)
13193 (org-set-local 'org-done-keywords done-keywords)
13194 (org-fast-tag-insert "Inherited" inherited i-face "\n")
13195 (org-fast-tag-insert "Current" current c-face "\n\n")
13196 (org-fast-tag-show-exit exit-after-next)
13197 (org-set-current-tags-overlay current ov-prefix)
13198 (setq tbl fulltable char ?a cnt 0)
13199 (while (setq e (pop tbl))
13200 (cond
13201 ((equal (car e) :startgroup)
13202 (push '() groups) (setq ingroup t)
13203 (when (not (= cnt 0))
13204 (setq cnt 0)
13205 (insert "\n"))
13206 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
13207 ((equal (car e) :endgroup)
13208 (setq ingroup nil cnt 0)
13209 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
13210 ((equal e '(:newline))
13211 (when (not (= cnt 0))
13212 (setq cnt 0)
13213 (insert "\n")
13214 (setq e (car tbl))
13215 (while (equal (car tbl) '(:newline))
13216 (insert "\n")
13217 (setq tbl (cdr tbl)))))
13219 (setq tg (copy-sequence (car e)) c2 nil)
13220 (if (cdr e)
13221 (setq c (cdr e))
13222 ;; automatically assign a character.
13223 (setq c1 (string-to-char
13224 (downcase (substring
13225 tg (if (= (string-to-char tg) ?@) 1 0)))))
13226 (if (or (rassoc c1 ntable) (rassoc c1 table))
13227 (while (or (rassoc char ntable) (rassoc char table))
13228 (setq char (1+ char)))
13229 (setq c2 c1))
13230 (setq c (or c2 char)))
13231 (if ingroup (push tg (car groups)))
13232 (setq tg (org-add-props tg nil 'face
13233 (cond
13234 ((not (assoc tg table))
13235 (org-get-todo-face tg))
13236 ((member tg current) c-face)
13237 ((member tg inherited) i-face)
13238 (t nil))))
13239 (if (and (= cnt 0) (not ingroup)) (insert " "))
13240 (insert "[" c "] " tg (make-string
13241 (- fwidth 4 (length tg)) ?\ ))
13242 (push (cons tg c) ntable)
13243 (when (= (setq cnt (1+ cnt)) ncol)
13244 (insert "\n")
13245 (if ingroup (insert " "))
13246 (setq cnt 0)))))
13247 (setq ntable (nreverse ntable))
13248 (insert "\n")
13249 (goto-char (point-min))
13250 (if (not expert) (org-fit-window-to-buffer))
13251 (setq rtn
13252 (catch 'exit
13253 (while t
13254 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
13255 (if (not groups) "no " "")
13256 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
13257 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13258 (setq org-last-tag-selection-key c)
13259 (cond
13260 ((= c ?\r) (throw 'exit t))
13261 ((= c ?!)
13262 (setq groups (not groups))
13263 (goto-char (point-min))
13264 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
13265 ((= c ?\C-c)
13266 (if (not expert)
13267 (org-fast-tag-show-exit
13268 (setq exit-after-next (not exit-after-next)))
13269 (setq expert nil)
13270 (delete-other-windows)
13271 (set-window-buffer (split-window-vertically) " *Org tags*")
13272 (org-switch-to-buffer-other-window " *Org tags*")
13273 (org-fit-window-to-buffer)))
13274 ((or (= c ?\C-g)
13275 (and (= c ?q) (not (rassoc c ntable))))
13276 (org-detach-overlay org-tags-overlay)
13277 (setq quit-flag t))
13278 ((= c ?\ )
13279 (setq current nil)
13280 (if exit-after-next (setq exit-after-next 'now)))
13281 ((= c ?\t)
13282 (condition-case nil
13283 (setq tg (org-icompleting-read
13284 "Tag: "
13285 (or buffer-tags
13286 (with-current-buffer buf
13287 (org-get-buffer-tags)))))
13288 (quit (setq tg "")))
13289 (when (string-match "\\S-" tg)
13290 (add-to-list 'buffer-tags (list tg))
13291 (if (member tg current)
13292 (setq current (delete tg current))
13293 (push tg current)))
13294 (if exit-after-next (setq exit-after-next 'now)))
13295 ((setq e (rassoc c todo-table) tg (car e))
13296 (with-current-buffer buf
13297 (save-excursion (org-todo tg)))
13298 (if exit-after-next (setq exit-after-next 'now)))
13299 ((setq e (rassoc c ntable) tg (car e))
13300 (if (member tg current)
13301 (setq current (delete tg current))
13302 (loop for g in groups do
13303 (if (member tg g)
13304 (mapc (lambda (x)
13305 (setq current (delete x current)))
13306 g)))
13307 (push tg current))
13308 (if exit-after-next (setq exit-after-next 'now))))
13310 ;; Create a sorted list
13311 (setq current
13312 (sort current
13313 (lambda (a b)
13314 (assoc b (cdr (memq (assoc a ntable) ntable))))))
13315 (if (eq exit-after-next 'now) (throw 'exit t))
13316 (goto-char (point-min))
13317 (beginning-of-line 2)
13318 (delete-region (point) (point-at-eol))
13319 (org-fast-tag-insert "Current" current c-face)
13320 (org-set-current-tags-overlay current ov-prefix)
13321 (while (re-search-forward
13322 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
13323 (setq tg (match-string 1))
13324 (add-text-properties
13325 (match-beginning 1) (match-end 1)
13326 (list 'face
13327 (cond
13328 ((member tg current) c-face)
13329 ((member tg inherited) i-face)
13330 (t (get-text-property (match-beginning 1) 'face))))))
13331 (goto-char (point-min)))))
13332 (org-detach-overlay org-tags-overlay)
13333 (if rtn
13334 (mapconcat 'identity current ":")
13335 nil))))
13337 (defun org-get-tags-string ()
13338 "Get the TAGS string in the current headline."
13339 (unless (org-on-heading-p t)
13340 (error "Not on a heading"))
13341 (save-excursion
13342 (beginning-of-line 1)
13343 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13344 (org-match-string-no-properties 1)
13345 "")))
13347 (defun org-get-tags ()
13348 "Get the list of tags specified in the current headline."
13349 (org-split-string (org-get-tags-string) ":"))
13351 (defun org-get-buffer-tags ()
13352 "Get a table of all tags used in the buffer, for completion."
13353 (let (tags)
13354 (save-excursion
13355 (goto-char (point-min))
13356 (while (re-search-forward
13357 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
13358 (when (equal (char-after (point-at-bol 0)) ?*)
13359 (mapc (lambda (x) (add-to-list 'tags x))
13360 (org-split-string (org-match-string-no-properties 1) ":")))))
13361 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
13362 (mapcar 'list tags)))
13364 ;;;; The mapping API
13366 ;;;###autoload
13367 (defun org-map-entries (func &optional match scope &rest skip)
13368 "Call FUNC at each headline selected by MATCH in SCOPE.
13370 FUNC is a function or a lisp form. The function will be called without
13371 arguments, with the cursor positioned at the beginning of the headline.
13372 The return values of all calls to the function will be collected and
13373 returned as a list.
13375 The call to FUNC will be wrapped into a save-excursion form, so FUNC
13376 does not need to preserve point. After evaluation, the cursor will be
13377 moved to the end of the line (presumably of the headline of the
13378 processed entry) and search continues from there. Under some
13379 circumstances, this may not produce the wanted results. For example,
13380 if you have removed (e.g. archived) the current (sub)tree it could
13381 mean that the next entry will be skipped entirely. In such cases, you
13382 can specify the position from where search should continue by making
13383 FUNC set the variable `org-map-continue-from' to the desired buffer
13384 position.
13386 MATCH is a tags/property/todo match as it is used in the agenda tags view.
13387 Only headlines that are matched by this query will be considered during
13388 the iteration. When MATCH is nil or t, all headlines will be
13389 visited by the iteration.
13391 SCOPE determines the scope of this command. It can be any of:
13393 nil The current buffer, respecting the restriction if any
13394 tree The subtree started with the entry at point
13395 file The current buffer, without restriction
13396 file-with-archives
13397 The current buffer, and any archives associated with it
13398 agenda All agenda files
13399 agenda-with-archives
13400 All agenda files with any archive files associated with them
13401 \(file1 file2 ...)
13402 If this is a list, all files in the list will be scanned
13404 The remaining args are treated as settings for the skipping facilities of
13405 the scanner. The following items can be given here:
13407 archive skip trees with the archive tag.
13408 comment skip trees with the COMMENT keyword
13409 function or Emacs Lisp form:
13410 will be used as value for `org-agenda-skip-function', so whenever
13411 the function returns t, FUNC will not be called for that
13412 entry and search will continue from the point where the
13413 function leaves it.
13415 If your function needs to retrieve the tags including inherited tags
13416 at the *current* entry, you can use the value of the variable
13417 `org-scanner-tags' which will be much faster than getting the value
13418 with `org-get-tags-at'. If your function gets properties with
13419 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
13420 to t around the call to `org-entry-properties' to get the same speedup.
13421 Note that if your function moves around to retrieve tags and properties at
13422 a *different* entry, you cannot use these techniques."
13423 (let* ((org-agenda-archives-mode nil) ; just to make sure
13424 (org-agenda-skip-archived-trees (memq 'archive skip))
13425 (org-agenda-skip-comment-trees (memq 'comment skip))
13426 (org-agenda-skip-function
13427 (car (org-delete-all '(comment archive) skip)))
13428 (org-tags-match-list-sublevels t)
13429 matcher file res
13430 org-todo-keywords-for-agenda
13431 org-done-keywords-for-agenda
13432 org-todo-keyword-alist-for-agenda
13433 org-drawers-for-agenda
13434 org-tag-alist-for-agenda)
13436 (cond
13437 ((eq match t) (setq matcher t))
13438 ((eq match nil) (setq matcher t))
13439 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
13441 (save-excursion
13442 (save-restriction
13443 (when (eq scope 'tree)
13444 (org-back-to-heading t)
13445 (org-narrow-to-subtree)
13446 (setq scope nil))
13448 (if (not scope)
13449 (progn
13450 (org-prepare-agenda-buffers
13451 (list (buffer-file-name (current-buffer))))
13452 (setq res (org-scan-tags func matcher)))
13453 ;; Get the right scope
13454 (cond
13455 ((and scope (listp scope) (symbolp (car scope)))
13456 (setq scope (eval scope)))
13457 ((eq scope 'agenda)
13458 (setq scope (org-agenda-files t)))
13459 ((eq scope 'agenda-with-archives)
13460 (setq scope (org-agenda-files t))
13461 (setq scope (org-add-archive-files scope)))
13462 ((eq scope 'file)
13463 (setq scope (list (buffer-file-name))))
13464 ((eq scope 'file-with-archives)
13465 (setq scope (org-add-archive-files (list (buffer-file-name))))))
13466 (org-prepare-agenda-buffers scope)
13467 (while (setq file (pop scope))
13468 (with-current-buffer (org-find-base-buffer-visiting file)
13469 (save-excursion
13470 (save-restriction
13471 (widen)
13472 (goto-char (point-min))
13473 (setq res (append res (org-scan-tags func matcher))))))))))
13474 res))
13476 ;;;; Properties
13478 ;;; Setting and retrieving properties
13480 (defconst org-special-properties
13481 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
13482 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE")
13483 "The special properties valid in Org-mode.
13485 These are properties that are not defined in the property drawer,
13486 but in some other way.")
13488 (defconst org-default-properties
13489 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
13490 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
13491 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
13492 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
13493 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
13494 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
13495 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
13496 "Some properties that are used by Org-mode for various purposes.
13497 Being in this list makes sure that they are offered for completion.")
13499 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
13500 "Regular expression matching the first line of a property drawer.")
13502 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
13503 "Regular expression matching the last line of a property drawer.")
13505 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
13506 "Regular expression matching the first line of a property drawer.")
13508 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
13509 "Regular expression matching the first line of a property drawer.")
13511 (defconst org-property-drawer-re
13512 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
13513 org-property-end-re "\\)\n?")
13514 "Matches an entire property drawer.")
13516 (defconst org-clock-drawer-re
13517 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
13518 org-property-end-re "\\)\n?")
13519 "Matches an entire clock drawer.")
13521 (defun org-property-action ()
13522 "Do an action on properties."
13523 (interactive)
13524 (let (c)
13525 (org-at-property-p)
13526 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
13527 (setq c (read-char-exclusive))
13528 (cond
13529 ((equal c ?s)
13530 (call-interactively 'org-set-property))
13531 ((equal c ?d)
13532 (call-interactively 'org-delete-property))
13533 ((equal c ?D)
13534 (call-interactively 'org-delete-property-globally))
13535 ((equal c ?c)
13536 (call-interactively 'org-compute-property-at-point))
13537 (t (error "No such property action %c" c)))))
13539 (defun org-set-effort (&optional value)
13540 "Set the effort property of the current entry.
13541 With numerical prefix arg, use the nth allowed value, 0 stands for the 10th
13542 allowed value."
13543 (interactive "P")
13544 (if (equal value 0) (setq value 10))
13545 (let* ((completion-ignore-case t)
13546 (prop org-effort-property)
13547 (cur (org-entry-get nil prop))
13548 (allowed (org-property-get-allowed-values nil prop 'table))
13549 (existing (mapcar 'list (org-property-values prop)))
13551 (val (cond
13552 ((stringp value) value)
13553 ((and allowed (integerp value))
13554 (or (car (nth (1- value) allowed))
13555 (car (org-last allowed))))
13556 (allowed
13557 (message "Select 1-9,0, [RET%s]: %s"
13558 (if cur (concat "=" cur) "")
13559 (mapconcat 'car allowed " "))
13560 (setq rpl (read-char-exclusive))
13561 (if (equal rpl ?\r)
13563 (setq rpl (- rpl ?0))
13564 (if (equal rpl 0) (setq rpl 10))
13565 (if (and (> rpl 0) (<= rpl (length allowed)))
13566 (car (nth (1- rpl) allowed))
13567 (org-completing-read "Effort: " allowed nil))))
13569 (let (org-completion-use-ido org-completion-use-iswitchb)
13570 (org-completing-read
13571 (concat "Effort " (if (and cur (string-match "\\S-" cur))
13572 (concat "[" cur "]") "")
13573 ": ")
13574 existing nil nil "" nil cur))))))
13575 (unless (equal (org-entry-get nil prop) val)
13576 (org-entry-put nil prop val))
13577 (message "%s is now %s" prop val)))
13579 (defun org-at-property-p ()
13580 "Is cursor inside a property drawer?"
13581 (save-excursion
13582 (beginning-of-line 1)
13583 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
13584 (save-match-data ;; Used by calling procedures
13585 (let ((p (point))
13586 (range (unless (org-before-first-heading-p)
13587 (org-get-property-block))))
13588 (and range (<= (car range) p) (< p (cdr range))))))))
13590 (defun org-get-property-block (&optional beg end force)
13591 "Return the (beg . end) range of the body of the property drawer.
13592 BEG and END can be beginning and end of subtree, if not given
13593 they will be found.
13594 If the drawer does not exist and FORCE is non-nil, create the drawer."
13595 (catch 'exit
13596 (save-excursion
13597 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
13598 (end (or end (progn (outline-next-heading) (point)))))
13599 (goto-char beg)
13600 (if (re-search-forward org-property-start-re end t)
13601 (setq beg (1+ (match-end 0)))
13602 (if force
13603 (save-excursion
13604 (org-insert-property-drawer)
13605 (setq end (progn (outline-next-heading) (point))))
13606 (throw 'exit nil))
13607 (goto-char beg)
13608 (if (re-search-forward org-property-start-re end t)
13609 (setq beg (1+ (match-end 0)))))
13610 (if (re-search-forward org-property-end-re end t)
13611 (setq end (match-beginning 0))
13612 (or force (throw 'exit nil))
13613 (goto-char beg)
13614 (setq end beg)
13615 (org-indent-line-function)
13616 (insert ":END:\n"))
13617 (cons beg end)))))
13619 (defun org-entry-properties (&optional pom which specific)
13620 "Get all properties of the entry at point-or-marker POM.
13621 This includes the TODO keyword, the tags, time strings for deadline,
13622 scheduled, and clocking, and any additional properties defined in the
13623 entry. The return value is an alist, keys may occur multiple times
13624 if the property key was used several times.
13625 POM may also be nil, in which case the current entry is used.
13626 If WHICH is nil or `all', get all properties. If WHICH is
13627 `special' or `standard', only get that subclass. If WHICH
13628 is a string only get exactly this property. SPECIFIC can be a string, the
13629 specific property we are interested in. Specifying it can speed
13630 things up because then unnecessary parsing is avoided."
13631 (setq which (or which 'all))
13632 (org-with-point-at pom
13633 (let ((clockstr (substring org-clock-string 0 -1))
13634 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
13635 (case-fold-search nil)
13636 beg end range props sum-props key key1 value string clocksum)
13637 (save-excursion
13638 (when (condition-case nil
13639 (and (org-mode-p) (org-back-to-heading t))
13640 (error nil))
13641 (setq beg (point))
13642 (setq sum-props (get-text-property (point) 'org-summaries))
13643 (setq clocksum (get-text-property (point) :org-clock-minutes))
13644 (outline-next-heading)
13645 (setq end (point))
13646 (when (memq which '(all special))
13647 ;; Get the special properties, like TODO and tags
13648 (goto-char beg)
13649 (when (and (or (not specific) (string= specific "TODO"))
13650 (looking-at org-todo-line-regexp) (match-end 2))
13651 (push (cons "TODO" (org-match-string-no-properties 2)) props))
13652 (when (and (or (not specific) (string= specific "PRIORITY"))
13653 (looking-at org-priority-regexp))
13654 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
13655 (when (or (not specific) (string= specific "FILE"))
13656 (push (cons "FILE" buffer-file-name) props))
13657 (when (and (or (not specific) (string= specific "TAGS"))
13658 (setq value (org-get-tags-string))
13659 (string-match "\\S-" value))
13660 (push (cons "TAGS" value) props))
13661 (when (and (or (not specific) (string= specific "ALLTAGS"))
13662 (setq value (org-get-tags-at)))
13663 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
13664 ":"))
13665 props))
13666 (when (or (not specific) (string= specific "BLOCKED"))
13667 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
13668 (when (or (not specific)
13669 (member specific
13670 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
13671 "TIMESTAMP" "TIMESTAMP_IA")))
13672 (catch 'match
13673 (while (re-search-forward org-maybe-keyword-time-regexp end t)
13674 (setq key (if (match-end 1)
13675 (substring (org-match-string-no-properties 1)
13676 0 -1))
13677 string (if (equal key clockstr)
13678 (org-no-properties
13679 (org-trim
13680 (buffer-substring
13681 (match-beginning 3) (goto-char
13682 (point-at-eol)))))
13683 (substring (org-match-string-no-properties 3)
13684 1 -1)))
13685 ;; Get the correct property name from the key. This is
13686 ;; necessary if the user has configured time keywords.
13687 (setq key1 (concat key ":"))
13688 (cond
13689 ((not key)
13690 (setq key
13691 (if (= (char-after (match-beginning 3)) ?\[)
13692 "TIMESTAMP_IA" "TIMESTAMP")))
13693 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
13694 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
13695 ((equal key1 org-closed-string) (setq key "CLOSED"))
13696 ((equal key1 org-clock-string) (setq key "CLOCK")))
13697 (if (and specific (equal key specific) (not (equal key "CLOCK")))
13698 (progn
13699 (push (cons key string) props)
13700 ;; no need to search further if match is found
13701 (throw 'match t))
13702 (when (or (equal key "CLOCK") (not (assoc key props)))
13703 (push (cons key string) props))))))
13706 (when (memq which '(all standard))
13707 ;; Get the standard properties, like :PROP: ...
13708 (setq range (org-get-property-block beg end))
13709 (when range
13710 (goto-char (car range))
13711 (while (re-search-forward
13712 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
13713 (cdr range) t)
13714 (setq key (org-match-string-no-properties 1)
13715 value (org-trim (or (org-match-string-no-properties 2) "")))
13716 (unless (member key excluded)
13717 (push (cons key (or value "")) props)))))
13718 (if clocksum
13719 (push (cons "CLOCKSUM"
13720 (org-columns-number-to-string (/ (float clocksum) 60.)
13721 'add_times))
13722 props))
13723 (unless (assoc "CATEGORY" props)
13724 (push (cons "CATEGORY" (org-get-category)) props))
13725 (append sum-props (nreverse props)))))))
13727 (defun org-entry-get (pom property &optional inherit literal-nil)
13728 "Get value of PROPERTY for entry at point-or-marker POM.
13729 If INHERIT is non-nil and the entry does not have the property,
13730 then also check higher levels of the hierarchy.
13731 If INHERIT is the symbol `selective', use inheritance only if the setting
13732 in `org-use-property-inheritance' selects PROPERTY for inheritance.
13733 If the property is present but empty, the return value is the empty string.
13734 If the property is not present at all, nil is returned.
13736 If LITERAL-NIL is set, return the string value \"nil\" as a string,
13737 do not interpret it as the list atom nil. This is used for inheritance
13738 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
13739 (org-with-point-at pom
13740 (if (and inherit (if (eq inherit 'selective)
13741 (org-property-inherit-p property)
13743 (org-entry-get-with-inheritance property literal-nil)
13744 (if (member property org-special-properties)
13745 ;; We need a special property. Use `org-entry-properties' to
13746 ;; retrieve it, but specify the wanted property
13747 (cdr (assoc property (org-entry-properties nil 'special property)))
13748 (let ((range (unless (org-before-first-heading-p)
13749 (org-get-property-block))))
13750 (if (and range
13751 (goto-char (car range))
13752 (re-search-forward
13753 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)?")
13754 (cdr range) t))
13755 ;; Found the property, return it.
13756 (if (match-end 1)
13757 (if literal-nil
13758 (org-match-string-no-properties 1)
13759 (org-not-nil (org-match-string-no-properties 1)))
13760 "")))))))
13762 (defun org-property-or-variable-value (var &optional inherit)
13763 "Check if there is a property fixing the value of VAR.
13764 If yes, return this value. If not, return the current value of the variable."
13765 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
13766 (if (and prop (stringp prop) (string-match "\\S-" prop))
13767 (read prop)
13768 (symbol-value var))))
13770 (defun org-entry-delete (pom property)
13771 "Delete the property PROPERTY from entry at point-or-marker POM."
13772 (org-with-point-at pom
13773 (if (member property org-special-properties)
13774 nil ; cannot delete these properties.
13775 (let ((range (org-get-property-block)))
13776 (if (and range
13777 (goto-char (car range))
13778 (re-search-forward
13779 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)")
13780 (cdr range) t))
13781 (progn
13782 (delete-region (match-beginning 0) (1+ (point-at-eol)))
13784 nil)))))
13786 ;; Multi-values properties are properties that contain multiple values
13787 ;; These values are assumed to be single words, separated by whitespace.
13788 (defun org-entry-add-to-multivalued-property (pom property value)
13789 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
13790 (let* ((old (org-entry-get pom property))
13791 (values (and old (org-split-string old "[ \t]"))))
13792 (setq value (org-entry-protect-space value))
13793 (unless (member value values)
13794 (setq values (cons value values))
13795 (org-entry-put pom property
13796 (mapconcat 'identity values " ")))))
13798 (defun org-entry-remove-from-multivalued-property (pom property value)
13799 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
13800 (let* ((old (org-entry-get pom property))
13801 (values (and old (org-split-string old "[ \t]"))))
13802 (setq value (org-entry-protect-space value))
13803 (when (member value values)
13804 (setq values (delete value values))
13805 (org-entry-put pom property
13806 (mapconcat 'identity values " ")))))
13808 (defun org-entry-member-in-multivalued-property (pom property value)
13809 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
13810 (let* ((old (org-entry-get pom property))
13811 (values (and old (org-split-string old "[ \t]"))))
13812 (setq value (org-entry-protect-space value))
13813 (member value values)))
13815 (defun org-entry-get-multivalued-property (pom property)
13816 "Return a list of values in a multivalued property."
13817 (let* ((value (org-entry-get pom property))
13818 (values (and value (org-split-string value "[ \t]"))))
13819 (mapcar 'org-entry-restore-space values)))
13821 (defun org-entry-put-multivalued-property (pom property &rest values)
13822 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
13823 VALUES should be a list of strings. Spaces will be protected."
13824 (org-entry-put pom property
13825 (mapconcat 'org-entry-protect-space values " "))
13826 (let* ((value (org-entry-get pom property))
13827 (values (and value (org-split-string value "[ \t]"))))
13828 (mapcar 'org-entry-restore-space values)))
13830 (defun org-entry-protect-space (s)
13831 "Protect spaces and newline in string S."
13832 (while (string-match " " s)
13833 (setq s (replace-match "%20" t t s)))
13834 (while (string-match "\n" s)
13835 (setq s (replace-match "%0A" t t s)))
13838 (defun org-entry-restore-space (s)
13839 "Restore spaces and newline in string S."
13840 (while (string-match "%20" s)
13841 (setq s (replace-match " " t t s)))
13842 (while (string-match "%0A" s)
13843 (setq s (replace-match "\n" t t s)))
13846 (defvar org-entry-property-inherited-from (make-marker)
13847 "Marker pointing to the entry from where a property was inherited.
13848 Each call to `org-entry-get-with-inheritance' will set this marker to the
13849 location of the entry where the inheritance search matched. If there was
13850 no match, the marker will point nowhere.
13851 Note that also `org-entry-get' calls this function, if the INHERIT flag
13852 is set.")
13854 (defun org-entry-get-with-inheritance (property &optional literal-nil)
13855 "Get entry property, and search higher levels if not present.
13856 The search will stop at the first ancestor which has the property defined.
13857 If the value found is \"nil\", return nil to show that the property
13858 should be considered as undefined (this is the meaning of nil here).
13859 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
13860 (move-marker org-entry-property-inherited-from nil)
13861 (let (tmp)
13862 (unless (org-before-first-heading-p)
13863 (save-excursion
13864 (save-restriction
13865 (widen)
13866 (catch 'ex
13867 (while t
13868 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
13869 (org-back-to-heading t)
13870 (move-marker org-entry-property-inherited-from (point))
13871 (throw 'ex tmp))
13872 (or (org-up-heading-safe) (throw 'ex nil)))))))
13873 (setq tmp (or tmp
13874 (cdr (assoc property org-file-properties))
13875 (cdr (assoc property org-global-properties))
13876 (cdr (assoc property org-global-properties-fixed))))
13877 (if literal-nil tmp (org-not-nil tmp))))
13879 (defvar org-property-changed-functions nil
13880 "Hook called when the value of a property has changed.
13881 Each hook function should accept two arguments, the name of the property
13882 and the new value.")
13884 (defun org-entry-put (pom property value)
13885 "Set PROPERTY to VALUE for entry at point-or-marker POM."
13886 (org-with-point-at pom
13887 (org-back-to-heading t)
13888 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
13889 range)
13890 (cond
13891 ((equal property "TODO")
13892 (when (and (stringp value) (string-match "\\S-" value)
13893 (not (member value org-todo-keywords-1)))
13894 (error "\"%s\" is not a valid TODO state" value))
13895 (if (or (not value)
13896 (not (string-match "\\S-" value)))
13897 (setq value 'none))
13898 (org-todo value)
13899 (org-set-tags nil 'align))
13900 ((equal property "PRIORITY")
13901 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
13902 (string-to-char value) ?\ ))
13903 (org-set-tags nil 'align))
13904 ((equal property "SCHEDULED")
13905 (if (re-search-forward org-scheduled-time-regexp end t)
13906 (cond
13907 ((eq value 'earlier) (org-timestamp-change -1 'day))
13908 ((eq value 'later) (org-timestamp-change 1 'day))
13909 (t (call-interactively 'org-schedule)))
13910 (call-interactively 'org-schedule)))
13911 ((equal property "DEADLINE")
13912 (if (re-search-forward org-deadline-time-regexp end t)
13913 (cond
13914 ((eq value 'earlier) (org-timestamp-change -1 'day))
13915 ((eq value 'later) (org-timestamp-change 1 'day))
13916 (t (call-interactively 'org-deadline)))
13917 (call-interactively 'org-deadline)))
13918 ((member property org-special-properties)
13919 (error "The %s property can not yet be set with `org-entry-put'"
13920 property))
13921 (t ; a non-special property
13922 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
13923 (setq range (org-get-property-block beg end 'force))
13924 (goto-char (car range))
13925 (if (re-search-forward
13926 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
13927 (progn
13928 (delete-region (match-beginning 1) (match-end 1))
13929 (goto-char (match-beginning 1)))
13930 (goto-char (cdr range))
13931 (insert "\n")
13932 (backward-char 1)
13933 (org-indent-line-function)
13934 (insert ":" property ":"))
13935 (and value (insert " " value))
13936 (org-indent-line-function)))))
13937 (run-hook-with-args 'org-property-changed-functions property value)))
13939 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
13940 "Get all property keys in the current buffer.
13941 With INCLUDE-SPECIALS, also list the special properties that reflect things
13942 like tags and TODO state.
13943 With INCLUDE-DEFAULTS, also include properties that has special meaning
13944 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
13945 and others.
13946 With INCLUDE-COLUMNS, also include property names given in COLUMN
13947 formats in the current buffer."
13948 (let (rtn range cfmt s p)
13949 (save-excursion
13950 (save-restriction
13951 (widen)
13952 (goto-char (point-min))
13953 (while (re-search-forward org-property-start-re nil t)
13954 (setq range (org-get-property-block))
13955 (goto-char (car range))
13956 (while (re-search-forward
13957 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
13958 (cdr range) t)
13959 (add-to-list 'rtn (org-match-string-no-properties 1)))
13960 (outline-next-heading))))
13962 (when include-specials
13963 (setq rtn (append org-special-properties rtn)))
13965 (when include-defaults
13966 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
13967 (add-to-list 'rtn org-effort-property))
13969 (when include-columns
13970 (save-excursion
13971 (save-restriction
13972 (widen)
13973 (goto-char (point-min))
13974 (while (re-search-forward
13975 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
13976 nil t)
13977 (setq cfmt (match-string 2) s 0)
13978 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
13979 cfmt s)
13980 (setq s (match-end 0)
13981 p (match-string 1 cfmt))
13982 (unless (or (equal p "ITEM")
13983 (member p org-special-properties))
13984 (add-to-list 'rtn (match-string 1 cfmt))))))))
13986 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
13988 (defun org-property-values (key)
13989 "Return a list of all values of property KEY."
13990 (save-excursion
13991 (save-restriction
13992 (widen)
13993 (goto-char (point-min))
13994 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
13995 values)
13996 (while (re-search-forward re nil t)
13997 (add-to-list 'values (org-trim (match-string 1))))
13998 (delete "" values)))))
14000 (defun org-insert-property-drawer ()
14001 "Insert a property drawer into the current entry."
14002 (interactive)
14003 (org-back-to-heading t)
14004 (looking-at outline-regexp)
14005 (let ((indent (if org-adapt-indentation
14006 (- (match-end 0)(match-beginning 0))
14008 (beg (point))
14009 (re (concat "^[ \t]*" org-keyword-time-regexp))
14010 end hiddenp)
14011 (outline-next-heading)
14012 (setq end (point))
14013 (goto-char beg)
14014 (while (re-search-forward re end t))
14015 (setq hiddenp (outline-invisible-p))
14016 (end-of-line 1)
14017 (and (equal (char-after) ?\n) (forward-char 1))
14018 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
14019 (if (member (match-string 1) '("CLOCK:" ":END:"))
14020 ;; just skip this line
14021 (beginning-of-line 2)
14022 ;; Drawer start, find the end
14023 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
14024 (beginning-of-line 1)))
14025 (org-skip-over-state-notes)
14026 (skip-chars-backward " \t\n\r")
14027 (if (eq (char-before) ?*) (forward-char 1))
14028 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
14029 (beginning-of-line 0)
14030 (org-indent-to-column indent)
14031 (beginning-of-line 2)
14032 (org-indent-to-column indent)
14033 (beginning-of-line 0)
14034 (if hiddenp
14035 (save-excursion
14036 (org-back-to-heading t)
14037 (hide-entry))
14038 (org-flag-drawer t))))
14040 (defvar org-property-set-functions-alist nil
14041 "Property set function alist.
14042 Each entry should have the following format:
14044 (PROPERTY . READ-FUNCTION)
14046 The read function will be called with the same argument as
14047 `org-completing-read'.")
14049 (defun org-set-property-function (property)
14050 "Get the function that should be used to set PROPERTY.
14051 This is computed according to `org-property-set-functions-alist'."
14052 (or (cdr (assoc property org-property-set-functions-alist))
14053 'org-completing-read))
14055 (defun org-read-property-value (property)
14056 "Read PROPERTY value from user."
14057 (let* ((completion-ignore-case t)
14058 (allowed (org-property-get-allowed-values nil property 'table))
14059 (cur (org-entry-get nil property))
14060 (prompt (concat property " value"
14061 (if (and cur (string-match "\\S-" cur))
14062 (concat " [" cur "]") "") ": "))
14063 (set-function (org-set-property-function property))
14064 (val (if allowed
14065 (funcall set-function prompt allowed nil
14066 (not (get-text-property 0 'org-unrestricted
14067 (caar allowed))))
14068 (let (org-completion-use-ido org-completion-use-iswitchb)
14069 (funcall set-function prompt
14070 (mapcar 'list (org-property-values property))
14071 nil nil "" nil cur)))))
14072 (if (equal val "")
14074 val)))
14076 (defun org-read-property-name ()
14077 "Read a property name."
14078 (let* ((completion-ignore-case t)
14079 (keys (org-buffer-property-keys nil t t))
14080 (property (org-icompleting-read "Property: " (mapcar 'list keys))))
14081 (if (member property keys)
14082 property
14083 (or (cdr (assoc (downcase property)
14084 (mapcar (lambda (x) (cons (downcase x) x))
14085 keys)))
14086 property))))
14088 (defun org-set-property (property value)
14089 "In the current entry, set PROPERTY to VALUE.
14090 When called interactively, this will prompt for a property name, offering
14091 completion on existing and default properties. And then it will prompt
14092 for a value, offering completion either on allowed values (via an inherited
14093 xxx_ALL property) or on existing values in other instances of this property
14094 in the current file."
14095 (interactive (list nil nil))
14096 (let* ((property (or property (org-read-property-name)))
14097 (value (or value (org-read-property-value property))))
14098 (unless (equal (org-entry-get nil property) value)
14099 (org-entry-put nil property value))))
14101 (defun org-delete-property (property)
14102 "In the current entry, delete PROPERTY."
14103 (interactive
14104 (let* ((completion-ignore-case t)
14105 (prop (org-icompleting-read "Property: "
14106 (org-entry-properties nil 'standard))))
14107 (list prop)))
14108 (message "Property %s %s" property
14109 (if (org-entry-delete nil property)
14110 "deleted"
14111 "was not present in the entry")))
14113 (defun org-delete-property-globally (property)
14114 "Remove PROPERTY globally, from all entries."
14115 (interactive
14116 (let* ((completion-ignore-case t)
14117 (prop (org-icompleting-read
14118 "Globally remove property: "
14119 (mapcar 'list (org-buffer-property-keys)))))
14120 (list prop)))
14121 (save-excursion
14122 (save-restriction
14123 (widen)
14124 (goto-char (point-min))
14125 (let ((cnt 0))
14126 (while (re-search-forward
14127 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
14128 nil t)
14129 (setq cnt (1+ cnt))
14130 (replace-match ""))
14131 (message "Property \"%s\" removed from %d entries" property cnt)))))
14133 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
14135 (defun org-compute-property-at-point ()
14136 "Compute the property at point.
14137 This looks for an enclosing column format, extracts the operator and
14138 then applies it to the property in the column format's scope."
14139 (interactive)
14140 (unless (org-at-property-p)
14141 (error "Not at a property"))
14142 (let ((prop (org-match-string-no-properties 2)))
14143 (org-columns-get-format-and-top-level)
14144 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
14145 (error "No operator defined for property %s" prop))
14146 (org-columns-compute prop)))
14148 (defvar org-property-allowed-value-functions nil
14149 "Hook for functions supplying allowed values for a specific property.
14150 The functions must take a single argument, the name of the property, and
14151 return a flat list of allowed values. If \":ETC\" is one of
14152 the values, this means that these values are intended as defaults for
14153 completion, but that other values should be allowed too.
14154 The functions must return nil if they are not responsible for this
14155 property.")
14157 (defun org-property-get-allowed-values (pom property &optional table)
14158 "Get allowed values for the property PROPERTY.
14159 When TABLE is non-nil, return an alist that can directly be used for
14160 completion."
14161 (let (vals)
14162 (cond
14163 ((equal property "TODO")
14164 (setq vals (org-with-point-at pom
14165 (append org-todo-keywords-1 '("")))))
14166 ((equal property "PRIORITY")
14167 (let ((n org-lowest-priority))
14168 (while (>= n org-highest-priority)
14169 (push (char-to-string n) vals)
14170 (setq n (1- n)))))
14171 ((member property org-special-properties))
14172 ((setq vals (run-hook-with-args-until-success
14173 'org-property-allowed-value-functions property)))
14175 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
14176 (when (and vals (string-match "\\S-" vals))
14177 (setq vals (car (read-from-string (concat "(" vals ")"))))
14178 (setq vals (mapcar (lambda (x)
14179 (cond ((stringp x) x)
14180 ((numberp x) (number-to-string x))
14181 ((symbolp x) (symbol-name x))
14182 (t "???")))
14183 vals)))))
14184 (when (member ":ETC" vals)
14185 (setq vals (remove ":ETC" vals))
14186 (org-add-props (car vals) '(org-unrestricted t)))
14187 (if table (mapcar 'list vals) vals)))
14189 (defun org-property-previous-allowed-value (&optional previous)
14190 "Switch to the next allowed value for this property."
14191 (interactive)
14192 (org-property-next-allowed-value t))
14194 (defun org-property-next-allowed-value (&optional previous)
14195 "Switch to the next allowed value for this property."
14196 (interactive)
14197 (unless (org-at-property-p)
14198 (error "Not at a property"))
14199 (let* ((key (match-string 2))
14200 (value (match-string 3))
14201 (allowed (or (org-property-get-allowed-values (point) key)
14202 (and (member value '("[ ]" "[-]" "[X]"))
14203 '("[ ]" "[X]"))))
14204 nval)
14205 (unless allowed
14206 (error "Allowed values for this property have not been defined"))
14207 (if previous (setq allowed (reverse allowed)))
14208 (if (member value allowed)
14209 (setq nval (car (cdr (member value allowed)))))
14210 (setq nval (or nval (car allowed)))
14211 (if (equal nval value)
14212 (error "Only one allowed value for this property"))
14213 (org-at-property-p)
14214 (replace-match (concat " :" key ": " nval) t t)
14215 (org-indent-line-function)
14216 (beginning-of-line 1)
14217 (skip-chars-forward " \t")
14218 (run-hook-with-args 'org-property-changed-functions key nval)))
14220 (defun org-find-olp (path &optional this-buffer)
14221 "Return a marker pointing to the entry at outline path OLP.
14222 If anything goes wrong, throw an error.
14223 You can wrap this call to catch the error like this:
14225 (condition-case msg
14226 (org-mobile-locate-entry (match-string 4))
14227 (error (nth 1 msg)))
14229 The return value will then be either a string with the error message,
14230 or a marker if everything is OK.
14232 If THIS-BUFFER is set, the outline path does not contain a file,
14233 only headings."
14234 (let* ((file (if this-buffer buffer-file-name (pop path)))
14235 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
14236 (level 1)
14237 (lmin 1)
14238 (lmax 1)
14239 limit re end found pos heading cnt flevel)
14240 (unless buffer (error "File not found :%s" file))
14241 (with-current-buffer buffer
14242 (save-excursion
14243 (save-restriction
14244 (widen)
14245 (setq limit (point-max))
14246 (goto-char (point-min))
14247 (while (setq heading (pop path))
14248 (setq re (format org-complex-heading-regexp-format
14249 (regexp-quote heading)))
14250 (setq cnt 0 pos (point))
14251 (while (re-search-forward re end t)
14252 (setq level (- (match-end 1) (match-beginning 1)))
14253 (if (and (>= level lmin) (<= level lmax))
14254 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
14255 (when (= cnt 0) (error "Heading not found on level %d: %s"
14256 lmax heading))
14257 (when (> cnt 1) (error "Heading not unique on level %d: %s"
14258 lmax heading))
14259 (goto-char found)
14260 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
14261 (setq end (save-excursion (org-end-of-subtree t t))))
14262 (when (org-on-heading-p)
14263 (move-marker (make-marker) (point))))))))
14265 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
14266 "Find node HEADING in BUFFER.
14267 Return a marker to the heading if it was found, or nil if not.
14268 If POS-ONLY is set, return just the position instead of a marker.
14270 The heading text must match exact, but it may have a TODO keyword,
14271 a priority cookie and tags in the standard locations."
14272 (with-current-buffer (or buffer (current-buffer))
14273 (save-excursion
14274 (save-restriction
14275 (widen)
14276 (goto-char (point-min))
14277 (let (case-fold-search)
14278 (if (re-search-forward
14279 (format org-complex-heading-regexp-format
14280 (regexp-quote heading)) nil t)
14281 (if pos-only
14282 (match-beginning 0)
14283 (move-marker (make-marker) (match-beginning 0)))))))))
14285 (defun org-find-exact-heading-in-directory (heading &optional dir)
14286 "Find Org node headline HEADING in all .org files in directory DIR.
14287 When the target headline is found, return a marker to this location."
14288 (let ((files (directory-files (or dir default-directory)
14289 nil "\\`[^.#].*\\.org\\'"))
14290 file visiting m buffer)
14291 (catch 'found
14292 (while (setq file (pop files))
14293 (message "trying %s" file)
14294 (setq visiting (org-find-base-buffer-visiting file))
14295 (setq buffer (or visiting (find-file-noselect file)))
14296 (setq m (org-find-exact-headline-in-buffer
14297 heading buffer))
14298 (when (and (not m) (not visiting)) (kill-buffer buffer))
14299 (and m (throw 'found m))))))
14301 (defun org-find-entry-with-id (ident)
14302 "Locate the entry that contains the ID property with exact value IDENT.
14303 IDENT can be a string, a symbol or a number, this function will search for
14304 the string representation of it.
14305 Return the position where this entry starts, or nil if there is no such entry."
14306 (interactive "sID: ")
14307 (let ((id (cond
14308 ((stringp ident) ident)
14309 ((symbol-name ident) (symbol-name ident))
14310 ((numberp ident) (number-to-string ident))
14311 (t (error "IDENT %s must be a string, symbol or number" ident))))
14312 (case-fold-search nil))
14313 (save-excursion
14314 (save-restriction
14315 (widen)
14316 (goto-char (point-min))
14317 (when (re-search-forward
14318 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
14319 nil t)
14320 (org-back-to-heading t)
14321 (point))))))
14323 ;;;; Timestamps
14325 (defvar org-last-changed-timestamp nil)
14326 (defvar org-last-inserted-timestamp nil
14327 "The last time stamp inserted with `org-insert-time-stamp'.")
14328 (defvar org-time-was-given) ; dynamically scoped parameter
14329 (defvar org-end-time-was-given) ; dynamically scoped parameter
14330 (defvar org-ts-what) ; dynamically scoped parameter
14332 (defun org-time-stamp (arg &optional inactive)
14333 "Prompt for a date/time and insert a time stamp.
14334 If the user specifies a time like HH:MM, or if this command is called
14335 with a prefix argument, the time stamp will contain date and time.
14336 Otherwise, only the date will be included. All parts of a date not
14337 specified by the user will be filled in from the current date/time.
14338 So if you press just return without typing anything, the time stamp
14339 will represent the current date/time. If there is already a timestamp
14340 at the cursor, it will be modified."
14341 (interactive "P")
14342 (let* ((ts nil)
14343 (default-time
14344 ;; Default time is either today, or, when entering a range,
14345 ;; the range start.
14346 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
14347 (save-excursion
14348 (re-search-backward
14349 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
14350 (- (point) 20) t)))
14351 (apply 'encode-time (org-parse-time-string (match-string 1)))
14352 (current-time)))
14353 (default-input (and ts (org-get-compact-tod ts)))
14354 org-time-was-given org-end-time-was-given time)
14355 (cond
14356 ((and (org-at-timestamp-p t)
14357 (memq last-command '(org-time-stamp org-time-stamp-inactive))
14358 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
14359 (insert "--")
14360 (setq time (let ((this-command this-command))
14361 (org-read-date arg 'totime nil nil
14362 default-time default-input)))
14363 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
14364 ((org-at-timestamp-p t)
14365 (setq time (let ((this-command this-command))
14366 (org-read-date arg 'totime nil nil default-time default-input)))
14367 (when (org-at-timestamp-p t) ; just to get the match data
14368 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
14369 (replace-match "")
14370 (setq org-last-changed-timestamp
14371 (org-insert-time-stamp
14372 time (or org-time-was-given arg)
14373 inactive nil nil (list org-end-time-was-given))))
14374 (message "Timestamp updated"))
14376 (setq time (let ((this-command this-command))
14377 (org-read-date arg 'totime nil nil default-time default-input)))
14378 (org-insert-time-stamp time (or org-time-was-given arg) inactive
14379 nil nil (list org-end-time-was-given))))))
14381 ;; FIXME: can we use this for something else, like computing time differences?
14382 (defun org-get-compact-tod (s)
14383 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
14384 (let* ((t1 (match-string 1 s))
14385 (h1 (string-to-number (match-string 2 s)))
14386 (m1 (string-to-number (match-string 3 s)))
14387 (t2 (and (match-end 4) (match-string 5 s)))
14388 (h2 (and t2 (string-to-number (match-string 6 s))))
14389 (m2 (and t2 (string-to-number (match-string 7 s))))
14390 dh dm)
14391 (if (not t2)
14393 (setq dh (- h2 h1) dm (- m2 m1))
14394 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
14395 (concat t1 "+" (number-to-string dh)
14396 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
14398 (defun org-time-stamp-inactive (&optional arg)
14399 "Insert an inactive time stamp.
14400 An inactive time stamp is enclosed in square brackets instead of angle
14401 brackets. It is inactive in the sense that it does not trigger agenda entries,
14402 does not link to the calendar and cannot be changed with the S-cursor keys.
14403 So these are more for recording a certain time/date."
14404 (interactive "P")
14405 (org-time-stamp arg 'inactive))
14407 (defvar org-date-ovl (make-overlay 1 1))
14408 (overlay-put org-date-ovl 'face 'org-warning)
14409 (org-detach-overlay org-date-ovl)
14411 (defvar org-ans1) ; dynamically scoped parameter
14412 (defvar org-ans2) ; dynamically scoped parameter
14414 (defvar org-plain-time-of-day-regexp) ; defined below
14416 (defvar org-overriding-default-time nil) ; dynamically scoped
14417 (defvar org-read-date-overlay nil)
14418 (defvar org-dcst nil) ; dynamically scoped
14419 (defvar org-read-date-history nil)
14420 (defvar org-read-date-final-answer nil)
14421 (defvar org-read-date-analyze-futurep nil)
14422 (defvar org-read-date-analyze-forced-year nil)
14424 (defun org-read-date (&optional with-time to-time from-string prompt
14425 default-time default-input)
14426 "Read a date, possibly a time, and make things smooth for the user.
14427 The prompt will suggest to enter an ISO date, but you can also enter anything
14428 which will at least partially be understood by `parse-time-string'.
14429 Unrecognized parts of the date will default to the current day, month, year,
14430 hour and minute. If this command is called to replace a timestamp at point,
14431 of to enter the second timestamp of a range, the default time is taken
14432 from the existing stamp. Furthermore, the command prefers the future,
14433 so if you are giving a date where the year is not given, and the day-month
14434 combination is already past in the current year, it will assume you
14435 mean next year. For details, see the manual. A few examples:
14437 3-2-5 --> 2003-02-05
14438 feb 15 --> currentyear-02-15
14439 2/15 --> currentyear-02-15
14440 sep 12 9 --> 2009-09-12
14441 12:45 --> today 12:45
14442 22 sept 0:34 --> currentyear-09-22 0:34
14443 12 --> currentyear-currentmonth-12
14444 Fri --> nearest Friday (today or later)
14445 etc.
14447 Furthermore you can specify a relative date by giving, as the *first* thing
14448 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
14449 change in days weeks, months, years.
14450 With a single plus or minus, the date is relative to today. With a double
14451 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
14452 +4d --> four days from today
14453 +4 --> same as above
14454 +2w --> two weeks from today
14455 ++5 --> five days from default date
14457 The function understands only English month and weekday abbreviations,
14458 but this can be configured with the variables `parse-time-months' and
14459 `parse-time-weekdays'.
14461 While prompting, a calendar is popped up - you can also select the
14462 date with the mouse (button 1). The calendar shows a period of three
14463 months. To scroll it to other months, use the keys `>' and `<'.
14464 If you don't like the calendar, turn it off with
14465 \(setq org-read-date-popup-calendar nil)
14467 With optional argument TO-TIME, the date will immediately be converted
14468 to an internal time.
14469 With an optional argument WITH-TIME, the prompt will suggest to also
14470 insert a time. Note that when WITH-TIME is not set, you can still
14471 enter a time, and this function will inform the calling routine about
14472 this change. The calling routine may then choose to change the format
14473 used to insert the time stamp into the buffer to include the time.
14474 With optional argument FROM-STRING, read from this string instead from
14475 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
14476 the time/date that is used for everything that is not specified by the
14477 user."
14478 (require 'parse-time)
14479 (let* ((org-time-stamp-rounding-minutes
14480 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
14481 (org-dcst org-display-custom-times)
14482 (ct (org-current-time))
14483 (def (or org-overriding-default-time default-time ct))
14484 (defdecode (decode-time def))
14485 (dummy (progn
14486 (when (< (nth 2 defdecode) org-extend-today-until)
14487 (setcar (nthcdr 2 defdecode) -1)
14488 (setcar (nthcdr 1 defdecode) 59)
14489 (setq def (apply 'encode-time defdecode)
14490 defdecode (decode-time def)))))
14491 (calendar-frame-setup nil)
14492 (calendar-setup nil)
14493 (calendar-move-hook nil)
14494 (calendar-view-diary-initially-flag nil)
14495 (calendar-view-holidays-initially-flag nil)
14496 (timestr (format-time-string
14497 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
14498 (prompt (concat (if prompt (concat prompt " ") "")
14499 (format "Date+time [%s]: " timestr)))
14500 ans (org-ans0 "") org-ans1 org-ans2 final)
14502 (cond
14503 (from-string (setq ans from-string))
14504 (org-read-date-popup-calendar
14505 (save-excursion
14506 (save-window-excursion
14507 (calendar)
14508 (calendar-forward-day (- (time-to-days def)
14509 (calendar-absolute-from-gregorian
14510 (calendar-current-date))))
14511 (org-eval-in-calendar nil t)
14512 (let* ((old-map (current-local-map))
14513 (map (copy-keymap calendar-mode-map))
14514 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
14515 (org-defkey map (kbd "RET") 'org-calendar-select)
14516 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
14517 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
14518 (org-defkey minibuffer-local-map [(meta shift left)]
14519 (lambda () (interactive)
14520 (org-eval-in-calendar '(calendar-backward-month 1))))
14521 (org-defkey minibuffer-local-map [(meta shift right)]
14522 (lambda () (interactive)
14523 (org-eval-in-calendar '(calendar-forward-month 1))))
14524 (org-defkey minibuffer-local-map [(meta shift up)]
14525 (lambda () (interactive)
14526 (org-eval-in-calendar '(calendar-backward-year 1))))
14527 (org-defkey minibuffer-local-map [(meta shift down)]
14528 (lambda () (interactive)
14529 (org-eval-in-calendar '(calendar-forward-year 1))))
14530 (org-defkey minibuffer-local-map [?\e (shift left)]
14531 (lambda () (interactive)
14532 (org-eval-in-calendar '(calendar-backward-month 1))))
14533 (org-defkey minibuffer-local-map [?\e (shift right)]
14534 (lambda () (interactive)
14535 (org-eval-in-calendar '(calendar-forward-month 1))))
14536 (org-defkey minibuffer-local-map [?\e (shift up)]
14537 (lambda () (interactive)
14538 (org-eval-in-calendar '(calendar-backward-year 1))))
14539 (org-defkey minibuffer-local-map [?\e (shift down)]
14540 (lambda () (interactive)
14541 (org-eval-in-calendar '(calendar-forward-year 1))))
14542 (org-defkey minibuffer-local-map [(shift up)]
14543 (lambda () (interactive)
14544 (org-eval-in-calendar '(calendar-backward-week 1))))
14545 (org-defkey minibuffer-local-map [(shift down)]
14546 (lambda () (interactive)
14547 (org-eval-in-calendar '(calendar-forward-week 1))))
14548 (org-defkey minibuffer-local-map [(shift left)]
14549 (lambda () (interactive)
14550 (org-eval-in-calendar '(calendar-backward-day 1))))
14551 (org-defkey minibuffer-local-map [(shift right)]
14552 (lambda () (interactive)
14553 (org-eval-in-calendar '(calendar-forward-day 1))))
14554 (org-defkey minibuffer-local-map ">"
14555 (lambda () (interactive)
14556 (org-eval-in-calendar '(scroll-calendar-left 1))))
14557 (org-defkey minibuffer-local-map "<"
14558 (lambda () (interactive)
14559 (org-eval-in-calendar '(scroll-calendar-right 1))))
14560 (org-defkey minibuffer-local-map "\C-v"
14561 (lambda () (interactive)
14562 (org-eval-in-calendar
14563 '(calendar-scroll-left-three-months 1))))
14564 (org-defkey minibuffer-local-map "\M-v"
14565 (lambda () (interactive)
14566 (org-eval-in-calendar
14567 '(calendar-scroll-right-three-months 1))))
14568 (run-hooks 'org-read-date-minibuffer-setup-hook)
14569 (unwind-protect
14570 (progn
14571 (use-local-map map)
14572 (add-hook 'post-command-hook 'org-read-date-display)
14573 (setq org-ans0 (read-string prompt default-input
14574 'org-read-date-history nil))
14575 ;; org-ans0: from prompt
14576 ;; org-ans1: from mouse click
14577 ;; org-ans2: from calendar motion
14578 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
14579 (remove-hook 'post-command-hook 'org-read-date-display)
14580 (use-local-map old-map)
14581 (when org-read-date-overlay
14582 (delete-overlay org-read-date-overlay)
14583 (setq org-read-date-overlay nil)))))))
14585 (t ; Naked prompt only
14586 (unwind-protect
14587 (setq ans (read-string prompt default-input
14588 'org-read-date-history timestr))
14589 (when org-read-date-overlay
14590 (delete-overlay org-read-date-overlay)
14591 (setq org-read-date-overlay nil)))))
14593 (setq final (org-read-date-analyze ans def defdecode))
14595 (when org-read-date-analyze-forced-year
14596 (message "Year was forced into %s"
14597 (if org-read-date-force-compatible-dates
14598 "compatible range (1970-2037)"
14599 "range representable on this machine"))
14600 (ding))
14602 ;; One round trip to get rid of 34th of August and stuff like that....
14603 (setq final (decode-time (apply 'encode-time final)))
14605 (setq org-read-date-final-answer ans)
14607 (if to-time
14608 (apply 'encode-time final)
14609 (if (and (boundp 'org-time-was-given) org-time-was-given)
14610 (format "%04d-%02d-%02d %02d:%02d"
14611 (nth 5 final) (nth 4 final) (nth 3 final)
14612 (nth 2 final) (nth 1 final))
14613 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
14615 (defvar def)
14616 (defvar defdecode)
14617 (defvar with-time)
14618 (defun org-read-date-display ()
14619 "Display the current date prompt interpretation in the minibuffer."
14620 (when org-read-date-display-live
14621 (when org-read-date-overlay
14622 (delete-overlay org-read-date-overlay))
14623 (let ((p (point)))
14624 (end-of-line 1)
14625 (while (not (equal (buffer-substring
14626 (max (point-min) (- (point) 4)) (point))
14627 " "))
14628 (insert " "))
14629 (goto-char p))
14630 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
14631 " " (or org-ans1 org-ans2)))
14632 (org-end-time-was-given nil)
14633 (f (org-read-date-analyze ans def defdecode))
14634 (fmts (if org-dcst
14635 org-time-stamp-custom-formats
14636 org-time-stamp-formats))
14637 (fmt (if (or with-time
14638 (and (boundp 'org-time-was-given) org-time-was-given))
14639 (cdr fmts)
14640 (car fmts)))
14641 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
14642 (when (and org-end-time-was-given
14643 (string-match org-plain-time-of-day-regexp txt))
14644 (setq txt (concat (substring txt 0 (match-end 0)) "-"
14645 org-end-time-was-given
14646 (substring txt (match-end 0)))))
14647 (when org-read-date-analyze-futurep
14648 (setq txt (concat txt " (=>F)")))
14649 (setq org-read-date-overlay
14650 (make-overlay (1- (point-at-eol)) (point-at-eol)))
14651 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
14653 (defun org-read-date-analyze (ans def defdecode)
14654 "Analyze the combined answer of the date prompt."
14655 ;; FIXME: cleanup and comment
14656 (let ((nowdecode (decode-time (current-time)))
14657 delta deltan deltaw deltadef year month day
14658 hour minute second wday pm h2 m2 tl wday1
14659 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
14660 (setq org-read-date-analyze-futurep nil
14661 org-read-date-analyze-forced-year nil)
14662 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
14663 (setq ans "+0"))
14665 (when (setq delta (org-read-date-get-relative ans (current-time) def))
14666 (setq ans (replace-match "" t t ans)
14667 deltan (car delta)
14668 deltaw (nth 1 delta)
14669 deltadef (nth 2 delta)))
14671 ;; Check if there is an iso week date in there
14672 ;; If yes, store the info and postpone interpreting it until the rest
14673 ;; of the parsing is done
14674 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
14675 (setq iso-year (if (match-end 1)
14676 (org-small-year-to-year
14677 (string-to-number (match-string 1 ans))))
14678 iso-weekday (if (match-end 3)
14679 (string-to-number (match-string 3 ans)))
14680 iso-week (string-to-number (match-string 2 ans)))
14681 (setq ans (replace-match "" t t ans)))
14683 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
14684 (when (string-match
14685 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
14686 (setq year (if (match-end 2)
14687 (string-to-number (match-string 2 ans))
14688 (progn (setq kill-year t)
14689 (string-to-number (format-time-string "%Y"))))
14690 month (string-to-number (match-string 3 ans))
14691 day (string-to-number (match-string 4 ans)))
14692 (if (< year 100) (setq year (+ 2000 year)))
14693 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
14694 t nil ans)))
14695 ;; Help matching american dates, like 5/30 or 5/30/7
14696 (when (string-match
14697 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
14698 (setq year (if (match-end 4)
14699 (string-to-number (match-string 4 ans))
14700 (progn (setq kill-year t)
14701 (string-to-number (format-time-string "%Y"))))
14702 month (string-to-number (match-string 1 ans))
14703 day (string-to-number (match-string 2 ans)))
14704 (if (< year 100) (setq year (+ 2000 year)))
14705 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
14706 t nil ans)))
14707 ;; Help matching am/pm times, because `parse-time-string' does not do that.
14708 ;; If there is a time with am/pm, and *no* time without it, we convert
14709 ;; so that matching will be successful.
14710 (loop for i from 1 to 2 do ; twice, for end time as well
14711 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
14712 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
14713 (setq hour (string-to-number (match-string 1 ans))
14714 minute (if (match-end 3)
14715 (string-to-number (match-string 3 ans))
14717 pm (equal ?p
14718 (string-to-char (downcase (match-string 4 ans)))))
14719 (if (and (= hour 12) (not pm))
14720 (setq hour 0)
14721 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
14722 (setq ans (replace-match (format "%02d:%02d" hour minute)
14723 t t ans))))
14725 ;; Check if a time range is given as a duration
14726 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
14727 (setq hour (string-to-number (match-string 1 ans))
14728 h2 (+ hour (string-to-number (match-string 3 ans)))
14729 minute (string-to-number (match-string 2 ans))
14730 m2 (+ minute (if (match-end 5) (string-to-number
14731 (match-string 5 ans))0)))
14732 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
14733 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
14734 t t ans)))
14736 ;; Check if there is a time range
14737 (when (boundp 'org-end-time-was-given)
14738 (setq org-time-was-given nil)
14739 (when (and (string-match org-plain-time-of-day-regexp ans)
14740 (match-end 8))
14741 (setq org-end-time-was-given (match-string 8 ans))
14742 (setq ans (concat (substring ans 0 (match-beginning 7))
14743 (substring ans (match-end 7))))))
14745 (setq tl (parse-time-string ans)
14746 day (or (nth 3 tl) (nth 3 defdecode))
14747 month (or (nth 4 tl)
14748 (if (and org-read-date-prefer-future
14749 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
14750 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
14751 (nth 4 defdecode)))
14752 year (or (and (not kill-year) (nth 5 tl))
14753 (if (and org-read-date-prefer-future
14754 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
14755 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
14756 (nth 5 defdecode)))
14757 hour (or (nth 2 tl) (nth 2 defdecode))
14758 minute (or (nth 1 tl) (nth 1 defdecode))
14759 second (or (nth 0 tl) 0)
14760 wday (nth 6 tl))
14762 (when (and (eq org-read-date-prefer-future 'time)
14763 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
14764 (equal day (nth 3 nowdecode))
14765 (equal month (nth 4 nowdecode))
14766 (equal year (nth 5 nowdecode))
14767 (nth 2 tl)
14768 (or (< (nth 2 tl) (nth 2 nowdecode))
14769 (and (= (nth 2 tl) (nth 2 nowdecode))
14770 (nth 1 tl)
14771 (< (nth 1 tl) (nth 1 nowdecode)))))
14772 (setq day (1+ day)
14773 futurep t))
14775 ;; Special date definitions below
14776 (cond
14777 (iso-week
14778 ;; There was an iso week
14779 (require 'cal-iso)
14780 (setq futurep nil)
14781 (setq year (or iso-year year)
14782 day (or iso-weekday wday 1)
14783 wday nil ; to make sure that the trigger below does not match
14784 iso-date (calendar-gregorian-from-absolute
14785 (calendar-absolute-from-iso
14786 (list iso-week day year))))
14787 ; FIXME: Should we also push ISO weeks into the future?
14788 ; (when (and org-read-date-prefer-future
14789 ; (not iso-year)
14790 ; (< (calendar-absolute-from-gregorian iso-date)
14791 ; (time-to-days (current-time))))
14792 ; (setq year (1+ year)
14793 ; iso-date (calendar-gregorian-from-absolute
14794 ; (calendar-absolute-from-iso
14795 ; (list iso-week day year)))))
14796 (setq month (car iso-date)
14797 year (nth 2 iso-date)
14798 day (nth 1 iso-date)))
14799 (deltan
14800 (setq futurep nil)
14801 (unless deltadef
14802 (let ((now (decode-time (current-time))))
14803 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
14804 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
14805 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
14806 ((equal deltaw "m") (setq month (+ month deltan)))
14807 ((equal deltaw "y") (setq year (+ year deltan)))))
14808 ((and wday (not (nth 3 tl)))
14809 (setq futurep nil)
14810 ;; Weekday was given, but no day, so pick that day in the week
14811 ;; on or after the derived date.
14812 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
14813 (unless (equal wday wday1)
14814 (setq day (+ day (% (- wday wday1 -7) 7))))))
14815 (if (and (boundp 'org-time-was-given)
14816 (nth 2 tl))
14817 (setq org-time-was-given t))
14818 (if (< year 100) (setq year (+ 2000 year)))
14819 ;; Check of the date is representable
14820 (if org-read-date-force-compatible-dates
14821 (progn
14822 (if (< year 1970)
14823 (setq year 1970 org-read-date-analyze-forced-year t))
14824 (if (> year 2037)
14825 (setq year 2037 org-read-date-analyze-forced-year t)))
14826 (condition-case nil
14827 (encode-time second minute hour day month year)
14828 (error
14829 (setq year (nth 5 defdecode))
14830 (setq org-read-date-analyze-forced-year t))))
14831 (setq org-read-date-analyze-futurep futurep)
14832 (list second minute hour day month year)))
14834 (defvar parse-time-weekdays)
14836 (defun org-read-date-get-relative (s today default)
14837 "Check string S for special relative date string.
14838 TODAY and DEFAULT are internal times, for today and for a default.
14839 Return shift list (N what def-flag)
14840 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
14841 N is the number of WHATs to shift.
14842 DEF-FLAG is t when a double ++ or -- indicates shift relative to
14843 the DEFAULT date rather than TODAY."
14844 (when (and
14845 (string-match
14846 (concat
14847 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
14848 "\\([0-9]+\\)?"
14849 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
14850 "\\([ \t]\\|$\\)") s)
14851 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
14852 (let* ((dir (if (> (match-end 1) (match-beginning 1))
14853 (string-to-char (substring (match-string 1 s) -1))
14854 ?+))
14855 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
14856 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
14857 (what (if (match-end 3) (match-string 3 s) "d"))
14858 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
14859 (date (if rel default today))
14860 (wday (nth 6 (decode-time date)))
14861 delta)
14862 (if wday1
14863 (progn
14864 (setq delta (mod (+ 7 (- wday1 wday)) 7))
14865 (if (= dir ?-) (setq delta (- delta 7)))
14866 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
14867 (list delta "d" rel))
14868 (list (* n (if (= dir ?-) -1 1)) what rel)))))
14870 (defun org-order-calendar-date-args (arg1 arg2 arg3)
14871 "Turn a user-specified date into the internal representation.
14872 The internal representation needed by the calendar is (month day year).
14873 This is a wrapper to handle the brain-dead convention in calendar that
14874 user function argument order change dependent on argument order."
14875 (if (boundp 'calendar-date-style)
14876 (cond
14877 ((eq calendar-date-style 'american)
14878 (list arg1 arg2 arg3))
14879 ((eq calendar-date-style 'european)
14880 (list arg2 arg1 arg3))
14881 ((eq calendar-date-style 'iso)
14882 (list arg2 arg3 arg1)))
14883 (with-no-warnings ;; european-calendar-style is obsolete as of version 23.1
14884 (if (org-bound-and-true-p european-calendar-style)
14885 (list arg2 arg1 arg3)
14886 (list arg1 arg2 arg3)))))
14888 (defun org-eval-in-calendar (form &optional keepdate)
14889 "Eval FORM in the calendar window and return to current window.
14890 Also, store the cursor date in variable org-ans2."
14891 (let ((sf (selected-frame))
14892 (sw (selected-window)))
14893 (select-window (get-buffer-window "*Calendar*" t))
14894 (eval form)
14895 (when (and (not keepdate) (calendar-cursor-to-date))
14896 (let* ((date (calendar-cursor-to-date))
14897 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
14898 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
14899 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
14900 (select-window sw)
14901 (org-select-frame-set-input-focus sf)))
14903 (defun org-calendar-select ()
14904 "Return to `org-read-date' with the date currently selected.
14905 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
14906 (interactive)
14907 (when (calendar-cursor-to-date)
14908 (let* ((date (calendar-cursor-to-date))
14909 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
14910 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
14911 (if (active-minibuffer-window) (exit-minibuffer))))
14913 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
14914 "Insert a date stamp for the date given by the internal TIME.
14915 WITH-HM means use the stamp format that includes the time of the day.
14916 INACTIVE means use square brackets instead of angular ones, so that the
14917 stamp will not contribute to the agenda.
14918 PRE and POST are optional strings to be inserted before and after the
14919 stamp.
14920 The command returns the inserted time stamp."
14921 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
14922 stamp)
14923 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
14924 (insert-before-markers (or pre ""))
14925 (when (listp extra)
14926 (setq extra (car extra))
14927 (if (and (stringp extra)
14928 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
14929 (setq extra (format "-%02d:%02d"
14930 (string-to-number (match-string 1 extra))
14931 (string-to-number (match-string 2 extra))))
14932 (setq extra nil)))
14933 (when extra
14934 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
14935 (insert-before-markers (setq stamp (format-time-string fmt time)))
14936 (insert-before-markers (or post ""))
14937 (setq org-last-inserted-timestamp stamp)))
14939 (defun org-toggle-time-stamp-overlays ()
14940 "Toggle the use of custom time stamp formats."
14941 (interactive)
14942 (setq org-display-custom-times (not org-display-custom-times))
14943 (unless org-display-custom-times
14944 (let ((p (point-min)) (bmp (buffer-modified-p)))
14945 (while (setq p (next-single-property-change p 'display))
14946 (if (and (get-text-property p 'display)
14947 (eq (get-text-property p 'face) 'org-date))
14948 (remove-text-properties
14949 p (setq p (next-single-property-change p 'display))
14950 '(display t))))
14951 (set-buffer-modified-p bmp)))
14952 (if (featurep 'xemacs)
14953 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
14954 (org-restart-font-lock)
14955 (setq org-table-may-need-update t)
14956 (if org-display-custom-times
14957 (message "Time stamps are overlayed with custom format")
14958 (message "Time stamp overlays removed")))
14960 (defun org-display-custom-time (beg end)
14961 "Overlay modified time stamp format over timestamp between BEG and END."
14962 (let* ((ts (buffer-substring beg end))
14963 t1 w1 with-hm tf time str w2 (off 0))
14964 (save-match-data
14965 (setq t1 (org-parse-time-string ts t))
14966 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)?\\'" ts)
14967 (setq off (- (match-end 0) (match-beginning 0)))))
14968 (setq end (- end off))
14969 (setq w1 (- end beg)
14970 with-hm (and (nth 1 t1) (nth 2 t1))
14971 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
14972 time (org-fix-decoded-time t1)
14973 str (org-add-props
14974 (format-time-string
14975 (substring tf 1 -1) (apply 'encode-time time))
14976 nil 'mouse-face 'highlight)
14977 w2 (length str))
14978 (if (not (= w2 w1))
14979 (add-text-properties (1+ beg) (+ 2 beg)
14980 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
14981 (if (featurep 'xemacs)
14982 (progn
14983 (put-text-property beg end 'invisible t)
14984 (put-text-property beg end 'end-glyph (make-glyph str)))
14985 (put-text-property beg end 'display str))))
14987 (defun org-translate-time (string)
14988 "Translate all timestamps in STRING to custom format.
14989 But do this only if the variable `org-display-custom-times' is set."
14990 (when org-display-custom-times
14991 (save-match-data
14992 (let* ((start 0)
14993 (re org-ts-regexp-both)
14994 t1 with-hm inactive tf time str beg end)
14995 (while (setq start (string-match re string start))
14996 (setq beg (match-beginning 0)
14997 end (match-end 0)
14998 t1 (save-match-data
14999 (org-parse-time-string (substring string beg end) t))
15000 with-hm (and (nth 1 t1) (nth 2 t1))
15001 inactive (equal (substring string beg (1+ beg)) "[")
15002 tf (funcall (if with-hm 'cdr 'car)
15003 org-time-stamp-custom-formats)
15004 time (org-fix-decoded-time t1)
15005 str (format-time-string
15006 (concat
15007 (if inactive "[" "<") (substring tf 1 -1)
15008 (if inactive "]" ">"))
15009 (apply 'encode-time time))
15010 string (replace-match str t t string)
15011 start (+ start (length str)))))))
15012 string)
15014 (defun org-fix-decoded-time (time)
15015 "Set 0 instead of nil for the first 6 elements of time.
15016 Don't touch the rest."
15017 (let ((n 0))
15018 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
15020 (defun org-days-to-time (timestamp-string)
15021 "Difference between TIMESTAMP-STRING and now in days."
15022 (- (time-to-days (org-time-string-to-time timestamp-string))
15023 (time-to-days (current-time))))
15025 (defun org-deadline-close (timestamp-string &optional ndays)
15026 "Is the time in TIMESTAMP-STRING close to the current date?"
15027 (setq ndays (or ndays (org-get-wdays timestamp-string)))
15028 (and (< (org-days-to-time timestamp-string) ndays)
15029 (not (org-entry-is-done-p))))
15031 (defun org-get-wdays (ts)
15032 "Get the deadline lead time appropriate for timestring TS."
15033 (cond
15034 ((<= org-deadline-warning-days 0)
15035 ;; 0 or negative, enforce this value no matter what
15036 (- org-deadline-warning-days))
15037 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\| \\)" ts)
15038 ;; lead time is specified.
15039 (floor (* (string-to-number (match-string 1 ts))
15040 (cdr (assoc (match-string 2 ts)
15041 '(("d" . 1) ("w" . 7)
15042 ("m" . 30.4) ("y" . 365.25)))))))
15043 ;; go for the default.
15044 (t org-deadline-warning-days)))
15046 (defun org-calendar-select-mouse (ev)
15047 "Return to `org-read-date' with the date currently selected.
15048 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15049 (interactive "e")
15050 (mouse-set-point ev)
15051 (when (calendar-cursor-to-date)
15052 (let* ((date (calendar-cursor-to-date))
15053 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15054 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15055 (if (active-minibuffer-window) (exit-minibuffer))))
15057 (defun org-check-deadlines (ndays)
15058 "Check if there are any deadlines due or past due.
15059 A deadline is considered due if it happens within `org-deadline-warning-days'
15060 days from today's date. If the deadline appears in an entry marked DONE,
15061 it is not shown. The prefix arg NDAYS can be used to test that many
15062 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
15063 (interactive "P")
15064 (let* ((org-warn-days
15065 (cond
15066 ((equal ndays '(4)) 100000)
15067 (ndays (prefix-numeric-value ndays))
15068 (t (abs org-deadline-warning-days))))
15069 (case-fold-search nil)
15070 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
15071 (callback
15072 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
15074 (message "%d deadlines past-due or due within %d days"
15075 (org-occur regexp nil callback)
15076 org-warn-days)))
15078 (defun org-check-before-date (date)
15079 "Check if there are deadlines or scheduled entries before DATE."
15080 (interactive (list (org-read-date)))
15081 (let ((case-fold-search nil)
15082 (regexp (concat "\\<\\(" org-deadline-string
15083 "\\|" org-scheduled-string
15084 "\\) *<\\([^>]+\\)>"))
15085 (callback
15086 (lambda () (time-less-p
15087 (org-time-string-to-time (match-string 2))
15088 (org-time-string-to-time date)))))
15089 (message "%d entries before %s"
15090 (org-occur regexp nil callback) date)))
15092 (defun org-check-after-date (date)
15093 "Check if there are deadlines or scheduled entries after DATE."
15094 (interactive (list (org-read-date)))
15095 (let ((case-fold-search nil)
15096 (regexp (concat "\\<\\(" org-deadline-string
15097 "\\|" org-scheduled-string
15098 "\\) *<\\([^>]+\\)>"))
15099 (callback
15100 (lambda () (not
15101 (time-less-p
15102 (org-time-string-to-time (match-string 2))
15103 (org-time-string-to-time date))))))
15104 (message "%d entries after %s"
15105 (org-occur regexp nil callback) date)))
15107 (defun org-evaluate-time-range (&optional to-buffer)
15108 "Evaluate a time range by computing the difference between start and end.
15109 Normally the result is just printed in the echo area, but with prefix arg
15110 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
15111 If the time range is actually in a table, the result is inserted into the
15112 next column.
15113 For time difference computation, a year is assumed to be exactly 365
15114 days in order to avoid rounding problems."
15115 (interactive "P")
15117 (org-clock-update-time-maybe)
15118 (save-excursion
15119 (unless (org-at-date-range-p t)
15120 (goto-char (point-at-bol))
15121 (re-search-forward org-tr-regexp-both (point-at-eol) t))
15122 (if (not (org-at-date-range-p t))
15123 (error "Not at a time-stamp range, and none found in current line")))
15124 (let* ((ts1 (match-string 1))
15125 (ts2 (match-string 2))
15126 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
15127 (match-end (match-end 0))
15128 (time1 (org-time-string-to-time ts1))
15129 (time2 (org-time-string-to-time ts2))
15130 (t1 (org-float-time time1))
15131 (t2 (org-float-time time2))
15132 (diff (abs (- t2 t1)))
15133 (negative (< (- t2 t1) 0))
15134 ;; (ys (floor (* 365 24 60 60)))
15135 (ds (* 24 60 60))
15136 (hs (* 60 60))
15137 (fy "%dy %dd %02d:%02d")
15138 (fy1 "%dy %dd")
15139 (fd "%dd %02d:%02d")
15140 (fd1 "%dd")
15141 (fh "%02d:%02d")
15142 y d h m align)
15143 (if havetime
15144 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
15146 d (floor (/ diff ds)) diff (mod diff ds)
15147 h (floor (/ diff hs)) diff (mod diff hs)
15148 m (floor (/ diff 60)))
15149 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
15151 d (floor (+ (/ diff ds) 0.5))
15152 h 0 m 0))
15153 (if (not to-buffer)
15154 (message "%s" (org-make-tdiff-string y d h m))
15155 (if (org-at-table-p)
15156 (progn
15157 (goto-char match-end)
15158 (setq align t)
15159 (and (looking-at " *|") (goto-char (match-end 0))))
15160 (goto-char match-end))
15161 (if (looking-at
15162 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
15163 (replace-match ""))
15164 (if negative (insert " -"))
15165 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
15166 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
15167 (insert " " (format fh h m))))
15168 (if align (org-table-align))
15169 (message "Time difference inserted")))))
15171 (defun org-make-tdiff-string (y d h m)
15172 (let ((fmt "")
15173 (l nil))
15174 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
15175 l (push y l)))
15176 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
15177 l (push d l)))
15178 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
15179 l (push h l)))
15180 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
15181 l (push m l)))
15182 (apply 'format fmt (nreverse l))))
15184 (defun org-time-string-to-time (s)
15185 (apply 'encode-time (org-parse-time-string s)))
15186 (defun org-time-string-to-seconds (s)
15187 (org-float-time (org-time-string-to-time s)))
15189 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
15190 "Convert a time stamp to an absolute day number.
15191 If there is a specifier for a cyclic time stamp, get the closest date to
15192 DAYNR.
15193 PREFER and SHOW-ALL are passed through to `org-closest-date'.
15194 The variable date is bound by the calendar when this is called."
15195 (cond
15196 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
15197 (if (org-diary-sexp-entry (match-string 1 s) "" date)
15198 daynr
15199 (+ daynr 1000)))
15200 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
15201 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
15202 (time-to-days (current-time))) (match-string 0 s)
15203 prefer show-all))
15204 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
15206 (defun org-days-to-iso-week (days)
15207 "Return the iso week number."
15208 (require 'cal-iso)
15209 (car (calendar-iso-from-absolute days)))
15211 (defun org-small-year-to-year (year)
15212 "Convert 2-digit years into 4-digit years.
15213 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
15214 The year 2000 cannot be abbreviated. Any year larger than 99
15215 is returned unchanged."
15216 (if (< year 38)
15217 (setq year (+ 2000 year))
15218 (if (< year 100)
15219 (setq year (+ 1900 year))))
15220 year)
15222 (defun org-time-from-absolute (d)
15223 "Return the time corresponding to date D.
15224 D may be an absolute day number, or a calendar-type list (month day year)."
15225 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
15226 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
15228 (defun org-calendar-holiday ()
15229 "List of holidays, for Diary display in Org-mode."
15230 (require 'holidays)
15231 (let ((hl (funcall
15232 (if (fboundp 'calendar-check-holidays)
15233 'calendar-check-holidays 'check-calendar-holidays) date)))
15234 (if hl (mapconcat 'identity hl "; "))))
15236 (defun org-diary-sexp-entry (sexp entry date)
15237 "Process a SEXP diary ENTRY for DATE."
15238 (require 'diary-lib)
15239 (let ((result (if calendar-debug-sexp
15240 (let ((stack-trace-on-error t))
15241 (eval (car (read-from-string sexp))))
15242 (condition-case nil
15243 (eval (car (read-from-string sexp)))
15244 (error
15245 (beep)
15246 (message "Bad sexp at line %d in %s: %s"
15247 (org-current-line)
15248 (buffer-file-name) sexp)
15249 (sleep-for 2))))))
15250 (cond ((stringp result) (split-string result "; "))
15251 ((and (consp result)
15252 (not (consp (cdr result)))
15253 (stringp (cdr result))) (cdr result))
15254 ((and (consp result)
15255 (stringp (car result))) result)
15256 (result entry)
15257 (t nil))))
15259 (defun org-diary-to-ical-string (frombuf)
15260 "Get iCalendar entries from diary entries in buffer FROMBUF.
15261 This uses the icalendar.el library."
15262 (let* ((tmpdir (if (featurep 'xemacs)
15263 (temp-directory)
15264 temporary-file-directory))
15265 (tmpfile (make-temp-name
15266 (expand-file-name "orgics" tmpdir)))
15267 buf rtn b e)
15268 (with-current-buffer frombuf
15269 (icalendar-export-region (point-min) (point-max) tmpfile)
15270 (setq buf (find-buffer-visiting tmpfile))
15271 (set-buffer buf)
15272 (goto-char (point-min))
15273 (if (re-search-forward "^BEGIN:VEVENT" nil t)
15274 (setq b (match-beginning 0)))
15275 (goto-char (point-max))
15276 (if (re-search-backward "^END:VEVENT" nil t)
15277 (setq e (match-end 0)))
15278 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
15279 (kill-buffer buf)
15280 (delete-file tmpfile)
15281 rtn))
15283 (defun org-closest-date (start current change prefer show-all)
15284 "Find the date closest to CURRENT that is consistent with START and CHANGE.
15285 When PREFER is `past', return a date that is either CURRENT or past.
15286 When PREFER is `future', return a date that is either CURRENT or future.
15287 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
15288 ;; Make the proper lists from the dates
15289 (catch 'exit
15290 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
15291 dn dw sday cday n1 n2 n0
15292 d m y y1 y2 date1 date2 nmonths nm ny m2)
15294 (setq start (org-date-to-gregorian start)
15295 current (org-date-to-gregorian
15296 (if show-all
15297 current
15298 (time-to-days (current-time))))
15299 sday (calendar-absolute-from-gregorian start)
15300 cday (calendar-absolute-from-gregorian current))
15302 (if (<= cday sday) (throw 'exit sday))
15304 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
15305 (setq dn (string-to-number (match-string 1 change))
15306 dw (cdr (assoc (match-string 2 change) a1)))
15307 (error "Invalid change specifier: %s" change))
15308 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
15309 (cond
15310 ((eq dw 'day)
15311 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
15312 n2 (+ n1 dn)))
15313 ((eq dw 'year)
15314 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
15315 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
15316 (setq date1 (list m d y1)
15317 n1 (calendar-absolute-from-gregorian date1)
15318 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
15319 n2 (calendar-absolute-from-gregorian date2)))
15320 ((eq dw 'month)
15321 ;; approx number of month between the two dates
15322 (setq nmonths (floor (/ (- cday sday) 30.436875)))
15323 ;; How often does dn fit in there?
15324 (setq d (nth 1 start) m (car start) y (nth 2 start)
15325 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
15326 m (+ m nm)
15327 ny (floor (/ m 12))
15328 y (+ y ny)
15329 m (- m (* ny 12)))
15330 (while (> m 12) (setq m (- m 12) y (1+ y)))
15331 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
15332 (setq m2 (+ m dn) y2 y)
15333 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
15334 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
15335 (while (<= n2 cday)
15336 (setq n1 n2 m m2 y y2)
15337 (setq m2 (+ m dn) y2 y)
15338 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
15339 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
15340 ;; Make sure n1 is the earlier date
15341 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
15342 (if show-all
15343 (cond
15344 ((eq prefer 'past) (if (= cday n2) n2 n1))
15345 ((eq prefer 'future) (if (= cday n1) n1 n2))
15346 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
15347 (cond
15348 ((eq prefer 'past) (if (= cday n2) n2 n1))
15349 ((eq prefer 'future) (if (= cday n1) n1 n2))
15350 (t (if (= cday n1) n1 n2)))))))
15352 (defun org-date-to-gregorian (date)
15353 "Turn any specification of DATE into a Gregorian date for the calendar."
15354 (cond ((integerp date) (calendar-gregorian-from-absolute date))
15355 ((and (listp date) (= (length date) 3)) date)
15356 ((stringp date)
15357 (setq date (org-parse-time-string date))
15358 (list (nth 4 date) (nth 3 date) (nth 5 date)))
15359 ((listp date)
15360 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
15362 (defun org-parse-time-string (s &optional nodefault)
15363 "Parse the standard Org-mode time string.
15364 This should be a lot faster than the normal `parse-time-string'.
15365 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
15366 hour and minute fields will be nil if not given."
15367 (if (string-match org-ts-regexp0 s)
15368 (list 0
15369 (if (or (match-beginning 8) (not nodefault))
15370 (string-to-number (or (match-string 8 s) "0")))
15371 (if (or (match-beginning 7) (not nodefault))
15372 (string-to-number (or (match-string 7 s) "0")))
15373 (string-to-number (match-string 4 s))
15374 (string-to-number (match-string 3 s))
15375 (string-to-number (match-string 2 s))
15376 nil nil nil)
15377 (error "Not a standard Org-mode time string: %s" s)))
15379 (defun org-timestamp-up (&optional arg)
15380 "Increase the date item at the cursor by one.
15381 If the cursor is on the year, change the year. If it is on the month or
15382 the day, change that.
15383 With prefix ARG, change by that many units."
15384 (interactive "p")
15385 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
15387 (defun org-timestamp-down (&optional arg)
15388 "Decrease the date item at the cursor by one.
15389 If the cursor is on the year, change the year. If it is on the month or
15390 the day, change that.
15391 With prefix ARG, change by that many units."
15392 (interactive "p")
15393 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
15395 (defun org-timestamp-up-day (&optional arg)
15396 "Increase the date in the time stamp by one day.
15397 With prefix ARG, change that many days."
15398 (interactive "p")
15399 (if (and (not (org-at-timestamp-p t))
15400 (org-on-heading-p))
15401 (org-todo 'up)
15402 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
15404 (defun org-timestamp-down-day (&optional arg)
15405 "Decrease the date in the time stamp by one day.
15406 With prefix ARG, change that many days."
15407 (interactive "p")
15408 (if (and (not (org-at-timestamp-p t))
15409 (org-on-heading-p))
15410 (org-todo 'down)
15411 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
15413 (defun org-at-timestamp-p (&optional inactive-ok)
15414 "Determine if the cursor is in or at a timestamp."
15415 (interactive)
15416 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
15417 (pos (point))
15418 (ans (or (looking-at tsr)
15419 (save-excursion
15420 (skip-chars-backward "^[<\n\r\t")
15421 (if (> (point) (point-min)) (backward-char 1))
15422 (and (looking-at tsr)
15423 (> (- (match-end 0) pos) -1))))))
15424 (and ans
15425 (boundp 'org-ts-what)
15426 (setq org-ts-what
15427 (cond
15428 ((= pos (match-beginning 0)) 'bracket)
15429 ((= pos (1- (match-end 0))) 'bracket)
15430 ((org-pos-in-match-range pos 2) 'year)
15431 ((org-pos-in-match-range pos 3) 'month)
15432 ((org-pos-in-match-range pos 7) 'hour)
15433 ((org-pos-in-match-range pos 8) 'minute)
15434 ((or (org-pos-in-match-range pos 4)
15435 (org-pos-in-match-range pos 5)) 'day)
15436 ((and (> pos (or (match-end 8) (match-end 5)))
15437 (< pos (match-end 0)))
15438 (- pos (or (match-end 8) (match-end 5))))
15439 (t 'day))))
15440 ans))
15442 (defun org-toggle-timestamp-type ()
15443 "Toggle the type (<active> or [inactive]) of a time stamp."
15444 (interactive)
15445 (when (org-at-timestamp-p t)
15446 (let ((beg (match-beginning 0)) (end (match-end 0))
15447 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
15448 (save-excursion
15449 (goto-char beg)
15450 (while (re-search-forward "[][<>]" end t)
15451 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
15452 t t)))
15453 (message "Timestamp is now %sactive"
15454 (if (equal (char-after beg) ?<) "" "in")))))
15456 (defun org-timestamp-change (n &optional what updown)
15457 "Change the date in the time stamp at point.
15458 The date will be changed by N times WHAT. WHAT can be `day', `month',
15459 `year', `minute', `second'. If WHAT is not given, the cursor position
15460 in the timestamp determines what will be changed."
15461 (let ((pos (point))
15462 with-hm inactive
15463 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
15464 org-ts-what
15465 extra rem
15466 ts time time0)
15467 (if (not (org-at-timestamp-p t))
15468 (error "Not at a timestamp"))
15469 (if (and (not what) (eq org-ts-what 'bracket))
15470 (org-toggle-timestamp-type)
15471 (if (and (not what) (not (eq org-ts-what 'day))
15472 org-display-custom-times
15473 (get-text-property (point) 'display)
15474 (not (get-text-property (1- (point)) 'display)))
15475 (setq org-ts-what 'day))
15476 (setq org-ts-what (or what org-ts-what)
15477 inactive (= (char-after (match-beginning 0)) ?\[)
15478 ts (match-string 0))
15479 (replace-match "")
15480 (if (string-match
15481 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)*\\)[]>]"
15483 (setq extra (match-string 1 ts)))
15484 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
15485 (setq with-hm t))
15486 (setq time0 (org-parse-time-string ts))
15487 (when (and updown
15488 (eq org-ts-what 'minute)
15489 (not current-prefix-arg))
15490 ;; This looks like s-up and s-down. Change by one rounding step.
15491 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
15492 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
15493 (setcar (cdr time0) (+ (nth 1 time0)
15494 (if (> n 0) (- rem) (- dm rem))))))
15495 (setq time
15496 (encode-time (or (car time0) 0)
15497 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
15498 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
15499 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
15500 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
15501 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
15502 (nthcdr 6 time0)))
15503 (when (and (member org-ts-what '(hour minute))
15504 extra
15505 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
15506 (setq extra (org-modify-ts-extra
15507 extra
15508 (if (eq org-ts-what 'hour) 2 5)
15509 n dm)))
15510 (when (integerp org-ts-what)
15511 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
15512 (if (eq what 'calendar)
15513 (let ((cal-date (org-get-date-from-calendar)))
15514 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
15515 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
15516 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
15517 (setcar time0 (or (car time0) 0))
15518 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
15519 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
15520 (setq time (apply 'encode-time time0))))
15521 (setq org-last-changed-timestamp
15522 (org-insert-time-stamp time with-hm inactive nil nil extra))
15523 (org-clock-update-time-maybe)
15524 (goto-char pos)
15525 ;; Try to recenter the calendar window, if any
15526 (if (and org-calendar-follow-timestamp-change
15527 (get-buffer-window "*Calendar*" t)
15528 (memq org-ts-what '(day month year)))
15529 (org-recenter-calendar (time-to-days time))))))
15531 (defun org-modify-ts-extra (s pos n dm)
15532 "Change the different parts of the lead-time and repeat fields in timestamp."
15533 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
15534 ng h m new rem)
15535 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
15536 (cond
15537 ((or (org-pos-in-match-range pos 2)
15538 (org-pos-in-match-range pos 3))
15539 (setq m (string-to-number (match-string 3 s))
15540 h (string-to-number (match-string 2 s)))
15541 (if (org-pos-in-match-range pos 2)
15542 (setq h (+ h n))
15543 (setq n (* dm (org-no-warnings (signum n))))
15544 (when (not (= 0 (setq rem (% m dm))))
15545 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
15546 (setq m (+ m n)))
15547 (if (< m 0) (setq m (+ m 60) h (1- h)))
15548 (if (> m 59) (setq m (- m 60) h (1+ h)))
15549 (setq h (min 24 (max 0 h)))
15550 (setq ng 1 new (format "-%02d:%02d" h m)))
15551 ((org-pos-in-match-range pos 6)
15552 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
15553 ((org-pos-in-match-range pos 5)
15554 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
15556 ((org-pos-in-match-range pos 9)
15557 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
15558 ((org-pos-in-match-range pos 8)
15559 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
15561 (when ng
15562 (setq s (concat
15563 (substring s 0 (match-beginning ng))
15565 (substring s (match-end ng))))))
15568 (defun org-recenter-calendar (date)
15569 "If the calendar is visible, recenter it to DATE."
15570 (let* ((win (selected-window))
15571 (cwin (get-buffer-window "*Calendar*" t))
15572 (calendar-move-hook nil))
15573 (when cwin
15574 (select-window cwin)
15575 (calendar-goto-date (if (listp date) date
15576 (calendar-gregorian-from-absolute date)))
15577 (select-window win))))
15579 (defun org-goto-calendar (&optional arg)
15580 "Go to the Emacs calendar at the current date.
15581 If there is a time stamp in the current line, go to that date.
15582 A prefix ARG can be used to force the current date."
15583 (interactive "P")
15584 (let ((tsr org-ts-regexp) diff
15585 (calendar-move-hook nil)
15586 (calendar-view-holidays-initially-flag nil)
15587 (calendar-view-diary-initially-flag nil))
15588 (if (or (org-at-timestamp-p)
15589 (save-excursion
15590 (beginning-of-line 1)
15591 (looking-at (concat ".*" tsr))))
15592 (let ((d1 (time-to-days (current-time)))
15593 (d2 (time-to-days
15594 (org-time-string-to-time (match-string 1)))))
15595 (setq diff (- d2 d1))))
15596 (calendar)
15597 (calendar-goto-today)
15598 (if (and diff (not arg)) (calendar-forward-day diff))))
15600 (defun org-get-date-from-calendar ()
15601 "Return a list (month day year) of date at point in calendar."
15602 (with-current-buffer "*Calendar*"
15603 (save-match-data
15604 (calendar-cursor-to-date))))
15606 (defun org-date-from-calendar ()
15607 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
15608 If there is already a time stamp at the cursor position, update it."
15609 (interactive)
15610 (if (org-at-timestamp-p t)
15611 (org-timestamp-change 0 'calendar)
15612 (let ((cal-date (org-get-date-from-calendar)))
15613 (org-insert-time-stamp
15614 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
15616 (defun org-minutes-to-hh:mm-string (m)
15617 "Compute H:MM from a number of minutes."
15618 (let ((h (/ m 60)))
15619 (setq m (- m (* 60 h)))
15620 (format org-time-clocksum-format h m)))
15622 (defun org-hh:mm-string-to-minutes (s)
15623 "Convert a string H:MM to a number of minutes.
15624 If the string is just a number, interpret it as minutes.
15625 In fact, the first hh:mm or number in the string will be taken,
15626 there can be extra stuff in the string.
15627 If no number is found, the return value is 0."
15628 (cond
15629 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
15630 (+ (* (string-to-number (match-string 1 s)) 60)
15631 (string-to-number (match-string 2 s))))
15632 ((string-match "\\([0-9]+\\)" s)
15633 (string-to-number (match-string 1 s)))
15634 (t 0)))
15636 (defcustom org-effort-durations
15637 `(("h" . 60)
15638 ("d" . ,(* 60 8))
15639 ("w" . ,(* 60 8 5))
15640 ("m" . ,(* 60 8 5 4))
15641 ("y" . ,(* 60 8 5 40)))
15642 "Conversion factor to minutes for an effort modifier.
15644 Each entry has the form (MODIFIER . MINUTES).
15646 In an effort string, a number followed by MODIFIER is multiplied
15647 by the specified number of MINUTES to obtain an effort in
15648 minutes.
15650 For example, if the value of this variable is ((\"hours\" . 60)), then an
15651 effort string \"2hours\" is equivalent to 120 minutes."
15652 :group 'org-agenda
15653 :type '(alist :key-type (string :tag "Modifier")
15654 :value-type (number :tag "Minutes")))
15656 (defun org-duration-string-to-minutes (s)
15657 "Convert a duration string S to minutes.
15659 A bare number is interpreted as minutes, modifiers can be set by
15660 customizing `org-effort-durations' (which see).
15662 Entries containing a colon are interpreted as H:MM by
15663 `org-hh:mm-string-to-minutes'."
15664 (let ((result 0)
15665 (re (concat "\\([0-9]+\\) *\\("
15666 (regexp-opt (mapcar 'car org-effort-durations))
15667 "\\)")))
15668 (while (string-match re s)
15669 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
15670 (string-to-number (match-string 1 s))))
15671 (setq s (replace-match "" nil t s)))
15672 (incf result (org-hh:mm-string-to-minutes s))
15673 result))
15675 ;;;; Files
15677 (defun org-save-all-org-buffers ()
15678 "Save all Org-mode buffers without user confirmation."
15679 (interactive)
15680 (message "Saving all Org-mode buffers...")
15681 (save-some-buffers t 'org-mode-p)
15682 (when (featurep 'org-id) (org-id-locations-save))
15683 (message "Saving all Org-mode buffers... done"))
15685 (defun org-revert-all-org-buffers ()
15686 "Revert all Org-mode buffers.
15687 Prompt for confirmation when there are unsaved changes.
15688 Be sure you know what you are doing before letting this function
15689 overwrite your changes.
15691 This function is useful in a setup where one tracks org files
15692 with a version control system, to revert on one machine after pulling
15693 changes from another. I believe the procedure must be like this:
15695 1. M-x org-save-all-org-buffers
15696 2. Pull changes from the other machine, resolve conflicts
15697 3. M-x org-revert-all-org-buffers"
15698 (interactive)
15699 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
15700 (error "Abort"))
15701 (save-excursion
15702 (save-window-excursion
15703 (mapc
15704 (lambda (b)
15705 (when (and (with-current-buffer b (org-mode-p))
15706 (with-current-buffer b buffer-file-name))
15707 (switch-to-buffer b)
15708 (revert-buffer t 'no-confirm)))
15709 (buffer-list))
15710 (when (and (featurep 'org-id) org-id-track-globally)
15711 (org-id-locations-load)))))
15713 ;;;; Agenda files
15715 ;;;###autoload
15716 (defun org-switchb (&optional arg)
15717 "Switch between Org buffers.
15718 With a prefix argument, restrict available to files.
15719 With two prefix arguments, restrict available buffers to agenda files.
15721 Defaults to `iswitchb' for buffer name completion.
15722 Set `org-completion-use-ido' to make it use ido instead."
15723 (interactive "P")
15724 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
15725 ((equal arg '(16)) (org-buffer-list 'agenda))
15726 (t (org-buffer-list))))
15727 (org-completion-use-iswitchb org-completion-use-iswitchb)
15728 (org-completion-use-ido org-completion-use-ido))
15729 (unless (or org-completion-use-ido org-completion-use-iswitchb)
15730 (setq org-completion-use-iswitchb t))
15731 (switch-to-buffer
15732 (org-icompleting-read "Org buffer: "
15733 (mapcar 'list (mapcar 'buffer-name blist))
15734 nil t))))
15736 ;;; Define some older names previously used for this functionality
15737 ;;;###autoload
15738 (defalias 'org-ido-switchb 'org-switchb)
15739 ;;;###autoload
15740 (defalias 'org-iswitchb 'org-switchb)
15742 (defun org-buffer-list (&optional predicate exclude-tmp)
15743 "Return a list of Org buffers.
15744 PREDICATE can be `export', `files' or `agenda'.
15746 export restrict the list to Export buffers.
15747 files restrict the list to buffers visiting Org files.
15748 agenda restrict the list to buffers visiting agenda files.
15750 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
15751 (let* ((bfn nil)
15752 (agenda-files (and (eq predicate 'agenda)
15753 (mapcar 'file-truename (org-agenda-files t))))
15754 (filter
15755 (cond
15756 ((eq predicate 'files)
15757 (lambda (b) (with-current-buffer b (org-mode-p))))
15758 ((eq predicate 'export)
15759 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
15760 ((eq predicate 'agenda)
15761 (lambda (b)
15762 (with-current-buffer b
15763 (and (org-mode-p)
15764 (setq bfn (buffer-file-name b))
15765 (member (file-truename bfn) agenda-files)))))
15766 (t (lambda (b) (with-current-buffer b
15767 (or (org-mode-p)
15768 (string-match "\*Org .*Export"
15769 (buffer-name b)))))))))
15770 (delq nil
15771 (mapcar
15772 (lambda(b)
15773 (if (and (funcall filter b)
15774 (or (not exclude-tmp)
15775 (not (string-match "tmp" (buffer-name b)))))
15777 nil))
15778 (buffer-list)))))
15780 (defun org-agenda-files (&optional unrestricted archives)
15781 "Get the list of agenda files.
15782 Optional UNRESTRICTED means return the full list even if a restriction
15783 is currently in place.
15784 When ARCHIVES is t, include all archive files that are really being
15785 used by the agenda files. If ARCHIVE is `ifmode', do this only if
15786 `org-agenda-archives-mode' is t."
15787 (let ((files
15788 (cond
15789 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
15790 ((stringp org-agenda-files) (org-read-agenda-file-list))
15791 ((listp org-agenda-files) org-agenda-files)
15792 (t (error "Invalid value of `org-agenda-files'")))))
15793 (setq files (apply 'append
15794 (mapcar (lambda (f)
15795 (if (file-directory-p f)
15796 (directory-files
15797 f t org-agenda-file-regexp)
15798 (list f)))
15799 files)))
15800 (when org-agenda-skip-unavailable-files
15801 (setq files (delq nil
15802 (mapcar (function
15803 (lambda (file)
15804 (and (file-readable-p file) file)))
15805 files))))
15806 (when (or (eq archives t)
15807 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
15808 (setq files (org-add-archive-files files)))
15809 files))
15811 (defun org-agenda-file-p (&optional file)
15812 "Return non-nil, if FILE is an agenda file.
15813 If FILE is omitted, use the file associated with the current
15814 buffer."
15815 (member (or file (buffer-file-name))
15816 (org-agenda-files t)))
15818 (defun org-edit-agenda-file-list ()
15819 "Edit the list of agenda files.
15820 Depending on setup, this either uses customize to edit the variable
15821 `org-agenda-files', or it visits the file that is holding the list. In the
15822 latter case, the buffer is set up in a way that saving it automatically kills
15823 the buffer and restores the previous window configuration."
15824 (interactive)
15825 (if (stringp org-agenda-files)
15826 (let ((cw (current-window-configuration)))
15827 (find-file org-agenda-files)
15828 (org-set-local 'org-window-configuration cw)
15829 (org-add-hook 'after-save-hook
15830 (lambda ()
15831 (set-window-configuration
15832 (prog1 org-window-configuration
15833 (kill-buffer (current-buffer))))
15834 (org-install-agenda-files-menu)
15835 (message "New agenda file list installed"))
15836 nil 'local)
15837 (message "%s" (substitute-command-keys
15838 "Edit list and finish with \\[save-buffer]")))
15839 (customize-variable 'org-agenda-files)))
15841 (defun org-store-new-agenda-file-list (list)
15842 "Set new value for the agenda file list and save it correctly."
15843 (if (stringp org-agenda-files)
15844 (let ((fe (org-read-agenda-file-list t)) b u)
15845 (while (setq b (find-buffer-visiting org-agenda-files))
15846 (kill-buffer b))
15847 (with-temp-file org-agenda-files
15848 (insert
15849 (mapconcat
15850 (lambda (f) ;; Keep un-expanded entries.
15851 (if (setq u (assoc f fe))
15852 (cdr u)
15854 list "\n")
15855 "\n")))
15856 (let ((org-mode-hook nil) (org-inhibit-startup t)
15857 (org-insert-mode-line-in-empty-file nil))
15858 (setq org-agenda-files list)
15859 (customize-save-variable 'org-agenda-files org-agenda-files))))
15861 (defun org-read-agenda-file-list (&optional pair-with-expansion)
15862 "Read the list of agenda files from a file.
15863 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
15864 filenames, used by `org-store-new-agenda-file-list' to write back
15865 un-expanded file names."
15866 (when (file-directory-p org-agenda-files)
15867 (error "`org-agenda-files' cannot be a single directory"))
15868 (when (stringp org-agenda-files)
15869 (with-temp-buffer
15870 (insert-file-contents org-agenda-files)
15871 (mapcar
15872 (lambda (f)
15873 (let ((e (expand-file-name (substitute-in-file-name f)
15874 org-directory)))
15875 (if pair-with-expansion
15876 (cons e f)
15877 e)))
15878 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
15880 ;;;###autoload
15881 (defun org-cycle-agenda-files ()
15882 "Cycle through the files in `org-agenda-files'.
15883 If the current buffer visits an agenda file, find the next one in the list.
15884 If the current buffer does not, find the first agenda file."
15885 (interactive)
15886 (let* ((fs (org-agenda-files t))
15887 (files (append fs (list (car fs))))
15888 (tcf (if buffer-file-name (file-truename buffer-file-name)))
15889 file)
15890 (unless files (error "No agenda files"))
15891 (catch 'exit
15892 (while (setq file (pop files))
15893 (if (equal (file-truename file) tcf)
15894 (when (car files)
15895 (find-file (car files))
15896 (throw 'exit t))))
15897 (find-file (car fs)))
15898 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
15900 (defun org-agenda-file-to-front (&optional to-end)
15901 "Move/add the current file to the top of the agenda file list.
15902 If the file is not present in the list, it is added to the front. If it is
15903 present, it is moved there. With optional argument TO-END, add/move to the
15904 end of the list."
15905 (interactive "P")
15906 (let ((org-agenda-skip-unavailable-files nil)
15907 (file-alist (mapcar (lambda (x)
15908 (cons (file-truename x) x))
15909 (org-agenda-files t)))
15910 (ctf (file-truename buffer-file-name))
15911 x had)
15912 (setq x (assoc ctf file-alist) had x)
15914 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
15915 (if to-end
15916 (setq file-alist (append (delq x file-alist) (list x)))
15917 (setq file-alist (cons x (delq x file-alist))))
15918 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
15919 (org-install-agenda-files-menu)
15920 (message "File %s to %s of agenda file list"
15921 (if had "moved" "added") (if to-end "end" "front"))))
15923 (defun org-remove-file (&optional file)
15924 "Remove current file from the list of files in variable `org-agenda-files'.
15925 These are the files which are being checked for agenda entries.
15926 Optional argument FILE means use this file instead of the current."
15927 (interactive)
15928 (let* ((org-agenda-skip-unavailable-files nil)
15929 (file (or file buffer-file-name))
15930 (true-file (file-truename file))
15931 (afile (abbreviate-file-name file))
15932 (files (delq nil (mapcar
15933 (lambda (x)
15934 (if (equal true-file
15935 (file-truename x))
15936 nil x))
15937 (org-agenda-files t)))))
15938 (if (not (= (length files) (length (org-agenda-files t))))
15939 (progn
15940 (org-store-new-agenda-file-list files)
15941 (org-install-agenda-files-menu)
15942 (message "Removed file: %s" afile))
15943 (message "File was not in list: %s (not removed)" afile))))
15945 (defun org-file-menu-entry (file)
15946 (vector file (list 'find-file file) t))
15948 (defun org-check-agenda-file (file)
15949 "Make sure FILE exists. If not, ask user what to do."
15950 (when (not (file-exists-p file))
15951 (message "non-existent agenda file %s. [R]emove from list or [A]bort?"
15952 (abbreviate-file-name file))
15953 (let ((r (downcase (read-char-exclusive))))
15954 (cond
15955 ((equal r ?r)
15956 (org-remove-file file)
15957 (throw 'nextfile t))
15958 (t (error "Abort"))))))
15960 (defun org-get-agenda-file-buffer (file)
15961 "Get a buffer visiting FILE. If the buffer needs to be created, add
15962 it to the list of buffers which might be released later."
15963 (let ((buf (org-find-base-buffer-visiting file)))
15964 (if buf
15965 buf ; just return it
15966 ;; Make a new buffer and remember it
15967 (setq buf (find-file-noselect file))
15968 (if buf (push buf org-agenda-new-buffers))
15969 buf)))
15971 (defun org-release-buffers (blist)
15972 "Release all buffers in list, asking the user for confirmation when needed.
15973 When a buffer is unmodified, it is just killed. When modified, it is saved
15974 \(if the user agrees) and then killed."
15975 (let (buf file)
15976 (while (setq buf (pop blist))
15977 (setq file (buffer-file-name buf))
15978 (when (and (buffer-modified-p buf)
15979 file
15980 (y-or-n-p (format "Save file %s? " file)))
15981 (with-current-buffer buf (save-buffer)))
15982 (kill-buffer buf))))
15984 (defun org-prepare-agenda-buffers (files)
15985 "Create buffers for all agenda files, protect archived trees and comments."
15986 (interactive)
15987 (let ((pa '(:org-archived t))
15988 (pc '(:org-comment t))
15989 (pall '(:org-archived t :org-comment t))
15990 (inhibit-read-only t)
15991 (rea (concat ":" org-archive-tag ":"))
15992 bmp file re)
15993 (save-excursion
15994 (save-restriction
15995 (while (setq file (pop files))
15996 (catch 'nextfile
15997 (if (bufferp file)
15998 (set-buffer file)
15999 (org-check-agenda-file file)
16000 (set-buffer (org-get-agenda-file-buffer file)))
16001 (widen)
16002 (setq bmp (buffer-modified-p))
16003 (org-refresh-category-properties)
16004 (setq org-todo-keywords-for-agenda
16005 (append org-todo-keywords-for-agenda org-todo-keywords-1))
16006 (setq org-done-keywords-for-agenda
16007 (append org-done-keywords-for-agenda org-done-keywords))
16008 (setq org-todo-keyword-alist-for-agenda
16009 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
16010 (setq org-drawers-for-agenda
16011 (append org-drawers-for-agenda org-drawers))
16012 (setq org-tag-alist-for-agenda
16013 (append org-tag-alist-for-agenda org-tag-alist))
16015 (save-excursion
16016 (remove-text-properties (point-min) (point-max) pall)
16017 (when org-agenda-skip-archived-trees
16018 (goto-char (point-min))
16019 (while (re-search-forward rea nil t)
16020 (if (org-on-heading-p t)
16021 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
16022 (goto-char (point-min))
16023 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
16024 (while (re-search-forward re nil t)
16025 (add-text-properties
16026 (match-beginning 0) (org-end-of-subtree t) pc)))
16027 (set-buffer-modified-p bmp)))))
16028 (setq org-todo-keywords-for-agenda
16029 (org-uniquify org-todo-keywords-for-agenda))
16030 (setq org-todo-keyword-alist-for-agenda
16031 (org-uniquify org-todo-keyword-alist-for-agenda)
16032 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
16034 ;;;; Embedded LaTeX
16036 (defvar org-cdlatex-mode-map (make-sparse-keymap)
16037 "Keymap for the minor `org-cdlatex-mode'.")
16039 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
16040 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
16041 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
16042 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
16043 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
16045 (defvar org-cdlatex-texmathp-advice-is-done nil
16046 "Flag remembering if we have applied the advice to texmathp already.")
16048 (define-minor-mode org-cdlatex-mode
16049 "Toggle the minor `org-cdlatex-mode'.
16050 This mode supports entering LaTeX environment and math in LaTeX fragments
16051 in Org-mode.
16052 \\{org-cdlatex-mode-map}"
16053 nil " OCDL" nil
16054 (when org-cdlatex-mode (require 'cdlatex))
16055 (unless org-cdlatex-texmathp-advice-is-done
16056 (setq org-cdlatex-texmathp-advice-is-done t)
16057 (defadvice texmathp (around org-math-always-on activate)
16058 "Always return t in org-mode buffers.
16059 This is because we want to insert math symbols without dollars even outside
16060 the LaTeX math segments. If Orgmode thinks that point is actually inside
16061 an embedded LaTeX fragment, let texmathp do its job.
16062 \\[org-cdlatex-mode-map]"
16063 (interactive)
16064 (let (p)
16065 (cond
16066 ((not (org-mode-p)) ad-do-it)
16067 ((eq this-command 'cdlatex-math-symbol)
16068 (setq ad-return-value t
16069 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
16071 (let ((p (org-inside-LaTeX-fragment-p)))
16072 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
16073 (setq ad-return-value t
16074 texmathp-why '("Org-mode embedded math" . 0))
16075 (if p ad-do-it)))))))))
16077 (defun turn-on-org-cdlatex ()
16078 "Unconditionally turn on `org-cdlatex-mode'."
16079 (org-cdlatex-mode 1))
16081 (defun org-inside-LaTeX-fragment-p ()
16082 "Test if point is inside a LaTeX fragment.
16083 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
16084 sequence appearing also before point.
16085 Even though the matchers for math are configurable, this function assumes
16086 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
16087 delimiters are skipped when they have been removed by customization.
16088 The return value is nil, or a cons cell with the delimiter and
16089 and the position of this delimiter.
16091 This function does a reasonably good job, but can locally be fooled by
16092 for example currency specifications. For example it will assume being in
16093 inline math after \"$22.34\". The LaTeX fragment formatter will only format
16094 fragments that are properly closed, but during editing, we have to live
16095 with the uncertainty caused by missing closing delimiters. This function
16096 looks only before point, not after."
16097 (catch 'exit
16098 (let ((pos (point))
16099 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
16100 (lim (progn
16101 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
16102 (point)))
16103 dd-on str (start 0) m re)
16104 (goto-char pos)
16105 (when dodollar
16106 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
16107 re (nth 1 (assoc "$" org-latex-regexps)))
16108 (while (string-match re str start)
16109 (cond
16110 ((= (match-end 0) (length str))
16111 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
16112 ((= (match-end 0) (- (length str) 5))
16113 (throw 'exit nil))
16114 (t (setq start (match-end 0))))))
16115 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
16116 (goto-char pos)
16117 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
16118 (and (match-beginning 2) (throw 'exit nil))
16119 ;; count $$
16120 (while (re-search-backward "\\$\\$" lim t)
16121 (setq dd-on (not dd-on)))
16122 (goto-char pos)
16123 (if dd-on (cons "$$" m))))))
16125 (defun org-inside-latex-macro-p ()
16126 "Is point inside a LaTeX macro or its arguments?"
16127 (save-match-data
16128 (org-in-regexp
16129 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
16131 (defun org-try-cdlatex-tab ()
16132 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
16133 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
16134 - inside a LaTeX fragment, or
16135 - after the first word in a line, where an abbreviation expansion could
16136 insert a LaTeX environment."
16137 (when org-cdlatex-mode
16138 (cond
16139 ((save-excursion
16140 (skip-chars-backward "a-zA-Z0-9*")
16141 (skip-chars-backward " \t")
16142 (bolp))
16143 (cdlatex-tab) t)
16144 ((org-inside-LaTeX-fragment-p)
16145 (cdlatex-tab) t)
16146 (t nil))))
16148 (defun org-cdlatex-underscore-caret (&optional arg)
16149 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
16150 Revert to the normal definition outside of these fragments."
16151 (interactive "P")
16152 (if (org-inside-LaTeX-fragment-p)
16153 (call-interactively 'cdlatex-sub-superscript)
16154 (let (org-cdlatex-mode)
16155 (call-interactively (key-binding (vector last-input-event))))))
16157 (defun org-cdlatex-math-modify (&optional arg)
16158 "Execute `cdlatex-math-modify' in LaTeX fragments.
16159 Revert to the normal definition outside of these fragments."
16160 (interactive "P")
16161 (if (org-inside-LaTeX-fragment-p)
16162 (call-interactively 'cdlatex-math-modify)
16163 (let (org-cdlatex-mode)
16164 (call-interactively (key-binding (vector last-input-event))))))
16166 (defvar org-latex-fragment-image-overlays nil
16167 "List of overlays carrying the images of latex fragments.")
16168 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
16170 (defun org-remove-latex-fragment-image-overlays ()
16171 "Remove all overlays with LaTeX fragment images in current buffer."
16172 (mapc 'delete-overlay org-latex-fragment-image-overlays)
16173 (setq org-latex-fragment-image-overlays nil))
16175 (defun org-preview-latex-fragment (&optional subtree)
16176 "Preview the LaTeX fragment at point, or all locally or globally.
16177 If the cursor is in a LaTeX fragment, create the image and overlay
16178 it over the source code. If there is no fragment at point, display
16179 all fragments in the current text, from one headline to the next. With
16180 prefix SUBTREE, display all fragments in the current subtree. With a
16181 double prefix arg \\[universal-argument] \\[universal-argument], or when \
16182 the cursor is before the first headline,
16183 display all fragments in the buffer.
16184 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
16185 (interactive "P")
16186 (org-remove-latex-fragment-image-overlays)
16187 (save-excursion
16188 (save-restriction
16189 (let (beg end at msg)
16190 (cond
16191 ((or (equal subtree '(16))
16192 (not (save-excursion
16193 (re-search-backward (concat "^" outline-regexp) nil t))))
16194 (setq beg (point-min) end (point-max)
16195 msg "Creating images for buffer...%s"))
16196 ((equal subtree '(4))
16197 (org-back-to-heading)
16198 (setq beg (point) end (org-end-of-subtree t)
16199 msg "Creating images for subtree...%s"))
16201 (if (setq at (org-inside-LaTeX-fragment-p))
16202 (goto-char (max (point-min) (- (cdr at) 2)))
16203 (org-back-to-heading))
16204 (setq beg (point) end (progn (outline-next-heading) (point))
16205 msg (if at "Creating image...%s"
16206 "Creating images for entry...%s"))))
16207 (message msg "")
16208 (narrow-to-region beg end)
16209 (goto-char beg)
16210 (org-format-latex
16211 (concat "ltxpng/" (file-name-sans-extension
16212 (file-name-nondirectory
16213 buffer-file-name)))
16214 default-directory 'overlays msg at 'forbuffer 'dvipng)
16215 (message msg "done. Use `C-c C-c' to remove images.")))))
16217 (defvar org-latex-regexps
16218 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
16219 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
16220 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
16221 ("$1" "\\([^$]\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
16222 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
16223 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
16224 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
16225 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
16226 "Regular expressions for matching embedded LaTeX.")
16228 (defvar org-export-have-math nil) ;; dynamic scoping
16229 (defun org-format-latex (prefix &optional dir overlays msg at
16230 forbuffer processing-type)
16231 "Replace LaTeX fragments with links to an image, and produce images.
16232 Some of the options can be changed using the variable
16233 `org-format-latex-options'."
16234 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
16235 (let* ((prefixnodir (file-name-nondirectory prefix))
16236 (absprefix (expand-file-name prefix dir))
16237 (todir (file-name-directory absprefix))
16238 (opt org-format-latex-options)
16239 (matchers (plist-get opt :matchers))
16240 (re-list org-latex-regexps)
16241 (org-format-latex-header-extra
16242 (plist-get (org-infile-export-plist) :latex-header-extra))
16243 (cnt 0) txt hash link beg end re e checkdir
16244 executables-checked string
16245 m n block linkfile movefile ov)
16246 ;; Check the different regular expressions
16247 (while (setq e (pop re-list))
16248 (setq m (car e) re (nth 1 e) n (nth 2 e)
16249 block (if (nth 3 e) "\n\n" ""))
16250 (when (member m matchers)
16251 (goto-char (point-min))
16252 (while (re-search-forward re nil t)
16253 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
16254 (not (get-text-property (match-beginning n)
16255 'org-protected))
16256 (or (not overlays)
16257 (not (eq (get-char-property (match-beginning n)
16258 'org-overlay-type)
16259 'org-latex-overlay))))
16260 (setq org-export-have-math t)
16261 (cond
16262 ((eq processing-type 'verbatim)
16263 ;; Leave the text verbatim, just protect it
16264 (add-text-properties (match-beginning n) (match-end n)
16265 '(org-protected t)))
16266 ((eq processing-type 'mathjax)
16267 ;; Prepare for MathJax processing
16268 (setq string (match-string n))
16269 (if (member m '("$" "$1"))
16270 (save-excursion
16271 (delete-region (match-beginning n) (match-end n))
16272 (goto-char (match-beginning n))
16273 (insert (org-add-props (concat "\\(" (substring string 1 -1)
16274 "\\)")
16275 '(org-protected t))))
16276 (add-text-properties (match-beginning n) (match-end n)
16277 '(org-protected t))))
16278 ((or (eq processing-type 'dvipng) t)
16279 ;; Process to an image
16280 (setq txt (match-string n)
16281 beg (match-beginning n) end (match-end n)
16282 cnt (1+ cnt))
16283 (let (print-length print-level) ; make sure full list is printed
16284 (setq hash (sha1 (prin1-to-string
16285 (list org-format-latex-header
16286 org-format-latex-header-extra
16287 org-export-latex-default-packages-alist
16288 org-export-latex-packages-alist
16289 org-format-latex-options
16290 forbuffer txt)))
16291 linkfile (format "%s_%s.png" prefix hash)
16292 movefile (format "%s_%s.png" absprefix hash)))
16293 (setq link (concat block "[[file:" linkfile "]]" block))
16294 (if msg (message msg cnt))
16295 (goto-char beg)
16296 (unless checkdir ; make sure the directory exists
16297 (setq checkdir t)
16298 (or (file-directory-p todir) (make-directory todir t)))
16300 (unless executables-checked
16301 (org-check-external-command
16302 "latex" "needed to convert LaTeX fragments to images")
16303 (org-check-external-command
16304 "dvipng" "needed to convert LaTeX fragments to images")
16305 (setq executables-checked t))
16307 (unless (file-exists-p movefile)
16308 (org-create-formula-image
16309 txt movefile opt forbuffer))
16310 (if overlays
16311 (progn
16312 (mapc (lambda (o)
16313 (if (eq (overlay-get o 'org-overlay-type)
16314 'org-latex-overlay)
16315 (delete-overlay o)))
16316 (overlays-in beg end))
16317 (setq ov (make-overlay beg end))
16318 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
16319 (if (featurep 'xemacs)
16320 (progn
16321 (overlay-put ov 'invisible t)
16322 (overlay-put
16323 ov 'end-glyph
16324 (make-glyph (vector 'png :file movefile))))
16325 (overlay-put
16326 ov 'display
16327 (list 'image :type 'png :file movefile :ascent 'center)))
16328 (push ov org-latex-fragment-image-overlays)
16329 (goto-char end))
16330 (delete-region beg end)
16331 (insert (org-add-props link
16332 (list 'org-latex-src
16333 (replace-regexp-in-string
16334 "\"" "" txt)))))))))))))
16336 ;; This function borrows from Ganesh Swami's latex2png.el
16337 (defun org-create-formula-image (string tofile options buffer)
16338 "This calls dvipng."
16339 (require 'org-latex)
16340 (let* ((tmpdir (if (featurep 'xemacs)
16341 (temp-directory)
16342 temporary-file-directory))
16343 (texfilebase (make-temp-name
16344 (expand-file-name "orgtex" tmpdir)))
16345 (texfile (concat texfilebase ".tex"))
16346 (dvifile (concat texfilebase ".dvi"))
16347 (pngfile (concat texfilebase ".png"))
16348 (fnh (if (featurep 'xemacs)
16349 (font-height (get-face-font 'default))
16350 (face-attribute 'default :height nil)))
16351 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
16352 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
16353 (fg (or (plist-get options (if buffer :foreground :html-foreground))
16354 "Black"))
16355 (bg (or (plist-get options (if buffer :background :html-background))
16356 "Transparent")))
16357 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
16358 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
16359 (with-temp-file texfile
16360 (insert (org-splice-latex-header
16361 org-format-latex-header
16362 org-export-latex-default-packages-alist
16363 org-export-latex-packages-alist t
16364 org-format-latex-header-extra))
16365 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")
16366 (require 'org-latex)
16367 (org-export-latex-fix-inputenc))
16368 (let ((dir default-directory))
16369 (condition-case nil
16370 (progn
16371 (cd tmpdir)
16372 (call-process "latex" nil nil nil texfile))
16373 (error nil))
16374 (cd dir))
16375 (if (not (file-exists-p dvifile))
16376 (progn (message "Failed to create dvi file from %s" texfile) nil)
16377 (condition-case nil
16378 (call-process "dvipng" nil nil nil
16379 "-fg" fg "-bg" bg
16380 "-D" dpi
16381 ;;"-x" scale "-y" scale
16382 "-T" "tight"
16383 "-o" pngfile
16384 dvifile)
16385 (error nil))
16386 (if (not (file-exists-p pngfile))
16387 (if org-format-latex-signal-error
16388 (error "Failed to create png file from %s" texfile)
16389 (message "Failed to create png file from %s" texfile)
16390 nil)
16391 ;; Use the requested file name and clean up
16392 (copy-file pngfile tofile 'replace)
16393 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
16394 (delete-file (concat texfilebase e)))
16395 pngfile))))
16397 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
16398 "Fill a LaTeX header template TPL.
16399 In the template, the following place holders will be recognized:
16401 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
16402 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
16403 [PACKAGES] \\usepackage statements for PKG
16404 [NO-PACKAGES] do not include PKG
16405 [EXTRA] the string EXTRA
16406 [NO-EXTRA] do not include EXTRA
16408 For backward compatibility, if both the positive and the negative place
16409 holder is missing, the positive one (without the \"NO-\") will be
16410 assumed to be present at the end of the template.
16411 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
16412 EXTRA is a string.
16413 SNIPPETS-P indicates if this is run to create snippet images for HTML."
16414 (let (rpl (end ""))
16415 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
16416 (setq rpl (if (or (match-end 1) (not def-pkg))
16417 "" (org-latex-packages-to-string def-pkg snippets-p t))
16418 tpl (replace-match rpl t t tpl))
16419 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
16421 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
16422 (setq rpl (if (or (match-end 1) (not pkg))
16423 "" (org-latex-packages-to-string pkg snippets-p t))
16424 tpl (replace-match rpl t t tpl))
16425 (if pkg (setq end
16426 (concat end "\n"
16427 (org-latex-packages-to-string pkg snippets-p)))))
16429 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
16430 (setq rpl (if (or (match-end 1) (not extra))
16431 "" (concat extra "\n"))
16432 tpl (replace-match rpl t t tpl))
16433 (if (and extra (string-match "\\S-" extra))
16434 (setq end (concat end "\n" extra))))
16436 (if (string-match "\\S-" end)
16437 (concat tpl "\n" end)
16438 tpl)))
16440 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
16441 "Turn an alist of packages into a string with the \\usepackage macros."
16442 (setq pkg (mapconcat (lambda(p)
16443 (cond
16444 ((stringp p) p)
16445 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
16446 (format "%% Package %s omitted" (cadr p)))
16447 ((equal "" (car p))
16448 (format "\\usepackage{%s}" (cadr p)))
16450 (format "\\usepackage[%s]{%s}"
16451 (car p) (cadr p)))))
16453 "\n"))
16454 (if newline (concat pkg "\n") pkg))
16456 (defun org-dvipng-color (attr)
16457 "Return an rgb color specification for dvipng."
16458 (apply 'format "rgb %s %s %s"
16459 (mapcar 'org-normalize-color
16460 (color-values (face-attribute 'default attr nil)))))
16462 (defun org-normalize-color (value)
16463 "Return string to be used as color value for an RGB component."
16464 (format "%g" (/ value 65535.0)))
16466 ;; Image display
16469 (defvar org-inline-image-overlays nil)
16470 (make-variable-buffer-local 'org-inline-image-overlays)
16472 (defun org-toggle-inline-images (&optional include-linked)
16473 "Toggle the display of inline images.
16474 INCLUDE-LINKED is passed to `org-display-inline-images'."
16475 (interactive "P")
16476 (if org-inline-image-overlays
16477 (progn
16478 (org-remove-inline-images)
16479 (message "Inline image display turned off"))
16480 (org-display-inline-images include-linked)
16481 (if org-inline-image-overlays
16482 (message "%d images displayed inline"
16483 (length org-inline-image-overlays))
16484 (message "No images to display inline"))))
16486 (defun org-display-inline-images (&optional include-linked refresh beg end)
16487 "Display inline images.
16488 Normally only links without a description part are inlined, because this
16489 is how it will work for export. When INCLUDE-LINKED is set, also links
16490 with a description part will be inlined. This can be nice for a quick
16491 look at those images, but it does not reflect what exported files will look
16492 like.
16493 When REFRESH is set, refresh existing images between BEG and END.
16494 This will create new image displays only if necessary.
16495 BEG and END default to the buffer boundaries."
16496 (interactive "P")
16497 (unless refresh
16498 (org-remove-inline-images)
16499 (if (fboundp 'clear-image-cache) (clear-image-cache)))
16500 (save-excursion
16501 (save-restriction
16502 (widen)
16503 (setq beg (or beg (point-min)) end (or end (point-max)))
16504 (goto-char (point-min))
16505 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
16506 (substring (org-image-file-name-regexp) 0 -2)
16507 "\\)\\]" (if include-linked "" "\\]")))
16508 old file ov img)
16509 (while (re-search-forward re end t)
16510 (setq old (get-char-property-and-overlay (match-beginning 1)
16511 'org-image-overlay))
16512 (setq file (expand-file-name
16513 (concat (or (match-string 3) "") (match-string 4))))
16514 (when (file-exists-p file)
16515 (if (and (car-safe old) refresh)
16516 (image-refresh (overlay-get (cdr old) 'display))
16517 (setq img (save-match-data (create-image file)))
16518 (when img
16519 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
16520 (overlay-put ov 'display img)
16521 (overlay-put ov 'face 'default)
16522 (overlay-put ov 'org-image-overlay t)
16523 (overlay-put ov 'modification-hooks
16524 (list 'org-display-inline-modification-hook))
16525 (push ov org-inline-image-overlays)))))))))
16527 (defun org-display-inline-modification-hook (ov after beg end &optional len)
16528 "Remove inline-display overlay if a corresponding region is modified."
16529 (let ((inhibit-modification-hooks t))
16530 (when (and ov after)
16531 (delete ov org-inline-image-overlays)
16532 (delete-overlay ov))))
16534 (defun org-remove-inline-images ()
16535 "Remove inline display of images."
16536 (interactive)
16537 (mapc 'delete-overlay org-inline-image-overlays)
16538 (setq org-inline-image-overlays nil))
16540 ;;;; Key bindings
16542 ;; Make `C-c C-x' a prefix key
16543 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
16545 ;; TAB key with modifiers
16546 (org-defkey org-mode-map "\C-i" 'org-cycle)
16547 (org-defkey org-mode-map [(tab)] 'org-cycle)
16548 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
16549 (org-defkey org-mode-map [(meta tab)] 'pcomplete)
16550 (org-defkey org-mode-map "\M-\t" 'pcomplete)
16551 (org-defkey org-mode-map "\M-\C-i" 'pcomplete)
16552 ;; The following line is necessary under Suse GNU/Linux
16553 (unless (featurep 'xemacs)
16554 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
16555 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
16556 (define-key org-mode-map [backtab] 'org-shifttab)
16558 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
16559 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
16560 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
16562 ;; Cursor keys with modifiers
16563 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
16564 (org-defkey org-mode-map [(meta right)] 'org-metaright)
16565 (org-defkey org-mode-map [(meta up)] 'org-metaup)
16566 (org-defkey org-mode-map [(meta down)] 'org-metadown)
16568 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
16569 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
16570 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
16571 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
16573 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
16574 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
16575 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
16576 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
16578 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
16579 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
16581 ;; Babel keys
16582 (define-key org-mode-map org-babel-key-prefix org-babel-map)
16583 (mapc (lambda (pair)
16584 (define-key org-babel-map (car pair) (cdr pair)))
16585 org-babel-key-bindings)
16587 ;;; Extra keys for tty access.
16588 ;; We only set them when really needed because otherwise the
16589 ;; menus don't show the simple keys
16591 (when (or org-use-extra-keys
16592 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
16593 (not window-system))
16594 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
16595 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
16596 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
16597 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
16598 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
16599 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
16600 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
16601 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
16602 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
16603 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
16604 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
16605 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
16606 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
16607 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
16608 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
16609 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
16610 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
16611 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
16612 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
16613 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
16614 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
16615 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
16616 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
16617 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
16618 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
16619 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
16620 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
16621 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
16623 ;; All the other keys
16625 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
16626 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
16627 (if (boundp 'narrow-map)
16628 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
16629 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
16630 (if (boundp 'narrow-map)
16631 (org-defkey narrow-map "b" 'org-narrow-to-block)
16632 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
16633 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-same-level)
16634 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-same-level)
16635 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
16636 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
16637 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
16638 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
16639 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
16640 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
16641 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
16642 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
16643 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
16644 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
16645 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
16646 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
16647 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
16648 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
16649 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
16650 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
16651 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
16652 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
16653 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
16654 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
16655 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
16656 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
16657 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
16658 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
16659 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
16660 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
16661 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
16662 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
16663 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
16664 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
16665 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
16666 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
16667 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
16668 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
16669 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
16670 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
16671 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
16672 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
16673 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
16674 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
16675 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
16676 (org-defkey org-mode-map "\C-c^" 'org-sort)
16677 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
16678 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
16679 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
16680 (org-defkey org-mode-map "\C-m" 'org-return)
16681 (org-defkey org-mode-map "\C-j" 'org-return-indent)
16682 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
16683 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
16684 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
16685 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
16686 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
16687 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
16688 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
16689 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
16690 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
16691 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
16692 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
16693 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
16694 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
16695 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
16696 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
16697 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
16698 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
16699 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
16700 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
16701 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
16702 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
16704 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
16705 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
16706 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
16707 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
16709 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
16710 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
16711 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
16712 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
16713 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
16714 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
16715 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
16716 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
16717 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
16718 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
16719 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
16720 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
16721 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
16722 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
16723 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
16724 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
16725 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
16726 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
16728 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
16729 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
16730 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
16731 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
16732 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
16734 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
16736 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
16738 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
16739 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
16741 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
16744 (when (featurep 'xemacs)
16745 (org-defkey org-mode-map 'button3 'popup-mode-menu))
16748 (defconst org-speed-commands-default
16750 ("Outline Navigation")
16751 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
16752 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
16753 ("f" . (org-speed-move-safe 'org-forward-same-level))
16754 ("b" . (org-speed-move-safe 'org-backward-same-level))
16755 ("u" . (org-speed-move-safe 'outline-up-heading))
16756 ("j" . org-goto)
16757 ("g" . (org-refile t))
16758 ("Outline Visibility")
16759 ("c" . org-cycle)
16760 ("C" . org-shifttab)
16761 (" " . org-display-outline-path)
16762 ("Outline Structure Editing")
16763 ("U" . org-shiftmetaup)
16764 ("D" . org-shiftmetadown)
16765 ("r" . org-metaright)
16766 ("l" . org-metaleft)
16767 ("R" . org-shiftmetaright)
16768 ("L" . org-shiftmetaleft)
16769 ("i" . (progn (forward-char 1) (call-interactively
16770 'org-insert-heading-respect-content)))
16771 ("^" . org-sort)
16772 ("w" . org-refile)
16773 ("a" . org-archive-subtree-default-with-confirmation)
16774 ("." . org-mark-subtree)
16775 ("Clock Commands")
16776 ("I" . org-clock-in)
16777 ("O" . org-clock-out)
16778 ("Meta Data Editing")
16779 ("t" . org-todo)
16780 ("0" . (org-priority ?\ ))
16781 ("1" . (org-priority ?A))
16782 ("2" . (org-priority ?B))
16783 ("3" . (org-priority ?C))
16784 (";" . org-set-tags-command)
16785 ("e" . org-set-effort)
16786 ("Agenda Views etc")
16787 ("v" . org-agenda)
16788 ("/" . org-sparse-tree)
16789 ("Misc")
16790 ("o" . org-open-at-point)
16791 ("?" . org-speed-command-help)
16792 ("<" . (org-agenda-set-restriction-lock 'subtree))
16793 (">" . (org-agenda-remove-restriction-lock))
16795 "The default speed commands.")
16797 (defun org-print-speed-command (e)
16798 (if (> (length (car e)) 1)
16799 (progn
16800 (princ "\n")
16801 (princ (car e))
16802 (princ "\n")
16803 (princ (make-string (length (car e)) ?-))
16804 (princ "\n"))
16805 (princ (car e))
16806 (princ " ")
16807 (if (symbolp (cdr e))
16808 (princ (symbol-name (cdr e)))
16809 (prin1 (cdr e)))
16810 (princ "\n")))
16812 (defun org-speed-command-help ()
16813 "Show the available speed commands."
16814 (interactive)
16815 (if (not org-use-speed-commands)
16816 (error "Speed commands are not activated, customize `org-use-speed-commands'")
16817 (with-output-to-temp-buffer "*Help*"
16818 (princ "User-defined Speed commands\n===========================\n")
16819 (mapc 'org-print-speed-command org-speed-commands-user)
16820 (princ "\n")
16821 (princ "Built-in Speed commands\n=======================\n")
16822 (mapc 'org-print-speed-command org-speed-commands-default))
16823 (with-current-buffer "*Help*"
16824 (setq truncate-lines t))))
16826 (defun org-speed-move-safe (cmd)
16827 "Execute CMD, but make sure that the cursor always ends up in a headline.
16828 If not, return to the original position and throw an error."
16829 (interactive)
16830 (let ((pos (point)))
16831 (call-interactively cmd)
16832 (unless (and (bolp) (org-on-heading-p))
16833 (goto-char pos)
16834 (error "Boundary reached while executing %s" cmd))))
16836 (defvar org-self-insert-command-undo-counter 0)
16838 (defvar org-table-auto-blank-field) ; defined in org-table.el
16839 (defvar org-speed-command nil)
16841 (defun org-speed-command-default-hook (keys)
16842 "Hook for activating single-letter speed commands.
16843 `org-speed-commands-default' specifies a minimal command set. Use
16844 `org-speed-commands-user' for further customization."
16845 (when (or (and (bolp) (looking-at outline-regexp))
16846 (and (functionp org-use-speed-commands)
16847 (funcall org-use-speed-commands)))
16848 (cdr (assoc keys (append org-speed-commands-user
16849 org-speed-commands-default)))))
16851 (defun org-babel-speed-command-hook (keys)
16852 "Hook for activating single-letter code block commands."
16853 (when (and (bolp) (looking-at org-babel-src-block-regexp))
16854 (cdr (assoc keys org-babel-key-bindings))))
16856 (defcustom org-speed-command-hook
16857 '(org-speed-command-default-hook org-babel-speed-command-hook)
16858 "Hook for activating speed commands at strategic locations.
16859 Hook functions are called in sequence until a valid handler is
16860 found.
16862 Each hook takes a single argument, a user-pressed command key
16863 which is also a `self-insert-command' from the global map.
16865 Within the hook, examine the cursor position and the command key
16866 and return nil or a valid handler as appropriate. Handler could
16867 be one of an interactive command, a function, or a form.
16869 Set `org-use-speed-commands' to non-nil value to enable this
16870 hook. The default setting is `org-speed-command-default-hook'."
16871 :group 'org-structure
16872 :type 'hook)
16874 (defun org-self-insert-command (N)
16875 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
16876 If the cursor is in a table looking at whitespace, the whitespace is
16877 overwritten, and the table is not marked as requiring realignment."
16878 (interactive "p")
16879 (cond
16880 ((and org-use-speed-commands
16881 (setq org-speed-command
16882 (run-hook-with-args-until-success
16883 'org-speed-command-hook (this-command-keys))))
16884 (cond
16885 ((commandp org-speed-command)
16886 (setq this-command org-speed-command)
16887 (call-interactively org-speed-command))
16888 ((functionp org-speed-command)
16889 (funcall org-speed-command))
16890 ((and org-speed-command (listp org-speed-command))
16891 (eval org-speed-command))
16892 (t (let (org-use-speed-commands)
16893 (call-interactively 'org-self-insert-command)))))
16894 ((and
16895 (org-table-p)
16896 (progn
16897 ;; check if we blank the field, and if that triggers align
16898 (and (featurep 'org-table) org-table-auto-blank-field
16899 (member last-command
16900 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
16901 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
16902 ;; got extra space, this field does not determine column width
16903 (let (org-table-may-need-update) (org-table-blank-field))
16904 ;; no extra space, this field may determine column width
16905 (org-table-blank-field)))
16907 (eq N 1)
16908 (looking-at "[^|\n]* |"))
16909 (let (org-table-may-need-update)
16910 (goto-char (1- (match-end 0)))
16911 (delete-backward-char 1)
16912 (goto-char (match-beginning 0))
16913 (self-insert-command N)))
16915 (setq org-table-may-need-update t)
16916 (self-insert-command N)
16917 (org-fix-tags-on-the-fly)
16918 (if org-self-insert-cluster-for-undo
16919 (if (not (eq last-command 'org-self-insert-command))
16920 (setq org-self-insert-command-undo-counter 1)
16921 (if (>= org-self-insert-command-undo-counter 20)
16922 (setq org-self-insert-command-undo-counter 1)
16923 (and (> org-self-insert-command-undo-counter 0)
16924 buffer-undo-list
16925 (not (cadr buffer-undo-list)) ; remove nil entry
16926 (setcdr buffer-undo-list (cddr buffer-undo-list)))
16927 (setq org-self-insert-command-undo-counter
16928 (1+ org-self-insert-command-undo-counter))))))))
16930 (defun org-fix-tags-on-the-fly ()
16931 (when (and (equal (char-after (point-at-bol)) ?*)
16932 (org-on-heading-p))
16933 (org-align-tags-here org-tags-column)))
16935 (defun org-delete-backward-char (N)
16936 "Like `delete-backward-char', insert whitespace at field end in tables.
16937 When deleting backwards, in tables this function will insert whitespace in
16938 front of the next \"|\" separator, to keep the table aligned. The table will
16939 still be marked for re-alignment if the field did fill the entire column,
16940 because, in this case the deletion might narrow the column."
16941 (interactive "p")
16942 (if (and (org-table-p)
16943 (eq N 1)
16944 (string-match "|" (buffer-substring (point-at-bol) (point)))
16945 (looking-at ".*?|"))
16946 (let ((pos (point))
16947 (noalign (looking-at "[^|\n\r]* |"))
16948 (c org-table-may-need-update))
16949 (backward-delete-char N)
16950 (if (not overwrite-mode)
16951 (progn
16952 (skip-chars-forward "^|")
16953 (insert " ")
16954 (goto-char (1- pos))))
16955 ;; noalign: if there were two spaces at the end, this field
16956 ;; does not determine the width of the column.
16957 (if noalign (setq org-table-may-need-update c)))
16958 (backward-delete-char N)
16959 (org-fix-tags-on-the-fly)))
16961 (defun org-delete-char (N)
16962 "Like `delete-char', but insert whitespace at field end in tables.
16963 When deleting characters, in tables this function will insert whitespace in
16964 front of the next \"|\" separator, to keep the table aligned. The table will
16965 still be marked for re-alignment if the field did fill the entire column,
16966 because, in this case the deletion might narrow the column."
16967 (interactive "p")
16968 (if (and (org-table-p)
16969 (not (bolp))
16970 (not (= (char-after) ?|))
16971 (eq N 1))
16972 (if (looking-at ".*?|")
16973 (let ((pos (point))
16974 (noalign (looking-at "[^|\n\r]* |"))
16975 (c org-table-may-need-update))
16976 (replace-match (concat
16977 (substring (match-string 0) 1 -1)
16978 " |"))
16979 (goto-char pos)
16980 ;; noalign: if there were two spaces at the end, this field
16981 ;; does not determine the width of the column.
16982 (if noalign (setq org-table-may-need-update c)))
16983 (delete-char N))
16984 (delete-char N)
16985 (org-fix-tags-on-the-fly)))
16987 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
16988 (put 'org-self-insert-command 'delete-selection t)
16989 (put 'orgtbl-self-insert-command 'delete-selection t)
16990 (put 'org-delete-char 'delete-selection 'supersede)
16991 (put 'org-delete-backward-char 'delete-selection 'supersede)
16992 (put 'org-yank 'delete-selection 'yank)
16994 ;; Make `flyspell-mode' delay after some commands
16995 (put 'org-self-insert-command 'flyspell-delayed t)
16996 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
16997 (put 'org-delete-char 'flyspell-delayed t)
16998 (put 'org-delete-backward-char 'flyspell-delayed t)
17000 ;; Make pabbrev-mode expand after org-mode commands
17001 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
17002 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
17004 ;; How to do this: Measure non-white length of current string
17005 ;; If equal to column width, we should realign.
17007 (defun org-remap (map &rest commands)
17008 "In MAP, remap the functions given in COMMANDS.
17009 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
17010 (let (new old)
17011 (while commands
17012 (setq old (pop commands) new (pop commands))
17013 (if (fboundp 'command-remapping)
17014 (org-defkey map (vector 'remap old) new)
17015 (substitute-key-definition old new map global-map)))))
17017 (when (eq org-enable-table-editor 'optimized)
17018 ;; If the user wants maximum table support, we need to hijack
17019 ;; some standard editing functions
17020 (org-remap org-mode-map
17021 'self-insert-command 'org-self-insert-command
17022 'delete-char 'org-delete-char
17023 'delete-backward-char 'org-delete-backward-char)
17024 (org-defkey org-mode-map "|" 'org-force-self-insert))
17026 (defvar org-ctrl-c-ctrl-c-hook nil
17027 "Hook for functions attaching themselves to `C-c C-c'.
17028 This can be used to add additional functionality to the C-c C-c key which
17029 executes context-dependent commands.
17030 Each function will be called with no arguments. The function must check
17031 if the context is appropriate for it to act. If yes, it should do its
17032 thing and then return a non-nil value. If the context is wrong,
17033 just do nothing and return nil.")
17035 (defvar org-tab-first-hook nil
17036 "Hook for functions to attach themselves to TAB.
17037 See `org-ctrl-c-ctrl-c-hook' for more information.
17038 This hook runs as the first action when TAB is pressed, even before
17039 `org-cycle' messes around with the `outline-regexp' to cater for
17040 inline tasks and plain list item folding.
17041 If any function in this hook returns t, any other actions that
17042 would have been caused by TAB (such as table field motion or visibility
17043 cycling) will not occur.")
17045 (defvar org-tab-after-check-for-table-hook nil
17046 "Hook for functions to attach themselves to TAB.
17047 See `org-ctrl-c-ctrl-c-hook' for more information.
17048 This hook runs after it has been established that the cursor is not in a
17049 table, but before checking if the cursor is in a headline or if global cycling
17050 should be done.
17051 If any function in this hook returns t, not other actions like visibility
17052 cycling will be done.")
17054 (defvar org-tab-after-check-for-cycling-hook nil
17055 "Hook for functions to attach themselves to TAB.
17056 See `org-ctrl-c-ctrl-c-hook' for more information.
17057 This hook runs after it has been established that not table field motion and
17058 not visibility should be done because of current context. This is probably
17059 the place where a package like yasnippets can hook in.")
17061 (defvar org-tab-before-tab-emulation-hook nil
17062 "Hook for functions to attach themselves to TAB.
17063 See `org-ctrl-c-ctrl-c-hook' for more information.
17064 This hook runs after every other options for TAB have been exhausted, but
17065 before indentation and \t insertion takes place.")
17067 (defvar org-metaleft-hook nil
17068 "Hook for functions attaching themselves to `M-left'.
17069 See `org-ctrl-c-ctrl-c-hook' for more information.")
17070 (defvar org-metaright-hook nil
17071 "Hook for functions attaching themselves to `M-right'.
17072 See `org-ctrl-c-ctrl-c-hook' for more information.")
17073 (defvar org-metaup-hook nil
17074 "Hook for functions attaching themselves to `M-up'.
17075 See `org-ctrl-c-ctrl-c-hook' for more information.")
17076 (defvar org-metadown-hook nil
17077 "Hook for functions attaching themselves to `M-down'.
17078 See `org-ctrl-c-ctrl-c-hook' for more information.")
17079 (defvar org-shiftmetaleft-hook nil
17080 "Hook for functions attaching themselves to `M-S-left'.
17081 See `org-ctrl-c-ctrl-c-hook' for more information.")
17082 (defvar org-shiftmetaright-hook nil
17083 "Hook for functions attaching themselves to `M-S-right'.
17084 See `org-ctrl-c-ctrl-c-hook' for more information.")
17085 (defvar org-shiftmetaup-hook nil
17086 "Hook for functions attaching themselves to `M-S-up'.
17087 See `org-ctrl-c-ctrl-c-hook' for more information.")
17088 (defvar org-shiftmetadown-hook nil
17089 "Hook for functions attaching themselves to `M-S-down'.
17090 See `org-ctrl-c-ctrl-c-hook' for more information.")
17091 (defvar org-metareturn-hook nil
17092 "Hook for functions attaching themselves to `M-RET'.
17093 See `org-ctrl-c-ctrl-c-hook' for more information.")
17094 (defvar org-shiftup-hook nil
17095 "Hook for functions attaching themselves to `S-up'.
17096 See `org-ctrl-c-ctrl-c-hook' for more information.")
17097 (defvar org-shiftup-final-hook nil
17098 "Hook for functions attaching themselves to `S-up'.
17099 This one runs after all other options except shift-select have been excluded.
17100 See `org-ctrl-c-ctrl-c-hook' for more information.")
17101 (defvar org-shiftdown-hook nil
17102 "Hook for functions attaching themselves to `S-down'.
17103 See `org-ctrl-c-ctrl-c-hook' for more information.")
17104 (defvar org-shiftdown-final-hook nil
17105 "Hook for functions attaching themselves to `S-down'.
17106 This one runs after all other options except shift-select have been excluded.
17107 See `org-ctrl-c-ctrl-c-hook' for more information.")
17108 (defvar org-shiftleft-hook nil
17109 "Hook for functions attaching themselves to `S-left'.
17110 See `org-ctrl-c-ctrl-c-hook' for more information.")
17111 (defvar org-shiftleft-final-hook nil
17112 "Hook for functions attaching themselves to `S-left'.
17113 This one runs after all other options except shift-select have been excluded.
17114 See `org-ctrl-c-ctrl-c-hook' for more information.")
17115 (defvar org-shiftright-hook nil
17116 "Hook for functions attaching themselves to `S-right'.
17117 See `org-ctrl-c-ctrl-c-hook' for more information.")
17118 (defvar org-shiftright-final-hook nil
17119 "Hook for functions attaching themselves to `S-right'.
17120 This one runs after all other options except shift-select have been excluded.
17121 See `org-ctrl-c-ctrl-c-hook' for more information.")
17123 (defun org-modifier-cursor-error ()
17124 "Throw an error, a modified cursor command was applied in wrong context."
17125 (error "This command is active in special context like tables, headlines or items"))
17127 (defun org-shiftselect-error ()
17128 "Throw an error because Shift-Cursor command was applied in wrong context."
17129 (if (and (boundp 'shift-select-mode) shift-select-mode)
17130 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
17131 (error "This command works only in special context like headlines or timestamps")))
17133 (defun org-call-for-shift-select (cmd)
17134 (let ((this-command-keys-shift-translated t))
17135 (call-interactively cmd)))
17137 (defun org-shifttab (&optional arg)
17138 "Global visibility cycling or move to previous table field.
17139 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
17140 on context.
17141 See the individual commands for more information."
17142 (interactive "P")
17143 (cond
17144 ((org-at-table-p) (call-interactively 'org-table-previous-field))
17145 ((integerp arg)
17146 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
17147 (message "Content view to level: %d" arg)
17148 (org-content (prefix-numeric-value arg2))
17149 (setq org-cycle-global-status 'overview)))
17150 (t (call-interactively 'org-global-cycle))))
17152 (defun org-shiftmetaleft ()
17153 "Promote subtree or delete table column.
17154 Calls `org-promote-subtree', `org-outdent-item',
17155 or `org-table-delete-column', depending on context.
17156 See the individual commands for more information."
17157 (interactive)
17158 (cond
17159 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
17160 ((org-at-table-p) (call-interactively 'org-table-delete-column))
17161 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
17162 ((org-at-item-p) (call-interactively 'org-outdent-item-tree))
17163 (t (org-modifier-cursor-error))))
17165 (defun org-shiftmetaright ()
17166 "Demote subtree or insert table column.
17167 Calls `org-demote-subtree', `org-indent-item',
17168 or `org-table-insert-column', depending on context.
17169 See the individual commands for more information."
17170 (interactive)
17171 (cond
17172 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
17173 ((org-at-table-p) (call-interactively 'org-table-insert-column))
17174 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
17175 ((org-at-item-p) (call-interactively 'org-indent-item-tree))
17176 (t (org-modifier-cursor-error))))
17178 (defun org-shiftmetaup (&optional arg)
17179 "Move subtree up or kill table row.
17180 Calls `org-move-subtree-up' or `org-table-kill-row' or
17181 `org-move-item-up' depending on context. See the individual commands
17182 for more information."
17183 (interactive "P")
17184 (cond
17185 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
17186 ((org-at-table-p) (call-interactively 'org-table-kill-row))
17187 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
17188 ((org-at-item-p) (call-interactively 'org-move-item-up))
17189 (t (org-modifier-cursor-error))))
17191 (defun org-shiftmetadown (&optional arg)
17192 "Move subtree down or insert table row.
17193 Calls `org-move-subtree-down' or `org-table-insert-row' or
17194 `org-move-item-down', depending on context. See the individual
17195 commands for more information."
17196 (interactive "P")
17197 (cond
17198 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
17199 ((org-at-table-p) (call-interactively 'org-table-insert-row))
17200 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
17201 ((org-at-item-p) (call-interactively 'org-move-item-down))
17202 (t (org-modifier-cursor-error))))
17204 (defsubst org-hidden-tree-error ()
17205 (error
17206 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
17208 (defun org-metaleft (&optional arg)
17209 "Promote heading or move table column to left.
17210 Calls `org-do-promote' or `org-table-move-column', depending on context.
17211 With no specific context, calls the Emacs default `backward-word'.
17212 See the individual commands for more information."
17213 (interactive "P")
17214 (cond
17215 ((run-hook-with-args-until-success 'org-metaleft-hook))
17216 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
17217 ((org-with-limited-levels
17218 (or (org-on-heading-p)
17219 (and (org-region-active-p)
17220 (save-excursion
17221 (goto-char (region-beginning))
17222 (org-on-heading-p)))))
17223 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
17224 (call-interactively 'org-do-promote))
17225 ;; At an inline task.
17226 ((org-on-heading-p)
17227 (call-interactively 'org-inlinetask-promote))
17228 ((or (org-at-item-p)
17229 (and (org-region-active-p)
17230 (save-excursion
17231 (goto-char (region-beginning))
17232 (org-at-item-p))))
17233 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
17234 (call-interactively 'org-outdent-item))
17235 (t (call-interactively 'backward-word))))
17237 (defun org-metaright (&optional arg)
17238 "Demote subtree or move table column to right.
17239 Calls `org-do-demote' or `org-table-move-column', depending on context.
17240 With no specific context, calls the Emacs default `forward-word'.
17241 See the individual commands for more information."
17242 (interactive "P")
17243 (cond
17244 ((run-hook-with-args-until-success 'org-metaright-hook))
17245 ((org-at-table-p) (call-interactively 'org-table-move-column))
17246 ((org-with-limited-levels
17247 (or (org-on-heading-p)
17248 (and (org-region-active-p)
17249 (save-excursion
17250 (goto-char (region-beginning))
17251 (org-on-heading-p)))))
17252 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
17253 (call-interactively 'org-do-demote))
17254 ;; At an inline task.
17255 ((org-on-heading-p)
17256 (call-interactively 'org-inlinetask-demote))
17257 ((or (org-at-item-p)
17258 (and (org-region-active-p)
17259 (save-excursion
17260 (goto-char (region-beginning))
17261 (org-at-item-p))))
17262 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
17263 (call-interactively 'org-indent-item))
17264 (t (call-interactively 'forward-word))))
17266 (defun org-check-for-hidden (what)
17267 "Check if there are hidden headlines/items in the current visual line.
17268 WHAT can be either `headlines' or `items'. If the current line is
17269 an outline or item heading and it has a folded subtree below it,
17270 this function returns t, nil otherwise."
17271 (let ((re (cond
17272 ((eq what 'headlines) (concat "^" org-outline-regexp))
17273 ((eq what 'items) (org-item-beginning-re))
17274 (t (error "This should not happen"))))
17275 beg end)
17276 (save-excursion
17277 (catch 'exit
17278 (unless (org-region-active-p)
17279 (setq beg (point-at-bol))
17280 (beginning-of-line 2)
17281 (while (and (not (eobp)) ;; this is like `next-line'
17282 (get-char-property (1- (point)) 'invisible))
17283 (beginning-of-line 2))
17284 (setq end (point))
17285 (goto-char beg)
17286 (goto-char (point-at-eol))
17287 (setq end (max end (point)))
17288 (while (re-search-forward re end t)
17289 (if (get-char-property (match-beginning 0) 'invisible)
17290 (throw 'exit t))))
17291 nil))))
17293 (defun org-metaup (&optional arg)
17294 "Move subtree up or move table row up.
17295 Calls `org-move-subtree-up' or `org-table-move-row' or
17296 `org-move-item-up', depending on context. See the individual commands
17297 for more information."
17298 (interactive "P")
17299 (cond
17300 ((run-hook-with-args-until-success 'org-metaup-hook))
17301 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
17302 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
17303 ((org-at-item-p) (call-interactively 'org-move-item-up))
17304 (t (transpose-lines 1) (beginning-of-line -1))))
17306 (defun org-metadown (&optional arg)
17307 "Move subtree down or move table row down.
17308 Calls `org-move-subtree-down' or `org-table-move-row' or
17309 `org-move-item-down', depending on context. See the individual
17310 commands for more information."
17311 (interactive "P")
17312 (cond
17313 ((run-hook-with-args-until-success 'org-metadown-hook))
17314 ((org-at-table-p) (call-interactively 'org-table-move-row))
17315 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
17316 ((org-at-item-p) (call-interactively 'org-move-item-down))
17317 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
17319 (defun org-shiftup (&optional arg)
17320 "Increase item in timestamp or increase priority of current headline.
17321 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
17322 depending on context. See the individual commands for more information."
17323 (interactive "P")
17324 (cond
17325 ((run-hook-with-args-until-success 'org-shiftup-hook))
17326 ((and org-support-shift-select (org-region-active-p))
17327 (org-call-for-shift-select 'previous-line))
17328 ((org-at-timestamp-p t)
17329 (call-interactively (if org-edit-timestamp-down-means-later
17330 'org-timestamp-down 'org-timestamp-up)))
17331 ((and (not (eq org-support-shift-select 'always))
17332 org-enable-priority-commands
17333 (org-on-heading-p))
17334 (call-interactively 'org-priority-up))
17335 ((and (not org-support-shift-select) (org-at-item-p))
17336 (call-interactively 'org-previous-item))
17337 ((org-clocktable-try-shift 'up arg))
17338 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
17339 (org-support-shift-select
17340 (org-call-for-shift-select 'previous-line))
17341 (t (org-shiftselect-error))))
17343 (defun org-shiftdown (&optional arg)
17344 "Decrease item in timestamp or decrease priority of current headline.
17345 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
17346 depending on context. See the individual commands for more information."
17347 (interactive "P")
17348 (cond
17349 ((run-hook-with-args-until-success 'org-shiftdown-hook))
17350 ((and org-support-shift-select (org-region-active-p))
17351 (org-call-for-shift-select 'next-line))
17352 ((org-at-timestamp-p t)
17353 (call-interactively (if org-edit-timestamp-down-means-later
17354 'org-timestamp-up 'org-timestamp-down)))
17355 ((and (not (eq org-support-shift-select 'always))
17356 org-enable-priority-commands
17357 (org-on-heading-p))
17358 (call-interactively 'org-priority-down))
17359 ((and (not org-support-shift-select) (org-at-item-p))
17360 (call-interactively 'org-next-item))
17361 ((org-clocktable-try-shift 'down arg))
17362 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
17363 (org-support-shift-select
17364 (org-call-for-shift-select 'next-line))
17365 (t (org-shiftselect-error))))
17367 (defun org-shiftright (&optional arg)
17368 "Cycle the thing at point or in the current line, depending on context.
17369 Depending on context, this does one of the following:
17371 - switch a timestamp at point one day into the future
17372 - on a headline, switch to the next TODO keyword.
17373 - on an item, switch entire list to the next bullet type
17374 - on a property line, switch to the next allowed value
17375 - on a clocktable definition line, move time block into the future"
17376 (interactive "P")
17377 (cond
17378 ((run-hook-with-args-until-success 'org-shiftright-hook))
17379 ((and org-support-shift-select (org-region-active-p))
17380 (org-call-for-shift-select 'forward-char))
17381 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
17382 ((and (not (eq org-support-shift-select 'always))
17383 (org-on-heading-p))
17384 (let ((org-inhibit-logging
17385 (not org-treat-S-cursor-todo-selection-as-state-change))
17386 (org-inhibit-blocking
17387 (not org-treat-S-cursor-todo-selection-as-state-change)))
17388 (org-call-with-arg 'org-todo 'right)))
17389 ((or (and org-support-shift-select
17390 (not (eq org-support-shift-select 'always))
17391 (org-at-item-bullet-p))
17392 (and (not org-support-shift-select) (org-at-item-p)))
17393 (org-call-with-arg 'org-cycle-list-bullet nil))
17394 ((and (not (eq org-support-shift-select 'always))
17395 (org-at-property-p))
17396 (call-interactively 'org-property-next-allowed-value))
17397 ((org-clocktable-try-shift 'right arg))
17398 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
17399 (org-support-shift-select
17400 (org-call-for-shift-select 'forward-char))
17401 (t (org-shiftselect-error))))
17403 (defun org-shiftleft (&optional arg)
17404 "Cycle the thing at point or in the current line, depending on context.
17405 Depending on context, this does one of the following:
17407 - switch a timestamp at point one day into the past
17408 - on a headline, switch to the previous TODO keyword.
17409 - on an item, switch entire list to the previous bullet type
17410 - on a property line, switch to the previous allowed value
17411 - on a clocktable definition line, move time block into the past"
17412 (interactive "P")
17413 (cond
17414 ((run-hook-with-args-until-success 'org-shiftleft-hook))
17415 ((and org-support-shift-select (org-region-active-p))
17416 (org-call-for-shift-select 'backward-char))
17417 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
17418 ((and (not (eq org-support-shift-select 'always))
17419 (org-on-heading-p))
17420 (let ((org-inhibit-logging
17421 (not org-treat-S-cursor-todo-selection-as-state-change))
17422 (org-inhibit-blocking
17423 (not org-treat-S-cursor-todo-selection-as-state-change)))
17424 (org-call-with-arg 'org-todo 'left)))
17425 ((or (and org-support-shift-select
17426 (not (eq org-support-shift-select 'always))
17427 (org-at-item-bullet-p))
17428 (and (not org-support-shift-select) (org-at-item-p)))
17429 (org-call-with-arg 'org-cycle-list-bullet 'previous))
17430 ((and (not (eq org-support-shift-select 'always))
17431 (org-at-property-p))
17432 (call-interactively 'org-property-previous-allowed-value))
17433 ((org-clocktable-try-shift 'left arg))
17434 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
17435 (org-support-shift-select
17436 (org-call-for-shift-select 'backward-char))
17437 (t (org-shiftselect-error))))
17439 (defun org-shiftcontrolright ()
17440 "Switch to next TODO set."
17441 (interactive)
17442 (cond
17443 ((and org-support-shift-select (org-region-active-p))
17444 (org-call-for-shift-select 'forward-word))
17445 ((and (not (eq org-support-shift-select 'always))
17446 (org-on-heading-p))
17447 (org-call-with-arg 'org-todo 'nextset))
17448 (org-support-shift-select
17449 (org-call-for-shift-select 'forward-word))
17450 (t (org-shiftselect-error))))
17452 (defun org-shiftcontrolleft ()
17453 "Switch to previous TODO set."
17454 (interactive)
17455 (cond
17456 ((and org-support-shift-select (org-region-active-p))
17457 (org-call-for-shift-select 'backward-word))
17458 ((and (not (eq org-support-shift-select 'always))
17459 (org-on-heading-p))
17460 (org-call-with-arg 'org-todo 'previousset))
17461 (org-support-shift-select
17462 (org-call-for-shift-select 'backward-word))
17463 (t (org-shiftselect-error))))
17465 (defun org-ctrl-c-ret ()
17466 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
17467 (interactive)
17468 (cond
17469 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
17470 (t (call-interactively 'org-insert-heading))))
17472 (defun org-copy-special ()
17473 "Copy region in table or copy current subtree.
17474 Calls `org-table-copy' or `org-copy-subtree', depending on context.
17475 See the individual commands for more information."
17476 (interactive)
17477 (call-interactively
17478 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
17480 (defun org-cut-special ()
17481 "Cut region in table or cut current subtree.
17482 Calls `org-table-copy' or `org-cut-subtree', depending on context.
17483 See the individual commands for more information."
17484 (interactive)
17485 (call-interactively
17486 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
17488 (defun org-paste-special (arg)
17489 "Paste rectangular region into table, or past subtree relative to level.
17490 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
17491 See the individual commands for more information."
17492 (interactive "P")
17493 (if (org-at-table-p)
17494 (org-table-paste-rectangle)
17495 (org-paste-subtree arg)))
17497 (defun org-edit-special (&optional arg)
17498 "Call a special editor for the stuff at point.
17499 When at a table, call the formula editor with `org-table-edit-formulas'.
17500 When at the first line of an src example, call `org-edit-src-code'.
17501 When in an #+include line, visit the include file. Otherwise call
17502 `ffap' to visit the file at point."
17503 (interactive)
17504 ;; possibly prep session before editing source
17505 (when arg
17506 (let* ((info (org-babel-get-src-block-info))
17507 (lang (nth 0 info))
17508 (params (nth 2 info))
17509 (session (cdr (assoc :session params))))
17510 (when (and info session) ;; we are in a source-code block with a session
17511 (funcall
17512 (intern (concat "org-babel-prep-session:" lang)) session params))))
17513 (cond ;; proceed with `org-edit-special'
17514 ((save-excursion
17515 (beginning-of-line 1)
17516 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
17517 (find-file (org-trim (match-string 1))))
17518 ((org-edit-src-code))
17519 ((org-edit-fixed-width-region))
17520 ((org-at-table.el-p)
17521 (org-edit-src-code))
17522 ((or (org-at-table-p)
17523 (save-excursion
17524 (beginning-of-line 1)
17525 (looking-at "[ \t]*#\\+TBLFM:")))
17526 (call-interactively 'org-table-edit-formulas))
17527 (t (call-interactively 'ffap))))
17529 (defun org-ctrl-c-ctrl-c (&optional arg)
17530 "Set tags in headline, or update according to changed information at point.
17532 This command does many different things, depending on context:
17534 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
17535 this is what we do.
17537 - If the cursor is on a statistics cookie, update it.
17539 - If the cursor is in a headline, prompt for tags and insert them
17540 into the current line, aligned to `org-tags-column'. When called
17541 with prefix arg, realign all tags in the current buffer.
17543 - If the cursor is in one of the special #+KEYWORD lines, this
17544 triggers scanning the buffer for these lines and updating the
17545 information.
17547 - If the cursor is inside a table, realign the table. This command
17548 works even if the automatic table editor has been turned off.
17550 - If the cursor is on a #+TBLFM line, re-apply the formulas to
17551 the entire table.
17553 - If the cursor is at a footnote reference or definition, jump to
17554 the corresponding definition or references, respectively.
17556 - If the cursor is a the beginning of a dynamic block, update it.
17558 - If the current buffer is a capture buffer, close note and file it.
17560 - If the cursor is on a <<<target>>>, update radio targets and
17561 corresponding links in this buffer.
17563 - If the cursor is on a numbered item in a plain list, renumber the
17564 ordered list.
17566 - If the cursor is on a checkbox, toggle it.
17568 - If the cursor is on a code block, evaluate it. The variable
17569 `org-confirm-babel-evaluate' can be used to control prompting
17570 before code block evaluation, by default every code block
17571 evaluation requires confirmation. Code block evaluation can be
17572 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
17573 (interactive "P")
17574 (let ((org-enable-table-editor t))
17575 (cond
17576 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
17577 org-occur-highlights
17578 org-latex-fragment-image-overlays)
17579 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
17580 (org-remove-occur-highlights)
17581 (org-remove-latex-fragment-image-overlays)
17582 (message "Temporary highlights/overlays removed from current buffer"))
17583 ((and (local-variable-p 'org-finish-function (current-buffer))
17584 (fboundp org-finish-function))
17585 (funcall org-finish-function))
17586 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
17587 ((or (looking-at org-property-start-re)
17588 (org-at-property-p))
17589 (call-interactively 'org-property-action))
17590 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
17591 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
17592 (or (org-on-heading-p) (org-at-item-p)))
17593 (call-interactively 'org-update-statistics-cookies))
17594 ((org-on-heading-p) (call-interactively 'org-set-tags))
17595 ((org-at-table.el-p)
17596 (message "Use C-c ' to edit table.el tables"))
17597 ((org-at-table-p)
17598 (org-table-maybe-eval-formula)
17599 (if arg
17600 (call-interactively 'org-table-recalculate)
17601 (org-table-maybe-recalculate-line))
17602 (call-interactively 'org-table-align)
17603 (orgtbl-send-table 'maybe))
17604 ((or (org-footnote-at-reference-p)
17605 (org-footnote-at-definition-p))
17606 (call-interactively 'org-footnote-action))
17607 ((org-at-item-checkbox-p)
17608 ;; Cursor at a checkbox: repair list and update checkboxes. Send
17609 ;; list only if at top item.
17610 (let* ((cbox (match-string 1))
17611 (struct (org-list-struct))
17612 (old-struct (copy-tree struct))
17613 (parents (org-list-parents-alist struct))
17614 (prevs (org-list-prevs-alist struct))
17615 (orderedp (org-entry-get nil "ORDERED"))
17616 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
17617 block-item)
17618 ;; Use a light version of `org-toggle-checkbox' to avoid
17619 ;; computing list structure twice.
17620 (org-list-set-checkbox (point-at-bol) struct
17621 (cond
17622 ((equal arg '(16)) "[-]")
17623 ((equal arg '(4)) nil)
17624 ((equal "[X]" cbox) "[ ]")
17625 (t "[X]")))
17626 (org-list-struct-fix-ind struct parents)
17627 (org-list-struct-fix-bul struct prevs)
17628 (setq block-item
17629 (org-list-struct-fix-box struct parents prevs orderedp))
17630 (when block-item
17631 (message
17632 "Checkboxes were removed due to unchecked box at line %d"
17633 (org-current-line block-item)))
17634 (org-list-struct-apply-struct struct old-struct)
17635 (org-update-checkbox-count-maybe)
17636 (when firstp (org-list-send-list 'maybe))))
17637 ((org-at-item-p)
17638 ;; Cursor at an item: repair list. Do checkbox related actions
17639 ;; only if function was called with an argument. Send list only
17640 ;; if at top item.
17641 (let* ((struct (org-list-struct))
17642 (old-struct (copy-tree struct))
17643 (parents (org-list-parents-alist struct))
17644 (prevs (org-list-prevs-alist struct))
17645 (firstp (= (org-list-get-top-point struct) (point-at-bol))))
17646 (org-list-struct-fix-ind struct parents)
17647 (org-list-struct-fix-bul struct prevs)
17648 (when arg
17649 (org-list-set-checkbox (point-at-bol) struct "[ ]")
17650 (org-list-struct-fix-box struct parents prevs))
17651 (org-list-struct-apply-struct struct old-struct)
17652 (when arg (org-update-checkbox-count-maybe))
17653 (when firstp (org-list-send-list 'maybe))))
17654 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
17655 ;; Dynamic block
17656 (beginning-of-line 1)
17657 (save-excursion (org-update-dblock)))
17658 ((save-excursion
17659 (beginning-of-line 1)
17660 (looking-at "[ \t]*#\\+\\([A-Z]+\\)"))
17661 (cond
17662 ((equal (match-string 1) "TBLFM")
17663 ;; Recalculate the table before this line
17664 (save-excursion
17665 (beginning-of-line 1)
17666 (skip-chars-backward " \r\n\t")
17667 (if (org-at-table-p)
17668 (org-call-with-arg 'org-table-recalculate (or arg t)))))
17670 (let ((org-inhibit-startup-visibility-stuff t)
17671 (org-startup-align-all-tables nil))
17672 (org-save-outline-visibility 'use-markers (org-mode-restart)))
17673 (message "Local setup has been refreshed"))))
17674 ((org-clock-update-time-maybe))
17675 (t (error "C-c C-c can do nothing useful at this location")))))
17677 (defun org-mode-restart ()
17678 "Restart Org-mode, to scan again for special lines.
17679 Also updates the keyword regular expressions."
17680 (interactive)
17681 (org-mode)
17682 (message "Org-mode restarted"))
17684 (defun org-kill-note-or-show-branches ()
17685 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
17686 (interactive)
17687 (if (not org-finish-function)
17688 (progn
17689 (hide-subtree)
17690 (call-interactively 'show-branches))
17691 (let ((org-note-abort t))
17692 (funcall org-finish-function))))
17694 (defun org-return (&optional indent)
17695 "Goto next table row or insert a newline.
17696 Calls `org-table-next-row' or `newline', depending on context.
17697 See the individual commands for more information."
17698 (interactive)
17699 (cond
17700 ((bobp) (if indent (newline-and-indent) (newline)))
17701 ((org-at-table-p)
17702 (org-table-justify-field-maybe)
17703 (call-interactively 'org-table-next-row))
17704 ;; when `newline-and-indent' is called within a list, make sure
17705 ;; text moved stays inside the item.
17706 ((and (org-in-item-p) indent)
17707 (if (and (org-at-item-p) (>= (point) (match-end 0)))
17708 (progn
17709 (newline)
17710 (org-indent-line-to (length (match-string 0))))
17711 (let ((ind (org-get-indentation)))
17712 (newline)
17713 (if (org-looking-back org-list-end-re)
17714 (org-indent-line-function)
17715 (org-indent-line-to ind)))))
17716 ((and org-return-follows-link
17717 (eq (get-text-property (point) 'face) 'org-link))
17718 (call-interactively 'org-open-at-point))
17719 ((and (org-at-heading-p)
17720 (looking-at
17721 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
17722 (org-show-entry)
17723 (end-of-line 1)
17724 (newline))
17725 (t (if indent (newline-and-indent) (newline)))))
17727 (defun org-return-indent ()
17728 "Goto next table row or insert a newline and indent.
17729 Calls `org-table-next-row' or `newline-and-indent', depending on
17730 context. See the individual commands for more information."
17731 (interactive)
17732 (org-return t))
17734 (defun org-ctrl-c-star ()
17735 "Compute table, or change heading status of lines.
17736 Calls `org-table-recalculate' or `org-toggle-heading',
17737 depending on context."
17738 (interactive)
17739 (cond
17740 ((org-at-table-p)
17741 (call-interactively 'org-table-recalculate))
17743 ;; Convert all lines in region to list items
17744 (call-interactively 'org-toggle-heading))))
17746 (defun org-ctrl-c-minus ()
17747 "Insert separator line in table or modify bullet status of line.
17748 Also turns a plain line or a region of lines into list items.
17749 Calls `org-table-insert-hline', `org-toggle-item', or
17750 `org-cycle-list-bullet', depending on context."
17751 (interactive)
17752 (cond
17753 ((org-at-table-p)
17754 (call-interactively 'org-table-insert-hline))
17755 ((org-region-active-p)
17756 (call-interactively 'org-toggle-item))
17757 ((org-in-item-p)
17758 (call-interactively 'org-cycle-list-bullet))
17760 (call-interactively 'org-toggle-item))))
17762 (defun org-toggle-item (arg)
17763 "Convert headings or normal lines to items, items to normal lines.
17764 If there is no active region, only the current line is considered.
17766 If the first non blank line in the region is an headline, convert
17767 all headlines to items.
17769 If it is an item, convert all items to normal lines.
17771 If it is normal text, change region into an item. With a prefix
17772 argument ARG, change each line in region into an item."
17773 (interactive "P")
17774 (let (l2 l beg end)
17775 (if (org-region-active-p)
17776 (setq beg (region-beginning) end (region-end))
17777 (setq beg (point-at-bol)
17778 end (min (1+ (point-at-eol)) (point-max))))
17779 (org-with-limited-levels
17780 (save-excursion
17781 (goto-char end)
17782 (setq l2 (org-current-line))
17783 (goto-char beg)
17784 (beginning-of-line 1)
17785 ;; Ignore blank lines at beginning of region
17786 (skip-chars-forward " \t\r\n")
17787 (beginning-of-line 1)
17788 (setq l (1- (org-current-line)))
17789 (cond
17790 ;; Case 1. Start at an item: de-itemize.
17791 ((org-at-item-p)
17792 (while (< (setq l (1+ l)) l2)
17793 (when (org-at-item-p)
17794 (skip-chars-forward " \t")
17795 (delete-region (point) (match-end 0)))
17796 (beginning-of-line 2)))
17797 ;; Case 2. Start an an heading: convert to items.
17798 ((org-on-heading-p)
17799 (let* ((bul (org-list-bullet-string "-"))
17800 (len (length bul))
17801 (ind 0) (level 0))
17802 (while (< (setq l (1+ l)) l2)
17803 (cond
17804 ((looking-at outline-regexp)
17805 (let* ((lvl (org-reduced-level
17806 (- (length (match-string 0)) 2)))
17807 (s (concat (make-string (* len lvl) ? ) bul)))
17808 (replace-match s t t)
17809 (setq ind (length s) level lvl)))
17810 ;; Ignore blank lines and inline tasks.
17811 ((looking-at "^[ \t]*$"))
17812 ((looking-at "^\\*+ "))
17813 ;; Ensure normal text belongs to the new item.
17814 (t (org-indent-line-to (+ (max (- (org-get-indentation) level 2) 0)
17815 ind))))
17816 (beginning-of-line 2))))
17817 ;; Case 3. Normal line with ARG: turn each of them into items
17818 ;; unless they are already one.
17819 (arg
17820 (while (< (setq l (1+ l)) l2)
17821 (unless (or (org-on-heading-p) (org-at-item-p))
17822 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
17823 (replace-match
17824 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
17825 (beginning-of-line 2)))
17826 ;; Case 4. Normal line without ARG: make the first line of
17827 ;; region an item, and shift indentation of others
17828 ;; lines to set them as item's body.
17829 (t (let* ((bul (org-list-bullet-string "-"))
17830 (bul-len (length bul))
17831 (ref-ind (org-get-indentation)))
17832 (skip-chars-forward " \t")
17833 (insert bul)
17834 (beginning-of-line 2)
17835 (while (and (< (setq l (1+ l)) l2) (< (point) end))
17836 ;; Ensure that lines less indented than first one
17837 ;; still get included in item body.
17838 (org-indent-line-to (+ (max ref-ind (org-get-indentation))
17839 bul-len))
17840 (beginning-of-line 2)))))))))
17842 (defun org-toggle-heading (&optional nstars)
17843 "Convert headings to normal text, or items or text to headings.
17844 If there is no active region, only the current line is considered.
17846 If the first non blank line is an headline, remove the stars from
17847 all headlines in the region.
17849 If it is a plain list item, turn all plain list items into headings.
17851 If it is a normal line, turn each and every normal line (i.e. not
17852 an heading or an item) in the region into a heading.
17854 When converting a line into a heading, the number of stars is chosen
17855 such that the lines become children of the current entry. However,
17856 when a prefix argument is given, its value determines the number of
17857 stars to add."
17858 (interactive "P")
17859 (let (l2 l itemp beg end)
17860 (if (org-region-active-p)
17861 (setq beg (region-beginning) end (copy-marker (region-end)))
17862 (setq beg (point-at-bol)
17863 end (min (1+ (point-at-eol)) (point-max))))
17864 ;; Ensure inline tasks don't count as headings.
17865 (org-with-limited-levels
17866 (save-excursion
17867 (goto-char end)
17868 (setq l2 (org-current-line))
17869 (goto-char beg)
17870 (beginning-of-line 1)
17871 ;; Ignore blank lines at beginning of region
17872 (skip-chars-forward " \t\r\n")
17873 (beginning-of-line 1)
17874 (setq l (1- (org-current-line)))
17875 (cond
17876 ;; Case 1. Started at an heading: de-star headings.
17877 ((org-on-heading-p)
17878 (while (< (setq l (1+ l)) l2)
17879 (when (org-on-heading-p t)
17880 (looking-at outline-regexp) (replace-match ""))
17881 (beginning-of-line 2)))
17882 ;; Case 2. Started at an item: change items into headlines.
17883 ((org-at-item-p)
17884 (let ((stars (make-string
17885 (if nstars
17886 (prefix-numeric-value current-prefix-arg)
17887 (or (org-current-level) 0))
17888 ?*)))
17889 (while (< (point) end)
17890 (when (org-at-item-p)
17891 ;; Pay attention to cases when region ends before list.
17892 (let* ((struct (org-list-struct))
17893 (list-end (min (org-list-get-bottom-point struct) end)))
17894 (save-restriction
17895 (narrow-to-region (point) list-end)
17896 (insert
17897 (org-list-to-subtree
17898 (org-list-parse-list t)
17899 '(:istart (concat stars (funcall get-stars depth))
17900 :icount (concat stars
17901 (funcall get-stars depth))))))))
17902 (beginning-of-line 2))))
17903 ;; Case 3. Started at normal text: make every line an heading,
17904 ;; skipping headlines and items.
17905 (t (let* ((stars (make-string
17906 (if nstars
17907 (prefix-numeric-value current-prefix-arg)
17908 (or (org-current-level) 0))
17909 ?*))
17910 (add-stars (cond (nstars "")
17911 ((equal stars "") "*")
17912 (org-odd-levels-only "**")
17913 (t "*")))
17914 (rpl (concat stars add-stars " ")))
17915 (while (< (setq l (1+ l)) l2)
17916 (unless (or (org-on-heading-p) (org-at-item-p))
17917 (when (looking-at "\\([ \t]*\\)\\(\\S-\\)")
17918 (replace-match (concat rpl (match-string 2)))))
17919 (beginning-of-line 2)))))))))
17921 (defun org-meta-return (&optional arg)
17922 "Insert a new heading or wrap a region in a table.
17923 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
17924 See the individual commands for more information."
17925 (interactive "P")
17926 (cond
17927 ((run-hook-with-args-until-success 'org-metareturn-hook))
17928 ((org-at-table-p)
17929 (call-interactively 'org-table-wrap-region))
17930 (t (call-interactively 'org-insert-heading))))
17932 ;;; Menu entries
17934 ;; Define the Org-mode menus
17935 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
17936 '("Tbl"
17937 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
17938 ["Next Field" org-cycle (org-at-table-p)]
17939 ["Previous Field" org-shifttab (org-at-table-p)]
17940 ["Next Row" org-return (org-at-table-p)]
17941 "--"
17942 ["Blank Field" org-table-blank-field (org-at-table-p)]
17943 ["Edit Field" org-table-edit-field (org-at-table-p)]
17944 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
17945 "--"
17946 ("Column"
17947 ["Move Column Left" org-metaleft (org-at-table-p)]
17948 ["Move Column Right" org-metaright (org-at-table-p)]
17949 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
17950 ["Insert Column" org-shiftmetaright (org-at-table-p)])
17951 ("Row"
17952 ["Move Row Up" org-metaup (org-at-table-p)]
17953 ["Move Row Down" org-metadown (org-at-table-p)]
17954 ["Delete Row" org-shiftmetaup (org-at-table-p)]
17955 ["Insert Row" org-shiftmetadown (org-at-table-p)]
17956 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
17957 "--"
17958 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
17959 ("Rectangle"
17960 ["Copy Rectangle" org-copy-special (org-at-table-p)]
17961 ["Cut Rectangle" org-cut-special (org-at-table-p)]
17962 ["Paste Rectangle" org-paste-special (org-at-table-p)]
17963 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
17964 "--"
17965 ("Calculate"
17966 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
17967 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
17968 ["Edit Formulas" org-edit-special (org-at-table-p)]
17969 "--"
17970 ["Recalculate line" org-table-recalculate (org-at-table-p)]
17971 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
17972 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
17973 "--"
17974 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
17975 "--"
17976 ["Sum Column/Rectangle" org-table-sum
17977 (or (org-at-table-p) (org-region-active-p))]
17978 ["Which Column?" org-table-current-column (org-at-table-p)])
17979 ["Debug Formulas"
17980 org-table-toggle-formula-debugger
17981 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
17982 ["Show Col/Row Numbers"
17983 org-table-toggle-coordinate-overlays
17984 :style toggle
17985 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
17986 "--"
17987 ["Create" org-table-create (and (not (org-at-table-p))
17988 org-enable-table-editor)]
17989 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
17990 ["Import from File" org-table-import (not (org-at-table-p))]
17991 ["Export to File" org-table-export (org-at-table-p)]
17992 "--"
17993 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
17995 (easy-menu-define org-org-menu org-mode-map "Org menu"
17996 '("Org"
17997 ("Show/Hide"
17998 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
17999 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
18000 ["Sparse Tree..." org-sparse-tree t]
18001 ["Reveal Context" org-reveal t]
18002 ["Show All" show-all t]
18003 "--"
18004 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
18005 "--"
18006 ["New Heading" org-insert-heading t]
18007 ("Navigate Headings"
18008 ["Up" outline-up-heading t]
18009 ["Next" outline-next-visible-heading t]
18010 ["Previous" outline-previous-visible-heading t]
18011 ["Next Same Level" outline-forward-same-level t]
18012 ["Previous Same Level" outline-backward-same-level t]
18013 "--"
18014 ["Jump" org-goto t])
18015 ("Edit Structure"
18016 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
18017 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
18018 "--"
18019 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
18020 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
18021 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
18022 "--"
18023 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
18024 "--"
18025 ["Promote Heading" org-metaleft (not (org-at-table-p))]
18026 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
18027 ["Demote Heading" org-metaright (not (org-at-table-p))]
18028 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
18029 "--"
18030 ["Sort Region/Children" org-sort (not (org-at-table-p))]
18031 "--"
18032 ["Convert to odd levels" org-convert-to-odd-levels t]
18033 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
18034 ("Editing"
18035 ["Emphasis..." org-emphasize t]
18036 ["Edit Source Example" org-edit-special t]
18037 "--"
18038 ["Footnote new/jump" org-footnote-action t]
18039 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
18040 ("Archive"
18041 ["Archive (default method)" org-archive-subtree-default t]
18042 "--"
18043 ["Move Subtree to Archive file" org-advertized-archive-subtree t]
18044 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
18045 ["Move subtree to Archive sibling" org-archive-to-archive-sibling t]
18047 "--"
18048 ("Hyperlinks"
18049 ["Store Link (Global)" org-store-link t]
18050 ["Find existing link to here" org-occur-link-in-agenda-files t]
18051 ["Insert Link" org-insert-link t]
18052 ["Follow Link" org-open-at-point t]
18053 "--"
18054 ["Next link" org-next-link t]
18055 ["Previous link" org-previous-link t]
18056 "--"
18057 ["Descriptive Links"
18058 (progn (add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
18059 :style radio
18060 :selected (member '(org-link) buffer-invisibility-spec)]
18061 ["Literal Links"
18062 (progn
18063 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
18064 :style radio
18065 :selected (not (member '(org-link) buffer-invisibility-spec))])
18066 "--"
18067 ("TODO Lists"
18068 ["TODO/DONE/-" org-todo t]
18069 ("Select keyword"
18070 ["Next keyword" org-shiftright (org-on-heading-p)]
18071 ["Previous keyword" org-shiftleft (org-on-heading-p)]
18072 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
18073 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
18074 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
18075 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
18076 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
18077 "--"
18078 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
18079 :selected org-enforce-todo-dependencies :style toggle :active t]
18080 "Settings for tree at point"
18081 ["Do Children sequentially" org-toggle-ordered-property :style radio
18082 :selected (org-entry-get nil "ORDERED")
18083 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
18084 ["Do Children parallel" org-toggle-ordered-property :style radio
18085 :selected (not (org-entry-get nil "ORDERED"))
18086 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
18087 "--"
18088 ["Set Priority" org-priority t]
18089 ["Priority Up" org-shiftup t]
18090 ["Priority Down" org-shiftdown t]
18091 "--"
18092 ["Get news from all feeds" org-feed-update-all t]
18093 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
18094 ["Customize feeds" (customize-variable 'org-feed-alist) t])
18095 ("TAGS and Properties"
18096 ["Set Tags" org-set-tags-command t]
18097 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
18098 "--"
18099 ["Set property" org-set-property t]
18100 ["Column view of properties" org-columns t]
18101 ["Insert Column View DBlock" org-insert-columns-dblock t])
18102 ("Dates and Scheduling"
18103 ["Timestamp" org-time-stamp t]
18104 ["Timestamp (inactive)" org-time-stamp-inactive t]
18105 ("Change Date"
18106 ["1 Day Later" org-shiftright t]
18107 ["1 Day Earlier" org-shiftleft t]
18108 ["1 ... Later" org-shiftup t]
18109 ["1 ... Earlier" org-shiftdown t])
18110 ["Compute Time Range" org-evaluate-time-range t]
18111 ["Schedule Item" org-schedule t]
18112 ["Deadline" org-deadline t]
18113 "--"
18114 ["Custom time format" org-toggle-time-stamp-overlays
18115 :style radio :selected org-display-custom-times]
18116 "--"
18117 ["Goto Calendar" org-goto-calendar t]
18118 ["Date from Calendar" org-date-from-calendar t]
18119 "--"
18120 ["Start/Restart Timer" org-timer-start t]
18121 ["Pause/Continue Timer" org-timer-pause-or-continue t]
18122 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
18123 ["Insert Timer String" org-timer t]
18124 ["Insert Timer Item" org-timer-item t])
18125 ("Logging work"
18126 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
18127 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
18128 ["Clock out" org-clock-out t]
18129 ["Clock cancel" org-clock-cancel t]
18130 "--"
18131 ["Mark as default task" org-clock-mark-default-task t]
18132 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
18133 ["Goto running clock" org-clock-goto t]
18134 "--"
18135 ["Display times" org-clock-display t]
18136 ["Create clock table" org-clock-report t]
18137 "--"
18138 ["Record DONE time"
18139 (progn (setq org-log-done (not org-log-done))
18140 (message "Switching to %s will %s record a timestamp"
18141 (car org-done-keywords)
18142 (if org-log-done "automatically" "not")))
18143 :style toggle :selected org-log-done])
18144 "--"
18145 ["Agenda Command..." org-agenda t]
18146 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
18147 ("File List for Agenda")
18148 ("Special views current file"
18149 ["TODO Tree" org-show-todo-tree t]
18150 ["Check Deadlines" org-check-deadlines t]
18151 ["Timeline" org-timeline t]
18152 ["Tags/Property tree" org-match-sparse-tree t])
18153 "--"
18154 ["Export/Publish..." org-export t]
18155 ("LaTeX"
18156 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
18157 :selected org-cdlatex-mode]
18158 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
18159 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
18160 ["Modify math symbol" org-cdlatex-math-modify
18161 (org-inside-LaTeX-fragment-p)]
18162 ["Insert citation" org-reftex-citation t]
18163 "--"
18164 ["Template for BEAMER" org-insert-beamer-options-template t])
18165 "--"
18166 ("MobileOrg"
18167 ["Push Files and Views" org-mobile-push t]
18168 ["Get Captured and Flagged" org-mobile-pull t]
18169 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
18170 "--"
18171 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
18172 "--"
18173 ("Documentation"
18174 ["Show Version" org-version t]
18175 ["Info Documentation" org-info t])
18176 ("Customize"
18177 ["Browse Org Group" org-customize t]
18178 "--"
18179 ["Expand This Menu" org-create-customize-menu
18180 (fboundp 'customize-menu-create)])
18181 ["Send bug report" org-submit-bug-report t]
18182 "--"
18183 ("Refresh/Reload"
18184 ["Refresh setup current buffer" org-mode-restart t]
18185 ["Reload Org (after update)" org-reload t]
18186 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
18189 (defun org-info (&optional node)
18190 "Read documentation for Org-mode in the info system.
18191 With optional NODE, go directly to that node."
18192 (interactive)
18193 (info (format "(org)%s" (or node ""))))
18195 ;;;###autoload
18196 (defun org-submit-bug-report ()
18197 "Submit a bug report on Org-mode via mail.
18199 Don't hesitate to report any problems or inaccurate documentation.
18201 If you don't have setup sending mail from (X)Emacs, please copy the
18202 output buffer into your mail program, as it gives us important
18203 information about your Org-mode version and configuration."
18204 (interactive)
18205 (require 'reporter)
18206 (org-load-modules-maybe)
18207 (org-require-autoloaded-modules)
18208 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
18209 (reporter-submit-bug-report
18210 "emacs-orgmode@gnu.org"
18211 (org-version)
18212 (let (list)
18213 (save-window-excursion
18214 (switch-to-buffer (get-buffer-create "*Warn about privacy*"))
18215 (delete-other-windows)
18216 (erase-buffer)
18217 (insert "You are about to submit a bug report to the Org-mode mailing list.
18219 We would like to add your full Org-mode and Outline configuration to the
18220 bug report. This greatly simplifies the work of the maintainer and
18221 other experts on the mailing list.
18223 HOWEVER, some variables you have customized may contain private
18224 information. The names of customers, colleagues, or friends, might
18225 appear in the form of file names, tags, todo states, or search strings.
18226 If you answer yes to the prompt, you might want to check and remove
18227 such private information before sending the email.")
18228 (add-text-properties (point-min) (point-max) '(face org-warning))
18229 (when (yes-or-no-p "Include your Org-mode configuration ")
18230 (mapatoms
18231 (lambda (v)
18232 (and (boundp v)
18233 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
18234 (or (and (symbol-value v)
18235 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
18236 (and
18237 (get v 'custom-type) (get v 'standard-value)
18238 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
18239 (push v list)))))
18240 (kill-buffer (get-buffer "*Warn about privacy*"))
18241 list))
18242 nil nil
18243 "Remember to cover the basics, that is, what you expected to happen and
18244 what in fact did happen. You don't know how to make a good report? See
18246 http://orgmode.org/manual/Feedback.html#Feedback
18248 Your bug report will be posted to the Org-mode mailing list.
18249 ------------------------------------------------------------------------")
18250 (save-excursion
18251 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
18252 (replace-match "\\1Bug: \\3 [\\2]")))))
18255 (defun org-install-agenda-files-menu ()
18256 (let ((bl (buffer-list)))
18257 (save-excursion
18258 (while bl
18259 (set-buffer (pop bl))
18260 (if (org-mode-p) (setq bl nil)))
18261 (when (org-mode-p)
18262 (easy-menu-change
18263 '("Org") "File List for Agenda"
18264 (append
18265 (list
18266 ["Edit File List" (org-edit-agenda-file-list) t]
18267 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
18268 ["Remove Current File from List" org-remove-file t]
18269 ["Cycle through agenda files" org-cycle-agenda-files t]
18270 ["Occur in all agenda files" org-occur-in-agenda-files t]
18271 "--")
18272 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
18274 ;;;; Documentation
18276 ;;;###autoload
18277 (defun org-require-autoloaded-modules ()
18278 (interactive)
18279 (mapc 'require
18280 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
18281 org-docbook org-exp org-html org-icalendar
18282 org-id org-latex
18283 org-publish org-remember org-table
18284 org-timer org-xoxo)))
18286 ;;;###autoload
18287 (defun org-reload (&optional uncompiled)
18288 "Reload all org lisp files.
18289 With prefix arg UNCOMPILED, load the uncompiled versions."
18290 (interactive "P")
18291 (require 'find-func)
18292 (let* ((file-re "^\\(org\\|orgtbl\\)\\(\\.el\\|-.*\\.el\\)")
18293 (dir-org (file-name-directory (org-find-library-name "org")))
18294 (dir-org-contrib (ignore-errors
18295 (file-name-directory
18296 (org-find-library-name "org-contribdir"))))
18297 (babel-files
18298 (mapcar (lambda (el) (concat "ob" (when el (format "-%s" el)) ".el"))
18299 (append (list nil "comint" "eval" "exp" "keys"
18300 "lob" "ref" "table" "tangle")
18301 (delq nil
18302 (mapcar
18303 (lambda (lang)
18304 (when (cdr lang) (symbol-name (car lang))))
18305 org-babel-load-languages)))))
18306 (files
18307 (append (directory-files dir-org t file-re)
18308 babel-files
18309 (and dir-org-contrib
18310 (directory-files dir-org-contrib t file-re))))
18311 (remove-re (concat (if (featurep 'xemacs)
18312 "org-colview" "org-colview-xemacs")
18313 "\\'")))
18314 (setq files (mapcar 'file-name-sans-extension files))
18315 (setq files (mapcar
18316 (lambda (x) (if (string-match remove-re x) nil x))
18317 files))
18318 (setq files (delq nil files))
18319 (mapc
18320 (lambda (f)
18321 (when (featurep (intern (file-name-nondirectory f)))
18322 (if (and (not uncompiled)
18323 (file-exists-p (concat f ".elc")))
18324 (load (concat f ".elc") nil nil t)
18325 (load (concat f ".el") nil nil t))))
18326 files))
18327 (org-version))
18329 ;;;###autoload
18330 (defun org-customize ()
18331 "Call the customize function with org as argument."
18332 (interactive)
18333 (org-load-modules-maybe)
18334 (org-require-autoloaded-modules)
18335 (customize-browse 'org))
18337 (defun org-create-customize-menu ()
18338 "Create a full customization menu for Org-mode, insert it into the menu."
18339 (interactive)
18340 (org-load-modules-maybe)
18341 (org-require-autoloaded-modules)
18342 (if (fboundp 'customize-menu-create)
18343 (progn
18344 (easy-menu-change
18345 '("Org") "Customize"
18346 `(["Browse Org group" org-customize t]
18347 "--"
18348 ,(customize-menu-create 'org)
18349 ["Set" Custom-set t]
18350 ["Save" Custom-save t]
18351 ["Reset to Current" Custom-reset-current t]
18352 ["Reset to Saved" Custom-reset-saved t]
18353 ["Reset to Standard Settings" Custom-reset-standard t]))
18354 (message "\"Org\"-menu now contains full customization menu"))
18355 (error "Cannot expand menu (outdated version of cus-edit.el)")))
18357 ;;;; Miscellaneous stuff
18359 ;;; Generally useful functions
18361 (defun org-get-at-bol (property)
18362 "Get text property PROPERTY at beginning of line."
18363 (get-text-property (point-at-bol) property))
18365 (defun org-find-text-property-in-string (prop s)
18366 "Return the first non-nil value of property PROP in string S."
18367 (or (get-text-property 0 prop s)
18368 (get-text-property (or (next-single-property-change 0 prop s) 0)
18369 prop s)))
18371 (defun org-display-warning (message) ;; Copied from Emacs-Muse
18372 "Display the given MESSAGE as a warning."
18373 (if (fboundp 'display-warning)
18374 (display-warning 'org message
18375 (if (featurep 'xemacs) 'warning :warning))
18376 (let ((buf (get-buffer-create "*Org warnings*")))
18377 (with-current-buffer buf
18378 (goto-char (point-max))
18379 (insert "Warning (Org): " message)
18380 (unless (bolp)
18381 (newline)))
18382 (display-buffer buf)
18383 (sit-for 0))))
18385 (defun org-eval (form)
18386 "Eval FORM and return result."
18387 (condition-case error
18388 (eval form)
18389 (error (format "%%![Error: %s]" error))))
18391 (defun org-in-commented-line ()
18392 "Is point in a line starting with `#'?"
18393 (equal (char-after (point-at-bol)) ?#))
18395 (defun org-in-indented-comment-line ()
18396 "Is point in a line starting with `#' after some white space?"
18397 (save-excursion
18398 (save-match-data
18399 (goto-char (point-at-bol))
18400 (looking-at "[ \t]*#"))))
18402 (defun org-in-verbatim-emphasis ()
18403 (save-match-data
18404 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
18406 (defun org-goto-marker-or-bmk (marker &optional bookmark)
18407 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
18408 (if (and marker (marker-buffer marker)
18409 (buffer-live-p (marker-buffer marker)))
18410 (progn
18411 (switch-to-buffer (marker-buffer marker))
18412 (if (or (> marker (point-max)) (< marker (point-min)))
18413 (widen))
18414 (goto-char marker)
18415 (org-show-context 'org-goto))
18416 (if bookmark
18417 (bookmark-jump bookmark)
18418 (error "Cannot find location"))))
18420 (defun org-quote-csv-field (s)
18421 "Quote field for inclusion in CSV material."
18422 (if (string-match "[\",]" s)
18423 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
18426 (defun org-force-self-insert (N)
18427 "Needed to enforce self-insert under remapping."
18428 (interactive "p")
18429 (self-insert-command N))
18431 (defun org-string-width (s)
18432 "Compute width of string, ignoring invisible characters.
18433 This ignores character with invisibility property `org-link', and also
18434 characters with property `org-cwidth', because these will become invisible
18435 upon the next fontification round."
18436 (let (b l)
18437 (when (or (eq t buffer-invisibility-spec)
18438 (assq 'org-link buffer-invisibility-spec))
18439 (while (setq b (text-property-any 0 (length s)
18440 'invisible 'org-link s))
18441 (setq s (concat (substring s 0 b)
18442 (substring s (or (next-single-property-change
18443 b 'invisible s) (length s)))))))
18444 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
18445 (setq s (concat (substring s 0 b)
18446 (substring s (or (next-single-property-change
18447 b 'org-cwidth s) (length s))))))
18448 (setq l (string-width s) b -1)
18449 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
18450 (setq l (- l (get-text-property b 'org-dwidth-n s))))
18453 (defun org-shorten-string (s maxlength)
18454 "Shorten string S so tht it is no longer than MAXLENGTH characters.
18455 If the string is shorter or has length MAXLENGTH, just return the
18456 original string. If it is longer, the functions finds a space in the
18457 string, breaks this string off at that locations and adds three dots
18458 as ellipsis. Including the ellipsis, the string will not be longer
18459 than MAXLENGTH. If finding a good breaking point in the string does
18460 not work, the string is just chopped off in the middle of a word
18461 if necessary."
18462 (if (<= (length s) maxlength)
18464 (let* ((n (max (- maxlength 4) 1))
18465 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
18466 (if (string-match re s)
18467 (concat (match-string 1 s) "...")
18468 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
18470 (defun org-get-indentation (&optional line)
18471 "Get the indentation of the current line, interpreting tabs.
18472 When LINE is given, assume it represents a line and compute its indentation."
18473 (if line
18474 (if (string-match "^ *" (org-remove-tabs line))
18475 (match-end 0))
18476 (save-excursion
18477 (beginning-of-line 1)
18478 (skip-chars-forward " \t")
18479 (current-column))))
18481 (defun org-get-string-indentation (s)
18482 "What indentation has S due to SPACE and TAB at the beginning of the string?"
18483 (let ((n -1) (i 0) (w tab-width) c)
18484 (catch 'exit
18485 (while (< (setq n (1+ n)) (length s))
18486 (setq c (aref s n))
18487 (cond ((= c ?\ ) (setq i (1+ i)))
18488 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
18489 (t (throw 'exit t)))))
18492 (defun org-remove-tabs (s &optional width)
18493 "Replace tabulators in S with spaces.
18494 Assumes that s is a single line, starting in column 0."
18495 (setq width (or width tab-width))
18496 (while (string-match "\t" s)
18497 (setq s (replace-match
18498 (make-string
18499 (- (* width (/ (+ (match-beginning 0) width) width))
18500 (match-beginning 0)) ?\ )
18501 t t s)))
18504 (defun org-fix-indentation (line ind)
18505 "Fix indentation in LINE.
18506 IND is a cons cell with target and minimum indentation.
18507 If the current indentation in LINE is smaller than the minimum,
18508 leave it alone. If it is larger than ind, set it to the target."
18509 (let* ((l (org-remove-tabs line))
18510 (i (org-get-indentation l))
18511 (i1 (car ind)) (i2 (cdr ind)))
18512 (if (>= i i2) (setq l (substring line i2)))
18513 (if (> i1 0)
18514 (concat (make-string i1 ?\ ) l)
18515 l)))
18517 (defun org-remove-indentation (code &optional n)
18518 "Remove the maximum common indentation from the lines in CODE.
18519 N may optionally be the number of spaces to remove."
18520 (with-temp-buffer
18521 (insert code)
18522 (org-do-remove-indentation n)
18523 (buffer-string)))
18525 (defun org-do-remove-indentation (&optional n)
18526 "Remove the maximum common indentation from the buffer."
18527 (untabify (point-min) (point-max))
18528 (let ((min 10000) re)
18529 (if n
18530 (setq min n)
18531 (goto-char (point-min))
18532 (while (re-search-forward "^ *[^ \n]" nil t)
18533 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
18534 (unless (or (= min 0) (= min 10000))
18535 (setq re (format "^ \\{%d\\}" min))
18536 (goto-char (point-min))
18537 (while (re-search-forward re nil t)
18538 (replace-match "")
18539 (end-of-line 1))
18540 min)))
18542 (defun org-fill-template (template alist)
18543 "Find each %key of ALIST in TEMPLATE and replace it."
18544 (let ((case-fold-search nil)
18545 entry key value)
18546 (setq alist (sort (copy-sequence alist)
18547 (lambda (a b) (< (length (car a)) (length (car b))))))
18548 (while (setq entry (pop alist))
18549 (setq template
18550 (replace-regexp-in-string
18551 (concat "%" (regexp-quote (car entry)))
18552 (cdr entry) template t t)))
18553 template))
18555 (defun org-base-buffer (buffer)
18556 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
18557 (if (not buffer)
18558 buffer
18559 (or (buffer-base-buffer buffer)
18560 buffer)))
18562 (defun org-trim (s)
18563 "Remove whitespace at beginning and end of string."
18564 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
18565 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
18568 (defun org-wrap (string &optional width lines)
18569 "Wrap string to either a number of lines, or a width in characters.
18570 If WIDTH is non-nil, the string is wrapped to that width, however many lines
18571 that costs. If there is a word longer than WIDTH, the text is actually
18572 wrapped to the length of that word.
18573 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
18574 many lines, whatever width that takes.
18575 The return value is a list of lines, without newlines at the end."
18576 (let* ((words (org-split-string string "[ \t\n]+"))
18577 (maxword (apply 'max (mapcar 'org-string-width words)))
18578 w ll)
18579 (cond (width
18580 (org-do-wrap words (max maxword width)))
18581 (lines
18582 (setq w maxword)
18583 (setq ll (org-do-wrap words maxword))
18584 (if (<= (length ll) lines)
18586 (setq ll words)
18587 (while (> (length ll) lines)
18588 (setq w (1+ w))
18589 (setq ll (org-do-wrap words w)))
18590 ll))
18591 (t (error "Cannot wrap this")))))
18593 (defun org-do-wrap (words width)
18594 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
18595 (let (lines line)
18596 (while words
18597 (setq line (pop words))
18598 (while (and words (< (+ (length line) (length (car words))) width))
18599 (setq line (concat line " " (pop words))))
18600 (setq lines (push line lines)))
18601 (nreverse lines)))
18603 (defun org-split-string (string &optional separators)
18604 "Splits STRING into substrings at SEPARATORS.
18605 No empty strings are returned if there are matches at the beginning
18606 and end of string."
18607 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
18608 (start 0)
18609 notfirst
18610 (list nil))
18611 (while (and (string-match rexp string
18612 (if (and notfirst
18613 (= start (match-beginning 0))
18614 (< start (length string)))
18615 (1+ start) start))
18616 (< (match-beginning 0) (length string)))
18617 (setq notfirst t)
18618 (or (eq (match-beginning 0) 0)
18619 (and (eq (match-beginning 0) (match-end 0))
18620 (eq (match-beginning 0) start))
18621 (setq list
18622 (cons (substring string start (match-beginning 0))
18623 list)))
18624 (setq start (match-end 0)))
18625 (or (eq start (length string))
18626 (setq list
18627 (cons (substring string start)
18628 list)))
18629 (nreverse list)))
18631 (defun org-quote-vert (s)
18632 "Replace \"|\" with \"\\vert\"."
18633 (while (string-match "|" s)
18634 (setq s (replace-match "\\vert" t t s)))
18637 (defun org-uuidgen-p (s)
18638 "Is S an ID created by UUIDGEN?"
18639 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
18641 (defun org-context ()
18642 "Return a list of contexts of the current cursor position.
18643 If several contexts apply, all are returned.
18644 Each context entry is a list with a symbol naming the context, and
18645 two positions indicating start and end of the context. Possible
18646 contexts are:
18648 :headline anywhere in a headline
18649 :headline-stars on the leading stars in a headline
18650 :todo-keyword on a TODO keyword (including DONE) in a headline
18651 :tags on the TAGS in a headline
18652 :priority on the priority cookie in a headline
18653 :item on the first line of a plain list item
18654 :item-bullet on the bullet/number of a plain list item
18655 :checkbox on the checkbox in a plain list item
18656 :table in an org-mode table
18657 :table-special on a special filed in a table
18658 :table-table in a table.el table
18659 :link on a hyperlink
18660 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
18661 :target on a <<target>>
18662 :radio-target on a <<<radio-target>>>
18663 :latex-fragment on a LaTeX fragment
18664 :latex-preview on a LaTeX fragment with overlayed preview image
18666 This function expects the position to be visible because it uses font-lock
18667 faces as a help to recognize the following contexts: :table-special, :link,
18668 and :keyword."
18669 (let* ((f (get-text-property (point) 'face))
18670 (faces (if (listp f) f (list f)))
18671 (p (point)) clist o)
18672 ;; First the large context
18673 (cond
18674 ((org-on-heading-p t)
18675 (push (list :headline (point-at-bol) (point-at-eol)) clist)
18676 (when (progn
18677 (beginning-of-line 1)
18678 (looking-at org-todo-line-tags-regexp))
18679 (push (org-point-in-group p 1 :headline-stars) clist)
18680 (push (org-point-in-group p 2 :todo-keyword) clist)
18681 (push (org-point-in-group p 4 :tags) clist))
18682 (goto-char p)
18683 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
18684 (if (looking-at "\\[#[A-Z0-9]\\]")
18685 (push (org-point-in-group p 0 :priority) clist)))
18687 ((org-at-item-p)
18688 (push (org-point-in-group p 2 :item-bullet) clist)
18689 (push (list :item (point-at-bol)
18690 (save-excursion (org-end-of-item) (point)))
18691 clist)
18692 (and (org-at-item-checkbox-p)
18693 (push (org-point-in-group p 0 :checkbox) clist)))
18695 ((org-at-table-p)
18696 (push (list :table (org-table-begin) (org-table-end)) clist)
18697 (if (memq 'org-formula faces)
18698 (push (list :table-special
18699 (previous-single-property-change p 'face)
18700 (next-single-property-change p 'face)) clist)))
18701 ((org-at-table-p 'any)
18702 (push (list :table-table) clist)))
18703 (goto-char p)
18705 ;; Now the small context
18706 (cond
18707 ((org-at-timestamp-p)
18708 (push (org-point-in-group p 0 :timestamp) clist))
18709 ((memq 'org-link faces)
18710 (push (list :link
18711 (previous-single-property-change p 'face)
18712 (next-single-property-change p 'face)) clist))
18713 ((memq 'org-special-keyword faces)
18714 (push (list :keyword
18715 (previous-single-property-change p 'face)
18716 (next-single-property-change p 'face)) clist))
18717 ((org-on-target-p)
18718 (push (org-point-in-group p 0 :target) clist)
18719 (goto-char (1- (match-beginning 0)))
18720 (if (looking-at org-radio-target-regexp)
18721 (push (org-point-in-group p 0 :radio-target) clist))
18722 (goto-char p))
18723 ((setq o (car (delq nil
18724 (mapcar
18725 (lambda (x)
18726 (if (memq x org-latex-fragment-image-overlays) x))
18727 (overlays-at (point))))))
18728 (push (list :latex-fragment
18729 (overlay-start o) (overlay-end o)) clist)
18730 (push (list :latex-preview
18731 (overlay-start o) (overlay-end o)) clist))
18732 ((org-inside-LaTeX-fragment-p)
18733 ;; FIXME: positions wrong.
18734 (push (list :latex-fragment (point) (point)) clist)))
18736 (setq clist (nreverse (delq nil clist)))
18737 clist))
18739 ;; FIXME: Compare with at-regexp-p Do we need both?
18740 (defun org-in-regexp (re &optional nlines visually)
18741 "Check if point is inside a match of regexp.
18742 Normally only the current line is checked, but you can include NLINES extra
18743 lines both before and after point into the search.
18744 If VISUALLY is set, require that the cursor is not after the match but
18745 really on, so that the block visually is on the match."
18746 (catch 'exit
18747 (let ((pos (point))
18748 (eol (point-at-eol (+ 1 (or nlines 0))))
18749 (inc (if visually 1 0)))
18750 (save-excursion
18751 (beginning-of-line (- 1 (or nlines 0)))
18752 (while (re-search-forward re eol t)
18753 (if (and (<= (match-beginning 0) pos)
18754 (>= (+ inc (match-end 0)) pos))
18755 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
18757 (defun org-at-regexp-p (regexp)
18758 "Is point inside a match of REGEXP in the current line?"
18759 (catch 'exit
18760 (save-excursion
18761 (let ((pos (point)) (end (point-at-eol)))
18762 (beginning-of-line 1)
18763 (while (re-search-forward regexp end t)
18764 (if (and (<= (match-beginning 0) pos)
18765 (>= (match-end 0) pos))
18766 (throw 'exit t)))
18767 nil))))
18769 (defun org-in-regexps-block-p (start-re end-re &optional bound)
18770 "Return t if the current point is between matches of START-RE and END-RE.
18771 This will also return t if point is on one of the two matches or
18772 in an unfinished block. END-RE can be a string or a form
18773 returning a string.
18775 An optional third argument bounds the search for START-RE. It
18776 defaults to previous heading or `point-min'."
18777 (let ((pos (point))
18778 (limit (or bound (save-excursion (outline-previous-heading)))))
18779 (save-excursion
18780 ;; we're on a block when point is on start-re...
18781 (or (org-at-regexp-p start-re)
18782 ;; ... or start-re can be found above...
18783 (and (re-search-backward start-re limit t)
18784 ;; ... but no end-re between start-re and point.
18785 (not (re-search-forward (eval end-re) pos t)))))))
18787 (defun org-occur-in-agenda-files (regexp &optional nlines)
18788 "Call `multi-occur' with buffers for all agenda files."
18789 (interactive "sOrg-files matching: \np")
18790 (let* ((files (org-agenda-files))
18791 (tnames (mapcar 'file-truename files))
18792 (extra org-agenda-text-search-extra-files)
18794 (when (eq (car extra) 'agenda-archives)
18795 (setq extra (cdr extra))
18796 (setq files (org-add-archive-files files)))
18797 (while (setq f (pop extra))
18798 (unless (member (file-truename f) tnames)
18799 (add-to-list 'files f 'append)
18800 (add-to-list 'tnames (file-truename f) 'append)))
18801 (multi-occur
18802 (mapcar (lambda (x)
18803 (with-current-buffer
18804 (or (get-file-buffer x) (find-file-noselect x))
18805 (widen)
18806 (current-buffer)))
18807 files)
18808 regexp)))
18810 (if (boundp 'occur-mode-find-occurrence-hook)
18811 ;; Emacs 23
18812 (add-hook 'occur-mode-find-occurrence-hook
18813 (lambda ()
18814 (when (org-mode-p)
18815 (org-reveal))))
18816 ;; Emacs 22
18817 (defadvice occur-mode-goto-occurrence
18818 (after org-occur-reveal activate)
18819 (and (org-mode-p) (org-reveal)))
18820 (defadvice occur-mode-goto-occurrence-other-window
18821 (after org-occur-reveal activate)
18822 (and (org-mode-p) (org-reveal)))
18823 (defadvice occur-mode-display-occurrence
18824 (after org-occur-reveal activate)
18825 (when (org-mode-p)
18826 (let ((pos (occur-mode-find-occurrence)))
18827 (with-current-buffer (marker-buffer pos)
18828 (save-excursion
18829 (goto-char pos)
18830 (org-reveal)))))))
18832 (defun org-occur-link-in-agenda-files ()
18833 "Create a link and search for it in the agendas.
18834 The link is not stored in `org-stored-links', it is just created
18835 for the search purpose."
18836 (interactive)
18837 (let ((link (condition-case nil
18838 (org-store-link nil)
18839 (error "Unable to create a link to here"))))
18840 (org-occur-in-agenda-files (regexp-quote link))))
18842 (defun org-uniquify (list)
18843 "Remove duplicate elements from LIST."
18844 (let (res)
18845 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
18846 res))
18848 (defun org-delete-all (elts list)
18849 "Remove all elements in ELTS from LIST."
18850 (while elts
18851 (setq list (delete (pop elts) list)))
18852 list)
18854 (defun org-count (cl-item cl-seq)
18855 "Count the number of occurrences of ITEM in SEQ.
18856 Taken from `count' in cl-seq.el with all keyword arguments removed."
18857 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
18858 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
18859 (while (< cl-start cl-end)
18860 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
18861 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
18862 (setq cl-start (1+ cl-start)))
18863 cl-count))
18865 (defun org-remove-if (predicate seq)
18866 "Remove everything from SEQ that fulfills PREDICATE."
18867 (let (res e)
18868 (while seq
18869 (setq e (pop seq))
18870 (if (not (funcall predicate e)) (push e res)))
18871 (nreverse res)))
18873 (defun org-remove-if-not (predicate seq)
18874 "Remove everything from SEQ that does not fulfill PREDICATE."
18875 (let (res e)
18876 (while seq
18877 (setq e (pop seq))
18878 (if (funcall predicate e) (push e res)))
18879 (nreverse res)))
18881 (defun org-back-over-empty-lines ()
18882 "Move backwards over whitespace, to the beginning of the first empty line.
18883 Returns the number of empty lines passed."
18884 (let ((pos (point)))
18885 (if (cdr (assoc 'heading org-blank-before-new-entry))
18886 (skip-chars-backward " \t\n\r")
18887 (forward-line -1))
18888 (beginning-of-line 2)
18889 (goto-char (min (point) pos))
18890 (count-lines (point) pos)))
18892 (defun org-skip-whitespace ()
18893 (skip-chars-forward " \t\n\r"))
18895 (defun org-point-in-group (point group &optional context)
18896 "Check if POINT is in match-group GROUP.
18897 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
18898 match. If the match group does not exist or point is not inside it,
18899 return nil."
18900 (and (match-beginning group)
18901 (>= point (match-beginning group))
18902 (<= point (match-end group))
18903 (if context
18904 (list context (match-beginning group) (match-end group))
18905 t)))
18907 (defun org-switch-to-buffer-other-window (&rest args)
18908 "Switch to buffer in a second window on the current frame.
18909 In particular, do not allow pop-up frames.
18910 Returns the newly created buffer."
18911 (let (pop-up-frames special-display-buffer-names special-display-regexps
18912 special-display-function)
18913 (apply 'switch-to-buffer-other-window args)))
18915 (defun org-combine-plists (&rest plists)
18916 "Create a single property list from all plists in PLISTS.
18917 The process starts by copying the first list, and then setting properties
18918 from the other lists. Settings in the last list are the most significant
18919 ones and overrule settings in the other lists."
18920 (let ((rtn (copy-sequence (pop plists)))
18921 p v ls)
18922 (while plists
18923 (setq ls (pop plists))
18924 (while ls
18925 (setq p (pop ls) v (pop ls))
18926 (setq rtn (plist-put rtn p v))))
18927 rtn))
18929 (defun org-move-line-down (arg)
18930 "Move the current line down. With prefix argument, move it past ARG lines."
18931 (interactive "p")
18932 (let ((col (current-column))
18933 beg end pos)
18934 (beginning-of-line 1) (setq beg (point))
18935 (beginning-of-line 2) (setq end (point))
18936 (beginning-of-line (+ 1 arg))
18937 (setq pos (move-marker (make-marker) (point)))
18938 (insert (delete-and-extract-region beg end))
18939 (goto-char pos)
18940 (org-move-to-column col)))
18942 (defun org-move-line-up (arg)
18943 "Move the current line up. With prefix argument, move it past ARG lines."
18944 (interactive "p")
18945 (let ((col (current-column))
18946 beg end pos)
18947 (beginning-of-line 1) (setq beg (point))
18948 (beginning-of-line 2) (setq end (point))
18949 (beginning-of-line (- arg))
18950 (setq pos (move-marker (make-marker) (point)))
18951 (insert (delete-and-extract-region beg end))
18952 (goto-char pos)
18953 (org-move-to-column col)))
18955 (defun org-replace-escapes (string table)
18956 "Replace %-escapes in STRING with values in TABLE.
18957 TABLE is an association list with keys like \"%a\" and string values.
18958 The sequences in STRING may contain normal field width and padding information,
18959 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
18960 so values can contain further %-escapes if they are define later in TABLE."
18961 (let ((tbl (copy-alist table))
18962 (case-fold-search nil)
18963 (pchg 0)
18964 e re rpl)
18965 (while (setq e (pop tbl))
18966 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
18967 (when (and (cdr e) (string-match re (cdr e)))
18968 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
18969 (safe "SREF"))
18970 (add-text-properties 0 3 (list 'sref sref) safe)
18971 (setcdr e (replace-match safe t t (cdr e)))))
18972 (while (string-match re string)
18973 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
18974 (cdr e)))
18975 (setq string (replace-match rpl t t string))))
18976 (while (setq pchg (next-property-change pchg string))
18977 (let ((sref (get-text-property pchg 'sref string)))
18978 (when (and sref (string-match "SREF" string pchg))
18979 (setq string (replace-match sref t t string)))))
18980 string))
18982 (defun org-sublist (list start end)
18983 "Return a section of LIST, from START to END.
18984 Counting starts at 1."
18985 (let (rtn (c start))
18986 (setq list (nthcdr (1- start) list))
18987 (while (and list (<= c end))
18988 (push (pop list) rtn)
18989 (setq c (1+ c)))
18990 (nreverse rtn)))
18992 (defun org-find-base-buffer-visiting (file)
18993 "Like `find-buffer-visiting' but always return the base buffer and
18994 not an indirect buffer."
18995 (let ((buf (or (get-file-buffer file)
18996 (find-buffer-visiting file))))
18997 (if buf
18998 (or (buffer-base-buffer buf) buf)
18999 nil)))
19001 (defun org-image-file-name-regexp (&optional extensions)
19002 "Return regexp matching the file names of images.
19003 If EXTENSIONS is given, only match these."
19004 (if (and (not extensions) (fboundp 'image-file-name-regexp))
19005 (image-file-name-regexp)
19006 (let ((image-file-name-extensions
19007 (or extensions
19008 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
19009 "xbm" "xpm" "pbm" "pgm" "ppm"))))
19010 (concat "\\."
19011 (regexp-opt (nconc (mapcar 'upcase
19012 image-file-name-extensions)
19013 image-file-name-extensions)
19015 "\\'"))))
19017 (defun org-file-image-p (file &optional extensions)
19018 "Return non-nil if FILE is an image."
19019 (save-match-data
19020 (string-match (org-image-file-name-regexp extensions) file)))
19022 (defun org-get-cursor-date ()
19023 "Return the date at cursor in as a time.
19024 This works in the calendar and in the agenda, anywhere else it just
19025 returns the current time."
19026 (let (date day defd)
19027 (cond
19028 ((eq major-mode 'calendar-mode)
19029 (setq date (calendar-cursor-to-date)
19030 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
19031 ((eq major-mode 'org-agenda-mode)
19032 (setq day (get-text-property (point) 'day))
19033 (if day
19034 (setq date (calendar-gregorian-from-absolute day)
19035 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
19036 (nth 2 date))))))
19037 (or defd (current-time))))
19039 (defvar org-agenda-action-marker (make-marker)
19040 "Marker pointing to the entry for the next agenda action.")
19042 (defun org-mark-entry-for-agenda-action ()
19043 "Mark the current entry as target of an agenda action.
19044 Agenda actions are actions executed from the agenda with the key `k',
19045 which make use of the date at the cursor."
19046 (interactive)
19047 (move-marker org-agenda-action-marker
19048 (save-excursion (org-back-to-heading t) (point))
19049 (current-buffer))
19050 (message
19051 "Entry marked for action; press `k' at desired date in agenda or calendar"))
19053 (defun org-mark-subtree ()
19054 "Mark the current subtree.
19055 This puts point at the start of the current subtree, and mark at the end.
19057 If point is in an inline task, mark that task instead."
19058 (interactive)
19059 (let ((inline-task-p
19060 (and (featurep 'org-inlinetask)
19061 (org-inlinetask-in-task-p)))
19062 (beg))
19063 ;; Get beginning of subtree
19064 (cond
19065 (inline-task-p (org-inlinetask-goto-beginning))
19066 ((org-at-heading-p) (beginning-of-line))
19067 (t (org-with-limited-levels (outline-previous-visible-heading 1))))
19068 (setq beg (point))
19069 ;; Get end of it
19070 (if inline-task-p
19071 (org-inlinetask-goto-end)
19072 (org-end-of-subtree))
19073 ;; Mark zone
19074 (push-mark (point) nil t)
19075 (goto-char beg)))
19077 ;;; Paragraph filling stuff.
19078 ;; We want this to be just right, so use the full arsenal.
19080 (defun org-indent-line-function ()
19081 "Indent line depending on context."
19082 (interactive)
19083 (let* ((pos (point))
19084 (itemp (org-at-item-p))
19085 (case-fold-search t)
19086 (org-drawer-regexp (or org-drawer-regexp "\000"))
19087 (inline-task-p (and (featurep 'org-inlinetask)
19088 (org-inlinetask-in-task-p)))
19089 (inline-re (and inline-task-p
19090 (org-inlinetask-outline-regexp)))
19091 column)
19092 (beginning-of-line 1)
19093 (cond
19094 ;; Comments
19095 ((looking-at "# ") (setq column 0))
19096 ;; Headings
19097 ((looking-at "\\*+ ") (setq column 0))
19098 ;; Literal examples
19099 ((looking-at "[ \t]*:[ \t]")
19100 (setq column (org-get-indentation))) ; do nothing
19101 ;; Lists
19102 ((ignore-errors (goto-char (org-in-item-p)))
19103 (setq column (if itemp
19104 (org-get-indentation)
19105 (org-list-item-body-column (point))))
19106 (goto-char pos))
19107 ;; Drawers
19108 ((and (looking-at "[ \t]*:END:")
19109 (save-excursion (re-search-backward org-drawer-regexp nil t)))
19110 (save-excursion
19111 (goto-char (1- (match-beginning 1)))
19112 (setq column (current-column))))
19113 ;; Special blocks
19114 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
19115 (save-excursion
19116 (re-search-backward
19117 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
19118 (setq column (org-get-indentation (match-string 0))))
19119 ((and (not (looking-at "[ \t]*#\\+begin_"))
19120 (org-in-regexps-block-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
19121 (save-excursion
19122 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
19123 (setq column
19124 (if (equal (downcase (match-string 1)) "src")
19125 ;; src blocks: let `org-edit-src-exit' handle them
19126 (org-get-indentation)
19127 (org-get-indentation (match-string 0)))))
19128 ;; This line has nothing special, look at the previous relevant
19129 ;; line to compute indentation
19131 (beginning-of-line 0)
19132 (while (and (not (bobp))
19133 (not (looking-at org-drawer-regexp))
19134 ;; When point started in an inline task, do not move
19135 ;; above task starting line.
19136 (not (and inline-task-p
19137 (looking-at inline-re)))
19138 ;; Skip comments, verbatim, empty lines, tables,
19139 ;; inline tasks, lists, drawers and blocks.
19140 (or (and (looking-at "[ \t]*:END:")
19141 (re-search-backward org-drawer-regexp nil t))
19142 (and (looking-at "[ \t]*#\\+end_")
19143 (re-search-backward "[ \t]*#\\+begin_"nil t))
19144 (looking-at "[ \t]*[\n:#|]")
19145 (and (ignore-errors (goto-char (org-in-item-p)))
19146 (goto-char
19147 (org-list-get-top-point (org-list-struct))))
19148 (and (not inline-task-p)
19149 (featurep 'org-inlinetask)
19150 (org-inlinetask-in-task-p)
19151 (or (org-inlinetask-goto-beginning) t))))
19152 (beginning-of-line 0))
19153 (cond
19154 ;; There was an heading above.
19155 ((looking-at "\\*+[ \t]+")
19156 (if (not org-adapt-indentation)
19157 (setq column 0)
19158 (goto-char (match-end 0))
19159 (setq column (current-column))))
19160 ;; A drawer had started and is unfinished
19161 ((looking-at org-drawer-regexp)
19162 (goto-char (1- (match-beginning 1)))
19163 (setq column (current-column)))
19164 ;; Else, nothing noticeable found: get indentation and go on.
19165 (t (setq column (org-get-indentation))))))
19166 ;; Now apply indentation and move cursor accordingly
19167 (goto-char pos)
19168 (if (<= (current-column) (current-indentation))
19169 (org-indent-line-to column)
19170 (save-excursion (org-indent-line-to column)))
19171 ;; Special polishing for properties, see `org-property-format'
19172 (setq column (current-column))
19173 (beginning-of-line 1)
19174 (if (looking-at
19175 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
19176 (replace-match (concat (match-string 1)
19177 (format org-property-format
19178 (match-string 2) (match-string 3)))
19179 t t))
19180 (org-move-to-column column)))
19182 (defvar org-adaptive-fill-regexp-backup adaptive-fill-regexp
19183 "Variable to store copy of `adaptive-fill-regexp'.
19184 Since `adaptive-fill-regexp' is set to never match, we need to
19185 store a backup of its value before entering `org-mode' so that
19186 the functionality can be provided as a fall-back.")
19188 (defun org-set-autofill-regexps ()
19189 (interactive)
19190 ;; In the paragraph separator we include headlines, because filling
19191 ;; text in a line directly attached to a headline would otherwise
19192 ;; fill the headline as well.
19193 (org-set-local 'comment-start-skip "^#+[ \t]*")
19194 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|#]")
19195 ;; The paragraph starter includes hand-formatted lists.
19196 (org-set-local
19197 'paragraph-start
19198 (concat
19199 "\f" "\\|"
19200 "[ ]*$" "\\|"
19201 "\\*+ " "\\|"
19202 "[ \t]*#" "\\|"
19203 (org-item-re) "\\|"
19204 "[ \t]*[:|]" "\\|"
19205 "\\$\\$" "\\|"
19206 "\\\\\\(begin\\|end\\|[][]\\)"))
19207 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
19208 ;; But only if the user has not turned off tables or fixed-width regions
19209 (org-set-local
19210 'auto-fill-inhibit-regexp
19211 (concat "\\*+ \\|#\\+"
19212 "\\|[ \t]*" org-keyword-time-regexp
19213 (if (or org-enable-table-editor org-enable-fixed-width-editor)
19214 (concat
19215 "\\|[ \t]*["
19216 (if org-enable-table-editor "|" "")
19217 (if org-enable-fixed-width-editor ":" "")
19218 "]"))))
19219 ;; We use our own fill-paragraph function, to make sure that tables
19220 ;; and fixed-width regions are not wrapped. That function will pass
19221 ;; through to `fill-paragraph' when appropriate.
19222 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
19223 ;; Adaptive filling: To get full control, first make sure that
19224 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
19225 (unless (local-variable-p 'adaptive-fill-regexp (current-buffer))
19226 (org-set-local 'org-adaptive-fill-regexp-backup
19227 adaptive-fill-regexp))
19228 (org-set-local 'adaptive-fill-regexp "\000")
19229 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
19230 (org-set-local 'adaptive-fill-function
19231 'org-adaptive-fill-function)
19232 (org-set-local
19233 'align-mode-rules-list
19234 '((org-in-buffer-settings
19235 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
19236 (modes . '(org-mode))))))
19238 (defun org-fill-paragraph (&optional justify)
19239 "Re-align a table, pass through to fill-paragraph if no table."
19240 (let ((table-p (org-at-table-p))
19241 (table.el-p (org-at-table.el-p))
19242 (itemp (org-in-item-p)))
19243 (cond ((and (equal (char-after (point-at-bol)) ?*)
19244 (save-excursion (goto-char (point-at-bol))
19245 (looking-at outline-regexp)))
19246 t) ; skip headlines
19247 (table.el-p t) ; skip table.el tables
19248 (table-p (org-table-align) t) ; align Org tables
19249 (itemp ; align text in items
19250 (let* ((struct (save-excursion (goto-char itemp)
19251 (org-list-struct)))
19252 (parents (org-list-parents-alist struct))
19253 (children (org-list-get-children itemp struct parents))
19254 beg end prev next prefix)
19255 ;; Determine in which part of item point is: before
19256 ;; first child, after last child, between two
19257 ;; sub-lists, or simply in item if there's no child.
19258 (cond
19259 ((not children)
19260 (setq prefix (make-string (org-list-item-body-column itemp) ?\ )
19261 beg itemp
19262 end (org-list-get-item-end itemp struct)))
19263 ((< (point) (setq next (car children)))
19264 (setq prefix (make-string (org-list-item-body-column itemp) ?\ )
19265 beg itemp
19266 end next))
19267 ((> (point) (setq prev (car (last children))))
19268 (setq beg (org-list-get-item-end prev struct)
19269 end (org-list-get-item-end itemp struct)
19270 prefix (save-excursion
19271 (goto-char beg)
19272 (skip-chars-forward " \t")
19273 (make-string (current-column) ?\ ))))
19274 (t (catch 'exit
19275 (while (setq next (pop children))
19276 (if (> (point) next)
19277 (setq prev next)
19278 (setq beg (org-list-get-item-end prev struct)
19279 end next
19280 prefix (save-excursion
19281 (goto-char beg)
19282 (skip-chars-forward " \t")
19283 (make-string (current-column) ?\ )))
19284 (throw 'exit nil))))))
19285 ;; Use `fill-paragraph' with buffer narrowed to item
19286 ;; without any child, and with our computed PREFIX.
19287 (flet ((fill-context-prefix (from to &optional flr) prefix))
19288 (save-restriction
19289 (narrow-to-region beg end)
19290 (save-excursion (fill-paragraph justify)))) t))
19291 ;; Special case where point is not in a list but is on
19292 ;; a paragraph adjacent to a list: make sure this paragraph
19293 ;; doesn't get merged with the end of the list by narrowing
19294 ;; buffer first.
19295 ((save-excursion (forward-paragraph -1)
19296 (setq itemp (org-in-item-p)))
19297 (let ((struct (save-excursion (goto-char itemp)
19298 (org-list-struct))))
19299 (save-restriction
19300 (narrow-to-region (org-list-get-bottom-point struct)
19301 (save-excursion (forward-paragraph 1)
19302 (point)))
19303 (fill-paragraph justify) t)))
19304 ;; Else simply call `fill-paragraph'.
19305 (t nil))))
19307 ;; For reference, this is the default value of adaptive-fill-regexp
19308 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
19310 (defun org-adaptive-fill-function ()
19311 "Return a fill prefix for org-mode files."
19312 (let (itemp)
19313 (save-excursion
19314 (cond
19315 ;; Comment line
19316 ((looking-at "#[ \t]+")
19317 (match-string-no-properties 0))
19318 ;; Plain list item
19319 ((org-at-item-p)
19320 (make-string (org-list-item-body-column (point-at-bol)) ?\ ))
19321 ;; Point is in a list after `backward-paragraph': original
19322 ;; point wasn't in the list, or filling would have been taken
19323 ;; care of by `org-auto-fill-function', but the list and the
19324 ;; real paragraph are not separated by a blank line. Thus, move
19325 ;; point after the list to go back to real paragraph and
19326 ;; determine fill-prefix.
19327 ((setq itemp (org-in-item-p))
19328 (goto-char itemp)
19329 (let* ((struct (org-list-struct))
19330 (bottom (org-list-get-bottom-point struct)))
19331 (goto-char bottom)
19332 (make-string (org-get-indentation) ?\ )))
19333 ;; Other text
19334 ((looking-at org-adaptive-fill-regexp-backup)
19335 (match-string-no-properties 0))))))
19337 (defun org-auto-fill-function ()
19338 "Auto-fill function."
19339 (let (itemp prefix)
19340 ;; When in a list, compute an appropriate fill-prefix and make
19341 ;; sure it will be used by `do-auto-fill'.
19342 (if (setq itemp (org-in-item-p))
19343 (progn
19344 (setq prefix (make-string (org-list-item-body-column itemp) ?\ ))
19345 (flet ((fill-context-prefix (from to &optional flr) prefix))
19346 (do-auto-fill)))
19347 ;; Else just use `do-auto-fill'.
19348 (do-auto-fill))))
19350 ;;; Other stuff.
19352 (defun org-toggle-fixed-width-section (arg)
19353 "Toggle the fixed-width export.
19354 If there is no active region, the QUOTE keyword at the current headline is
19355 inserted or removed. When present, it causes the text between this headline
19356 and the next to be exported as fixed-width text, and unmodified.
19357 If there is an active region, this command adds or removes a colon as the
19358 first character of this line. If the first character of a line is a colon,
19359 this line is also exported in fixed-width font."
19360 (interactive "P")
19361 (let* ((cc 0)
19362 (regionp (org-region-active-p))
19363 (beg (if regionp (region-beginning) (point)))
19364 (end (if regionp (region-end)))
19365 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
19366 (case-fold-search nil)
19367 (re "[ \t]*\\(: \\)")
19368 off)
19369 (if regionp
19370 (save-excursion
19371 (goto-char beg)
19372 (setq cc (current-column))
19373 (beginning-of-line 1)
19374 (setq off (looking-at re))
19375 (while (> nlines 0)
19376 (setq nlines (1- nlines))
19377 (beginning-of-line 1)
19378 (cond
19379 (arg
19380 (org-move-to-column cc t)
19381 (insert ": \n")
19382 (forward-line -1))
19383 ((and off (looking-at re))
19384 (replace-match "" t t nil 1))
19385 ((not off) (org-move-to-column cc t) (insert ": ")))
19386 (forward-line 1)))
19387 (save-excursion
19388 (org-back-to-heading)
19389 (if (looking-at (concat outline-regexp
19390 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
19391 (replace-match "" t t nil 1)
19392 (if (looking-at outline-regexp)
19393 (progn
19394 (goto-char (match-end 0))
19395 (insert org-quote-string " "))))))))
19397 (defun org-reftex-citation ()
19398 "Use reftex-citation to insert a citation into the buffer.
19399 This looks for a line like
19401 #+BIBLIOGRAPHY: foo plain option:-d
19403 and derives from it that foo.bib is the bibliography file relevant
19404 for this document. It then installs the necessary environment for RefTeX
19405 to work in this buffer and calls `reftex-citation' to insert a citation
19406 into the buffer.
19408 Export of such citations to both LaTeX and HTML is handled by the contributed
19409 package org-exp-bibtex by Taru Karttunen."
19410 (interactive)
19411 (let ((reftex-docstruct-symbol 'rds)
19412 (reftex-cite-format "\\cite{%l}")
19413 rds bib)
19414 (save-excursion
19415 (save-restriction
19416 (widen)
19417 (let ((case-fold-search t)
19418 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
19419 (if (not (save-excursion
19420 (or (re-search-forward re nil t)
19421 (re-search-backward re nil t))))
19422 (error "No bibliography defined in file")
19423 (setq bib (concat (match-string 1) ".bib")
19424 rds (list (list 'bib bib)))))))
19425 (call-interactively 'reftex-citation)))
19427 ;;;; Functions extending outline functionality
19429 (defun org-beginning-of-line (&optional arg)
19430 "Go to the beginning of the current line. If that is invisible, continue
19431 to a visible line beginning. This makes the function of C-a more intuitive.
19432 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
19433 first attempt, and only move to after the tags when the cursor is already
19434 beyond the end of the headline."
19435 (interactive "P")
19436 (let ((pos (point))
19437 (special (if (consp org-special-ctrl-a/e)
19438 (car org-special-ctrl-a/e)
19439 org-special-ctrl-a/e))
19440 refpos)
19441 (if (org-bound-and-true-p line-move-visual)
19442 (beginning-of-visual-line 1)
19443 (beginning-of-line 1))
19444 (if (and arg (fboundp 'move-beginning-of-line))
19445 (call-interactively 'move-beginning-of-line)
19446 (if (bobp)
19448 (backward-char 1)
19449 (if (org-truely-invisible-p)
19450 (while (and (not (bobp)) (org-truely-invisible-p))
19451 (backward-char 1)
19452 (beginning-of-line 1))
19453 (forward-char 1))))
19454 (when special
19455 (cond
19456 ((and (looking-at org-complex-heading-regexp)
19457 (= (char-after (match-end 1)) ?\ ))
19458 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
19459 (point-at-eol)))
19460 (goto-char
19461 (if (eq special t)
19462 (cond ((> pos refpos) refpos)
19463 ((= pos (point)) refpos)
19464 (t (point)))
19465 (cond ((> pos (point)) (point))
19466 ((not (eq last-command this-command)) (point))
19467 (t refpos)))))
19468 ((org-at-item-p)
19469 (goto-char
19470 (if (eq special t)
19471 (cond ((> pos (match-end 0)) (match-end 0))
19472 ((= pos (point)) (match-end 0))
19473 (t (point)))
19474 (cond ((> pos (point)) (point))
19475 ((not (eq last-command this-command)) (point))
19476 (t (match-end 0))))))))
19477 (org-no-warnings
19478 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
19480 (defun org-end-of-line (&optional arg)
19481 "Go to the end of the line.
19482 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
19483 first attempt, and only move to after the tags when the cursor is already
19484 beyond the end of the headline."
19485 (interactive "P")
19486 (let ((special (if (consp org-special-ctrl-a/e)
19487 (cdr org-special-ctrl-a/e)
19488 org-special-ctrl-a/e)))
19489 (if (or (not special)
19490 (not (org-on-heading-p))
19491 arg)
19492 (call-interactively
19493 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
19494 ((fboundp 'move-end-of-line) 'move-end-of-line)
19495 (t 'end-of-line)))
19496 (let ((pos (point)))
19497 (beginning-of-line 1)
19498 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
19499 (if (eq special t)
19500 (if (or (< pos (match-beginning 1))
19501 (= pos (match-end 0)))
19502 (goto-char (match-beginning 1))
19503 (goto-char (match-end 0)))
19504 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
19505 (goto-char (match-end 0))
19506 (goto-char (match-beginning 1))))
19507 (call-interactively (if (fboundp 'move-end-of-line)
19508 'move-end-of-line
19509 'end-of-line)))))
19510 (org-no-warnings
19511 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
19513 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
19514 (define-key org-mode-map "\C-e" 'org-end-of-line)
19516 (defun org-backward-sentence (&optional arg)
19517 "Go to beginning of sentence, or beginning of table field.
19518 This will call `backward-sentence' or `org-table-beginning-of-field',
19519 depending on context."
19520 (interactive "P")
19521 (cond
19522 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
19523 (t (call-interactively 'backward-sentence))))
19525 (defun org-forward-sentence (&optional arg)
19526 "Go to end of sentence, or end of table field.
19527 This will call `forward-sentence' or `org-table-end-of-field',
19528 depending on context."
19529 (interactive "P")
19530 (cond
19531 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
19532 (t (call-interactively 'forward-sentence))))
19534 (define-key org-mode-map "\M-a" 'org-backward-sentence)
19535 (define-key org-mode-map "\M-e" 'org-forward-sentence)
19537 (defun org-kill-line (&optional arg)
19538 "Kill line, to tags or end of line."
19539 (interactive "P")
19540 (cond
19541 ((or (not org-special-ctrl-k)
19542 (bolp)
19543 (not (org-on-heading-p)))
19544 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
19545 org-ctrl-k-protect-subtree)
19546 (if (or (eq org-ctrl-k-protect-subtree 'error)
19547 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
19548 (error "C-k aborted - would kill hidden subtree")))
19549 (call-interactively 'kill-line))
19550 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
19551 (kill-region (point) (match-beginning 1))
19552 (org-set-tags nil t))
19553 (t (kill-region (point) (point-at-eol)))))
19555 (define-key org-mode-map "\C-k" 'org-kill-line)
19557 (defun org-yank (&optional arg)
19558 "Yank. If the kill is a subtree, treat it specially.
19559 This command will look at the current kill and check if is a single
19560 subtree, or a series of subtrees[1]. If it passes the test, and if the
19561 cursor is at the beginning of a line or after the stars of a currently
19562 empty headline, then the yank is handled specially. How exactly depends
19563 on the value of the following variables, both set by default.
19565 org-yank-folded-subtrees
19566 When set, the subtree(s) will be folded after insertion, but only
19567 if doing so would now swallow text after the yanked text.
19569 org-yank-adjusted-subtrees
19570 When set, the subtree will be promoted or demoted in order to
19571 fit into the local outline tree structure, which means that the level
19572 will be adjusted so that it becomes the smaller one of the two
19573 *visible* surrounding headings.
19575 Any prefix to this command will cause `yank' to be called directly with
19576 no special treatment. In particular, a simple \\[universal-argument] prefix \
19577 will just
19578 plainly yank the text as it is.
19580 \[1] The test checks if the first non-white line is a heading
19581 and if there are no other headings with fewer stars."
19582 (interactive "P")
19583 (org-yank-generic 'yank arg))
19585 (defun org-yank-generic (command arg)
19586 "Perform some yank-like command.
19588 This function implements the behavior described in the `org-yank'
19589 documentation. However, it has been generalized to work for any
19590 interactive command with similar behavior."
19592 ;; pretend to be command COMMAND
19593 (setq this-command command)
19595 (if arg
19596 (call-interactively command)
19598 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
19599 (and (org-kill-is-subtree-p)
19600 (or (bolp)
19601 (and (looking-at "[ \t]*$")
19602 (string-match
19603 "\\`\\*+\\'"
19604 (buffer-substring (point-at-bol) (point)))))))
19605 swallowp)
19606 (cond
19607 ((and subtreep org-yank-folded-subtrees)
19608 (let ((beg (point))
19609 end)
19610 (if (and subtreep org-yank-adjusted-subtrees)
19611 (org-paste-subtree nil nil 'for-yank)
19612 (call-interactively command))
19614 (setq end (point))
19615 (goto-char beg)
19616 (when (and (bolp) subtreep
19617 (not (setq swallowp
19618 (org-yank-folding-would-swallow-text beg end))))
19619 (or (looking-at outline-regexp)
19620 (re-search-forward (concat "^" outline-regexp) end t))
19621 (while (and (< (point) end) (looking-at outline-regexp))
19622 (hide-subtree)
19623 (org-cycle-show-empty-lines 'folded)
19624 (condition-case nil
19625 (outline-forward-same-level 1)
19626 (error (goto-char end)))))
19627 (when swallowp
19628 (message
19629 "Inserted text not folded because that would swallow text"))
19631 (goto-char end)
19632 (skip-chars-forward " \t\n\r")
19633 (beginning-of-line 1)
19634 (push-mark beg 'nomsg)))
19635 ((and subtreep org-yank-adjusted-subtrees)
19636 (let ((beg (point-at-bol)))
19637 (org-paste-subtree nil nil 'for-yank)
19638 (push-mark beg 'nomsg)))
19640 (call-interactively command))))))
19642 (defun org-yank-folding-would-swallow-text (beg end)
19643 "Would hide-subtree at BEG swallow any text after END?"
19644 (let (level)
19645 (save-excursion
19646 (goto-char beg)
19647 (when (or (looking-at outline-regexp)
19648 (re-search-forward (concat "^" outline-regexp) end t))
19649 (setq level (org-outline-level)))
19650 (goto-char end)
19651 (skip-chars-forward " \t\r\n\v\f")
19652 (if (or (eobp)
19653 (and (bolp) (looking-at org-outline-regexp)
19654 (<= (org-outline-level) level)))
19655 nil ; Nothing would be swallowed
19656 t)))) ; something would swallow
19658 (define-key org-mode-map "\C-y" 'org-yank)
19660 (defun org-truely-invisible-p ()
19661 "Check if point is at a character currently not visible.
19662 This version does not only check the character property, but also
19663 `visible-mode'."
19664 ;; Early versions of noutline don't have `outline-invisible-p'.
19665 (if (org-bound-and-true-p visible-mode)
19667 (outline-invisible-p)))
19669 (defun org-invisible-p2 ()
19670 "Check if point is at a character currently not visible."
19671 (save-excursion
19672 (if (and (eolp) (not (bobp))) (backward-char 1))
19673 ;; Early versions of noutline don't have `outline-invisible-p'.
19674 (outline-invisible-p)))
19676 (defun org-back-to-heading (&optional invisible-ok)
19677 "Call `outline-back-to-heading', but provide a better error message."
19678 (condition-case nil
19679 (outline-back-to-heading invisible-ok)
19680 (error (error "Before first headline at position %d in buffer %s"
19681 (point) (current-buffer)))))
19683 (defun org-beginning-of-defun ()
19684 "Go to the beginning of the subtree, i.e. back to the heading."
19685 (org-back-to-heading))
19686 (defun org-end-of-defun ()
19687 "Go to the end of the subtree."
19688 (org-end-of-subtree nil t))
19690 (defun org-before-first-heading-p ()
19691 "Before first heading?"
19692 (save-excursion
19693 (end-of-line)
19694 (null (re-search-backward "^\\*+ " nil t))))
19696 (defun org-on-heading-p (&optional ignored)
19697 (outline-on-heading-p t))
19698 (defun org-at-heading-p (&optional ignored)
19699 (outline-on-heading-p t))
19701 (defun org-point-at-end-of-empty-headline ()
19702 "If point is at the end of an empty headline, return t, else nil.
19703 If the heading only contains a TODO keyword, it is still still considered
19704 empty."
19705 (and (looking-at "[ \t]*$")
19706 (save-excursion
19707 (beginning-of-line 1)
19708 (looking-at (concat "^\\(\\*+\\)[ \t]+\\(" org-todo-regexp
19709 "\\)?[ \t]*$")))))
19710 (defun org-at-heading-or-item-p ()
19711 (or (org-on-heading-p) (org-at-item-p)))
19713 (defun org-on-target-p ()
19714 (or (org-in-regexp org-radio-target-regexp)
19715 (org-in-regexp org-target-regexp)))
19717 (defun org-up-heading-all (arg)
19718 "Move to the heading line of which the present line is a subheading.
19719 This function considers both visible and invisible heading lines.
19720 With argument, move up ARG levels."
19721 (if (fboundp 'outline-up-heading-all)
19722 (outline-up-heading-all arg) ; emacs 21 version of outline.el
19723 (outline-up-heading arg t))) ; emacs 22 version of outline.el
19725 (defun org-up-heading-safe ()
19726 "Move to the heading line of which the present line is a subheading.
19727 This version will not throw an error. It will return the level of the
19728 headline found, or nil if no higher level is found.
19730 Also, this function will be a lot faster than `outline-up-heading',
19731 because it relies on stars being the outline starters. This can really
19732 make a significant difference in outlines with very many siblings."
19733 (let (start-level re)
19734 (org-back-to-heading t)
19735 (setq start-level (funcall outline-level))
19736 (if (equal start-level 1)
19738 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
19739 (if (re-search-backward re nil t)
19740 (funcall outline-level)))))
19742 (defun org-first-sibling-p ()
19743 "Is this heading the first child of its parents?"
19744 (interactive)
19745 (let ((re (concat "^" outline-regexp))
19746 level l)
19747 (unless (org-at-heading-p t)
19748 (error "Not at a heading"))
19749 (setq level (funcall outline-level))
19750 (save-excursion
19751 (if (not (re-search-backward re nil t))
19753 (setq l (funcall outline-level))
19754 (< l level)))))
19756 (defun org-goto-sibling (&optional previous)
19757 "Goto the next sibling, even if it is invisible.
19758 When PREVIOUS is set, go to the previous sibling instead. Returns t
19759 when a sibling was found. When none is found, return nil and don't
19760 move point."
19761 (let ((fun (if previous 're-search-backward 're-search-forward))
19762 (pos (point))
19763 (re (concat "^" outline-regexp))
19764 level l)
19765 (when (condition-case nil (org-back-to-heading t) (error nil))
19766 (setq level (funcall outline-level))
19767 (catch 'exit
19768 (or previous (forward-char 1))
19769 (while (funcall fun re nil t)
19770 (setq l (funcall outline-level))
19771 (when (< l level) (goto-char pos) (throw 'exit nil))
19772 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
19773 (goto-char pos)
19774 nil))))
19776 (defun org-show-siblings ()
19777 "Show all siblings of the current headline."
19778 (save-excursion
19779 (while (org-goto-sibling) (org-flag-heading nil)))
19780 (save-excursion
19781 (while (org-goto-sibling 'previous)
19782 (org-flag-heading nil))))
19784 (defun org-goto-first-child ()
19785 "Goto the first child, even if it is invisible.
19786 Return t when a child was found. Otherwise don't move point and
19787 return nil."
19788 (let (level (pos (point)) (re (concat "^" outline-regexp)))
19789 (when (condition-case nil (org-back-to-heading t) (error nil))
19790 (setq level (outline-level))
19791 (forward-char 1)
19792 (if (and (re-search-forward re nil t) (> (outline-level) level))
19793 (progn (goto-char (match-beginning 0)) t)
19794 (goto-char pos) nil))))
19796 (defun org-show-hidden-entry ()
19797 "Show an entry where even the heading is hidden."
19798 (save-excursion
19799 (org-show-entry)))
19801 (defun org-flag-heading (flag &optional entry)
19802 "Flag the current heading. FLAG non-nil means make invisible.
19803 When ENTRY is non-nil, show the entire entry."
19804 (save-excursion
19805 (org-back-to-heading t)
19806 ;; Check if we should show the entire entry
19807 (if entry
19808 (progn
19809 (org-show-entry)
19810 (save-excursion
19811 (and (outline-next-heading)
19812 (org-flag-heading nil))))
19813 (outline-flag-region (max (point-min) (1- (point)))
19814 (save-excursion (outline-end-of-heading) (point))
19815 flag))))
19817 (defun org-get-next-sibling ()
19818 "Move to next heading of the same level, and return point.
19819 If there is no such heading, return nil.
19820 This is like outline-next-sibling, but invisible headings are ok."
19821 (let ((level (funcall outline-level)))
19822 (outline-next-heading)
19823 (while (and (not (eobp)) (> (funcall outline-level) level))
19824 (outline-next-heading))
19825 (if (or (eobp) (< (funcall outline-level) level))
19827 (point))))
19829 (defun org-get-last-sibling ()
19830 "Move to previous heading of the same level, and return point.
19831 If there is no such heading, return nil."
19832 (let ((opoint (point))
19833 (level (funcall outline-level)))
19834 (outline-previous-heading)
19835 (when (and (/= (point) opoint) (outline-on-heading-p t))
19836 (while (and (> (funcall outline-level) level)
19837 (not (bobp)))
19838 (outline-previous-heading))
19839 (if (< (funcall outline-level) level)
19841 (point)))))
19843 (defun org-end-of-subtree (&optional invisible-OK to-heading)
19844 ;; This contains an exact copy of the original function, but it uses
19845 ;; `org-back-to-heading', to make it work also in invisible
19846 ;; trees. And is uses an invisible-OK argument.
19847 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
19848 ;; Furthermore, when used inside Org, finding the end of a large subtree
19849 ;; with many children and grandchildren etc, this can be much faster
19850 ;; than the outline version.
19851 (org-back-to-heading invisible-OK)
19852 (let ((first t)
19853 (level (funcall outline-level)))
19854 (if (and (org-mode-p) (< level 1000))
19855 ;; A true heading (not a plain list item), in Org-mode
19856 ;; This means we can easily find the end by looking
19857 ;; only for the right number of stars. Using a regexp to do
19858 ;; this is so much faster than using a Lisp loop.
19859 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
19860 (forward-char 1)
19861 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
19862 ;; something else, do it the slow way
19863 (while (and (not (eobp))
19864 (or first (> (funcall outline-level) level)))
19865 (setq first nil)
19866 (outline-next-heading)))
19867 (unless to-heading
19868 (if (memq (preceding-char) '(?\n ?\^M))
19869 (progn
19870 ;; Go to end of line before heading
19871 (forward-char -1)
19872 (if (memq (preceding-char) '(?\n ?\^M))
19873 ;; leave blank line before heading
19874 (forward-char -1))))))
19875 (point))
19877 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
19878 "Use Org version in org-mode, for dramatic speed-up."
19879 (if (org-mode-p)
19880 (progn
19881 (org-end-of-subtree nil t)
19882 (unless (eobp) (backward-char 1)))
19883 ad-do-it))
19885 (defun org-forward-same-level (arg &optional invisible-ok)
19886 "Move forward to the arg'th subheading at same level as this one.
19887 Stop at the first and last subheadings of a superior heading.
19888 Normally this only looks at visible headings, but when INVISIBLE-OK is non-nil
19889 it wil also look at invisible ones."
19890 (interactive "p")
19891 (org-back-to-heading invisible-ok)
19892 (org-on-heading-p)
19893 (let* ((level (- (match-end 0) (match-beginning 0) 1))
19894 (re (format "^\\*\\{1,%d\\} " level))
19896 (forward-char 1)
19897 (while (> arg 0)
19898 (while (and (re-search-forward re nil 'move)
19899 (setq l (- (match-end 0) (match-beginning 0) 1))
19900 (= l level)
19901 (not invisible-ok)
19902 (progn (backward-char 1) (outline-invisible-p)))
19903 (if (< l level) (setq arg 1)))
19904 (setq arg (1- arg)))
19905 (beginning-of-line 1)))
19907 (defun org-backward-same-level (arg &optional invisible-ok)
19908 "Move backward to the arg'th subheading at same level as this one.
19909 Stop at the first and last subheadings of a superior heading."
19910 (interactive "p")
19911 (org-back-to-heading)
19912 (org-on-heading-p)
19913 (let* ((level (- (match-end 0) (match-beginning 0) 1))
19914 (re (format "^\\*\\{1,%d\\} " level))
19916 (while (> arg 0)
19917 (while (and (re-search-backward re nil 'move)
19918 (setq l (- (match-end 0) (match-beginning 0) 1))
19919 (= l level)
19920 (not invisible-ok)
19921 (outline-invisible-p))
19922 (if (< l level) (setq arg 1)))
19923 (setq arg (1- arg)))))
19925 (defun org-show-subtree ()
19926 "Show everything after this heading at deeper levels."
19927 (outline-flag-region
19928 (point)
19929 (save-excursion
19930 (org-end-of-subtree t t))
19931 nil))
19933 (defun org-show-entry ()
19934 "Show the body directly following this heading.
19935 Show the heading too, if it is currently invisible."
19936 (interactive)
19937 (save-excursion
19938 (condition-case nil
19939 (progn
19940 (org-back-to-heading t)
19941 (outline-flag-region
19942 (max (point-min) (1- (point)))
19943 (save-excursion
19944 (if (re-search-forward
19945 (concat "[\r\n]\\(" outline-regexp "\\)") nil t)
19946 (match-beginning 1)
19947 (point-max)))
19948 nil)
19949 (org-cycle-hide-drawers 'children))
19950 (error nil))))
19952 (defun org-make-options-regexp (kwds &optional extra)
19953 "Make a regular expression for keyword lines."
19954 (concat
19956 "#?[ \t]*\\+\\("
19957 (mapconcat 'regexp-quote kwds "\\|")
19958 (if extra (concat "\\|" extra))
19959 "\\):[ \t]*"
19960 "\\(.*\\)"))
19962 ;; Make isearch reveal the necessary context
19963 (defun org-isearch-end ()
19964 "Reveal context after isearch exits."
19965 (when isearch-success ; only if search was successful
19966 (if (featurep 'xemacs)
19967 ;; Under XEmacs, the hook is run in the correct place,
19968 ;; we directly show the context.
19969 (org-show-context 'isearch)
19970 ;; In Emacs the hook runs *before* restoring the overlays.
19971 ;; So we have to use a one-time post-command-hook to do this.
19972 ;; (Emacs 22 has a special variable, see function `org-mode')
19973 (unless (and (boundp 'isearch-mode-end-hook-quit)
19974 isearch-mode-end-hook-quit)
19975 ;; Only when the isearch was not quitted.
19976 (org-add-hook 'post-command-hook 'org-isearch-post-command
19977 'append 'local)))))
19979 (defun org-isearch-post-command ()
19980 "Remove self from hook, and show context."
19981 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
19982 (org-show-context 'isearch))
19985 ;;;; Integration with and fixes for other packages
19987 ;;; Imenu support
19989 (defvar org-imenu-markers nil
19990 "All markers currently used by Imenu.")
19991 (make-variable-buffer-local 'org-imenu-markers)
19993 (defun org-imenu-new-marker (&optional pos)
19994 "Return a new marker for use by Imenu, and remember the marker."
19995 (let ((m (make-marker)))
19996 (move-marker m (or pos (point)))
19997 (push m org-imenu-markers)
20000 (defun org-imenu-get-tree ()
20001 "Produce the index for Imenu."
20002 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
20003 (setq org-imenu-markers nil)
20004 (let* ((n org-imenu-depth)
20005 (re (concat "^" outline-regexp))
20006 (subs (make-vector (1+ n) nil))
20007 (last-level 0)
20008 m level head)
20009 (save-excursion
20010 (save-restriction
20011 (widen)
20012 (goto-char (point-max))
20013 (while (re-search-backward re nil t)
20014 (setq level (org-reduced-level (funcall outline-level)))
20015 (when (<= level n)
20016 (looking-at org-complex-heading-regexp)
20017 (setq head (org-link-display-format
20018 (org-match-string-no-properties 4))
20019 m (org-imenu-new-marker))
20020 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
20021 (if (>= level last-level)
20022 (push (cons head m) (aref subs level))
20023 (push (cons head (aref subs (1+ level))) (aref subs level))
20024 (loop for i from (1+ level) to n do (aset subs i nil)))
20025 (setq last-level level)))))
20026 (aref subs 1)))
20028 (eval-after-load "imenu"
20029 '(progn
20030 (add-hook 'imenu-after-jump-hook
20031 (lambda ()
20032 (if (org-mode-p)
20033 (org-show-context 'org-goto))))))
20035 (defun org-link-display-format (link)
20036 "Replace a link with either the description, or the link target
20037 if no description is present"
20038 (save-match-data
20039 (if (string-match org-bracket-link-analytic-regexp link)
20040 (replace-match (if (match-end 5)
20041 (match-string 5 link)
20042 (concat (match-string 1 link)
20043 (match-string 3 link)))
20044 nil t link)
20045 link)))
20047 ;; Speedbar support
20049 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
20050 "Overlay marking the agenda restriction line in speedbar.")
20051 (overlay-put org-speedbar-restriction-lock-overlay
20052 'face 'org-agenda-restriction-lock)
20053 (overlay-put org-speedbar-restriction-lock-overlay
20054 'help-echo "Agendas are currently limited to this item.")
20055 (org-detach-overlay org-speedbar-restriction-lock-overlay)
20057 (defun org-speedbar-set-agenda-restriction ()
20058 "Restrict future agenda commands to the location at point in speedbar.
20059 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
20060 (interactive)
20061 (require 'org-agenda)
20062 (let (p m tp np dir txt)
20063 (cond
20064 ((setq p (text-property-any (point-at-bol) (point-at-eol)
20065 'org-imenu t))
20066 (setq m (get-text-property p 'org-imenu-marker))
20067 (with-current-buffer (marker-buffer m)
20068 (goto-char m)
20069 (org-agenda-set-restriction-lock 'subtree)))
20070 ((setq p (text-property-any (point-at-bol) (point-at-eol)
20071 'speedbar-function 'speedbar-find-file))
20072 (setq tp (previous-single-property-change
20073 (1+ p) 'speedbar-function)
20074 np (next-single-property-change
20075 tp 'speedbar-function)
20076 dir (speedbar-line-directory)
20077 txt (buffer-substring-no-properties (or tp (point-min))
20078 (or np (point-max))))
20079 (with-current-buffer (find-file-noselect
20080 (let ((default-directory dir))
20081 (expand-file-name txt)))
20082 (unless (org-mode-p)
20083 (error "Cannot restrict to non-Org-mode file"))
20084 (org-agenda-set-restriction-lock 'file)))
20085 (t (error "Don't know how to restrict Org-mode's agenda")))
20086 (move-overlay org-speedbar-restriction-lock-overlay
20087 (point-at-bol) (point-at-eol))
20088 (setq current-prefix-arg nil)
20089 (org-agenda-maybe-redo)))
20091 (eval-after-load "speedbar"
20092 '(progn
20093 (speedbar-add-supported-extension ".org")
20094 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
20095 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
20096 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
20097 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
20098 (add-hook 'speedbar-visiting-tag-hook
20099 (lambda () (and (org-mode-p) (org-show-context 'org-goto))))))
20101 ;;; Fixes and Hacks for problems with other packages
20103 ;; Make flyspell not check words in links, to not mess up our keymap
20104 (defun org-mode-flyspell-verify ()
20105 "Don't let flyspell put overlays at active buttons."
20106 (and (not (get-text-property (max (1- (point)) (point-min)) 'keymap))
20107 (not (get-text-property (max (1- (point)) (point-min)) 'org-no-flyspell))))
20109 (defun org-remove-flyspell-overlays-in (beg end)
20110 "Remove flyspell overlays in region."
20111 (and (org-bound-and-true-p flyspell-mode)
20112 (fboundp 'flyspell-delete-region-overlays)
20113 (flyspell-delete-region-overlays beg end))
20114 (add-text-properties beg end '(org-no-flyspell t)))
20116 ;; Make `bookmark-jump' shows the jump location if it was hidden.
20117 (eval-after-load "bookmark"
20118 '(if (boundp 'bookmark-after-jump-hook)
20119 ;; We can use the hook
20120 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
20121 ;; Hook not available, use advice
20122 (defadvice bookmark-jump (after org-make-visible activate)
20123 "Make the position visible."
20124 (org-bookmark-jump-unhide))))
20126 ;; Make sure saveplace shows the location if it was hidden
20127 (eval-after-load "saveplace"
20128 '(defadvice save-place-find-file-hook (after org-make-visible activate)
20129 "Make the position visible."
20130 (org-bookmark-jump-unhide)))
20132 ;; Make sure ecb shows the location if it was hidden
20133 (eval-after-load "ecb"
20134 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
20135 "Make hierarchy visible when jumping into location from ECB tree buffer."
20136 (if (org-mode-p)
20137 (org-show-context))))
20139 (defun org-bookmark-jump-unhide ()
20140 "Unhide the current position, to show the bookmark location."
20141 (and (org-mode-p)
20142 (or (outline-invisible-p)
20143 (save-excursion (goto-char (max (point-min) (1- (point))))
20144 (outline-invisible-p)))
20145 (org-show-context 'bookmark-jump)))
20147 ;; Make session.el ignore our circular variable
20148 (eval-after-load "session"
20149 '(add-to-list 'session-globals-exclude 'org-mark-ring))
20151 ;;;; Experimental code
20153 (defun org-closed-in-range ()
20154 "Sparse tree of items closed in a certain time range.
20155 Still experimental, may disappear in the future."
20156 (interactive)
20157 ;; Get the time interval from the user.
20158 (let* ((time1 (org-float-time
20159 (org-read-date nil 'to-time nil "Starting date: ")))
20160 (time2 (org-float-time
20161 (org-read-date nil 'to-time nil "End date:")))
20162 ;; callback function
20163 (callback (lambda ()
20164 (let ((time
20165 (org-float-time
20166 (apply 'encode-time
20167 (org-parse-time-string
20168 (match-string 1))))))
20169 ;; check if time in interval
20170 (and (>= time time1) (<= time time2))))))
20171 ;; make tree, check each match with the callback
20172 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
20174 ;;;; Finish up
20176 (provide 'org)
20178 (run-hooks 'org-load-hook)
20180 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
20182 ;;; org.el ends here