Move contrib/odt/styles/*.xml to etc/styles
[org-mode.git] / lisp / org.el
blob2c7fc069ac6f226599ce61fb6fa721acf1205e85
1 ;;; org.el --- Outline-based notes management and organizer
2 ;; Carstens outline-mode for keeping track of everything.
3 ;; Copyright (C) 2004-2011 Free Software Foundation, Inc.
4 ;;
5 ;; Author: Carsten Dominik <carsten at orgmode dot org>
6 ;; Maintainer: Bastien Guerry <bzg at gnu dot org>
7 ;; Keywords: outlines, hypermedia, calendar, wp
8 ;; Homepage: http://orgmode.org
9 ;; Version: 7.7
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" ())
109 (declare-function org-pop-to-buffer-same-window "org-compat" (&optional buffer-or-name norecord label))
110 (declare-function org-at-clock-log-p "org-clock" ())
111 (declare-function org-clock-timestamps-up "org-clock" ())
112 (declare-function org-clock-timestamps-down "org-clock" ())
114 ;; babel
115 (require 'ob)
116 (require 'ob-table)
117 (require 'ob-lob)
118 (require 'ob-ref)
119 (require 'ob-tangle)
120 (require 'ob-comint)
121 (require 'ob-keys)
123 ;; load languages based on value of `org-babel-load-languages'
124 (defvar org-babel-load-languages)
125 ;;;###autoload
126 (defun org-babel-do-load-languages (sym value)
127 "Load the languages defined in `org-babel-load-languages'."
128 (set-default sym value)
129 (mapc (lambda (pair)
130 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
131 (if active
132 (progn
133 (require (intern (concat "ob-" lang))))
134 (progn
135 (funcall 'fmakunbound
136 (intern (concat "org-babel-execute:" lang)))
137 (funcall 'fmakunbound
138 (intern (concat "org-babel-expand-body:" lang)))))))
139 org-babel-load-languages))
141 (defcustom org-babel-load-languages '((emacs-lisp . t))
142 "Languages which can be evaluated in Org-mode buffers.
143 This list can be used to load support for any of the languages
144 below, note that each language will depend on a different set of
145 system executables and/or Emacs modes. When a language is
146 \"loaded\", then code blocks in that language can be evaluated
147 with `org-babel-execute-src-block' bound by default to C-c
148 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
149 be set to remove code block evaluation from the C-c C-c
150 keybinding. By default only Emacs Lisp (which has no
151 requirements) is loaded."
152 :group 'org-babel
153 :set 'org-babel-do-load-languages
154 :type '(alist :tag "Babel Languages"
155 :key-type
156 (choice
157 (const :tag "Awk" awk)
158 (const :tag "C" C)
159 (const :tag "R" R)
160 (const :tag "Asymptote" asymptote)
161 (const :tag "Calc" calc)
162 (const :tag "Clojure" clojure)
163 (const :tag "CSS" css)
164 (const :tag "Ditaa" ditaa)
165 (const :tag "Dot" dot)
166 (const :tag "Emacs Lisp" emacs-lisp)
167 (const :tag "Fortran" fortran)
168 (const :tag "Gnuplot" gnuplot)
169 (const :tag "Haskell" haskell)
170 (const :tag "Java" java)
171 (const :tag "Javascript" js)
172 (const :tag "Latex" latex)
173 (const :tag "Ledger" ledger)
174 (const :tag "Lilypond" lilypond)
175 (const :tag "Maxima" maxima)
176 (const :tag "Matlab" matlab)
177 (const :tag "Mscgen" mscgen)
178 (const :tag "Ocaml" ocaml)
179 (const :tag "Octave" octave)
180 (const :tag "Org" org)
181 (const :tag "Perl" perl)
182 (const :tag "Pico Lisp" picolisp)
183 (const :tag "PlantUML" plantuml)
184 (const :tag "Python" python)
185 (const :tag "Ruby" ruby)
186 (const :tag "Sass" sass)
187 (const :tag "Scheme" scheme)
188 (const :tag "Screen" screen)
189 (const :tag "Shell Script" sh)
190 (const :tag "Shen" shen)
191 (const :tag "Sql" sql)
192 (const :tag "Sqlite" sqlite))
193 :value-type (boolean :tag "Activate" :value t)))
195 ;;;; Customization variables
196 (defcustom org-clone-delete-id nil
197 "Remove ID property of clones of a subtree.
198 When non-nil, clones of a subtree don't inherit the ID property.
199 Otherwise they inherit the ID property with a new unique
200 identifier."
201 :type 'boolean
202 :group 'org-id)
204 ;;; Version
206 (defconst org-version "7.7"
207 "The version number of the file org.el.")
209 (defun org-version (&optional here)
210 "Show the org-mode version in the echo area.
211 With prefix arg HERE, insert it at point."
212 (interactive "P")
213 (let* ((origin default-directory)
214 (version org-version)
215 (git-version)
216 (dir (concat (file-name-directory (locate-library "org")) "../" )))
217 (when (and (file-exists-p (expand-file-name ".git" dir))
218 (executable-find "git"))
219 (unwind-protect
220 (progn
221 (cd dir)
222 (when (eql 0 (shell-command "git describe --abbrev=4 HEAD"))
223 (with-current-buffer "*Shell Command Output*"
224 (goto-char (point-min))
225 (setq git-version (buffer-substring (point) (point-at-eol))))
226 (subst-char-in-string ?- ?. git-version t)
227 (when (string-match "\\S-"
228 (shell-command-to-string
229 "git diff-index --name-only HEAD --"))
230 (setq git-version (concat git-version ".dirty")))
231 (setq version (concat version " (" git-version ")"))))
232 (cd origin)))
233 (setq version (format "Org-mode version %s" version))
234 (if here (insert version))
235 (message version)))
237 ;;; Compatibility constants
239 ;;; The custom variables
241 (defgroup org nil
242 "Outline-based notes management and organizer."
243 :tag "Org"
244 :group 'outlines
245 :group 'calendar)
247 (defcustom org-mode-hook nil
248 "Mode hook for Org-mode, run after the mode was turned on."
249 :group 'org
250 :type 'hook)
252 (defcustom org-load-hook nil
253 "Hook that is run after org.el has been loaded."
254 :group 'org
255 :type 'hook)
257 (defcustom org-log-buffer-setup-hook nil
258 "Hook that is run after an Org log buffer is created."
259 :group 'org
260 :type 'hook)
262 (defvar org-modules) ; defined below
263 (defvar org-modules-loaded nil
264 "Have the modules been loaded already?")
266 (defun org-load-modules-maybe (&optional force)
267 "Load all extensions listed in `org-modules'."
268 (when (or force (not org-modules-loaded))
269 (mapc (lambda (ext)
270 (condition-case nil (require ext)
271 (error (message "Problems while trying to load feature `%s'" ext))))
272 org-modules)
273 (setq org-modules-loaded t)))
275 (defun org-set-modules (var value)
276 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
277 (set var value)
278 (when (featurep 'org)
279 (org-load-modules-maybe 'force)))
281 (when (org-bound-and-true-p org-modules)
282 (let ((a (member 'org-infojs org-modules)))
283 (and a (setcar a 'org-jsinfo))))
285 (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)
286 "Modules that should always be loaded together with org.el.
287 If a description starts with <C>, the file is not part of Emacs
288 and loading it will require that you have downloaded and properly installed
289 the org-mode distribution.
291 You can also use this system to load external packages (i.e. neither Org
292 core modules, nor modules from the CONTRIB directory). Just add symbols
293 to the end of the list. If the package is called org-xyz.el, then you need
294 to add the symbol `xyz', and the package must have a call to
296 (provide 'org-xyz)"
297 :group 'org
298 :set 'org-set-modules
299 :type
300 '(set :greedy t
301 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
302 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
303 (const :tag " crypt: Encryption of subtrees" org-crypt)
304 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
305 (const :tag " docview: Links to doc-view buffers" org-docview)
306 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
307 (const :tag " id: Global IDs for identifying entries" org-id)
308 (const :tag " info: Links to Info nodes" org-info)
309 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
310 (const :tag " habit: Track your consistency with habits" org-habit)
311 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
312 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
313 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
314 (const :tag " mew Links to Mew folders/messages" org-mew)
315 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
316 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
317 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
318 (const :tag " special-blocks: Turn blocks into LaTeX envs and HTML divs" org-special-blocks)
319 (const :tag " vm: Links to VM folders/messages" org-vm)
320 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
321 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
322 (const :tag " mouse: Additional mouse support" org-mouse)
323 (const :tag " TaskJuggler: Export tasks to a TaskJuggler project" org-taskjuggler)
325 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
326 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
327 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
328 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
329 (const :tag "C collector: Collect properties into tables" org-collector)
330 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
331 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
332 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
333 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
334 (const :tag "C eval: Include command output as text" org-eval)
335 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
336 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
337 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
338 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
339 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
341 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
343 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
344 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
345 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
346 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
347 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
348 (const :tag "C mac-link-grabber Grab links and URLs from various Mac applications" org-mac-link-grabber)
349 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
350 (const :tag "C mtags: Support for muse-like tags" org-mtags)
351 (const :tag "C odt: OpenDocumentText exporter for Org-mode" org-odt)
352 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
353 (const :tag "C registry: A registry for Org-mode links" org-registry)
354 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
355 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
356 (const :tag "C secretary: Team management with org-mode" org-secretary)
357 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
358 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
359 (const :tag "C track: Keep up with Org-mode development" org-track)
360 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
361 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
362 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
364 (defcustom org-support-shift-select nil
365 "Non-nil means make shift-cursor commands select text when possible.
367 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
368 start selecting a region, or enlarge regions started in this way.
369 In Org-mode, in special contexts, these same keys are used for
370 other purposes, important enough to compete with shift selection.
371 Org tries to balance these needs by supporting `shift-select-mode'
372 outside these special contexts, under control of this variable.
374 The default of this variable is nil, to avoid confusing behavior. Shifted
375 cursor keys will then execute Org commands in the following contexts:
376 - on a headline, changing TODO state (left/right) and priority (up/down)
377 - on a time stamp, changing the time
378 - in a plain list item, changing the bullet type
379 - in a property definition line, switching between allowed values
380 - in the BEGIN line of a clock table (changing the time block).
381 Outside these contexts, the commands will throw an error.
383 When this variable is t and the cursor is not in a special
384 context, Org-mode will support shift-selection for making and
385 enlarging regions. To make this more effective, the bullet
386 cycling will no longer happen anywhere in an item line, but only
387 if the cursor is exactly on the bullet.
389 If you set this variable to the symbol `always', then the keys
390 will not be special in headlines, property lines, and item lines,
391 to make shift selection work there as well. If this is what you
392 want, you can use the following alternative commands: `C-c C-t'
393 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
394 can be used to switch TODO sets, `C-c -' to cycle item bullet
395 types, and properties can be edited by hand or in column view.
397 However, when the cursor is on a timestamp, shift-cursor commands
398 will still edit the time stamp - this is just too good to give up.
400 XEmacs user should have this variable set to nil, because
401 `shift-select-mode' is in Emacs 23 or later only."
402 :group 'org
403 :type '(choice
404 (const :tag "Never" nil)
405 (const :tag "When outside special context" t)
406 (const :tag "Everywhere except timestamps" always)))
408 (defcustom org-loop-over-headlines-in-active-region nil
409 "Shall some commands act upon headlines in the active region?
411 When set to `t', some commands will be performed in all headlines
412 within the active region.
414 When set to a string, those commands will be performed on the
415 matching headlines within the active region. Such string must be
416 a tags/property/todo match as it is used in the agenda tags view.
418 The list of commands is:
419 - `org-schedule'
420 - `org-deadline'"
421 :type '(choice (const :tag "Don't loop" nil)
422 (const :tag "All headlines in active region" t)
423 (string :tag "Tags/Property/Todo matcher"))
424 :group 'org-todo
425 :group 'org-archive)
427 (defgroup org-startup nil
428 "Options concerning startup of Org-mode."
429 :tag "Org Startup"
430 :group 'org)
432 (defcustom org-startup-folded t
433 "Non-nil means entering Org-mode will switch to OVERVIEW.
434 This can also be configured on a per-file basis by adding one of
435 the following lines anywhere in the buffer:
437 #+STARTUP: fold (or `overview', this is equivalent)
438 #+STARTUP: nofold (or `showall', this is equivalent)
439 #+STARTUP: content
440 #+STARTUP: showeverything"
441 :group 'org-startup
442 :type '(choice
443 (const :tag "nofold: show all" nil)
444 (const :tag "fold: overview" t)
445 (const :tag "content: all headlines" content)
446 (const :tag "show everything, even drawers" showeverything)))
448 (defcustom org-startup-truncated t
449 "Non-nil means entering Org-mode will set `truncate-lines'.
450 This is useful since some lines containing links can be very long and
451 uninteresting. Also tables look terrible when wrapped."
452 :group 'org-startup
453 :type 'boolean)
455 (defcustom org-startup-indented nil
456 "Non-nil means turn on `org-indent-mode' on startup.
457 This can also be configured on a per-file basis by adding one of
458 the following lines anywhere in the buffer:
460 #+STARTUP: indent
461 #+STARTUP: noindent"
462 :group 'org-structure
463 :type '(choice
464 (const :tag "Not" nil)
465 (const :tag "Globally (slow on startup in large files)" t)))
467 (defcustom org-use-sub-superscripts t
468 "Non-nil means interpret \"_\" and \"^\" for export.
469 When this option is turned on, you can use TeX-like syntax for sub- and
470 superscripts. Several characters after \"_\" or \"^\" will be
471 considered as a single item - so grouping with {} is normally not
472 needed. For example, the following things will be parsed as single
473 sub- or superscripts.
475 10^24 or 10^tau several digits will be considered 1 item.
476 10^-12 or 10^-tau a leading sign with digits or a word
477 x^2-y^3 will be read as x^2 - y^3, because items are
478 terminated by almost any nonword/nondigit char.
479 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
481 Still, ambiguity is possible - so when in doubt use {} to enclose the
482 sub/superscript. If you set this variable to the symbol `{}',
483 the braces are *required* in order to trigger interpretations as
484 sub/superscript. This can be helpful in documents that need \"_\"
485 frequently in plain text.
487 Not all export backends support this, but HTML does.
489 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
490 :group 'org-startup
491 :group 'org-export-translation
492 :type '(choice
493 (const :tag "Always interpret" t)
494 (const :tag "Only with braces" {})
495 (const :tag "Never interpret" nil)))
497 (if (fboundp 'defvaralias)
498 (defvaralias 'org-export-with-sub-superscripts 'org-use-sub-superscripts))
501 (defcustom org-startup-with-beamer-mode nil
502 "Non-nil means turn on `org-beamer-mode' on startup.
503 This can also be configured on a per-file basis by adding one of
504 the following lines anywhere in the buffer:
506 #+STARTUP: beamer"
507 :group 'org-startup
508 :type 'boolean)
510 (defcustom org-startup-align-all-tables nil
511 "Non-nil means align all tables when visiting a file.
512 This is useful when the column width in tables is forced with <N> cookies
513 in table fields. Such tables will look correct only after the first re-align.
514 This can also be configured on a per-file basis by adding one of
515 the following lines anywhere in the buffer:
516 #+STARTUP: align
517 #+STARTUP: noalign"
518 :group 'org-startup
519 :type 'boolean)
521 (defcustom org-startup-with-inline-images nil
522 "Non-nil means show inline images when loading a new Org file.
523 This can also be configured on a per-file basis by adding one of
524 the following lines anywhere in the buffer:
525 #+STARTUP: inlineimages
526 #+STARTUP: noinlineimages"
527 :group 'org-startup
528 :type 'boolean)
530 (defcustom org-insert-mode-line-in-empty-file nil
531 "Non-nil means insert the first line setting Org-mode in empty files.
532 When the function `org-mode' is called interactively in an empty file, this
533 normally means that the file name does not automatically trigger Org-mode.
534 To ensure that the file will always be in Org-mode in the future, a
535 line enforcing Org-mode will be inserted into the buffer, if this option
536 has been set."
537 :group 'org-startup
538 :type 'boolean)
540 (defcustom org-replace-disputed-keys nil
541 "Non-nil means use alternative key bindings for some keys.
542 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
543 These keys are also used by other packages like shift-selection-mode'
544 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
545 If you want to use Org-mode together with one of these other modes,
546 or more generally if you would like to move some Org-mode commands to
547 other keys, set this variable and configure the keys with the variable
548 `org-disputed-keys'.
550 This option is only relevant at load-time of Org-mode, and must be set
551 *before* org.el is loaded. Changing it requires a restart of Emacs to
552 become effective."
553 :group 'org-startup
554 :type 'boolean)
556 (defcustom org-use-extra-keys nil
557 "Non-nil means use extra key sequence definitions for certain commands.
558 This happens automatically if you run XEmacs or if `window-system'
559 is nil. This variable lets you do the same manually. You must
560 set it before loading org.
562 Example: on Carbon Emacs 22 running graphically, with an external
563 keyboard on a Powerbook, the default way of setting M-left might
564 not work for either Alt or ESC. Setting this variable will make
565 it work for ESC."
566 :group 'org-startup
567 :type 'boolean)
569 (if (fboundp 'defvaralias)
570 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
572 (defcustom org-disputed-keys
573 '(([(shift up)] . [(meta p)])
574 ([(shift down)] . [(meta n)])
575 ([(shift left)] . [(meta -)])
576 ([(shift right)] . [(meta +)])
577 ([(control shift right)] . [(meta shift +)])
578 ([(control shift left)] . [(meta shift -)]))
579 "Keys for which Org-mode and other modes compete.
580 This is an alist, cars are the default keys, second element specifies
581 the alternative to use when `org-replace-disputed-keys' is t.
583 Keys can be specified in any syntax supported by `define-key'.
584 The value of this option takes effect only at Org-mode's startup,
585 therefore you'll have to restart Emacs to apply it after changing."
586 :group 'org-startup
587 :type 'alist)
589 (defun org-key (key)
590 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
591 Or return the original if not disputed.
592 Also apply the translations defined in `org-xemacs-key-equivalents'."
593 (when org-replace-disputed-keys
594 (let* ((nkey (key-description key))
595 (x (org-find-if (lambda (x)
596 (equal (key-description (car x)) nkey))
597 org-disputed-keys)))
598 (setq key (if x (cdr x) key))))
599 (when (featurep 'xemacs)
600 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
601 key)
603 (defun org-find-if (predicate seq)
604 (catch 'exit
605 (while seq
606 (if (funcall predicate (car seq))
607 (throw 'exit (car seq))
608 (pop seq)))))
610 (defun org-defkey (keymap key def)
611 "Define a key, possibly translated, as returned by `org-key'."
612 (define-key keymap (org-key key) def))
614 (defcustom org-ellipsis nil
615 "The ellipsis to use in the Org-mode outline.
616 When nil, just use the standard three dots. When a string, use that instead,
617 When a face, use the standard 3 dots, but with the specified face.
618 The change affects only Org-mode (which will then use its own display table).
619 Changing this requires executing `M-x org-mode' in a buffer to become
620 effective."
621 :group 'org-startup
622 :type '(choice (const :tag "Default" nil)
623 (face :tag "Face" :value org-warning)
624 (string :tag "String" :value "...#")))
626 (defvar org-display-table nil
627 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
629 (defgroup org-keywords nil
630 "Keywords in Org-mode."
631 :tag "Org Keywords"
632 :group 'org)
634 (defcustom org-deadline-string "DEADLINE:"
635 "String to mark deadline entries.
636 A deadline is this string, followed by a time stamp. Should be a word,
637 terminated by a colon. You can insert a schedule keyword and
638 a timestamp with \\[org-deadline].
639 Changes become only effective after restarting Emacs."
640 :group 'org-keywords
641 :type 'string)
643 (defcustom org-scheduled-string "SCHEDULED:"
644 "String to mark scheduled TODO entries.
645 A schedule is this string, followed by a time stamp. Should be a word,
646 terminated by a colon. You can insert a schedule keyword and
647 a timestamp with \\[org-schedule].
648 Changes become only effective after restarting Emacs."
649 :group 'org-keywords
650 :type 'string)
652 (defcustom org-closed-string "CLOSED:"
653 "String used as the prefix for timestamps logging closing a TODO entry."
654 :group 'org-keywords
655 :type 'string)
657 (defcustom org-clock-string "CLOCK:"
658 "String used as prefix for timestamps clocking work hours on an item."
659 :group 'org-keywords
660 :type 'string)
662 (defcustom org-comment-string "COMMENT"
663 "Entries starting with this keyword will never be exported.
664 An entry can be toggled between COMMENT and normal with
665 \\[org-toggle-comment].
666 Changes become only effective after restarting Emacs."
667 :group 'org-keywords
668 :type 'string)
670 (defcustom org-quote-string "QUOTE"
671 "Entries starting with this keyword will be exported in fixed-width font.
672 Quoting applies only to the text in the entry following the headline, and does
673 not extend beyond the next headline, even if that is lower level.
674 An entry can be toggled between QUOTE and normal with
675 \\[org-toggle-fixed-width-section]."
676 :group 'org-keywords
677 :type 'string)
679 (defconst org-repeat-re
680 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)"
681 "Regular expression for specifying repeated events.
682 After a match, group 1 contains the repeat expression.")
684 (defgroup org-structure nil
685 "Options concerning the general structure of Org-mode files."
686 :tag "Org Structure"
687 :group 'org)
689 (defgroup org-reveal-location nil
690 "Options about how to make context of a location visible."
691 :tag "Org Reveal Location"
692 :group 'org-structure)
694 (defconst org-context-choice
695 '(choice
696 (const :tag "Always" t)
697 (const :tag "Never" nil)
698 (repeat :greedy t :tag "Individual contexts"
699 (cons
700 (choice :tag "Context"
701 (const agenda)
702 (const org-goto)
703 (const occur-tree)
704 (const tags-tree)
705 (const link-search)
706 (const mark-goto)
707 (const bookmark-jump)
708 (const isearch)
709 (const default))
710 (boolean))))
711 "Contexts for the reveal options.")
713 (defcustom org-show-hierarchy-above '((default . t))
714 "Non-nil means show full hierarchy when revealing a location.
715 Org-mode often shows locations in an org-mode file which might have
716 been invisible before. When this is set, the hierarchy of headings
717 above the exposed location is shown.
718 Turning this off for example for sparse trees makes them very compact.
719 Instead of t, this can also be an alist specifying this option for different
720 contexts. Valid contexts are
721 agenda when exposing an entry from the agenda
722 org-goto when using the command `org-goto' on key C-c C-j
723 occur-tree when using the command `org-occur' on key C-c /
724 tags-tree when constructing a sparse tree based on tags matches
725 link-search when exposing search matches associated with a link
726 mark-goto when exposing the jump goal of a mark
727 bookmark-jump when exposing a bookmark location
728 isearch when exiting from an incremental search
729 default default for all contexts not set explicitly"
730 :group 'org-reveal-location
731 :type org-context-choice)
733 (defcustom org-show-following-heading '((default . nil))
734 "Non-nil means show following heading when revealing a location.
735 Org-mode often shows locations in an org-mode file which might have
736 been invisible before. When this is set, the heading following the
737 match is shown.
738 Turning this off for example for sparse trees makes them very compact,
739 but makes it harder to edit the location of the match. In such a case,
740 use the command \\[org-reveal] to show more context.
741 Instead of t, this can also be an alist specifying this option for different
742 contexts. See `org-show-hierarchy-above' for valid contexts."
743 :group 'org-reveal-location
744 :type org-context-choice)
746 (defcustom org-show-siblings '((default . nil) (isearch t))
747 "Non-nil means show all sibling heading when revealing a location.
748 Org-mode often shows locations in an org-mode file which might have
749 been invisible before. When this is set, the sibling of the current entry
750 heading are all made visible. If `org-show-hierarchy-above' is t,
751 the same happens on each level of the hierarchy above the current entry.
753 By default this is on for the isearch context, off for all other contexts.
754 Turning this off for example for sparse trees makes them very compact,
755 but makes it harder to edit the location of the match. In such a case,
756 use the command \\[org-reveal] to show more context.
757 Instead of t, this can also be an alist specifying this option for different
758 contexts. See `org-show-hierarchy-above' for valid contexts."
759 :group 'org-reveal-location
760 :type org-context-choice)
762 (defcustom org-show-entry-below '((default . nil))
763 "Non-nil means show the entry below a headline when revealing a location.
764 Org-mode often shows locations in an org-mode file which might have
765 been invisible before. When this is set, the text below the headline that is
766 exposed is also shown.
768 By default this is off for all contexts.
769 Instead of t, this can also be an alist specifying this option for different
770 contexts. See `org-show-hierarchy-above' for valid contexts."
771 :group 'org-reveal-location
772 :type org-context-choice)
774 (defcustom org-indirect-buffer-display 'other-window
775 "How should indirect tree buffers be displayed?
776 This applies to indirect buffers created with the commands
777 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
778 Valid values are:
779 current-window Display in the current window
780 other-window Just display in another window.
781 dedicated-frame Create one new frame, and re-use it each time.
782 new-frame Make a new frame each time. Note that in this case
783 previously-made indirect buffers are kept, and you need to
784 kill these buffers yourself."
785 :group 'org-structure
786 :group 'org-agenda-windows
787 :type '(choice
788 (const :tag "In current window" current-window)
789 (const :tag "In current frame, other window" other-window)
790 (const :tag "Each time a new frame" new-frame)
791 (const :tag "One dedicated frame" dedicated-frame)))
793 (defcustom org-use-speed-commands nil
794 "Non-nil means activate single letter commands at beginning of a headline.
795 This may also be a function to test for appropriate locations where speed
796 commands should be active."
797 :group 'org-structure
798 :type '(choice
799 (const :tag "Never" nil)
800 (const :tag "At beginning of headline stars" t)
801 (function)))
803 (defcustom org-speed-commands-user nil
804 "Alist of additional speed commands.
805 This list will be checked before `org-speed-commands-default'
806 when the variable `org-use-speed-commands' is non-nil
807 and when the cursor is at the beginning of a headline.
808 The car if each entry is a string with a single letter, which must
809 be assigned to `self-insert-command' in the global map.
810 The cdr is either a command to be called interactively, a function
811 to be called, or a form to be evaluated.
812 An entry that is just a list with a single string will be interpreted
813 as a descriptive headline that will be added when listing the speed
814 commands in the Help buffer using the `?' speed command."
815 :group 'org-structure
816 :type '(repeat :value ("k" . ignore)
817 (choice :value ("k" . ignore)
818 (list :tag "Descriptive Headline" (string :tag "Headline"))
819 (cons :tag "Letter and Command"
820 (string :tag "Command letter")
821 (choice
822 (function)
823 (sexp))))))
825 (defgroup org-cycle nil
826 "Options concerning visibility cycling in Org-mode."
827 :tag "Org Cycle"
828 :group 'org-structure)
830 (defcustom org-cycle-skip-children-state-if-no-children t
831 "Non-nil means skip CHILDREN state in entries that don't have any."
832 :group 'org-cycle
833 :type 'boolean)
835 (defcustom org-cycle-max-level nil
836 "Maximum level which should still be subject to visibility cycling.
837 Levels higher than this will, for cycling, be treated as text, not a headline.
838 When `org-odd-levels-only' is set, a value of N in this variable actually
839 means 2N-1 stars as the limiting headline.
840 When nil, cycle all levels.
841 Note that the limiting level of cycling is also influenced by
842 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
843 `org-inlinetask-min-level' is, cycling will be limited to levels one less
844 than its value."
845 :group 'org-cycle
846 :type '(choice
847 (const :tag "No limit" nil)
848 (integer :tag "Maximum level")))
850 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK")
851 "Names of drawers. Drawers are not opened by cycling on the headline above.
852 Drawers only open with a TAB on the drawer line itself. A drawer looks like
853 this:
854 :DRAWERNAME:
855 .....
856 :END:
857 The drawer \"PROPERTIES\" is special for capturing properties through
858 the property API.
860 Drawers can be defined on the per-file basis with a line like:
862 #+DRAWERS: HIDDEN STATE PROPERTIES"
863 :group 'org-structure
864 :group 'org-cycle
865 :type '(repeat (string :tag "Drawer Name")))
867 (defcustom org-hide-block-startup nil
868 "Non-nil means entering Org-mode will fold all blocks.
869 This can also be set in on a per-file basis with
871 #+STARTUP: hideblocks
872 #+STARTUP: showblocks"
873 :group 'org-startup
874 :group 'org-cycle
875 :type 'boolean)
877 (defcustom org-cycle-global-at-bob nil
878 "Cycle globally if cursor is at beginning of buffer and not at a headline.
879 This makes it possible to do global cycling without having to use S-TAB or
880 \\[universal-argument] TAB. For this special case to work, the first line \
881 of the buffer
882 must not be a headline - it may be empty or some other text. When used in
883 this way, `org-cycle-hook' is disables temporarily, to make sure the
884 cursor stays at the beginning of the buffer.
885 When this option is nil, don't do anything special at the beginning
886 of the buffer."
887 :group 'org-cycle
888 :type 'boolean)
890 (defcustom org-cycle-level-after-item/entry-creation t
891 "Non-nil means cycle entry level or item indentation in new empty entries.
893 When the cursor is at the end of an empty headline, i.e with only stars
894 and maybe a TODO keyword, TAB will then switch the entry to become a child,
895 and then all possible ancestor states, before returning to the original state.
896 This makes data entry extremely fast: M-RET to create a new headline,
897 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
899 When the cursor is at the end of an empty plain list item, one TAB will
900 make it a subitem, two or more tabs will back up to make this an item
901 higher up in the item hierarchy."
902 :group 'org-cycle
903 :type 'boolean)
905 (defcustom org-cycle-emulate-tab t
906 "Where should `org-cycle' emulate TAB.
907 nil Never
908 white Only in completely white lines
909 whitestart Only at the beginning of lines, before the first non-white char
910 t Everywhere except in headlines
911 exc-hl-bol Everywhere except at the start of a headline
912 If TAB is used in a place where it does not emulate TAB, the current subtree
913 visibility is cycled."
914 :group 'org-cycle
915 :type '(choice (const :tag "Never" nil)
916 (const :tag "Only in completely white lines" white)
917 (const :tag "Before first char in a line" whitestart)
918 (const :tag "Everywhere except in headlines" t)
919 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
922 (defcustom org-cycle-separator-lines 2
923 "Number of empty lines needed to keep an empty line between collapsed trees.
924 If you leave an empty line between the end of a subtree and the following
925 headline, this empty line is hidden when the subtree is folded.
926 Org-mode will leave (exactly) one empty line visible if the number of
927 empty lines is equal or larger to the number given in this variable.
928 So the default 2 means at least 2 empty lines after the end of a subtree
929 are needed to produce free space between a collapsed subtree and the
930 following headline.
932 If the number is negative, and the number of empty lines is at least -N,
933 all empty lines are shown.
935 Special case: when 0, never leave empty lines in collapsed view."
936 :group 'org-cycle
937 :type 'integer)
938 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
940 (defcustom org-pre-cycle-hook nil
941 "Hook that is run before visibility cycling is happening.
942 The function(s) in this hook must accept a single argument which indicates
943 the new state that will be set right after running this hook. The
944 argument is a symbol. Before a global state change, it can have the values
945 `overview', `content', or `all'. Before a local state change, it can have
946 the values `folded', `children', or `subtree'."
947 :group 'org-cycle
948 :type 'hook)
950 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
951 org-cycle-hide-drawers
952 org-cycle-show-empty-lines
953 org-optimize-window-after-visibility-change)
954 "Hook that is run after `org-cycle' has changed the buffer visibility.
955 The function(s) in this hook must accept a single argument which indicates
956 the new state that was set by the most recent `org-cycle' command. The
957 argument is a symbol. After a global state change, it can have the values
958 `overview', `content', or `all'. After a local state change, it can have
959 the values `folded', `children', or `subtree'."
960 :group 'org-cycle
961 :type 'hook)
963 (defgroup org-edit-structure nil
964 "Options concerning structure editing in Org-mode."
965 :tag "Org Edit Structure"
966 :group 'org-structure)
968 (defcustom org-odd-levels-only nil
969 "Non-nil means skip even levels and only use odd levels for the outline.
970 This has the effect that two stars are being added/taken away in
971 promotion/demotion commands. It also influences how levels are
972 handled by the exporters.
973 Changing it requires restart of `font-lock-mode' to become effective
974 for fontification also in regions already fontified.
975 You may also set this on a per-file basis by adding one of the following
976 lines to the buffer:
978 #+STARTUP: odd
979 #+STARTUP: oddeven"
980 :group 'org-edit-structure
981 :group 'org-appearance
982 :type 'boolean)
984 (defcustom org-adapt-indentation t
985 "Non-nil means adapt indentation to outline node level.
987 When this variable is set, Org assumes that you write outlines by
988 indenting text in each node to align with the headline (after the stars).
989 The following issues are influenced by this variable:
991 - When this is set and the *entire* text in an entry is indented, the
992 indentation is increased by one space in a demotion command, and
993 decreased by one in a promotion command. If any line in the entry
994 body starts with text at column 0, indentation is not changed at all.
996 - Property drawers and planning information is inserted indented when
997 this variable s set. When nil, they will not be indented.
999 - TAB indents a line relative to context. The lines below a headline
1000 will be indented when this variable is set.
1002 Note that this is all about true indentation, by adding and removing
1003 space characters. See also `org-indent.el' which does level-dependent
1004 indentation in a virtual way, i.e. at display time in Emacs."
1005 :group 'org-edit-structure
1006 :type 'boolean)
1008 (defcustom org-special-ctrl-a/e nil
1009 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1011 When t, `C-a' will bring back the cursor to the beginning of the
1012 headline text, i.e. after the stars and after a possible TODO keyword.
1013 In an item, this will be the position after the bullet.
1014 When the cursor is already at that position, another `C-a' will bring
1015 it to the beginning of the line.
1017 `C-e' will jump to the end of the headline, ignoring the presence of tags
1018 in the headline. A second `C-e' will then jump to the true end of the
1019 line, after any tags. This also means that, when this variable is
1020 non-nil, `C-e' also will never jump beyond the end of the heading of a
1021 folded section, i.e. not after the ellipses.
1023 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
1024 going to the true line boundary first. Only a directly following, identical
1025 keypress will bring the cursor to the special positions.
1027 This may also be a cons cell where the behavior for `C-a' and `C-e' is
1028 set separately."
1029 :group 'org-edit-structure
1030 :type '(choice
1031 (const :tag "off" nil)
1032 (const :tag "on: after stars/bullet and before tags first" t)
1033 (const :tag "reversed: true line boundary first" reversed)
1034 (cons :tag "Set C-a and C-e separately"
1035 (choice :tag "Special C-a"
1036 (const :tag "off" nil)
1037 (const :tag "on: after stars/bullet first" t)
1038 (const :tag "reversed: before stars/bullet first" reversed))
1039 (choice :tag "Special C-e"
1040 (const :tag "off" nil)
1041 (const :tag "on: before tags first" t)
1042 (const :tag "reversed: after tags first" reversed)))))
1043 (if (fboundp 'defvaralias)
1044 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
1046 (defcustom org-special-ctrl-k nil
1047 "Non-nil means `C-k' will behave specially in headlines.
1048 When nil, `C-k' will call the default `kill-line' command.
1049 When t, the following will happen while the cursor is in the headline:
1051 - When the cursor is at the beginning of a headline, kill the entire
1052 line and possible the folded subtree below the line.
1053 - When in the middle of the headline text, kill the headline up to the tags.
1054 - When after the headline text, kill the tags."
1055 :group 'org-edit-structure
1056 :type 'boolean)
1058 (defcustom org-ctrl-k-protect-subtree nil
1059 "Non-nil means, do not delete a hidden subtree with C-k.
1060 When set to the symbol `error', simply throw an error when C-k is
1061 used to kill (part-of) a headline that has hidden text behind it.
1062 Any other non-nil value will result in a query to the user, if it is
1063 OK to kill that hidden subtree. When nil, kill without remorse."
1064 :group 'org-edit-structure
1065 :type '(choice
1066 (const :tag "Do not protect hidden subtrees" nil)
1067 (const :tag "Protect hidden subtrees with a security query" t)
1068 (const :tag "Never kill a hidden subtree with C-k" error)))
1070 (defcustom org-catch-invisible-edits nil
1071 "Check if in invisible region before inserting or deleting a character.
1072 Valid values are:
1074 nil Do not check, so just do invisible edits.
1075 error Throw an error and do nothing.
1076 show Make point visible, and do the requested edit.
1077 show-and-error Make point visible, then throw an error and abort the edit.
1078 smart Make point visible, and do insertion/deletion if it is
1079 adjacent to visible text and the change feels predictable.
1080 Never delete a previously invisible character or add in the
1081 middle or right after an invisible region. Basically, this
1082 allows insertion and backward-delete right before ellipses.
1083 FIXME: maybe in this case we should not even show?"
1084 :group 'org-edit-structure
1085 :type '(choice
1086 (const :tag "Do not check" nil)
1087 (const :tag "Throw error when trying to edit" error)
1088 (const :tag "Unhide, but do not do the edit" show-and-error)
1089 (const :tag "Show invisible part and do the edit" show)
1090 (const :tag "Be smart and do the right thing" smart)))
1092 (defcustom org-yank-folded-subtrees t
1093 "Non-nil means when yanking subtrees, fold them.
1094 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1095 it starts with a heading and all other headings in it are either children
1096 or siblings, then fold all the subtrees. However, do this only if no
1097 text after the yank would be swallowed into a folded tree by this action."
1098 :group 'org-edit-structure
1099 :type 'boolean)
1101 (defcustom org-yank-adjusted-subtrees nil
1102 "Non-nil means when yanking subtrees, adjust the level.
1103 With this setting, `org-paste-subtree' is used to insert the subtree, see
1104 this function for details."
1105 :group 'org-edit-structure
1106 :type 'boolean)
1108 (defcustom org-M-RET-may-split-line '((default . t))
1109 "Non-nil means M-RET will split the line at the cursor position.
1110 When nil, it will go to the end of the line before making a
1111 new line.
1112 You may also set this option in a different way for different
1113 contexts. Valid contexts are:
1115 headline when creating a new headline
1116 item when creating a new item
1117 table in a table field
1118 default the value to be used for all contexts not explicitly
1119 customized"
1120 :group 'org-structure
1121 :group 'org-table
1122 :type '(choice
1123 (const :tag "Always" t)
1124 (const :tag "Never" nil)
1125 (repeat :greedy t :tag "Individual contexts"
1126 (cons
1127 (choice :tag "Context"
1128 (const headline)
1129 (const item)
1130 (const table)
1131 (const default))
1132 (boolean)))))
1135 (defcustom org-insert-heading-respect-content nil
1136 "Non-nil means insert new headings after the current subtree.
1137 When nil, the new heading is created directly after the current line.
1138 The commands \\[org-insert-heading-respect-content] and
1139 \\[org-insert-todo-heading-respect-content] turn this variable on
1140 for the duration of the command."
1141 :group 'org-structure
1142 :type 'boolean)
1144 (defcustom org-blank-before-new-entry '((heading . auto)
1145 (plain-list-item . auto))
1146 "Should `org-insert-heading' leave a blank line before new heading/item?
1147 The value is an alist, with `heading' and `plain-list-item' as CAR,
1148 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1149 which case Org will look at the surrounding headings/items and try to
1150 make an intelligent decision whether to insert a blank line or not.
1152 For plain lists, if the variable `org-empty-line-terminates-plain-lists' is
1153 set, the setting here is ignored and no empty line is inserted, to avoid
1154 breaking the list structure."
1155 :group 'org-edit-structure
1156 :type '(list
1157 (cons (const heading)
1158 (choice (const :tag "Never" nil)
1159 (const :tag "Always" t)
1160 (const :tag "Auto" auto)))
1161 (cons (const plain-list-item)
1162 (choice (const :tag "Never" nil)
1163 (const :tag "Always" t)
1164 (const :tag "Auto" auto)))))
1166 (defcustom org-insert-heading-hook nil
1167 "Hook being run after inserting a new heading."
1168 :group 'org-edit-structure
1169 :type 'hook)
1171 (defcustom org-enable-fixed-width-editor t
1172 "Non-nil means lines starting with \":\" are treated as fixed-width.
1173 This currently only means they are never auto-wrapped.
1174 When nil, such lines will be treated like ordinary lines.
1175 See also the QUOTE keyword."
1176 :group 'org-edit-structure
1177 :type 'boolean)
1179 (defcustom org-goto-auto-isearch t
1180 "Non-nil means typing characters in `org-goto' starts incremental search."
1181 :group 'org-edit-structure
1182 :type 'boolean)
1184 (defgroup org-sparse-trees nil
1185 "Options concerning sparse trees in Org-mode."
1186 :tag "Org Sparse Trees"
1187 :group 'org-structure)
1189 (defcustom org-highlight-sparse-tree-matches t
1190 "Non-nil means highlight all matches that define a sparse tree.
1191 The highlights will automatically disappear the next time the buffer is
1192 changed by an edit command."
1193 :group 'org-sparse-trees
1194 :type 'boolean)
1196 (defcustom org-remove-highlights-with-change t
1197 "Non-nil means any change to the buffer will remove temporary highlights.
1198 Such highlights are created by `org-occur' and `org-clock-display'.
1199 When nil, `C-c C-c needs to be used to get rid of the highlights.
1200 The highlights created by `org-preview-latex-fragment' always need
1201 `C-c C-c' to be removed."
1202 :group 'org-sparse-trees
1203 :group 'org-time
1204 :type 'boolean)
1207 (defcustom org-occur-hook '(org-first-headline-recenter)
1208 "Hook that is run after `org-occur' has constructed a sparse tree.
1209 This can be used to recenter the window to show as much of the structure
1210 as possible."
1211 :group 'org-sparse-trees
1212 :type 'hook)
1214 (defgroup org-imenu-and-speedbar nil
1215 "Options concerning imenu and speedbar in Org-mode."
1216 :tag "Org Imenu and Speedbar"
1217 :group 'org-structure)
1219 (defcustom org-imenu-depth 2
1220 "The maximum level for Imenu access to Org-mode headlines.
1221 This also applied for speedbar access."
1222 :group 'org-imenu-and-speedbar
1223 :type 'integer)
1225 (defgroup org-table nil
1226 "Options concerning tables in Org-mode."
1227 :tag "Org Table"
1228 :group 'org)
1230 (defcustom org-enable-table-editor 'optimized
1231 "Non-nil means lines starting with \"|\" are handled by the table editor.
1232 When nil, such lines will be treated like ordinary lines.
1234 When equal to the symbol `optimized', the table editor will be optimized to
1235 do the following:
1236 - Automatic overwrite mode in front of whitespace in table fields.
1237 This makes the structure of the table stay in tact as long as the edited
1238 field does not exceed the column width.
1239 - Minimize the number of realigns. Normally, the table is aligned each time
1240 TAB or RET are pressed to move to another field. With optimization this
1241 happens only if changes to a field might have changed the column width.
1242 Optimization requires replacing the functions `self-insert-command',
1243 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1244 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1245 very good at guessing when a re-align will be necessary, but you can always
1246 force one with \\[org-ctrl-c-ctrl-c].
1248 If you would like to use the optimized version in Org-mode, but the
1249 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1251 This variable can be used to turn on and off the table editor during a session,
1252 but in order to toggle optimization, a restart is required.
1254 See also the variable `org-table-auto-blank-field'."
1255 :group 'org-table
1256 :type '(choice
1257 (const :tag "off" nil)
1258 (const :tag "on" t)
1259 (const :tag "on, optimized" optimized)))
1261 (defcustom org-self-insert-cluster-for-undo t
1262 "Non-nil means cluster self-insert commands for undo when possible.
1263 If this is set, then, like in the Emacs command loop, 20 consecutive
1264 characters will be undone together.
1265 This is configurable, because there is some impact on typing performance."
1266 :group 'org-table
1267 :type 'boolean)
1269 (defcustom org-table-tab-recognizes-table.el t
1270 "Non-nil means TAB will automatically notice a table.el table.
1271 When it sees such a table, it moves point into it and - if necessary -
1272 calls `table-recognize-table'."
1273 :group 'org-table-editing
1274 :type 'boolean)
1276 (defgroup org-link nil
1277 "Options concerning links in Org-mode."
1278 :tag "Org Link"
1279 :group 'org)
1281 (defvar org-link-abbrev-alist-local nil
1282 "Buffer-local version of `org-link-abbrev-alist', which see.
1283 The value of this is taken from the #+LINK lines.")
1284 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1286 (defcustom org-link-abbrev-alist nil
1287 "Alist of link abbreviations.
1288 The car of each element is a string, to be replaced at the start of a link.
1289 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1290 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1292 [[linkkey:tag][description]]
1294 The 'linkkey' must be a word word, starting with a letter, followed
1295 by letters, numbers, '-' or '_'.
1297 If REPLACE is a string, the tag will simply be appended to create the link.
1298 If the string contains \"%s\", the tag will be inserted there. Alternatively,
1299 the placeholder \"%h\" will cause a url-encoded version of the tag to
1300 be inserted at that point (see the function `url-hexify-string').
1302 REPLACE may also be a function that will be called with the tag as the
1303 only argument to create the link, which should be returned as a string.
1305 See the manual for examples."
1306 :group 'org-link
1307 :type '(repeat
1308 (cons
1309 (string :tag "Protocol")
1310 (choice
1311 (string :tag "Format")
1312 (function)))))
1314 (defcustom org-descriptive-links t
1315 "Non-nil means Org will display descriptive links.
1316 E.g. [[http://orgmode.org][Org website]] will be displayed as
1317 \"Org Website\", hiding the link itself and just displaying its
1318 description. When set to `nil', Org will display the full links
1319 literally.
1321 You can interactively set the value of this variable by calling
1322 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1323 :group 'org-link
1324 :type 'boolean)
1326 (defcustom org-link-file-path-type 'adaptive
1327 "How the path name in file links should be stored.
1328 Valid values are:
1330 relative Relative to the current directory, i.e. the directory of the file
1331 into which the link is being inserted.
1332 absolute Absolute path, if possible with ~ for home directory.
1333 noabbrev Absolute path, no abbreviation of home directory.
1334 adaptive Use relative path for files in the current directory and sub-
1335 directories of it. For other files, use an absolute path."
1336 :group 'org-link
1337 :type '(choice
1338 (const relative)
1339 (const absolute)
1340 (const noabbrev)
1341 (const adaptive)))
1343 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1344 "Types of links that should be activated in Org-mode files.
1345 This is a list of symbols, each leading to the activation of a certain link
1346 type. In principle, it does not hurt to turn on most link types - there may
1347 be a small gain when turning off unused link types. The types are:
1349 bracket The recommended [[link][description]] or [[link]] links with hiding.
1350 angle Links in angular brackets that may contain whitespace like
1351 <bbdb:Carsten Dominik>.
1352 plain Plain links in normal text, no whitespace, like http://google.com.
1353 radio Text that is matched by a radio target, see manual for details.
1354 tag Tag settings in a headline (link to tag search).
1355 date Time stamps (link to calendar).
1356 footnote Footnote labels.
1358 Changing this variable requires a restart of Emacs to become effective."
1359 :group 'org-link
1360 :type '(set :greedy t
1361 (const :tag "Double bracket links" bracket)
1362 (const :tag "Angular bracket links" angle)
1363 (const :tag "Plain text links" plain)
1364 (const :tag "Radio target matches" radio)
1365 (const :tag "Tags" tag)
1366 (const :tag "Timestamps" date)
1367 (const :tag "Footnotes" footnote)))
1369 (defcustom org-make-link-description-function nil
1370 "Function to use to generate link descriptions from links.
1371 If nil the link location will be used. This function must take
1372 two parameters; the first is the link and the second the
1373 description `org-insert-link' has generated, and should return the
1374 description to use."
1375 :group 'org-link
1376 :type 'function)
1378 (defgroup org-link-store nil
1379 "Options concerning storing links in Org-mode."
1380 :tag "Org Store Link"
1381 :group 'org-link)
1383 (defcustom org-email-link-description-format "Email %c: %.30s"
1384 "Format of the description part of a link to an email or usenet message.
1385 The following %-escapes will be replaced by corresponding information:
1387 %F full \"From\" field
1388 %f name, taken from \"From\" field, address if no name
1389 %T full \"To\" field
1390 %t first name in \"To\" field, address if no name
1391 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1392 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1393 %s subject
1394 %d date
1395 %m message-id.
1397 You may use normal field width specification between the % and the letter.
1398 This is for example useful to limit the length of the subject.
1400 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1401 :group 'org-link-store
1402 :type 'string)
1404 (defcustom org-from-is-user-regexp
1405 (let (r1 r2)
1406 (when (and user-mail-address (not (string= user-mail-address "")))
1407 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1408 (when (and user-full-name (not (string= user-full-name "")))
1409 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1410 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1411 "Regexp matched against the \"From:\" header of an email or usenet message.
1412 It should match if the message is from the user him/herself."
1413 :group 'org-link-store
1414 :type 'regexp)
1416 (defcustom org-link-to-org-use-id 'create-if-interactive-and-no-custom-id
1417 "Non-nil means storing a link to an Org file will use entry IDs.
1419 Note that before this variable is even considered, org-id must be loaded,
1420 so please customize `org-modules' and turn it on.
1422 The variable can have the following values:
1424 t Create an ID if needed to make a link to the current entry.
1426 create-if-interactive
1427 If `org-store-link' is called directly (interactively, as a user
1428 command), do create an ID to support the link. But when doing the
1429 job for remember, only use the ID if it already exists. The
1430 purpose of this setting is to avoid proliferation of unwanted
1431 IDs, just because you happen to be in an Org file when you
1432 call `org-remember' that automatically and preemptively
1433 creates a link. If you do want to get an ID link in a remember
1434 template to an entry not having an ID, create it first by
1435 explicitly creating a link to it, using `C-c C-l' first.
1437 create-if-interactive-and-no-custom-id
1438 Like create-if-interactive, but do not create an ID if there is
1439 a CUSTOM_ID property defined in the entry. This is the default.
1441 use-existing
1442 Use existing ID, do not create one.
1444 nil Never use an ID to make a link, instead link using a text search for
1445 the headline text."
1446 :group 'org-link-store
1447 :type '(choice
1448 (const :tag "Create ID to make link" t)
1449 (const :tag "Create if storing link interactively"
1450 create-if-interactive)
1451 (const :tag "Create if storing link interactively and no CUSTOM_ID is present"
1452 create-if-interactive-and-no-custom-id)
1453 (const :tag "Only use existing" use-existing)
1454 (const :tag "Do not use ID to create link" nil)))
1456 (defcustom org-context-in-file-links t
1457 "Non-nil means file links from `org-store-link' contain context.
1458 A search string will be added to the file name with :: as separator and
1459 used to find the context when the link is activated by the command
1460 `org-open-at-point'. When this option is t, the entire active region
1461 will be placed in the search string of the file link. If set to a
1462 positive integer, only the first n lines of context will be stored.
1464 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1465 negates this setting for the duration of the command."
1466 :group 'org-link-store
1467 :type '(choice boolean integer))
1469 (defcustom org-keep-stored-link-after-insertion nil
1470 "Non-nil means keep link in list for entire session.
1472 The command `org-store-link' adds a link pointing to the current
1473 location to an internal list. These links accumulate during a session.
1474 The command `org-insert-link' can be used to insert links into any
1475 Org-mode file (offering completion for all stored links). When this
1476 option is nil, every link which has been inserted once using \\[org-insert-link]
1477 will be removed from the list, to make completing the unused links
1478 more efficient."
1479 :group 'org-link-store
1480 :type 'boolean)
1482 (defgroup org-link-follow nil
1483 "Options concerning following links in Org-mode."
1484 :tag "Org Follow Link"
1485 :group 'org-link)
1487 (defcustom org-link-translation-function nil
1488 "Function to translate links with different syntax to Org syntax.
1489 This can be used to translate links created for example by the Planner
1490 or emacs-wiki packages to Org syntax.
1491 The function must accept two parameters, a TYPE containing the link
1492 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1493 which is everything after the link protocol. It should return a cons
1494 with possibly modified values of type and path.
1495 Org contains a function for this, so if you set this variable to
1496 `org-translate-link-from-planner', you should be able follow many
1497 links created by planner."
1498 :group 'org-link-follow
1499 :type 'function)
1501 (defcustom org-follow-link-hook nil
1502 "Hook that is run after a link has been followed."
1503 :group 'org-link-follow
1504 :type 'hook)
1506 (defcustom org-tab-follows-link nil
1507 "Non-nil means on links TAB will follow the link.
1508 Needs to be set before org.el is loaded.
1509 This really should not be used, it does not make sense, and the
1510 implementation is bad."
1511 :group 'org-link-follow
1512 :type 'boolean)
1514 (defcustom org-return-follows-link nil
1515 "Non-nil means on links RET will follow the link."
1516 :group 'org-link-follow
1517 :type 'boolean)
1519 (defcustom org-mouse-1-follows-link
1520 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1521 "Non-nil means mouse-1 on a link will follow the link.
1522 A longer mouse click will still set point. Does not work on XEmacs.
1523 Needs to be set before org.el is loaded."
1524 :group 'org-link-follow
1525 :type 'boolean)
1527 (defcustom org-mark-ring-length 4
1528 "Number of different positions to be recorded in the ring.
1529 Changing this requires a restart of Emacs to work correctly."
1530 :group 'org-link-follow
1531 :type 'integer)
1533 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1534 "Non-nil means internal links in Org files must exactly match a headline.
1535 When nil, the link search tries to match a phrase with all words
1536 in the search text."
1537 :group 'org-link-follow
1538 :type '(choice
1539 (const :tag "Use fuzzy text search" nil)
1540 (const :tag "Match only exact headline" t)
1541 (const :tag "Match exact headline or query to create it"
1542 query-to-create)))
1544 (defcustom org-link-frame-setup
1545 '((vm . vm-visit-folder-other-frame)
1546 (gnus . org-gnus-no-new-news)
1547 (file . find-file-other-window)
1548 (wl . wl-other-frame))
1549 "Setup the frame configuration for following links.
1550 When following a link with Emacs, it may often be useful to display
1551 this link in another window or frame. This variable can be used to
1552 set this up for the different types of links.
1553 For VM, use any of
1554 `vm-visit-folder'
1555 `vm-visit-folder-other-window'
1556 `vm-visit-folder-other-frame'
1557 For Gnus, use any of
1558 `gnus'
1559 `gnus-other-frame'
1560 `org-gnus-no-new-news'
1561 For FILE, use any of
1562 `find-file'
1563 `find-file-other-window'
1564 `find-file-other-frame'
1565 For Wanderlust use any of
1566 `wl'
1567 `wl-other-frame'
1568 For the calendar, use the variable `calendar-setup'.
1569 For BBDB, it is currently only possible to display the matches in
1570 another window."
1571 :group 'org-link-follow
1572 :type '(list
1573 (cons (const vm)
1574 (choice
1575 (const vm-visit-folder)
1576 (const vm-visit-folder-other-window)
1577 (const vm-visit-folder-other-frame)))
1578 (cons (const gnus)
1579 (choice
1580 (const gnus)
1581 (const gnus-other-frame)
1582 (const org-gnus-no-new-news)))
1583 (cons (const file)
1584 (choice
1585 (const find-file)
1586 (const find-file-other-window)
1587 (const find-file-other-frame)))
1588 (cons (const wl)
1589 (choice
1590 (const wl)
1591 (const wl-other-frame)))))
1593 (defcustom org-display-internal-link-with-indirect-buffer nil
1594 "Non-nil means use indirect buffer to display infile links.
1595 Activating internal links (from one location in a file to another location
1596 in the same file) normally just jumps to the location. When the link is
1597 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1598 is displayed in
1599 another window. When this option is set, the other window actually displays
1600 an indirect buffer clone of the current buffer, to avoid any visibility
1601 changes to the current buffer."
1602 :group 'org-link-follow
1603 :type 'boolean)
1605 (defcustom org-open-non-existing-files nil
1606 "Non-nil means `org-open-file' will open non-existing files.
1607 When nil, an error will be generated.
1608 This variable applies only to external applications because they
1609 might choke on non-existing files. If the link is to a file that
1610 will be opened in Emacs, the variable is ignored."
1611 :group 'org-link-follow
1612 :type 'boolean)
1614 (defcustom org-open-directory-means-index-dot-org nil
1615 "Non-nil means a link to a directory really means to index.org.
1616 When nil, following a directory link will run dired or open a finder/explorer
1617 window on that directory."
1618 :group 'org-link-follow
1619 :type 'boolean)
1621 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1622 "Function and arguments to call for following mailto links.
1623 This is a list with the first element being a Lisp function, and the
1624 remaining elements being arguments to the function. In string arguments,
1625 %a will be replaced by the address, and %s will be replaced by the subject
1626 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1627 :group 'org-link-follow
1628 :type '(choice
1629 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1630 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1631 (const :tag "message-mail" (message-mail "%a" "%s"))
1632 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1634 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1635 "Non-nil means ask for confirmation before executing shell links.
1636 Shell links can be dangerous: just think about a link
1638 [[shell:rm -rf ~/*][Google Search]]
1640 This link would show up in your Org-mode document as \"Google Search\",
1641 but really it would remove your entire home directory.
1642 Therefore we advise against setting this variable to nil.
1643 Just change it to `y-or-n-p' if you want to confirm with a
1644 single keystroke rather than having to type \"yes\"."
1645 :group 'org-link-follow
1646 :type '(choice
1647 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1648 (const :tag "with y-or-n (faster)" y-or-n-p)
1649 (const :tag "no confirmation (dangerous)" nil)))
1650 (put 'org-confirm-shell-link-function
1651 'safe-local-variable
1652 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1654 (defcustom org-confirm-shell-link-not-regexp ""
1655 "A regexp to skip confirmation for shell links."
1656 :group 'org-link-follow
1657 :type 'regexp)
1659 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1660 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1661 Elisp links can be dangerous: just think about a link
1663 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1665 This link would show up in your Org-mode document as \"Google Search\",
1666 but really it would remove your entire home directory.
1667 Therefore we advise against setting this variable to nil.
1668 Just change it to `y-or-n-p' if you want to confirm with a
1669 single keystroke rather than having to type \"yes\"."
1670 :group 'org-link-follow
1671 :type '(choice
1672 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1673 (const :tag "with y-or-n (faster)" y-or-n-p)
1674 (const :tag "no confirmation (dangerous)" nil)))
1675 (put 'org-confirm-shell-link-function
1676 'safe-local-variable
1677 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1679 (defcustom org-confirm-elisp-link-not-regexp ""
1680 "A regexp to skip confirmation for Elisp links."
1681 :group 'org-link-follow
1682 :type 'regexp)
1684 (defconst org-file-apps-defaults-gnu
1685 '((remote . emacs)
1686 (system . mailcap)
1687 (t . mailcap))
1688 "Default file applications on a UNIX or GNU/Linux system.
1689 See `org-file-apps'.")
1691 (defconst org-file-apps-defaults-macosx
1692 '((remote . emacs)
1693 (t . "open %s")
1694 (system . "open %s")
1695 ("ps.gz" . "gv %s")
1696 ("eps.gz" . "gv %s")
1697 ("dvi" . "xdvi %s")
1698 ("fig" . "xfig %s"))
1699 "Default file applications on a MacOS X system.
1700 The system \"open\" is known as a default, but we use X11 applications
1701 for some files for which the OS does not have a good default.
1702 See `org-file-apps'.")
1704 (defconst org-file-apps-defaults-windowsnt
1705 (list
1706 '(remote . emacs)
1707 (cons t
1708 (list (if (featurep 'xemacs)
1709 'mswindows-shell-execute
1710 'w32-shell-execute)
1711 "open" 'file))
1712 (cons 'system
1713 (list (if (featurep 'xemacs)
1714 'mswindows-shell-execute
1715 'w32-shell-execute)
1716 "open" 'file)))
1717 "Default file applications on a Windows NT system.
1718 The system \"open\" is used for most files.
1719 See `org-file-apps'.")
1721 (defcustom org-file-apps
1723 (auto-mode . emacs)
1724 ("\\.mm\\'" . default)
1725 ("\\.x?html?\\'" . default)
1726 ("\\.pdf\\'" . default)
1728 "External applications for opening `file:path' items in a document.
1729 Org-mode uses system defaults for different file types, but
1730 you can use this variable to set the application for a given file
1731 extension. The entries in this list are cons cells where the car identifies
1732 files and the cdr the corresponding command. Possible values for the
1733 file identifier are
1734 \"string\" A string as a file identifier can be interpreted in different
1735 ways, depending on its contents:
1737 - Alphanumeric characters only:
1738 Match links with this file extension.
1739 Example: (\"pdf\" . \"evince %s\")
1740 to open PDFs with evince.
1742 - Regular expression: Match links where the
1743 filename matches the regexp. If you want to
1744 use groups here, use shy groups.
1746 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1747 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1748 to open *.html and *.xhtml with firefox.
1750 - Regular expression which contains (non-shy) groups:
1751 Match links where the whole link, including \"::\", and
1752 anything after that, matches the regexp.
1753 In a custom command string, %1, %2, etc. are replaced with
1754 the parts of the link that were matched by the groups.
1755 For backwards compatibility, if a command string is given
1756 that does not use any of the group matches, this case is
1757 handled identically to the second one (i.e. match against
1758 file name only).
1759 In a custom lisp form, you can access the group matches with
1760 (match-string n link).
1762 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1763 to open [[file:document.pdf::5]] with evince at page 5.
1765 `directory' Matches a directory
1766 `remote' Matches a remote file, accessible through tramp or efs.
1767 Remote files most likely should be visited through Emacs
1768 because external applications cannot handle such paths.
1769 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1770 so all files Emacs knows how to handle. Using this with
1771 command `emacs' will open most files in Emacs. Beware that this
1772 will also open html files inside Emacs, unless you add
1773 (\"html\" . default) to the list as well.
1774 t Default for files not matched by any of the other options.
1775 `system' The system command to open files, like `open' on Windows
1776 and Mac OS X, and mailcap under GNU/Linux. This is the command
1777 that will be selected if you call `C-c C-o' with a double
1778 \\[universal-argument] \\[universal-argument] prefix.
1780 Possible values for the command are:
1781 `emacs' The file will be visited by the current Emacs process.
1782 `default' Use the default application for this file type, which is the
1783 association for t in the list, most likely in the system-specific
1784 part.
1785 This can be used to overrule an unwanted setting in the
1786 system-specific variable.
1787 `system' Use the system command for opening files, like \"open\".
1788 This command is specified by the entry whose car is `system'.
1789 Most likely, the system-specific version of this variable
1790 does define this command, but you can overrule/replace it
1791 here.
1792 string A command to be executed by a shell; %s will be replaced
1793 by the path to the file.
1794 sexp A Lisp form which will be evaluated. The file path will
1795 be available in the Lisp variable `file'.
1796 For more examples, see the system specific constants
1797 `org-file-apps-defaults-macosx'
1798 `org-file-apps-defaults-windowsnt'
1799 `org-file-apps-defaults-gnu'."
1800 :group 'org-link-follow
1801 :type '(repeat
1802 (cons (choice :value ""
1803 (string :tag "Extension")
1804 (const :tag "System command to open files" system)
1805 (const :tag "Default for unrecognized files" t)
1806 (const :tag "Remote file" remote)
1807 (const :tag "Links to a directory" directory)
1808 (const :tag "Any files that have Emacs modes"
1809 auto-mode))
1810 (choice :value ""
1811 (const :tag "Visit with Emacs" emacs)
1812 (const :tag "Use default" default)
1813 (const :tag "Use the system command" system)
1814 (string :tag "Command")
1815 (sexp :tag "Lisp form")))))
1819 (defgroup org-refile nil
1820 "Options concerning refiling entries in Org-mode."
1821 :tag "Org Refile"
1822 :group 'org)
1824 (defcustom org-directory "~/org"
1825 "Directory with org files.
1826 This is just a default location to look for Org files. There is no need
1827 at all to put your files into this directory. It is only used in the
1828 following situations:
1830 1. When a remember template specifies a target file that is not an
1831 absolute path. The path will then be interpreted relative to
1832 `org-directory'
1833 2. When a remember note is filed away in an interactive way (when exiting the
1834 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1835 with `org-directory' as the default path."
1836 :group 'org-refile
1837 :group 'org-remember
1838 :type 'directory)
1840 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1841 "Default target for storing notes.
1842 Used as a fall back file for org-remember.el and org-capture.el, for
1843 templates that do not specify a target file."
1844 :group 'org-refile
1845 :group 'org-remember
1846 :type '(choice
1847 (const :tag "Default from remember-data-file" nil)
1848 file))
1850 (defcustom org-goto-interface 'outline
1851 "The default interface to be used for `org-goto'.
1852 Allowed values are:
1853 outline The interface shows an outline of the relevant file
1854 and the correct heading is found by moving through
1855 the outline or by searching with incremental search.
1856 outline-path-completion Headlines in the current buffer are offered via
1857 completion. This is the interface also used by
1858 the refile command."
1859 :group 'org-refile
1860 :type '(choice
1861 (const :tag "Outline" outline)
1862 (const :tag "Outline-path-completion" outline-path-completion)))
1864 (defcustom org-goto-max-level 5
1865 "Maximum target level when running `org-goto' with refile interface."
1866 :group 'org-refile
1867 :type 'integer)
1869 (defcustom org-reverse-note-order nil
1870 "Non-nil means store new notes at the beginning of a file or entry.
1871 When nil, new notes will be filed to the end of a file or entry.
1872 This can also be a list with cons cells of regular expressions that
1873 are matched against file names, and values."
1874 :group 'org-remember
1875 :group 'org-refile
1876 :type '(choice
1877 (const :tag "Reverse always" t)
1878 (const :tag "Reverse never" nil)
1879 (repeat :tag "By file name regexp"
1880 (cons regexp boolean))))
1882 (defcustom org-log-refile nil
1883 "Information to record when a task is refiled.
1885 Possible values are:
1887 nil Don't add anything
1888 time Add a time stamp to the task
1889 note Prompt for a note and add it with template `org-log-note-headings'
1891 This option can also be set with on a per-file-basis with
1893 #+STARTUP: nologrefile
1894 #+STARTUP: logrefile
1895 #+STARTUP: lognoterefile
1897 You can have local logging settings for a subtree by setting the LOGGING
1898 property to one or more of these keywords.
1900 When bulk-refiling from the agenda, the value `note' is forbidden and
1901 will temporarily be changed to `time'."
1902 :group 'org-refile
1903 :group 'org-progress
1904 :type '(choice
1905 (const :tag "No logging" nil)
1906 (const :tag "Record timestamp" time)
1907 (const :tag "Record timestamp with note." note)))
1909 (defcustom org-refile-targets nil
1910 "Targets for refiling entries with \\[org-refile].
1911 This is a list of cons cells. Each cell contains:
1912 - a specification of the files to be considered, either a list of files,
1913 or a symbol whose function or variable value will be used to retrieve
1914 a file name or a list of file names. If you use `org-agenda-files' for
1915 that, all agenda files will be scanned for targets. Nil means consider
1916 headings in the current buffer.
1917 - A specification of how to find candidate refile targets. This may be
1918 any of:
1919 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1920 This tag has to be present in all target headlines, inheritance will
1921 not be considered.
1922 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1923 todo keyword.
1924 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1925 headlines that are refiling targets.
1926 - a cons cell (:level . N). Any headline of level N is considered a target.
1927 Note that, when `org-odd-levels-only' is set, level corresponds to
1928 order in hierarchy, not to the number of stars.
1929 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1930 Note that, when `org-odd-levels-only' is set, level corresponds to
1931 order in hierarchy, not to the number of stars.
1933 Each element of this list generates a set of possible targets.
1934 The union of these sets is presented (with completion) to
1935 the user by `org-refile'.
1937 You can set the variable `org-refile-target-verify-function' to a function
1938 to verify each headline found by the simple criteria above.
1940 When this variable is nil, all top-level headlines in the current buffer
1941 are used, equivalent to the value `((nil . (:level . 1))'."
1942 :group 'org-refile
1943 :type '(repeat
1944 (cons
1945 (choice :value org-agenda-files
1946 (const :tag "All agenda files" org-agenda-files)
1947 (const :tag "Current buffer" nil)
1948 (function) (variable) (file))
1949 (choice :tag "Identify target headline by"
1950 (cons :tag "Specific tag" (const :value :tag) (string))
1951 (cons :tag "TODO keyword" (const :value :todo) (string))
1952 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1953 (cons :tag "Level number" (const :value :level) (integer))
1954 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1956 (defcustom org-refile-target-verify-function nil
1957 "Function to verify if the headline at point should be a refile target.
1958 The function will be called without arguments, with point at the
1959 beginning of the headline. It should return t and leave point
1960 where it is if the headline is a valid target for refiling.
1962 If the target should not be selected, the function must return nil.
1963 In addition to this, it may move point to a place from where the search
1964 should be continued. For example, the function may decide that the entire
1965 subtree of the current entry should be excluded and move point to the end
1966 of the subtree."
1967 :group 'org-refile
1968 :type 'function)
1970 (defcustom org-refile-use-cache nil
1971 "Non-nil means cache refile targets to speed up the process.
1972 The cache for a particular file will be updated automatically when
1973 the buffer has been killed, or when any of the marker used for flagging
1974 refile targets no longer points at a live buffer.
1975 If you have added new entries to a buffer that might themselves be targets,
1976 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
1977 find that easier, `C-u C-u C-u C-c C-w'."
1978 :group 'org-refile
1979 :type 'boolean)
1981 (defcustom org-refile-use-outline-path nil
1982 "Non-nil means provide refile targets as paths.
1983 So a level 3 headline will be available as level1/level2/level3.
1985 When the value is `file', also include the file name (without directory)
1986 into the path. In this case, you can also stop the completion after
1987 the file name, to get entries inserted as top level in the file.
1989 When `full-file-path', include the full file path."
1990 :group 'org-refile
1991 :type '(choice
1992 (const :tag "Not" nil)
1993 (const :tag "Yes" t)
1994 (const :tag "Start with file name" file)
1995 (const :tag "Start with full file path" full-file-path)))
1997 (defcustom org-outline-path-complete-in-steps t
1998 "Non-nil means complete the outline path in hierarchical steps.
1999 When Org-mode uses the refile interface to select an outline path
2000 \(see variable `org-refile-use-outline-path'), the completion of
2001 the path can be done is a single go, or if can be done in steps down
2002 the headline hierarchy. Going in steps is probably the best if you
2003 do not use a special completion package like `ido' or `icicles'.
2004 However, when using these packages, going in one step can be very
2005 fast, while still showing the whole path to the entry."
2006 :group 'org-refile
2007 :type 'boolean)
2009 (defcustom org-refile-allow-creating-parent-nodes nil
2010 "Non-nil means allow to create new nodes as refile targets.
2011 New nodes are then created by adding \"/new node name\" to the completion
2012 of an existing node. When the value of this variable is `confirm',
2013 new node creation must be confirmed by the user (recommended)
2014 When nil, the completion must match an existing entry.
2016 Note that, if the new heading is not seen by the criteria
2017 listed in `org-refile-targets', multiple instances of the same
2018 heading would be created by trying again to file under the new
2019 heading."
2020 :group 'org-refile
2021 :type '(choice
2022 (const :tag "Never" nil)
2023 (const :tag "Always" t)
2024 (const :tag "Prompt for confirmation" confirm)))
2026 (defcustom org-refile-active-region-within-subtree nil
2027 "Non-nil means also refile active region within a subtree.
2029 By default `org-refile' doesn't allow refiling regions if they
2030 don't contain a set of subtrees, but it might be convenient to
2031 do so sometimes: in that case, the first line of the region is
2032 converted to a headline before refiling."
2033 :group 'org-refile
2034 :type 'boolean)
2036 (defgroup org-todo nil
2037 "Options concerning TODO items in Org-mode."
2038 :tag "Org TODO"
2039 :group 'org)
2041 (defgroup org-progress nil
2042 "Options concerning Progress logging in Org-mode."
2043 :tag "Org Progress"
2044 :group 'org-time)
2046 (defvar org-todo-interpretation-widgets
2047 '((:tag "Sequence (cycling hits every state)" sequence)
2048 (:tag "Type (cycling directly to DONE)" type))
2049 "The available interpretation symbols for customizing `org-todo-keywords'.
2050 Interested libraries should add to this list.")
2052 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2053 "List of TODO entry keyword sequences and their interpretation.
2054 \\<org-mode-map>This is a list of sequences.
2056 Each sequence starts with a symbol, either `sequence' or `type',
2057 indicating if the keywords should be interpreted as a sequence of
2058 action steps, or as different types of TODO items. The first
2059 keywords are states requiring action - these states will select a headline
2060 for inclusion into the global TODO list Org-mode produces. If one of
2061 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2062 signify that no further action is necessary. If \"|\" is not found,
2063 the last keyword is treated as the only DONE state of the sequence.
2065 The command \\[org-todo] cycles an entry through these states, and one
2066 additional state where no keyword is present. For details about this
2067 cycling, see the manual.
2069 TODO keywords and interpretation can also be set on a per-file basis with
2070 the special #+SEQ_TODO and #+TYP_TODO lines.
2072 Each keyword can optionally specify a character for fast state selection
2073 \(in combination with the variable `org-use-fast-todo-selection')
2074 and specifiers for state change logging, using the same syntax
2075 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
2076 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2077 indicates to record a time stamp each time this state is selected.
2079 Each keyword may also specify if a timestamp or a note should be
2080 recorded when entering or leaving the state, by adding additional
2081 characters in the parenthesis after the keyword. This looks like this:
2082 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2083 record only the time of the state change. With X and Y being either
2084 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2085 Y when leaving the state if and only if the *target* state does not
2086 define X. You may omit any of the fast-selection key or X or /Y,
2087 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2089 For backward compatibility, this variable may also be just a list
2090 of keywords - in this case the interpretation (sequence or type) will be
2091 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2092 :group 'org-todo
2093 :group 'org-keywords
2094 :type '(choice
2095 (repeat :tag "Old syntax, just keywords"
2096 (string :tag "Keyword"))
2097 (repeat :tag "New syntax"
2098 (cons
2099 (choice
2100 :tag "Interpretation"
2101 ;;Quick and dirty way to see
2102 ;;`org-todo-interpretations'. This takes the
2103 ;;place of item arguments
2104 :convert-widget
2105 (lambda (widget)
2106 (widget-put widget
2107 :args (mapcar
2108 #'(lambda (x)
2109 (widget-convert
2110 (cons 'const x)))
2111 org-todo-interpretation-widgets))
2112 widget))
2113 (repeat
2114 (string :tag "Keyword"))))))
2116 (defvar org-todo-keywords-1 nil
2117 "All TODO and DONE keywords active in a buffer.")
2118 (make-variable-buffer-local 'org-todo-keywords-1)
2119 (defvar org-todo-keywords-for-agenda nil)
2120 (defvar org-done-keywords-for-agenda nil)
2121 (defvar org-drawers-for-agenda nil)
2122 (defvar org-todo-keyword-alist-for-agenda nil)
2123 (defvar org-tag-alist-for-agenda nil)
2124 (defvar org-agenda-contributing-files nil)
2125 (defvar org-not-done-keywords nil)
2126 (make-variable-buffer-local 'org-not-done-keywords)
2127 (defvar org-done-keywords nil)
2128 (make-variable-buffer-local 'org-done-keywords)
2129 (defvar org-todo-heads nil)
2130 (make-variable-buffer-local 'org-todo-heads)
2131 (defvar org-todo-sets nil)
2132 (make-variable-buffer-local 'org-todo-sets)
2133 (defvar org-todo-log-states nil)
2134 (make-variable-buffer-local 'org-todo-log-states)
2135 (defvar org-todo-kwd-alist nil)
2136 (make-variable-buffer-local 'org-todo-kwd-alist)
2137 (defvar org-todo-key-alist nil)
2138 (make-variable-buffer-local 'org-todo-key-alist)
2139 (defvar org-todo-key-trigger nil)
2140 (make-variable-buffer-local 'org-todo-key-trigger)
2142 (defcustom org-todo-interpretation 'sequence
2143 "Controls how TODO keywords are interpreted.
2144 This variable is in principle obsolete and is only used for
2145 backward compatibility, if the interpretation of todo keywords is
2146 not given already in `org-todo-keywords'. See that variable for
2147 more information."
2148 :group 'org-todo
2149 :group 'org-keywords
2150 :type '(choice (const sequence)
2151 (const type)))
2153 (defcustom org-use-fast-todo-selection t
2154 "Non-nil means use the fast todo selection scheme with C-c C-t.
2155 This variable describes if and under what circumstances the cycling
2156 mechanism for TODO keywords will be replaced by a single-key, direct
2157 selection scheme.
2159 When nil, fast selection is never used.
2161 When the symbol `prefix', it will be used when `org-todo' is called with
2162 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
2163 in an agenda buffer.
2165 When t, fast selection is used by default. In this case, the prefix
2166 argument forces cycling instead.
2168 In all cases, the special interface is only used if access keys have actually
2169 been assigned by the user, i.e. if keywords in the configuration are followed
2170 by a letter in parenthesis, like TODO(t)."
2171 :group 'org-todo
2172 :type '(choice
2173 (const :tag "Never" nil)
2174 (const :tag "By default" t)
2175 (const :tag "Only with C-u C-c C-t" prefix)))
2177 (defcustom org-provide-todo-statistics t
2178 "Non-nil means update todo statistics after insert and toggle.
2179 ALL-HEADLINES means update todo statistics by including headlines
2180 with no TODO keyword as well, counting them as not done.
2181 A list of TODO keywords means the same, but skip keywords that are
2182 not in this list.
2184 When this is set, todo statistics is updated in the parent of the
2185 current entry each time a todo state is changed."
2186 :group 'org-todo
2187 :type '(choice
2188 (const :tag "Yes, only for TODO entries" t)
2189 (const :tag "Yes, including all entries" 'all-headlines)
2190 (repeat :tag "Yes, for TODOs in this list"
2191 (string :tag "TODO keyword"))
2192 (other :tag "No TODO statistics" nil)))
2194 (defcustom org-hierarchical-todo-statistics t
2195 "Non-nil means TODO statistics covers just direct children.
2196 When nil, all entries in the subtree are considered.
2197 This has only an effect if `org-provide-todo-statistics' is set.
2198 To set this to nil for only a single subtree, use a COOKIE_DATA
2199 property and include the word \"recursive\" into the value."
2200 :group 'org-todo
2201 :type 'boolean)
2203 (defcustom org-after-todo-state-change-hook nil
2204 "Hook which is run after the state of a TODO item was changed.
2205 The new state (a string with a TODO keyword, or nil) is available in the
2206 Lisp variable `state'."
2207 :group 'org-todo
2208 :type 'hook)
2210 (defvar org-blocker-hook nil
2211 "Hook for functions that are allowed to block a state change.
2213 Each function gets as its single argument a property list, see
2214 `org-trigger-hook' for more information about this list.
2216 If any of the functions in this hook returns nil, the state change
2217 is blocked.")
2219 (defvar org-trigger-hook nil
2220 "Hook for functions that are triggered by a state change.
2222 Each function gets as its single argument a property list with at least
2223 the following elements:
2225 (:type type-of-change :position pos-at-entry-start
2226 :from old-state :to new-state)
2228 Depending on the type, more properties may be present.
2230 This mechanism is currently implemented for:
2232 TODO state changes
2233 ------------------
2234 :type todo-state-change
2235 :from previous state (keyword as a string), or nil, or a symbol
2236 'todo' or 'done', to indicate the general type of state.
2237 :to new state, like in :from")
2239 (defcustom org-enforce-todo-dependencies nil
2240 "Non-nil means undone TODO entries will block switching the parent to DONE.
2241 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2242 be blocked if any prior sibling is not yet done.
2243 Finally, if the parent is blocked because of ordered siblings of its own,
2244 the child will also be blocked.
2245 This variable needs to be set before org.el is loaded, and you need to
2246 restart Emacs after a change to make the change effective. The only way
2247 to change is while Emacs is running is through the customize interface."
2248 :set (lambda (var val)
2249 (set var val)
2250 (if val
2251 (add-hook 'org-blocker-hook
2252 'org-block-todo-from-children-or-siblings-or-parent)
2253 (remove-hook 'org-blocker-hook
2254 'org-block-todo-from-children-or-siblings-or-parent)))
2255 :group 'org-todo
2256 :type 'boolean)
2258 (defcustom org-enforce-todo-checkbox-dependencies nil
2259 "Non-nil means unchecked boxes will block switching the parent to DONE.
2260 When this is nil, checkboxes have no influence on switching TODO states.
2261 When non-nil, you first need to check off all check boxes before the TODO
2262 entry can be switched to DONE.
2263 This variable needs to be set before org.el is loaded, and you need to
2264 restart Emacs after a change to make the change effective. The only way
2265 to change is while Emacs is running is through the customize interface."
2266 :set (lambda (var val)
2267 (set var val)
2268 (if val
2269 (add-hook 'org-blocker-hook
2270 'org-block-todo-from-checkboxes)
2271 (remove-hook 'org-blocker-hook
2272 'org-block-todo-from-checkboxes)))
2273 :group 'org-todo
2274 :type 'boolean)
2276 (defcustom org-treat-insert-todo-heading-as-state-change nil
2277 "Non-nil means inserting a TODO heading is treated as state change.
2278 So when the command \\[org-insert-todo-heading] is used, state change
2279 logging will apply if appropriate. When nil, the new TODO item will
2280 be inserted directly, and no logging will take place."
2281 :group 'org-todo
2282 :type 'boolean)
2284 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2285 "Non-nil means switching TODO states with S-cursor counts as state change.
2286 This is the default behavior. However, setting this to nil allows a
2287 convenient way to select a TODO state and bypass any logging associated
2288 with that."
2289 :group 'org-todo
2290 :type 'boolean)
2292 (defcustom org-todo-state-tags-triggers nil
2293 "Tag changes that should be triggered by TODO state changes.
2294 This is a list. Each entry is
2296 (state-change (tag . flag) .......)
2298 State-change can be a string with a state, and empty string to indicate the
2299 state that has no TODO keyword, or it can be one of the symbols `todo'
2300 or `done', meaning any not-done or done state, respectively."
2301 :group 'org-todo
2302 :group 'org-tags
2303 :type '(repeat
2304 (cons (choice :tag "When changing to"
2305 (const :tag "Not-done state" todo)
2306 (const :tag "Done state" done)
2307 (string :tag "State"))
2308 (repeat
2309 (cons :tag "Tag action"
2310 (string :tag "Tag")
2311 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2313 (defcustom org-log-done nil
2314 "Information to record when a task moves to the DONE state.
2316 Possible values are:
2318 nil Don't add anything, just change the keyword
2319 time Add a time stamp to the task
2320 note Prompt for a note and add it with template `org-log-note-headings'
2322 This option can also be set with on a per-file-basis with
2324 #+STARTUP: nologdone
2325 #+STARTUP: logdone
2326 #+STARTUP: lognotedone
2328 You can have local logging settings for a subtree by setting the LOGGING
2329 property to one or more of these keywords."
2330 :group 'org-todo
2331 :group 'org-progress
2332 :type '(choice
2333 (const :tag "No logging" nil)
2334 (const :tag "Record CLOSED timestamp" time)
2335 (const :tag "Record CLOSED timestamp with note." note)))
2337 ;; Normalize old uses of org-log-done.
2338 (cond
2339 ((eq org-log-done t) (setq org-log-done 'time))
2340 ((and (listp org-log-done) (memq 'done org-log-done))
2341 (setq org-log-done 'note)))
2343 (defcustom org-log-reschedule nil
2344 "Information to record when the scheduling date of a tasks is modified.
2346 Possible values are:
2348 nil Don't add anything, just change the date
2349 time Add a time stamp to the task
2350 note Prompt for a note and add it with template `org-log-note-headings'
2352 This option can also be set with on a per-file-basis with
2354 #+STARTUP: nologreschedule
2355 #+STARTUP: logreschedule
2356 #+STARTUP: lognotereschedule"
2357 :group 'org-todo
2358 :group 'org-progress
2359 :type '(choice
2360 (const :tag "No logging" nil)
2361 (const :tag "Record timestamp" time)
2362 (const :tag "Record timestamp with note." note)))
2364 (defcustom org-log-redeadline nil
2365 "Information to record when the deadline date of a tasks is modified.
2367 Possible values are:
2369 nil Don't add anything, just change the date
2370 time Add a time stamp to the task
2371 note Prompt for a note and add it with template `org-log-note-headings'
2373 This option can also be set with on a per-file-basis with
2375 #+STARTUP: nologredeadline
2376 #+STARTUP: logredeadline
2377 #+STARTUP: lognoteredeadline
2379 You can have local logging settings for a subtree by setting the LOGGING
2380 property to one or more of these keywords."
2381 :group 'org-todo
2382 :group 'org-progress
2383 :type '(choice
2384 (const :tag "No logging" nil)
2385 (const :tag "Record timestamp" time)
2386 (const :tag "Record timestamp with note." note)))
2388 (defcustom org-log-note-clock-out nil
2389 "Non-nil means record a note when clocking out of an item.
2390 This can also be configured on a per-file basis by adding one of
2391 the following lines anywhere in the buffer:
2393 #+STARTUP: lognoteclock-out
2394 #+STARTUP: nolognoteclock-out"
2395 :group 'org-todo
2396 :group 'org-progress
2397 :type 'boolean)
2399 (defcustom org-log-done-with-time t
2400 "Non-nil means the CLOSED time stamp will contain date and time.
2401 When nil, only the date will be recorded."
2402 :group 'org-progress
2403 :type 'boolean)
2405 (defcustom org-log-note-headings
2406 '((done . "CLOSING NOTE %t")
2407 (state . "State %-12s from %-12S %t")
2408 (note . "Note taken on %t")
2409 (reschedule . "Rescheduled from %S on %t")
2410 (delschedule . "Not scheduled, was %S on %t")
2411 (redeadline . "New deadline from %S on %t")
2412 (deldeadline . "Removed deadline, was %S on %t")
2413 (refile . "Refiled on %t")
2414 (clock-out . ""))
2415 "Headings for notes added to entries.
2416 The value is an alist, with the car being a symbol indicating the note
2417 context, and the cdr is the heading to be used. The heading may also be the
2418 empty string.
2419 %t in the heading will be replaced by a time stamp.
2420 %T will be an active time stamp instead the default inactive one
2421 %d will be replaced by a short-format time stamp.
2422 %D will be replaced by an active short-format time stamp.
2423 %s will be replaced by the new TODO state, in double quotes.
2424 %S will be replaced by the old TODO state, in double quotes.
2425 %u will be replaced by the user name.
2426 %U will be replaced by the full user name.
2428 In fact, it is not a good idea to change the `state' entry, because
2429 agenda log mode depends on the format of these entries."
2430 :group 'org-todo
2431 :group 'org-progress
2432 :type '(list :greedy t
2433 (cons (const :tag "Heading when closing an item" done) string)
2434 (cons (const :tag
2435 "Heading when changing todo state (todo sequence only)"
2436 state) string)
2437 (cons (const :tag "Heading when just taking a note" note) string)
2438 (cons (const :tag "Heading when clocking out" clock-out) string)
2439 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2440 (cons (const :tag "Heading when rescheduling" reschedule) string)
2441 (cons (const :tag "Heading when changing deadline" redeadline) string)
2442 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2443 (cons (const :tag "Heading when refiling" refile) string)))
2445 (unless (assq 'note org-log-note-headings)
2446 (push '(note . "%t") org-log-note-headings))
2448 (defcustom org-log-into-drawer nil
2449 "Non-nil means insert state change notes and time stamps into a drawer.
2450 When nil, state changes notes will be inserted after the headline and
2451 any scheduling and clock lines, but not inside a drawer.
2453 The value of this variable should be the name of the drawer to use.
2454 LOGBOOK is proposed as the default drawer for this purpose, you can
2455 also set this to a string to define the drawer of your choice.
2457 A value of t is also allowed, representing \"LOGBOOK\".
2459 If this variable is set, `org-log-state-notes-insert-after-drawers'
2460 will be ignored.
2462 You can set the property LOG_INTO_DRAWER to overrule this setting for
2463 a subtree."
2464 :group 'org-todo
2465 :group 'org-progress
2466 :type '(choice
2467 (const :tag "Not into a drawer" nil)
2468 (const :tag "LOGBOOK" t)
2469 (string :tag "Other")))
2471 (if (fboundp 'defvaralias)
2472 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2474 (defun org-log-into-drawer ()
2475 "Return the value of `org-log-into-drawer', but let properties overrule.
2476 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2477 used instead of the default value."
2478 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit)))
2479 (cond
2480 ((or (not p) (equal p "nil")) org-log-into-drawer)
2481 ((equal p "t") "LOGBOOK")
2482 (t p))))
2484 (defcustom org-log-state-notes-insert-after-drawers nil
2485 "Non-nil means insert state change notes after any drawers in entry.
2486 Only the drawers that *immediately* follow the headline and the
2487 deadline/scheduled line are skipped.
2488 When nil, insert notes right after the heading and perhaps the line
2489 with deadline/scheduling if present.
2491 This variable will have no effect if `org-log-into-drawer' is
2492 set."
2493 :group 'org-todo
2494 :group 'org-progress
2495 :type 'boolean)
2497 (defcustom org-log-states-order-reversed t
2498 "Non-nil means the latest state note will be directly after heading.
2499 When nil, the state change notes will be ordered according to time."
2500 :group 'org-todo
2501 :group 'org-progress
2502 :type 'boolean)
2504 (defcustom org-todo-repeat-to-state nil
2505 "The TODO state to which a repeater should return the repeating task.
2506 By default this is the first task in a TODO sequence, or the previous state
2507 in a TODO_TYP set. But you can specify another task here.
2508 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2509 :group 'org-todo
2510 :type '(choice (const :tag "Head of sequence" nil)
2511 (string :tag "Specific state")))
2513 (defcustom org-log-repeat 'time
2514 "Non-nil means record moving through the DONE state when triggering repeat.
2515 An auto-repeating task is immediately switched back to TODO when
2516 marked DONE. If you are not logging state changes (by adding \"@\"
2517 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2518 record a closing note, there will be no record of the task moving
2519 through DONE. This variable forces taking a note anyway.
2521 nil Don't force a record
2522 time Record a time stamp
2523 note Record a note
2525 This option can also be set with on a per-file-basis with
2527 #+STARTUP: logrepeat
2528 #+STARTUP: lognoterepeat
2529 #+STARTUP: nologrepeat
2531 You can have local logging settings for a subtree by setting the LOGGING
2532 property to one or more of these keywords."
2533 :group 'org-todo
2534 :group 'org-progress
2535 :type '(choice
2536 (const :tag "Don't force a record" nil)
2537 (const :tag "Force recording the DONE state" time)
2538 (const :tag "Force recording a note with the DONE state" note)))
2541 (defgroup org-priorities nil
2542 "Priorities in Org-mode."
2543 :tag "Org Priorities"
2544 :group 'org-todo)
2546 (defcustom org-enable-priority-commands t
2547 "Non-nil means priority commands are active.
2548 When nil, these commands will be disabled, so that you never accidentally
2549 set a priority."
2550 :group 'org-priorities
2551 :type 'boolean)
2553 (defcustom org-highest-priority ?A
2554 "The highest priority of TODO items. A character like ?A, ?B etc.
2555 Must have a smaller ASCII number than `org-lowest-priority'."
2556 :group 'org-priorities
2557 :type 'character)
2559 (defcustom org-lowest-priority ?C
2560 "The lowest priority of TODO items. A character like ?A, ?B etc.
2561 Must have a larger ASCII number than `org-highest-priority'."
2562 :group 'org-priorities
2563 :type 'character)
2565 (defcustom org-default-priority ?B
2566 "The default priority of TODO items.
2567 This is the priority an item gets if no explicit priority is given.
2568 When starting to cycle on an empty priority the first step in the cycle
2569 depends on `org-priority-start-cycle-with-default'. The resulting first
2570 step priority must not exceed the range from `org-highest-priority' to
2571 `org-lowest-priority' which means that `org-default-priority' has to be
2572 in this range exclusive or inclusive the range boundaries. Else the
2573 first step refuses to set the default and the second will fall back
2574 to (depending on the command used) the highest or lowest priority."
2575 :group 'org-priorities
2576 :type 'character)
2578 (defcustom org-priority-start-cycle-with-default t
2579 "Non-nil means start with default priority when starting to cycle.
2580 When this is nil, the first step in the cycle will be (depending on the
2581 command used) one higher or lower than the default priority.
2582 See also `org-default-priority'."
2583 :group 'org-priorities
2584 :type 'boolean)
2586 (defcustom org-get-priority-function nil
2587 "Function to extract the priority from a string.
2588 The string is normally the headline. If this is nil Org computes the
2589 priority from the priority cookie like [#A] in the headline. It returns
2590 an integer, increasing by 1000 for each priority level.
2591 The user can set a different function here, which should take a string
2592 as an argument and return the numeric priority."
2593 :group 'org-priorities
2594 :type 'function)
2596 (defgroup org-time nil
2597 "Options concerning time stamps and deadlines in Org-mode."
2598 :tag "Org Time"
2599 :group 'org)
2601 (defcustom org-insert-labeled-timestamps-at-point nil
2602 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2603 When nil, these labeled time stamps are forces into the second line of an
2604 entry, just after the headline. When scheduling from the global TODO list,
2605 the time stamp will always be forced into the second line."
2606 :group 'org-time
2607 :type 'boolean)
2609 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2610 "Formats for `format-time-string' which are used for time stamps.
2611 It is not recommended to change this constant.")
2613 (defcustom org-time-stamp-rounding-minutes '(0 5)
2614 "Number of minutes to round time stamps to.
2615 These are two values, the first applies when first creating a time stamp.
2616 The second applies when changing it with the commands `S-up' and `S-down'.
2617 When changing the time stamp, this means that it will change in steps
2618 of N minutes, as given by the second value.
2620 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2621 numbers should be factors of 60, so for example 5, 10, 15.
2623 When this is larger than 1, you can still force an exact time stamp by using
2624 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2625 and by using a prefix arg to `S-up/down' to specify the exact number
2626 of minutes to shift."
2627 :group 'org-time
2628 :get #'(lambda (var) ; Make sure both elements are there
2629 (if (integerp (default-value var))
2630 (list (default-value var) 5)
2631 (default-value var)))
2632 :type '(list
2633 (integer :tag "when inserting times")
2634 (integer :tag "when modifying times")))
2636 ;; Normalize old customizations of this variable.
2637 (when (integerp org-time-stamp-rounding-minutes)
2638 (setq org-time-stamp-rounding-minutes
2639 (list org-time-stamp-rounding-minutes
2640 org-time-stamp-rounding-minutes)))
2642 (defcustom org-display-custom-times nil
2643 "Non-nil means overlay custom formats over all time stamps.
2644 The formats are defined through the variable `org-time-stamp-custom-formats'.
2645 To turn this on on a per-file basis, insert anywhere in the file:
2646 #+STARTUP: customtime"
2647 :group 'org-time
2648 :set 'set-default
2649 :type 'sexp)
2650 (make-variable-buffer-local 'org-display-custom-times)
2652 (defcustom org-time-stamp-custom-formats
2653 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2654 "Custom formats for time stamps. See `format-time-string' for the syntax.
2655 These are overlayed over the default ISO format if the variable
2656 `org-display-custom-times' is set. Time like %H:%M should be at the
2657 end of the second format. The custom formats are also honored by export
2658 commands, if custom time display is turned on at the time of export."
2659 :group 'org-time
2660 :type 'sexp)
2662 (defun org-time-stamp-format (&optional long inactive)
2663 "Get the right format for a time string."
2664 (let ((f (if long (cdr org-time-stamp-formats)
2665 (car org-time-stamp-formats))))
2666 (if inactive
2667 (concat "[" (substring f 1 -1) "]")
2668 f)))
2670 (defcustom org-time-clocksum-format "%d:%02d"
2671 "The format string used when creating CLOCKSUM lines.
2672 This is also used when org-mode generates a time duration."
2673 :group 'org-time
2674 :type 'string)
2676 (defcustom org-time-clocksum-use-fractional nil
2677 "If non-nil, \\[org-clock-display] uses fractional times.
2678 org-mode generates a time duration."
2679 :group 'org-time
2680 :type 'boolean)
2682 (defcustom org-time-clocksum-fractional-format "%.2f"
2683 "The format string used when creating CLOCKSUM lines, or when
2684 org-mode generates a time duration."
2685 :group 'org-time
2686 :type 'string)
2688 (defcustom org-deadline-warning-days 14
2689 "No. of days before expiration during which a deadline becomes active.
2690 This variable governs the display in sparse trees and in the agenda.
2691 When 0 or negative, it means use this number (the absolute value of it)
2692 even if a deadline has a different individual lead time specified.
2694 Custom commands can set this variable in the options section."
2695 :group 'org-time
2696 :group 'org-agenda-daily/weekly
2697 :type 'integer)
2699 (defcustom org-read-date-prefer-future t
2700 "Non-nil means assume future for incomplete date input from user.
2701 This affects the following situations:
2702 1. The user gives a month but not a year.
2703 For example, if it is April and you enter \"feb 2\", this will be read
2704 as Feb 2, *next* year. \"May 5\", however, will be this year.
2705 2. The user gives a day, but no month.
2706 For example, if today is the 15th, and you enter \"3\", Org-mode will
2707 read this as the third of *next* month. However, if you enter \"17\",
2708 it will be considered as *this* month.
2710 If you set this variable to the symbol `time', then also the following
2711 will work:
2713 3. If the user gives a time, but no day. If the time is before now,
2714 to will be interpreted as tomorrow.
2716 Currently none of this works for ISO week specifications.
2718 When this option is nil, the current day, month and year will always be
2719 used as defaults.
2721 See also `org-agenda-jump-prefer-future'."
2722 :group 'org-time
2723 :type '(choice
2724 (const :tag "Never" nil)
2725 (const :tag "Check month and day" t)
2726 (const :tag "Check month, day, and time" time)))
2728 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
2729 "Should the agenda jump command prefer the future for incomplete dates?
2730 The default is to do the same as configured in `org-read-date-prefer-future'.
2731 But you can also set a deviating value here.
2732 This may t or nil, or the symbol `org-read-date-prefer-future'."
2733 :group 'org-agenda
2734 :group 'org-time
2735 :type '(choice
2736 (const :tag "Use org-read-date-prefer-future"
2737 org-read-date-prefer-future)
2738 (const :tag "Never" nil)
2739 (const :tag "Always" t)))
2741 (defcustom org-read-date-force-compatible-dates t
2742 "Should date/time prompt force dates that are guaranteed to work in Emacs?
2744 Depending on the system Emacs is running on, certain dates cannot
2745 be represented with the type used internally to represent time.
2746 Dates between 1970-1-1 and 2038-1-1 can always be represented
2747 correctly. Some systems allow for earlier dates, some for later,
2748 some for both. One way to find out it to insert any date into an
2749 Org buffer, putting the cursor on the year and hitting S-up and
2750 S-down to test the range.
2752 When this variable is set to t, the date/time prompt will not let
2753 you specify dates outside the 1970-2037 range, so it is certain that
2754 these dates will work in whatever version of Emacs you are
2755 running, and also that you can move a file from one Emacs implementation
2756 to another. WHenever Org is forcing the year for you, it will display
2757 a message and beep.
2759 When this variable is nil, Org will check if the date is
2760 representable in the specific Emacs implementation you are using.
2761 If not, it will force a year, usually the current year, and beep
2762 to remind you. Currently this setting is not recommended because
2763 the likelihood that you will open your Org files in an Emacs that
2764 has limited date range is not negligible.
2766 A workaround for this problem is to use diary sexp dates for time
2767 stamps outside of this range."
2768 :group 'org-time
2769 :type 'boolean)
2771 (defcustom org-read-date-display-live t
2772 "Non-nil means display current interpretation of date prompt live.
2773 This display will be in an overlay, in the minibuffer."
2774 :group 'org-time
2775 :type 'boolean)
2777 (defcustom org-read-date-popup-calendar t
2778 "Non-nil means pop up a calendar when prompting for a date.
2779 In the calendar, the date can be selected with mouse-1. However, the
2780 minibuffer will also be active, and you can simply enter the date as well.
2781 When nil, only the minibuffer will be available."
2782 :group 'org-time
2783 :type 'boolean)
2784 (if (fboundp 'defvaralias)
2785 (defvaralias 'org-popup-calendar-for-date-prompt
2786 'org-read-date-popup-calendar))
2788 (defcustom org-read-date-minibuffer-setup-hook nil
2789 "Hook to be used to set up keys for the date/time interface.
2790 Add key definitions to `minibuffer-local-map', which will be a temporary
2791 copy."
2792 :group 'org-time
2793 :type 'hook)
2795 (defcustom org-extend-today-until 0
2796 "The hour when your day really ends. Must be an integer.
2797 This has influence for the following applications:
2798 - When switching the agenda to \"today\". It it is still earlier than
2799 the time given here, the day recognized as TODAY is actually yesterday.
2800 - When a date is read from the user and it is still before the time given
2801 here, the current date and time will be assumed to be yesterday, 23:59.
2802 Also, timestamps inserted in remember templates follow this rule.
2804 IMPORTANT: This is a feature whose implementation is and likely will
2805 remain incomplete. Really, it is only here because past midnight seems to
2806 be the favorite working time of John Wiegley :-)"
2807 :group 'org-time
2808 :type 'integer)
2810 (defcustom org-use-effective-time nil
2811 "If non-nil, consider `org-extend-today-until' when creating timestamps.
2812 For example, if `org-extend-today-until' is 8, and it's 4am, then the
2813 \"effective time\" of any timestamps between midnight and 8am will be
2814 23:59 of the previous day."
2815 :group 'boolean
2816 :type 'integer)
2818 (defcustom org-edit-timestamp-down-means-later nil
2819 "Non-nil means S-down will increase the time in a time stamp.
2820 When nil, S-up will increase."
2821 :group 'org-time
2822 :type 'boolean)
2824 (defcustom org-calendar-follow-timestamp-change t
2825 "Non-nil means make the calendar window follow timestamp changes.
2826 When a timestamp is modified and the calendar window is visible, it will be
2827 moved to the new date."
2828 :group 'org-time
2829 :type 'boolean)
2831 (defgroup org-tags nil
2832 "Options concerning tags in Org-mode."
2833 :tag "Org Tags"
2834 :group 'org)
2836 (defcustom org-tag-alist nil
2837 "List of tags allowed in Org-mode files.
2838 When this list is nil, Org-mode will base TAG input on what is already in the
2839 buffer.
2840 The value of this variable is an alist, the car of each entry must be a
2841 keyword as a string, the cdr may be a character that is used to select
2842 that tag through the fast-tag-selection interface.
2843 See the manual for details."
2844 :group 'org-tags
2845 :type '(repeat
2846 (choice
2847 (cons (string :tag "Tag name")
2848 (character :tag "Access char"))
2849 (list :tag "Start radio group"
2850 (const :startgroup)
2851 (option (string :tag "Group description")))
2852 (list :tag "End radio group"
2853 (const :endgroup)
2854 (option (string :tag "Group description")))
2855 (const :tag "New line" (:newline)))))
2857 (defcustom org-tag-persistent-alist nil
2858 "List of tags that will always appear in all Org-mode files.
2859 This is in addition to any in buffer settings or customizations
2860 of `org-tag-alist'.
2861 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2862 The value of this variable is an alist, the car of each entry must be a
2863 keyword as a string, the cdr may be a character that is used to select
2864 that tag through the fast-tag-selection interface.
2865 See the manual for details.
2866 To disable these tags on a per-file basis, insert anywhere in the file:
2867 #+STARTUP: noptag"
2868 :group 'org-tags
2869 :type '(repeat
2870 (choice
2871 (cons (string :tag "Tag name")
2872 (character :tag "Access char"))
2873 (const :tag "Start radio group" (:startgroup))
2874 (const :tag "End radio group" (:endgroup))
2875 (const :tag "New line" (:newline)))))
2877 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
2878 "If non-nil, always offer completion for all tags of all agenda files.
2879 Instead of customizing this variable directly, you might want to
2880 set it locally for capture buffers, because there no list of
2881 tags in that file can be created dynamically (there are none).
2883 (add-hook 'org-capture-mode-hook
2884 (lambda ()
2885 (set (make-local-variable
2886 'org-complete-tags-always-offer-all-agenda-tags)
2887 t)))"
2888 :group 'org-tags
2889 :type 'boolean)
2891 (defvar org-file-tags nil
2892 "List of tags that can be inherited by all entries in the file.
2893 The tags will be inherited if the variable `org-use-tag-inheritance'
2894 says they should be.
2895 This variable is populated from #+FILETAGS lines.")
2897 (defcustom org-use-fast-tag-selection 'auto
2898 "Non-nil means use fast tag selection scheme.
2899 This is a special interface to select and deselect tags with single keys.
2900 When nil, fast selection is never used.
2901 When the symbol `auto', fast selection is used if and only if selection
2902 characters for tags have been configured, either through the variable
2903 `org-tag-alist' or through a #+TAGS line in the buffer.
2904 When t, fast selection is always used and selection keys are assigned
2905 automatically if necessary."
2906 :group 'org-tags
2907 :type '(choice
2908 (const :tag "Always" t)
2909 (const :tag "Never" nil)
2910 (const :tag "When selection characters are configured" 'auto)))
2912 (defcustom org-fast-tag-selection-single-key nil
2913 "Non-nil means fast tag selection exits after first change.
2914 When nil, you have to press RET to exit it.
2915 During fast tag selection, you can toggle this flag with `C-c'.
2916 This variable can also have the value `expert'. In this case, the window
2917 displaying the tags menu is not even shown, until you press C-c again."
2918 :group 'org-tags
2919 :type '(choice
2920 (const :tag "No" nil)
2921 (const :tag "Yes" t)
2922 (const :tag "Expert" expert)))
2924 (defvar org-fast-tag-selection-include-todo nil
2925 "Non-nil means fast tags selection interface will also offer TODO states.
2926 This is an undocumented feature, you should not rely on it.")
2928 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2929 "The column to which tags should be indented in a headline.
2930 If this number is positive, it specifies the column. If it is negative,
2931 it means that the tags should be flushright to that column. For example,
2932 -80 works well for a normal 80 character screen.
2933 When 0, place tags directly after headline text, with only one space in
2934 between."
2935 :group 'org-tags
2936 :type 'integer)
2938 (defcustom org-auto-align-tags t
2939 "Non-nil keeps tags aligned when modifying headlines.
2940 Some operations (i.e. demoting) change the length of a headline and
2941 therefore shift the tags around. With this option turned on, after
2942 each such operation the tags are again aligned to `org-tags-column'."
2943 :group 'org-tags
2944 :type 'boolean)
2946 (defcustom org-use-tag-inheritance t
2947 "Non-nil means tags in levels apply also for sublevels.
2948 When nil, only the tags directly given in a specific line apply there.
2949 This may also be a list of tags that should be inherited, or a regexp that
2950 matches tags that should be inherited. Additional control is possible
2951 with the variable `org-tags-exclude-from-inheritance' which gives an
2952 explicit list of tags to be excluded from inheritance., even if the value of
2953 `org-use-tag-inheritance' would select it for inheritance.
2955 If this option is t, a match early-on in a tree can lead to a large
2956 number of matches in the subtree when constructing the agenda or creating
2957 a sparse tree. If you only want to see the first match in a tree during
2958 a search, check out the variable `org-tags-match-list-sublevels'."
2959 :group 'org-tags
2960 :type '(choice
2961 (const :tag "Not" nil)
2962 (const :tag "Always" t)
2963 (repeat :tag "Specific tags" (string :tag "Tag"))
2964 (regexp :tag "Tags matched by regexp")))
2966 (defcustom org-tags-exclude-from-inheritance nil
2967 "List of tags that should never be inherited.
2968 This is a way to exclude a few tags from inheritance. For way to do
2969 the opposite, to actively allow inheritance for selected tags,
2970 see the variable `org-use-tag-inheritance'."
2971 :group 'org-tags
2972 :type '(repeat (string :tag "Tag")))
2974 (defun org-tag-inherit-p (tag)
2975 "Check if TAG is one that should be inherited."
2976 (cond
2977 ((member tag org-tags-exclude-from-inheritance) nil)
2978 ((eq org-use-tag-inheritance t) t)
2979 ((not org-use-tag-inheritance) nil)
2980 ((stringp org-use-tag-inheritance)
2981 (string-match org-use-tag-inheritance tag))
2982 ((listp org-use-tag-inheritance)
2983 (member tag org-use-tag-inheritance))
2984 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
2986 (defcustom org-tags-match-list-sublevels t
2987 "Non-nil means list also sublevels of headlines matching a search.
2988 This variable applies to tags/property searches, and also to stuck
2989 projects because this search is based on a tags match as well.
2991 When set to the symbol `indented', sublevels are indented with
2992 leading dots.
2994 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2995 the sublevels of a headline matching a tag search often also match
2996 the same search. Listing all of them can create very long lists.
2997 Setting this variable to nil causes subtrees of a match to be skipped.
2999 This variable is semi-obsolete and probably should always be true. It
3000 is better to limit inheritance to certain tags using the variables
3001 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3002 :group 'org-tags
3003 :type '(choice
3004 (const :tag "No, don't list them" nil)
3005 (const :tag "Yes, do list them" t)
3006 (const :tag "List them, indented with leading dots" indented)))
3008 (defcustom org-tags-sort-function nil
3009 "When set, tags are sorted using this function as a comparator."
3010 :group 'org-tags
3011 :type '(choice
3012 (const :tag "No sorting" nil)
3013 (const :tag "Alphabetical" string<)
3014 (const :tag "Reverse alphabetical" string>)
3015 (function :tag "Custom function" nil)))
3017 (defvar org-tags-history nil
3018 "History of minibuffer reads for tags.")
3019 (defvar org-last-tags-completion-table nil
3020 "The last used completion table for tags.")
3021 (defvar org-after-tags-change-hook nil
3022 "Hook that is run after the tags in a line have changed.")
3024 (defgroup org-properties nil
3025 "Options concerning properties in Org-mode."
3026 :tag "Org Properties"
3027 :group 'org)
3029 (defcustom org-property-format "%-10s %s"
3030 "How property key/value pairs should be formatted by `indent-line'.
3031 When `indent-line' hits a property definition, it will format the line
3032 according to this format, mainly to make sure that the values are
3033 lined-up with respect to each other."
3034 :group 'org-properties
3035 :type 'string)
3037 (defcustom org-properties-postprocess-alist nil
3038 "Alist of properties and functions to adjust inserted values.
3039 Elements of this alist must be of the form
3041 ([string] [function])
3043 where [string] must be a property name and [function] must be a
3044 lambda expression: this lambda expression must take one argument,
3045 the value to adjust, and return the new value as a string.
3047 For example, this element will allow the property \"Remaining\"
3048 to be updated wrt the relation between the \"Effort\" property
3049 and the clock summary:
3051 ((\"Remaining\" (lambda(value)
3052 (let ((clocksum (org-clock-sum-current-item))
3053 (effort (org-duration-string-to-minutes
3054 (org-entry-get (point) \"Effort\"))))
3055 (org-minutes-to-hh:mm-string (- effort clocksum))))))"
3056 :group 'org-properties
3057 :type 'alist)
3059 (defcustom org-use-property-inheritance nil
3060 "Non-nil means properties apply also for sublevels.
3062 This setting is chiefly used during property searches. Turning it on can
3063 cause significant overhead when doing a search, which is why it is not
3064 on by default.
3066 When nil, only the properties directly given in the current entry count.
3067 When t, every property is inherited. The value may also be a list of
3068 properties that should have inheritance, or a regular expression matching
3069 properties that should be inherited.
3071 However, note that some special properties use inheritance under special
3072 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3073 and the properties ending in \"_ALL\" when they are used as descriptor
3074 for valid values of a property.
3076 Note for programmers:
3077 When querying an entry with `org-entry-get', you can control if inheritance
3078 should be used. By default, `org-entry-get' looks only at the local
3079 properties. You can request inheritance by setting the inherit argument
3080 to t (to force inheritance) or to `selective' (to respect the setting
3081 in this variable)."
3082 :group 'org-properties
3083 :type '(choice
3084 (const :tag "Not" nil)
3085 (const :tag "Always" t)
3086 (repeat :tag "Specific properties" (string :tag "Property"))
3087 (regexp :tag "Properties matched by regexp")))
3089 (defun org-property-inherit-p (property)
3090 "Check if PROPERTY is one that should be inherited."
3091 (cond
3092 ((eq org-use-property-inheritance t) t)
3093 ((not org-use-property-inheritance) nil)
3094 ((stringp org-use-property-inheritance)
3095 (string-match org-use-property-inheritance property))
3096 ((listp org-use-property-inheritance)
3097 (member property org-use-property-inheritance))
3098 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3100 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3101 "The default column format, if no other format has been defined.
3102 This variable can be set on the per-file basis by inserting a line
3104 #+COLUMNS: %25ITEM ....."
3105 :group 'org-properties
3106 :type 'string)
3108 (defcustom org-columns-ellipses ".."
3109 "The ellipses to be used when a field in column view is truncated.
3110 When this is the empty string, as many characters as possible are shown,
3111 but then there will be no visual indication that the field has been truncated.
3112 When this is a string of length N, the last N characters of a truncated
3113 field are replaced by this string. If the column is narrower than the
3114 ellipses string, only part of the ellipses string will be shown."
3115 :group 'org-properties
3116 :type 'string)
3118 (defcustom org-columns-modify-value-for-display-function nil
3119 "Function that modifies values for display in column view.
3120 For example, it can be used to cut out a certain part from a time stamp.
3121 The function must take 2 arguments:
3123 column-title The title of the column (*not* the property name)
3124 value The value that should be modified.
3126 The function should return the value that should be displayed,
3127 or nil if the normal value should be used."
3128 :group 'org-properties
3129 :type 'function)
3131 (defcustom org-effort-property "Effort"
3132 "The property that is being used to keep track of effort estimates.
3133 Effort estimates given in this property need to have the format H:MM."
3134 :group 'org-properties
3135 :group 'org-progress
3136 :type '(string :tag "Property"))
3138 (defconst org-global-properties-fixed
3139 '(("VISIBILITY_ALL" . "folded children content all")
3140 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3141 "List of property/value pairs that can be inherited by any entry.
3143 These are fixed values, for the preset properties. The user variable
3144 that can be used to add to this list is `org-global-properties'.
3146 The entries in this list are cons cells where the car is a property
3147 name and cdr is a string with the value. If the value represents
3148 multiple items like an \"_ALL\" property, separate the items by
3149 spaces.")
3151 (defcustom org-global-properties nil
3152 "List of property/value pairs that can be inherited by any entry.
3154 This list will be combined with the constant `org-global-properties-fixed'.
3156 The entries in this list are cons cells where the car is a property
3157 name and cdr is a string with the value.
3159 You can set buffer-local values for the same purpose in the variable
3160 `org-file-properties' this by adding lines like
3162 #+PROPERTY: NAME VALUE"
3163 :group 'org-properties
3164 :type '(repeat
3165 (cons (string :tag "Property")
3166 (string :tag "Value"))))
3168 (defvar org-file-properties nil
3169 "List of property/value pairs that can be inherited by any entry.
3170 Valid for the current buffer.
3171 This variable is populated from #+PROPERTY lines.")
3172 (make-variable-buffer-local 'org-file-properties)
3174 (defgroup org-agenda nil
3175 "Options concerning agenda views in Org-mode."
3176 :tag "Org Agenda"
3177 :group 'org)
3179 (defvar org-category nil
3180 "Variable used by org files to set a category for agenda display.
3181 Such files should use a file variable to set it, for example
3183 # -*- mode: org; org-category: \"ELisp\"
3185 or contain a special line
3187 #+CATEGORY: ELisp
3189 If the file does not specify a category, then file's base name
3190 is used instead.")
3191 (make-variable-buffer-local 'org-category)
3192 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3194 (defcustom org-agenda-files nil
3195 "The files to be used for agenda display.
3196 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3197 \\[org-remove-file]. You can also use customize to edit the list.
3199 If an entry is a directory, all files in that directory that are matched by
3200 `org-agenda-file-regexp' will be part of the file list.
3202 If the value of the variable is not a list but a single file name, then
3203 the list of agenda files is actually stored and maintained in that file, one
3204 agenda file per line. In this file paths can be given relative to
3205 `org-directory'. Tilde expansion and environment variable substitution
3206 are also made."
3207 :group 'org-agenda
3208 :type '(choice
3209 (repeat :tag "List of files and directories" file)
3210 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3212 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3213 "Regular expression to match files for `org-agenda-files'.
3214 If any element in the list in that variable contains a directory instead
3215 of a normal file, all files in that directory that are matched by this
3216 regular expression will be included."
3217 :group 'org-agenda
3218 :type 'regexp)
3220 (defcustom org-agenda-text-search-extra-files nil
3221 "List of extra files to be searched by text search commands.
3222 These files will be search in addition to the agenda files by the
3223 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3224 Note that these files will only be searched for text search commands,
3225 not for the other agenda views like todo lists, tag searches or the weekly
3226 agenda. This variable is intended to list notes and possibly archive files
3227 that should also be searched by these two commands.
3228 In fact, if the first element in the list is the symbol `agenda-archives',
3229 than all archive files of all agenda files will be added to the search
3230 scope."
3231 :group 'org-agenda
3232 :type '(set :greedy t
3233 (const :tag "Agenda Archives" agenda-archives)
3234 (repeat :inline t (file))))
3236 (if (fboundp 'defvaralias)
3237 (defvaralias 'org-agenda-multi-occur-extra-files
3238 'org-agenda-text-search-extra-files))
3240 (defcustom org-agenda-skip-unavailable-files nil
3241 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3242 A nil value means to remove them, after a query, from the list."
3243 :group 'org-agenda
3244 :type 'boolean)
3246 (defcustom org-calendar-to-agenda-key [?c]
3247 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3248 The command `org-calendar-goto-agenda' will be bound to this key. The
3249 default is the character `c' because then `c' can be used to switch back and
3250 forth between agenda and calendar."
3251 :group 'org-agenda
3252 :type 'sexp)
3254 (defcustom org-calendar-agenda-action-key [?k]
3255 "The key to be installed in `calendar-mode-map' for agenda-action.
3256 The command `org-agenda-action' will be bound to this key. The
3257 default is the character `k' because we use the same key in the agenda."
3258 :group 'org-agenda
3259 :type 'sexp)
3261 (defcustom org-calendar-insert-diary-entry-key [?i]
3262 "The key to be installed in `calendar-mode-map' for adding diary entries.
3263 This option is irrelevant until `org-agenda-diary-file' has been configured
3264 to point to an Org-mode file. When that is the case, the command
3265 `org-agenda-diary-entry' will be bound to the key given here, by default
3266 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3267 if you want to continue doing this, you need to change this to a different
3268 key."
3269 :group 'org-agenda
3270 :type 'sexp)
3272 (defcustom org-agenda-diary-file 'diary-file
3273 "File to which to add new entries with the `i' key in agenda and calendar.
3274 When this is the symbol `diary-file', the functionality in the Emacs
3275 calendar will be used to add entries to the `diary-file'. But when this
3276 points to a file, `org-agenda-diary-entry' will be used instead."
3277 :group 'org-agenda
3278 :type '(choice
3279 (const :tag "The standard Emacs diary file" diary-file)
3280 (file :tag "Special Org file diary entries")))
3282 (eval-after-load "calendar"
3283 '(progn
3284 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3285 'org-calendar-goto-agenda)
3286 (org-defkey calendar-mode-map org-calendar-agenda-action-key
3287 'org-agenda-action)
3288 (add-hook 'calendar-mode-hook
3289 (lambda ()
3290 (unless (eq org-agenda-diary-file 'diary-file)
3291 (define-key calendar-mode-map
3292 org-calendar-insert-diary-entry-key
3293 'org-agenda-diary-entry))))))
3295 (defgroup org-latex nil
3296 "Options for embedding LaTeX code into Org-mode."
3297 :tag "Org LaTeX"
3298 :group 'org)
3300 (defcustom org-format-latex-options
3301 '(:foreground default :background default :scale 1.0
3302 :html-foreground "Black" :html-background "Transparent"
3303 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3304 "Options for creating images from LaTeX fragments.
3305 This is a property list with the following properties:
3306 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3307 `default' means use the foreground of the default face.
3308 :background the background color, or \"Transparent\".
3309 `default' means use the background of the default face.
3310 :scale a scaling factor for the size of the images, to get more pixels
3311 :html-foreground, :html-background, :html-scale
3312 the same numbers for HTML export.
3313 :matchers a list indicating which matchers should be used to
3314 find LaTeX fragments. Valid members of this list are:
3315 \"begin\" find environments
3316 \"$1\" find single characters surrounded by $.$
3317 \"$\" find math expressions surrounded by $...$
3318 \"$$\" find math expressions surrounded by $$....$$
3319 \"\\(\" find math expressions surrounded by \\(...\\)
3320 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3321 :group 'org-latex
3322 :type 'plist)
3324 (defcustom org-format-latex-signal-error t
3325 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3326 When nil, just push out a message."
3327 :group 'org-latex
3328 :type 'boolean)
3329 (defcustom org-latex-to-mathml-jar-file nil
3330 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3331 Use this to specify additional executable file say a jar file.
3333 When using MathToWeb as the converter, specify the full-path to
3334 your mathtoweb.jar file."
3335 :group 'org-latex
3336 :type '(choice
3337 (const :tag "None" nil)
3338 (file :tag "JAR file" :must-match t)))
3340 (defcustom org-latex-to-mathml-convert-command nil
3341 "Command to convert LaTeX fragments to MathML.
3342 Replace format-specifiers in the command as noted below and use
3343 `shell-command' to convert LaTeX to MathML.
3344 %j: Executable file in fully expanded form as specified by
3345 `org-latex-to-mathml-jar-file'.
3346 %I: Input LaTeX file in fully expanded form
3347 %o: Output MathML file
3348 This command is used by `org-create-math-formula'.
3350 When using MathToWeb as the converter, set this to
3351 \"java -jar %j -unicode -force -df %o %I\"."
3352 :group 'org-latex
3353 :type '(choice
3354 (const :tag "None" nil)
3355 (string :tag "\nShell command")))
3357 (defun org-format-latex-mathml-available-p ()
3358 "Return t if `org-latex-to-mathml-convert-command' is usable."
3359 (save-match-data
3360 (when (and (boundp 'org-latex-to-mathml-convert-command)
3361 org-latex-to-mathml-convert-command)
3362 (let ((executable (car (split-string
3363 org-latex-to-mathml-convert-command))))
3364 (when (executable-find executable)
3365 (if (string-match
3366 "%j" org-latex-to-mathml-convert-command)
3367 (file-readable-p org-latex-to-mathml-jar-file)
3368 t))))))
3370 (defcustom org-format-latex-header "\\documentclass{article}
3371 \\usepackage[usenames]{color}
3372 \\usepackage{amsmath}
3373 \\usepackage[mathscr]{eucal}
3374 \\pagestyle{empty} % do not remove
3375 \[PACKAGES]
3376 \[DEFAULT-PACKAGES]
3377 % The settings below are copied from fullpage.sty
3378 \\setlength{\\textwidth}{\\paperwidth}
3379 \\addtolength{\\textwidth}{-3cm}
3380 \\setlength{\\oddsidemargin}{1.5cm}
3381 \\addtolength{\\oddsidemargin}{-2.54cm}
3382 \\setlength{\\evensidemargin}{\\oddsidemargin}
3383 \\setlength{\\textheight}{\\paperheight}
3384 \\addtolength{\\textheight}{-\\headheight}
3385 \\addtolength{\\textheight}{-\\headsep}
3386 \\addtolength{\\textheight}{-\\footskip}
3387 \\addtolength{\\textheight}{-3cm}
3388 \\setlength{\\topmargin}{1.5cm}
3389 \\addtolength{\\topmargin}{-2.54cm}"
3390 "The document header used for processing LaTeX fragments.
3391 It is imperative that this header make sure that no page number
3392 appears on the page. The package defined in the variables
3393 `org-export-latex-default-packages-alist' and `org-export-latex-packages-alist'
3394 will either replace the placeholder \"[PACKAGES]\" in this header, or they
3395 will be appended."
3396 :group 'org-latex
3397 :type 'string)
3399 (defvar org-format-latex-header-extra nil)
3401 (defun org-set-packages-alist (var val)
3402 "Set the packages alist and make sure it has 3 elements per entry."
3403 (set var (mapcar (lambda (x)
3404 (if (and (consp x) (= (length x) 2))
3405 (list (car x) (nth 1 x) t)
3407 val)))
3409 (defun org-get-packages-alist (var)
3411 "Get the packages alist and make sure it has 3 elements per entry."
3412 (mapcar (lambda (x)
3413 (if (and (consp x) (= (length x) 2))
3414 (list (car x) (nth 1 x) t)
3416 (default-value var)))
3418 ;; The following variables are defined here because is it also used
3419 ;; when formatting latex fragments. Originally it was part of the
3420 ;; LaTeX exporter, which is why the name includes "export".
3421 (defcustom org-export-latex-default-packages-alist
3422 '(("AUTO" "inputenc" t)
3423 ("T1" "fontenc" t)
3424 ("" "fixltx2e" nil)
3425 ("" "graphicx" t)
3426 ("" "longtable" nil)
3427 ("" "float" nil)
3428 ("" "wrapfig" nil)
3429 ("" "soul" t)
3430 ("" "textcomp" t)
3431 ("" "marvosym" t)
3432 ("" "wasysym" t)
3433 ("" "latexsym" t)
3434 ("" "amssymb" t)
3435 ("" "hyperref" nil)
3436 "\\tolerance=1000"
3438 "Alist of default packages to be inserted in the header.
3439 Change this only if one of the packages here causes an incompatibility
3440 with another package you are using.
3441 The packages in this list are needed by one part or another of Org-mode
3442 to function properly.
3444 - inputenc, fontenc: for basic font and character selection
3445 - textcomp, marvosymb, wasysym, latexsym, amssym: for various symbols used
3446 for interpreting the entities in `org-entities'. You can skip some of these
3447 packages if you don't use any of the symbols in it.
3448 - graphicx: for including images
3449 - float, wrapfig: for figure placement
3450 - longtable: for long tables
3451 - hyperref: for cross references
3453 Therefore you should not modify this variable unless you know what you
3454 are doing. The one reason to change it anyway is that you might be loading
3455 some other package that conflicts with one of the default packages.
3456 Each cell is of the format \( \"options\" \"package\" snippet-flag\).
3457 If SNIPPET-FLAG is t, the package also needs to be included when
3458 compiling LaTeX snippets into images for inclusion into HTML."
3459 :group 'org-export-latex
3460 :set 'org-set-packages-alist
3461 :get 'org-get-packages-alist
3462 :type '(repeat
3463 (choice
3464 (list :tag "options/package pair"
3465 (string :tag "options")
3466 (string :tag "package")
3467 (boolean :tag "Snippet"))
3468 (string :tag "A line of LaTeX"))))
3470 (defcustom org-export-latex-packages-alist nil
3471 "Alist of packages to be inserted in every LaTeX header.
3472 These will be inserted after `org-export-latex-default-packages-alist'.
3473 Each cell is of the format \( \"options\" \"package\" snippet-flag \).
3474 SNIPPET-FLAG, when t, indicates that this package is also needed when
3475 turning LaTeX snippets into images for inclusion into HTML.
3476 Make sure that you only list packages here which:
3477 - you want in every file
3478 - do not conflict with the default packages in
3479 `org-export-latex-default-packages-alist'
3480 - do not conflict with the setup in `org-format-latex-header'."
3481 :group 'org-export-latex
3482 :set 'org-set-packages-alist
3483 :get 'org-get-packages-alist
3484 :type '(repeat
3485 (choice
3486 (list :tag "options/package pair"
3487 (string :tag "options")
3488 (string :tag "package")
3489 (boolean :tag "Snippet"))
3490 (string :tag "A line of LaTeX"))))
3493 (defgroup org-appearance nil
3494 "Settings for Org-mode appearance."
3495 :tag "Org Appearance"
3496 :group 'org)
3498 (defcustom org-level-color-stars-only nil
3499 "Non-nil means fontify only the stars in each headline.
3500 When nil, the entire headline is fontified.
3501 Changing it requires restart of `font-lock-mode' to become effective
3502 also in regions already fontified."
3503 :group 'org-appearance
3504 :type 'boolean)
3506 (defcustom org-hide-leading-stars nil
3507 "Non-nil means hide the first N-1 stars in a headline.
3508 This works by using the face `org-hide' for these stars. This
3509 face is white for a light background, and black for a dark
3510 background. You may have to customize the face `org-hide' to
3511 make this work.
3512 Changing it requires restart of `font-lock-mode' to become effective
3513 also in regions already fontified.
3514 You may also set this on a per-file basis by adding one of the following
3515 lines to the buffer:
3517 #+STARTUP: hidestars
3518 #+STARTUP: showstars"
3519 :group 'org-appearance
3520 :type 'boolean)
3522 (defcustom org-hidden-keywords nil
3523 "List of symbols corresponding to keywords to be hidden the org buffer.
3524 For example, a value '(title) for this list will make the document's title
3525 appear in the buffer without the initial #+TITLE: keyword."
3526 :group 'org-appearance
3527 :type '(set (const :tag "#+AUTHOR" author)
3528 (const :tag "#+DATE" date)
3529 (const :tag "#+EMAIL" email)
3530 (const :tag "#+TITLE" title)))
3532 (defcustom org-fontify-done-headline nil
3533 "Non-nil means change the face of a headline if it is marked DONE.
3534 Normally, only the TODO/DONE keyword indicates the state of a headline.
3535 When this is non-nil, the headline after the keyword is set to the
3536 `org-headline-done' as an additional indication."
3537 :group 'org-appearance
3538 :type 'boolean)
3540 (defcustom org-fontify-emphasized-text t
3541 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3542 Changing this variable requires a restart of Emacs to take effect."
3543 :group 'org-appearance
3544 :type 'boolean)
3546 (defcustom org-fontify-whole-heading-line nil
3547 "Non-nil means fontify the whole line for headings.
3548 This is useful when setting a background color for the
3549 org-level-* faces."
3550 :group 'org-appearance
3551 :type 'boolean)
3553 (defcustom org-highlight-latex-fragments-and-specials nil
3554 "Non-nil means fontify what is treated specially by the exporters."
3555 :group 'org-appearance
3556 :type 'boolean)
3558 (defcustom org-hide-emphasis-markers nil
3559 "Non-nil mean font-lock should hide the emphasis marker characters."
3560 :group 'org-appearance
3561 :type 'boolean)
3563 (defcustom org-pretty-entities nil
3564 "Non-nil means show entities as UTF8 characters.
3565 When nil, the \\name form remains in the buffer."
3566 :group 'org-appearance
3567 :type 'boolean)
3569 (defcustom org-pretty-entities-include-sub-superscripts t
3570 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3571 :group 'org-appearance
3572 :type 'boolean)
3574 (defvar org-emph-re nil
3575 "Regular expression for matching emphasis.
3576 After a match, the match groups contain these elements:
3577 0 The match of the full regular expression, including the characters
3578 before and after the proper match
3579 1 The character before the proper match, or empty at beginning of line
3580 2 The proper match, including the leading and trailing markers
3581 3 The leading marker like * or /, indicating the type of highlighting
3582 4 The text between the emphasis markers, not including the markers
3583 5 The character after the match, empty at the end of a line")
3584 (defvar org-verbatim-re nil
3585 "Regular expression for matching verbatim text.")
3586 (defvar org-emphasis-regexp-components) ; defined just below
3587 (defvar org-emphasis-alist) ; defined just below
3588 (defun org-set-emph-re (var val)
3589 "Set variable and compute the emphasis regular expression."
3590 (set var val)
3591 (when (and (boundp 'org-emphasis-alist)
3592 (boundp 'org-emphasis-regexp-components)
3593 org-emphasis-alist org-emphasis-regexp-components)
3594 (let* ((e org-emphasis-regexp-components)
3595 (pre (car e))
3596 (post (nth 1 e))
3597 (border (nth 2 e))
3598 (body (nth 3 e))
3599 (nl (nth 4 e))
3600 (body1 (concat body "*?"))
3601 (markers (mapconcat 'car org-emphasis-alist ""))
3602 (vmarkers (mapconcat
3603 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3604 org-emphasis-alist "")))
3605 ;; make sure special characters appear at the right position in the class
3606 (if (string-match "\\^" markers)
3607 (setq markers (concat (replace-match "" t t markers) "^")))
3608 (if (string-match "-" markers)
3609 (setq markers (concat (replace-match "" t t markers) "-")))
3610 (if (string-match "\\^" vmarkers)
3611 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3612 (if (string-match "-" vmarkers)
3613 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3614 (if (> nl 0)
3615 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3616 (int-to-string nl) "\\}")))
3617 ;; Make the regexp
3618 (setq org-emph-re
3619 (concat "\\([" pre "]\\|^\\)"
3620 "\\("
3621 "\\([" markers "]\\)"
3622 "\\("
3623 "[^" border "]\\|"
3624 "[^" border "]"
3625 body1
3626 "[^" border "]"
3627 "\\)"
3628 "\\3\\)"
3629 "\\([" post "]\\|$\\)"))
3630 (setq org-verbatim-re
3631 (concat "\\([" pre "]\\|^\\)"
3632 "\\("
3633 "\\([" vmarkers "]\\)"
3634 "\\("
3635 "[^" border "]\\|"
3636 "[^" border "]"
3637 body1
3638 "[^" border "]"
3639 "\\)"
3640 "\\3\\)"
3641 "\\([" post "]\\|$\\)")))))
3643 (defcustom org-emphasis-regexp-components
3644 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
3645 "Components used to build the regular expression for emphasis.
3646 This is a list with five entries. Terminology: In an emphasis string
3647 like \" *strong word* \", we call the initial space PREMATCH, the final
3648 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3649 and \"trong wor\" is the body. The different components in this variable
3650 specify what is allowed/forbidden in each part:
3652 pre Chars allowed as prematch. Beginning of line will be allowed too.
3653 post Chars allowed as postmatch. End of line will be allowed too.
3654 border The chars *forbidden* as border characters.
3655 body-regexp A regexp like \".\" to match a body character. Don't use
3656 non-shy groups here, and don't allow newline here.
3657 newline The maximum number of newlines allowed in an emphasis exp.
3659 Use customize to modify this, or restart Emacs after changing it."
3660 :group 'org-appearance
3661 :set 'org-set-emph-re
3662 :type '(list
3663 (sexp :tag "Allowed chars in pre ")
3664 (sexp :tag "Allowed chars in post ")
3665 (sexp :tag "Forbidden chars in border ")
3666 (sexp :tag "Regexp for body ")
3667 (integer :tag "number of newlines allowed")
3668 (option (boolean :tag "Please ignore this button"))))
3670 (defcustom org-emphasis-alist
3671 `(("*" bold "<b>" "</b>")
3672 ("/" italic "<i>" "</i>")
3673 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
3674 ("=" org-code "<code>" "</code>" verbatim)
3675 ("~" org-verbatim "<code>" "</code>" verbatim)
3676 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
3677 "<del>" "</del>")
3679 "Special syntax for emphasized text.
3680 Text starting and ending with a special character will be emphasized, for
3681 example *bold*, _underlined_ and /italic/. This variable sets the marker
3682 characters, the face to be used by font-lock for highlighting in Org-mode
3683 Emacs buffers, and the HTML tags to be used for this.
3684 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
3685 For DocBook export, see the variable `org-export-docbook-emphasis-alist'.
3686 Use customize to modify this, or restart Emacs after changing it."
3687 :group 'org-appearance
3688 :set 'org-set-emph-re
3689 :type '(repeat
3690 (list
3691 (string :tag "Marker character")
3692 (choice
3693 (face :tag "Font-lock-face")
3694 (plist :tag "Face property list"))
3695 (string :tag "HTML start tag")
3696 (string :tag "HTML end tag")
3697 (option (const verbatim)))))
3699 (defvar org-protecting-blocks
3700 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
3701 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
3702 This is needed for font-lock setup.")
3704 ;;; Miscellaneous options
3706 (defgroup org-completion nil
3707 "Completion in Org-mode."
3708 :tag "Org Completion"
3709 :group 'org)
3711 (defcustom org-completion-use-ido nil
3712 "Non-nil means use ido completion wherever possible.
3713 Note that `ido-mode' must be active for this variable to be relevant.
3714 If you decide to turn this variable on, you might well want to turn off
3715 `org-outline-path-complete-in-steps'.
3716 See also `org-completion-use-iswitchb'."
3717 :group 'org-completion
3718 :type 'boolean)
3720 (defcustom org-completion-use-iswitchb nil
3721 "Non-nil means use iswitchb completion wherever possible.
3722 Note that `iswitchb-mode' must be active for this variable to be relevant.
3723 If you decide to turn this variable on, you might well want to turn off
3724 `org-outline-path-complete-in-steps'.
3725 Note that this variable has only an effect if `org-completion-use-ido' is nil."
3726 :group 'org-completion
3727 :type 'boolean)
3729 (defcustom org-completion-fallback-command 'hippie-expand
3730 "The expansion command called by \\[pcomplete] in normal context.
3731 Normal means, no org-mode-specific context."
3732 :group 'org-completion
3733 :type 'function)
3735 ;;; Functions and variables from their packages
3736 ;; Declared here to avoid compiler warnings
3738 ;; XEmacs only
3739 (defvar outline-mode-menu-heading)
3740 (defvar outline-mode-menu-show)
3741 (defvar outline-mode-menu-hide)
3742 (defvar zmacs-regions) ; XEmacs regions
3744 ;; Emacs only
3745 (defvar mark-active)
3747 ;; Various packages
3748 (declare-function calendar-absolute-from-iso "cal-iso" (date))
3749 (declare-function calendar-forward-day "cal-move" (arg))
3750 (declare-function calendar-goto-date "cal-move" (date))
3751 (declare-function calendar-goto-today "cal-move" ())
3752 (declare-function calendar-iso-from-absolute "cal-iso" (date))
3753 (defvar calc-embedded-close-formula)
3754 (defvar calc-embedded-open-formula)
3755 (declare-function cdlatex-tab "ext:cdlatex" ())
3756 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
3757 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3758 (defvar font-lock-unfontify-region-function)
3759 (declare-function iswitchb-read-buffer "iswitchb"
3760 (prompt &optional default require-match start matches-set))
3761 (defvar iswitchb-temp-buflist)
3762 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
3763 (defvar org-agenda-tags-todo-honor-ignore-options)
3764 (declare-function org-agenda-skip "org-agenda" ())
3765 (declare-function
3766 org-agenda-format-item "org-agenda"
3767 (extra txt &optional category tags dotime noprefix remove-re habitp))
3768 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
3769 (declare-function org-agenda-change-all-lines "org-agenda"
3770 (newhead hdmarker &optional fixface just-this))
3771 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
3772 (declare-function org-agenda-maybe-redo "org-agenda" ())
3773 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
3774 (beg end))
3775 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
3776 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
3777 "org-agenda" (&optional end))
3778 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
3779 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
3780 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
3781 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
3782 (declare-function org-indent-mode "org-indent" (&optional arg))
3783 (declare-function parse-time-string "parse-time" (string))
3784 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
3785 (declare-function org-export-latex-fix-inputenc "org-latex" ())
3786 (declare-function orgtbl-send-table "org-table" (&optional maybe))
3787 (defvar remember-data-file)
3788 (defvar texmathp-why)
3789 (declare-function speedbar-line-directory "speedbar" (&optional depth))
3790 (declare-function table--at-cell-p "table" (position &optional object at-column))
3792 (defvar w3m-current-url)
3793 (defvar w3m-current-title)
3795 (defvar org-latex-regexps)
3797 ;;; Autoload and prepare some org modules
3799 ;; Some table stuff that needs to be defined here, because it is used
3800 ;; by the functions setting up org-mode or checking for table context.
3802 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
3803 "Detect an org-type or table-type table.")
3804 (defconst org-table-line-regexp "^[ \t]*|"
3805 "Detect an org-type table line.")
3806 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
3807 "Detect an org-type table line.")
3808 (defconst org-table-hline-regexp "^[ \t]*|-"
3809 "Detect an org-type table hline.")
3810 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
3811 "Detect a table-type table hline.")
3812 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
3813 "Detect the first line outside a table when searching from within it.
3814 This works for both table types.")
3816 ;; Autoload the functions in org-table.el that are needed by functions here.
3818 (eval-and-compile
3819 (org-autoload "org-table"
3820 '(org-table-align org-table-begin org-table-blank-field
3821 org-table-convert org-table-convert-region org-table-copy-down
3822 org-table-copy-region org-table-create
3823 org-table-create-or-convert-from-region
3824 org-table-create-with-table.el org-table-current-dline
3825 org-table-cut-region org-table-delete-column org-table-edit-field
3826 org-table-edit-formulas org-table-end org-table-eval-formula
3827 org-table-export org-table-field-info
3828 org-table-get-stored-formulas org-table-goto-column
3829 org-table-hline-and-move org-table-import org-table-insert-column
3830 org-table-insert-hline org-table-insert-row org-table-iterate
3831 org-table-justify-field-maybe org-table-kill-row
3832 org-table-maybe-eval-formula org-table-maybe-recalculate-line
3833 org-table-move-column org-table-move-column-left
3834 org-table-move-column-right org-table-move-row
3835 org-table-move-row-down org-table-move-row-up
3836 org-table-next-field org-table-next-row org-table-paste-rectangle
3837 org-table-previous-field org-table-recalculate
3838 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
3839 org-table-toggle-coordinate-overlays
3840 org-table-toggle-formula-debugger org-table-wrap-region
3841 orgtbl-mode turn-on-orgtbl org-table-to-lisp
3842 orgtbl-to-generic orgtbl-to-tsv orgtbl-to-csv orgtbl-to-latex
3843 orgtbl-to-orgtbl orgtbl-to-html orgtbl-to-texinfo)))
3845 (defun org-at-table-p (&optional table-type)
3846 "Return t if the cursor is inside an org-type table.
3847 If TABLE-TYPE is non-nil, also check for table.el-type tables."
3848 (if org-enable-table-editor
3849 (save-excursion
3850 (beginning-of-line 1)
3851 (looking-at (if table-type org-table-any-line-regexp
3852 org-table-line-regexp)))
3853 nil))
3854 (defsubst org-table-p () (org-at-table-p))
3856 (defun org-at-table.el-p ()
3857 "Return t if and only if we are at a table.el table."
3858 (and (org-at-table-p 'any)
3859 (save-excursion
3860 (goto-char (org-table-begin 'any))
3861 (looking-at org-table1-hline-regexp))))
3862 (defun org-table-recognize-table.el ()
3863 "If there is a table.el table nearby, recognize it and move into it."
3864 (if org-table-tab-recognizes-table.el
3865 (if (org-at-table.el-p)
3866 (progn
3867 (beginning-of-line 1)
3868 (if (looking-at org-table-dataline-regexp)
3870 (if (looking-at org-table1-hline-regexp)
3871 (progn
3872 (beginning-of-line 2)
3873 (if (looking-at org-table-any-border-regexp)
3874 (beginning-of-line -1)))))
3875 (if (re-search-forward "|" (org-table-end t) t)
3876 (progn
3877 (require 'table)
3878 (if (table--at-cell-p (point))
3880 (message "recognizing table.el table...")
3881 (table-recognize-table)
3882 (message "recognizing table.el table...done")))
3883 (error "This should not happen"))
3885 nil)
3886 nil))
3888 (defun org-at-table-hline-p ()
3889 "Return t if the cursor is inside a hline in a table."
3890 (if org-enable-table-editor
3891 (save-excursion
3892 (beginning-of-line 1)
3893 (looking-at org-table-hline-regexp))
3894 nil))
3896 (defvar org-table-clean-did-remove-column nil)
3898 (defun org-table-map-tables (function &optional quietly)
3899 "Apply FUNCTION to the start of all tables in the buffer."
3900 (save-excursion
3901 (save-restriction
3902 (widen)
3903 (goto-char (point-min))
3904 (while (re-search-forward org-table-any-line-regexp nil t)
3905 (unless quietly
3906 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
3907 (beginning-of-line 1)
3908 (when (looking-at org-table-line-regexp)
3909 (save-excursion (funcall function))
3910 (or (looking-at org-table-line-regexp)
3911 (forward-char 1)))
3912 (re-search-forward org-table-any-border-regexp nil 1))))
3913 (unless quietly (message "Mapping tables: done")))
3915 ;; Declare and autoload functions from org-exp.el & Co
3917 (declare-function org-default-export-plist "org-exp")
3918 (declare-function org-infile-export-plist "org-exp")
3919 (declare-function org-get-current-options "org-exp")
3920 (eval-and-compile
3921 (org-autoload "org-exp"
3922 '(org-export org-export-visible
3923 org-insert-export-options-template
3924 org-table-clean-before-export))
3925 (org-autoload "org-ascii"
3926 '(org-export-as-ascii org-export-ascii-preprocess
3927 org-export-as-ascii-to-buffer org-replace-region-by-ascii
3928 org-export-region-as-ascii))
3929 (org-autoload "org-latex"
3930 '(org-export-as-latex-batch org-export-as-latex-to-buffer
3931 org-replace-region-by-latex org-export-region-as-latex
3932 org-export-as-latex org-export-as-pdf
3933 org-export-as-pdf-and-open))
3934 (org-autoload "org-html"
3935 '(org-export-as-html-and-open
3936 org-export-as-html-batch org-export-as-html-to-buffer
3937 org-replace-region-by-html org-export-region-as-html
3938 org-export-as-html))
3939 (org-autoload "org-docbook"
3940 '(org-export-as-docbook-batch org-export-as-docbook-to-buffer
3941 org-replace-region-by-docbook org-export-region-as-docbook
3942 org-export-as-docbook-pdf org-export-as-docbook-pdf-and-open
3943 org-export-as-docbook))
3944 (org-autoload "org-icalendar"
3945 '(org-export-icalendar-this-file
3946 org-export-icalendar-all-agenda-files
3947 org-export-icalendar-combine-agenda-files))
3948 (org-autoload "org-xoxo" '(org-export-as-xoxo))
3949 (org-autoload "org-beamer" '(org-beamer-mode org-beamer-sectioning)))
3951 ;; Declare and autoload functions from org-agenda.el
3953 (eval-and-compile
3954 (org-autoload "org-agenda"
3955 '(org-agenda org-agenda-list org-search-view
3956 org-todo-list org-tags-view org-agenda-list-stuck-projects
3957 org-diary org-agenda-to-appt
3958 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
3960 ;; Autoload org-remember
3962 (eval-and-compile
3963 (org-autoload "org-remember"
3964 '(org-remember-insinuate org-remember-annotation
3965 org-remember-apply-template org-remember org-remember-handler)))
3967 (eval-and-compile
3968 (org-autoload "org-capture"
3969 '(org-capture org-capture-insert-template-here
3970 org-capture-import-remember-templates)))
3972 ;; Autoload org-clock.el
3974 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
3975 (beg end))
3976 (declare-function org-clock-update-mode-line "org-clock" ())
3977 (declare-function org-resolve-clocks "org-clock"
3978 (&optional also-non-dangling-p prompt last-valid))
3979 (defvar org-clock-start-time)
3980 (defvar org-clock-marker (make-marker)
3981 "Marker recording the last clock-in.")
3982 (defvar org-clock-hd-marker (make-marker)
3983 "Marker recording the last clock-in, but the headline position.")
3984 (defvar org-clock-heading ""
3985 "The heading of the current clock entry.")
3986 (defun org-clock-is-active ()
3987 "Return non-nil if clock is currently running.
3988 The return value is actually the clock marker."
3989 (marker-buffer org-clock-marker))
3991 (eval-and-compile
3992 (org-autoload
3993 "org-clock"
3994 '(org-clock-in org-clock-out org-clock-cancel
3995 org-clock-goto org-clock-sum org-clock-display
3996 org-clock-remove-overlays org-clock-report
3997 org-clocktable-shift org-dblock-write:clocktable
3998 org-get-clocktable org-resolve-clocks)))
4000 (defun org-clock-update-time-maybe ()
4001 "If this is a CLOCK line, update it and return t.
4002 Otherwise, return nil."
4003 (interactive)
4004 (save-excursion
4005 (beginning-of-line 1)
4006 (skip-chars-forward " \t")
4007 (when (looking-at org-clock-string)
4008 (let ((re (concat "[ \t]*" org-clock-string
4009 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
4010 "\\([ \t]*=>.*\\)?\\)?"))
4011 ts te h m s neg)
4012 (cond
4013 ((not (looking-at re))
4014 nil)
4015 ((not (match-end 2))
4016 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4017 (> org-clock-marker (point))
4018 (<= org-clock-marker (point-at-eol)))
4019 ;; The clock is running here
4020 (setq org-clock-start-time
4021 (apply 'encode-time
4022 (org-parse-time-string (match-string 1))))
4023 (org-clock-update-mode-line)))
4025 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
4026 (end-of-line 1)
4027 (setq ts (match-string 1)
4028 te (match-string 3))
4029 (setq s (- (org-float-time
4030 (apply 'encode-time (org-parse-time-string te)))
4031 (org-float-time
4032 (apply 'encode-time (org-parse-time-string ts))))
4033 neg (< s 0)
4034 s (abs s)
4035 h (floor (/ s 3600))
4036 s (- s (* 3600 h))
4037 m (floor (/ s 60))
4038 s (- s (* 60 s)))
4039 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
4040 t))))))
4042 (defun org-check-running-clock ()
4043 "Check if the current buffer contains the running clock.
4044 If yes, offer to stop it and to save the buffer with the changes."
4045 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4046 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4047 (buffer-name))))
4048 (org-clock-out)
4049 (when (y-or-n-p "Save changed buffer?")
4050 (save-buffer))))
4052 (defun org-clocktable-try-shift (dir n)
4053 "Check if this line starts a clock table, if yes, shift the time block."
4054 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4055 (org-clocktable-shift dir n)))
4057 ;; Autoload org-timer.el
4059 (eval-and-compile
4060 (org-autoload
4061 "org-timer"
4062 '(org-timer-start org-timer org-timer-item
4063 org-timer-change-times-in-region
4064 org-timer-set-timer
4065 org-timer-reset-timers
4066 org-timer-show-remaining-time)))
4068 ;; Autoload org-feed.el
4070 (eval-and-compile
4071 (org-autoload
4072 "org-feed"
4073 '(org-feed-update org-feed-update-all org-feed-goto-inbox)))
4076 ;; Autoload org-indent.el
4078 ;; Define the variable already here, to make sure we have it.
4079 (defvar org-indent-mode nil
4080 "Non-nil if Org-Indent mode is enabled.
4081 Use the command `org-indent-mode' to change this variable.")
4083 (eval-and-compile
4084 (org-autoload
4085 "org-indent"
4086 '(org-indent-mode)))
4088 ;; Autoload org-mobile.el
4090 (eval-and-compile
4091 (org-autoload
4092 "org-mobile"
4093 '(org-mobile-push org-mobile-pull org-mobile-create-sumo-agenda)))
4095 ;; Autoload archiving code
4096 ;; The stuff that is needed for cycling and tags has to be defined here.
4098 (defgroup org-archive nil
4099 "Options concerning archiving in Org-mode."
4100 :tag "Org Archive"
4101 :group 'org-structure)
4103 (defcustom org-archive-location "%s_archive::"
4104 "The location where subtrees should be archived.
4106 The value of this variable is a string, consisting of two parts,
4107 separated by a double-colon. The first part is a filename and
4108 the second part is a headline.
4110 When the filename is omitted, archiving happens in the same file.
4111 %s in the filename will be replaced by the current file
4112 name (without the directory part). Archiving to a different file
4113 is useful to keep archived entries from contributing to the
4114 Org-mode Agenda.
4116 The archived entries will be filed as subtrees of the specified
4117 headline. When the headline is omitted, the subtrees are simply
4118 filed away at the end of the file, as top-level entries. Also in
4119 the heading you can use %s to represent the file name, this can be
4120 useful when using the same archive for a number of different files.
4122 Here are a few examples:
4123 \"%s_archive::\"
4124 If the current file is Projects.org, archive in file
4125 Projects.org_archive, as top-level trees. This is the default.
4127 \"::* Archived Tasks\"
4128 Archive in the current file, under the top-level headline
4129 \"* Archived Tasks\".
4131 \"~/org/archive.org::\"
4132 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4134 \"~/org/archive.org::* From %s\"
4135 Archive in file ~/org/archive.org (absolute path), under headlines
4136 \"From FILENAME\" where file name is the current file name.
4138 \"basement::** Finished Tasks\"
4139 Archive in file ./basement (relative path), as level 3 trees
4140 below the level 2 heading \"** Finished Tasks\".
4142 You may set this option on a per-file basis by adding to the buffer a
4143 line like
4145 #+ARCHIVE: basement::** Finished Tasks
4147 You may also define it locally for a subtree by setting an ARCHIVE property
4148 in the entry. If such a property is found in an entry, or anywhere up
4149 the hierarchy, it will be used."
4150 :group 'org-archive
4151 :type 'string)
4153 (defcustom org-archive-tag "ARCHIVE"
4154 "The tag that marks a subtree as archived.
4155 An archived subtree does not open during visibility cycling, and does
4156 not contribute to the agenda listings.
4157 After changing this, font-lock must be restarted in the relevant buffers to
4158 get the proper fontification."
4159 :group 'org-archive
4160 :group 'org-keywords
4161 :type 'string)
4163 (defcustom org-agenda-skip-archived-trees t
4164 "Non-nil means the agenda will skip any items located in archived trees.
4165 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4166 variable is no longer recommended, you should leave it at the value t.
4167 Instead, use the key `v' to cycle the archives-mode in the agenda."
4168 :group 'org-archive
4169 :group 'org-agenda-skip
4170 :type 'boolean)
4172 (defcustom org-columns-skip-archived-trees t
4173 "Non-nil means ignore archived trees when creating column view."
4174 :group 'org-archive
4175 :group 'org-properties
4176 :type 'boolean)
4178 (defcustom org-cycle-open-archived-trees nil
4179 "Non-nil means `org-cycle' will open archived trees.
4180 An archived tree is a tree marked with the tag ARCHIVE.
4181 When nil, archived trees will stay folded. You can still open them with
4182 normal outline commands like `show-all', but not with the cycling commands."
4183 :group 'org-archive
4184 :group 'org-cycle
4185 :type 'boolean)
4187 (defcustom org-sparse-tree-open-archived-trees nil
4188 "Non-nil means sparse tree construction shows matches in archived trees.
4189 When nil, matches in these trees are highlighted, but the trees are kept in
4190 collapsed state."
4191 :group 'org-archive
4192 :group 'org-sparse-trees
4193 :type 'boolean)
4195 (defun org-cycle-hide-archived-subtrees (state)
4196 "Re-hide all archived subtrees after a visibility state change."
4197 (when (and (not org-cycle-open-archived-trees)
4198 (not (memq state '(overview folded))))
4199 (save-excursion
4200 (let* ((globalp (memq state '(contents all)))
4201 (beg (if globalp (point-min) (point)))
4202 (end (if globalp (point-max) (org-end-of-subtree t))))
4203 (org-hide-archived-subtrees beg end)
4204 (goto-char beg)
4205 (if (looking-at (concat ".*:" org-archive-tag ":"))
4206 (message "%s" (substitute-command-keys
4207 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4209 (defun org-force-cycle-archived ()
4210 "Cycle subtree even if it is archived."
4211 (interactive)
4212 (setq this-command 'org-cycle)
4213 (let ((org-cycle-open-archived-trees t))
4214 (call-interactively 'org-cycle)))
4216 (defun org-hide-archived-subtrees (beg end)
4217 "Re-hide all archived subtrees after a visibility state change."
4218 (save-excursion
4219 (let* ((re (concat ":" org-archive-tag ":")))
4220 (goto-char beg)
4221 (while (re-search-forward re end t)
4222 (when (org-on-heading-p)
4223 (org-flag-subtree t)
4224 (org-end-of-subtree t))))))
4226 (defun org-flag-subtree (flag)
4227 (save-excursion
4228 (org-back-to-heading t)
4229 (outline-end-of-heading)
4230 (outline-flag-region (point)
4231 (progn (org-end-of-subtree t) (point))
4232 flag)))
4234 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4236 (eval-and-compile
4237 (org-autoload "org-archive"
4238 '(org-add-archive-files org-archive-subtree
4239 org-archive-to-archive-sibling org-toggle-archive-tag
4240 org-archive-subtree-default
4241 org-archive-subtree-default-with-confirmation)))
4243 ;; Autoload Column View Code
4245 (declare-function org-columns-number-to-string "org-colview")
4246 (declare-function org-columns-get-format-and-top-level "org-colview")
4247 (declare-function org-columns-compute "org-colview")
4249 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4250 '(org-columns-number-to-string org-columns-get-format-and-top-level
4251 org-columns-compute org-agenda-columns org-columns-remove-overlays
4252 org-columns org-insert-columns-dblock org-dblock-write:columnview))
4254 ;; Autoload ID code
4256 (declare-function org-id-store-link "org-id")
4257 (declare-function org-id-locations-load "org-id")
4258 (declare-function org-id-locations-save "org-id")
4259 (defvar org-id-track-globally)
4260 (org-autoload "org-id"
4261 '(org-id-get-create org-id-new org-id-copy org-id-get
4262 org-id-get-with-outline-path-completion
4263 org-id-get-with-outline-drilling org-id-store-link
4264 org-id-goto org-id-find org-id-store-link))
4266 ;; Autoload Plotting Code
4268 (org-autoload "org-plot"
4269 '(org-plot/gnuplot))
4271 ;;; Variables for pre-computed regular expressions, all buffer local
4273 (defvar org-drawer-regexp nil
4274 "Matches first line of a hidden block.")
4275 (make-variable-buffer-local 'org-drawer-regexp)
4276 (defvar org-todo-regexp nil
4277 "Matches any of the TODO state keywords.")
4278 (make-variable-buffer-local 'org-todo-regexp)
4279 (defvar org-not-done-regexp nil
4280 "Matches any of the TODO state keywords except the last one.")
4281 (make-variable-buffer-local 'org-not-done-regexp)
4282 (defvar org-not-done-heading-regexp nil
4283 "Matches a TODO headline that is not done.")
4284 (make-variable-buffer-local 'org-not-done-regexp)
4285 (defvar org-todo-line-regexp nil
4286 "Matches a headline and puts TODO state into group 2 if present.")
4287 (make-variable-buffer-local 'org-todo-line-regexp)
4288 (defvar org-complex-heading-regexp nil
4289 "Matches a headline and puts everything into groups:
4290 group 1: the stars
4291 group 2: The todo keyword, maybe
4292 group 3: Priority cookie
4293 group 4: True headline
4294 group 5: Tags")
4295 (make-variable-buffer-local 'org-complex-heading-regexp)
4296 (defvar org-complex-heading-regexp-format nil
4297 "Printf format to make regexp to match an exact headline.
4298 This regexp will match the headline of any node which has the
4299 exact headline text that is put into the format, but may have any
4300 TODO state, priority and tags.")
4301 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4302 (defvar org-todo-line-tags-regexp nil
4303 "Matches a headline and puts TODO state into group 2 if present.
4304 Also put tags into group 4 if tags are present.")
4305 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4306 (defvar org-ds-keyword-length 12
4307 "Maximum length of the Deadline and SCHEDULED keywords.")
4308 (make-variable-buffer-local 'org-ds-keyword-length)
4309 (defvar org-deadline-regexp nil
4310 "Matches the DEADLINE keyword.")
4311 (make-variable-buffer-local 'org-deadline-regexp)
4312 (defvar org-deadline-time-regexp nil
4313 "Matches the DEADLINE keyword together with a time stamp.")
4314 (make-variable-buffer-local 'org-deadline-time-regexp)
4315 (defvar org-deadline-line-regexp nil
4316 "Matches the DEADLINE keyword and the rest of the line.")
4317 (make-variable-buffer-local 'org-deadline-line-regexp)
4318 (defvar org-scheduled-regexp nil
4319 "Matches the SCHEDULED keyword.")
4320 (make-variable-buffer-local 'org-scheduled-regexp)
4321 (defvar org-scheduled-time-regexp nil
4322 "Matches the SCHEDULED keyword together with a time stamp.")
4323 (make-variable-buffer-local 'org-scheduled-time-regexp)
4324 (defvar org-closed-time-regexp nil
4325 "Matches the CLOSED keyword together with a time stamp.")
4326 (make-variable-buffer-local 'org-closed-time-regexp)
4328 (defvar org-keyword-time-regexp nil
4329 "Matches any of the 4 keywords, together with the time stamp.")
4330 (make-variable-buffer-local 'org-keyword-time-regexp)
4331 (defvar org-keyword-time-not-clock-regexp nil
4332 "Matches any of the 3 keywords, together with the time stamp.")
4333 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4334 (defvar org-maybe-keyword-time-regexp nil
4335 "Matches a timestamp, possibly preceded by a keyword.")
4336 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4337 (defvar org-planning-or-clock-line-re nil
4338 "Matches a line with planning or clock info.")
4339 (make-variable-buffer-local 'org-planning-or-clock-line-re)
4340 (defvar org-all-time-keywords nil
4341 "List of time keywords.")
4342 (make-variable-buffer-local 'org-all-time-keywords)
4344 (defconst org-plain-time-of-day-regexp
4345 (concat
4346 "\\(\\<[012]?[0-9]"
4347 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4348 "\\(--?"
4349 "\\(\\<[012]?[0-9]"
4350 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4351 "\\)?")
4352 "Regular expression to match a plain time or time range.
4353 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4354 groups carry important information:
4355 0 the full match
4356 1 the first time, range or not
4357 8 the second time, if it is a range.")
4359 (defconst org-plain-time-extension-regexp
4360 (concat
4361 "\\(\\<[012]?[0-9]"
4362 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4363 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4364 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4365 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4366 groups carry important information:
4367 0 the full match
4368 7 hours of duration
4369 9 minutes of duration")
4371 (defconst org-stamp-time-of-day-regexp
4372 (concat
4373 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4374 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4375 "\\(--?"
4376 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4377 "Regular expression to match a timestamp time or time range.
4378 After a match, the following groups carry important information:
4379 0 the full match
4380 1 date plus weekday, for back referencing to make sure both times are on the same day
4381 2 the first time, range or not
4382 4 the second time, if it is a range.")
4384 (defconst org-startup-options
4385 '(("fold" org-startup-folded t)
4386 ("overview" org-startup-folded t)
4387 ("nofold" org-startup-folded nil)
4388 ("showall" org-startup-folded nil)
4389 ("showeverything" org-startup-folded showeverything)
4390 ("content" org-startup-folded content)
4391 ("indent" org-startup-indented t)
4392 ("noindent" org-startup-indented nil)
4393 ("hidestars" org-hide-leading-stars t)
4394 ("showstars" org-hide-leading-stars nil)
4395 ("odd" org-odd-levels-only t)
4396 ("oddeven" org-odd-levels-only nil)
4397 ("align" org-startup-align-all-tables t)
4398 ("noalign" org-startup-align-all-tables nil)
4399 ("inlineimages" org-startup-with-inline-images t)
4400 ("noinlineimages" org-startup-with-inline-images nil)
4401 ("customtime" org-display-custom-times t)
4402 ("logdone" org-log-done time)
4403 ("lognotedone" org-log-done note)
4404 ("nologdone" org-log-done nil)
4405 ("lognoteclock-out" org-log-note-clock-out t)
4406 ("nolognoteclock-out" org-log-note-clock-out nil)
4407 ("logrepeat" org-log-repeat state)
4408 ("lognoterepeat" org-log-repeat note)
4409 ("nologrepeat" org-log-repeat nil)
4410 ("logreschedule" org-log-reschedule time)
4411 ("lognotereschedule" org-log-reschedule note)
4412 ("nologreschedule" org-log-reschedule nil)
4413 ("logredeadline" org-log-redeadline time)
4414 ("lognoteredeadline" org-log-redeadline note)
4415 ("nologredeadline" org-log-redeadline nil)
4416 ("logrefile" org-log-refile time)
4417 ("lognoterefile" org-log-refile note)
4418 ("nologrefile" org-log-refile nil)
4419 ("fninline" org-footnote-define-inline t)
4420 ("nofninline" org-footnote-define-inline nil)
4421 ("fnlocal" org-footnote-section nil)
4422 ("fnauto" org-footnote-auto-label t)
4423 ("fnprompt" org-footnote-auto-label nil)
4424 ("fnconfirm" org-footnote-auto-label confirm)
4425 ("fnplain" org-footnote-auto-label plain)
4426 ("fnadjust" org-footnote-auto-adjust t)
4427 ("nofnadjust" org-footnote-auto-adjust nil)
4428 ("constcgs" constants-unit-system cgs)
4429 ("constSI" constants-unit-system SI)
4430 ("noptag" org-tag-persistent-alist nil)
4431 ("hideblocks" org-hide-block-startup t)
4432 ("nohideblocks" org-hide-block-startup nil)
4433 ("beamer" org-startup-with-beamer-mode t)
4434 ("entitiespretty" org-pretty-entities t)
4435 ("entitiesplain" org-pretty-entities nil))
4436 "Variable associated with STARTUP options for org-mode.
4437 Each element is a list of three items: The startup options as written
4438 in the #+STARTUP line, the corresponding variable, and the value to
4439 set this variable to if the option is found. An optional forth element PUSH
4440 means to push this value onto the list in the variable.")
4442 (defun org-update-property-plist (key val props)
4443 "Update PROPS with KEY and VAL."
4444 (if (string= "+" (substring key (- (length key) 1)))
4445 (let* ((key (substring key 0 (- (length key) 1)))
4446 (previous (cdr (assoc key props))))
4447 (cons (cons key (concat previous " " val))
4448 (org-remove-if (lambda (p) (string= (car p) key)) props)))
4449 (cons (cons key val) props)))
4451 (defun org-set-regexps-and-options ()
4452 "Precompute regular expressions for current buffer."
4453 (when (eq major-mode 'org-mode)
4454 (org-set-local 'org-todo-kwd-alist nil)
4455 (org-set-local 'org-todo-key-alist nil)
4456 (org-set-local 'org-todo-key-trigger nil)
4457 (org-set-local 'org-todo-keywords-1 nil)
4458 (org-set-local 'org-done-keywords nil)
4459 (org-set-local 'org-todo-heads nil)
4460 (org-set-local 'org-todo-sets nil)
4461 (org-set-local 'org-todo-log-states nil)
4462 (org-set-local 'org-file-properties nil)
4463 (org-set-local 'org-file-tags nil)
4464 (let ((re (org-make-options-regexp
4465 '("CATEGORY" "TODO" "COLUMNS"
4466 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
4467 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE" "LATEX_CLASS"
4468 "OPTIONS")
4469 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4470 (splitre "[ \t]+")
4471 (scripts org-use-sub-superscripts)
4472 kwds kws0 kwsa key log value cat arch tags const links hw dws
4473 tail sep kws1 prio props ftags drawers beamer-p
4474 ext-setup-or-nil setup-contents (start 0))
4475 (save-excursion
4476 (save-restriction
4477 (widen)
4478 (goto-char (point-min))
4479 (while (or (and ext-setup-or-nil
4480 (string-match re ext-setup-or-nil start)
4481 (setq start (match-end 0)))
4482 (and (setq ext-setup-or-nil nil start 0)
4483 (re-search-forward re nil t)))
4484 (setq key (upcase (match-string 1 ext-setup-or-nil))
4485 value (org-match-string-no-properties 2 ext-setup-or-nil))
4486 (if (stringp value) (setq value (org-trim value)))
4487 (cond
4488 ((equal key "CATEGORY")
4489 (setq cat value))
4490 ((member key '("SEQ_TODO" "TODO"))
4491 (push (cons 'sequence (org-split-string value splitre)) kwds))
4492 ((equal key "TYP_TODO")
4493 (push (cons 'type (org-split-string value splitre)) kwds))
4494 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4495 ;; general TODO-like setup
4496 (push (cons (intern (downcase (match-string 1 key)))
4497 (org-split-string value splitre)) kwds))
4498 ((equal key "TAGS")
4499 (setq tags (append tags (if tags '("\\n") nil)
4500 (org-split-string value splitre))))
4501 ((equal key "COLUMNS")
4502 (org-set-local 'org-columns-default-format value))
4503 ((equal key "LINK")
4504 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4505 (push (cons (match-string 1 value)
4506 (org-trim (match-string 2 value)))
4507 links)))
4508 ((equal key "PRIORITIES")
4509 (setq prio (org-split-string value " +")))
4510 ((equal key "PROPERTY")
4511 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4512 (setq props (org-update-property-plist (match-string 1 value)
4513 (match-string 2 value)
4514 props))))
4515 ((equal key "FILETAGS")
4516 (when (string-match "\\S-" value)
4517 (setq ftags
4518 (append
4519 ftags
4520 (apply 'append
4521 (mapcar (lambda (x) (org-split-string x ":"))
4522 (org-split-string value)))))))
4523 ((equal key "DRAWERS")
4524 (setq drawers (org-split-string value splitre)))
4525 ((equal key "CONSTANTS")
4526 (setq const (append const (org-split-string value splitre))))
4527 ((equal key "STARTUP")
4528 (let ((opts (org-split-string value splitre))
4529 l var val)
4530 (while (setq l (pop opts))
4531 (when (setq l (assoc l org-startup-options))
4532 (setq var (nth 1 l) val (nth 2 l))
4533 (if (not (nth 3 l))
4534 (set (make-local-variable var) val)
4535 (if (not (listp (symbol-value var)))
4536 (set (make-local-variable var) nil))
4537 (set (make-local-variable var) (symbol-value var))
4538 (add-to-list var val))))))
4539 ((equal key "ARCHIVE")
4540 (setq arch value)
4541 (remove-text-properties 0 (length arch)
4542 '(face t fontified t) arch))
4543 ((equal key "LATEX_CLASS")
4544 (setq beamer-p (equal value "beamer")))
4545 ((equal key "OPTIONS")
4546 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4547 (setq scripts (read (match-string 2 value)))))
4548 ((equal key "SETUPFILE")
4549 (setq setup-contents (org-file-contents
4550 (expand-file-name
4551 (org-remove-double-quotes value))
4552 'noerror))
4553 (if (not ext-setup-or-nil)
4554 (setq ext-setup-or-nil setup-contents start 0)
4555 (setq ext-setup-or-nil
4556 (concat (substring ext-setup-or-nil 0 start)
4557 "\n" setup-contents "\n"
4558 (substring ext-setup-or-nil start)))))))
4559 ;; search for property blocks
4560 (goto-char (point-min))
4561 (while (re-search-forward org-block-regexp nil t)
4562 (when (equal "PROPERTY" (upcase (match-string 1)))
4563 (setq value (replace-regexp-in-string
4564 "[\n\r]" " " (match-string 4)))
4565 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4566 (setq props (org-update-property-plist (match-string 1 value)
4567 (match-string 2 value)
4568 props)))))))
4569 (org-set-local 'org-use-sub-superscripts scripts)
4570 (when cat
4571 (org-set-local 'org-category (intern cat))
4572 (push (cons "CATEGORY" cat) props))
4573 (when prio
4574 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4575 (setq prio (mapcar 'string-to-char prio))
4576 (org-set-local 'org-highest-priority (nth 0 prio))
4577 (org-set-local 'org-lowest-priority (nth 1 prio))
4578 (org-set-local 'org-default-priority (nth 2 prio)))
4579 (and props (org-set-local 'org-file-properties (nreverse props)))
4580 (and ftags (org-set-local 'org-file-tags
4581 (mapcar 'org-add-prop-inherited ftags)))
4582 (and drawers (org-set-local 'org-drawers drawers))
4583 (and arch (org-set-local 'org-archive-location arch))
4584 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4585 ;; Process the TODO keywords
4586 (unless kwds
4587 ;; Use the global values as if they had been given locally.
4588 (setq kwds (default-value 'org-todo-keywords))
4589 (if (stringp (car kwds))
4590 (setq kwds (list (cons org-todo-interpretation
4591 (default-value 'org-todo-keywords)))))
4592 (setq kwds (reverse kwds)))
4593 (setq kwds (nreverse kwds))
4594 (let (inter kws kw)
4595 (while (setq kws (pop kwds))
4596 (let ((kws (or
4597 (run-hook-with-args-until-success
4598 'org-todo-setup-filter-hook kws)
4599 kws)))
4600 (setq inter (pop kws) sep (member "|" kws)
4601 kws0 (delete "|" (copy-sequence kws))
4602 kwsa nil
4603 kws1 (mapcar
4604 (lambda (x)
4605 ;; 1 2
4606 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4607 (progn
4608 (setq kw (match-string 1 x)
4609 key (and (match-end 2) (match-string 2 x))
4610 log (org-extract-log-state-settings x))
4611 (push (cons kw (and key (string-to-char key))) kwsa)
4612 (and log (push log org-todo-log-states))
4614 (error "Invalid TODO keyword %s" x)))
4615 kws0)
4616 kwsa (if kwsa (append '((:startgroup))
4617 (nreverse kwsa)
4618 '((:endgroup))))
4619 hw (car kws1)
4620 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4621 tail (list inter hw (car dws) (org-last dws))))
4622 (add-to-list 'org-todo-heads hw 'append)
4623 (push kws1 org-todo-sets)
4624 (setq org-done-keywords (append org-done-keywords dws nil))
4625 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4626 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4627 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4628 (setq org-todo-sets (nreverse org-todo-sets)
4629 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4630 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4631 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4632 ;; Process the constants
4633 (when const
4634 (let (e cst)
4635 (while (setq e (pop const))
4636 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4637 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4638 (setq org-table-formula-constants-local cst)))
4640 ;; Process the tags.
4641 (when tags
4642 (let (e tgs)
4643 (while (setq e (pop tags))
4644 (cond
4645 ((equal e "{") (push '(:startgroup) tgs))
4646 ((equal e "}") (push '(:endgroup) tgs))
4647 ((equal e "\\n") (push '(:newline) tgs))
4648 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4649 (push (cons (match-string 1 e)
4650 (string-to-char (match-string 2 e)))
4651 tgs))
4652 (t (push (list e) tgs))))
4653 (org-set-local 'org-tag-alist nil)
4654 (while (setq e (pop tgs))
4655 (or (and (stringp (car e))
4656 (assoc (car e) org-tag-alist))
4657 (push e org-tag-alist)))))
4659 ;; Compute the regular expressions and other local variables.
4660 ;; Using `org-outline-regexp-bol' would complicate them much,
4661 ;; because of the fixed white space at the end of that string.
4662 (if (not org-done-keywords)
4663 (setq org-done-keywords (and org-todo-keywords-1
4664 (list (org-last org-todo-keywords-1)))))
4665 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4666 (length org-scheduled-string)
4667 (length org-clock-string)
4668 (length org-closed-string)))
4669 org-drawer-regexp
4670 (concat "^[ \t]*:\\("
4671 (mapconcat 'regexp-quote org-drawers "\\|")
4672 "\\):[ \t]*$")
4673 org-not-done-keywords
4674 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4675 org-todo-regexp
4676 (concat "\\("
4677 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4678 "\\)")
4679 org-not-done-regexp
4680 (concat "\\("
4681 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4682 "\\)")
4683 org-not-done-heading-regexp
4684 (format org-heading-keyword-regexp-format org-not-done-regexp)
4685 org-todo-line-regexp
4686 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
4687 org-complex-heading-regexp
4688 (concat "^\\(\\*+\\)"
4689 "\\(?: +" org-todo-regexp "\\)?"
4690 "\\(?: +\\(\\[#.\\]\\)\\)?"
4691 "\\(?: +\\(.*?\\)\\)?"
4692 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
4693 "[ \t]*$")
4694 org-complex-heading-regexp-format
4695 (concat "^\\(\\*+\\)"
4696 "\\(?: +" org-todo-regexp "\\)?"
4697 "\\(?: +\\(\\[#.\\]\\)\\)?"
4698 "\\(?: +"
4699 ;; Stats cookies can be sticked to body.
4700 "\\(?:\\[[0-9%%/]+\\] *\\)?"
4701 "\\(%s\\)"
4702 "\\(?: *\\[[0-9%%/]+\\]\\)?"
4703 "\\)"
4704 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
4705 "[ \t]*$")
4706 org-todo-line-tags-regexp
4707 (concat "^\\(\\*+\\)"
4708 "\\(?: +" org-todo-regexp "\\)?"
4709 "\\(?: +\\(.*?\\)\\)?"
4710 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
4711 "[ \t]*$")
4712 org-deadline-regexp (concat "\\<" org-deadline-string)
4713 org-deadline-time-regexp
4714 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4715 org-deadline-line-regexp
4716 (concat "\\<\\(" org-deadline-string "\\).*")
4717 org-scheduled-regexp
4718 (concat "\\<" org-scheduled-string)
4719 org-scheduled-time-regexp
4720 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4721 org-closed-time-regexp
4722 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4723 org-keyword-time-regexp
4724 (concat "\\<\\(" org-scheduled-string
4725 "\\|" org-deadline-string
4726 "\\|" org-closed-string
4727 "\\|" org-clock-string "\\)"
4728 " *[[<]\\([^]>]+\\)[]>]")
4729 org-keyword-time-not-clock-regexp
4730 (concat "\\<\\(" org-scheduled-string
4731 "\\|" org-deadline-string
4732 "\\|" org-closed-string
4733 "\\)"
4734 " *[[<]\\([^]>]+\\)[]>]")
4735 org-maybe-keyword-time-regexp
4736 (concat "\\(\\<\\(" org-scheduled-string
4737 "\\|" org-deadline-string
4738 "\\|" org-closed-string
4739 "\\|" org-clock-string "\\)\\)?"
4740 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4741 org-planning-or-clock-line-re
4742 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
4743 "\\|" org-deadline-string
4744 "\\|" org-closed-string "\\|" org-clock-string
4745 "\\)\\>\\)")
4746 org-all-time-keywords
4747 (mapcar (lambda (w) (substring w 0 -1))
4748 (list org-scheduled-string org-deadline-string
4749 org-clock-string org-closed-string))
4751 (org-compute-latex-and-specials-regexp)
4752 (org-set-font-lock-defaults))))
4754 (defun org-file-contents (file &optional noerror)
4755 "Return the contents of FILE, as a string."
4756 (if (or (not file)
4757 (not (file-readable-p file)))
4758 (if noerror
4759 (progn
4760 (message "Cannot read file \"%s\"" file)
4761 (ding) (sit-for 2)
4763 (error "Cannot read file \"%s\"" file))
4764 (with-temp-buffer
4765 (insert-file-contents file)
4766 (buffer-string))))
4768 (defun org-extract-log-state-settings (x)
4769 "Extract the log state setting from a TODO keyword string.
4770 This will extract info from a string like \"WAIT(w@/!)\"."
4771 (let (kw key log1 log2)
4772 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4773 (setq kw (match-string 1 x)
4774 key (and (match-end 2) (match-string 2 x))
4775 log1 (and (match-end 3) (match-string 3 x))
4776 log2 (and (match-end 4) (match-string 4 x)))
4777 (and (or log1 log2)
4778 (list kw
4779 (and log1 (if (equal log1 "!") 'time 'note))
4780 (and log2 (if (equal log2 "!") 'time 'note)))))))
4782 (defun org-remove-keyword-keys (list)
4783 "Remove a pair of parenthesis at the end of each string in LIST."
4784 (mapcar (lambda (x)
4785 (if (string-match "(.*)$" x)
4786 (substring x 0 (match-beginning 0))
4788 list))
4790 (defun org-assign-fast-keys (alist)
4791 "Assign fast keys to a keyword-key alist.
4792 Respect keys that are already there."
4793 (let (new e (alt ?0))
4794 (while (setq e (pop alist))
4795 (if (or (memq (car e) '(:newline :endgroup :startgroup))
4796 (cdr e)) ;; Key already assigned.
4797 (push e new)
4798 (let ((clist (string-to-list (downcase (car e))))
4799 (used (append new alist)))
4800 (when (= (car clist) ?@)
4801 (pop clist))
4802 (while (and clist (rassoc (car clist) used))
4803 (pop clist))
4804 (unless clist
4805 (while (rassoc alt used)
4806 (incf alt)))
4807 (push (cons (car e) (or (car clist) alt)) new))))
4808 (nreverse new)))
4810 ;;; Some variables used in various places
4812 (defvar org-window-configuration nil
4813 "Used in various places to store a window configuration.")
4814 (defvar org-selected-window nil
4815 "Used in various places to store a window configuration.")
4816 (defvar org-finish-function nil
4817 "Function to be called when `C-c C-c' is used.
4818 This is for getting out of special buffers like remember.")
4821 ;; FIXME: Occasionally check by commenting these, to make sure
4822 ;; no other functions uses these, forgetting to let-bind them.
4823 (defvar entry)
4824 (defvar last-state)
4825 (defvar date)
4827 ;; Defined somewhere in this file, but used before definition.
4828 (defvar org-entities) ;; defined in org-entities.el
4829 (defvar org-struct-menu)
4830 (defvar org-org-menu)
4831 (defvar org-tbl-menu)
4833 ;;;; Define the Org-mode
4835 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4836 (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"))
4839 ;; We use a before-change function to check if a table might need
4840 ;; an update.
4841 (defvar org-table-may-need-update t
4842 "Indicates that a table might need an update.
4843 This variable is set by `org-before-change-function'.
4844 `org-table-align' sets it back to nil.")
4845 (defun org-before-change-function (beg end)
4846 "Every change indicates that a table might need an update."
4847 (setq org-table-may-need-update t))
4848 (defvar org-mode-map)
4849 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4850 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
4851 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4852 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
4853 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
4854 (defvar org-table-buffer-is-an nil)
4856 ;; `org-outline-regexp' ought to be a defconst but is let-binding in
4857 ;; some places -- e.g. see the macro org-with-limited-levels.
4859 ;; In Org buffers, the value of `outline-regexp' is that of
4860 ;; `org-outline-regexp'. The only function still directly relying on
4861 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
4862 ;; job when `orgstruct-mode' is active.
4863 (defvar org-outline-regexp "\\*+ "
4864 "Regexp to match Org headlines.")
4865 (defconst org-outline-regexp-bol "^\\*+ "
4866 "Regexp to match Org headlines.
4867 This is similar to `org-outline-regexp' but additionally makes
4868 sure that we are at the beginning of the line.")
4870 (defconst org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4871 "Matches an headline, putting stars and text into groups.
4872 Stars are put in group 1 and the trimmed body in group 2.")
4873 (defconst org-heading-keyword-regexp-format
4874 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4875 "Printf format for a regexp matching an headline with some keyword.
4876 This regexp will match the headline of any node which has the
4877 exact keyword that is put into the format. The keyword isn't in
4878 any group by default, but the stars and the body are.")
4879 (defconst org-heading-keyword-maybe-regexp-format
4880 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4881 "Printf format for a regexp matching an headline, possibly with some keyword.
4882 This regexp can match any headline with the specified keyword, or
4883 without a keyword. The keyword isn't in any group by default,
4884 but the stars and the body are.")
4886 ;;;###autoload
4887 (define-derived-mode org-mode outline-mode "Org"
4888 "Outline-based notes management and organizer, alias
4889 \"Carsten's outline-mode for keeping track of everything.\"
4891 Org-mode develops organizational tasks around a NOTES file which
4892 contains information about projects as plain text. Org-mode is
4893 implemented on top of outline-mode, which is ideal to keep the content
4894 of large files well structured. It supports ToDo items, deadlines and
4895 time stamps, which magically appear in the diary listing of the Emacs
4896 calendar. Tables are easily created with a built-in table editor.
4897 Plain text URL-like links connect to websites, emails (VM), Usenet
4898 messages (Gnus), BBDB entries, and any files related to the project.
4899 For printing and sharing of notes, an Org-mode file (or a part of it)
4900 can be exported as a structured ASCII or HTML file.
4902 The following commands are available:
4904 \\{org-mode-map}"
4906 ;; Get rid of Outline menus, they are not needed
4907 ;; Need to do this here because define-derived-mode sets up
4908 ;; the keymap so late. Still, it is a waste to call this each time
4909 ;; we switch another buffer into org-mode.
4910 (if (featurep 'xemacs)
4911 (when (boundp 'outline-mode-menu-heading)
4912 ;; Assume this is Greg's port, it uses easymenu
4913 (easy-menu-remove outline-mode-menu-heading)
4914 (easy-menu-remove outline-mode-menu-show)
4915 (easy-menu-remove outline-mode-menu-hide))
4916 (define-key org-mode-map [menu-bar headings] 'undefined)
4917 (define-key org-mode-map [menu-bar hide] 'undefined)
4918 (define-key org-mode-map [menu-bar show] 'undefined))
4920 (org-load-modules-maybe)
4921 (easy-menu-add org-org-menu)
4922 (easy-menu-add org-tbl-menu)
4923 (org-install-agenda-files-menu)
4924 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
4925 (add-to-invisibility-spec '(org-cwidth))
4926 (add-to-invisibility-spec '(org-hide-block . t))
4927 (when (featurep 'xemacs)
4928 (org-set-local 'line-move-ignore-invisible t))
4929 (org-set-local 'outline-regexp org-outline-regexp)
4930 (org-set-local 'outline-level 'org-outline-level)
4931 (setq bidi-paragraph-direction 'left-to-right)
4932 (when (and org-ellipsis
4933 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
4934 (fboundp 'make-glyph-code))
4935 (unless org-display-table
4936 (setq org-display-table (make-display-table)))
4937 (set-display-table-slot
4938 org-display-table 4
4939 (vconcat (mapcar
4940 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
4941 org-ellipsis)))
4942 (if (stringp org-ellipsis) org-ellipsis "..."))))
4943 (setq buffer-display-table org-display-table))
4944 (org-set-regexps-and-options)
4945 (when (and org-tag-faces (not org-tags-special-faces-re))
4946 ;; tag faces set outside customize.... force initialization.
4947 (org-set-tag-faces 'org-tag-faces org-tag-faces))
4948 ;; Calc embedded
4949 (org-set-local 'calc-embedded-open-mode "# ")
4950 (modify-syntax-entry ?@ "w")
4951 (if org-startup-truncated (setq truncate-lines t))
4952 (org-set-local 'font-lock-unfontify-region-function
4953 'org-unfontify-region)
4954 ;; Activate before-change-function
4955 (org-set-local 'org-table-may-need-update t)
4956 (org-add-hook 'before-change-functions 'org-before-change-function nil
4957 'local)
4958 ;; Check for running clock before killing a buffer
4959 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
4960 ;; Paragraphs and auto-filling
4961 (org-set-autofill-regexps)
4962 (setq indent-line-function 'org-indent-line-function)
4963 (org-update-radio-target-regexp)
4964 ;; Beginning/end of defun
4965 (org-set-local 'beginning-of-defun-function 'org-beginning-of-defun)
4966 (org-set-local 'end-of-defun-function 'org-end-of-defun)
4967 ;; Next error for sparse trees
4968 (org-set-local 'next-error-function 'org-occur-next-match)
4969 ;; Make sure dependence stuff works reliably, even for users who set it
4970 ;; too late :-(
4971 (if org-enforce-todo-dependencies
4972 (add-hook 'org-blocker-hook
4973 'org-block-todo-from-children-or-siblings-or-parent)
4974 (remove-hook 'org-blocker-hook
4975 'org-block-todo-from-children-or-siblings-or-parent))
4976 (if org-enforce-todo-checkbox-dependencies
4977 (add-hook 'org-blocker-hook
4978 'org-block-todo-from-checkboxes)
4979 (remove-hook 'org-blocker-hook
4980 'org-block-todo-from-checkboxes))
4982 ;; Comment characters
4983 (org-set-local 'comment-start "#")
4984 (org-set-local 'comment-padding " ")
4986 ;; Align options lines
4987 (org-set-local
4988 'align-mode-rules-list
4989 '((org-in-buffer-settings
4990 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
4991 (modes . '(org-mode)))))
4993 ;; Imenu
4994 (org-set-local 'imenu-create-index-function
4995 'org-imenu-get-tree)
4997 ;; Make isearch reveal context
4998 (if (or (featurep 'xemacs)
4999 (not (boundp 'outline-isearch-open-invisible-function)))
5000 ;; Emacs 21 and XEmacs make use of the hook
5001 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5002 ;; Emacs 22 deals with this through a special variable
5003 (org-set-local 'outline-isearch-open-invisible-function
5004 (lambda (&rest ignore) (org-show-context 'isearch))))
5006 ;; Turn on org-beamer-mode?
5007 (and org-startup-with-beamer-mode (org-beamer-mode 1))
5009 ;; Setup the pcomplete hooks
5010 (set (make-local-variable 'pcomplete-command-completion-function)
5011 'org-pcomplete-initial)
5012 (set (make-local-variable 'pcomplete-command-name-function)
5013 'org-command-at-point)
5014 (set (make-local-variable 'pcomplete-default-completion-function)
5015 'ignore)
5016 (set (make-local-variable 'pcomplete-parse-arguments-function)
5017 'org-parse-arguments)
5018 (set (make-local-variable 'pcomplete-termination-string) "")
5019 (set (make-local-variable 'face-remapping-alist)
5020 '((default org-default)))
5022 ;; If empty file that did not turn on org-mode automatically, make it to.
5023 (if (and org-insert-mode-line-in-empty-file
5024 (org-called-interactively-p 'any)
5025 (= (point-min) (point-max)))
5026 (insert "# -*- mode: org -*-\n\n"))
5027 (unless org-inhibit-startup
5028 (when org-startup-align-all-tables
5029 (let ((bmp (buffer-modified-p)))
5030 (org-table-map-tables 'org-table-align 'quietly)
5031 (set-buffer-modified-p bmp)))
5032 (when org-startup-with-inline-images
5033 (org-display-inline-images))
5034 (when org-startup-indented
5035 (require 'org-indent)
5036 (org-indent-mode 1))
5037 (unless org-inhibit-startup-visibility-stuff
5038 (org-set-startup-visibility))))
5040 (when (fboundp 'abbrev-table-put)
5041 (abbrev-table-put org-mode-abbrev-table
5042 :parents (list text-mode-abbrev-table)))
5044 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5046 (defun org-current-time ()
5047 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
5048 (if (> (car org-time-stamp-rounding-minutes) 1)
5049 (let ((r (car org-time-stamp-rounding-minutes))
5050 (time (decode-time)))
5051 (apply 'encode-time
5052 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5053 (nthcdr 2 time))))
5054 (current-time)))
5056 (defun org-today ()
5057 "Return today date, considering `org-extend-today-until'."
5058 (time-to-days
5059 (time-subtract (current-time)
5060 (list 0 (* 3600 org-extend-today-until) 0))))
5062 ;;;; Font-Lock stuff, including the activators
5064 (defvar org-mouse-map (make-sparse-keymap))
5065 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5066 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5067 (when org-mouse-1-follows-link
5068 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5069 (when org-tab-follows-link
5070 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5071 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5073 (require 'font-lock)
5075 (defconst org-non-link-chars "]\t\n\r<>")
5076 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5077 "shell" "elisp" "doi" "message"))
5078 (defvar org-link-types-re nil
5079 "Matches a link that has a url-like prefix like \"http:\"")
5080 (defvar org-link-re-with-space nil
5081 "Matches a link with spaces, optional angular brackets around it.")
5082 (defvar org-link-re-with-space2 nil
5083 "Matches a link with spaces, optional angular brackets around it.")
5084 (defvar org-link-re-with-space3 nil
5085 "Matches a link with spaces, only for internal part in bracket links.")
5086 (defvar org-angle-link-re nil
5087 "Matches link with angular brackets, spaces are allowed.")
5088 (defvar org-plain-link-re nil
5089 "Matches plain link, without spaces.")
5090 (defvar org-bracket-link-regexp nil
5091 "Matches a link in double brackets.")
5092 (defvar org-bracket-link-analytic-regexp nil
5093 "Regular expression used to analyze links.
5094 Here is what the match groups contain after a match:
5095 1: http:
5096 2: http
5097 3: path
5098 4: [desc]
5099 5: desc")
5100 (defvar org-bracket-link-analytic-regexp++ nil
5101 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5102 (defvar org-any-link-re nil
5103 "Regular expression matching any link.")
5105 (defcustom org-match-sexp-depth 3
5106 "Number of stacked braces for sub/superscript matching.
5107 This has to be set before loading org.el to be effective."
5108 :group 'org-export-translation ; ??????????????????????????/
5109 :type 'integer)
5111 (defun org-create-multibrace-regexp (left right n)
5112 "Create a regular expression which will match a balanced sexp.
5113 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5114 as single character strings.
5115 The regexp returned will match the entire expression including the
5116 delimiters. It will also define a single group which contains the
5117 match except for the outermost delimiters. The maximum depth of
5118 stacked delimiters is N. Escaping delimiters is not possible."
5119 (let* ((nothing (concat "[^" left right "]*?"))
5120 (or "\\|")
5121 (re nothing)
5122 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5123 (while (> n 1)
5124 (setq n (1- n)
5125 re (concat re or next)
5126 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5127 (concat left "\\(" re "\\)" right)))
5129 (defvar org-match-substring-regexp
5130 (concat
5131 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5132 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5133 "\\|"
5134 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5135 "\\|"
5136 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5137 "The regular expression matching a sub- or superscript.")
5139 (defvar org-match-substring-with-braces-regexp
5140 (concat
5141 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5142 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5143 "\\)")
5144 "The regular expression matching a sub- or superscript, forcing braces.")
5146 (defun org-make-link-regexps ()
5147 "Update the link regular expressions.
5148 This should be called after the variable `org-link-types' has changed."
5149 (setq org-link-types-re
5150 (concat
5151 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5152 org-link-re-with-space
5153 (concat
5154 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5155 "\\([^" org-non-link-chars " ]"
5156 "[^" org-non-link-chars "]*"
5157 "[^" org-non-link-chars " ]\\)>?")
5158 org-link-re-with-space2
5159 (concat
5160 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5161 "\\([^" org-non-link-chars " ]"
5162 "[^\t\n\r]*"
5163 "[^" org-non-link-chars " ]\\)>?")
5164 org-link-re-with-space3
5165 (concat
5166 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5167 "\\([^" org-non-link-chars " ]"
5168 "[^\t\n\r]*\\)")
5169 org-angle-link-re
5170 (concat
5171 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5172 "\\([^" org-non-link-chars " ]"
5173 "[^" org-non-link-chars "]*"
5174 "\\)>")
5175 org-plain-link-re
5176 (concat
5177 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5178 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5179 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5180 org-bracket-link-regexp
5181 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5182 org-bracket-link-analytic-regexp
5183 (concat
5184 "\\[\\["
5185 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5186 "\\([^]]+\\)"
5187 "\\]"
5188 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5189 "\\]")
5190 org-bracket-link-analytic-regexp++
5191 (concat
5192 "\\[\\["
5193 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5194 "\\([^]]+\\)"
5195 "\\]"
5196 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5197 "\\]")
5198 org-any-link-re
5199 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5200 org-angle-link-re "\\)\\|\\("
5201 org-plain-link-re "\\)")))
5203 (org-make-link-regexps)
5205 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5206 "Regular expression for fast time stamp matching.")
5207 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5208 "Regular expression for fast time stamp matching.")
5209 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5210 "Regular expression matching time strings for analysis.
5211 This one does not require the space after the date, so it can be used
5212 on a string that terminates immediately after the date.")
5213 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5214 "Regular expression matching time strings for analysis.")
5215 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5216 "Regular expression matching time stamps, with groups.")
5217 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5218 "Regular expression matching time stamps (also [..]), with groups.")
5219 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5220 "Regular expression matching a time stamp range.")
5221 (defconst org-tr-regexp-both
5222 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5223 "Regular expression matching a time stamp range.")
5224 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5225 org-ts-regexp "\\)?")
5226 "Regular expression matching a time stamp or time stamp range.")
5227 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5228 org-ts-regexp-both "\\)?")
5229 "Regular expression matching a time stamp or time stamp range.
5230 The time stamps may be either active or inactive.")
5232 (defvar org-emph-face nil)
5234 (defun org-do-emphasis-faces (limit)
5235 "Run through the buffer and add overlays to emphasised strings."
5236 (let (rtn a)
5237 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5238 (if (not (= (char-after (match-beginning 3))
5239 (char-after (match-beginning 4))))
5240 (progn
5241 (setq rtn t)
5242 (setq a (assoc (match-string 3) org-emphasis-alist))
5243 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5244 'face
5245 (nth 1 a))
5246 (and (nth 4 a)
5247 (org-remove-flyspell-overlays-in
5248 (match-beginning 0) (match-end 0)))
5249 (add-text-properties (match-beginning 2) (match-end 2)
5250 '(font-lock-multiline t org-emphasis t))
5251 (when org-hide-emphasis-markers
5252 (add-text-properties (match-end 4) (match-beginning 5)
5253 '(invisible org-link))
5254 (add-text-properties (match-beginning 3) (match-end 3)
5255 '(invisible org-link)))))
5256 (backward-char 1))
5257 rtn))
5259 (defun org-emphasize (&optional char)
5260 "Insert or change an emphasis, i.e. a font like bold or italic.
5261 If there is an active region, change that region to a new emphasis.
5262 If there is no region, just insert the marker characters and position
5263 the cursor between them.
5264 CHAR should be either the marker character, or the first character of the
5265 HTML tag associated with that emphasis. If CHAR is a space, the means
5266 to remove the emphasis of the selected region.
5267 If char is not given (for example in an interactive call) it
5268 will be prompted for."
5269 (interactive)
5270 (let ((eal org-emphasis-alist) e det
5271 (erc org-emphasis-regexp-components)
5272 (prompt "")
5273 (string "") beg end move tag c s)
5274 (if (org-region-active-p)
5275 (setq beg (region-beginning) end (region-end)
5276 string (buffer-substring beg end))
5277 (setq move t))
5279 (while (setq e (pop eal))
5280 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5281 c (aref tag 0))
5282 (push (cons c (string-to-char (car e))) det)
5283 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5284 (substring tag 1)))))
5285 (setq det (nreverse det))
5286 (unless char
5287 (message "%s" (concat "Emphasis marker or tag:" prompt))
5288 (setq char (read-char-exclusive)))
5289 (setq char (or (cdr (assoc char det)) char))
5290 (if (equal char ?\ )
5291 (setq s "" move nil)
5292 (unless (assoc (char-to-string char) org-emphasis-alist)
5293 (error "No such emphasis marker: \"%c\"" char))
5294 (setq s (char-to-string char)))
5295 (while (and (> (length string) 1)
5296 (equal (substring string 0 1) (substring string -1))
5297 (assoc (substring string 0 1) org-emphasis-alist))
5298 (setq string (substring string 1 -1)))
5299 (setq string (concat s string s))
5300 (if beg (delete-region beg end))
5301 (unless (or (bolp)
5302 (string-match (concat "[" (nth 0 erc) "\n]")
5303 (char-to-string (char-before (point)))))
5304 (insert " "))
5305 (unless (or (eobp)
5306 (string-match (concat "[" (nth 1 erc) "\n]")
5307 (char-to-string (char-after (point)))))
5308 (insert " ") (backward-char 1))
5309 (insert string)
5310 (and move (backward-char 1))))
5312 (defconst org-nonsticky-props
5313 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
5315 (defsubst org-rear-nonsticky-at (pos)
5316 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5318 (defun org-activate-plain-links (limit)
5319 "Run through the buffer and add overlays to links."
5320 (catch 'exit
5321 (let (f)
5322 (if (re-search-forward org-plain-link-re limit t)
5323 (progn
5324 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5325 (setq f (get-text-property (match-beginning 0) 'face))
5326 (if (or (eq f 'org-tag)
5327 (and (listp f) (memq 'org-tag f)))
5329 (add-text-properties (match-beginning 0) (match-end 0)
5330 (list 'mouse-face 'highlight
5331 'face 'org-link
5332 'keymap org-mouse-map))
5333 (org-rear-nonsticky-at (match-end 0)))
5334 t)))))
5336 (defun org-activate-code (limit)
5337 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5338 (progn
5339 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5340 (remove-text-properties (match-beginning 0) (match-end 0)
5341 '(display t invisible t intangible t))
5342 t)))
5344 (defcustom org-src-fontify-natively nil
5345 "When non-nil, fontify code in code blocks."
5346 :type 'boolean
5347 :group 'org-appearance
5348 :group 'org-babel)
5350 (defun org-fontify-meta-lines-and-blocks (limit)
5351 (condition-case nil
5352 (org-fontify-meta-lines-and-blocks-1 limit)
5353 (error (message "org-mode fontification error"))))
5355 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5356 "Fontify #+ lines and blocks, in the correct ways."
5357 (let ((case-fold-search t))
5358 (if (re-search-forward
5359 "^\\([ \t]*#\\+\\(\\([a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5360 limit t)
5361 (let ((beg (match-beginning 0))
5362 (block-start (match-end 0))
5363 (block-end nil)
5364 (lang (match-string 7))
5365 (beg1 (line-beginning-position 2))
5366 (dc1 (downcase (match-string 2)))
5367 (dc3 (downcase (match-string 3)))
5368 end end1 quoting block-type ovl)
5369 (cond
5370 ((member dc1 '("html:" "ascii:" "latex:" "docbook:"))
5371 ;; a single line of backend-specific content
5372 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5373 (remove-text-properties (match-beginning 0) (match-end 0)
5374 '(display t invisible t intangible t))
5375 (add-text-properties (match-beginning 1) (match-end 3)
5376 '(font-lock-fontified t face org-meta-line))
5377 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5378 '(font-lock-fontified t face org-block))
5379 ; for backend-specific code
5381 ((and (match-end 4) (equal dc3 "begin"))
5382 ;; Truly a block
5383 (setq block-type (downcase (match-string 5))
5384 quoting (member block-type org-protecting-blocks))
5385 (when (re-search-forward
5386 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5387 nil t) ;; on purpose, we look further than LIMIT
5388 (setq end (match-end 0) end1 (1- (match-beginning 0)))
5389 (setq block-end (match-beginning 0))
5390 (when quoting
5391 (remove-text-properties beg end
5392 '(display t invisible t intangible t)))
5393 (add-text-properties
5394 beg end
5395 '(font-lock-fontified t font-lock-multiline t))
5396 (add-text-properties beg beg1 '(face org-meta-line))
5397 (add-text-properties end1 (min (point-max) (1+ end))
5398 '(face org-meta-line)) ; for end_src
5399 (cond
5400 ((and lang (not (string= lang "")) org-src-fontify-natively)
5401 (org-src-font-lock-fontify-block lang block-start block-end)
5402 ;; remove old background overlays
5403 (mapc (lambda (ov)
5404 (if (eq (overlay-get ov 'face) 'org-block-background)
5405 (delete-overlay ov)))
5406 (overlays-at (/ (+ beg1 block-end) 2)))
5407 ;; add a background overlay
5408 (setq ovl (make-overlay beg1 block-end))
5409 (overlay-put ovl 'face 'org-block-background)
5410 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5411 (quoting
5412 (add-text-properties beg1 (min (point-max) (1+ end1))
5413 '(face org-block))) ; end of source block
5414 ((not org-fontify-quote-and-verse-blocks))
5415 ((string= block-type "quote")
5416 (add-text-properties beg1 (1+ end1) '(face org-quote)))
5417 ((string= block-type "verse")
5418 (add-text-properties beg1 (1+ end1) '(face org-verse))))
5419 (add-text-properties beg beg1 '(face org-block-begin-line))
5420 (add-text-properties (1+ end) (1+ end1) '(face org-block-end-line))
5422 ((member dc1 '("title:" "author:" "email:" "date:"))
5423 (add-text-properties
5424 beg (match-end 3)
5425 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5426 '(font-lock-fontified t invisible t)
5427 '(font-lock-fontified t face org-document-info-keyword)))
5428 (add-text-properties
5429 (match-beginning 6) (match-end 6)
5430 (if (string-equal dc1 "title:")
5431 '(font-lock-fontified t face org-document-title)
5432 '(font-lock-fontified t face org-document-info))))
5433 ((not (member (char-after beg) '(?\ ?\t)))
5434 ;; just any other in-buffer setting, but not indented
5435 (add-text-properties
5436 beg (1+ (match-end 0))
5437 '(font-lock-fontified t face org-meta-line))
5439 ((or (member dc1 '("begin:" "end:" "caption:" "label:"
5440 "orgtbl:" "tblfm:" "tblname:" "results:"
5441 "call:" "header:" "headers:" "name:"))
5442 (and (match-end 4) (equal dc3 "attr")))
5443 (add-text-properties
5444 beg (match-end 0)
5445 '(font-lock-fontified t face org-meta-line))
5447 ((member dc3 '(" " ""))
5448 (add-text-properties
5449 beg (match-end 0)
5450 '(font-lock-fontified t face font-lock-comment-face)))
5451 (t nil))))))
5453 (defun org-activate-angle-links (limit)
5454 "Run through the buffer and add overlays to links."
5455 (if (re-search-forward org-angle-link-re limit t)
5456 (progn
5457 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5458 (add-text-properties (match-beginning 0) (match-end 0)
5459 (list 'mouse-face 'highlight
5460 'keymap org-mouse-map))
5461 (org-rear-nonsticky-at (match-end 0))
5462 t)))
5464 (defun org-activate-footnote-links (limit)
5465 "Run through the buffer and add overlays to footnotes."
5466 (let ((fn (org-footnote-next-reference-or-definition limit)))
5467 (when fn
5468 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5469 (org-remove-flyspell-overlays-in beg end)
5470 (add-text-properties beg end
5471 (list 'mouse-face 'highlight
5472 'keymap org-mouse-map
5473 'help-echo
5474 (if (= (point-at-bol) beg)
5475 "Footnote definition"
5476 "Footnote reference")
5477 'font-lock-fontified t
5478 'font-lock-multiline t
5479 'face 'org-footnote))))))
5481 (defun org-activate-bracket-links (limit)
5482 "Run through the buffer and add overlays to bracketed links."
5483 (if (re-search-forward org-bracket-link-regexp limit t)
5484 (let* ((help (concat "LINK: "
5485 (org-match-string-no-properties 1)))
5486 ;; FIXME: above we should remove the escapes.
5487 ;; but that requires another match, protecting match data,
5488 ;; a lot of overhead for font-lock.
5489 (ip (org-maybe-intangible
5490 (list 'invisible 'org-link
5491 'keymap org-mouse-map 'mouse-face 'highlight
5492 'font-lock-multiline t 'help-echo help)))
5493 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5494 'font-lock-multiline t 'help-echo help)))
5495 ;; We need to remove the invisible property here. Table narrowing
5496 ;; may have made some of this invisible.
5497 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5498 (remove-text-properties (match-beginning 0) (match-end 0)
5499 '(invisible nil))
5500 (if (match-end 3)
5501 (progn
5502 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5503 (org-rear-nonsticky-at (match-beginning 3))
5504 (add-text-properties (match-beginning 3) (match-end 3) vp)
5505 (org-rear-nonsticky-at (match-end 3))
5506 (add-text-properties (match-end 3) (match-end 0) ip)
5507 (org-rear-nonsticky-at (match-end 0)))
5508 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5509 (org-rear-nonsticky-at (match-beginning 1))
5510 (add-text-properties (match-beginning 1) (match-end 1) vp)
5511 (org-rear-nonsticky-at (match-end 1))
5512 (add-text-properties (match-end 1) (match-end 0) ip)
5513 (org-rear-nonsticky-at (match-end 0)))
5514 t)))
5516 (defun org-activate-dates (limit)
5517 "Run through the buffer and add overlays to dates."
5518 (if (re-search-forward org-tsr-regexp-both limit t)
5519 (progn
5520 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5521 (add-text-properties (match-beginning 0) (match-end 0)
5522 (list 'mouse-face 'highlight
5523 'keymap org-mouse-map))
5524 (org-rear-nonsticky-at (match-end 0))
5525 (when org-display-custom-times
5526 (if (match-end 3)
5527 (org-display-custom-time (match-beginning 3) (match-end 3)))
5528 (org-display-custom-time (match-beginning 1) (match-end 1)))
5529 t)))
5531 (defvar org-target-link-regexp nil
5532 "Regular expression matching radio targets in plain text.")
5533 (make-variable-buffer-local 'org-target-link-regexp)
5534 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5535 "Regular expression matching a link target.")
5536 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5537 "Regular expression matching a radio target.")
5538 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5539 "Regular expression matching any target.")
5541 (defun org-activate-target-links (limit)
5542 "Run through the buffer and add overlays to target matches."
5543 (when org-target-link-regexp
5544 (let ((case-fold-search t))
5545 (if (re-search-forward org-target-link-regexp limit t)
5546 (progn
5547 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5548 (add-text-properties (match-beginning 0) (match-end 0)
5549 (list 'mouse-face 'highlight
5550 'keymap org-mouse-map
5551 'help-echo "Radio target link"
5552 'org-linked-text t))
5553 (org-rear-nonsticky-at (match-end 0))
5554 t)))))
5556 (defun org-update-radio-target-regexp ()
5557 "Find all radio targets in this file and update the regular expression."
5558 (interactive)
5559 (when (memq 'radio org-activate-links)
5560 (setq org-target-link-regexp
5561 (org-make-target-link-regexp (org-all-targets 'radio)))
5562 (org-restart-font-lock)))
5564 (defun org-hide-wide-columns (limit)
5565 (let (s e)
5566 (setq s (text-property-any (point) (or limit (point-max))
5567 'org-cwidth t))
5568 (when s
5569 (setq e (next-single-property-change s 'org-cwidth))
5570 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5571 (goto-char e)
5572 t)))
5574 (defvar org-latex-and-specials-regexp nil
5575 "Regular expression for highlighting export special stuff.")
5576 (defvar org-match-substring-regexp)
5577 (defvar org-match-substring-with-braces-regexp)
5579 ;; This should be with the exporter code, but we also use if for font-locking
5580 (defconst org-export-html-special-string-regexps
5581 '(("\\\\-" . "&shy;")
5582 ("---\\([^-]\\)" . "&mdash;\\1")
5583 ("--\\([^-]\\)" . "&ndash;\\1")
5584 ("\\.\\.\\." . "&hellip;"))
5585 "Regular expressions for special string conversion.")
5588 (defun org-compute-latex-and-specials-regexp ()
5589 "Compute regular expression for stuff treated specially by exporters."
5590 (if (not org-highlight-latex-fragments-and-specials)
5591 (org-set-local 'org-latex-and-specials-regexp nil)
5592 (require 'org-exp)
5593 (let*
5594 ((matchers (plist-get org-format-latex-options :matchers))
5595 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5596 org-latex-regexps)))
5597 (org-export-allow-BIND nil)
5598 (options (org-combine-plists (org-default-export-plist)
5599 (org-infile-export-plist)))
5600 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5601 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5602 (org-export-with-TeX-macros (plist-get options :TeX-macros))
5603 (org-export-html-expand (plist-get options :expand-quoted-html))
5604 (org-export-with-special-strings (plist-get options :special-strings))
5605 (re-sub
5606 (cond
5607 ((equal org-export-with-sub-superscripts '{})
5608 (list org-match-substring-with-braces-regexp))
5609 (org-export-with-sub-superscripts
5610 (list org-match-substring-regexp))
5611 (t nil)))
5612 (re-latex
5613 (if org-export-with-LaTeX-fragments
5614 (mapcar (lambda (x) (nth 1 x)) latexs)))
5615 (re-macros
5616 (if org-export-with-TeX-macros
5617 (list (concat "\\\\"
5618 (regexp-opt
5619 (append
5621 (delq nil
5622 (mapcar 'car-safe
5623 (append org-entities-user
5624 org-entities)))
5625 (if (boundp 'org-latex-entities)
5626 (mapcar (lambda (x)
5627 (or (car-safe x) x))
5628 org-latex-entities)
5629 nil))
5630 'words))) ; FIXME
5632 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5633 (re-special (if org-export-with-special-strings
5634 (mapcar (lambda (x) (car x))
5635 org-export-html-special-string-regexps)))
5636 (re-rest
5637 (delq nil
5638 (list
5639 (if org-export-html-expand "@<[^>\n]+>")
5640 ))))
5641 (org-set-local
5642 'org-latex-and-specials-regexp
5643 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5644 re-rest) "\\|")))))
5646 (defun org-do-latex-and-special-faces (limit)
5647 "Run through the buffer and add overlays to links."
5648 (when org-latex-and-specials-regexp
5649 (let (rtn d)
5650 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5651 limit t))
5652 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5653 'face))
5654 '(org-code org-verbatim underline)))
5655 (progn
5656 (setq rtn t
5657 d (cond ((member (char-after (1+ (match-beginning 0)))
5658 '(?_ ?^)) 1)
5659 (t 0)))
5660 (font-lock-prepend-text-property
5661 (+ d (match-beginning 0)) (match-end 0)
5662 'face 'org-latex-and-export-specials)
5663 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5664 '(font-lock-multiline t)))))
5665 rtn)))
5667 (defun org-restart-font-lock ()
5668 "Restart `font-lock-mode', to force refontification."
5669 (when (and (boundp 'font-lock-mode) font-lock-mode)
5670 (font-lock-mode -1)
5671 (font-lock-mode 1)))
5673 (defun org-all-targets (&optional radio)
5674 "Return a list of all targets in this file.
5675 With optional argument RADIO, only find radio targets."
5676 (let ((re (if radio org-radio-target-regexp org-target-regexp))
5677 rtn)
5678 (save-excursion
5679 (goto-char (point-min))
5680 (while (re-search-forward re nil t)
5681 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
5682 rtn)))
5684 (defun org-make-target-link-regexp (targets)
5685 "Make regular expression matching all strings in TARGETS.
5686 The regular expression finds the targets also if there is a line break
5687 between words."
5688 (and targets
5689 (concat
5690 "\\<\\("
5691 (mapconcat
5692 (lambda (x)
5693 (setq x (regexp-quote x))
5694 (while (string-match " +" x)
5695 (setq x (replace-match "\\s-+" t t x)))
5697 targets
5698 "\\|")
5699 "\\)\\>")))
5701 (defun org-activate-tags (limit)
5702 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
5703 (progn
5704 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5705 (add-text-properties (match-beginning 1) (match-end 1)
5706 (list 'mouse-face 'highlight
5707 'keymap org-mouse-map))
5708 (org-rear-nonsticky-at (match-end 1))
5709 t)))
5711 (defun org-outline-level ()
5712 "Compute the outline level of the heading at point.
5713 This function assumes that the cursor is at the beginning of a line matched
5714 by `outline-regexp'. Otherwise it returns garbage.
5715 If this is called at a normal headline, the level is the number of stars.
5716 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
5717 (save-excursion
5718 (looking-at org-outline-regexp)
5719 (1- (- (match-end 0) (match-beginning 0)))))
5721 (defvar org-font-lock-keywords nil)
5723 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
5724 "Regular expression matching a property line.")
5726 (defvar org-font-lock-hook nil
5727 "Functions to be called for special font lock stuff.")
5729 (defvar org-font-lock-set-keywords-hook nil
5730 "Functions that can manipulate `org-font-lock-extra-keywords'.
5731 This is calles after `org-font-lock-extra-keywords' is defined, but before
5732 it is installed to be used by font lock. This can be useful if something
5733 needs to be inserted at a specific position in the font-lock sequence.")
5735 (defun org-font-lock-hook (limit)
5736 (run-hook-with-args 'org-font-lock-hook limit))
5738 (defun org-set-font-lock-defaults ()
5739 (let* ((em org-fontify-emphasized-text)
5740 (lk org-activate-links)
5741 (org-font-lock-extra-keywords
5742 (list
5743 ;; Call the hook
5744 '(org-font-lock-hook)
5745 ;; Headlines
5746 `(,(if org-fontify-whole-heading-line
5747 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
5748 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
5749 (1 (org-get-level-face 1))
5750 (2 (org-get-level-face 2))
5751 (3 (org-get-level-face 3)))
5752 ;; Table lines
5753 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5754 (1 'org-table t))
5755 ;; Table internals
5756 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5757 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5758 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5759 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
5760 ;; Drawers
5761 (list org-drawer-regexp '(0 'org-special-keyword t))
5762 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5763 ;; Properties
5764 (list org-property-re
5765 '(1 'org-special-keyword t)
5766 '(3 'org-property-value t))
5767 ;; Links
5768 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5769 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5770 (if (memq 'plain lk) '(org-activate-plain-links))
5771 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5772 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5773 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5774 (if (memq 'footnote lk) '(org-activate-footnote-links))
5775 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5776 '(org-hide-wide-columns (0 nil append))
5777 ;; TODO keyword
5778 (list (format org-heading-keyword-regexp-format
5779 org-todo-regexp)
5780 '(2 (org-get-todo-face 2) t))
5781 ;; DONE
5782 (if org-fontify-done-headline
5783 (list (format org-heading-keyword-regexp-format
5784 (concat
5785 "\\("
5786 (mapconcat 'regexp-quote org-done-keywords "\\|")
5787 "\\)"))
5788 '(2 'org-headline-done t))
5789 nil)
5790 ;; Priorities
5791 '(org-font-lock-add-priority-faces)
5792 ;; Tags
5793 '(org-font-lock-add-tag-faces)
5794 ;; Special keywords
5795 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5796 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5797 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5798 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5799 ;; Emphasis
5800 (if em
5801 (if (featurep 'xemacs)
5802 '(org-do-emphasis-faces (0 nil append))
5803 '(org-do-emphasis-faces)))
5804 ;; Checkboxes
5805 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
5806 1 'org-checkbox prepend)
5807 (if (cdr (assq 'checkbox org-list-automatic-rules))
5808 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5809 (0 (org-get-checkbox-statistics-face) t)))
5810 ;; Description list items
5811 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
5812 1 'bold prepend)
5813 ;; ARCHIVEd headings
5814 (list (concat
5815 org-outline-regexp-bol
5816 "\\(.*:" org-archive-tag ":.*\\)")
5817 '(1 'org-archived prepend))
5818 ;; Specials
5819 '(org-do-latex-and-special-faces)
5820 '(org-fontify-entities)
5821 '(org-raise-scripts)
5822 ;; Code
5823 '(org-activate-code (1 'org-code t))
5824 ;; COMMENT
5825 (list (format org-heading-keyword-regexp-format
5826 (concat "\\("
5827 org-comment-string "\\|" org-quote-string
5828 "\\)"))
5829 '(2 'org-special-keyword t))
5830 '("^#.*" (0 'font-lock-comment-face t))
5831 ;; Blocks and meta lines
5832 '(org-fontify-meta-lines-and-blocks)
5834 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5835 (run-hooks 'org-font-lock-set-keywords-hook)
5836 ;; Now set the full font-lock-keywords
5837 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5838 (org-set-local 'font-lock-defaults
5839 '(org-font-lock-keywords t nil nil backward-paragraph))
5840 (kill-local-variable 'font-lock-keywords) nil))
5842 (defun org-toggle-pretty-entities ()
5843 "Toggle the composition display of entities as UTF8 characters."
5844 (interactive)
5845 (org-set-local 'org-pretty-entities (not org-pretty-entities))
5846 (org-restart-font-lock)
5847 (if org-pretty-entities
5848 (message "Entities are displayed as UTF8 characers")
5849 (save-restriction
5850 (widen)
5851 (org-decompose-region (point-min) (point-max))
5852 (message "Entities are displayed plain"))))
5854 (defun org-fontify-entities (limit)
5855 "Find an entity to fontify."
5856 (let (ee)
5857 (when org-pretty-entities
5858 (catch 'match
5859 (while (re-search-forward
5860 "\\\\\\(frac[13][24]\\|[a-zA-Z]+\\)\\($\\|[^[:alpha:]\n]\\)"
5861 limit t)
5862 (if (and (not (org-in-indented-comment-line))
5863 (setq ee (org-entity-get (match-string 1)))
5864 (= (length (nth 6 ee)) 1))
5865 (progn
5866 (add-text-properties
5867 (match-beginning 0) (match-end 1)
5868 (list 'font-lock-fontified t))
5869 (compose-region (match-beginning 0) (match-end 1)
5870 (nth 6 ee) nil)
5871 (backward-char 1)
5872 (throw 'match t))))
5873 nil))))
5875 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
5876 "Fontify string S like in Org-mode."
5877 (with-temp-buffer
5878 (insert s)
5879 (let ((org-odd-levels-only odd-levels))
5880 (org-mode)
5881 (font-lock-fontify-buffer)
5882 (buffer-string))))
5884 (defvar org-m nil)
5885 (defvar org-l nil)
5886 (defvar org-f nil)
5887 (defun org-get-level-face (n)
5888 "Get the right face for match N in font-lock matching of headlines."
5889 (setq org-l (- (match-end 2) (match-beginning 1) 1))
5890 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
5891 (if org-cycle-level-faces
5892 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
5893 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
5894 (cond
5895 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
5896 ((eq n 2) org-f)
5897 (t (if org-level-color-stars-only nil org-f))))
5900 (defun org-get-todo-face (kwd)
5901 "Get the right face for a TODO keyword KWD.
5902 If KWD is a number, get the corresponding match group."
5903 (if (numberp kwd) (setq kwd (match-string kwd)))
5904 (or (org-face-from-face-or-color
5905 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
5906 (and (member kwd org-done-keywords) 'org-done)
5907 'org-todo))
5909 (defun org-face-from-face-or-color (context inherit face-or-color)
5910 "Create a face list that inherits INHERIT, but sets the foreground color.
5911 When FACE-OR-COLOR is not a string, just return it."
5912 (if (stringp face-or-color)
5913 (list :inherit inherit
5914 (cdr (assoc context org-faces-easy-properties))
5915 face-or-color)
5916 face-or-color))
5918 (defun org-font-lock-add-tag-faces (limit)
5919 "Add the special tag faces."
5920 (when (and org-tag-faces org-tags-special-faces-re)
5921 (while (re-search-forward org-tags-special-faces-re limit t)
5922 (add-text-properties (match-beginning 1) (match-end 1)
5923 (list 'face (org-get-tag-face 1)
5924 'font-lock-fontified t))
5925 (backward-char 1))))
5927 (defun org-font-lock-add-priority-faces (limit)
5928 "Add the special priority faces."
5929 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
5930 (add-text-properties
5931 (match-beginning 0) (match-end 0)
5932 (list 'face (or (org-face-from-face-or-color
5933 'priority 'org-special-keyword
5934 (cdr (assoc (char-after (match-beginning 1))
5935 org-priority-faces)))
5936 'org-special-keyword)
5937 'font-lock-fontified t))))
5939 (defun org-get-tag-face (kwd)
5940 "Get the right face for a TODO keyword KWD.
5941 If KWD is a number, get the corresponding match group."
5942 (if (numberp kwd) (setq kwd (match-string kwd)))
5943 (or (org-face-from-face-or-color
5944 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
5945 'org-tag))
5947 (defun org-unfontify-region (beg end &optional maybe_loudly)
5948 "Remove fontification and activation overlays from links."
5949 (font-lock-default-unfontify-region beg end)
5950 (let* ((buffer-undo-list t)
5951 (inhibit-read-only t) (inhibit-point-motion-hooks t)
5952 (inhibit-modification-hooks t)
5953 deactivate-mark buffer-file-name buffer-file-truename)
5954 (org-decompose-region beg end)
5955 (remove-text-properties beg end
5956 '(mouse-face t keymap t org-linked-text t
5957 invisible t intangible t
5958 org-no-flyspell t org-emphasis t))
5959 (org-remove-font-lock-display-properties beg end)))
5961 (defconst org-script-display '(((raise -0.3) (height 0.7))
5962 ((raise 0.3) (height 0.7))
5963 ((raise -0.5))
5964 ((raise 0.5)))
5965 "Display properties for showing superscripts and subscripts.")
5967 (defun org-remove-font-lock-display-properties (beg end)
5968 "Remove specific display properties that have been added by font lock.
5969 The will remove the raise properties that are used to show superscripts
5970 and subscripts."
5971 (let (next prop)
5972 (while (< beg end)
5973 (setq next (next-single-property-change beg 'display nil end)
5974 prop (get-text-property beg 'display))
5975 (if (member prop org-script-display)
5976 (put-text-property beg next 'display nil))
5977 (setq beg next))))
5979 (defun org-raise-scripts (limit)
5980 "Add raise properties to sub/superscripts."
5981 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
5982 (if (re-search-forward
5983 (if (eq org-use-sub-superscripts t)
5984 org-match-substring-regexp
5985 org-match-substring-with-braces-regexp)
5986 limit t)
5987 (let* ((pos (point)) table-p comment-p
5988 (mpos (match-beginning 3))
5989 (emph-p (get-text-property mpos 'org-emphasis))
5990 (link-p (get-text-property mpos 'mouse-face))
5991 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
5992 (goto-char (point-at-bol))
5993 (setq table-p (org-looking-at-p org-table-dataline-regexp)
5994 comment-p (org-looking-at-p "[ \t]*#"))
5995 (goto-char pos)
5996 ;; FIXME: Should we go back one character here, for a_b^c
5997 ;; (goto-char (1- pos)) ;????????????????????
5998 (if (or comment-p emph-p link-p keyw-p)
6000 (put-text-property (match-beginning 3) (match-end 0)
6001 'display
6002 (if (equal (char-after (match-beginning 2)) ?^)
6003 (nth (if table-p 3 1) org-script-display)
6004 (nth (if table-p 2 0) org-script-display)))
6005 (add-text-properties (match-beginning 2) (match-end 2)
6006 (list 'invisible t
6007 'org-dwidth t 'org-dwidth-n 1))
6008 (if (and (eq (char-after (match-beginning 3)) ?{)
6009 (eq (char-before (match-end 3)) ?}))
6010 (progn
6011 (add-text-properties
6012 (match-beginning 3) (1+ (match-beginning 3))
6013 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6014 (add-text-properties
6015 (1- (match-end 3)) (match-end 3)
6016 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6017 t)))))
6019 ;;;; Visibility cycling, including org-goto and indirect buffer
6021 ;;; Cycling
6023 (defvar org-cycle-global-status nil)
6024 (make-variable-buffer-local 'org-cycle-global-status)
6025 (defvar org-cycle-subtree-status nil)
6026 (make-variable-buffer-local 'org-cycle-subtree-status)
6028 ;;;###autoload
6030 (defvar org-inlinetask-min-level)
6032 (defun org-cycle (&optional arg)
6033 "TAB-action and visibility cycling for Org-mode.
6035 This is the command invoked in Org-mode by the TAB key. Its main purpose
6036 is outline visibility cycling, but it also invokes other actions
6037 in special contexts.
6039 - When this function is called with a prefix argument, rotate the entire
6040 buffer through 3 states (global cycling)
6041 1. OVERVIEW: Show only top-level headlines.
6042 2. CONTENTS: Show all headlines of all levels, but no body text.
6043 3. SHOW ALL: Show everything.
6044 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6045 determined by the variable `org-startup-folded', and by any VISIBILITY
6046 properties in the buffer.
6047 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6048 including any drawers.
6050 - When inside a table, re-align the table and move to the next field.
6052 - When point is at the beginning of a headline, rotate the subtree started
6053 by this line through 3 different states (local cycling)
6054 1. FOLDED: Only the main headline is shown.
6055 2. CHILDREN: The main headline and the direct children are shown.
6056 From this state, you can move to one of the children
6057 and zoom in further.
6058 3. SUBTREE: Show the entire subtree, including body text.
6059 If there is no subtree, switch directly from CHILDREN to FOLDED.
6061 - When point is at the beginning of an empty headline and the variable
6062 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6063 of the headline by demoting and promoting it to likely levels. This
6064 speeds up creation document structure by pressing TAB once or several
6065 times right after creating a new headline.
6067 - When there is a numeric prefix, go up to a heading with level ARG, do
6068 a `show-subtree' and return to the previous cursor position. If ARG
6069 is negative, go up that many levels.
6071 - When point is not at the beginning of a headline, execute the global
6072 binding for TAB, which is re-indenting the line. See the option
6073 `org-cycle-emulate-tab' for details.
6075 - Special case: if point is at the beginning of the buffer and there is
6076 no headline in line 1, this function will act as if called with prefix arg
6077 (C-u TAB, same as S-TAB) also when called without prefix arg.
6078 But only if also the variable `org-cycle-global-at-bob' is t."
6079 (interactive "P")
6080 (org-load-modules-maybe)
6081 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6082 (and org-cycle-level-after-item/entry-creation
6083 (or (org-cycle-level)
6084 (org-cycle-item-indentation))))
6085 (let* ((limit-level
6086 (or org-cycle-max-level
6087 (and (boundp 'org-inlinetask-min-level)
6088 org-inlinetask-min-level
6089 (1- org-inlinetask-min-level))))
6090 (nstars (and limit-level
6091 (if org-odd-levels-only
6092 (and limit-level (1- (* limit-level 2)))
6093 limit-level)))
6094 (org-outline-regexp
6095 (if (not (eq major-mode 'org-mode))
6096 outline-regexp
6097 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6098 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6099 (not (looking-at org-outline-regexp))))
6100 (org-cycle-hook
6101 (if bob-special
6102 (delq 'org-optimize-window-after-visibility-change
6103 (copy-sequence org-cycle-hook))
6104 org-cycle-hook))
6105 (pos (point)))
6107 (if (or bob-special (equal arg '(4)))
6108 ;; special case: use global cycling
6109 (setq arg t))
6111 (cond
6113 ((equal arg '(16))
6114 (setq last-command 'dummy)
6115 (org-set-startup-visibility)
6116 (message "Startup visibility, plus VISIBILITY properties"))
6118 ((equal arg '(64))
6119 (show-all)
6120 (message "Entire buffer visible, including drawers"))
6122 ;; Table: enter it or move to the next field.
6123 ((org-at-table-p 'any)
6124 (if (org-at-table.el-p)
6125 (message "Use C-c ' to edit table.el tables")
6126 (if arg (org-table-edit-field t)
6127 (org-table-justify-field-maybe)
6128 (call-interactively 'org-table-next-field))))
6130 ((run-hook-with-args-until-success
6131 'org-tab-after-check-for-table-hook))
6133 ;; Global cycling: delegate to `org-cycle-internal-global'.
6134 ((eq arg t) (org-cycle-internal-global))
6136 ;; Drawers: delegate to `org-flag-drawer'.
6137 ((and org-drawers org-drawer-regexp
6138 (save-excursion
6139 (beginning-of-line 1)
6140 (looking-at org-drawer-regexp)))
6141 (org-flag-drawer ; toggle block visibility
6142 (not (get-char-property (match-end 0) 'invisible))))
6144 ;; Show-subtree, ARG levels up from here.
6145 ((integerp arg)
6146 (save-excursion
6147 (org-back-to-heading)
6148 (outline-up-heading (if (< arg 0) (- arg)
6149 (- (funcall outline-level) arg)))
6150 (org-show-subtree)))
6152 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6153 ((and (featurep 'org-inlinetask)
6154 (org-inlinetask-at-task-p)
6155 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6156 (org-inlinetask-toggle-visibility))
6158 ((org-try-cdlatex-tab))
6160 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6161 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6162 (save-excursion (beginning-of-line 1)
6163 (looking-at org-outline-regexp)))
6164 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6165 (org-cycle-internal-local))
6167 ;; From there: TAB emulation and template completion.
6168 (buffer-read-only (org-back-to-heading))
6170 ((run-hook-with-args-until-success
6171 'org-tab-after-check-for-cycling-hook))
6173 ((org-try-structure-completion))
6175 ((run-hook-with-args-until-success
6176 'org-tab-before-tab-emulation-hook))
6178 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6179 (or (not (bolp))
6180 (not (looking-at org-outline-regexp))))
6181 (call-interactively (global-key-binding "\t")))
6183 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6184 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6185 (or (and (eq org-cycle-emulate-tab 'white)
6186 (= (match-end 0) (point-at-eol)))
6187 (and (eq org-cycle-emulate-tab 'whitestart)
6188 (>= (match-end 0) pos))))
6190 (eq org-cycle-emulate-tab t))
6191 (call-interactively (global-key-binding "\t")))
6193 (t (save-excursion
6194 (org-back-to-heading)
6195 (org-cycle)))))))
6197 (defun org-cycle-internal-global ()
6198 "Do the global cycling action."
6199 (cond
6200 ((and (eq last-command this-command)
6201 (eq org-cycle-global-status 'overview))
6202 ;; We just created the overview - now do table of contents
6203 ;; This can be slow in very large buffers, so indicate action
6204 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6205 (message "CONTENTS...")
6206 (org-content)
6207 (message "CONTENTS...done")
6208 (setq org-cycle-global-status 'contents)
6209 (run-hook-with-args 'org-cycle-hook 'contents))
6211 ((and (eq last-command this-command)
6212 (eq org-cycle-global-status 'contents))
6213 ;; We just showed the table of contents - now show everything
6214 (run-hook-with-args 'org-pre-cycle-hook 'all)
6215 (show-all)
6216 (message "SHOW ALL")
6217 (setq org-cycle-global-status 'all)
6218 (run-hook-with-args 'org-cycle-hook 'all))
6221 ;; Default action: go to overview
6222 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6223 (org-overview)
6224 (message "OVERVIEW")
6225 (setq org-cycle-global-status 'overview)
6226 (run-hook-with-args 'org-cycle-hook 'overview))))
6228 (defun org-cycle-internal-local ()
6229 "Do the local cycling action."
6230 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6231 ;; First, determine end of headline (EOH), end of subtree or item
6232 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6233 (save-excursion
6234 (if (org-at-item-p)
6235 (progn
6236 (beginning-of-line)
6237 (setq struct (org-list-struct))
6238 (setq eoh (point-at-eol))
6239 (setq eos (org-list-get-item-end-before-blank (point) struct))
6240 (setq has-children (org-list-has-child-p (point) struct)))
6241 (org-back-to-heading)
6242 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6243 (setq eos (save-excursion
6244 (org-end-of-subtree t)
6245 (unless (eobp)
6246 (skip-chars-forward " \t\n"))
6247 (if (eobp) (point) (1- (point)))))
6248 (setq has-children
6249 (or (save-excursion
6250 (let ((level (funcall outline-level)))
6251 (outline-next-heading)
6252 (and (org-at-heading-p t)
6253 (> (funcall outline-level) level))))
6254 (save-excursion
6255 (org-list-search-forward (org-item-beginning-re) eos t)))))
6256 ;; Determine end invisible part of buffer (EOL)
6257 (beginning-of-line 2)
6258 ;; XEmacs doesn't have `next-single-char-property-change'
6259 (if (featurep 'xemacs)
6260 (while (and (not (eobp)) ;; this is like `next-line'
6261 (get-char-property (1- (point)) 'invisible))
6262 (beginning-of-line 2))
6263 (while (and (not (eobp)) ;; this is like `next-line'
6264 (get-char-property (1- (point)) 'invisible))
6265 (goto-char (next-single-char-property-change (point) 'invisible))
6266 (and (eolp) (beginning-of-line 2))))
6267 (setq eol (point)))
6268 ;; Find out what to do next and set `this-command'
6269 (cond
6270 ((= eos eoh)
6271 ;; Nothing is hidden behind this heading
6272 (run-hook-with-args 'org-pre-cycle-hook 'empty)
6273 (message "EMPTY ENTRY")
6274 (setq org-cycle-subtree-status nil)
6275 (save-excursion
6276 (goto-char eos)
6277 (outline-next-heading)
6278 (if (outline-invisible-p) (org-flag-heading nil))))
6279 ((and (or (>= eol eos)
6280 (not (string-match "\\S-" (buffer-substring eol eos))))
6281 (or has-children
6282 (not (setq children-skipped
6283 org-cycle-skip-children-state-if-no-children))))
6284 ;; Entire subtree is hidden in one line: children view
6285 (run-hook-with-args 'org-pre-cycle-hook 'children)
6286 (if (org-at-item-p)
6287 (org-list-set-item-visibility (point-at-bol) struct 'children)
6288 (org-show-entry)
6289 (show-children)
6290 ;; Fold every list in subtree to top-level items.
6291 (when (eq org-cycle-include-plain-lists 'integrate)
6292 (save-excursion
6293 (org-back-to-heading)
6294 (while (org-list-search-forward (org-item-beginning-re) eos t)
6295 (beginning-of-line 1)
6296 (let* ((struct (org-list-struct))
6297 (prevs (org-list-prevs-alist struct))
6298 (end (org-list-get-bottom-point struct)))
6299 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6300 (org-list-get-all-items (point) struct prevs))
6301 (goto-char end))))))
6302 (message "CHILDREN")
6303 (save-excursion
6304 (goto-char eos)
6305 (outline-next-heading)
6306 (if (outline-invisible-p) (org-flag-heading nil)))
6307 (setq org-cycle-subtree-status 'children)
6308 (run-hook-with-args 'org-cycle-hook 'children))
6309 ((or children-skipped
6310 (and (eq last-command this-command)
6311 (eq org-cycle-subtree-status 'children)))
6312 ;; We just showed the children, or no children are there,
6313 ;; now show everything.
6314 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
6315 (outline-flag-region eoh eos nil)
6316 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6317 (setq org-cycle-subtree-status 'subtree)
6318 (run-hook-with-args 'org-cycle-hook 'subtree))
6320 ;; Default action: hide the subtree.
6321 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6322 (outline-flag-region eoh eos t)
6323 (message "FOLDED")
6324 (setq org-cycle-subtree-status 'folded)
6325 (run-hook-with-args 'org-cycle-hook 'folded)))))
6327 ;;;###autoload
6328 (defun org-global-cycle (&optional arg)
6329 "Cycle the global visibility. For details see `org-cycle'.
6330 With \\[universal-argument] prefix arg, switch to startup visibility.
6331 With a numeric prefix, show all headlines up to that level."
6332 (interactive "P")
6333 (let ((org-cycle-include-plain-lists
6334 (if (eq major-mode 'org-mode) org-cycle-include-plain-lists nil)))
6335 (cond
6336 ((integerp arg)
6337 (show-all)
6338 (hide-sublevels arg)
6339 (setq org-cycle-global-status 'contents))
6340 ((equal arg '(4))
6341 (org-set-startup-visibility)
6342 (message "Startup visibility, plus VISIBILITY properties."))
6344 (org-cycle '(4))))))
6346 (defun org-set-startup-visibility ()
6347 "Set the visibility required by startup options and properties."
6348 (cond
6349 ((eq org-startup-folded t)
6350 (org-cycle '(4)))
6351 ((eq org-startup-folded 'content)
6352 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6353 (org-cycle '(4)) (org-cycle '(4)))))
6354 (unless (eq org-startup-folded 'showeverything)
6355 (if org-hide-block-startup (org-hide-block-all))
6356 (org-set-visibility-according-to-property 'no-cleanup)
6357 (org-cycle-hide-archived-subtrees 'all)
6358 (org-cycle-hide-drawers 'all)
6359 (org-cycle-show-empty-lines t)))
6361 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6362 "Switch subtree visibilities according to :VISIBILITY: property."
6363 (interactive)
6364 (let (org-show-entry-below state)
6365 (save-excursion
6366 (goto-char (point-min))
6367 (while (re-search-forward
6368 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6369 nil t)
6370 (setq state (match-string 1))
6371 (save-excursion
6372 (org-back-to-heading t)
6373 (hide-subtree)
6374 (org-reveal)
6375 (cond
6376 ((equal state '("fold" "folded"))
6377 (hide-subtree))
6378 ((equal state "children")
6379 (org-show-hidden-entry)
6380 (show-children))
6381 ((equal state "content")
6382 (save-excursion
6383 (save-restriction
6384 (org-narrow-to-subtree)
6385 (org-content))))
6386 ((member state '("all" "showall"))
6387 (show-subtree)))))
6388 (unless no-cleanup
6389 (org-cycle-hide-archived-subtrees 'all)
6390 (org-cycle-hide-drawers 'all)
6391 (org-cycle-show-empty-lines 'all)))))
6393 ;; This function uses outline-regexp instead of the more fundamental
6394 ;; org-outline-regexp so that org-cycle-global works outside of Org
6395 ;; buffers, where outline-regexp is needed.
6396 (defun org-overview ()
6397 "Switch to overview mode, showing only top-level headlines.
6398 Really, this shows all headlines with level equal or greater than the level
6399 of the first headline in the buffer. This is important, because if the
6400 first headline is not level one, then (hide-sublevels 1) gives confusing
6401 results."
6402 (interactive)
6403 (let ((level (save-excursion
6404 (goto-char (point-min))
6405 (if (re-search-forward (concat "^" outline-regexp) nil t)
6406 (progn
6407 (goto-char (match-beginning 0))
6408 (funcall outline-level))))))
6409 (and level (hide-sublevels level))))
6411 (defun org-content (&optional arg)
6412 "Show all headlines in the buffer, like a table of contents.
6413 With numerical argument N, show content up to level N."
6414 (interactive "P")
6415 (save-excursion
6416 ;; Visit all headings and show their offspring
6417 (and (integerp arg) (org-overview))
6418 (goto-char (point-max))
6419 (catch 'exit
6420 (while (and (progn (condition-case nil
6421 (outline-previous-visible-heading 1)
6422 (error (goto-char (point-min))))
6424 (looking-at org-outline-regexp))
6425 (if (integerp arg)
6426 (show-children (1- arg))
6427 (show-branches))
6428 (if (bobp) (throw 'exit nil))))))
6431 (defun org-optimize-window-after-visibility-change (state)
6432 "Adjust the window after a change in outline visibility.
6433 This function is the default value of the hook `org-cycle-hook'."
6434 (when (get-buffer-window (current-buffer))
6435 (cond
6436 ((eq state 'content) nil)
6437 ((eq state 'all) nil)
6438 ((eq state 'folded) nil)
6439 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6440 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6442 (defun org-remove-empty-overlays-at (pos)
6443 "Remove outline overlays that do not contain non-white stuff."
6444 (mapc
6445 (lambda (o)
6446 (and (eq 'outline (overlay-get o 'invisible))
6447 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6448 (overlay-end o))))
6449 (delete-overlay o)))
6450 (overlays-at pos)))
6452 (defun org-clean-visibility-after-subtree-move ()
6453 "Fix visibility issues after moving a subtree."
6454 ;; First, find a reasonable region to look at:
6455 ;; Start two siblings above, end three below
6456 (let* ((beg (save-excursion
6457 (and (org-get-last-sibling)
6458 (org-get-last-sibling))
6459 (point)))
6460 (end (save-excursion
6461 (and (org-get-next-sibling)
6462 (org-get-next-sibling)
6463 (org-get-next-sibling))
6464 (if (org-at-heading-p)
6465 (point-at-eol)
6466 (point))))
6467 (level (looking-at "\\*+"))
6468 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6469 (save-excursion
6470 (save-restriction
6471 (narrow-to-region beg end)
6472 (when re
6473 ;; Properly fold already folded siblings
6474 (goto-char (point-min))
6475 (while (re-search-forward re nil t)
6476 (if (and (not (outline-invisible-p))
6477 (save-excursion
6478 (goto-char (point-at-eol)) (outline-invisible-p)))
6479 (hide-entry))))
6480 (org-cycle-show-empty-lines 'overview)
6481 (org-cycle-hide-drawers 'overview)))))
6483 (defun org-cycle-show-empty-lines (state)
6484 "Show empty lines above all visible headlines.
6485 The region to be covered depends on STATE when called through
6486 `org-cycle-hook'. Lisp program can use t for STATE to get the
6487 entire buffer covered. Note that an empty line is only shown if there
6488 are at least `org-cycle-separator-lines' empty lines before the headline."
6489 (when (not (= org-cycle-separator-lines 0))
6490 (save-excursion
6491 (let* ((n (abs org-cycle-separator-lines))
6492 (re (cond
6493 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6494 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6495 (t (let ((ns (number-to-string (- n 2))))
6496 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6497 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6498 beg end b e)
6499 (cond
6500 ((memq state '(overview contents t))
6501 (setq beg (point-min) end (point-max)))
6502 ((memq state '(children folded))
6503 (setq beg (point) end (progn (org-end-of-subtree t t)
6504 (beginning-of-line 2)
6505 (point)))))
6506 (when beg
6507 (goto-char beg)
6508 (while (re-search-forward re end t)
6509 (unless (get-char-property (match-end 1) 'invisible)
6510 (setq e (match-end 1))
6511 (if (< org-cycle-separator-lines 0)
6512 (setq b (save-excursion
6513 (goto-char (match-beginning 0))
6514 (org-back-over-empty-lines)
6515 (if (save-excursion
6516 (goto-char (max (point-min) (1- (point))))
6517 (org-on-heading-p))
6518 (1- (point))
6519 (point))))
6520 (setq b (match-beginning 1)))
6521 (outline-flag-region b e nil)))))))
6522 ;; Never hide empty lines at the end of the file.
6523 (save-excursion
6524 (goto-char (point-max))
6525 (outline-previous-heading)
6526 (outline-end-of-heading)
6527 (if (and (looking-at "[ \t\n]+")
6528 (= (match-end 0) (point-max)))
6529 (outline-flag-region (point) (match-end 0) nil))))
6531 (defun org-show-empty-lines-in-parent ()
6532 "Move to the parent and re-show empty lines before visible headlines."
6533 (save-excursion
6534 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6535 (org-cycle-show-empty-lines context))))
6537 (defun org-files-list ()
6538 "Return `org-agenda-files' list, plus all open org-mode files.
6539 This is useful for operations that need to scan all of a user's
6540 open and agenda-wise Org files."
6541 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6542 (dolist (buf (buffer-list))
6543 (with-current-buffer buf
6544 (if (and (eq major-mode 'org-mode) (buffer-file-name))
6545 (let ((file (expand-file-name (buffer-file-name))))
6546 (unless (member file files)
6547 (push file files))))))
6548 files))
6550 (defsubst org-entry-beginning-position ()
6551 "Return the beginning position of the current entry."
6552 (save-excursion (outline-back-to-heading t) (point)))
6554 (defsubst org-entry-end-position ()
6555 "Return the end position of the current entry."
6556 (save-excursion (outline-next-heading) (point)))
6558 (defun org-cycle-hide-drawers (state)
6559 "Re-hide all drawers after a visibility state change."
6560 (when (and (eq major-mode 'org-mode)
6561 (not (memq state '(overview folded contents))))
6562 (save-excursion
6563 (let* ((globalp (memq state '(contents all)))
6564 (beg (if globalp (point-min) (point)))
6565 (end (if globalp (point-max)
6566 (if (eq state 'children)
6567 (save-excursion (outline-next-heading) (point))
6568 (org-end-of-subtree t)))))
6569 (goto-char beg)
6570 (while (re-search-forward org-drawer-regexp end t)
6571 (org-flag-drawer t))))))
6573 (defun org-flag-drawer (flag)
6574 (save-excursion
6575 (beginning-of-line 1)
6576 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6577 (let ((b (match-end 0)))
6578 (if (re-search-forward
6579 "^[ \t]*:END:"
6580 (save-excursion (outline-next-heading) (point)) t)
6581 (outline-flag-region b (point-at-eol) flag)
6582 (error ":END: line missing at position %s" b))))))
6584 (defun org-subtree-end-visible-p ()
6585 "Is the end of the current subtree visible?"
6586 (pos-visible-in-window-p
6587 (save-excursion (org-end-of-subtree t) (point))))
6589 (defun org-first-headline-recenter (&optional N)
6590 "Move cursor to the first headline and recenter the headline.
6591 Optional argument N means put the headline into the Nth line of the window."
6592 (goto-char (point-min))
6593 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
6594 (beginning-of-line)
6595 (recenter (prefix-numeric-value N))))
6597 ;;; Saving and restoring visibility
6599 (defun org-outline-overlay-data (&optional use-markers)
6600 "Return a list of the locations of all outline overlays.
6601 These are overlays with the `invisible' property value `outline'.
6602 The return value is a list of cons cells, with start and stop
6603 positions for each overlay.
6604 If USE-MARKERS is set, return the positions as markers."
6605 (let (beg end)
6606 (save-excursion
6607 (save-restriction
6608 (widen)
6609 (delq nil
6610 (mapcar (lambda (o)
6611 (when (eq (overlay-get o 'invisible) 'outline)
6612 (setq beg (overlay-start o)
6613 end (overlay-end o))
6614 (and beg end (> end beg)
6615 (if use-markers
6616 (cons (move-marker (make-marker) beg)
6617 (move-marker (make-marker) end))
6618 (cons beg end)))))
6619 (overlays-in (point-min) (point-max))))))))
6621 (defun org-set-outline-overlay-data (data)
6622 "Create visibility overlays for all positions in DATA.
6623 DATA should have been made by `org-outline-overlay-data'."
6624 (let (o)
6625 (save-excursion
6626 (save-restriction
6627 (widen)
6628 (show-all)
6629 (mapc (lambda (c)
6630 (outline-flag-region (car c) (cdr c) t))
6631 data)))))
6633 ;;; Folding of blocks
6635 (defconst org-block-regexp
6636 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
6637 "Regular expression for hiding blocks.")
6639 (defvar org-hide-block-overlays nil
6640 "Overlays hiding blocks.")
6641 (make-variable-buffer-local 'org-hide-block-overlays)
6643 (defun org-block-map (function &optional start end)
6644 "Call FUNCTION at the head of all source blocks in the current buffer.
6645 Optional arguments START and END can be used to limit the range."
6646 (let ((start (or start (point-min)))
6647 (end (or end (point-max))))
6648 (save-excursion
6649 (goto-char start)
6650 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
6651 (save-excursion
6652 (save-match-data
6653 (goto-char (match-beginning 0))
6654 (funcall function)))))))
6656 (defun org-hide-block-toggle-all ()
6657 "Toggle the visibility of all blocks in the current buffer."
6658 (org-block-map #'org-hide-block-toggle))
6660 (defun org-hide-block-all ()
6661 "Fold all blocks in the current buffer."
6662 (interactive)
6663 (org-show-block-all)
6664 (org-block-map #'org-hide-block-toggle-maybe))
6666 (defun org-show-block-all ()
6667 "Unfold all blocks in the current buffer."
6668 (interactive)
6669 (mapc 'delete-overlay org-hide-block-overlays)
6670 (setq org-hide-block-overlays nil))
6672 (defun org-hide-block-toggle-maybe ()
6673 "Toggle visibility of block at point."
6674 (interactive)
6675 (let ((case-fold-search t))
6676 (if (save-excursion
6677 (beginning-of-line 1)
6678 (looking-at org-block-regexp))
6679 (progn (org-hide-block-toggle)
6680 t) ;; to signal that we took action
6681 nil))) ;; to signal that we did not
6683 (defun org-hide-block-toggle (&optional force)
6684 "Toggle the visibility of the current block."
6685 (interactive)
6686 (save-excursion
6687 (beginning-of-line)
6688 (if (re-search-forward org-block-regexp nil t)
6689 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
6690 (end (match-end 0)) ;; end of entire body
6692 (if (memq t (mapcar (lambda (overlay)
6693 (eq (overlay-get overlay 'invisible)
6694 'org-hide-block))
6695 (overlays-at start)))
6696 (if (or (not force) (eq force 'off))
6697 (mapc (lambda (ov)
6698 (when (member ov org-hide-block-overlays)
6699 (setq org-hide-block-overlays
6700 (delq ov org-hide-block-overlays)))
6701 (when (eq (overlay-get ov 'invisible)
6702 'org-hide-block)
6703 (delete-overlay ov)))
6704 (overlays-at start)))
6705 (setq ov (make-overlay start end))
6706 (overlay-put ov 'invisible 'org-hide-block)
6707 ;; make the block accessible to isearch
6708 (overlay-put
6709 ov 'isearch-open-invisible
6710 (lambda (ov)
6711 (when (member ov org-hide-block-overlays)
6712 (setq org-hide-block-overlays
6713 (delq ov org-hide-block-overlays)))
6714 (when (eq (overlay-get ov 'invisible)
6715 'org-hide-block)
6716 (delete-overlay ov))))
6717 (push ov org-hide-block-overlays)))
6718 (error "Not looking at a source block"))))
6720 ;; org-tab-after-check-for-cycling-hook
6721 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
6722 ;; Remove overlays when changing major mode
6723 (add-hook 'org-mode-hook
6724 (lambda () (org-add-hook 'change-major-mode-hook
6725 'org-show-block-all 'append 'local)))
6727 ;;; Org-goto
6729 (defvar org-goto-window-configuration nil)
6730 (defvar org-goto-marker nil)
6731 (defvar org-goto-map
6732 (let ((map (make-sparse-keymap)))
6733 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
6734 (while (setq cmd (pop cmds))
6735 (substitute-key-definition cmd cmd map global-map)))
6736 (suppress-keymap map)
6737 (org-defkey map "\C-m" 'org-goto-ret)
6738 (org-defkey map [(return)] 'org-goto-ret)
6739 (org-defkey map [(left)] 'org-goto-left)
6740 (org-defkey map [(right)] 'org-goto-right)
6741 (org-defkey map [(control ?g)] 'org-goto-quit)
6742 (org-defkey map "\C-i" 'org-cycle)
6743 (org-defkey map [(tab)] 'org-cycle)
6744 (org-defkey map [(down)] 'outline-next-visible-heading)
6745 (org-defkey map [(up)] 'outline-previous-visible-heading)
6746 (if org-goto-auto-isearch
6747 (if (fboundp 'define-key-after)
6748 (define-key-after map [t] 'org-goto-local-auto-isearch)
6749 nil)
6750 (org-defkey map "q" 'org-goto-quit)
6751 (org-defkey map "n" 'outline-next-visible-heading)
6752 (org-defkey map "p" 'outline-previous-visible-heading)
6753 (org-defkey map "f" 'outline-forward-same-level)
6754 (org-defkey map "b" 'outline-backward-same-level)
6755 (org-defkey map "u" 'outline-up-heading))
6756 (org-defkey map "/" 'org-occur)
6757 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
6758 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
6759 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
6760 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
6761 (org-defkey map "\C-c\C-u" 'outline-up-heading)
6762 map))
6764 (defconst org-goto-help
6765 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
6766 RET=jump to location [Q]uit and return to previous location
6767 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
6769 (defvar org-goto-start-pos) ; dynamically scoped parameter
6771 ;; FIXME: Docstring does not mention both interfaces
6772 (defun org-goto (&optional alternative-interface)
6773 "Look up a different location in the current file, keeping current visibility.
6775 When you want look-up or go to a different location in a document, the
6776 fastest way is often to fold the entire buffer and then dive into the tree.
6777 This method has the disadvantage, that the previous location will be folded,
6778 which may not be what you want.
6780 This command works around this by showing a copy of the current buffer
6781 in an indirect buffer, in overview mode. You can dive into the tree in
6782 that copy, use org-occur and incremental search to find a location.
6783 When pressing RET or `Q', the command returns to the original buffer in
6784 which the visibility is still unchanged. After RET is will also jump to
6785 the location selected in the indirect buffer and expose the headline
6786 hierarchy above."
6787 (interactive "P")
6788 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
6789 (org-refile-use-outline-path t)
6790 (org-refile-target-verify-function nil)
6791 (interface
6792 (if (not alternative-interface)
6793 org-goto-interface
6794 (if (eq org-goto-interface 'outline)
6795 'outline-path-completion
6796 'outline)))
6797 (org-goto-start-pos (point))
6798 (selected-point
6799 (if (eq interface 'outline)
6800 (car (org-get-location (current-buffer) org-goto-help))
6801 (let ((pa (org-refile-get-location "Goto")))
6802 (org-refile-check-position pa)
6803 (nth 3 pa)))))
6804 (if selected-point
6805 (progn
6806 (org-mark-ring-push org-goto-start-pos)
6807 (goto-char selected-point)
6808 (if (or (outline-invisible-p) (org-invisible-p2))
6809 (org-show-context 'org-goto)))
6810 (message "Quit"))))
6812 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
6813 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
6814 (defvar org-goto-local-auto-isearch-map) ; defined below
6816 (defun org-get-location (buf help)
6817 "Let the user select a location in the Org-mode buffer BUF.
6818 This function uses a recursive edit. It returns the selected position
6819 or nil."
6820 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
6821 (isearch-hide-immediately nil)
6822 (isearch-search-fun-function
6823 (lambda () 'org-goto-local-search-headings))
6824 (org-goto-selected-point org-goto-exit-command)
6825 (pop-up-frames nil)
6826 (special-display-buffer-names nil)
6827 (special-display-regexps nil)
6828 (special-display-function nil))
6829 (save-excursion
6830 (save-window-excursion
6831 (delete-other-windows)
6832 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
6833 (org-pop-to-buffer-same-window
6834 (condition-case nil
6835 (make-indirect-buffer (current-buffer) "*org-goto*")
6836 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
6837 (with-output-to-temp-buffer "*Help*"
6838 (princ help))
6839 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
6840 (setq buffer-read-only nil)
6841 (let ((org-startup-truncated t)
6842 (org-startup-folded nil)
6843 (org-startup-align-all-tables nil))
6844 (org-mode)
6845 (org-overview))
6846 (setq buffer-read-only t)
6847 (if (and (boundp 'org-goto-start-pos)
6848 (integer-or-marker-p org-goto-start-pos))
6849 (let ((org-show-hierarchy-above t)
6850 (org-show-siblings t)
6851 (org-show-following-heading t))
6852 (goto-char org-goto-start-pos)
6853 (and (outline-invisible-p) (org-show-context)))
6854 (goto-char (point-min)))
6855 (let (org-special-ctrl-a/e) (org-beginning-of-line))
6856 (message "Select location and press RET")
6857 (use-local-map org-goto-map)
6858 (recursive-edit)
6860 (kill-buffer "*org-goto*")
6861 (cons org-goto-selected-point org-goto-exit-command)))
6863 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
6864 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
6865 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
6866 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
6868 (defun org-goto-local-search-headings (string bound noerror)
6869 "Search and make sure that any matches are in headlines."
6870 (catch 'return
6871 (while (if isearch-forward
6872 (search-forward string bound noerror)
6873 (search-backward string bound noerror))
6874 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
6875 (and (member :headline context)
6876 (not (member :tags context))))
6877 (throw 'return (point))))))
6879 (defun org-goto-local-auto-isearch ()
6880 "Start isearch."
6881 (interactive)
6882 (goto-char (point-min))
6883 (let ((keys (this-command-keys)))
6884 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
6885 (isearch-mode t)
6886 (isearch-process-search-char (string-to-char keys)))))
6888 (defun org-goto-ret (&optional arg)
6889 "Finish `org-goto' by going to the new location."
6890 (interactive "P")
6891 (setq org-goto-selected-point (point)
6892 org-goto-exit-command 'return)
6893 (throw 'exit nil))
6895 (defun org-goto-left ()
6896 "Finish `org-goto' by going to the new location."
6897 (interactive)
6898 (if (org-on-heading-p)
6899 (progn
6900 (beginning-of-line 1)
6901 (setq org-goto-selected-point (point)
6902 org-goto-exit-command 'left)
6903 (throw 'exit nil))
6904 (error "Not on a heading")))
6906 (defun org-goto-right ()
6907 "Finish `org-goto' by going to the new location."
6908 (interactive)
6909 (if (org-on-heading-p)
6910 (progn
6911 (setq org-goto-selected-point (point)
6912 org-goto-exit-command 'right)
6913 (throw 'exit nil))
6914 (error "Not on a heading")))
6916 (defun org-goto-quit ()
6917 "Finish `org-goto' without cursor motion."
6918 (interactive)
6919 (setq org-goto-selected-point nil)
6920 (setq org-goto-exit-command 'quit)
6921 (throw 'exit nil))
6923 ;;; Indirect buffer display of subtrees
6925 (defvar org-indirect-dedicated-frame nil
6926 "This is the frame being used for indirect tree display.")
6927 (defvar org-last-indirect-buffer nil)
6929 (defun org-tree-to-indirect-buffer (&optional arg)
6930 "Create indirect buffer and narrow it to current subtree.
6931 With numerical prefix ARG, go up to this level and then take that tree.
6932 If ARG is negative, go up that many levels.
6933 If `org-indirect-buffer-display' is not `new-frame', the command removes the
6934 indirect buffer previously made with this command, to avoid proliferation of
6935 indirect buffers. However, when you call the command with a \
6936 \\[universal-argument] prefix, or
6937 when `org-indirect-buffer-display' is `new-frame', the last buffer
6938 is kept so that you can work with several indirect buffers at the same time.
6939 If `org-indirect-buffer-display' is `dedicated-frame', the \
6940 \\[universal-argument] prefix also
6941 requests that a new frame be made for the new buffer, so that the dedicated
6942 frame is not changed."
6943 (interactive "P")
6944 (let ((cbuf (current-buffer))
6945 (cwin (selected-window))
6946 (pos (point))
6947 beg end level heading ibuf)
6948 (save-excursion
6949 (org-back-to-heading t)
6950 (when (numberp arg)
6951 (setq level (org-outline-level))
6952 (if (< arg 0) (setq arg (+ level arg)))
6953 (while (> (setq level (org-outline-level)) arg)
6954 (outline-up-heading 1 t)))
6955 (setq beg (point)
6956 heading (org-get-heading))
6957 (org-end-of-subtree t t)
6958 (if (org-on-heading-p) (backward-char 1))
6959 (setq end (point)))
6960 (if (and (buffer-live-p org-last-indirect-buffer)
6961 (not (eq org-indirect-buffer-display 'new-frame))
6962 (not arg))
6963 (kill-buffer org-last-indirect-buffer))
6964 (setq ibuf (org-get-indirect-buffer cbuf)
6965 org-last-indirect-buffer ibuf)
6966 (cond
6967 ((or (eq org-indirect-buffer-display 'new-frame)
6968 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
6969 (select-frame (make-frame))
6970 (delete-other-windows)
6971 (org-pop-to-buffer-same-window ibuf)
6972 (org-set-frame-title heading))
6973 ((eq org-indirect-buffer-display 'dedicated-frame)
6974 (raise-frame
6975 (select-frame (or (and org-indirect-dedicated-frame
6976 (frame-live-p org-indirect-dedicated-frame)
6977 org-indirect-dedicated-frame)
6978 (setq org-indirect-dedicated-frame (make-frame)))))
6979 (delete-other-windows)
6980 (org-pop-to-buffer-same-window ibuf)
6981 (org-set-frame-title (concat "Indirect: " heading)))
6982 ((eq org-indirect-buffer-display 'current-window)
6983 (org-pop-to-buffer-same-window ibuf))
6984 ((eq org-indirect-buffer-display 'other-window)
6985 (pop-to-buffer ibuf))
6986 (t (error "Invalid value")))
6987 (if (featurep 'xemacs)
6988 (save-excursion (org-mode) (turn-on-font-lock)))
6989 (narrow-to-region beg end)
6990 (show-all)
6991 (goto-char pos)
6992 (run-hook-with-args 'org-cycle-hook 'all)
6993 (and (window-live-p cwin) (select-window cwin))))
6995 (defun org-get-indirect-buffer (&optional buffer)
6996 (setq buffer (or buffer (current-buffer)))
6997 (let ((n 1) (base (buffer-name buffer)) bname)
6998 (while (buffer-live-p
6999 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7000 (setq n (1+ n)))
7001 (condition-case nil
7002 (make-indirect-buffer buffer bname 'clone)
7003 (error (make-indirect-buffer buffer bname)))))
7005 (defun org-set-frame-title (title)
7006 "Set the title of the current frame to the string TITLE."
7007 ;; FIXME: how to name a single frame in XEmacs???
7008 (unless (featurep 'xemacs)
7009 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7011 ;;;; Structure editing
7013 ;;; Inserting headlines
7015 (defun org-previous-line-empty-p ()
7016 (save-excursion
7017 (and (not (bobp))
7018 (or (beginning-of-line 0) t)
7019 (save-match-data
7020 (looking-at "[ \t]*$")))))
7022 (defun org-insert-heading (&optional force-heading invisible-ok)
7023 "Insert a new heading or item with same depth at point.
7024 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
7025 If point is at the beginning of a headline, insert a sibling before the
7026 current headline. If point is not at the beginning, split the line,
7027 create the new headline with the text in the current line after point
7028 \(but see also the variable `org-M-RET-may-split-line').
7030 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7031 This is important for non-interactive uses of the command."
7032 (interactive "P")
7033 (if (or (= (buffer-size) 0)
7034 (and (not (save-excursion
7035 (and (ignore-errors (org-back-to-heading invisible-ok))
7036 (org-on-heading-p))))
7037 (or force-heading (not (org-in-item-p)))))
7038 (progn
7039 (insert "\n* ")
7040 (run-hooks 'org-insert-heading-hook))
7041 (when (or force-heading (not (org-insert-item)))
7042 (let* ((empty-line-p nil)
7043 (level nil)
7044 (on-heading (org-on-heading-p))
7045 (head (save-excursion
7046 (condition-case nil
7047 (progn
7048 (org-back-to-heading invisible-ok)
7049 (when (and (not on-heading)
7050 (featurep 'org-inlinetask)
7051 (integerp org-inlinetask-min-level)
7052 (>= (length (match-string 0))
7053 org-inlinetask-min-level))
7054 ;; Find a heading level before the inline task
7055 (while (and (setq level (org-up-heading-safe))
7056 (>= level org-inlinetask-min-level)))
7057 (if (org-on-heading-p)
7058 (org-back-to-heading invisible-ok)
7059 (error "This should not happen")))
7060 (setq empty-line-p (org-previous-line-empty-p))
7061 (match-string 0))
7062 (error "*"))))
7063 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7064 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7065 pos hide-previous previous-pos)
7066 (cond
7067 ((and (org-on-heading-p) (bolp)
7068 (or (bobp)
7069 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
7070 ;; insert before the current line
7071 (open-line (if blank 2 1)))
7072 ((and (bolp)
7073 (not org-insert-heading-respect-content)
7074 (or (bobp)
7075 (save-excursion
7076 (backward-char 1) (not (outline-invisible-p)))))
7077 ;; insert right here
7078 nil)
7080 ;; somewhere in the line
7081 (save-excursion
7082 (setq previous-pos (point-at-bol))
7083 (end-of-line)
7084 (setq hide-previous (outline-invisible-p)))
7085 (and org-insert-heading-respect-content (org-show-subtree))
7086 (let ((split
7087 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
7088 (save-excursion
7089 (let ((p (point)))
7090 (goto-char (point-at-bol))
7091 (and (looking-at org-complex-heading-regexp)
7092 (match-beginning 4)
7093 (> p (match-beginning 4)))))))
7094 tags pos)
7095 (cond
7096 (org-insert-heading-respect-content
7097 (org-end-of-subtree nil t)
7098 (when (featurep 'org-inlinetask)
7099 (while (and (not (eobp))
7100 (looking-at "\\(\\*+\\)[ \t]+")
7101 (>= (length (match-string 1))
7102 org-inlinetask-min-level))
7103 (org-end-of-subtree nil t)))
7104 (or (bolp) (newline))
7105 (or (org-previous-line-empty-p)
7106 (and blank (newline)))
7107 (open-line 1))
7108 ((org-on-heading-p)
7109 (when hide-previous
7110 (show-children)
7111 (org-show-entry))
7112 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7113 (setq tags (and (match-end 2) (match-string 2)))
7114 (and (match-end 1)
7115 (delete-region (match-beginning 1) (match-end 1)))
7116 (setq pos (point-at-bol))
7117 (or split (end-of-line 1))
7118 (delete-horizontal-space)
7119 (if (string-match "\\`\\*+\\'"
7120 (buffer-substring (point-at-bol) (point)))
7121 (insert " "))
7122 (newline (if blank 2 1))
7123 (when tags
7124 (save-excursion
7125 (goto-char pos)
7126 (end-of-line 1)
7127 (insert " " tags)
7128 (org-set-tags nil 'align))))
7130 (or split (end-of-line 1))
7131 (newline (if blank 2 1)))))))
7132 (insert head) (just-one-space)
7133 (setq pos (point))
7134 (end-of-line 1)
7135 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7136 (when (and org-insert-heading-respect-content hide-previous)
7137 (save-excursion
7138 (goto-char previous-pos)
7139 (hide-subtree)))
7140 (run-hooks 'org-insert-heading-hook)))))
7142 (defun org-get-heading (&optional no-tags no-todo)
7143 "Return the heading of the current entry, without the stars.
7144 When NO-TAGS is non-nil, don't include tags.
7145 When NO-TODO is non-nil, don't include TODO keywords."
7146 (save-excursion
7147 (org-back-to-heading t)
7148 (cond
7149 ((and no-tags no-todo)
7150 (looking-at org-complex-heading-regexp)
7151 (match-string 4))
7152 (no-tags
7153 (looking-at (concat org-outline-regexp
7154 "\\(.*?\\)"
7155 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7156 (match-string 1))
7157 (no-todo
7158 (looking-at org-todo-line-regexp)
7159 (match-string 3))
7160 (t (looking-at org-heading-regexp)
7161 (match-string 2)))))
7163 (defun org-heading-components ()
7164 "Return the components of the current heading.
7165 This is a list with the following elements:
7166 - the level as an integer
7167 - the reduced level, different if `org-odd-levels-only' is set.
7168 - the TODO keyword, or nil
7169 - the priority character, like ?A, or nil if no priority is given
7170 - the headline text itself, or the tags string if no headline text
7171 - the tags string, or nil."
7172 (save-excursion
7173 (org-back-to-heading t)
7174 (if (let (case-fold-search) (looking-at org-complex-heading-regexp))
7175 (list (length (match-string 1))
7176 (org-reduced-level (length (match-string 1)))
7177 (org-match-string-no-properties 2)
7178 (and (match-end 3) (aref (match-string 3) 2))
7179 (org-match-string-no-properties 4)
7180 (org-match-string-no-properties 5)))))
7182 (defun org-get-entry ()
7183 "Get the entry text, after heading, entire subtree."
7184 (save-excursion
7185 (org-back-to-heading t)
7186 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7188 (defun org-insert-heading-after-current ()
7189 "Insert a new heading with same level as current, after current subtree."
7190 (interactive)
7191 (org-back-to-heading)
7192 (org-insert-heading)
7193 (org-move-subtree-down)
7194 (end-of-line 1))
7196 (defun org-insert-heading-respect-content ()
7197 (interactive)
7198 (let ((org-insert-heading-respect-content t))
7199 (org-insert-heading t)))
7201 (defun org-insert-todo-heading-respect-content (&optional force-state)
7202 (interactive "P")
7203 (let ((org-insert-heading-respect-content t))
7204 (org-insert-todo-heading force-state t)))
7206 (defun org-insert-todo-heading (arg &optional force-heading)
7207 "Insert a new heading with the same level and TODO state as current heading.
7208 If the heading has no TODO state, or if the state is DONE, use the first
7209 state (TODO by default). Also with prefix arg, force first state."
7210 (interactive "P")
7211 (when (or force-heading (not (org-insert-item 'checkbox)))
7212 (org-insert-heading force-heading)
7213 (save-excursion
7214 (org-back-to-heading)
7215 (outline-previous-heading)
7216 (looking-at org-todo-line-regexp))
7217 (let*
7218 ((new-mark-x
7219 (if (or arg
7220 (not (match-beginning 2))
7221 (member (match-string 2) org-done-keywords))
7222 (car org-todo-keywords-1)
7223 (match-string 2)))
7224 (new-mark
7226 (run-hook-with-args-until-success
7227 'org-todo-get-default-hook new-mark-x nil)
7228 new-mark-x)))
7229 (beginning-of-line 1)
7230 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7231 (if org-treat-insert-todo-heading-as-state-change
7232 (org-todo new-mark)
7233 (insert new-mark " "))))
7234 (when org-provide-todo-statistics
7235 (org-update-parent-todo-statistics))))
7237 (defun org-insert-subheading (arg)
7238 "Insert a new subheading and demote it.
7239 Works for outline headings and for plain lists alike."
7240 (interactive "P")
7241 (org-insert-heading arg)
7242 (cond
7243 ((org-on-heading-p) (org-do-demote))
7244 ((org-at-item-p) (org-indent-item))))
7246 (defun org-insert-todo-subheading (arg)
7247 "Insert a new subheading with TODO keyword or checkbox and demote it.
7248 Works for outline headings and for plain lists alike."
7249 (interactive "P")
7250 (org-insert-todo-heading arg)
7251 (cond
7252 ((org-on-heading-p) (org-do-demote))
7253 ((org-at-item-p) (org-indent-item))))
7255 ;;; Promotion and Demotion
7257 (defvar org-after-demote-entry-hook nil
7258 "Hook run after an entry has been demoted.
7259 The cursor will be at the beginning of the entry.
7260 When a subtree is being demoted, the hook will be called for each node.")
7262 (defvar org-after-promote-entry-hook nil
7263 "Hook run after an entry has been promoted.
7264 The cursor will be at the beginning of the entry.
7265 When a subtree is being promoted, the hook will be called for each node.")
7267 (defun org-promote-subtree ()
7268 "Promote the entire subtree.
7269 See also `org-promote'."
7270 (interactive)
7271 (save-excursion
7272 (org-with-limited-levels (org-map-tree 'org-promote)))
7273 (org-fix-position-after-promote))
7275 (defun org-demote-subtree ()
7276 "Demote the entire subtree. See `org-demote'.
7277 See also `org-promote'."
7278 (interactive)
7279 (save-excursion
7280 (org-with-limited-levels (org-map-tree 'org-demote)))
7281 (org-fix-position-after-promote))
7284 (defun org-do-promote ()
7285 "Promote the current heading higher up the tree.
7286 If the region is active in `transient-mark-mode', promote all headings
7287 in the region."
7288 (interactive)
7289 (save-excursion
7290 (if (org-region-active-p)
7291 (org-map-region 'org-promote (region-beginning) (region-end))
7292 (org-promote)))
7293 (org-fix-position-after-promote))
7295 (defun org-do-demote ()
7296 "Demote the current heading lower down the tree.
7297 If the region is active in `transient-mark-mode', demote all headings
7298 in the region."
7299 (interactive)
7300 (save-excursion
7301 (if (org-region-active-p)
7302 (org-map-region 'org-demote (region-beginning) (region-end))
7303 (org-demote)))
7304 (org-fix-position-after-promote))
7306 (defun org-fix-position-after-promote ()
7307 "Make sure that after pro/demotion cursor position is right."
7308 (let ((pos (point)))
7309 (when (save-excursion
7310 (beginning-of-line 1)
7311 (looking-at org-todo-line-regexp)
7312 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7313 (cond ((eobp) (insert " "))
7314 ((eolp) (insert " "))
7315 ((equal (char-after) ?\ ) (forward-char 1))))))
7317 (defun org-current-level ()
7318 "Return the level of the current entry, or nil if before the first headline.
7319 The level is the number of stars at the beginning of the headline."
7320 (save-excursion
7321 (org-with-limited-levels
7322 (if (ignore-errors (org-back-to-heading t))
7323 (funcall outline-level)))))
7325 (defun org-get-previous-line-level ()
7326 "Return the outline depth of the last headline before the current line.
7327 Returns 0 for the first headline in the buffer, and nil if before the
7328 first headline."
7329 (let ((current-level (org-current-level))
7330 (prev-level (when (> (line-number-at-pos) 1)
7331 (save-excursion
7332 (beginning-of-line 0)
7333 (org-current-level)))))
7334 (cond ((null current-level) nil) ; Before first headline
7335 ((null prev-level) 0) ; At first headline
7336 (prev-level))))
7338 (defun org-reduced-level (l)
7339 "Compute the effective level of a heading.
7340 This takes into account the setting of `org-odd-levels-only'."
7341 (cond
7342 ((zerop l) 0)
7343 (org-odd-levels-only (1+ (floor (/ l 2))))
7344 (t l)))
7346 (defun org-level-increment ()
7347 "Return the number of stars that will be added or removed at a
7348 time to headlines when structure editing, based on the value of
7349 `org-odd-levels-only'."
7350 (if org-odd-levels-only 2 1))
7352 (defun org-get-valid-level (level &optional change)
7353 "Rectify a level change under the influence of `org-odd-levels-only'
7354 LEVEL is a current level, CHANGE is by how much the level should be
7355 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7356 even level numbers will become the next higher odd number."
7357 (if org-odd-levels-only
7358 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7359 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7360 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7361 (max 1 (+ level (or change 0)))))
7363 (if (boundp 'define-obsolete-function-alias)
7364 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7365 (define-obsolete-function-alias 'org-get-legal-level
7366 'org-get-valid-level)
7367 (define-obsolete-function-alias 'org-get-legal-level
7368 'org-get-valid-level "23.1")))
7370 (defun org-promote ()
7371 "Promote the current heading higher up the tree.
7372 If the region is active in `transient-mark-mode', promote all headings
7373 in the region."
7374 (org-back-to-heading t)
7375 (let* ((level (save-match-data (funcall outline-level)))
7376 (after-change-functions (remove 'flyspell-after-change-function
7377 after-change-functions))
7378 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7379 (diff (abs (- level (length up-head) -1))))
7380 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
7381 (replace-match up-head nil t)
7382 ;; Fixup tag positioning
7383 (and org-auto-align-tags (org-set-tags nil t))
7384 (if org-adapt-indentation (org-fixup-indentation (- diff)))
7385 (run-hooks 'org-after-promote-entry-hook)))
7387 (defun org-demote ()
7388 "Demote the current heading lower down the tree.
7389 If the region is active in `transient-mark-mode', demote all headings
7390 in the region."
7391 (org-back-to-heading t)
7392 (let* ((level (save-match-data (funcall outline-level)))
7393 (after-change-functions (remove 'flyspell-after-change-function
7394 after-change-functions))
7395 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7396 (diff (abs (- level (length down-head) -1))))
7397 (replace-match down-head nil t)
7398 ;; Fixup tag positioning
7399 (and org-auto-align-tags (org-set-tags nil t))
7400 (if org-adapt-indentation (org-fixup-indentation diff))
7401 (run-hooks 'org-after-demote-entry-hook)))
7403 (defun org-cycle-level ()
7404 "Cycle the level of an empty headline through possible states.
7405 This goes first to child, then to parent, level, then up the hierarchy.
7406 After top level, it switches back to sibling level."
7407 (interactive)
7408 (let ((org-adapt-indentation nil))
7409 (when (org-point-at-end-of-empty-headline)
7410 (setq this-command 'org-cycle-level) ; Only needed for caching
7411 (let ((cur-level (org-current-level))
7412 (prev-level (org-get-previous-line-level)))
7413 (cond
7414 ;; If first headline in file, promote to top-level.
7415 ((= prev-level 0)
7416 (loop repeat (/ (- cur-level 1) (org-level-increment))
7417 do (org-do-promote)))
7418 ;; If same level as prev, demote one.
7419 ((= prev-level cur-level)
7420 (org-do-demote))
7421 ;; If parent is top-level, promote to top level if not already.
7422 ((= prev-level 1)
7423 (loop repeat (/ (- cur-level 1) (org-level-increment))
7424 do (org-do-promote)))
7425 ;; If top-level, return to prev-level.
7426 ((= cur-level 1)
7427 (loop repeat (/ (- prev-level 1) (org-level-increment))
7428 do (org-do-demote)))
7429 ;; If less than prev-level, promote one.
7430 ((< cur-level prev-level)
7431 (org-do-promote))
7432 ;; If deeper than prev-level, promote until higher than
7433 ;; prev-level.
7434 ((> cur-level prev-level)
7435 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7436 do (org-do-promote))))
7437 t))))
7439 (defun org-map-tree (fun)
7440 "Call FUN for every heading underneath the current one."
7441 (org-back-to-heading)
7442 (let ((level (funcall outline-level)))
7443 (save-excursion
7444 (funcall fun)
7445 (while (and (progn
7446 (outline-next-heading)
7447 (> (funcall outline-level) level))
7448 (not (eobp)))
7449 (funcall fun)))))
7451 (defun org-map-region (fun beg end)
7452 "Call FUN for every heading between BEG and END."
7453 (let ((org-ignore-region t))
7454 (save-excursion
7455 (setq end (copy-marker end))
7456 (goto-char beg)
7457 (if (and (re-search-forward org-outline-regexp-bol nil t)
7458 (< (point) end))
7459 (funcall fun))
7460 (while (and (progn
7461 (outline-next-heading)
7462 (< (point) end))
7463 (not (eobp)))
7464 (funcall fun)))))
7466 (defvar org-property-end-re) ; silence byte-compiler
7467 (defun org-fixup-indentation (diff)
7468 "Change the indentation in the current entry by DIFF.
7469 However, if any line in the current entry has no indentation, or if it
7470 would end up with no indentation after the change, nothing at all is done."
7471 (save-excursion
7472 (let ((end (save-excursion (outline-next-heading)
7473 (point-marker)))
7474 (prohibit (if (> diff 0)
7475 "^\\S-"
7476 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7477 col)
7478 (unless (save-excursion (end-of-line 1)
7479 (re-search-forward prohibit end t))
7480 (while (and (< (point) end)
7481 (re-search-forward "^[ \t]+" end t))
7482 (goto-char (match-end 0))
7483 (setq col (current-column))
7484 (if (< diff 0) (replace-match ""))
7485 (org-indent-to-column (+ diff col))))
7486 (move-marker end nil))))
7488 (defun org-convert-to-odd-levels ()
7489 "Convert an org-mode file with all levels allowed to one with odd levels.
7490 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7491 level 5 etc."
7492 (interactive)
7493 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7494 (let ((outline-level 'org-outline-level)
7495 (org-odd-levels-only nil) n)
7496 (save-excursion
7497 (goto-char (point-min))
7498 (while (re-search-forward "^\\*\\*+ " nil t)
7499 (setq n (- (length (match-string 0)) 2))
7500 (while (>= (setq n (1- n)) 0)
7501 (org-demote))
7502 (end-of-line 1))))))
7504 (defun org-convert-to-oddeven-levels ()
7505 "Convert an org-mode file with only odd levels to one with odd/even levels.
7506 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7507 file contains a section with an even level, conversion would
7508 destroy the structure of the file. An error is signaled in this
7509 case."
7510 (interactive)
7511 (goto-char (point-min))
7512 ;; First check if there are no even levels
7513 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7514 (org-show-context t)
7515 (error "Not all levels are odd in this file. Conversion not possible"))
7516 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
7517 (let ((outline-regexp org-outline-regexp)
7518 (outline-level 'org-outline-level)
7519 (org-odd-levels-only nil) n)
7520 (save-excursion
7521 (goto-char (point-min))
7522 (while (re-search-forward "^\\*\\*+ " nil t)
7523 (setq n (/ (1- (length (match-string 0))) 2))
7524 (while (>= (setq n (1- n)) 0)
7525 (org-promote))
7526 (end-of-line 1))))))
7528 (defun org-tr-level (n)
7529 "Make N odd if required."
7530 (if org-odd-levels-only (1+ (/ n 2)) n))
7532 ;;; Vertical tree motion, cutting and pasting of subtrees
7534 (defun org-move-subtree-up (&optional arg)
7535 "Move the current subtree up past ARG headlines of the same level."
7536 (interactive "p")
7537 (org-move-subtree-down (- (prefix-numeric-value arg))))
7539 (defun org-move-subtree-down (&optional arg)
7540 "Move the current subtree down past ARG headlines of the same level."
7541 (interactive "p")
7542 (setq arg (prefix-numeric-value arg))
7543 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
7544 'org-get-last-sibling))
7545 (ins-point (make-marker))
7546 (cnt (abs arg))
7547 (col (current-column))
7548 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
7549 ;; Select the tree
7550 (org-back-to-heading)
7551 (setq beg0 (point))
7552 (save-excursion
7553 (setq ne-beg (org-back-over-empty-lines))
7554 (setq beg (point)))
7555 (save-match-data
7556 (save-excursion (outline-end-of-heading)
7557 (setq folded (outline-invisible-p)))
7558 (outline-end-of-subtree))
7559 (outline-next-heading)
7560 (setq ne-end (org-back-over-empty-lines))
7561 (setq end (point))
7562 (goto-char beg0)
7563 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
7564 ;; include less whitespace
7565 (save-excursion
7566 (goto-char beg)
7567 (forward-line (- ne-beg ne-end))
7568 (setq beg (point))))
7569 ;; Find insertion point, with error handling
7570 (while (> cnt 0)
7571 (or (and (funcall movfunc) (looking-at org-outline-regexp))
7572 (progn (goto-char beg0)
7573 (error "Cannot move past superior level or buffer limit")))
7574 (setq cnt (1- cnt)))
7575 (if (> arg 0)
7576 ;; Moving forward - still need to move over subtree
7577 (progn (org-end-of-subtree t t)
7578 (save-excursion
7579 (org-back-over-empty-lines)
7580 (or (bolp) (newline)))))
7581 (setq ne-ins (org-back-over-empty-lines))
7582 (move-marker ins-point (point))
7583 (setq txt (buffer-substring beg end))
7584 (org-save-markers-in-region beg end)
7585 (delete-region beg end)
7586 (org-remove-empty-overlays-at beg)
7587 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
7588 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
7589 (and (not (bolp)) (looking-at "\n") (forward-char 1))
7590 (let ((bbb (point)))
7591 (insert-before-markers txt)
7592 (org-reinstall-markers-in-region bbb)
7593 (move-marker ins-point bbb))
7594 (or (bolp) (insert "\n"))
7595 (setq ins-end (point))
7596 (goto-char ins-point)
7597 (org-skip-whitespace)
7598 (when (and (< arg 0)
7599 (org-first-sibling-p)
7600 (> ne-ins ne-beg))
7601 ;; Move whitespace back to beginning
7602 (save-excursion
7603 (goto-char ins-end)
7604 (let ((kill-whole-line t))
7605 (kill-line (- ne-ins ne-beg)) (point)))
7606 (insert (make-string (- ne-ins ne-beg) ?\n)))
7607 (move-marker ins-point nil)
7608 (if folded
7609 (hide-subtree)
7610 (org-show-entry)
7611 (show-children)
7612 (org-cycle-hide-drawers 'children))
7613 (org-clean-visibility-after-subtree-move)
7614 ;; move back to the initial column we were at
7615 (move-to-column col)))
7617 (defvar org-subtree-clip ""
7618 "Clipboard for cut and paste of subtrees.
7619 This is actually only a copy of the kill, because we use the normal kill
7620 ring. We need it to check if the kill was created by `org-copy-subtree'.")
7622 (defvar org-subtree-clip-folded nil
7623 "Was the last copied subtree folded?
7624 This is used to fold the tree back after pasting.")
7626 (defun org-cut-subtree (&optional n)
7627 "Cut the current subtree into the clipboard.
7628 With prefix arg N, cut this many sequential subtrees.
7629 This is a short-hand for marking the subtree and then cutting it."
7630 (interactive "p")
7631 (org-copy-subtree n 'cut))
7633 (defun org-copy-subtree (&optional n cut force-store-markers)
7634 "Cut the current subtree into the clipboard.
7635 With prefix arg N, cut this many sequential subtrees.
7636 This is a short-hand for marking the subtree and then copying it.
7637 If CUT is non-nil, actually cut the subtree.
7638 If FORCE-STORE-MARKERS is non-nil, store the relative locations
7639 of some markers in the region, even if CUT is non-nil. This is
7640 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
7641 (interactive "p")
7642 (let (beg end folded (beg0 (point)))
7643 (if (org-called-interactively-p 'any)
7644 (org-back-to-heading nil) ; take what looks like a subtree
7645 (org-back-to-heading t)) ; take what is really there
7646 (org-back-over-empty-lines)
7647 (setq beg (point))
7648 (skip-chars-forward " \t\r\n")
7649 (save-match-data
7650 (save-excursion (outline-end-of-heading)
7651 (setq folded (outline-invisible-p)))
7652 (condition-case nil
7653 (org-forward-same-level (1- n) t)
7654 (error nil))
7655 (org-end-of-subtree t t))
7656 (org-back-over-empty-lines)
7657 (setq end (point))
7658 (goto-char beg0)
7659 (when (> end beg)
7660 (setq org-subtree-clip-folded folded)
7661 (when (or cut force-store-markers)
7662 (org-save-markers-in-region beg end))
7663 (if cut (kill-region beg end) (copy-region-as-kill beg end))
7664 (setq org-subtree-clip (current-kill 0))
7665 (message "%s: Subtree(s) with %d characters"
7666 (if cut "Cut" "Copied")
7667 (length org-subtree-clip)))))
7669 (defun org-paste-subtree (&optional level tree for-yank)
7670 "Paste the clipboard as a subtree, with modification of headline level.
7671 The entire subtree is promoted or demoted in order to match a new headline
7672 level.
7674 If the cursor is at the beginning of a headline, the same level as
7675 that headline is used to paste the tree
7677 If not, the new level is derived from the *visible* headings
7678 before and after the insertion point, and taken to be the inferior headline
7679 level of the two. So if the previous visible heading is level 3 and the
7680 next is level 4 (or vice versa), level 4 will be used for insertion.
7681 This makes sure that the subtree remains an independent subtree and does
7682 not swallow low level entries.
7684 You can also force a different level, either by using a numeric prefix
7685 argument, or by inserting the heading marker by hand. For example, if the
7686 cursor is after \"*****\", then the tree will be shifted to level 5.
7688 If optional TREE is given, use this text instead of the kill ring.
7690 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
7691 move back over whitespace before inserting, and move point to the end of
7692 the inserted text when done."
7693 (interactive "P")
7694 (setq tree (or tree (and kill-ring (current-kill 0))))
7695 (unless (org-kill-is-subtree-p tree)
7696 (error "%s"
7697 (substitute-command-keys
7698 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
7699 (org-with-limited-levels
7700 (let* ((visp (not (outline-invisible-p)))
7701 (txt tree)
7702 (^re_ "\\(\\*+\\)[ \t]*")
7703 (old-level (if (string-match org-outline-regexp-bol txt)
7704 (- (match-end 0) (match-beginning 0) 1)
7705 -1))
7706 (force-level (cond (level (prefix-numeric-value level))
7707 ((and (looking-at "[ \t]*$")
7708 (string-match
7709 "^\\*+$" (buffer-substring
7710 (point-at-bol) (point))))
7711 (- (match-end 1) (match-beginning 1)))
7712 ((and (bolp)
7713 (looking-at org-outline-regexp))
7714 (- (match-end 0) (point) 1))
7715 (t nil)))
7716 (previous-level (save-excursion
7717 (condition-case nil
7718 (progn
7719 (outline-previous-visible-heading 1)
7720 (if (looking-at ^re_)
7721 (- (match-end 0) (match-beginning 0) 1)
7723 (error 1))))
7724 (next-level (save-excursion
7725 (condition-case nil
7726 (progn
7727 (or (looking-at org-outline-regexp)
7728 (outline-next-visible-heading 1))
7729 (if (looking-at ^re_)
7730 (- (match-end 0) (match-beginning 0) 1)
7732 (error 1))))
7733 (new-level (or force-level (max previous-level next-level)))
7734 (shift (if (or (= old-level -1)
7735 (= new-level -1)
7736 (= old-level new-level))
7738 (- new-level old-level)))
7739 (delta (if (> shift 0) -1 1))
7740 (func (if (> shift 0) 'org-demote 'org-promote))
7741 (org-odd-levels-only nil)
7742 beg end newend)
7743 ;; Remove the forced level indicator
7744 (if force-level
7745 (delete-region (point-at-bol) (point)))
7746 ;; Paste
7747 (beginning-of-line (if (bolp) 1 2))
7748 (unless for-yank (org-back-over-empty-lines))
7749 (setq beg (point))
7750 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
7751 (insert-before-markers txt)
7752 (unless (string-match "\n\\'" txt) (insert "\n"))
7753 (setq newend (point))
7754 (org-reinstall-markers-in-region beg)
7755 (setq end (point))
7756 (goto-char beg)
7757 (skip-chars-forward " \t\n\r")
7758 (setq beg (point))
7759 (if (and (outline-invisible-p) visp)
7760 (save-excursion (outline-show-heading)))
7761 ;; Shift if necessary
7762 (unless (= shift 0)
7763 (save-restriction
7764 (narrow-to-region beg end)
7765 (while (not (= shift 0))
7766 (org-map-region func (point-min) (point-max))
7767 (setq shift (+ delta shift)))
7768 (goto-char (point-min))
7769 (setq newend (point-max))))
7770 (when (or (org-called-interactively-p 'interactive) for-yank)
7771 (message "Clipboard pasted as level %d subtree" new-level))
7772 (if (and (not for-yank) ; in this case, org-yank will decide about folding
7773 kill-ring
7774 (eq org-subtree-clip (current-kill 0))
7775 org-subtree-clip-folded)
7776 ;; The tree was folded before it was killed/copied
7777 (hide-subtree))
7778 (and for-yank (goto-char newend)))))
7780 (defun org-kill-is-subtree-p (&optional txt)
7781 "Check if the current kill is an outline subtree, or a set of trees.
7782 Returns nil if kill does not start with a headline, or if the first
7783 headline level is not the largest headline level in the tree.
7784 So this will actually accept several entries of equal levels as well,
7785 which is OK for `org-paste-subtree'.
7786 If optional TXT is given, check this string instead of the current kill."
7787 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
7788 (re (org-get-limited-outline-regexp))
7789 (^re (concat "^" re))
7790 (start-level (and kill
7791 (string-match
7792 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
7793 kill)
7794 (- (match-end 2) (match-beginning 2) 1)))
7795 (start (1+ (or (match-beginning 2) -1))))
7796 (if (not start-level)
7797 (progn
7798 nil) ;; does not even start with a heading
7799 (catch 'exit
7800 (while (setq start (string-match ^re kill (1+ start)))
7801 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
7802 (throw 'exit nil)))
7803 t))))
7805 (defvar org-markers-to-move nil
7806 "Markers that should be moved with a cut-and-paste operation.
7807 Those markers are stored together with their positions relative to
7808 the start of the region.")
7810 (defun org-save-markers-in-region (beg end)
7811 "Check markers in region.
7812 If these markers are between BEG and END, record their position relative
7813 to BEG, so that after moving the block of text, we can put the markers back
7814 into place.
7815 This function gets called just before an entry or tree gets cut from the
7816 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
7817 called immediately, to move the markers with the entries."
7818 (setq org-markers-to-move nil)
7819 (when (featurep 'org-clock)
7820 (org-clock-save-markers-for-cut-and-paste beg end))
7821 (when (featurep 'org-agenda)
7822 (org-agenda-save-markers-for-cut-and-paste beg end)))
7824 (defun org-check-and-save-marker (marker beg end)
7825 "Check if MARKER is between BEG and END.
7826 If yes, remember the marker and the distance to BEG."
7827 (when (and (marker-buffer marker)
7828 (equal (marker-buffer marker) (current-buffer)))
7829 (if (and (>= marker beg) (< marker end))
7830 (push (cons marker (- marker beg)) org-markers-to-move))))
7832 (defun org-reinstall-markers-in-region (beg)
7833 "Move all remembered markers to their position relative to BEG."
7834 (mapc (lambda (x)
7835 (move-marker (car x) (+ beg (cdr x))))
7836 org-markers-to-move)
7837 (setq org-markers-to-move nil))
7839 (defun org-narrow-to-subtree ()
7840 "Narrow buffer to the current subtree."
7841 (interactive)
7842 (save-excursion
7843 (save-match-data
7844 (org-with-limited-levels
7845 (narrow-to-region
7846 (progn (org-back-to-heading t) (point))
7847 (progn (org-end-of-subtree t t)
7848 (if (and (org-on-heading-p) (not (eobp))) (backward-char 1))
7849 (point)))))))
7851 (defun org-narrow-to-block ()
7852 "Narrow buffer to the current block."
7853 (interactive)
7854 (let* ((case-fold-search t)
7855 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
7856 "^[ \t]*#\\+end_.*")))
7857 (if blockp
7858 (narrow-to-region (car blockp) (cdr blockp))
7859 (error "Not in a block"))))
7861 (eval-when-compile
7862 (defvar org-property-drawer-re))
7864 (defvar org-property-start-re) ;; defined below
7865 (defun org-clone-subtree-with-time-shift (n &optional shift)
7866 "Clone the task (subtree) at point N times.
7867 The clones will be inserted as siblings.
7869 In interactive use, the user will be prompted for the number of
7870 clones to be produced, and for a time SHIFT, which may be a
7871 repeater as used in time stamps, for example `+3d'.
7873 When a valid repeater is given and the entry contains any time
7874 stamps, the clones will become a sequence in time, with time
7875 stamps in the subtree shifted for each clone produced. If SHIFT
7876 is nil or the empty string, time stamps will be left alone. The
7877 ID property of the original subtree is removed.
7879 If the original subtree did contain time stamps with a repeater,
7880 the following will happen:
7881 - the repeater will be removed in each clone
7882 - an additional clone will be produced, with the current, unshifted
7883 date(s) in the entry.
7884 - the original entry will be placed *after* all the clones, with
7885 repeater intact.
7886 - the start days in the repeater in the original entry will be shifted
7887 to past the last clone.
7888 I this way you can spell out a number of instances of a repeating task,
7889 and still retain the repeater to cover future instances of the task."
7890 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
7891 (let (beg end template task idprop
7892 shift-n shift-what doshift nmin nmax (n-no-remove -1)
7893 (drawer-re org-drawer-regexp))
7894 (if (not (and (integerp n) (> n 0)))
7895 (error "Invalid number of replications %s" n))
7896 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
7897 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
7898 shift)))
7899 (error "Invalid shift specification %s" shift))
7900 (when doshift
7901 (setq shift-n (string-to-number (match-string 1 shift))
7902 shift-what (cdr (assoc (match-string 2 shift)
7903 '(("d" . day) ("w" . week)
7904 ("m" . month) ("y" . year))))))
7905 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
7906 (setq nmin 1 nmax n)
7907 (org-back-to-heading t)
7908 (setq beg (point))
7909 (setq idprop (org-entry-get nil "ID"))
7910 (org-end-of-subtree t t)
7911 (or (bolp) (insert "\n"))
7912 (setq end (point))
7913 (setq template (buffer-substring beg end))
7914 (when (and doshift
7915 (string-match "<[^<>\n]+ \\+[0-9]+[dwmy][^<>\n]*>" template))
7916 (delete-region beg end)
7917 (setq end beg)
7918 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
7919 (goto-char end)
7920 (loop for n from nmin to nmax do
7921 ;; prepare clone
7922 (with-temp-buffer
7923 (insert template)
7924 (org-mode)
7925 (goto-char (point-min))
7926 (org-show-subtree)
7927 (and idprop (if org-clone-delete-id
7928 (org-entry-delete nil "ID")
7929 (org-id-get-create t)))
7930 (unless (= n 0)
7931 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
7932 (kill-whole-line))
7933 (goto-char (point-min))
7934 (while (re-search-forward drawer-re nil t)
7935 (mapc (lambda (d)
7936 (org-remove-empty-drawer-at d (point))) org-drawers)))
7937 (goto-char (point-min))
7938 (when doshift
7939 (while (re-search-forward org-ts-regexp-both nil t)
7940 (org-timestamp-change (* n shift-n) shift-what))
7941 (unless (= n n-no-remove)
7942 (goto-char (point-min))
7943 (while (re-search-forward org-ts-regexp nil t)
7944 (save-excursion
7945 (goto-char (match-beginning 0))
7946 (if (looking-at "<[^<>\n]+\\( +\\+[0-9]+[dwmy]\\)")
7947 (delete-region (match-beginning 1) (match-end 1)))))))
7948 (setq task (buffer-string)))
7949 (insert task))
7950 (goto-char beg)))
7952 ;;; Outline Sorting
7954 (defun org-sort (with-case)
7955 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
7956 Optional argument WITH-CASE means sort case-sensitively.
7957 With a double prefix argument, also remove duplicate entries."
7958 (interactive "P")
7959 (cond
7960 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
7961 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
7963 (org-call-with-arg 'org-sort-entries with-case))))
7965 (defun org-sort-remove-invisible (s)
7966 (remove-text-properties 0 (length s) org-rm-props s)
7967 (while (string-match org-bracket-link-regexp s)
7968 (setq s (replace-match (if (match-end 2)
7969 (match-string 3 s)
7970 (match-string 1 s)) t t s)))
7973 (defvar org-priority-regexp) ; defined later in the file
7975 (defvar org-after-sorting-entries-or-items-hook nil
7976 "Hook that is run after a bunch of entries or items have been sorted.
7977 When children are sorted, the cursor is in the parent line when this
7978 hook gets called. When a region or a plain list is sorted, the cursor
7979 will be in the first entry of the sorted region/list.")
7981 (defun org-sort-entries
7982 (&optional with-case sorting-type getkey-func compare-func property)
7983 "Sort entries on a certain level of an outline tree.
7984 If there is an active region, the entries in the region are sorted.
7985 Else, if the cursor is before the first entry, sort the top-level items.
7986 Else, the children of the entry at point are sorted.
7988 Sorting can be alphabetically, numerically, by date/time as given by
7989 a time stamp, by a property or by priority.
7991 The command prompts for the sorting type unless it has been given to the
7992 function through the SORTING-TYPE argument, which needs to be a character,
7993 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F). Here is the
7994 precise meaning of each character:
7996 n Numerically, by converting the beginning of the entry/item to a number.
7997 a Alphabetically, ignoring the TODO keyword and the priority, if any.
7998 t By date/time, either the first active time stamp in the entry, or, if
7999 none exist, by the first inactive one.
8000 s By the scheduled date/time.
8001 d By deadline date/time.
8002 c By creation time, which is assumed to be the first inactive time stamp
8003 at the beginning of a line.
8004 p By priority according to the cookie.
8005 r By the value of a property.
8007 Capital letters will reverse the sort order.
8009 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8010 called with point at the beginning of the record. It must return either
8011 a string or a number that should serve as the sorting key for that record.
8013 Comparing entries ignores case by default. However, with an optional argument
8014 WITH-CASE, the sorting considers case as well."
8015 (interactive "P")
8016 (let ((case-func (if with-case 'identity 'downcase))
8017 start beg end stars re re2
8018 txt what tmp)
8019 ;; Find beginning and end of region to sort
8020 (cond
8021 ((org-region-active-p)
8022 ;; we will sort the region
8023 (setq end (region-end)
8024 what "region")
8025 (goto-char (region-beginning))
8026 (if (not (org-on-heading-p)) (outline-next-heading))
8027 (setq start (point)))
8028 ((or (org-on-heading-p)
8029 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8030 ;; we will sort the children of the current headline
8031 (org-back-to-heading)
8032 (setq start (point)
8033 end (progn (org-end-of-subtree t t)
8034 (or (bolp) (insert "\n"))
8035 (org-back-over-empty-lines)
8036 (point))
8037 what "children")
8038 (goto-char start)
8039 (show-subtree)
8040 (outline-next-heading))
8042 ;; we will sort the top-level entries in this file
8043 (goto-char (point-min))
8044 (or (org-on-heading-p) (outline-next-heading))
8045 (setq start (point))
8046 (goto-char (point-max))
8047 (beginning-of-line 1)
8048 (when (looking-at ".*?\\S-")
8049 ;; File ends in a non-white line
8050 (end-of-line 1)
8051 (insert "\n"))
8052 (setq end (point-max))
8053 (setq what "top-level")
8054 (goto-char start)
8055 (show-all)))
8057 (setq beg (point))
8058 (if (>= beg end) (error "Nothing to sort"))
8060 (looking-at "\\(\\*+\\)")
8061 (setq stars (match-string 1)
8062 re (concat "^" (regexp-quote stars) " +")
8063 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8064 txt (buffer-substring beg end))
8065 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8066 (if (and (not (equal stars "*")) (string-match re2 txt))
8067 (error "Region to sort contains a level above the first entry"))
8069 (unless sorting-type
8070 (message
8071 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8072 [t]ime [s]cheduled [d]eadline [c]reated
8073 A/N/T/S/D/C/P/O/F means reversed:"
8074 what)
8075 (setq sorting-type (read-char-exclusive))
8077 (and (= (downcase sorting-type) ?f)
8078 (setq getkey-func
8079 (org-icompleting-read "Sort using function: "
8080 obarray 'fboundp t nil nil))
8081 (setq getkey-func (intern getkey-func)))
8083 (and (= (downcase sorting-type) ?r)
8084 (setq property
8085 (org-icompleting-read "Property: "
8086 (mapcar 'list (org-buffer-property-keys t))
8087 nil t))))
8089 (message "Sorting entries...")
8091 (save-restriction
8092 (narrow-to-region start end)
8093 (let ((dcst (downcase sorting-type))
8094 (case-fold-search nil)
8095 (now (current-time)))
8096 (sort-subr
8097 (/= dcst sorting-type)
8098 ;; This function moves to the beginning character of the "record" to
8099 ;; be sorted.
8100 (lambda nil
8101 (if (re-search-forward re nil t)
8102 (goto-char (match-beginning 0))
8103 (goto-char (point-max))))
8104 ;; This function moves to the last character of the "record" being
8105 ;; sorted.
8106 (lambda nil
8107 (save-match-data
8108 (condition-case nil
8109 (outline-forward-same-level 1)
8110 (error
8111 (goto-char (point-max))))))
8112 ;; This function returns the value that gets sorted against.
8113 (lambda nil
8114 (cond
8115 ((= dcst ?n)
8116 (if (looking-at org-complex-heading-regexp)
8117 (string-to-number (match-string 4))
8118 nil))
8119 ((= dcst ?a)
8120 (if (looking-at org-complex-heading-regexp)
8121 (funcall case-func (match-string 4))
8122 nil))
8123 ((= dcst ?t)
8124 (let ((end (save-excursion (outline-next-heading) (point))))
8125 (if (or (re-search-forward org-ts-regexp end t)
8126 (re-search-forward org-ts-regexp-both end t))
8127 (org-time-string-to-seconds (match-string 0))
8128 (org-float-time now))))
8129 ((= dcst ?c)
8130 (let ((end (save-excursion (outline-next-heading) (point))))
8131 (if (re-search-forward
8132 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8133 end t)
8134 (org-time-string-to-seconds (match-string 0))
8135 (org-float-time now))))
8136 ((= dcst ?s)
8137 (let ((end (save-excursion (outline-next-heading) (point))))
8138 (if (re-search-forward org-scheduled-time-regexp end t)
8139 (org-time-string-to-seconds (match-string 1))
8140 (org-float-time now))))
8141 ((= dcst ?d)
8142 (let ((end (save-excursion (outline-next-heading) (point))))
8143 (if (re-search-forward org-deadline-time-regexp end t)
8144 (org-time-string-to-seconds (match-string 1))
8145 (org-float-time now))))
8146 ((= dcst ?p)
8147 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8148 (string-to-char (match-string 2))
8149 org-default-priority))
8150 ((= dcst ?r)
8151 (or (org-entry-get nil property) ""))
8152 ((= dcst ?o)
8153 (if (looking-at org-complex-heading-regexp)
8154 (- 9999 (length (member (match-string 2)
8155 org-todo-keywords-1)))))
8156 ((= dcst ?f)
8157 (if getkey-func
8158 (progn
8159 (setq tmp (funcall getkey-func))
8160 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8161 tmp)
8162 (error "Invalid key function `%s'" getkey-func)))
8163 (t (error "Invalid sorting type `%c'" sorting-type))))
8165 (cond
8166 ((= dcst ?a) 'string<)
8167 ((= dcst ?f) compare-func)
8168 ((member dcst '(?p ?t ?s ?d ?c)) '<)
8169 (t nil)))))
8170 (run-hooks 'org-after-sorting-entries-or-items-hook)
8171 (message "Sorting entries...done")))
8173 (defun org-do-sort (table what &optional with-case sorting-type)
8174 "Sort TABLE of WHAT according to SORTING-TYPE.
8175 The user will be prompted for the SORTING-TYPE if the call to this
8176 function does not specify it. WHAT is only for the prompt, to indicate
8177 what is being sorted. The sorting key will be extracted from
8178 the car of the elements of the table.
8179 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8180 (unless sorting-type
8181 (message
8182 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
8183 what)
8184 (setq sorting-type (read-char-exclusive)))
8185 (let ((dcst (downcase sorting-type))
8186 extractfun comparefun)
8187 ;; Define the appropriate functions
8188 (cond
8189 ((= dcst ?n)
8190 (setq extractfun 'string-to-number
8191 comparefun (if (= dcst sorting-type) '< '>)))
8192 ((= dcst ?a)
8193 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8194 (lambda(x) (downcase (org-sort-remove-invisible x))))
8195 comparefun (if (= dcst sorting-type)
8196 'string<
8197 (lambda (a b) (and (not (string< a b))
8198 (not (string= a b)))))))
8199 ((= dcst ?t)
8200 (setq extractfun
8201 (lambda (x)
8202 (if (or (string-match org-ts-regexp x)
8203 (string-match org-ts-regexp-both x))
8204 (org-float-time
8205 (org-time-string-to-time (match-string 0 x)))
8207 comparefun (if (= dcst sorting-type) '< '>)))
8208 (t (error "Invalid sorting type `%c'" sorting-type)))
8210 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8211 table)
8212 (lambda (a b) (funcall comparefun (car a) (car b))))))
8215 ;;; The orgstruct minor mode
8217 ;; Define a minor mode which can be used in other modes in order to
8218 ;; integrate the org-mode structure editing commands.
8220 ;; This is really a hack, because the org-mode structure commands use
8221 ;; keys which normally belong to the major mode. Here is how it
8222 ;; works: The minor mode defines all the keys necessary to operate the
8223 ;; structure commands, but wraps the commands into a function which
8224 ;; tests if the cursor is currently at a headline or a plain list
8225 ;; item. If that is the case, the structure command is used,
8226 ;; temporarily setting many Org-mode variables like regular
8227 ;; expressions for filling etc. However, when any of those keys is
8228 ;; used at a different location, function uses `key-binding' to look
8229 ;; up if the key has an associated command in another currently active
8230 ;; keymap (minor modes, major mode, global), and executes that
8231 ;; command. There might be problems if any of the keys is otherwise
8232 ;; used as a prefix key.
8234 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
8235 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
8236 ;; addresses this by checking explicitly for both bindings.
8238 (defvar orgstruct-mode-map (make-sparse-keymap)
8239 "Keymap for the minor `orgstruct-mode'.")
8241 (defvar org-local-vars nil
8242 "List of local variables, for use by `orgstruct-mode'.")
8244 ;;;###autoload
8245 (define-minor-mode orgstruct-mode
8246 "Toggle the minor mode `orgstruct-mode'.
8247 This mode is for using Org-mode structure commands in other
8248 modes. The following keys behave as if Org-mode were active, if
8249 the cursor is on a headline, or on a plain list item (both as
8250 defined by Org-mode).
8252 M-up Move entry/item up
8253 M-down Move entry/item down
8254 M-left Promote
8255 M-right Demote
8256 M-S-up Move entry/item up
8257 M-S-down Move entry/item down
8258 M-S-left Promote subtree
8259 M-S-right Demote subtree
8260 M-q Fill paragraph and items like in Org-mode
8261 C-c ^ Sort entries
8262 C-c - Cycle list bullet
8263 TAB Cycle item visibility
8264 M-RET Insert new heading/item
8265 S-M-RET Insert new TODO heading / Checkbox item
8266 C-c C-c Set tags / toggle checkbox"
8267 nil " OrgStruct" nil
8268 (org-load-modules-maybe)
8269 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
8271 ;;;###autoload
8272 (defun turn-on-orgstruct ()
8273 "Unconditionally turn on `orgstruct-mode'."
8274 (orgstruct-mode 1))
8276 (defun orgstruct++-mode (&optional arg)
8277 "Toggle `orgstruct-mode', the enhanced version of it.
8278 In addition to setting orgstruct-mode, this also exports all indentation
8279 and autofilling variables from org-mode into the buffer. It will also
8280 recognize item context in multiline items.
8281 Note that turning off orgstruct-mode will *not* remove the
8282 indentation/paragraph settings. This can only be done by refreshing the
8283 major mode, for example with \\[normal-mode]."
8284 (interactive "P")
8285 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8286 (if (< arg 1)
8287 (orgstruct-mode -1)
8288 (orgstruct-mode 1)
8289 (let (var val)
8290 (mapc
8291 (lambda (x)
8292 (when (string-match
8293 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
8294 (symbol-name (car x)))
8295 (setq var (car x) val (nth 1 x))
8296 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8297 org-local-vars)
8298 (org-set-local 'orgstruct-is-++ t))))
8300 (defvar orgstruct-is-++ nil
8301 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8302 (make-variable-buffer-local 'orgstruct-is-++)
8304 ;;;###autoload
8305 (defun turn-on-orgstruct++ ()
8306 "Unconditionally turn on `orgstruct++-mode'."
8307 (orgstruct++-mode 1))
8309 (defun orgstruct-error ()
8310 "Error when there is no default binding for a structure key."
8311 (interactive)
8312 (error "This key has no function outside structure elements"))
8314 (defun orgstruct-setup ()
8315 "Setup orgstruct keymaps."
8316 (let ((nfunc 0)
8317 (bindings
8318 (list
8319 '([(meta up)] org-metaup)
8320 '([(meta down)] org-metadown)
8321 '([(meta left)] org-metaleft)
8322 '([(meta right)] org-metaright)
8323 '([(meta shift up)] org-shiftmetaup)
8324 '([(meta shift down)] org-shiftmetadown)
8325 '([(meta shift left)] org-shiftmetaleft)
8326 '([(meta shift right)] org-shiftmetaright)
8327 '([?\e (up)] org-metaup)
8328 '([?\e (down)] org-metadown)
8329 '([?\e (left)] org-metaleft)
8330 '([?\e (right)] org-metaright)
8331 '([?\e (shift up)] org-shiftmetaup)
8332 '([?\e (shift down)] org-shiftmetadown)
8333 '([?\e (shift left)] org-shiftmetaleft)
8334 '([?\e (shift right)] org-shiftmetaright)
8335 '([(shift up)] org-shiftup)
8336 '([(shift down)] org-shiftdown)
8337 '([(shift left)] org-shiftleft)
8338 '([(shift right)] org-shiftright)
8339 '("\C-c\C-c" org-ctrl-c-ctrl-c)
8340 '("\M-q" fill-paragraph)
8341 '("\C-c^" org-sort)
8342 '("\C-c-" org-cycle-list-bullet)))
8343 elt key fun cmd)
8344 (while (setq elt (pop bindings))
8345 (setq nfunc (1+ nfunc))
8346 (setq key (org-key (car elt))
8347 fun (nth 1 elt)
8348 cmd (orgstruct-make-binding fun nfunc key))
8349 (org-defkey orgstruct-mode-map key cmd))
8351 ;; Special treatment needed for TAB and RET
8352 (org-defkey orgstruct-mode-map [(tab)]
8353 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
8354 (org-defkey orgstruct-mode-map "\C-i"
8355 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
8357 (org-defkey orgstruct-mode-map "\M-\C-m"
8358 (orgstruct-make-binding 'org-insert-heading 105
8359 "\M-\C-m" [(meta return)]))
8360 (org-defkey orgstruct-mode-map [(meta return)]
8361 (orgstruct-make-binding 'org-insert-heading 106
8362 [(meta return)] "\M-\C-m"))
8364 (org-defkey orgstruct-mode-map [(shift meta return)]
8365 (orgstruct-make-binding 'org-insert-todo-heading 107
8366 [(meta return)] "\M-\C-m"))
8368 (org-defkey orgstruct-mode-map "\e\C-m"
8369 (orgstruct-make-binding 'org-insert-heading 108
8370 "\e\C-m" [?\e (return)]))
8371 (org-defkey orgstruct-mode-map [?\e (return)]
8372 (orgstruct-make-binding 'org-insert-heading 109
8373 [?\e (return)] "\e\C-m"))
8374 (org-defkey orgstruct-mode-map [?\e (shift return)]
8375 (orgstruct-make-binding 'org-insert-todo-heading 110
8376 [?\e (return)] "\e\C-m"))
8378 (unless org-local-vars
8379 (setq org-local-vars (org-get-local-variables)))
8383 (defun orgstruct-make-binding (fun n &rest keys)
8384 "Create a function for binding in the structure minor mode.
8385 FUN is the command to call inside a table. N is used to create a unique
8386 command name. KEYS are keys that should be checked in for a command
8387 to execute outside of tables."
8388 (eval
8389 (list 'defun
8390 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
8391 '(arg)
8392 (concat "In Structure, run `" (symbol-name fun) "'.\n"
8393 "Outside of structure, run the binding of `"
8394 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
8395 "'.")
8396 '(interactive "p")
8397 (list 'if
8398 `(org-context-p 'headline 'item
8399 (and orgstruct-is-++
8400 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
8401 'item-body))
8402 (list 'org-run-like-in-org-mode (list 'quote fun))
8403 (list 'let '(orgstruct-mode)
8404 (list 'call-interactively
8405 (append '(or)
8406 (mapcar (lambda (k)
8407 (list 'key-binding k))
8408 keys)
8409 '('orgstruct-error))))))))
8411 (defun org-context-p (&rest contexts)
8412 "Check if local context is any of CONTEXTS.
8413 Possible values in the list of contexts are `table', `headline', and `item'."
8414 (let ((pos (point)))
8415 (goto-char (point-at-bol))
8416 (prog1 (or (and (memq 'table contexts)
8417 (looking-at "[ \t]*|"))
8418 (and (memq 'headline contexts)
8419 (looking-at org-outline-regexp))
8420 (and (memq 'item contexts)
8421 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
8422 (and (memq 'item-body contexts)
8423 (org-in-item-p)))
8424 (goto-char pos))))
8426 (defun org-get-local-variables ()
8427 "Return a list of all local variables in an org-mode buffer."
8428 (let (varlist)
8429 (with-current-buffer (get-buffer-create "*Org tmp*")
8430 (erase-buffer)
8431 (org-mode)
8432 (setq varlist (buffer-local-variables)))
8433 (kill-buffer "*Org tmp*")
8434 (delq nil
8435 (mapcar
8436 (lambda (x)
8437 (setq x
8438 (if (symbolp x)
8439 (list x)
8440 (list (car x) (list 'quote (cdr x)))))
8441 (if (string-match
8442 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
8443 (symbol-name (car x)))
8444 x nil))
8445 varlist))))
8447 (defun org-clone-local-variables (from-buffer &optional regexp)
8448 "Clone local variables from FROM-BUFFER.
8449 Optional argument REGEXP selects variables to clone."
8450 (mapc
8451 (lambda (pair)
8452 (and (symbolp (car pair))
8453 (or (null regexp)
8454 (string-match regexp (symbol-name (car pair))))
8455 (set (make-local-variable (car pair))
8456 (cdr pair))))
8457 (buffer-local-variables from-buffer)))
8459 ;;;###autoload
8460 (defun org-run-like-in-org-mode (cmd)
8461 "Run a command, pretending that the current buffer is in Org-mode.
8462 This will temporarily bind local variables that are typically bound in
8463 Org-mode to the values they have in Org-mode, and then interactively
8464 call CMD."
8465 (org-load-modules-maybe)
8466 (unless org-local-vars
8467 (setq org-local-vars (org-get-local-variables)))
8468 (eval (list 'let org-local-vars
8469 (list 'call-interactively (list 'quote cmd)))))
8471 ;;;; Archiving
8473 (defun org-get-category (&optional pos force-refresh)
8474 "Get the category applying to position POS."
8475 (if force-refresh (org-refresh-category-properties))
8476 (let ((pos (or pos (point))))
8477 (or (get-text-property pos 'org-category)
8478 (progn (org-refresh-category-properties)
8479 (get-text-property pos 'org-category)))))
8481 (defun org-refresh-category-properties ()
8482 "Refresh category text properties in the buffer."
8483 (let ((def-cat (cond
8484 ((null org-category)
8485 (if buffer-file-name
8486 (file-name-sans-extension
8487 (file-name-nondirectory buffer-file-name))
8488 "???"))
8489 ((symbolp org-category) (symbol-name org-category))
8490 (t org-category)))
8491 beg end cat pos optionp)
8492 (org-unmodified
8493 (save-excursion
8494 (save-restriction
8495 (widen)
8496 (goto-char (point-min))
8497 (put-text-property (point) (point-max) 'org-category def-cat)
8498 (while (re-search-forward
8499 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8500 (setq pos (match-end 0)
8501 optionp (equal (char-after (match-beginning 0)) ?#)
8502 cat (org-trim (match-string 2)))
8503 (if optionp
8504 (setq beg (point-at-bol) end (point-max))
8505 (org-back-to-heading t)
8506 (setq beg (point) end (org-end-of-subtree t t)))
8507 (put-text-property beg end 'org-category cat)
8508 (put-text-property beg end 'org-category-position beg)
8509 (goto-char pos)))))))
8512 ;;;; Link Stuff
8514 ;;; Link abbreviations
8516 (defun org-link-expand-abbrev (link)
8517 "Apply replacements as defined in `org-link-abbrev-alist."
8518 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
8519 (let* ((key (match-string 1 link))
8520 (as (or (assoc key org-link-abbrev-alist-local)
8521 (assoc key org-link-abbrev-alist)))
8522 (tag (and (match-end 2) (match-string 3 link)))
8523 rpl)
8524 (if (not as)
8525 link
8526 (setq rpl (cdr as))
8527 (cond
8528 ((symbolp rpl) (funcall rpl tag))
8529 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
8530 ((string-match "%h" rpl)
8531 (replace-match (url-hexify-string (or tag "")) t t rpl))
8532 (t (concat rpl tag)))))
8533 link))
8535 ;;; Storing and inserting links
8537 (defvar org-insert-link-history nil
8538 "Minibuffer history for links inserted with `org-insert-link'.")
8540 (defvar org-stored-links nil
8541 "Contains the links stored with `org-store-link'.")
8543 (defvar org-store-link-plist nil
8544 "Plist with info about the most recently link created with `org-store-link'.")
8546 (defvar org-link-protocols nil
8547 "Link protocols added to Org-mode using `org-add-link-type'.")
8549 (defvar org-store-link-functions nil
8550 "List of functions that are called to create and store a link.
8551 Each function will be called in turn until one returns a non-nil
8552 value. Each function should check if it is responsible for creating
8553 this link (for example by looking at the major mode).
8554 If not, it must exit and return nil.
8555 If yes, it should return a non-nil value after a calling
8556 `org-store-link-props' with a list of properties and values.
8557 Special properties are:
8559 :type The link prefix, like \"http\". This must be given.
8560 :link The link, like \"http://www.astro.uva.nl/~dominik\".
8561 This is obligatory as well.
8562 :description Optional default description for the second pair
8563 of brackets in an Org-mode link. The user can still change
8564 this when inserting this link into an Org-mode buffer.
8566 In addition to these, any additional properties can be specified
8567 and then used in remember templates.")
8569 (defun org-add-link-type (type &optional follow export)
8570 "Add TYPE to the list of `org-link-types'.
8571 Re-compute all regular expressions depending on `org-link-types'
8573 FOLLOW and EXPORT are two functions.
8575 FOLLOW should take the link path as the single argument and do whatever
8576 is necessary to follow the link, for example find a file or display
8577 a mail message.
8579 EXPORT should format the link path for export to one of the export formats.
8580 It should be a function accepting three arguments:
8582 path the path of the link, the text after the prefix (like \"http:\")
8583 desc the description of the link, if any, or a description added by
8584 org-export-normalize-links if there is none
8585 format the export format, a symbol like `html' or `latex' or `ascii'..
8587 The function may use the FORMAT information to return different values
8588 depending on the format. The return value will be put literally into
8589 the exported file. If the return value is nil, this means Org should
8590 do what it normally does with links which do not have EXPORT defined.
8592 Org-mode has a built-in default for exporting links. If you are happy with
8593 this default, there is no need to define an export function for the link
8594 type. For a simple example of an export function, see `org-bbdb.el'."
8595 (add-to-list 'org-link-types type t)
8596 (org-make-link-regexps)
8597 (if (assoc type org-link-protocols)
8598 (setcdr (assoc type org-link-protocols) (list follow export))
8599 (push (list type follow export) org-link-protocols)))
8601 (defvar org-agenda-buffer-name)
8603 ;;;###autoload
8604 (defun org-store-link (arg)
8605 "\\<org-mode-map>Store an org-link to the current location.
8606 This link is added to `org-stored-links' and can later be inserted
8607 into an org-buffer with \\[org-insert-link].
8609 For some link types, a prefix arg is interpreted:
8610 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
8611 For file links, arg negates `org-context-in-file-links'."
8612 (interactive "P")
8613 (org-load-modules-maybe)
8614 (setq org-store-link-plist nil) ; reset
8615 (org-with-limited-levels
8616 (let (link cpltxt desc description search txt custom-id agenda-link)
8617 (cond
8619 ((run-hook-with-args-until-success 'org-store-link-functions)
8620 (setq link (plist-get org-store-link-plist :link)
8621 desc (or (plist-get org-store-link-plist :description) link)))
8623 ((equal (buffer-name) "*Org Edit Src Example*")
8624 (let (label gc)
8625 (while (or (not label)
8626 (save-excursion
8627 (save-restriction
8628 (widen)
8629 (goto-char (point-min))
8630 (re-search-forward
8631 (regexp-quote (format org-coderef-label-format label))
8632 nil t))))
8633 (when label (message "Label exists already") (sit-for 2))
8634 (setq label (read-string "Code line label: " label)))
8635 (end-of-line 1)
8636 (setq link (format org-coderef-label-format label))
8637 (setq gc (- 79 (length link)))
8638 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
8639 (insert link)
8640 (setq link (concat "(" label ")") desc nil)))
8642 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
8643 ;; We are in the agenda, link to referenced location
8644 (let ((m (or (get-text-property (point) 'org-hd-marker)
8645 (get-text-property (point) 'org-marker))))
8646 (when m
8647 (org-with-point-at m
8648 (setq agenda-link
8649 (if (org-called-interactively-p 'any)
8650 (call-interactively 'org-store-link)
8651 (org-store-link nil)))))))
8653 ((eq major-mode 'calendar-mode)
8654 (let ((cd (calendar-cursor-to-date)))
8655 (setq link
8656 (format-time-string
8657 (car org-time-stamp-formats)
8658 (apply 'encode-time
8659 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
8660 nil nil nil))))
8661 (org-store-link-props :type "calendar" :date cd)))
8663 ((eq major-mode 'w3-mode)
8664 (setq cpltxt (if (and (buffer-name)
8665 (not (string-match "Untitled" (buffer-name))))
8666 (buffer-name)
8667 (url-view-url t))
8668 link (org-make-link (url-view-url t)))
8669 (org-store-link-props :type "w3" :url (url-view-url t)))
8671 ((eq major-mode 'w3m-mode)
8672 (setq cpltxt (or w3m-current-title w3m-current-url)
8673 link (org-make-link w3m-current-url))
8674 (org-store-link-props :type "w3m" :url (url-view-url t)))
8676 ((setq search (run-hook-with-args-until-success
8677 'org-create-file-search-functions))
8678 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
8679 "::" search))
8680 (setq cpltxt (or description link)))
8682 ((eq major-mode 'image-mode)
8683 (setq cpltxt (concat "file:"
8684 (abbreviate-file-name buffer-file-name))
8685 link (org-make-link cpltxt))
8686 (org-store-link-props :type "image" :file buffer-file-name))
8688 ((eq major-mode 'dired-mode)
8689 ;; link to the file in the current line
8690 (let ((file (dired-get-filename nil t)))
8691 (setq file (if file
8692 (abbreviate-file-name
8693 (expand-file-name (dired-get-filename nil t)))
8694 ;; otherwise, no file so use current directory.
8695 default-directory))
8696 (setq cpltxt (concat "file:" file)
8697 link (org-make-link cpltxt))))
8699 ((and (buffer-file-name (buffer-base-buffer)) (eq major-mode 'org-mode))
8700 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
8701 (cond
8702 ((org-in-regexp "<<\\(.*?\\)>>")
8703 (setq cpltxt
8704 (concat "file:"
8705 (abbreviate-file-name
8706 (buffer-file-name (buffer-base-buffer)))
8707 "::" (match-string 1))
8708 link (org-make-link cpltxt)))
8709 ((and (featurep 'org-id)
8710 (or (eq org-link-to-org-use-id t)
8711 (and (eq org-link-to-org-use-id 'create-if-interactive)
8712 (org-called-interactively-p 'any))
8713 (and (eq org-link-to-org-use-id
8714 'create-if-interactive-and-no-custom-id)
8715 (org-called-interactively-p 'any)
8716 (not custom-id))
8717 (and org-link-to-org-use-id
8718 (org-entry-get nil "ID"))))
8719 ;; We can make a link using the ID.
8720 (setq link (condition-case nil
8721 (prog1 (org-id-store-link)
8722 (setq desc (plist-get org-store-link-plist
8723 :description)))
8724 (error
8725 ;; probably before first headline, link to file only
8726 (concat "file:"
8727 (abbreviate-file-name
8728 (buffer-file-name (buffer-base-buffer))))))))
8730 ;; Just link to current headline
8731 (setq cpltxt (concat "file:"
8732 (abbreviate-file-name
8733 (buffer-file-name (buffer-base-buffer)))))
8734 ;; Add a context search string
8735 (when (org-xor org-context-in-file-links arg)
8736 (setq txt (cond
8737 ((org-on-heading-p) nil)
8738 ((org-region-active-p)
8739 (buffer-substring (region-beginning) (region-end)))
8740 (t nil)))
8741 (when (or (null txt) (string-match "\\S-" txt))
8742 (setq cpltxt
8743 (concat cpltxt "::"
8744 (condition-case nil
8745 (org-make-org-heading-search-string txt)
8746 (error "")))
8747 desc (or (nth 4 (ignore-errors
8748 (org-heading-components))) "NONE"))))
8749 (if (string-match "::\\'" cpltxt)
8750 (setq cpltxt (substring cpltxt 0 -2)))
8751 (setq link (org-make-link cpltxt)))))
8753 ((buffer-file-name (buffer-base-buffer))
8754 ;; Just link to this file here.
8755 (setq cpltxt (concat "file:"
8756 (abbreviate-file-name
8757 (buffer-file-name (buffer-base-buffer)))))
8758 ;; Add a context string
8759 (when (org-xor org-context-in-file-links arg)
8760 (setq txt (if (org-region-active-p)
8761 (buffer-substring (region-beginning) (region-end))
8762 (buffer-substring (point-at-bol) (point-at-eol))))
8763 ;; Only use search option if there is some text.
8764 (when (string-match "\\S-" txt)
8765 (setq cpltxt
8766 (concat cpltxt "::" (org-make-org-heading-search-string txt))
8767 desc "NONE")))
8768 (setq link (org-make-link cpltxt)))
8770 ((org-called-interactively-p 'interactive)
8771 (error "Cannot link to a buffer which is not visiting a file"))
8773 (t (setq link nil)))
8775 (if (consp link) (setq cpltxt (car link) link (cdr link)))
8776 (setq link (or link cpltxt)
8777 desc (or desc cpltxt))
8778 (if (equal desc "NONE") (setq desc nil))
8780 (if (and (or (org-called-interactively-p 'any) executing-kbd-macro) link)
8781 (progn
8782 (setq org-stored-links
8783 (cons (list link desc) org-stored-links))
8784 (message "Stored: %s" (or desc link))
8785 (when custom-id
8786 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
8787 "::#" custom-id))
8788 (setq org-stored-links
8789 (cons (list link desc) org-stored-links))))
8790 (or agenda-link (and link (org-make-link-string link desc)))))))
8792 (defun org-store-link-props (&rest plist)
8793 "Store link properties, extract names and addresses."
8794 (let (x adr)
8795 (when (setq x (plist-get plist :from))
8796 (setq adr (mail-extract-address-components x))
8797 (setq plist (plist-put plist :fromname (car adr)))
8798 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
8799 (when (setq x (plist-get plist :to))
8800 (setq adr (mail-extract-address-components x))
8801 (setq plist (plist-put plist :toname (car adr)))
8802 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
8803 (let ((from (plist-get plist :from))
8804 (to (plist-get plist :to)))
8805 (when (and from to org-from-is-user-regexp)
8806 (setq plist
8807 (plist-put plist :fromto
8808 (if (string-match org-from-is-user-regexp from)
8809 (concat "to %t")
8810 (concat "from %f"))))))
8811 (setq org-store-link-plist plist))
8813 (defun org-add-link-props (&rest plist)
8814 "Add these properties to the link property list."
8815 (let (key value)
8816 (while plist
8817 (setq key (pop plist) value (pop plist))
8818 (setq org-store-link-plist
8819 (plist-put org-store-link-plist key value)))))
8821 (defun org-email-link-description (&optional fmt)
8822 "Return the description part of an email link.
8823 This takes information from `org-store-link-plist' and formats it
8824 according to FMT (default from `org-email-link-description-format')."
8825 (setq fmt (or fmt org-email-link-description-format))
8826 (let* ((p org-store-link-plist)
8827 (to (plist-get p :toaddress))
8828 (from (plist-get p :fromaddress))
8829 (table
8830 (list
8831 (cons "%c" (plist-get p :fromto))
8832 (cons "%F" (plist-get p :from))
8833 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
8834 (cons "%T" (plist-get p :to))
8835 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
8836 (cons "%s" (plist-get p :subject))
8837 (cons "%d" (plist-get p :date))
8838 (cons "%m" (plist-get p :message-id)))))
8839 (when (string-match "%c" fmt)
8840 ;; Check if the user wrote this message
8841 (if (and org-from-is-user-regexp from to
8842 (save-match-data (string-match org-from-is-user-regexp from)))
8843 (setq fmt (replace-match "to %t" t t fmt))
8844 (setq fmt (replace-match "from %f" t t fmt))))
8845 (org-replace-escapes fmt table)))
8847 (defun org-make-org-heading-search-string (&optional string heading)
8848 "Make search string for STRING or current headline."
8849 (interactive)
8850 (let ((s (or string (org-get-heading)))
8851 (lines org-context-in-file-links))
8852 (unless (and string (not heading))
8853 ;; We are using a headline, clean up garbage in there.
8854 (if (string-match org-todo-regexp s)
8855 (setq s (replace-match "" t t s)))
8856 (if (string-match (org-re ":[[:alnum:]_@#%:]+:[ \t]*$") s)
8857 (setq s (replace-match "" t t s)))
8858 (setq s (org-trim s))
8859 (if (string-match (concat "^\\(" org-quote-string "\\|"
8860 org-comment-string "\\)") s)
8861 (setq s (replace-match "" t t s)))
8862 (while (string-match org-ts-regexp s)
8863 (setq s (replace-match "" t t s))))
8864 (or string (setq s (concat "*" s))) ; Add * for headlines
8865 (when (and string (integerp lines) (> lines 0))
8866 (let ((slines (org-split-string s "\n")))
8867 (when (< lines (length slines))
8868 (setq s (mapconcat
8869 'identity
8870 (reverse (nthcdr (- (length slines) lines)
8871 (reverse slines))) "\n")))))
8872 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
8874 (defun org-make-link (&rest strings)
8875 "Concatenate STRINGS."
8876 (apply 'concat strings))
8878 (defun org-make-link-string (link &optional description)
8879 "Make a link with brackets, consisting of LINK and DESCRIPTION."
8880 (unless (string-match "\\S-" link)
8881 (error "Empty link"))
8882 (when (and description
8883 (stringp description)
8884 (not (string-match "\\S-" description)))
8885 (setq description nil))
8886 (when (stringp description)
8887 ;; Remove brackets from the description, they are fatal.
8888 (while (string-match "\\[" description)
8889 (setq description (replace-match "{" t t description)))
8890 (while (string-match "\\]" description)
8891 (setq description (replace-match "}" t t description))))
8892 (when (equal link description)
8893 ;; No description needed, it is identical
8894 (setq description nil))
8895 (when (and (not description)
8896 (not (string-match (org-image-file-name-regexp) link))
8897 (not (equal link (org-link-escape link))))
8898 (setq description (org-extract-attributes link)))
8899 (setq link
8900 (cond ((string-match (org-image-file-name-regexp) link) link)
8901 ((string-match org-link-types-re link)
8902 (concat (match-string 1 link)
8903 (org-link-escape (substring link (match-end 1)))))
8904 (t (org-link-escape link))))
8905 (concat "[[" link "]"
8906 (if description (concat "[" description "]") "")
8907 "]"))
8909 (defconst org-link-escape-chars
8910 '(?\ ?\[ ?\] ?\; ?\= ?\+)
8911 "List of characters that should be escaped in link.
8912 This is the list that is used for internal purposes.")
8914 (defvar org-url-encoding-use-url-hexify nil)
8916 (defconst org-link-escape-chars-browser
8917 '(?\ )
8918 "List of escapes for characters that are problematic in links.
8919 This is the list that is used before handing over to the browser.")
8921 (defun org-link-escape (text &optional table merge)
8922 "Return percent escaped representation of TEXT.
8923 TEXT is a string with the text to escape.
8924 Optional argument TABLE is a list with characters that should be
8925 escaped. When nil, `org-link-escape-chars' is used.
8926 If optional argument MERGE is set, merge TABLE into
8927 `org-link-escape-chars'."
8928 (if (and org-url-encoding-use-url-hexify (not table))
8929 (url-hexify-string text)
8930 (cond
8931 ((and table merge)
8932 (mapc (lambda (defchr)
8933 (unless (member defchr table)
8934 (setq table (cons defchr table)))) org-link-escape-chars))
8935 ((null table)
8936 (setq table org-link-escape-chars)))
8937 (mapconcat
8938 (lambda (char)
8939 (if (or (member char table)
8940 (< char 32) (= char 37) (> char 126))
8941 (mapconcat (lambda (sequence-element)
8942 (format "%%%.2X" sequence-element))
8943 (or (encode-coding-char char 'utf-8)
8944 (error "Unable to percent escape character: %s"
8945 (char-to-string char))) "")
8946 (char-to-string char))) text "")))
8948 (defun org-link-unescape (str)
8949 "Unhex hexified Unicode strings as returned from the JavaScript function
8950 encodeURIComponent. E.g. `%C3%B6' is the german Umlaut `ö'."
8951 (unless (and (null str) (string= "" str))
8952 (let ((pos 0) (case-fold-search t) unhexed)
8953 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
8954 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
8955 (setq str (replace-match unhexed t t str))
8956 (setq pos (+ pos (length unhexed))))))
8957 str)
8959 (defun org-link-unescape-compound (hex)
8960 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German Umlaut `ö'.
8961 Note: this function also decodes single byte encodings like
8962 `%E1' (\"á\") if not followed by another `%[A-F0-9]{2}' group."
8963 (save-match-data
8964 (let* ((bytes (cdr (split-string hex "%")))
8965 (ret "")
8966 (eat 0)
8967 (sum 0))
8968 (while bytes
8969 (let* ((val (string-to-number (pop bytes) 16))
8970 (shift-xor
8971 (if (= 0 eat)
8972 (cond
8973 ((>= val 252) (cons 6 252))
8974 ((>= val 248) (cons 5 248))
8975 ((>= val 240) (cons 4 240))
8976 ((>= val 224) (cons 3 224))
8977 ((>= val 192) (cons 2 192))
8978 (t (cons 0 0)))
8979 (cons 6 128))))
8980 (if (>= val 192) (setq eat (car shift-xor)))
8981 (setq val (logxor val (cdr shift-xor)))
8982 (setq sum (+ (lsh sum (car shift-xor)) val))
8983 (if (> eat 0) (setq eat (- eat 1)))
8984 (cond
8985 ((= 0 eat) ;multi byte
8986 (setq ret (concat ret (org-char-to-string sum)))
8987 (setq sum 0))
8988 ((not bytes) ; single byte(s)
8989 (setq ret (org-link-unescape-single-byte-sequence hex))))
8990 )) ;; end (while bytes
8991 ret )))
8993 (defun org-link-unescape-single-byte-sequence (hex)
8994 "Unhexify hex-encoded single byte character sequences."
8995 (mapconcat (lambda (byte)
8996 (char-to-string (string-to-number byte 16)))
8997 (cdr (split-string hex "%")) ""))
8999 (defun org-xor (a b)
9000 "Exclusive or."
9001 (if a (not b) b))
9003 (defun org-fixup-message-id-for-http (s)
9004 "Replace special characters in a message id, so it can be used in an http query."
9005 (when (string-match "%" s)
9006 (setq s (mapconcat (lambda (c)
9007 (if (eq c ?%)
9008 "%25"
9009 (char-to-string c)))
9010 s "")))
9011 (while (string-match "<" s)
9012 (setq s (replace-match "%3C" t t s)))
9013 (while (string-match ">" s)
9014 (setq s (replace-match "%3E" t t s)))
9015 (while (string-match "@" s)
9016 (setq s (replace-match "%40" t t s)))
9019 ;;;###autoload
9020 (defun org-insert-link-global ()
9021 "Insert a link like Org-mode does.
9022 This command can be called in any mode to insert a link in Org-mode syntax."
9023 (interactive)
9024 (org-load-modules-maybe)
9025 (org-run-like-in-org-mode 'org-insert-link))
9027 (defun org-insert-link (&optional complete-file link-location default-description)
9028 "Insert a link. At the prompt, enter the link.
9030 Completion can be used to insert any of the link protocol prefixes like
9031 http or ftp in use.
9033 The history can be used to select a link previously stored with
9034 `org-store-link'. When the empty string is entered (i.e. if you just
9035 press RET at the prompt), the link defaults to the most recently
9036 stored link. As SPC triggers completion in the minibuffer, you need to
9037 use M-SPC or C-q SPC to force the insertion of a space character.
9039 You will also be prompted for a description, and if one is given, it will
9040 be displayed in the buffer instead of the link.
9042 If there is already a link at point, this command will allow you to edit link
9043 and description parts.
9045 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9046 be selected using completion. The path to the file will be relative to the
9047 current directory if the file is in the current directory or a subdirectory.
9048 Otherwise, the link will be the absolute path as completed in the minibuffer
9049 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9050 option `org-link-file-path-type'.
9052 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9053 the current directory or below.
9055 With three \\[universal-argument] prefixes, negate the meaning of
9056 `org-keep-stored-link-after-insertion'.
9058 If `org-make-link-description-function' is non-nil, this function will be
9059 called with the link target, and the result will be the default
9060 link description.
9062 If the LINK-LOCATION parameter is non-nil, this value will be
9063 used as the link location instead of reading one interactively.
9065 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9066 be used as the default description."
9067 (interactive "P")
9068 (let* ((wcf (current-window-configuration))
9069 (region (if (org-region-active-p)
9070 (buffer-substring (region-beginning) (region-end))))
9071 (remove (and region (list (region-beginning) (region-end))))
9072 (desc region)
9073 tmphist ; byte-compile incorrectly complains about this
9074 (link link-location)
9075 entry file all-prefixes)
9076 (cond
9077 (link-location) ; specified by arg, just use it.
9078 ((org-in-regexp org-bracket-link-regexp 1)
9079 ;; We do have a link at point, and we are going to edit it.
9080 (setq remove (list (match-beginning 0) (match-end 0)))
9081 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9082 (setq link (read-string "Link: "
9083 (org-link-unescape
9084 (org-match-string-no-properties 1)))))
9085 ((or (org-in-regexp org-angle-link-re)
9086 (org-in-regexp org-plain-link-re))
9087 ;; Convert to bracket link
9088 (setq remove (list (match-beginning 0) (match-end 0))
9089 link (read-string "Link: "
9090 (org-remove-angle-brackets (match-string 0)))))
9091 ((member complete-file '((4) (16)))
9092 ;; Completing read for file names.
9093 (setq link (org-file-complete-link complete-file)))
9095 ;; Read link, with completion for stored links.
9096 (with-output-to-temp-buffer "*Org Links*"
9097 (princ "Insert a link.
9098 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9099 (when org-stored-links
9100 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9101 (princ (mapconcat
9102 (lambda (x)
9103 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
9104 (reverse org-stored-links) "\n"))))
9105 (let ((cw (selected-window)))
9106 (select-window (get-buffer-window "*Org Links*" 'visible))
9107 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9108 (unless (pos-visible-in-window-p (point-max))
9109 (org-fit-window-to-buffer))
9110 (and (window-live-p cw) (select-window cw)))
9111 ;; Fake a link history, containing the stored links.
9112 (setq tmphist (append (mapcar 'car org-stored-links)
9113 org-insert-link-history))
9114 (setq all-prefixes (append (mapcar 'car org-link-abbrev-alist-local)
9115 (mapcar 'car org-link-abbrev-alist)
9116 org-link-types))
9117 (unwind-protect
9118 (progn
9119 (setq link
9120 (let ((org-completion-use-ido nil)
9121 (org-completion-use-iswitchb nil))
9122 (org-completing-read
9123 "Link: "
9124 (append
9125 (mapcar (lambda (x) (list (concat x ":")))
9126 all-prefixes)
9127 (mapcar 'car org-stored-links))
9128 nil nil nil
9129 'tmphist
9130 (car (car org-stored-links)))))
9131 (if (not (string-match "\\S-" link))
9132 (error "No link selected"))
9133 (if (or (member link all-prefixes)
9134 (and (equal ":" (substring link -1))
9135 (member (substring link 0 -1) all-prefixes)
9136 (setq link (substring link 0 -1))))
9137 (setq link (org-link-try-special-completion link))))
9138 (set-window-configuration wcf)
9139 (kill-buffer "*Org Links*"))
9140 (setq entry (assoc link org-stored-links))
9141 (or entry (push link org-insert-link-history))
9142 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9143 (not org-keep-stored-link-after-insertion))
9144 (setq org-stored-links (delq (assoc link org-stored-links)
9145 org-stored-links)))
9146 (setq desc (or desc (nth 1 entry)))))
9148 (if (string-match org-plain-link-re link)
9149 ;; URL-like link, normalize the use of angular brackets.
9150 (setq link (org-make-link (org-remove-angle-brackets link))))
9152 ;; Check if we are linking to the current file with a search option
9153 ;; If yes, simplify the link by using only the search option.
9154 (when (and buffer-file-name
9155 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
9156 (let* ((path (match-string 1 link))
9157 (case-fold-search nil)
9158 (search (match-string 2 link)))
9159 (save-match-data
9160 (if (equal (file-truename buffer-file-name) (file-truename path))
9161 ;; We are linking to this same file, with a search option
9162 (setq link search)))))
9164 ;; Check if we can/should use a relative path. If yes, simplify the link
9165 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
9166 (let* ((type (match-string 1 link))
9167 (path (match-string 2 link))
9168 (origpath path)
9169 (case-fold-search nil))
9170 (cond
9171 ((or (eq org-link-file-path-type 'absolute)
9172 (equal complete-file '(16)))
9173 (setq path (abbreviate-file-name (expand-file-name path))))
9174 ((eq org-link-file-path-type 'noabbrev)
9175 (setq path (expand-file-name path)))
9176 ((eq org-link-file-path-type 'relative)
9177 (setq path (file-relative-name path)))
9179 (save-match-data
9180 (if (string-match (concat "^" (regexp-quote
9181 (expand-file-name
9182 (file-name-as-directory
9183 default-directory))))
9184 (expand-file-name path))
9185 ;; We are linking a file with relative path name.
9186 (setq path (substring (expand-file-name path)
9187 (match-end 0)))
9188 (setq path (abbreviate-file-name (expand-file-name path)))))))
9189 (setq link (concat type path))
9190 (if (equal desc origpath)
9191 (setq desc path))))
9193 (if org-make-link-description-function
9194 (setq desc (funcall org-make-link-description-function link desc))
9195 (if default-description (setq desc default-description)))
9197 (setq desc (read-string "Description: " desc))
9198 (unless (string-match "\\S-" desc) (setq desc nil))
9199 (if remove (apply 'delete-region remove))
9200 (insert (org-make-link-string link desc))))
9202 (defun org-link-try-special-completion (type)
9203 "If there is completion support for link type TYPE, offer it."
9204 (let ((fun (intern (concat "org-" type "-complete-link"))))
9205 (if (functionp fun)
9206 (funcall fun)
9207 (read-string "Link (no completion support): " (concat type ":")))))
9209 (defun org-file-complete-link (&optional arg)
9210 "Create a file link using completion."
9211 (let (file link)
9212 (setq file (read-file-name "File: "))
9213 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9214 (pwd1 (file-name-as-directory (abbreviate-file-name
9215 (expand-file-name ".")))))
9216 (cond
9217 ((equal arg '(16))
9218 (setq link (org-make-link
9219 "file:"
9220 (abbreviate-file-name (expand-file-name file)))))
9221 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9222 (setq link (org-make-link "file:" (match-string 1 file))))
9223 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9224 (expand-file-name file))
9225 (setq link (org-make-link
9226 "file:" (match-string 1 (expand-file-name file)))))
9227 (t (setq link (org-make-link "file:" file)))))
9228 link))
9230 (defun org-completing-read (&rest args)
9231 "Completing-read with SPACE being a normal character."
9232 (let ((enable-recursive-minibuffers t)
9233 (minibuffer-local-completion-map
9234 (copy-keymap minibuffer-local-completion-map)))
9235 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
9236 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
9237 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
9238 (apply 'org-icompleting-read args)))
9240 (defun org-completing-read-no-i (&rest args)
9241 (let (org-completion-use-ido org-completion-use-iswitchb)
9242 (apply 'org-completing-read args)))
9244 (defun org-iswitchb-completing-read (prompt choices &rest args)
9245 "Use iswitch as a completing-read replacement to choose from choices.
9246 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
9247 from."
9248 (let* ((iswitchb-use-virtual-buffers nil)
9249 (iswitchb-make-buflist-hook
9250 (lambda ()
9251 (setq iswitchb-temp-buflist choices))))
9252 (iswitchb-read-buffer prompt)))
9254 (defun org-icompleting-read (&rest args)
9255 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
9256 (org-without-partial-completion
9257 (if (and org-completion-use-ido
9258 (fboundp 'ido-completing-read)
9259 (boundp 'ido-mode) ido-mode
9260 (listp (second args)))
9261 (let ((ido-enter-matching-directory nil))
9262 (apply 'ido-completing-read (concat (car args))
9263 (if (consp (car (nth 1 args)))
9264 (mapcar 'car (nth 1 args))
9265 (nth 1 args))
9266 (cddr args)))
9267 (if (and org-completion-use-iswitchb
9268 (boundp 'iswitchb-mode) iswitchb-mode
9269 (listp (second args)))
9270 (apply 'org-iswitchb-completing-read (concat (car args))
9271 (if (consp (car (nth 1 args)))
9272 (mapcar 'car (nth 1 args))
9273 (nth 1 args))
9274 (cddr args))
9275 (apply 'completing-read args)))))
9277 (defun org-extract-attributes (s)
9278 "Extract the attributes cookie from a string and set as text property."
9279 (let (a attr (start 0) key value)
9280 (save-match-data
9281 (when (string-match "{{\\([^}]+\\)}}$" s)
9282 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
9283 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
9284 (setq key (match-string 1 a) value (match-string 2 a)
9285 start (match-end 0)
9286 attr (plist-put attr (intern key) value))))
9287 (org-add-props s nil 'org-attr attr))
9290 (defun org-extract-attributes-from-string (tag)
9291 (let (key value attr)
9292 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
9293 (setq key (match-string 1 tag) value (match-string 2 tag)
9294 tag (replace-match "" t t tag)
9295 attr (plist-put attr (intern key) value)))
9296 (cons tag attr)))
9298 (defun org-attributes-to-string (plist)
9299 "Format a property list into an HTML attribute list."
9300 (let ((s "") key value)
9301 (while plist
9302 (setq key (pop plist) value (pop plist))
9303 (and value
9304 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
9307 ;;; Opening/following a link
9309 (defvar org-link-search-failed nil)
9311 (defvar org-open-link-functions nil
9312 "Hook for functions finding a plain text link.
9313 These functions must take a single argument, the link content.
9314 They will be called for links that look like [[link text][description]]
9315 when LINK TEXT does not have a protocol like \"http:\" and does not look
9316 like a filename (e.g. \"./blue.png\").
9318 These functions will be called *before* Org attempts to resolve the
9319 link by doing text searches in the current buffer - so if you want a
9320 link \"[[target]]\" to still find \"<<target>>\", your function should
9321 handle this as a special case.
9323 When the function does handle the link, it must return a non-nil value.
9324 If it decides that it is not responsible for this link, it must return
9325 nil to indicate that that Org-mode can continue with other options
9326 like exact and fuzzy text search.")
9328 (defun org-next-link ()
9329 "Move forward to the next link.
9330 If the link is in hidden text, expose it."
9331 (interactive)
9332 (when (and org-link-search-failed (eq this-command last-command))
9333 (goto-char (point-min))
9334 (message "Link search wrapped back to beginning of buffer"))
9335 (setq org-link-search-failed nil)
9336 (let* ((pos (point))
9337 (ct (org-context))
9338 (a (assoc :link ct)))
9339 (if a (goto-char (nth 2 a)))
9340 (if (re-search-forward org-any-link-re nil t)
9341 (progn
9342 (goto-char (match-beginning 0))
9343 (if (outline-invisible-p) (org-show-context)))
9344 (goto-char pos)
9345 (setq org-link-search-failed t)
9346 (error "No further link found"))))
9348 (defun org-previous-link ()
9349 "Move backward to the previous link.
9350 If the link is in hidden text, expose it."
9351 (interactive)
9352 (when (and org-link-search-failed (eq this-command last-command))
9353 (goto-char (point-max))
9354 (message "Link search wrapped back to end of buffer"))
9355 (setq org-link-search-failed nil)
9356 (let* ((pos (point))
9357 (ct (org-context))
9358 (a (assoc :link ct)))
9359 (if a (goto-char (nth 1 a)))
9360 (if (re-search-backward org-any-link-re nil t)
9361 (progn
9362 (goto-char (match-beginning 0))
9363 (if (outline-invisible-p) (org-show-context)))
9364 (goto-char pos)
9365 (setq org-link-search-failed t)
9366 (error "No further link found"))))
9368 (defun org-translate-link (s)
9369 "Translate a link string if a translation function has been defined."
9370 (if (and org-link-translation-function
9371 (fboundp org-link-translation-function)
9372 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
9373 (progn
9374 (setq s (funcall org-link-translation-function
9375 (match-string 1) (match-string 2)))
9376 (concat (car s) ":" (cdr s)))
9379 (defun org-translate-link-from-planner (type path)
9380 "Translate a link from Emacs Planner syntax so that Org can follow it.
9381 This is still an experimental function, your mileage may vary."
9382 (cond
9383 ((member type '("http" "https" "news" "ftp"))
9384 ;; standard Internet links are the same.
9385 nil)
9386 ((and (equal type "irc") (string-match "^//" path))
9387 ;; Planner has two / at the beginning of an irc link, we have 1.
9388 ;; We should have zero, actually....
9389 (setq path (substring path 1)))
9390 ((and (equal type "lisp") (string-match "^/" path))
9391 ;; Planner has a slash, we do not.
9392 (setq type "elisp" path (substring path 1)))
9393 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9394 ;; A typical message link. Planner has the id after the final slash,
9395 ;; we separate it with a hash mark
9396 (setq path (concat (match-string 1 path) "#"
9397 (org-remove-angle-brackets (match-string 2 path)))))
9399 (cons type path))
9401 (defun org-find-file-at-mouse (ev)
9402 "Open file link or URL at mouse."
9403 (interactive "e")
9404 (mouse-set-point ev)
9405 (org-open-at-point 'in-emacs))
9407 (defun org-open-at-mouse (ev)
9408 "Open file link or URL at mouse.
9409 See the docstring of `org-open-file' for details."
9410 (interactive "e")
9411 (mouse-set-point ev)
9412 (if (eq major-mode 'org-agenda-mode)
9413 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
9414 (org-open-at-point))
9416 (defvar org-window-config-before-follow-link nil
9417 "The window configuration before following a link.
9418 This is saved in case the need arises to restore it.")
9420 (defvar org-open-link-marker (make-marker)
9421 "Marker pointing to the location where `org-open-at-point; was called.")
9423 ;;;###autoload
9424 (defun org-open-at-point-global ()
9425 "Follow a link like Org-mode does.
9426 This command can be called in any mode to follow a link that has
9427 Org-mode syntax."
9428 (interactive)
9429 (org-run-like-in-org-mode 'org-open-at-point))
9431 ;;;###autoload
9432 (defun org-open-link-from-string (s &optional arg reference-buffer)
9433 "Open a link in the string S, as if it was in Org-mode."
9434 (interactive "sLink: \nP")
9435 (let ((reference-buffer (or reference-buffer (current-buffer))))
9436 (with-temp-buffer
9437 (let ((org-inhibit-startup t))
9438 (org-mode)
9439 (insert s)
9440 (goto-char (point-min))
9441 (when reference-buffer
9442 (setq org-link-abbrev-alist-local
9443 (with-current-buffer reference-buffer
9444 org-link-abbrev-alist-local)))
9445 (org-open-at-point arg reference-buffer)))))
9447 (defvar org-open-at-point-functions nil
9448 "Hook that is run when following a link at point.
9450 Functions in this hook must return t if they identify and follow
9451 a link at point. If they don't find anything interesting at point,
9452 they must return nil.")
9454 (defun org-open-at-point (&optional arg reference-buffer)
9455 "Open link at or after point.
9456 If there is no link at point, this function will search forward up to
9457 the end of the current line.
9458 Normally, files will be opened by an appropriate application. If the
9459 optional prefix argument ARG is non-nil, Emacs will visit the file.
9460 With a double prefix argument, try to open outside of Emacs, in the
9461 application the system uses for this file type."
9462 (interactive "P")
9463 ;; if in a code block, then open the block's results
9464 (unless (call-interactively #'org-babel-open-src-block-result)
9465 (org-load-modules-maybe)
9466 (move-marker org-open-link-marker (point))
9467 (setq org-window-config-before-follow-link (current-window-configuration))
9468 (org-remove-occur-highlights nil nil t)
9469 (cond
9470 ((and (org-on-heading-p)
9471 (not (org-in-regexp
9472 (concat org-plain-link-re "\\|"
9473 org-bracket-link-regexp "\\|"
9474 org-angle-link-re "\\|"
9475 "[ \t]:[^ \t\n]+:[ \t]*$")))
9476 (not (get-text-property (point) 'org-linked-text)))
9477 (or (org-offer-links-in-entry arg)
9478 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
9479 ((run-hook-with-args-until-success 'org-open-at-point-functions))
9480 ((org-at-timestamp-p t) (org-follow-timestamp-link))
9481 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
9482 (not (org-in-regexp org-bracket-link-regexp)))
9483 (org-footnote-action))
9485 (let (type path link line search (pos (point)))
9486 (catch 'match
9487 (save-excursion
9488 (skip-chars-forward "^]\n\r")
9489 (when (org-in-regexp org-bracket-link-regexp 1)
9490 (setq link (org-extract-attributes
9491 (org-link-unescape (org-match-string-no-properties 1))))
9492 (while (string-match " *\n *" link)
9493 (setq link (replace-match " " t t link)))
9494 (setq link (org-link-expand-abbrev link))
9495 (cond
9496 ((or (file-name-absolute-p link)
9497 (string-match "^\\.\\.?/" link))
9498 (setq type "file" path link))
9499 ((string-match org-link-re-with-space3 link)
9500 (setq type (match-string 1 link) path (match-string 2 link)))
9501 (t (setq type "thisfile" path link)))
9502 (throw 'match t)))
9504 (when (get-text-property (point) 'org-linked-text)
9505 (setq type "thisfile"
9506 pos (if (get-text-property (1+ (point)) 'org-linked-text)
9507 (1+ (point)) (point))
9508 path (buffer-substring
9509 (or (previous-single-property-change pos 'org-linked-text)
9510 (point-min))
9511 (or (next-single-property-change pos 'org-linked-text)
9512 (point-max))))
9513 (throw 'match t))
9515 (save-excursion
9516 (when (or (org-in-regexp org-angle-link-re)
9517 (org-in-regexp org-plain-link-re))
9518 (setq type (match-string 1)
9519 path (org-link-unescape (match-string 2)))
9520 (throw 'match t)))
9521 (save-excursion
9522 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
9523 (setq type "tags"
9524 path (match-string 1))
9525 (while (string-match ":" path)
9526 (setq path (replace-match "+" t t path)))
9527 (throw 'match t)))
9528 (when (org-in-regexp "<\\([^><\n]+\\)>")
9529 (setq type "tree-match"
9530 path (match-string 1))
9531 (throw 'match t)))
9532 (unless path
9533 (error "No link found"))
9535 ;; switch back to reference buffer
9536 ;; needed when if called in a temporary buffer through
9537 ;; org-open-link-from-string
9538 (with-current-buffer (or reference-buffer (current-buffer))
9540 ;; Remove any trailing spaces in path
9541 (if (string-match " +\\'" path)
9542 (setq path (replace-match "" t t path)))
9543 (if (and org-link-translation-function
9544 (fboundp org-link-translation-function))
9545 ;; Check if we need to translate the link
9546 (let ((tmp (funcall org-link-translation-function type path)))
9547 (setq type (car tmp) path (cdr tmp))))
9549 (cond
9551 ((assoc type org-link-protocols)
9552 (funcall (nth 1 (assoc type org-link-protocols)) path))
9554 ((equal type "mailto")
9555 (let ((cmd (car org-link-mailto-program))
9556 (args (cdr org-link-mailto-program)) args1
9557 (address path) (subject "") a)
9558 (if (string-match "\\(.*\\)::\\(.*\\)" path)
9559 (setq address (match-string 1 path)
9560 subject (org-link-escape (match-string 2 path))))
9561 (while args
9562 (cond
9563 ((not (stringp (car args))) (push (pop args) args1))
9564 (t (setq a (pop args))
9565 (if (string-match "%a" a)
9566 (setq a (replace-match address t t a)))
9567 (if (string-match "%s" a)
9568 (setq a (replace-match subject t t a)))
9569 (push a args1))))
9570 (apply cmd (nreverse args1))))
9572 ((member type '("http" "https" "ftp" "news"))
9573 (browse-url (concat type ":" (org-link-escape
9574 path org-link-escape-chars-browser))))
9576 ((string= type "doi")
9577 (browse-url (concat "http://dx.doi.org/"
9578 (org-link-escape
9579 path org-link-escape-chars-browser))))
9581 ((member type '("message"))
9582 (browse-url (concat type ":" path)))
9584 ((string= type "tags")
9585 (org-tags-view arg path))
9587 ((string= type "tree-match")
9588 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
9590 ((string= type "file")
9591 (if (string-match "::\\([0-9]+\\)\\'" path)
9592 (setq line (string-to-number (match-string 1 path))
9593 path (substring path 0 (match-beginning 0)))
9594 (if (string-match "::\\(.+\\)\\'" path)
9595 (setq search (match-string 1 path)
9596 path (substring path 0 (match-beginning 0)))))
9597 (if (string-match "[*?{]" (file-name-nondirectory path))
9598 (dired path)
9599 (org-open-file path arg line search)))
9601 ((string= type "shell")
9602 (let ((cmd path))
9603 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
9604 (string-match org-confirm-shell-link-not-regexp cmd))
9605 (not org-confirm-shell-link-function)
9606 (funcall org-confirm-shell-link-function
9607 (format "Execute \"%s\" in shell? "
9608 (org-add-props cmd nil
9609 'face 'org-warning))))
9610 (progn
9611 (message "Executing %s" cmd)
9612 (shell-command cmd))
9613 (error "Abort"))))
9615 ((string= type "elisp")
9616 (let ((cmd path))
9617 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
9618 (string-match org-confirm-elisp-link-not-regexp cmd))
9619 (not org-confirm-elisp-link-function)
9620 (funcall org-confirm-elisp-link-function
9621 (format "Execute \"%s\" as elisp? "
9622 (org-add-props cmd nil
9623 'face 'org-warning))))
9624 (message "%s => %s" cmd
9625 (if (equal (string-to-char cmd) ?\()
9626 (eval (read cmd))
9627 (call-interactively (read cmd))))
9628 (error "Abort"))))
9630 ((and (string= type "thisfile")
9631 (run-hook-with-args-until-success
9632 'org-open-link-functions path)))
9634 ((string= type "thisfile")
9635 (if arg
9636 (switch-to-buffer-other-window
9637 (org-get-buffer-for-internal-link (current-buffer)))
9638 (org-mark-ring-push))
9639 (let ((cmd `(org-link-search
9640 ,path
9641 ,(cond ((equal arg '(4)) ''occur)
9642 ((equal arg '(16)) ''org-occur)
9643 (t nil))
9644 ,pos)))
9645 (condition-case nil (let ((org-link-search-inhibit-query t))
9646 (eval cmd))
9647 (error (progn (widen) (eval cmd))))))
9650 (browse-url-at-point)))))))
9651 (move-marker org-open-link-marker nil)
9652 (run-hook-with-args 'org-follow-link-hook)))
9654 (defun org-offer-links-in-entry (&optional nth zero)
9655 "Offer links in the current entry and follow the selected link.
9656 If there is only one link, follow it immediately as well.
9657 If NTH is an integer, immediately pick the NTH link found.
9658 If ZERO is a string, check also this string for a link, and if
9659 there is one, offer it as link number zero."
9660 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
9661 "\\(" org-angle-link-re "\\)\\|"
9662 "\\(" org-plain-link-re "\\)"))
9663 (cnt ?0)
9664 (in-emacs (if (integerp nth) nil nth))
9665 have-zero end links link c)
9666 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
9667 (push (match-string 0 zero) links)
9668 (setq cnt (1- cnt) have-zero t))
9669 (save-excursion
9670 (org-back-to-heading t)
9671 (setq end (save-excursion (outline-next-heading) (point)))
9672 (while (re-search-forward re end t)
9673 (push (match-string 0) links))
9674 (setq links (org-uniquify (reverse links))))
9676 (cond
9677 ((null links)
9678 (message "No links"))
9679 ((equal (length links) 1)
9680 (setq link (list (car links))))
9681 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
9682 (setq link (nth (if have-zero nth (1- nth)) links)))
9683 (t ; we have to select a link
9684 (save-excursion
9685 (save-window-excursion
9686 (delete-other-windows)
9687 (with-output-to-temp-buffer "*Select Link*"
9688 (mapc (lambda (l)
9689 (if (not (string-match org-bracket-link-regexp l))
9690 (princ (format "[%c] %s\n" (incf cnt)
9691 (org-remove-angle-brackets l)))
9692 (if (match-end 3)
9693 (princ (format "[%c] %s (%s)\n" (incf cnt)
9694 (match-string 3 l) (match-string 1 l)))
9695 (princ (format "[%c] %s\n" (incf cnt)
9696 (match-string 1 l))))))
9697 links))
9698 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
9699 (message "Select link to open, RET to open all:")
9700 (setq c (read-char-exclusive))
9701 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
9702 (when (equal c ?q) (error "Abort"))
9703 (if (equal c ?\C-m)
9704 (setq link links)
9705 (setq nth (- c ?0))
9706 (if have-zero (setq nth (1+ nth)))
9707 (unless (and (integerp nth) (>= (length links) nth))
9708 (error "Invalid link selection"))
9709 (setq link (list (nth (1- nth) links))))))
9710 (if link
9711 (let ((buf (current-buffer)))
9712 (dolist (l link)
9713 (org-open-link-from-string l in-emacs buf))
9715 nil)))
9717 ;; Add special file links that specify the way of opening
9719 (org-add-link-type "file+sys" 'org-open-file-with-system)
9720 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
9721 (defun org-open-file-with-system (path)
9722 "Open file at PATH using the system way of opening it."
9723 (org-open-file path 'system))
9724 (defun org-open-file-with-emacs (path)
9725 "Open file at PATH in Emacs."
9726 (org-open-file path 'emacs))
9727 (defun org-remove-file-link-modifiers ()
9728 "Remove the file link modifiers in `file+sys:' and `file+emacs:' links."
9729 (goto-char (point-min))
9730 (while (re-search-forward "\\<file\\+\\(sys\\|emacs\\):" nil t)
9731 (org-if-unprotected
9732 (replace-match "file:" t t))))
9733 (eval-after-load "org-exp"
9734 '(add-hook 'org-export-preprocess-before-normalizing-links-hook
9735 'org-remove-file-link-modifiers))
9737 ;;;; Time estimates
9739 (defun org-get-effort (&optional pom)
9740 "Get the effort estimate for the current entry."
9741 (org-entry-get pom org-effort-property))
9743 ;;; File search
9745 (defvar org-create-file-search-functions nil
9746 "List of functions to construct the right search string for a file link.
9747 These functions are called in turn with point at the location to
9748 which the link should point.
9750 A function in the hook should first test if it would like to
9751 handle this file type, for example by checking the `major-mode'
9752 or the file extension. If it decides not to handle this file, it
9753 should just return nil to give other functions a chance. If it
9754 does handle the file, it must return the search string to be used
9755 when following the link. The search string will be part of the
9756 file link, given after a double colon, and `org-open-at-point'
9757 will automatically search for it. If special measures must be
9758 taken to make the search successful, another function should be
9759 added to the companion hook `org-execute-file-search-functions',
9760 which see.
9762 A function in this hook may also use `setq' to set the variable
9763 `description' to provide a suggestion for the descriptive text to
9764 be used for this link when it gets inserted into an Org-mode
9765 buffer with \\[org-insert-link].")
9767 (defvar org-execute-file-search-functions nil
9768 "List of functions to execute a file search triggered by a link.
9770 Functions added to this hook must accept a single argument, the
9771 search string that was part of the file link, the part after the
9772 double colon. The function must first check if it would like to
9773 handle this search, for example by checking the `major-mode' or
9774 the file extension. If it decides not to handle this search, it
9775 should just return nil to give other functions a chance. If it
9776 does handle the search, it must return a non-nil value to keep
9777 other functions from trying.
9779 Each function can access the current prefix argument through the
9780 variable `current-prefix-argument'. Note that a single prefix is
9781 used to force opening a link in Emacs, so it may be good to only
9782 use a numeric or double prefix to guide the search function.
9784 In case this is needed, a function in this hook can also restore
9785 the window configuration before `org-open-at-point' was called using:
9787 (set-window-configuration org-window-config-before-follow-link)")
9789 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
9790 (defun org-link-search (s &optional type avoid-pos stealth)
9791 "Search for a link search option.
9792 If S is surrounded by forward slashes, it is interpreted as a
9793 regular expression. In org-mode files, this will create an `org-occur'
9794 sparse tree. In ordinary files, `occur' will be used to list matches.
9795 If the current buffer is in `dired-mode', grep will be used to search
9796 in all files. If AVOID-POS is given, ignore matches near that position.
9798 When optional argument STEALTH is non-nil, do not modify
9799 visibility around point, thus ignoring
9800 `org-show-hierarchy-above', `org-show-following-heading' and
9801 `org-show-siblings' variables."
9802 (let ((case-fold-search t)
9803 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
9804 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
9805 (append '(("") (" ") ("\t") ("\n"))
9806 org-emphasis-alist)
9807 "\\|") "\\)"))
9808 (pos (point))
9809 (pre nil) (post nil)
9810 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
9811 (cond
9812 ;; First check if there are any special search functions
9813 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
9814 ;; Now try the builtin stuff
9815 ((and (equal (string-to-char s0) ?#)
9816 (> (length s0) 1)
9817 (save-excursion
9818 (goto-char (point-min))
9819 (and
9820 (re-search-forward
9821 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
9822 (setq type 'dedicated
9823 pos (match-beginning 0))))
9824 ;; There is an exact target for this
9825 (goto-char pos)
9826 (org-back-to-heading t)))
9827 ((save-excursion
9828 (goto-char (point-min))
9829 (and
9830 (re-search-forward
9831 (concat "<<" (regexp-quote s0) ">>") nil t)
9832 (setq type 'dedicated
9833 pos (match-beginning 0))))
9834 ;; There is an exact target for this
9835 (goto-char pos))
9836 ((and (string-match "^(\\(.*\\))$" s0)
9837 (save-excursion
9838 (goto-char (point-min))
9839 (and
9840 (re-search-forward
9841 (concat "[^[]" (regexp-quote
9842 (format org-coderef-label-format
9843 (match-string 1 s0))))
9844 nil t)
9845 (setq type 'dedicated
9846 pos (1+ (match-beginning 0))))))
9847 ;; There is a coderef target for this
9848 (goto-char pos))
9849 ((string-match "^/\\(.*\\)/$" s)
9850 ;; A regular expression
9851 (cond
9852 ((eq major-mode 'org-mode)
9853 (org-occur (match-string 1 s)))
9854 ;;((eq major-mode 'dired-mode)
9855 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
9856 (t (org-do-occur (match-string 1 s)))))
9857 ((and (eq major-mode 'org-mode) org-link-search-must-match-exact-headline)
9858 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
9859 (goto-char (point-min))
9860 (cond
9861 ((let (case-fold-search)
9862 (re-search-forward (format org-complex-heading-regexp-format
9863 (regexp-quote s))
9864 nil t))
9865 ;; OK, found a match
9866 (setq type 'dedicated)
9867 (goto-char (match-beginning 0)))
9868 ((and (not org-link-search-inhibit-query)
9869 (eq org-link-search-must-match-exact-headline 'query-to-create)
9870 (y-or-n-p "No match - create this as a new heading? "))
9871 (goto-char (point-max))
9872 (or (bolp) (newline))
9873 (insert "* " s "\n")
9874 (beginning-of-line 0))
9876 (goto-char pos)
9877 (error "No match"))))
9879 ;; A normal search string
9880 (when (equal (string-to-char s) ?*)
9881 ;; Anchor on headlines, post may include tags.
9882 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
9883 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
9884 s (substring s 1)))
9885 (remove-text-properties
9886 0 (length s)
9887 '(face nil mouse-face nil keymap nil fontified nil) s)
9888 ;; Make a series of regular expressions to find a match
9889 (setq words (org-split-string s "[ \n\r\t]+")
9891 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
9892 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
9893 "\\)" markers)
9894 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
9895 re2a (concat "[ \t\r\n]" re2a_)
9896 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
9897 re4 (concat "[^a-zA-Z_]" re4_)
9899 re1 (concat pre re2 post)
9900 re3 (concat pre (if pre re4_ re4) post)
9901 re5 (concat pre ".*" re4)
9902 re2 (concat pre re2)
9903 re2a (concat pre (if pre re2a_ re2a))
9904 re4 (concat pre (if pre re4_ re4))
9905 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
9906 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
9907 re5 "\\)"
9909 (cond
9910 ((eq type 'org-occur) (org-occur reall))
9911 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
9912 (t (goto-char (point-min))
9913 (setq type 'fuzzy)
9914 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
9915 (org-search-not-self 1 re1 nil t)
9916 (org-search-not-self 1 re2 nil t)
9917 (org-search-not-self 1 re2a nil t)
9918 (org-search-not-self 1 re3 nil t)
9919 (org-search-not-self 1 re4 nil t)
9920 (org-search-not-self 1 re5 nil t)
9922 (goto-char (match-beginning 1))
9923 (goto-char pos)
9924 (error "No match"))))))
9925 (and (eq major-mode 'org-mode)
9926 (not stealth)
9927 (org-show-context 'link-search))
9928 type))
9930 (defun org-search-not-self (group &rest args)
9931 "Execute `re-search-forward', but only accept matches that do not
9932 enclose the position of `org-open-link-marker'."
9933 (let ((m org-open-link-marker))
9934 (catch 'exit
9935 (while (apply 're-search-forward args)
9936 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
9937 (goto-char (match-end group))
9938 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
9939 (> (match-beginning 0) (marker-position m))
9940 (< (match-end 0) (marker-position m)))
9941 (save-match-data
9942 (or (not (org-in-regexp
9943 org-bracket-link-analytic-regexp 1))
9944 (not (match-end 4)) ; no description
9945 (and (<= (match-beginning 4) (point))
9946 (>= (match-end 4) (point))))))
9947 (throw 'exit (point))))))))
9949 (defun org-get-buffer-for-internal-link (buffer)
9950 "Return a buffer to be used for displaying the link target of internal links."
9951 (cond
9952 ((not org-display-internal-link-with-indirect-buffer)
9953 buffer)
9954 ((string-match "(Clone)$" (buffer-name buffer))
9955 (message "Buffer is already a clone, not making another one")
9956 ;; we also do not modify visibility in this case
9957 buffer)
9958 (t ; make a new indirect buffer for displaying the link
9959 (let* ((bn (buffer-name buffer))
9960 (ibn (concat bn "(Clone)"))
9961 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
9962 (with-current-buffer ib (org-overview))
9963 ib))))
9965 (defun org-do-occur (regexp &optional cleanup)
9966 "Call the Emacs command `occur'.
9967 If CLEANUP is non-nil, remove the printout of the regular expression
9968 in the *Occur* buffer. This is useful if the regex is long and not useful
9969 to read."
9970 (occur regexp)
9971 (when cleanup
9972 (let ((cwin (selected-window)) win beg end)
9973 (when (setq win (get-buffer-window "*Occur*"))
9974 (select-window win))
9975 (goto-char (point-min))
9976 (when (re-search-forward "match[a-z]+" nil t)
9977 (setq beg (match-end 0))
9978 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
9979 (setq end (1- (match-beginning 0)))))
9980 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
9981 (goto-char (point-min))
9982 (select-window cwin))))
9984 ;;; The mark ring for links jumps
9986 (defvar org-mark-ring nil
9987 "Mark ring for positions before jumps in Org-mode.")
9988 (defvar org-mark-ring-last-goto nil
9989 "Last position in the mark ring used to go back.")
9990 ;; Fill and close the ring
9991 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
9992 (loop for i from 1 to org-mark-ring-length do
9993 (push (make-marker) org-mark-ring))
9994 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
9995 org-mark-ring)
9997 (defun org-mark-ring-push (&optional pos buffer)
9998 "Put the current position or POS into the mark ring and rotate it."
9999 (interactive)
10000 (setq pos (or pos (point)))
10001 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10002 (move-marker (car org-mark-ring)
10003 (or pos (point))
10004 (or buffer (current-buffer)))
10005 (message "%s"
10006 (substitute-command-keys
10007 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10009 (defun org-mark-ring-goto (&optional n)
10010 "Jump to the previous position in the mark ring.
10011 With prefix arg N, jump back that many stored positions. When
10012 called several times in succession, walk through the entire ring.
10013 Org-mode commands jumping to a different position in the current file,
10014 or to another Org-mode file, automatically push the old position
10015 onto the ring."
10016 (interactive "p")
10017 (let (p m)
10018 (if (eq last-command this-command)
10019 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10020 (setq p org-mark-ring))
10021 (setq org-mark-ring-last-goto p)
10022 (setq m (car p))
10023 (org-pop-to-buffer-same-window (marker-buffer m))
10024 (goto-char m)
10025 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10027 (defun org-remove-angle-brackets (s)
10028 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10029 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10031 (defun org-add-angle-brackets (s)
10032 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10033 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10035 (defun org-remove-double-quotes (s)
10036 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10037 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10040 ;;; Following specific links
10042 (defun org-follow-timestamp-link ()
10043 (cond
10044 ((org-at-date-range-p t)
10045 (let ((org-agenda-start-on-weekday)
10046 (t1 (match-string 1))
10047 (t2 (match-string 2)))
10048 (setq t1 (time-to-days (org-time-string-to-time t1))
10049 t2 (time-to-days (org-time-string-to-time t2)))
10050 (org-agenda-list nil t1 (1+ (- t2 t1)))))
10051 ((org-at-timestamp-p t)
10052 (org-agenda-list nil (time-to-days (org-time-string-to-time
10053 (substring (match-string 1) 0 10)))
10055 (t (error "This should not happen"))))
10058 ;;; Following file links
10059 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10060 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10061 (declare-function mailcap-mime-info
10062 "mailcap" (string &optional request no-decode))
10063 (defvar org-wait nil)
10064 (defun org-open-file (path &optional in-emacs line search)
10065 "Open the file at PATH.
10066 First, this expands any special file name abbreviations. Then the
10067 configuration variable `org-file-apps' is checked if it contains an
10068 entry for this file type, and if yes, the corresponding command is launched.
10070 If no application is found, Emacs simply visits the file.
10072 With optional prefix argument IN-EMACS, Emacs will visit the file.
10073 With a double \\[universal-argument] \\[universal-argument] \
10074 prefix arg, Org tries to avoid opening in Emacs
10075 and to use an external application to visit the file.
10077 Optional LINE specifies a line to go to, optional SEARCH a string
10078 to search for. If LINE or SEARCH is given, the file will be
10079 opened in Emacs, unless an entry from org-file-apps that makes
10080 use of groups in a regexp matches.
10082 If you want to change the way frames are used when following a
10083 link, please customize `org-link-frame-setup'.
10085 If the file does not exist, an error is thrown."
10086 (let* ((file (if (equal path "")
10087 buffer-file-name
10088 (substitute-in-file-name (expand-file-name path))))
10089 (file-apps (append org-file-apps (org-default-apps)))
10090 (apps (org-remove-if
10091 'org-file-apps-entry-match-against-dlink-p file-apps))
10092 (apps-dlink (org-remove-if-not
10093 'org-file-apps-entry-match-against-dlink-p file-apps))
10094 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10095 (dirp (if remp nil (file-directory-p file)))
10096 (file (if (and dirp org-open-directory-means-index-dot-org)
10097 (concat (file-name-as-directory file) "index.org")
10098 file))
10099 (a-m-a-p (assq 'auto-mode apps))
10100 (dfile (downcase file))
10101 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10102 (link (cond ((and (eq line nil)
10103 (eq search nil))
10104 file)
10105 (line
10106 (concat file "::" (number-to-string line)))
10107 (search
10108 (concat file "::" search))))
10109 (dlink (downcase link))
10110 (old-buffer (current-buffer))
10111 (old-pos (point))
10112 (old-mode major-mode)
10113 ext cmd link-match-data)
10114 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10115 (setq ext (match-string 1 dfile))
10116 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10117 (setq ext (match-string 1 dfile))))
10118 (cond
10119 ((member in-emacs '((16) system))
10120 (setq cmd (cdr (assoc 'system apps))))
10121 (in-emacs (setq cmd 'emacs))
10123 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10124 (and dirp (cdr (assoc 'directory apps)))
10125 ; first, try matching against apps-dlink
10126 ; if we get a match here, store the match data for later
10127 (let ((match (assoc-default dlink apps-dlink
10128 'string-match)))
10129 (if match
10130 (progn (setq link-match-data (match-data))
10131 match)
10132 (progn (setq in-emacs (or in-emacs line search))
10133 nil))) ; if we have no match in apps-dlink,
10134 ; always open the file in emacs if line or search
10135 ; is given (for backwards compatibility)
10136 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10137 'string-match)
10138 (cdr (assoc ext apps))
10139 (cdr (assoc t apps))))))
10140 (when (eq cmd 'system)
10141 (setq cmd (cdr (assoc 'system apps))))
10142 (when (eq cmd 'default)
10143 (setq cmd (cdr (assoc t apps))))
10144 (when (eq cmd 'mailcap)
10145 (require 'mailcap)
10146 (mailcap-parse-mailcaps)
10147 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10148 (command (mailcap-mime-info mime-type)))
10149 (if (stringp command)
10150 (setq cmd command)
10151 (setq cmd 'emacs))))
10152 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10153 (not (file-exists-p file))
10154 (not org-open-non-existing-files))
10155 (error "No such file: %s" file))
10156 (cond
10157 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10158 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10159 (while (string-match "['\"]%s['\"]" cmd)
10160 (setq cmd (replace-match "%s" t t cmd)))
10161 (while (string-match "%s" cmd)
10162 (setq cmd (replace-match
10163 (save-match-data
10164 (shell-quote-argument
10165 (convert-standard-filename file)))
10166 t t cmd)))
10168 ;; Replace "%1", "%2" etc. in command with group matches from regex
10169 (save-match-data
10170 (let ((match-index 1)
10171 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10172 (set-match-data link-match-data)
10173 (while (<= match-index number-of-groups)
10174 (let ((regex (concat "%" (number-to-string match-index)))
10175 (replace-with (match-string match-index dlink)))
10176 (while (string-match regex cmd)
10177 (setq cmd (replace-match replace-with t t cmd))))
10178 (setq match-index (+ match-index 1)))))
10180 (save-window-excursion
10181 (start-process-shell-command cmd nil cmd)
10182 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
10184 ((or (stringp cmd)
10185 (eq cmd 'emacs))
10186 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10187 (widen)
10188 (if line (org-goto-line line)
10189 (if search (org-link-search search))))
10190 ((consp cmd)
10191 (let ((file (convert-standard-filename file)))
10192 (save-match-data
10193 (set-match-data link-match-data)
10194 (eval cmd))))
10195 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10196 (and (eq major-mode 'org-mode) (eq old-mode 'org-mode)
10197 (or (not (equal old-buffer (current-buffer)))
10198 (not (equal old-pos (point))))
10199 (org-mark-ring-push old-pos old-buffer))))
10201 (defun org-file-apps-entry-match-against-dlink-p (entry)
10202 "This function returns non-nil if `entry' uses a regular
10203 expression which should be matched against the whole link by
10204 org-open-file.
10206 It assumes that is the case when the entry uses a regular
10207 expression which has at least one grouping construct and the
10208 action is either a lisp form or a command string containing
10209 '%1', i.e. using at least one subexpression match as a
10210 parameter."
10211 (let ((selector (car entry))
10212 (action (cdr entry)))
10213 (if (stringp selector)
10214 (and (> (regexp-opt-depth selector) 0)
10215 (or (and (stringp action)
10216 (string-match "%[0-9]" action))
10217 (consp action)))
10218 nil)))
10220 (defun org-default-apps ()
10221 "Return the default applications for this operating system."
10222 (cond
10223 ((eq system-type 'darwin)
10224 org-file-apps-defaults-macosx)
10225 ((eq system-type 'windows-nt)
10226 org-file-apps-defaults-windowsnt)
10227 (t org-file-apps-defaults-gnu)))
10229 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10230 "Convert extensions to regular expressions in the cars of LIST.
10231 Also, weed out any non-string entries, because the return value is used
10232 only for regexp matching.
10233 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10234 point to the symbol `emacs', indicating that the file should
10235 be opened in Emacs."
10236 (append
10237 (delq nil
10238 (mapcar (lambda (x)
10239 (if (not (stringp (car x)))
10241 (if (string-match "\\W" (car x))
10243 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10244 list))
10245 (if add-auto-mode
10246 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10248 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10249 (defun org-file-remote-p (file)
10250 "Test whether FILE specifies a location on a remote system.
10251 Return non-nil if the location is indeed remote.
10253 For example, the filename \"/user@host:/foo\" specifies a location
10254 on the system \"/user@host:\"."
10255 (cond ((fboundp 'file-remote-p)
10256 (file-remote-p file))
10257 ((fboundp 'tramp-handle-file-remote-p)
10258 (tramp-handle-file-remote-p file))
10259 ((and (boundp 'ange-ftp-name-format)
10260 (string-match (car ange-ftp-name-format) file))
10262 (t nil)))
10265 ;;;; Refiling
10267 (defun org-get-org-file ()
10268 "Read a filename, with default directory `org-directory'."
10269 (let ((default (or org-default-notes-file remember-data-file)))
10270 (read-file-name (format "File name [%s]: " default)
10271 (file-name-as-directory org-directory)
10272 default)))
10274 (defun org-notes-order-reversed-p ()
10275 "Check if the current file should receive notes in reversed order."
10276 (cond
10277 ((not org-reverse-note-order) nil)
10278 ((eq t org-reverse-note-order) t)
10279 ((not (listp org-reverse-note-order)) nil)
10280 (t (catch 'exit
10281 (let ((all org-reverse-note-order)
10282 entry)
10283 (while (setq entry (pop all))
10284 (if (string-match (car entry) buffer-file-name)
10285 (throw 'exit (cdr entry))))
10286 nil)))))
10288 (defvar org-refile-target-table nil
10289 "The list of refile targets, created by `org-refile'.")
10291 (defvar org-agenda-new-buffers nil
10292 "Buffers created to visit agenda files.")
10294 (defvar org-refile-cache nil
10295 "Cache for refile targets.")
10297 (defvar org-refile-markers nil
10298 "All the markers used for caching refile locations.")
10300 (defun org-refile-marker (pos)
10301 "Get a new refile marker, but only if caching is in use."
10302 (if (not org-refile-use-cache)
10304 (let ((m (make-marker)))
10305 (move-marker m pos)
10306 (push m org-refile-markers)
10307 m)))
10309 (defun org-refile-cache-clear ()
10310 "Clear the refile cache and disable all the markers."
10311 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
10312 (setq org-refile-markers nil)
10313 (setq org-refile-cache nil)
10314 (message "Refile cache has been cleared"))
10316 (defun org-refile-cache-check-set (set)
10317 "Check if all the markers in the cache still have live buffers."
10318 (let (marker)
10319 (catch 'exit
10320 (while (and set (setq marker (nth 3 (pop set))))
10321 ;; if org-refile-use-outline-path is 'file, marker may be nil
10322 (when (and marker (null (marker-buffer marker)))
10323 (message "not found") (sit-for 3)
10324 (throw 'exit nil)))
10325 t)))
10327 (defun org-refile-cache-put (set &rest identifiers)
10328 "Push the refile targets SET into the cache, under IDENTIFIERS."
10329 (let* ((key (sha1 (prin1-to-string identifiers)))
10330 (entry (assoc key org-refile-cache)))
10331 (if entry
10332 (setcdr entry set)
10333 (push (cons key set) org-refile-cache))))
10335 (defun org-refile-cache-get (&rest identifiers)
10336 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10337 (cond
10338 ((not org-refile-cache) nil)
10339 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10341 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10342 org-refile-cache))))
10343 (and set (org-refile-cache-check-set set) set)))))
10345 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
10346 "Produce a table with refile targets."
10347 (let ((case-fold-search nil)
10348 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10349 (entries (or org-refile-targets '((nil . (:level . 1)))))
10350 targets tgs txt re files f desc descre fast-path-p level pos0)
10351 (message "Getting targets...")
10352 (with-current-buffer (or default-buffer (current-buffer))
10353 (while (setq entry (pop entries))
10354 (setq files (car entry) desc (cdr entry))
10355 (setq fast-path-p nil)
10356 (cond
10357 ((null files) (setq files (list (current-buffer))))
10358 ((eq files 'org-agenda-files)
10359 (setq files (org-agenda-files 'unrestricted)))
10360 ((and (symbolp files) (fboundp files))
10361 (setq files (funcall files)))
10362 ((and (symbolp files) (boundp files))
10363 (setq files (symbol-value files))))
10364 (if (stringp files) (setq files (list files)))
10365 (cond
10366 ((eq (car desc) :tag)
10367 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
10368 ((eq (car desc) :todo)
10369 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
10370 ((eq (car desc) :regexp)
10371 (setq descre (cdr desc)))
10372 ((eq (car desc) :level)
10373 (setq descre (concat "^\\*\\{" (number-to-string
10374 (if org-odd-levels-only
10375 (1- (* 2 (cdr desc)))
10376 (cdr desc)))
10377 "\\}[ \t]")))
10378 ((eq (car desc) :maxlevel)
10379 (setq fast-path-p t)
10380 (setq descre (concat "^\\*\\{1," (number-to-string
10381 (if org-odd-levels-only
10382 (1- (* 2 (cdr desc)))
10383 (cdr desc)))
10384 "\\}[ \t]")))
10385 (t (error "Bad refiling target description %s" desc)))
10386 (while (setq f (pop files))
10387 (with-current-buffer
10388 (if (bufferp f) f (org-get-agenda-file-buffer f))
10390 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
10391 (progn
10392 (if (bufferp f) (setq f (buffer-file-name
10393 (buffer-base-buffer f))))
10394 (setq f (and f (expand-file-name f)))
10395 (if (eq org-refile-use-outline-path 'file)
10396 (push (list (file-name-nondirectory f) f nil nil) tgs))
10397 (save-excursion
10398 (save-restriction
10399 (widen)
10400 (goto-char (point-min))
10401 (while (re-search-forward descre nil t)
10402 (goto-char (setq pos0 (point-at-bol)))
10403 (catch 'next
10404 (when org-refile-target-verify-function
10405 (save-match-data
10406 (or (funcall org-refile-target-verify-function)
10407 (throw 'next t))))
10408 (when (and (looking-at org-complex-heading-regexp)
10409 (not (member (match-string 4) excluded-entries)))
10410 (setq level (org-reduced-level
10411 (- (match-end 1) (match-beginning 1)))
10412 txt (org-link-display-format (match-string 4))
10413 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
10414 re (format org-complex-heading-regexp-format
10415 (regexp-quote (match-string 4))))
10416 (when org-refile-use-outline-path
10417 (setq txt (mapconcat
10418 'org-protect-slash
10419 (append
10420 (if (eq org-refile-use-outline-path
10421 'file)
10422 (list (file-name-nondirectory
10423 (buffer-file-name
10424 (buffer-base-buffer))))
10425 (if (eq org-refile-use-outline-path
10426 'full-file-path)
10427 (list (buffer-file-name
10428 (buffer-base-buffer)))))
10429 (org-get-outline-path fast-path-p
10430 level txt)
10431 (list txt))
10432 "/")))
10433 (push (list txt f re (org-refile-marker (point)))
10434 tgs)))
10435 (when (= (point) pos0)
10436 ;; verification function has not moved point
10437 (goto-char (point-at-eol))))))))
10438 (when org-refile-use-cache
10439 (org-refile-cache-put tgs (buffer-file-name) descre))
10440 (setq targets (append tgs targets))
10441 ))))
10442 (message "Getting targets...done")
10443 (nreverse targets)))
10445 (defun org-protect-slash (s)
10446 (while (string-match "/" s)
10447 (setq s (replace-match "\\" t t s)))
10450 (defvar org-olpa (make-vector 20 nil))
10452 (defun org-get-outline-path (&optional fastp level heading)
10453 "Return the outline path to the current entry, as a list.
10455 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
10456 routine which makes outline path derivations for an entire file,
10457 avoiding backtracing. Refile target collection makes use of that."
10458 (if fastp
10459 (progn
10460 (if (> level 19)
10461 (error "Outline path failure, more than 19 levels"))
10462 (loop for i from level upto 19 do
10463 (aset org-olpa i nil))
10464 (prog1
10465 (delq nil (append org-olpa nil))
10466 (aset org-olpa level heading)))
10467 (let (rtn case-fold-search)
10468 (save-excursion
10469 (save-restriction
10470 (widen)
10471 (while (org-up-heading-safe)
10472 (when (looking-at org-complex-heading-regexp)
10473 (push (org-match-string-no-properties 4) rtn)))
10474 rtn)))))
10476 (defun org-format-outline-path (path &optional width prefix)
10477 "Format the outline path PATH for display.
10478 Width is the maximum number of characters that is available.
10479 Prefix is a prefix to be included in the returned string,
10480 such as the file name."
10481 (setq width (or width 79))
10482 (if prefix (setq width (- width (length prefix))))
10483 (if (not path)
10484 (or prefix "")
10485 (let* ((nsteps (length path))
10486 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
10487 (maxwidth (if (<= total-width width)
10488 10000 ;; everything fits
10489 ;; we need to shorten the level headings
10490 (/ (- width nsteps) nsteps)))
10491 (org-odd-levels-only nil)
10492 (n 0)
10493 (total (1+ (length prefix))))
10494 (setq maxwidth (max maxwidth 10))
10495 (concat prefix
10496 (mapconcat
10497 (lambda (h)
10498 (setq n (1+ n))
10499 (if (and (= n nsteps) (< maxwidth 10000))
10500 (setq maxwidth (- total-width total)))
10501 (if (< (length h) maxwidth)
10502 (progn (setq total (+ total (length h) 1)) h)
10503 (setq h (substring h 0 (- maxwidth 2))
10504 total (+ total maxwidth 1))
10505 (if (string-match "[ \t]+\\'" h)
10506 (setq h (substring h 0 (match-beginning 0))))
10507 (setq h (concat h "..")))
10508 (org-add-props h nil 'face
10509 (nth (% (1- n) org-n-level-faces)
10510 org-level-faces))
10512 path "/")))))
10514 (defun org-display-outline-path (&optional file current)
10515 "Display the current outline path in the echo area."
10516 (interactive "P")
10517 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
10518 (case-fold-search nil)
10519 (path (and (eq major-mode 'org-mode) (org-get-outline-path))))
10520 (if current (setq path (append path
10521 (save-excursion
10522 (org-back-to-heading t)
10523 (if (looking-at org-complex-heading-regexp)
10524 (list (match-string 4)))))))
10525 (message "%s"
10526 (org-format-outline-path
10527 path
10528 (1- (frame-width))
10529 (and file bfn (concat (file-name-nondirectory bfn) "/"))))))
10531 (defvar org-refile-history nil
10532 "History for refiling operations.")
10534 (defvar org-after-refile-insert-hook nil
10535 "Hook run after `org-refile' has inserted its stuff at the new location.
10536 Note that this is still *before* the stuff will be removed from
10537 the *old* location.")
10539 (defvar org-capture-last-stored-marker)
10540 (defun org-refile (&optional goto default-buffer rfloc)
10541 "Move the entry or entries at point to another heading.
10542 The list of target headings is compiled using the information in
10543 `org-refile-targets', which see.
10545 At the target location, the entry is filed as a subitem of the target
10546 heading. Depending on `org-reverse-note-order', the new subitem will
10547 either be the first or the last subitem.
10549 If there is an active region, all entries in that region will be moved.
10550 However, the region must fulfill the requirement that the first heading
10551 is the first one sets the top-level of the moved text - at most siblings
10552 below it are allowed.
10554 With prefix arg GOTO, the command will only visit the target location
10555 and not actually move anything.
10557 With a double prefix arg \\[universal-argument] \\[universal-argument], \
10558 go to the location where the last refiling operation has put the subtree.
10559 With a prefix argument of `2', refile to the running clock.
10561 RFLOC can be a refile location obtained in a different way.
10563 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
10565 If you are using target caching (see `org-refile-use-cache'),
10566 You have to clear the target cache in order to find new targets.
10567 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
10568 prefix argument (`C-u C-u C-u C-c C-w')."
10570 (interactive "P")
10571 (if (member goto '(0 (64)))
10572 (org-refile-cache-clear)
10573 (let* ((cbuf (current-buffer))
10574 (regionp (org-region-active-p))
10575 (region-start (and regionp (region-beginning)))
10576 (region-end (and regionp (region-end)))
10577 (region-length (and regionp (- region-end region-start)))
10578 (filename (buffer-file-name (buffer-base-buffer cbuf)))
10579 pos it nbuf file re level reversed)
10580 (setq last-command nil)
10581 (when regionp
10582 (goto-char region-start)
10583 (or (bolp) (goto-char (point-at-bol)))
10584 (setq region-start (point))
10585 (unless (or (org-kill-is-subtree-p
10586 (buffer-substring region-start region-end))
10587 (prog1 org-refile-active-region-within-subtree
10588 (org-toggle-heading)))
10589 (error "The region is not a (sequence of) subtree(s)")))
10590 (if (equal goto '(16))
10591 (org-refile-goto-last-stored)
10592 (when (or
10593 (and (equal goto 2)
10594 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
10595 (prog1
10596 (setq it (list (or org-clock-heading "running clock")
10597 (buffer-file-name
10598 (marker-buffer org-clock-hd-marker))
10600 (marker-position org-clock-hd-marker)))
10601 (setq goto nil)))
10602 (setq it (or rfloc
10603 (let (heading-text)
10604 (save-excursion
10605 (unless goto
10606 (org-back-to-heading t)
10607 (setq heading-text
10608 (nth 4 (org-heading-components))))
10609 (org-refile-get-location
10610 (cond (goto "Goto")
10611 (regionp "Refile region to")
10612 (t (concat "Refile subtree \""
10613 heading-text "\" to")))
10614 default-buffer
10615 org-refile-allow-creating-parent-nodes
10616 goto))))))
10617 (setq file (nth 1 it)
10618 re (nth 2 it)
10619 pos (nth 3 it))
10620 (if (and (not goto)
10622 (equal (buffer-file-name) file)
10623 (if regionp
10624 (and (>= pos region-start)
10625 (<= pos region-end))
10626 (and (>= pos (point))
10627 (< pos (save-excursion
10628 (org-end-of-subtree t t))))))
10629 (error "Cannot refile to position inside the tree or region"))
10631 (setq nbuf (or (find-buffer-visiting file)
10632 (find-file-noselect file)))
10633 (if goto
10634 (progn
10635 (org-pop-to-buffer-same-window nbuf)
10636 (goto-char pos)
10637 (org-show-context 'org-goto))
10638 (if regionp
10639 (progn
10640 (org-kill-new (buffer-substring region-start region-end))
10641 (org-save-markers-in-region region-start region-end))
10642 (org-copy-subtree 1 nil t))
10643 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
10644 (find-file-noselect file)))
10645 (setq reversed (org-notes-order-reversed-p))
10646 (save-excursion
10647 (save-restriction
10648 (widen)
10649 (if pos
10650 (progn
10651 (goto-char pos)
10652 (looking-at org-outline-regexp)
10653 (setq level (org-get-valid-level (funcall outline-level) 1))
10654 (goto-char
10655 (if reversed
10656 (or (outline-next-heading) (point-max))
10657 (or (save-excursion (org-get-next-sibling))
10658 (org-end-of-subtree t t)
10659 (point-max)))))
10660 (setq level 1)
10661 (if (not reversed)
10662 (goto-char (point-max))
10663 (goto-char (point-min))
10664 (or (outline-next-heading) (goto-char (point-max)))))
10665 (if (not (bolp)) (newline))
10666 (org-paste-subtree level)
10667 (when org-log-refile
10668 (org-add-log-setup 'refile nil nil 'findpos
10669 org-log-refile)
10670 (unless (eq org-log-refile 'note)
10671 (save-excursion (org-add-log-note))))
10672 (and org-auto-align-tags (org-set-tags nil t))
10673 (bookmark-set "org-refile-last-stored")
10674 ;; If we are refiling for capture, make sure that the
10675 ;; last-capture pointers point here
10676 (when (org-bound-and-true-p org-refile-for-capture)
10677 (bookmark-set "org-capture-last-stored-marker")
10678 (move-marker org-capture-last-stored-marker (point)))
10679 (if (fboundp 'deactivate-mark) (deactivate-mark))
10680 (run-hooks 'org-after-refile-insert-hook))))
10681 (if regionp
10682 (delete-region (point) (+ (point) region-length))
10683 (org-cut-subtree))
10684 (when (featurep 'org-inlinetask)
10685 (org-inlinetask-remove-END-maybe))
10686 (setq org-markers-to-move nil)
10687 (message "Refiled to \"%s\" in file %s" (car it) file)))))))
10689 (defun org-refile-goto-last-stored ()
10690 "Go to the location where the last refile was stored."
10691 (interactive)
10692 (bookmark-jump "org-refile-last-stored")
10693 (message "This is the location of the last refile"))
10695 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
10696 no-exclude)
10697 "Prompt the user for a refile location, using PROMPT.
10698 PROMPT should not be suffixed with a colon and a space, because
10699 this function appends the default value from
10700 `org-refile-history' automatically, if that is not empty.
10701 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
10702 this is used for the GOTO interface."
10703 (let ((org-refile-targets org-refile-targets)
10704 (org-refile-use-outline-path org-refile-use-outline-path)
10705 excluded-entries)
10706 (when (and (eq major-mode 'org-mode)
10707 (not org-refile-use-cache)
10708 (not no-exclude))
10709 (org-map-tree
10710 (lambda()
10711 (setq excluded-entries
10712 (append excluded-entries (list (org-get-heading t t)))))))
10713 (setq org-refile-target-table
10714 (org-refile-get-targets default-buffer excluded-entries)))
10715 (unless org-refile-target-table
10716 (error "No refile targets"))
10717 (let* ((prompt (concat prompt
10718 (and (car org-refile-history)
10719 (concat " (default " (car org-refile-history) ")"))
10720 ": "))
10721 (cbuf (current-buffer))
10722 (partial-completion-mode nil)
10723 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
10724 (cfunc (if (and org-refile-use-outline-path
10725 org-outline-path-complete-in-steps)
10726 'org-olpath-completing-read
10727 'org-icompleting-read))
10728 (extra (if org-refile-use-outline-path "/" ""))
10729 (filename (and cfn (expand-file-name cfn)))
10730 (tbl (mapcar
10731 (lambda (x)
10732 (if (and (not (member org-refile-use-outline-path
10733 '(file full-file-path)))
10734 (not (equal filename (nth 1 x))))
10735 (cons (concat (car x) extra " ("
10736 (file-name-nondirectory (nth 1 x)) ")")
10737 (cdr x))
10738 (cons (concat (car x) extra) (cdr x))))
10739 org-refile-target-table))
10740 (completion-ignore-case t)
10741 pa answ parent-target child parent old-hist)
10742 (setq old-hist org-refile-history)
10743 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
10744 nil 'org-refile-history (car org-refile-history)))
10745 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
10746 (org-refile-check-position pa)
10747 (if pa
10748 (progn
10749 (when (or (not org-refile-history)
10750 (not (eq old-hist org-refile-history))
10751 (not (equal (car pa) (car org-refile-history))))
10752 (setq org-refile-history
10753 (cons (car pa) (if (assoc (car org-refile-history) tbl)
10754 org-refile-history
10755 (cdr org-refile-history))))
10756 (if (equal (car org-refile-history) (nth 1 org-refile-history))
10757 (pop org-refile-history)))
10759 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
10760 (progn
10761 (setq parent (match-string 1 answ)
10762 child (match-string 2 answ))
10763 (setq parent-target (or (assoc parent tbl)
10764 (assoc (concat parent "/") tbl)))
10765 (when (and parent-target
10766 (or (eq new-nodes t)
10767 (and (eq new-nodes 'confirm)
10768 (y-or-n-p (format "Create new node \"%s\"? "
10769 child)))))
10770 (org-refile-new-child parent-target child)))
10771 (error "Invalid target location")))))
10773 (defun org-refile-check-position (refile-pointer)
10774 "Check if the refile pointer matches the readline to which it points."
10775 (let* ((file (nth 1 refile-pointer))
10776 (re (nth 2 refile-pointer))
10777 (pos (nth 3 refile-pointer))
10778 buffer)
10779 (when (org-string-nw-p re)
10780 (setq buffer (if (markerp pos)
10781 (marker-buffer pos)
10782 (or (find-buffer-visiting file)
10783 (find-file-noselect file))))
10784 (with-current-buffer buffer
10785 (save-excursion
10786 (save-restriction
10787 (widen)
10788 (goto-char pos)
10789 (beginning-of-line 1)
10790 (unless (org-looking-at-p re)
10791 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
10793 (defun org-refile-new-child (parent-target child)
10794 "Use refile target PARENT-TARGET to add new CHILD below it."
10795 (unless parent-target
10796 (error "Cannot find parent for new node"))
10797 (let ((file (nth 1 parent-target))
10798 (pos (nth 3 parent-target))
10799 level)
10800 (with-current-buffer (or (find-buffer-visiting file)
10801 (find-file-noselect file))
10802 (save-excursion
10803 (save-restriction
10804 (widen)
10805 (if pos
10806 (goto-char pos)
10807 (goto-char (point-max))
10808 (if (not (bolp)) (newline)))
10809 (when (looking-at org-outline-regexp)
10810 (setq level (funcall outline-level))
10811 (org-end-of-subtree t t))
10812 (org-back-over-empty-lines)
10813 (insert "\n" (make-string
10814 (if pos (org-get-valid-level level 1) 1) ?*)
10815 " " child "\n")
10816 (beginning-of-line 0)
10817 (list (concat (car parent-target) "/" child) file "" (point)))))))
10819 (defun org-olpath-completing-read (prompt collection &rest args)
10820 "Read an outline path like a file name."
10821 (let ((thetable collection)
10822 (org-completion-use-ido nil) ; does not work with ido.
10823 (org-completion-use-iswitchb nil)) ; or iswitchb
10824 (apply
10825 'org-icompleting-read prompt
10826 (lambda (string predicate &optional flag)
10827 (let (rtn r f (l (length string)))
10828 (cond
10829 ((eq flag nil)
10830 ;; try completion
10831 (try-completion string thetable))
10832 ((eq flag t)
10833 ;; all-completions
10834 (setq rtn (all-completions string thetable predicate))
10835 (mapcar
10836 (lambda (x)
10837 (setq r (substring x l))
10838 (if (string-match " ([^)]*)$" x)
10839 (setq f (match-string 0 x))
10840 (setq f ""))
10841 (if (string-match "/" r)
10842 (concat string (substring r 0 (match-end 0)) f)
10844 rtn))
10845 ((eq flag 'lambda)
10846 ;; exact match?
10847 (assoc string thetable)))
10849 args)))
10851 ;;;; Dynamic blocks
10853 (defun org-find-dblock (name)
10854 "Find the first dynamic block with name NAME in the buffer.
10855 If not found, stay at current position and return nil."
10856 (let (pos)
10857 (save-excursion
10858 (goto-char (point-min))
10859 (setq pos (and (re-search-forward (concat "^[ \t]*#\\+BEGIN:[ \t]+" name "\\>")
10860 nil t)
10861 (match-beginning 0))))
10862 (if pos (goto-char pos))
10863 pos))
10865 (defconst org-dblock-start-re
10866 "^[ \t]*#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
10867 "Matches the start line of a dynamic block, with parameters.")
10869 (defconst org-dblock-end-re "^[ \t]*#\\+END\\([: \t\r\n]\\|$\\)"
10870 "Matches the end of a dynamic block.")
10872 (defun org-create-dblock (plist)
10873 "Create a dynamic block section, with parameters taken from PLIST.
10874 PLIST must contain a :name entry which is used as name of the block."
10875 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
10876 (end-of-line 1)
10877 (newline))
10878 (let ((col (current-column))
10879 (name (plist-get plist :name)))
10880 (insert "#+BEGIN: " name)
10881 (while plist
10882 (if (eq (car plist) :name)
10883 (setq plist (cddr plist))
10884 (insert " " (prin1-to-string (pop plist)))))
10885 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
10886 (beginning-of-line -2)))
10888 (defun org-prepare-dblock ()
10889 "Prepare dynamic block for refresh.
10890 This empties the block, puts the cursor at the insert position and returns
10891 the property list including an extra property :name with the block name."
10892 (unless (looking-at org-dblock-start-re)
10893 (error "Not at a dynamic block"))
10894 (let* ((begdel (1+ (match-end 0)))
10895 (name (org-no-properties (match-string 1)))
10896 (params (append (list :name name)
10897 (read (concat "(" (match-string 3) ")")))))
10898 (save-excursion
10899 (beginning-of-line 1)
10900 (skip-chars-forward " \t")
10901 (setq params (plist-put params :indentation-column (current-column))))
10902 (unless (re-search-forward org-dblock-end-re nil t)
10903 (error "Dynamic block not terminated"))
10904 (setq params
10905 (append params
10906 (list :content (buffer-substring
10907 begdel (match-beginning 0)))))
10908 (delete-region begdel (match-beginning 0))
10909 (goto-char begdel)
10910 (open-line 1)
10911 params))
10913 (defun org-map-dblocks (&optional command)
10914 "Apply COMMAND to all dynamic blocks in the current buffer.
10915 If COMMAND is not given, use `org-update-dblock'."
10916 (let ((cmd (or command 'org-update-dblock)))
10917 (save-excursion
10918 (goto-char (point-min))
10919 (while (re-search-forward org-dblock-start-re nil t)
10920 (goto-char (match-beginning 0))
10921 (save-excursion
10922 (condition-case nil
10923 (funcall cmd)
10924 (error (message "Error during update of dynamic block"))))
10925 (unless (re-search-forward org-dblock-end-re nil t)
10926 (error "Dynamic block not terminated"))))))
10928 (defun org-dblock-update (&optional arg)
10929 "User command for updating dynamic blocks.
10930 Update the dynamic block at point. With prefix ARG, update all dynamic
10931 blocks in the buffer."
10932 (interactive "P")
10933 (if arg
10934 (org-update-all-dblocks)
10935 (or (looking-at org-dblock-start-re)
10936 (org-beginning-of-dblock))
10937 (org-update-dblock)))
10939 (defun org-update-dblock ()
10940 "Update the dynamic block at point.
10941 This means to empty the block, parse for parameters and then call
10942 the correct writing function."
10943 (interactive)
10944 (save-window-excursion
10945 (let* ((pos (point))
10946 (line (org-current-line))
10947 (params (org-prepare-dblock))
10948 (name (plist-get params :name))
10949 (indent (plist-get params :indentation-column))
10950 (cmd (intern (concat "org-dblock-write:" name))))
10951 (message "Updating dynamic block `%s' at line %d..." name line)
10952 (funcall cmd params)
10953 (message "Updating dynamic block `%s' at line %d...done" name line)
10954 (goto-char pos)
10955 (when (and indent (> indent 0))
10956 (setq indent (make-string indent ?\ ))
10957 (save-excursion
10958 (org-beginning-of-dblock)
10959 (forward-line 1)
10960 (while (not (looking-at org-dblock-end-re))
10961 (insert indent)
10962 (beginning-of-line 2))
10963 (when (looking-at org-dblock-end-re)
10964 (and (looking-at "[ \t]+")
10965 (replace-match ""))
10966 (insert indent)))))))
10968 (defun org-beginning-of-dblock ()
10969 "Find the beginning of the dynamic block at point.
10970 Error if there is no such block at point."
10971 (let ((pos (point))
10972 beg)
10973 (end-of-line 1)
10974 (if (and (re-search-backward org-dblock-start-re nil t)
10975 (setq beg (match-beginning 0))
10976 (re-search-forward org-dblock-end-re nil t)
10977 (> (match-end 0) pos))
10978 (goto-char beg)
10979 (goto-char pos)
10980 (error "Not in a dynamic block"))))
10982 (defun org-update-all-dblocks ()
10983 "Update all dynamic blocks in the buffer.
10984 This function can be used in a hook."
10985 (interactive)
10986 (when (eq major-mode 'org-mode)
10987 (org-map-dblocks 'org-update-dblock)))
10990 ;;;; Completion
10992 (defconst org-additional-option-like-keywords
10993 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML:"
10994 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook:"
10995 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"
10996 "LATEX_CLASS:" "LATEX_CLASS_OPTIONS:" "ATTR_LaTeX:"
10997 "BEGIN:" "END:"
10998 "ORGTBL" "TBLFM:" "TBLNAME:"
10999 "BEGIN_EXAMPLE" "END_EXAMPLE"
11000 "BEGIN_QUOTE" "END_QUOTE"
11001 "BEGIN_VERSE" "END_VERSE"
11002 "BEGIN_CENTER" "END_CENTER"
11003 "BEGIN_SRC" "END_SRC"
11004 "BEGIN_RESULT" "END_RESULT"
11005 "NAME:" "RESULTS:"
11006 "HEADER:" "HEADERS:"
11007 "CATEGORY:" "COLUMNS:" "PROPERTY:"
11008 "CAPTION:" "LABEL:"
11009 "SETUPFILE:"
11010 "INCLUDE:"
11011 "BIND:"
11012 "MACRO:"))
11014 (defcustom org-structure-template-alist
11016 ("s" "#+begin_src ?\n\n#+end_src"
11017 "<src lang=\"?\">\n\n</src>")
11018 ("e" "#+begin_example\n?\n#+end_example"
11019 "<example>\n?\n</example>")
11020 ("q" "#+begin_quote\n?\n#+end_quote"
11021 "<quote>\n?\n</quote>")
11022 ("v" "#+begin_verse\n?\n#+end_verse"
11023 "<verse>\n?\n/verse>")
11024 ("c" "#+begin_center\n?\n#+end_center"
11025 "<center>\n?\n/center>")
11026 ("l" "#+begin_latex\n?\n#+end_latex"
11027 "<literal style=\"latex\">\n?\n</literal>")
11028 ("L" "#+latex: "
11029 "<literal style=\"latex\">?</literal>")
11030 ("h" "#+begin_html\n?\n#+end_html"
11031 "<literal style=\"html\">\n?\n</literal>")
11032 ("H" "#+html: "
11033 "<literal style=\"html\">?</literal>")
11034 ("a" "#+begin_ascii\n?\n#+end_ascii")
11035 ("A" "#+ascii: ")
11036 ("i" "#+index: ?"
11037 "#+index: ?")
11038 ("I" "#+include %file ?"
11039 "<include file=%file markup=\"?\">")
11041 "Structure completion elements.
11042 This is a list of abbreviation keys and values. The value gets inserted
11043 if you type `<' followed by the key and then press the completion key,
11044 usually `M-TAB'. %file will be replaced by a file name after prompting
11045 for the file using completion. The cursor will be placed at the position
11046 of the `?` in the template.
11047 There are two templates for each key, the first uses the original Org syntax,
11048 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11049 the default when the /org-mtags.el/ module has been loaded. See also the
11050 variable `org-mtags-prefer-muse-templates'.
11051 This is an experimental feature, it is undecided if it is going to stay in."
11052 :group 'org-completion
11053 :type '(repeat
11054 (string :tag "Key")
11055 (string :tag "Template")
11056 (string :tag "Muse Template")))
11058 (defun org-try-structure-completion ()
11059 "Try to complete a structure template before point.
11060 This looks for strings like \"<e\" on an otherwise empty line and
11061 expands them."
11062 (let ((l (buffer-substring (point-at-bol) (point)))
11064 (when (and (looking-at "[ \t]*$")
11065 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
11066 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
11067 (org-complete-expand-structure-template (+ -1 (point-at-bol)
11068 (match-beginning 1)) a)
11069 t)))
11071 (defun org-complete-expand-structure-template (start cell)
11072 "Expand a structure template."
11073 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
11074 (rpl (nth (if musep 2 1) cell))
11075 (ind ""))
11076 (delete-region start (point))
11077 (when (string-match "\\`#\\+" rpl)
11078 (cond
11079 ((bolp))
11080 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
11081 (setq ind (buffer-substring (point-at-bol) (point))))
11082 (t (newline))))
11083 (setq start (point))
11084 (if (string-match "%file" rpl)
11085 (setq rpl (replace-match
11086 (concat
11087 "\""
11088 (save-match-data
11089 (abbreviate-file-name (read-file-name "Include file: ")))
11090 "\"")
11091 t t rpl)))
11092 (setq rpl (mapconcat 'identity (split-string rpl "\n")
11093 (concat "\n" ind)))
11094 (insert rpl)
11095 (if (re-search-backward "\\?" start t) (delete-char 1))))
11097 ;;;; TODO, DEADLINE, Comments
11099 (defun org-toggle-comment ()
11100 "Change the COMMENT state of an entry."
11101 (interactive)
11102 (save-excursion
11103 (org-back-to-heading)
11104 (let (case-fold-search)
11105 (cond
11106 ((looking-at (format org-heading-keyword-regexp-format
11107 org-comment-string))
11108 (goto-char (match-end 1))
11109 (looking-at (concat " +" org-comment-string))
11110 (replace-match "" t t)
11111 (when (eolp) (insert " ")))
11112 ((looking-at org-outline-regexp)
11113 (goto-char (match-end 0))
11114 (insert org-comment-string " "))))))
11116 (defvar org-last-todo-state-is-todo nil
11117 "This is non-nil when the last TODO state change led to a TODO state.
11118 If the last change removed the TODO tag or switched to DONE, then
11119 this is nil.")
11121 (defvar org-setting-tags nil) ; dynamically skipped
11123 (defvar org-todo-setup-filter-hook nil
11124 "Hook for functions that pre-filter todo specs.
11125 Each function takes a todo spec and returns either nil or the spec
11126 transformed into canonical form." )
11128 (defvar org-todo-get-default-hook nil
11129 "Hook for functions that get a default item for todo.
11130 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11131 nil or a string to be used for the todo mark." )
11133 (defvar org-agenda-headline-snapshot-before-repeat)
11135 (defun org-current-effective-time ()
11136 "Return current time adjusted for `org-extend-today-until' variable"
11137 (let* ((ct (org-current-time))
11138 (dct (decode-time ct))
11139 (ct1
11140 (if (and org-use-effective-time
11141 (< (nth 2 dct) org-extend-today-until))
11142 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct))
11143 ct)))
11144 ct1))
11146 (defun org-todo-yesterday (&optional arg)
11147 "Like `org-todo' but the time of change will be 23:59 of yesterday"
11148 (interactive "P")
11149 (let* ((hour (third (decode-time
11150 (org-current-time))))
11151 (org-extend-today-until (1+ hour)))
11152 (org-todo arg)))
11154 (defun org-todo (&optional arg)
11155 "Change the TODO state of an item.
11156 The state of an item is given by a keyword at the start of the heading,
11157 like
11158 *** TODO Write paper
11159 *** DONE Call mom
11161 The different keywords are specified in the variable `org-todo-keywords'.
11162 By default the available states are \"TODO\" and \"DONE\".
11163 So for this example: when the item starts with TODO, it is changed to DONE.
11164 When it starts with DONE, the DONE is removed. And when neither TODO nor
11165 DONE are present, add TODO at the beginning of the heading.
11167 With \\[universal-argument] prefix arg, use completion to determine the new \
11168 state.
11169 With numeric prefix arg, switch to that state.
11170 With a double \\[universal-argument] prefix, switch to the next set of TODO \
11171 keywords (nextset).
11172 With a triple \\[universal-argument] prefix, circumvent any state blocking.
11173 With a numeric prefix arg of 0, inhibit note taking for the change.
11175 For calling through lisp, arg is also interpreted in the following way:
11176 'none -> empty state
11177 \"\"(empty string) -> switch to empty state
11178 'done -> switch to DONE
11179 'nextset -> switch to the next set of keywords
11180 'previousset -> switch to the previous set of keywords
11181 \"WAITING\" -> switch to the specified keyword, but only if it
11182 really is a member of `org-todo-keywords'."
11183 (interactive "P")
11184 (if (equal arg '(16)) (setq arg 'nextset))
11185 (let ((org-blocker-hook org-blocker-hook)
11186 (case-fold-search nil))
11187 (when (equal arg '(64))
11188 (setq arg nil org-blocker-hook nil))
11189 (when (and org-blocker-hook
11190 (or org-inhibit-blocking
11191 (org-entry-get nil "NOBLOCKING")))
11192 (setq org-blocker-hook nil))
11193 (save-excursion
11194 (catch 'exit
11195 (org-back-to-heading t)
11196 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
11197 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
11198 (looking-at "\\(?: *\\|[ \t]*$\\)"))
11199 (let* ((match-data (match-data))
11200 (startpos (point-at-bol))
11201 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
11202 (org-log-done org-log-done)
11203 (org-log-repeat org-log-repeat)
11204 (org-todo-log-states org-todo-log-states)
11205 (org-inhibit-logging
11206 (if (equal arg 0)
11207 (progn (setq arg nil) 'note) org-inhibit-logging))
11208 (this (match-string 1))
11209 (hl-pos (match-beginning 0))
11210 (head (org-get-todo-sequence-head this))
11211 (ass (assoc head org-todo-kwd-alist))
11212 (interpret (nth 1 ass))
11213 (done-word (nth 3 ass))
11214 (final-done-word (nth 4 ass))
11215 (last-state (or this ""))
11216 (completion-ignore-case t)
11217 (member (member this org-todo-keywords-1))
11218 (tail (cdr member))
11219 (state (cond
11220 ((and org-todo-key-trigger
11221 (or (and (equal arg '(4))
11222 (eq org-use-fast-todo-selection 'prefix))
11223 (and (not arg) org-use-fast-todo-selection
11224 (not (eq org-use-fast-todo-selection
11225 'prefix)))))
11226 ;; Use fast selection
11227 (org-fast-todo-selection))
11228 ((and (equal arg '(4))
11229 (or (not org-use-fast-todo-selection)
11230 (not org-todo-key-trigger)))
11231 ;; Read a state with completion
11232 (org-icompleting-read
11233 "State: " (mapcar (lambda(x) (list x))
11234 org-todo-keywords-1)
11235 nil t))
11236 ((eq arg 'right)
11237 (if this
11238 (if tail (car tail) nil)
11239 (car org-todo-keywords-1)))
11240 ((eq arg 'left)
11241 (if (equal member org-todo-keywords-1)
11243 (if this
11244 (nth (- (length org-todo-keywords-1)
11245 (length tail) 2)
11246 org-todo-keywords-1)
11247 (org-last org-todo-keywords-1))))
11248 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
11249 (setq arg nil))) ; hack to fall back to cycling
11250 (arg
11251 ;; user or caller requests a specific state
11252 (cond
11253 ((equal arg "") nil)
11254 ((eq arg 'none) nil)
11255 ((eq arg 'done) (or done-word (car org-done-keywords)))
11256 ((eq arg 'nextset)
11257 (or (car (cdr (member head org-todo-heads)))
11258 (car org-todo-heads)))
11259 ((eq arg 'previousset)
11260 (let ((org-todo-heads (reverse org-todo-heads)))
11261 (or (car (cdr (member head org-todo-heads)))
11262 (car org-todo-heads))))
11263 ((car (member arg org-todo-keywords-1)))
11264 ((stringp arg)
11265 (error "State `%s' not valid in this file" arg))
11266 ((nth (1- (prefix-numeric-value arg))
11267 org-todo-keywords-1))))
11268 ((null member) (or head (car org-todo-keywords-1)))
11269 ((equal this final-done-word) nil) ;; -> make empty
11270 ((null tail) nil) ;; -> first entry
11271 ((memq interpret '(type priority))
11272 (if (eq this-command last-command)
11273 (car tail)
11274 (if (> (length tail) 0)
11275 (or done-word (car org-done-keywords))
11276 nil)))
11278 (car tail))))
11279 (state (or
11280 (run-hook-with-args-until-success
11281 'org-todo-get-default-hook state last-state)
11282 state))
11283 (next (if state (concat " " state " ") " "))
11284 (change-plist (list :type 'todo-state-change :from this :to state
11285 :position startpos))
11286 dolog now-done-p)
11287 (when org-blocker-hook
11288 (setq org-last-todo-state-is-todo
11289 (not (member this org-done-keywords)))
11290 (unless (save-excursion
11291 (save-match-data
11292 (org-with-wide-buffer
11293 (run-hook-with-args-until-failure
11294 'org-blocker-hook change-plist))))
11295 (if (org-called-interactively-p 'interactive)
11296 (error "TODO state change from %s to %s blocked" this state)
11297 ;; fail silently
11298 (message "TODO state change from %s to %s blocked" this state)
11299 (throw 'exit nil))))
11300 (store-match-data match-data)
11301 (replace-match next t t)
11302 (unless (pos-visible-in-window-p hl-pos)
11303 (message "TODO state changed to %s" (org-trim next)))
11304 (unless head
11305 (setq head (org-get-todo-sequence-head state)
11306 ass (assoc head org-todo-kwd-alist)
11307 interpret (nth 1 ass)
11308 done-word (nth 3 ass)
11309 final-done-word (nth 4 ass)))
11310 (when (memq arg '(nextset previousset))
11311 (message "Keyword-Set %d/%d: %s"
11312 (- (length org-todo-sets) -1
11313 (length (memq (assoc state org-todo-sets) org-todo-sets)))
11314 (length org-todo-sets)
11315 (mapconcat 'identity (assoc state org-todo-sets) " ")))
11316 (setq org-last-todo-state-is-todo
11317 (not (member state org-done-keywords)))
11318 (setq now-done-p (and (member state org-done-keywords)
11319 (not (member this org-done-keywords))))
11320 (and logging (org-local-logging logging))
11321 (when (and (or org-todo-log-states org-log-done)
11322 (not (eq org-inhibit-logging t))
11323 (not (memq arg '(nextset previousset))))
11324 ;; we need to look at recording a time and note
11325 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
11326 (nth 2 (assoc this org-todo-log-states))))
11327 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
11328 (setq dolog 'time))
11329 (when (and state
11330 (member state org-not-done-keywords)
11331 (not (member this org-not-done-keywords)))
11332 ;; This is now a todo state and was not one before
11333 ;; If there was a CLOSED time stamp, get rid of it.
11334 (org-add-planning-info nil nil 'closed))
11335 (when (and now-done-p org-log-done)
11336 ;; It is now done, and it was not done before
11337 (org-add-planning-info 'closed (org-current-effective-time))
11338 (if (and (not dolog) (eq 'note org-log-done))
11339 (org-add-log-setup 'done state this 'findpos 'note)))
11340 (when (and state dolog)
11341 ;; This is a non-nil state, and we need to log it
11342 (org-add-log-setup 'state state this 'findpos dolog)))
11343 ;; Fixup tag positioning
11344 (org-todo-trigger-tag-changes state)
11345 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
11346 (when org-provide-todo-statistics
11347 (org-update-parent-todo-statistics))
11348 (run-hooks 'org-after-todo-state-change-hook)
11349 (if (and arg (not (member state org-done-keywords)))
11350 (setq head (org-get-todo-sequence-head state)))
11351 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
11352 ;; Do we need to trigger a repeat?
11353 (when now-done-p
11354 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
11355 ;; This is for the agenda, take a snapshot of the headline.
11356 (save-match-data
11357 (setq org-agenda-headline-snapshot-before-repeat
11358 (org-get-heading))))
11359 (org-auto-repeat-maybe state))
11360 ;; Fixup cursor location if close to the keyword
11361 (if (and (outline-on-heading-p)
11362 (not (bolp))
11363 (save-excursion (beginning-of-line 1)
11364 (looking-at org-todo-line-regexp))
11365 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
11366 (progn
11367 (goto-char (or (match-end 2) (match-end 1)))
11368 (and (looking-at " ") (just-one-space))))
11369 (when org-trigger-hook
11370 (save-excursion
11371 (run-hook-with-args 'org-trigger-hook change-plist))))))))
11373 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
11374 "Block turning an entry into a TODO, using the hierarchy.
11375 This checks whether the current task should be blocked from state
11376 changes. Such blocking occurs when:
11378 1. The task has children which are not all in a completed state.
11380 2. A task has a parent with the property :ORDERED:, and there
11381 are siblings prior to the current task with incomplete
11382 status.
11384 3. The parent of the task is blocked because it has siblings that should
11385 be done first, or is child of a block grandparent TODO entry."
11387 (if (not org-enforce-todo-dependencies)
11388 t ; if locally turned off don't block
11389 (catch 'dont-block
11390 ;; If this is not a todo state change, or if this entry is already DONE,
11391 ;; do not block
11392 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11393 (member (plist-get change-plist :from)
11394 (cons 'done org-done-keywords))
11395 (member (plist-get change-plist :to)
11396 (cons 'todo org-not-done-keywords))
11397 (not (plist-get change-plist :to)))
11398 (throw 'dont-block t))
11399 ;; If this task has children, and any are undone, it's blocked
11400 (save-excursion
11401 (org-back-to-heading t)
11402 (let ((this-level (funcall outline-level)))
11403 (outline-next-heading)
11404 (let ((child-level (funcall outline-level)))
11405 (while (and (not (eobp))
11406 (> child-level this-level))
11407 ;; this todo has children, check whether they are all
11408 ;; completed
11409 (if (and (not (org-entry-is-done-p))
11410 (org-entry-is-todo-p))
11411 (throw 'dont-block nil))
11412 (outline-next-heading)
11413 (setq child-level (funcall outline-level))))))
11414 ;; Otherwise, if the task's parent has the :ORDERED: property, and
11415 ;; any previous siblings are undone, it's blocked
11416 (save-excursion
11417 (org-back-to-heading t)
11418 (let* ((pos (point))
11419 (parent-pos (and (org-up-heading-safe) (point))))
11420 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11421 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11422 (forward-line 1)
11423 (re-search-forward org-not-done-heading-regexp pos t))
11424 (throw 'dont-block nil)) ; block, there is an older sibling not done.
11425 ;; Search further up the hierarchy, to see if an anchestor is blocked
11426 (while t
11427 (goto-char parent-pos)
11428 (if (not (looking-at org-not-done-heading-regexp))
11429 (throw 'dont-block t)) ; do not block, parent is not a TODO
11430 (setq pos (point))
11431 (setq parent-pos (and (org-up-heading-safe) (point)))
11432 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11433 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11434 (forward-line 1)
11435 (re-search-forward org-not-done-heading-regexp pos t))
11436 (throw 'dont-block nil)))))))) ; block, older sibling not done.
11438 (defcustom org-track-ordered-property-with-tag nil
11439 "Should the ORDERED property also be shown as a tag?
11440 The ORDERED property decides if an entry should require subtasks to be
11441 completed in sequence. Since a property is not very visible, setting
11442 this option means that toggling the ORDERED property with the command
11443 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
11444 not relevant for the behavior, but it makes things more visible.
11446 Note that toggling the tag with tags commands will not change the property
11447 and therefore not influence behavior!
11449 This can be t, meaning the tag ORDERED should be used, It can also be a
11450 string to select a different tag for this task."
11451 :group 'org-todo
11452 :type '(choice
11453 (const :tag "No tracking" nil)
11454 (const :tag "Track with ORDERED tag" t)
11455 (string :tag "Use other tag")))
11457 (defun org-toggle-ordered-property ()
11458 "Toggle the ORDERED property of the current entry.
11459 For better visibility, you can track the value of this property with a tag.
11460 See variable `org-track-ordered-property-with-tag'."
11461 (interactive)
11462 (let* ((t1 org-track-ordered-property-with-tag)
11463 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
11464 (save-excursion
11465 (org-back-to-heading)
11466 (if (org-entry-get nil "ORDERED")
11467 (progn
11468 (org-delete-property "ORDERED")
11469 (and tag (org-toggle-tag tag 'off))
11470 (message "Subtasks can be completed in arbitrary order"))
11471 (org-entry-put nil "ORDERED" "t")
11472 (and tag (org-toggle-tag tag 'on))
11473 (message "Subtasks must be completed in sequence")))))
11475 (defvar org-blocked-by-checkboxes) ; dynamically scoped
11476 (defun org-block-todo-from-checkboxes (change-plist)
11477 "Block turning an entry into a TODO, using checkboxes.
11478 This checks whether the current task should be blocked from state
11479 changes because there are unchecked boxes in this entry."
11480 (if (not org-enforce-todo-checkbox-dependencies)
11481 t ; if locally turned off don't block
11482 (catch 'dont-block
11483 ;; If this is not a todo state change, or if this entry is already DONE,
11484 ;; do not block
11485 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11486 (member (plist-get change-plist :from)
11487 (cons 'done org-done-keywords))
11488 (member (plist-get change-plist :to)
11489 (cons 'todo org-not-done-keywords))
11490 (not (plist-get change-plist :to)))
11491 (throw 'dont-block t))
11492 ;; If this task has checkboxes that are not checked, it's blocked
11493 (save-excursion
11494 (org-back-to-heading t)
11495 (let ((beg (point)) end)
11496 (outline-next-heading)
11497 (setq end (point))
11498 (goto-char beg)
11499 (if (org-list-search-forward
11500 (concat (org-item-beginning-re)
11501 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
11502 "\\[[- ]\\]")
11503 end t)
11504 (progn
11505 (if (boundp 'org-blocked-by-checkboxes)
11506 (setq org-blocked-by-checkboxes t))
11507 (throw 'dont-block nil)))))
11508 t))) ; do not block
11510 (defun org-entry-blocked-p ()
11511 "Is the current entry blocked?"
11512 (if (org-entry-get nil "NOBLOCKING")
11513 nil ;; Never block this entry
11514 (not
11515 (run-hook-with-args-until-failure
11516 'org-blocker-hook
11517 (list :type 'todo-state-change
11518 :position (point)
11519 :from 'todo
11520 :to 'done)))))
11522 (defun org-update-statistics-cookies (all)
11523 "Update the statistics cookie, either from TODO or from checkboxes.
11524 This should be called with the cursor in a line with a statistics cookie."
11525 (interactive "P")
11526 (if all
11527 (progn
11528 (org-update-checkbox-count 'all)
11529 (org-map-entries 'org-update-parent-todo-statistics))
11530 (if (not (org-on-heading-p))
11531 (org-update-checkbox-count)
11532 (let ((pos (move-marker (make-marker) (point)))
11533 end l1 l2)
11534 (ignore-errors (org-back-to-heading t))
11535 (if (not (org-on-heading-p))
11536 (org-update-checkbox-count)
11537 (setq l1 (org-outline-level))
11538 (setq end (save-excursion
11539 (outline-next-heading)
11540 (if (org-on-heading-p) (setq l2 (org-outline-level)))
11541 (point)))
11542 (if (and (save-excursion
11543 (re-search-forward
11544 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
11545 (not (save-excursion (re-search-forward
11546 ":COOKIE_DATA:.*\\<todo\\>" end t))))
11547 (org-update-checkbox-count)
11548 (if (and l2 (> l2 l1))
11549 (progn
11550 (goto-char end)
11551 (org-update-parent-todo-statistics))
11552 (goto-char pos)
11553 (beginning-of-line 1)
11554 (while (re-search-forward
11555 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
11556 (point-at-eol) t)
11557 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
11558 (goto-char pos)
11559 (move-marker pos nil)))))
11561 (defvar org-entry-property-inherited-from) ;; defined below
11562 (defun org-update-parent-todo-statistics ()
11563 "Update any statistics cookie in the parent of the current headline.
11564 When `org-hierarchical-todo-statistics' is nil, statistics will cover
11565 the entire subtree and this will travel up the hierarchy and update
11566 statistics everywhere."
11567 (let* ((prop (save-excursion (org-up-heading-safe)
11568 (org-entry-get nil "COOKIE_DATA" 'inherit)))
11569 (recursive (or (not org-hierarchical-todo-statistics)
11570 (and prop (string-match "\\<recursive\\>" prop))))
11571 (lim (or (and prop (marker-position org-entry-property-inherited-from))
11573 (first t)
11574 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
11575 level ltoggle l1 new ndel
11576 (cnt-all 0) (cnt-done 0) is-percent kwd
11577 checkbox-beg ov ovs ove cookie-present)
11578 (catch 'exit
11579 (save-excursion
11580 (beginning-of-line 1)
11581 (setq ltoggle (funcall outline-level))
11582 ;; Three situations are to consider:
11584 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
11585 ;; to the top-level ancestor on the headline;
11587 ;; 2. If parent has "recursive" property, repeat up to the
11588 ;; headline setting that property, taking inheritance into
11589 ;; account;
11591 ;; 3. Else, move up to direct parent and proceed only once.
11592 (while (and (setq level (org-up-heading-safe))
11593 (or recursive first)
11594 (>= (point) lim))
11595 (setq first nil cookie-present nil)
11596 (unless (and level
11597 (not (string-match
11598 "\\<checkbox\\>"
11599 (downcase (or (org-entry-get nil "COOKIE_DATA")
11600 "")))))
11601 (throw 'exit nil))
11602 (while (re-search-forward box-re (point-at-eol) t)
11603 (setq cnt-all 0 cnt-done 0 cookie-present t)
11604 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
11605 (save-match-data
11606 (unless (outline-next-heading) (throw 'exit nil))
11607 (while (and (looking-at org-complex-heading-regexp)
11608 (> (setq l1 (length (match-string 1))) level))
11609 (setq kwd (and (or recursive (= l1 ltoggle))
11610 (match-string 2)))
11611 (if (or (eq org-provide-todo-statistics 'all-headlines)
11612 (and (listp org-provide-todo-statistics)
11613 (or (member kwd org-provide-todo-statistics)
11614 (member kwd org-done-keywords))))
11615 (setq cnt-all (1+ cnt-all))
11616 (if (eq org-provide-todo-statistics t)
11617 (and kwd (setq cnt-all (1+ cnt-all)))))
11618 (and (member kwd org-done-keywords)
11619 (setq cnt-done (1+ cnt-done)))
11620 (outline-next-heading)))
11621 (setq new
11622 (if is-percent
11623 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
11624 (format "[%d/%d]" cnt-done cnt-all))
11625 ndel (- (match-end 0) checkbox-beg))
11626 ;; handle overlays when updating cookie from column view
11627 (when (setq ov (car (overlays-at checkbox-beg)))
11628 (setq ovs (overlay-start ov) ove (overlay-end ov))
11629 (delete-overlay ov))
11630 (goto-char checkbox-beg)
11631 (insert new)
11632 (delete-region (point) (+ (point) ndel))
11633 (when org-auto-align-tags (org-fix-tags-on-the-fly))
11634 (when ov (move-overlay ov ovs ove)))
11635 (when cookie-present
11636 (run-hook-with-args 'org-after-todo-statistics-hook
11637 cnt-done (- cnt-all cnt-done))))))
11638 (run-hooks 'org-todo-statistics-hook)))
11640 (defvar org-after-todo-statistics-hook nil
11641 "Hook that is called after a TODO statistics cookie has been updated.
11642 Each function is called with two arguments: the number of not-done entries
11643 and the number of done entries.
11645 For example, the following function, when added to this hook, will switch
11646 an entry to DONE when all children are done, and back to TODO when new
11647 entries are set to a TODO status. Note that this hook is only called
11648 when there is a statistics cookie in the headline!
11650 (defun org-summary-todo (n-done n-not-done)
11651 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
11652 (let (org-log-done org-log-states) ; turn off logging
11653 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
11656 (defvar org-todo-statistics-hook nil
11657 "Hook that is run whenever Org thinks TODO statistics should be updated.
11658 This hook runs even if there is no statistics cookie present, in which case
11659 `org-after-todo-statistics-hook' would not run.")
11661 (defun org-todo-trigger-tag-changes (state)
11662 "Apply the changes defined in `org-todo-state-tags-triggers'."
11663 (let ((l org-todo-state-tags-triggers)
11664 changes)
11665 (when (or (not state) (equal state ""))
11666 (setq changes (append changes (cdr (assoc "" l)))))
11667 (when (and (stringp state) (> (length state) 0))
11668 (setq changes (append changes (cdr (assoc state l)))))
11669 (when (member state org-not-done-keywords)
11670 (setq changes (append changes (cdr (assoc 'todo l)))))
11671 (when (member state org-done-keywords)
11672 (setq changes (append changes (cdr (assoc 'done l)))))
11673 (dolist (c changes)
11674 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
11676 (defun org-local-logging (value)
11677 "Get logging settings from a property VALUE."
11678 (let* (words w a)
11679 ;; directly set the variables, they are already local.
11680 (setq org-log-done nil
11681 org-log-repeat nil
11682 org-todo-log-states nil)
11683 (setq words (org-split-string value))
11684 (while (setq w (pop words))
11685 (cond
11686 ((setq a (assoc w org-startup-options))
11687 (and (member (nth 1 a) '(org-log-done org-log-repeat))
11688 (set (nth 1 a) (nth 2 a))))
11689 ((setq a (org-extract-log-state-settings w))
11690 (and (member (car a) org-todo-keywords-1)
11691 (push a org-todo-log-states)))))))
11693 (defun org-get-todo-sequence-head (kwd)
11694 "Return the head of the TODO sequence to which KWD belongs.
11695 If KWD is not set, check if there is a text property remembering the
11696 right sequence."
11697 (let (p)
11698 (cond
11699 ((not kwd)
11700 (or (get-text-property (point-at-bol) 'org-todo-head)
11701 (progn
11702 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
11703 nil (point-at-eol)))
11704 (get-text-property p 'org-todo-head))))
11705 ((not (member kwd org-todo-keywords-1))
11706 (car org-todo-keywords-1))
11707 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
11709 (defun org-fast-todo-selection ()
11710 "Fast TODO keyword selection with single keys.
11711 Returns the new TODO keyword, or nil if no state change should occur."
11712 (let* ((fulltable org-todo-key-alist)
11713 (done-keywords org-done-keywords) ;; needed for the faces.
11714 (maxlen (apply 'max (mapcar
11715 (lambda (x)
11716 (if (stringp (car x)) (string-width (car x)) 0))
11717 fulltable)))
11718 (expert nil)
11719 (fwidth (+ maxlen 3 1 3))
11720 (ncol (/ (- (window-width) 4) fwidth))
11721 tg cnt e c tbl
11722 groups ingroup)
11723 (save-excursion
11724 (save-window-excursion
11725 (if expert
11726 (set-buffer (get-buffer-create " *Org todo*"))
11727 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
11728 (erase-buffer)
11729 (org-set-local 'org-done-keywords done-keywords)
11730 (setq tbl fulltable cnt 0)
11731 (while (setq e (pop tbl))
11732 (cond
11733 ((equal e '(:startgroup))
11734 (push '() groups) (setq ingroup t)
11735 (when (not (= cnt 0))
11736 (setq cnt 0)
11737 (insert "\n"))
11738 (insert "{ "))
11739 ((equal e '(:endgroup))
11740 (setq ingroup nil cnt 0)
11741 (insert "}\n"))
11742 ((equal e '(:newline))
11743 (when (not (= cnt 0))
11744 (setq cnt 0)
11745 (insert "\n")
11746 (setq e (car tbl))
11747 (while (equal (car tbl) '(:newline))
11748 (insert "\n")
11749 (setq tbl (cdr tbl)))))
11751 (setq tg (car e) c (cdr e))
11752 (if ingroup (push tg (car groups)))
11753 (setq tg (org-add-props tg nil 'face
11754 (org-get-todo-face tg)))
11755 (if (and (= cnt 0) (not ingroup)) (insert " "))
11756 (insert "[" c "] " tg (make-string
11757 (- fwidth 4 (length tg)) ?\ ))
11758 (when (= (setq cnt (1+ cnt)) ncol)
11759 (insert "\n")
11760 (if ingroup (insert " "))
11761 (setq cnt 0)))))
11762 (insert "\n")
11763 (goto-char (point-min))
11764 (if (not expert) (org-fit-window-to-buffer))
11765 (message "[a-z..]:Set [SPC]:clear")
11766 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
11767 (cond
11768 ((or (= c ?\C-g)
11769 (and (= c ?q) (not (rassoc c fulltable))))
11770 (setq quit-flag t))
11771 ((= c ?\ ) nil)
11772 ((setq e (rassoc c fulltable) tg (car e))
11774 (t (setq quit-flag t)))))))
11776 (defun org-entry-is-todo-p ()
11777 (member (org-get-todo-state) org-not-done-keywords))
11779 (defun org-entry-is-done-p ()
11780 (member (org-get-todo-state) org-done-keywords))
11782 (defun org-get-todo-state ()
11783 (save-excursion
11784 (org-back-to-heading t)
11785 (and (looking-at org-todo-line-regexp)
11786 (match-end 2)
11787 (match-string 2))))
11789 (defun org-at-date-range-p (&optional inactive-ok)
11790 "Is the cursor inside a date range?"
11791 (interactive)
11792 (save-excursion
11793 (catch 'exit
11794 (let ((pos (point)))
11795 (skip-chars-backward "^[<\r\n")
11796 (skip-chars-backward "<[")
11797 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
11798 (>= (match-end 0) pos)
11799 (throw 'exit t))
11800 (skip-chars-backward "^<[\r\n")
11801 (skip-chars-backward "<[")
11802 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
11803 (>= (match-end 0) pos)
11804 (throw 'exit t)))
11805 nil)))
11807 (defun org-get-repeat (&optional tagline)
11808 "Check if there is a deadline/schedule with repeater in this entry."
11809 (save-match-data
11810 (save-excursion
11811 (org-back-to-heading t)
11812 (and (re-search-forward (if tagline
11813 (concat tagline "\\s-*" org-repeat-re)
11814 org-repeat-re)
11815 (org-entry-end-position) t)
11816 (match-string-no-properties 1)))))
11818 (defvar org-last-changed-timestamp)
11819 (defvar org-last-inserted-timestamp)
11820 (defvar org-log-post-message)
11821 (defvar org-log-note-purpose)
11822 (defvar org-log-note-how)
11823 (defvar org-log-note-extra)
11824 (defun org-auto-repeat-maybe (done-word)
11825 "Check if the current headline contains a repeated deadline/schedule.
11826 If yes, set TODO state back to what it was and change the base date
11827 of repeating deadline/scheduled time stamps to new date.
11828 This function is run automatically after each state change to a DONE state."
11829 ;; last-state is dynamically scoped into this function
11830 (let* ((repeat (org-get-repeat))
11831 (aa (assoc last-state org-todo-kwd-alist))
11832 (interpret (nth 1 aa))
11833 (head (nth 2 aa))
11834 (whata '(("d" . day) ("m" . month) ("y" . year)))
11835 (msg "Entry repeats: ")
11836 (org-log-done nil)
11837 (org-todo-log-states nil)
11838 re type n what ts time to-state)
11839 (when repeat
11840 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
11841 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
11842 org-todo-repeat-to-state))
11843 (unless (and to-state (member to-state org-todo-keywords-1))
11844 (setq to-state (if (eq interpret 'type) last-state head)))
11845 (org-todo to-state)
11846 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
11847 (org-entry-put nil "LAST_REPEAT" (format-time-string
11848 (org-time-stamp-format t t))))
11849 (when org-log-repeat
11850 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
11851 (memq 'org-add-log-note post-command-hook))
11852 ;; OK, we are already setup for some record
11853 (if (eq org-log-repeat 'note)
11854 ;; make sure we take a note, not only a time stamp
11855 (setq org-log-note-how 'note))
11856 ;; Set up for taking a record
11857 (org-add-log-setup 'state (or done-word (car org-done-keywords))
11858 last-state
11859 'findpos org-log-repeat)))
11860 (org-back-to-heading t)
11861 (org-add-planning-info nil nil 'closed)
11862 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
11863 org-deadline-time-regexp "\\)\\|\\("
11864 org-ts-regexp "\\)"))
11865 (while (re-search-forward
11866 re (save-excursion (outline-next-heading) (point)) t)
11867 (setq type (if (match-end 1) org-scheduled-string
11868 (if (match-end 3) org-deadline-string "Plain:"))
11869 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
11870 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
11871 (setq n (string-to-number (match-string 2 ts))
11872 what (match-string 3 ts))
11873 (if (equal what "w") (setq n (* n 7) what "d"))
11874 ;; Preparation, see if we need to modify the start date for the change
11875 (when (match-end 1)
11876 (setq time (save-match-data (org-time-string-to-time ts)))
11877 (cond
11878 ((equal (match-string 1 ts) ".")
11879 ;; Shift starting date to today
11880 (org-timestamp-change
11881 (- (org-today) (time-to-days time))
11882 'day))
11883 ((equal (match-string 1 ts) "+")
11884 (let ((nshiftmax 10) (nshift 0))
11885 (while (or (= nshift 0)
11886 (<= (time-to-days time)
11887 (time-to-days (current-time))))
11888 (when (= (incf nshift) nshiftmax)
11889 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
11890 (error "Abort")))
11891 (org-timestamp-change n (cdr (assoc what whata)))
11892 (org-at-timestamp-p t)
11893 (setq ts (match-string 1))
11894 (setq time (save-match-data (org-time-string-to-time ts)))))
11895 (org-timestamp-change (- n) (cdr (assoc what whata)))
11896 ;; rematch, so that we have everything in place for the real shift
11897 (org-at-timestamp-p t)
11898 (setq ts (match-string 1))
11899 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
11900 (org-timestamp-change n (cdr (assoc what whata)))
11901 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
11902 (setq org-log-post-message msg)
11903 (message "%s" msg))))
11905 (defun org-show-todo-tree (arg)
11906 "Make a compact tree which shows all headlines marked with TODO.
11907 The tree will show the lines where the regexp matches, and all higher
11908 headlines above the match.
11909 With a \\[universal-argument] prefix, prompt for a regexp to match.
11910 With a numeric prefix N, construct a sparse tree for the Nth element
11911 of `org-todo-keywords-1'."
11912 (interactive "P")
11913 (let ((case-fold-search nil)
11914 (kwd-re
11915 (cond ((null arg) org-not-done-regexp)
11916 ((equal arg '(4))
11917 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
11918 (mapcar 'list org-todo-keywords-1))))
11919 (concat "\\("
11920 (mapconcat 'identity (org-split-string kwd "|") "\\|")
11921 "\\)\\>")))
11922 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
11923 (regexp-quote (nth (1- (prefix-numeric-value arg))
11924 org-todo-keywords-1)))
11925 (t (error "Invalid prefix argument: %s" arg)))))
11926 (message "%d TODO entries found"
11927 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
11929 (defun org-deadline (&optional remove time)
11930 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
11931 With argument REMOVE, remove any deadline from the item.
11932 With argument TIME, set the deadline at the corresponding date. TIME
11933 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
11934 (interactive "P")
11935 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11936 (let (org-loop-over-headlines-in-active-region)
11937 (org-map-entries
11938 `(org-deadline ',remove ,time) org-loop-over-headlines-in-active-region 'region (if (outline-invisible-p) (org-end-of-subtree nil t))))
11939 (let* ((old-date (org-entry-get nil "DEADLINE"))
11940 (repeater (and old-date
11941 (string-match
11942 "\\([.+-]+[0-9]+[dwmy]\\(?:[/ ][-+]?[0-9]+[dwmy]\\)?\\) ?"
11943 old-date)
11944 (match-string 1 old-date))))
11945 (if remove
11946 (progn
11947 (when (and old-date org-log-redeadline)
11948 (org-add-log-setup 'deldeadline nil old-date 'findpos
11949 org-log-redeadline))
11950 (org-remove-timestamp-with-keyword org-deadline-string)
11951 (message "Item no longer has a deadline."))
11952 (org-add-planning-info 'deadline time 'closed)
11953 (when (and old-date org-log-redeadline
11954 (not (equal old-date
11955 (substring org-last-inserted-timestamp 1 -1))))
11956 (org-add-log-setup 'redeadline nil old-date 'findpos
11957 org-log-redeadline))
11958 (when repeater
11959 (save-excursion
11960 (org-back-to-heading t)
11961 (when (re-search-forward (concat org-deadline-string " "
11962 org-last-inserted-timestamp)
11963 (save-excursion
11964 (outline-next-heading) (point)) t)
11965 (goto-char (1- (match-end 0)))
11966 (insert " " repeater)
11967 (setq org-last-inserted-timestamp
11968 (concat (substring org-last-inserted-timestamp 0 -1)
11969 " " repeater
11970 (substring org-last-inserted-timestamp -1))))))
11971 (message "Deadline on %s" org-last-inserted-timestamp)))))
11973 (defun org-schedule (&optional remove time)
11974 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
11975 With argument REMOVE, remove any scheduling date from the item.
11976 With argument TIME, scheduled at the corresponding date. TIME can
11977 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
11978 (interactive "P")
11979 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11980 (let (org-loop-over-headlines-in-active-region)
11981 (org-map-entries
11982 `(org-schedule ',remove ,time) org-loop-over-headlines-in-active-region 'region (if (outline-invisible-p) (org-end-of-subtree nil t))))
11983 (let* ((old-date (org-entry-get nil "SCHEDULED"))
11984 (repeater (and old-date
11985 (string-match
11986 "\\([.+-]+[0-9]+[dwmy]\\(?:[/ ][-+]?[0-9]+[dwmy]\\)?\\) ?"
11987 old-date)
11988 (match-string 1 old-date))))
11989 (if remove
11990 (progn
11991 (when (and old-date org-log-reschedule)
11992 (org-add-log-setup 'delschedule nil old-date 'findpos
11993 org-log-reschedule))
11994 (org-remove-timestamp-with-keyword org-scheduled-string)
11995 (message "Item is no longer scheduled."))
11996 (org-add-planning-info 'scheduled time 'closed)
11997 (when (and old-date org-log-reschedule
11998 (not (equal old-date
11999 (substring org-last-inserted-timestamp 1 -1))))
12000 (org-add-log-setup 'reschedule nil old-date 'findpos
12001 org-log-reschedule))
12002 (when repeater
12003 (save-excursion
12004 (org-back-to-heading t)
12005 (when (re-search-forward (concat org-scheduled-string " "
12006 org-last-inserted-timestamp)
12007 (save-excursion
12008 (outline-next-heading) (point)) t)
12009 (goto-char (1- (match-end 0)))
12010 (insert " " repeater)
12011 (setq org-last-inserted-timestamp
12012 (concat (substring org-last-inserted-timestamp 0 -1)
12013 " " repeater
12014 (substring org-last-inserted-timestamp -1))))))
12015 (message "Scheduled to %s" org-last-inserted-timestamp)))))
12017 (defun org-get-scheduled-time (pom &optional inherit)
12018 "Get the scheduled time as a time tuple, of a format suitable
12019 for calling org-schedule with, or if there is no scheduling,
12020 returns nil."
12021 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12022 (when time
12023 (apply 'encode-time (org-parse-time-string time)))))
12025 (defun org-get-deadline-time (pom &optional inherit)
12026 "Get the deadline as a time tuple, of a format suitable for
12027 calling org-deadline with, or if there is no scheduling, returns
12028 nil."
12029 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12030 (when time
12031 (apply 'encode-time (org-parse-time-string time)))))
12033 (defun org-remove-timestamp-with-keyword (keyword)
12034 "Remove all time stamps with KEYWORD in the current entry."
12035 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12036 beg)
12037 (save-excursion
12038 (org-back-to-heading t)
12039 (setq beg (point))
12040 (outline-next-heading)
12041 (while (re-search-backward re beg t)
12042 (replace-match "")
12043 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12044 (equal (char-before) ?\ ))
12045 (backward-delete-char 1)
12046 (if (string-match "^[ \t]*$" (buffer-substring
12047 (point-at-bol) (point-at-eol)))
12048 (delete-region (point-at-bol)
12049 (min (point-max) (1+ (point-at-eol))))))))))
12051 (defun org-add-planning-info (what &optional time &rest remove)
12052 "Insert new timestamp with keyword in the line directly after the headline.
12053 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
12054 If non is given, the user is prompted for a date.
12055 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
12056 be removed."
12057 (interactive)
12058 (let (org-time-was-given org-end-time-was-given ts
12059 end default-time default-input)
12061 (catch 'exit
12062 (when (and (memq what '(scheduled deadline))
12063 (or (not time)
12064 (and (stringp time)
12065 (string-match "^[-+]+[0-9]" time))))
12066 ;; Try to get a default date/time from existing timestamp
12067 (save-excursion
12068 (org-back-to-heading t)
12069 (setq end (save-excursion (outline-next-heading) (point)))
12070 (when (re-search-forward (if (eq what 'scheduled)
12071 org-scheduled-time-regexp
12072 org-deadline-time-regexp)
12073 end t)
12074 (setq ts (match-string 1)
12075 default-time
12076 (apply 'encode-time (org-parse-time-string ts))
12077 default-input (and ts (org-get-compact-tod ts))))))
12078 (when what
12079 (setq time
12080 (if (and (stringp time)
12081 (string-match "^[-+]+[0-9]" time))
12082 ;; This is a relative time, set the proper date
12083 (apply 'encode-time
12084 (org-read-date-analyze
12085 time default-time (decode-time default-time)))
12086 ;; If necessary, get the time from the user
12087 (or time (org-read-date nil 'to-time nil nil
12088 default-time default-input)))))
12090 (when (and org-insert-labeled-timestamps-at-point
12091 (member what '(scheduled deadline)))
12092 (insert
12093 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
12094 (org-insert-time-stamp time org-time-was-given
12095 nil nil nil (list org-end-time-was-given))
12096 (setq what nil))
12097 (save-excursion
12098 (save-restriction
12099 (let (col list elt ts buffer-invisibility-spec)
12100 (org-back-to-heading t)
12101 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
12102 (goto-char (match-end 1))
12103 (setq col (current-column))
12104 (goto-char (match-end 0))
12105 (if (eobp) (insert "\n") (forward-char 1))
12106 (when (and (not what)
12107 (not (looking-at
12108 (concat "[ \t]*"
12109 org-keyword-time-not-clock-regexp))))
12110 ;; Nothing to add, nothing to remove...... :-)
12111 (throw 'exit nil))
12112 (if (and (not (looking-at org-outline-regexp))
12113 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
12114 "[^\r\n]*"))
12115 (not (equal (match-string 1) org-clock-string)))
12116 (narrow-to-region (match-beginning 0) (match-end 0))
12117 (insert-before-markers "\n")
12118 (backward-char 1)
12119 (narrow-to-region (point) (point))
12120 (and org-adapt-indentation (org-indent-to-column col)))
12121 ;; Check if we have to remove something.
12122 (setq list (cons what remove))
12123 (while list
12124 (setq elt (pop list))
12125 (when (or (and (eq elt 'scheduled)
12126 (re-search-forward org-scheduled-time-regexp nil t))
12127 (and (eq elt 'deadline)
12128 (re-search-forward org-deadline-time-regexp nil t))
12129 (and (eq elt 'closed)
12130 (re-search-forward org-closed-time-regexp nil t)))
12131 (replace-match "")
12132 (if (looking-at "--+<[^>]+>") (replace-match ""))))
12133 (and (looking-at "[ \t]+") (replace-match ""))
12134 (and org-adapt-indentation (bolp) (org-indent-to-column col))
12135 (when what
12136 (insert
12137 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
12138 (cond ((eq what 'scheduled) org-scheduled-string)
12139 ((eq what 'deadline) org-deadline-string)
12140 ((eq what 'closed) org-closed-string))
12141 " ")
12142 (setq ts (org-insert-time-stamp
12143 time
12144 (or org-time-was-given
12145 (and (eq what 'closed) org-log-done-with-time))
12146 (eq what 'closed)
12147 nil nil (list org-end-time-was-given)))
12148 (insert
12149 (if (not (or (bolp) (eq (char-before) ?\ )
12150 (memq (char-after) '(32 10))
12151 (eobp))) " " ""))
12152 (end-of-line 1))
12153 (goto-char (point-min))
12154 (widen)
12155 (if (and (looking-at "[ \t]*\n")
12156 (equal (char-before) ?\n))
12157 (delete-region (1- (point)) (point-at-eol)))
12158 ts))))))
12160 (defvar org-log-note-marker (make-marker))
12161 (defvar org-log-note-purpose nil)
12162 (defvar org-log-note-state nil)
12163 (defvar org-log-note-previous-state nil)
12164 (defvar org-log-note-how nil)
12165 (defvar org-log-note-extra nil)
12166 (defvar org-log-note-window-configuration nil)
12167 (defvar org-log-note-return-to (make-marker))
12168 (defvar org-log-note-effective-time nil
12169 "Remembered current time so that dynamically scoped
12170 `org-extend-today-until' affects tha timestamps in state change
12171 log")
12173 (defvar org-log-post-message nil
12174 "Message to be displayed after a log note has been stored.
12175 The auto-repeater uses this.")
12177 (defun org-add-note ()
12178 "Add a note to the current entry.
12179 This is done in the same way as adding a state change note."
12180 (interactive)
12181 (org-add-log-setup 'note nil nil 'findpos nil))
12183 (defvar org-property-end-re)
12184 (defun org-add-log-setup (&optional purpose state prev-state
12185 findpos how extra)
12186 "Set up the post command hook to take a note.
12187 If this is about to TODO state change, the new state is expected in STATE.
12188 When FINDPOS is non-nil, find the correct position for the note in
12189 the current entry. If not, assume that it can be inserted at point.
12190 HOW is an indicator what kind of note should be created.
12191 EXTRA is additional text that will be inserted into the notes buffer."
12192 (let* ((org-log-into-drawer (org-log-into-drawer))
12193 (drawer (cond ((stringp org-log-into-drawer)
12194 org-log-into-drawer)
12195 (org-log-into-drawer "LOGBOOK")
12196 (t nil))))
12197 (save-restriction
12198 (save-excursion
12199 (when findpos
12200 (org-back-to-heading t)
12201 (narrow-to-region (point) (save-excursion
12202 (outline-next-heading) (point)))
12203 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
12204 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
12205 "[^\r\n]*\\)?"))
12206 (goto-char (match-end 0))
12207 (cond
12208 (drawer
12209 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
12210 nil t)
12211 (progn
12212 (goto-char (match-end 0))
12213 (or org-log-states-order-reversed
12214 (and (re-search-forward org-property-end-re nil t)
12215 (goto-char (1- (match-beginning 0))))))
12216 (insert "\n:" drawer ":\n:END:")
12217 (beginning-of-line 0)
12218 (org-indent-line-function)
12219 (beginning-of-line 2)
12220 (org-indent-line-function)
12221 (end-of-line 0)))
12222 ((and org-log-state-notes-insert-after-drawers
12223 (save-excursion
12224 (forward-line) (looking-at org-drawer-regexp)))
12225 (forward-line)
12226 (while (looking-at org-drawer-regexp)
12227 (goto-char (match-end 0))
12228 (re-search-forward org-property-end-re (point-max) t)
12229 (forward-line))
12230 (forward-line -1)))
12231 (unless org-log-states-order-reversed
12232 (and (= (char-after) ?\n) (forward-char 1))
12233 (org-skip-over-state-notes)
12234 (skip-chars-backward " \t\n\r")))
12235 (move-marker org-log-note-marker (point))
12236 (setq org-log-note-purpose purpose
12237 org-log-note-state state
12238 org-log-note-previous-state prev-state
12239 org-log-note-how how
12240 org-log-note-extra extra
12241 org-log-note-effective-time (org-current-effective-time))
12242 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
12244 (defun org-skip-over-state-notes ()
12245 "Skip past the list of State notes in an entry."
12246 (if (looking-at "\n[ \t]*- State") (forward-char 1))
12247 (when (ignore-errors (goto-char (org-in-item-p)))
12248 (let* ((struct (org-list-struct))
12249 (prevs (org-list-prevs-alist struct)))
12250 (while (looking-at "[ \t]*- State")
12251 (goto-char (or (org-list-get-next-item (point) struct prevs)
12252 (org-list-get-item-end (point) struct)))))))
12254 (defun org-add-log-note (&optional purpose)
12255 "Pop up a window for taking a note, and add this note later at point."
12256 (remove-hook 'post-command-hook 'org-add-log-note)
12257 (setq org-log-note-window-configuration (current-window-configuration))
12258 (delete-other-windows)
12259 (move-marker org-log-note-return-to (point))
12260 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
12261 (goto-char org-log-note-marker)
12262 (org-switch-to-buffer-other-window "*Org Note*")
12263 (erase-buffer)
12264 (if (memq org-log-note-how '(time state))
12265 (let (current-prefix-arg) (org-store-log-note))
12266 (let ((org-inhibit-startup t)) (org-mode))
12267 (insert (format "# Insert note for %s.
12268 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
12269 (cond
12270 ((eq org-log-note-purpose 'clock-out) "stopped clock")
12271 ((eq org-log-note-purpose 'done) "closed todo item")
12272 ((eq org-log-note-purpose 'state)
12273 (format "state change from \"%s\" to \"%s\""
12274 (or org-log-note-previous-state "")
12275 (or org-log-note-state "")))
12276 ((eq org-log-note-purpose 'reschedule)
12277 "rescheduling")
12278 ((eq org-log-note-purpose 'delschedule)
12279 "no longer scheduled")
12280 ((eq org-log-note-purpose 'redeadline)
12281 "changing deadline")
12282 ((eq org-log-note-purpose 'deldeadline)
12283 "removing deadline")
12284 ((eq org-log-note-purpose 'refile)
12285 "refiling")
12286 ((eq org-log-note-purpose 'note)
12287 "this entry")
12288 (t (error "This should not happen")))))
12289 (if org-log-note-extra (insert org-log-note-extra))
12290 (org-set-local 'org-finish-function 'org-store-log-note)
12291 (run-hooks 'org-log-buffer-setup-hook)))
12293 (defvar org-note-abort nil) ; dynamically scoped
12294 (defun org-store-log-note ()
12295 "Finish taking a log note, and insert it to where it belongs."
12296 (let ((txt (buffer-string))
12297 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
12298 lines ind bul)
12299 (kill-buffer (current-buffer))
12300 (while (string-match "\\`#.*\n[ \t\n]*" txt)
12301 (setq txt (replace-match "" t t txt)))
12302 (if (string-match "\\s-+\\'" txt)
12303 (setq txt (replace-match "" t t txt)))
12304 (setq lines (org-split-string txt "\n"))
12305 (when (and note (string-match "\\S-" note))
12306 (setq note
12307 (org-replace-escapes
12308 note
12309 (list (cons "%u" (user-login-name))
12310 (cons "%U" user-full-name)
12311 (cons "%t" (format-time-string
12312 (org-time-stamp-format 'long 'inactive)
12313 org-log-note-effective-time))
12314 (cons "%T" (format-time-string
12315 (org-time-stamp-format 'long nil)
12316 org-log-note-effective-time))
12317 (cons "%d" (format-time-string
12318 (org-time-stamp-format nil 'inactive)
12319 org-log-note-effective-time))
12320 (cons "%D" (format-time-string
12321 (org-time-stamp-format nil nil)
12322 org-log-note-effective-time))
12323 (cons "%s" (if org-log-note-state
12324 (concat "\"" org-log-note-state "\"")
12325 ""))
12326 (cons "%S" (if org-log-note-previous-state
12327 (concat "\"" org-log-note-previous-state "\"")
12328 "\"\"")))))
12329 (if lines (setq note (concat note " \\\\")))
12330 (push note lines))
12331 (when (or current-prefix-arg org-note-abort)
12332 (when org-log-into-drawer
12333 (org-remove-empty-drawer-at
12334 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
12335 org-log-note-marker))
12336 (setq lines nil))
12337 (when lines
12338 (with-current-buffer (marker-buffer org-log-note-marker)
12339 (save-excursion
12340 (goto-char org-log-note-marker)
12341 (move-marker org-log-note-marker nil)
12342 (end-of-line 1)
12343 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
12344 (setq ind (save-excursion
12345 (if (ignore-errors (goto-char (org-in-item-p)))
12346 (let ((struct (org-list-struct)))
12347 (org-list-get-ind
12348 (org-list-get-top-point struct) struct))
12349 (skip-chars-backward " \r\t\n")
12350 (cond
12351 ((and (org-at-heading-p)
12352 org-adapt-indentation)
12353 (1+ (org-current-level)))
12354 ((org-at-heading-p) 0)
12355 (t (org-get-indentation))))))
12356 (setq bul (org-list-bullet-string "-"))
12357 (org-indent-line-to ind)
12358 (insert bul (pop lines))
12359 (let ((ind-body (+ (length bul) ind)))
12360 (while lines
12361 (insert "\n")
12362 (org-indent-line-to ind-body)
12363 (insert (pop lines))))
12364 (message "Note stored")
12365 (org-back-to-heading t)
12366 (org-cycle-hide-drawers 'children)))))
12367 (set-window-configuration org-log-note-window-configuration)
12368 (with-current-buffer (marker-buffer org-log-note-return-to)
12369 (goto-char org-log-note-return-to))
12370 (move-marker org-log-note-return-to nil)
12371 (and org-log-post-message (message "%s" org-log-post-message)))
12373 (defun org-remove-empty-drawer-at (drawer pos)
12374 "Remove an empty drawer DRAWER at position POS.
12375 POS may also be a marker."
12376 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
12377 (save-excursion
12378 (save-restriction
12379 (widen)
12380 (goto-char pos)
12381 (if (org-in-regexp
12382 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
12383 (replace-match ""))))))
12385 (defun org-sparse-tree (&optional arg)
12386 "Create a sparse tree, prompt for the details.
12387 This command can create sparse trees. You first need to select the type
12388 of match used to create the tree:
12390 t Show all TODO entries.
12391 T Show entries with a specific TODO keyword.
12392 m Show entries selected by a tags/property match.
12393 p Enter a property name and its value (both with completion on existing
12394 names/values) and show entries with that property.
12395 r Show entries matching a regular expression (`/' can be used as well)
12396 d Show deadlines due within `org-deadline-warning-days'.
12397 b Show deadlines and scheduled items before a date.
12398 a Show deadlines and scheduled items after a date."
12399 (interactive "P")
12400 (let (ans kwd value)
12401 (message "Sparse tree: [r]egexp [/]regexp [t]odo [T]odo-kwd [m]atch [p]roperty\n [d]eadlines [b]efore-date [a]fter-date")
12402 (setq ans (read-char-exclusive))
12403 (cond
12404 ((equal ans ?d)
12405 (call-interactively 'org-check-deadlines))
12406 ((equal ans ?b)
12407 (call-interactively 'org-check-before-date))
12408 ((equal ans ?a)
12409 (call-interactively 'org-check-after-date))
12410 ((equal ans ?t)
12411 (org-show-todo-tree nil))
12412 ((equal ans ?T)
12413 (org-show-todo-tree '(4)))
12414 ((member ans '(?T ?m))
12415 (call-interactively 'org-match-sparse-tree))
12416 ((member ans '(?p ?P))
12417 (setq kwd (org-icompleting-read "Property: "
12418 (mapcar 'list (org-buffer-property-keys))))
12419 (setq value (org-icompleting-read "Value: "
12420 (mapcar 'list (org-property-values kwd))))
12421 (unless (string-match "\\`{.*}\\'" value)
12422 (setq value (concat "\"" value "\"")))
12423 (org-match-sparse-tree arg (concat kwd "=" value)))
12424 ((member ans '(?r ?R ?/))
12425 (call-interactively 'org-occur))
12426 (t (error "No such sparse tree command \"%c\"" ans)))))
12428 (defvar org-occur-highlights nil
12429 "List of overlays used for occur matches.")
12430 (make-variable-buffer-local 'org-occur-highlights)
12431 (defvar org-occur-parameters nil
12432 "Parameters of the active org-occur calls.
12433 This is a list, each call to org-occur pushes as cons cell,
12434 containing the regular expression and the callback, onto the list.
12435 The list can contain several entries if `org-occur' has been called
12436 several time with the KEEP-PREVIOUS argument. Otherwise, this list
12437 will only contain one set of parameters. When the highlights are
12438 removed (for example with `C-c C-c', or with the next edit (depending
12439 on `org-remove-highlights-with-change'), this variable is emptied
12440 as well.")
12441 (make-variable-buffer-local 'org-occur-parameters)
12443 (defun org-occur (regexp &optional keep-previous callback)
12444 "Make a compact tree which shows all matches of REGEXP.
12445 The tree will show the lines where the regexp matches, and all higher
12446 headlines above the match. It will also show the heading after the match,
12447 to make sure editing the matching entry is easy.
12448 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
12449 call to `org-occur' will be kept, to allow stacking of calls to this
12450 command.
12451 If CALLBACK is non-nil, it is a function which is called to confirm
12452 that the match should indeed be shown."
12453 (interactive "sRegexp: \nP")
12454 (when (equal regexp "")
12455 (error "Regexp cannot be empty"))
12456 (unless keep-previous
12457 (org-remove-occur-highlights nil nil t))
12458 (push (cons regexp callback) org-occur-parameters)
12459 (let ((cnt 0))
12460 (save-excursion
12461 (goto-char (point-min))
12462 (if (or (not keep-previous) ; do not want to keep
12463 (not org-occur-highlights)) ; no previous matches
12464 ;; hide everything
12465 (org-overview))
12466 (while (re-search-forward regexp nil t)
12467 (when (or (not callback)
12468 (save-match-data (funcall callback)))
12469 (setq cnt (1+ cnt))
12470 (when org-highlight-sparse-tree-matches
12471 (org-highlight-new-match (match-beginning 0) (match-end 0)))
12472 (org-show-context 'occur-tree))))
12473 (when org-remove-highlights-with-change
12474 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
12475 nil 'local))
12476 (unless org-sparse-tree-open-archived-trees
12477 (org-hide-archived-subtrees (point-min) (point-max)))
12478 (run-hooks 'org-occur-hook)
12479 (if (org-called-interactively-p 'interactive)
12480 (message "%d match(es) for regexp %s" cnt regexp))
12481 cnt))
12483 (defun org-occur-next-match (&optional n reset)
12484 "Function for `next-error-function' to find sparse tree matches.
12485 N is the number of matches to move, when negative move backwards.
12486 RESET is entirely ignored - this function always goes back to the
12487 starting point when no match is found."
12488 (let* ((limit (if (< n 0) (point-min) (point-max)))
12489 (search-func (if (< n 0)
12490 'previous-single-char-property-change
12491 'next-single-char-property-change))
12492 (n (abs n))
12493 (pos (point))
12495 (catch 'exit
12496 (while (setq p1 (funcall search-func (point) 'org-type))
12497 (when (equal p1 limit)
12498 (goto-char pos)
12499 (error "No more matches"))
12500 (when (equal (get-char-property p1 'org-type) 'org-occur)
12501 (setq n (1- n))
12502 (when (= n 0)
12503 (goto-char p1)
12504 (throw 'exit (point))))
12505 (goto-char p1))
12506 (goto-char p1)
12507 (error "No more matches"))))
12509 (defun org-show-context (&optional key)
12510 "Make sure point and context are visible.
12511 How much context is shown depends upon the variables
12512 `org-show-hierarchy-above', `org-show-following-heading'. and
12513 `org-show-siblings'."
12514 (let ((heading-p (org-on-heading-p t))
12515 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
12516 (following-p (org-get-alist-option org-show-following-heading key))
12517 (entry-p (org-get-alist-option org-show-entry-below key))
12518 (siblings-p (org-get-alist-option org-show-siblings key)))
12519 (catch 'exit
12520 ;; Show heading or entry text
12521 (if (and heading-p (not entry-p))
12522 (org-flag-heading nil) ; only show the heading
12523 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
12524 (org-show-hidden-entry))) ; show entire entry
12525 (when following-p
12526 ;; Show next sibling, or heading below text
12527 (save-excursion
12528 (and (if heading-p (org-goto-sibling) (outline-next-heading))
12529 (org-flag-heading nil))))
12530 (when siblings-p (org-show-siblings))
12531 (when hierarchy-p
12532 ;; show all higher headings, possibly with siblings
12533 (save-excursion
12534 (while (and (condition-case nil
12535 (progn (org-up-heading-all 1) t)
12536 (error nil))
12537 (not (bobp)))
12538 (org-flag-heading nil)
12539 (when siblings-p (org-show-siblings))))))))
12541 (defvar org-reveal-start-hook nil
12542 "Hook run before revealing a location.")
12544 (defun org-reveal (&optional siblings)
12545 "Show current entry, hierarchy above it, and the following headline.
12546 This can be used to show a consistent set of context around locations
12547 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
12548 not t for the search context.
12550 With optional argument SIBLINGS, on each level of the hierarchy all
12551 siblings are shown. This repairs the tree structure to what it would
12552 look like when opened with hierarchical calls to `org-cycle'.
12553 With double optional argument \\[universal-argument] \\[universal-argument], \
12554 go to the parent and show the
12555 entire tree."
12556 (interactive "P")
12557 (run-hooks 'org-reveal-start-hook)
12558 (let ((org-show-hierarchy-above t)
12559 (org-show-following-heading t)
12560 (org-show-siblings (if siblings t org-show-siblings)))
12561 (org-show-context nil))
12562 (when (equal siblings '(16))
12563 (save-excursion
12564 (when (org-up-heading-safe)
12565 (org-show-subtree)
12566 (run-hook-with-args 'org-cycle-hook 'subtree)))))
12568 (defun org-highlight-new-match (beg end)
12569 "Highlight from BEG to END and mark the highlight is an occur headline."
12570 (let ((ov (make-overlay beg end)))
12571 (overlay-put ov 'face 'secondary-selection)
12572 (overlay-put ov 'org-type 'org-occur)
12573 (push ov org-occur-highlights)))
12575 (defun org-remove-occur-highlights (&optional beg end noremove)
12576 "Remove the occur highlights from the buffer.
12577 BEG and END are ignored. If NOREMOVE is nil, remove this function
12578 from the `before-change-functions' in the current buffer."
12579 (interactive)
12580 (unless org-inhibit-highlight-removal
12581 (mapc 'delete-overlay org-occur-highlights)
12582 (setq org-occur-highlights nil)
12583 (setq org-occur-parameters nil)
12584 (unless noremove
12585 (remove-hook 'before-change-functions
12586 'org-remove-occur-highlights 'local))))
12588 ;;;; Priorities
12590 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
12591 "Regular expression matching the priority indicator.")
12593 (defvar org-remove-priority-next-time nil)
12595 (defun org-priority-up ()
12596 "Increase the priority of the current item."
12597 (interactive)
12598 (org-priority 'up))
12600 (defun org-priority-down ()
12601 "Decrease the priority of the current item."
12602 (interactive)
12603 (org-priority 'down))
12605 (defun org-priority (&optional action)
12606 "Change the priority of an item by ARG.
12607 ACTION can be `set', `up', `down', or a character."
12608 (interactive)
12609 (unless org-enable-priority-commands
12610 (error "Priority commands are disabled"))
12611 (setq action (or action 'set))
12612 (let (current new news have remove)
12613 (save-excursion
12614 (org-back-to-heading t)
12615 (if (looking-at org-priority-regexp)
12616 (setq current (string-to-char (match-string 2))
12617 have t))
12618 (cond
12619 ((eq action 'remove)
12620 (setq remove t new ?\ ))
12621 ((or (eq action 'set)
12622 (if (featurep 'xemacs) (characterp action) (integerp action)))
12623 (if (not (eq action 'set))
12624 (setq new action)
12625 (message "Priority %c-%c, SPC to remove: "
12626 org-highest-priority org-lowest-priority)
12627 (save-match-data
12628 (setq new (read-char-exclusive))))
12629 (if (and (= (upcase org-highest-priority) org-highest-priority)
12630 (= (upcase org-lowest-priority) org-lowest-priority))
12631 (setq new (upcase new)))
12632 (cond ((equal new ?\ ) (setq remove t))
12633 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
12634 (error "Priority must be between `%c' and `%c'"
12635 org-highest-priority org-lowest-priority))))
12636 ((eq action 'up)
12637 (setq new (if have
12638 (1- current) ; normal cycling
12639 ;; last priority was empty
12640 (if (eq last-command this-command)
12641 org-lowest-priority ; wrap around empty to lowest
12642 ;; default
12643 (if org-priority-start-cycle-with-default
12644 org-default-priority
12645 (1- org-default-priority))))))
12646 ((eq action 'down)
12647 (setq new (if have
12648 (1+ current) ; normal cycling
12649 ;; last priority was empty
12650 (if (eq last-command this-command)
12651 org-highest-priority ; wrap around empty to highest
12652 ;; default
12653 (if org-priority-start-cycle-with-default
12654 org-default-priority
12655 (1+ org-default-priority))))))
12656 (t (error "Invalid action")))
12657 (if (or (< (upcase new) org-highest-priority)
12658 (> (upcase new) org-lowest-priority))
12659 (if (and (memq action '(up down))
12660 (not have) (not (eq last-command this-command)))
12661 ;; `new' is from default priority
12662 (error
12663 "The default can not be set, see `org-default-priority' why")
12664 ;; normal cycling: `new' is beyond highest/lowest priority
12665 ;; and is wrapped around to the empty priority
12666 (setq remove t)))
12667 (setq news (format "%c" new))
12668 (if have
12669 (if remove
12670 (replace-match "" t t nil 1)
12671 (replace-match news t t nil 2))
12672 (if remove
12673 (error "No priority cookie found in line")
12674 (let ((case-fold-search nil))
12675 (looking-at org-todo-line-regexp))
12676 (if (match-end 2)
12677 (progn
12678 (goto-char (match-end 2))
12679 (insert " [#" news "]"))
12680 (goto-char (match-beginning 3))
12681 (insert "[#" news "] "))))
12682 (org-preserve-lc (org-set-tags nil 'align)))
12683 (if remove
12684 (message "Priority removed")
12685 (message "Priority of current item set to %s" news))))
12687 (defun org-get-priority (s)
12688 "Find priority cookie and return priority."
12689 (if (functionp org-get-priority-function)
12690 (funcall org-get-priority-function)
12691 (save-match-data
12692 (if (not (string-match org-priority-regexp s))
12693 (* 1000 (- org-lowest-priority org-default-priority))
12694 (* 1000 (- org-lowest-priority
12695 (string-to-char (match-string 2 s))))))))
12697 ;;;; Tags
12699 (defvar org-agenda-archives-mode)
12700 (defvar org-map-continue-from nil
12701 "Position from where mapping should continue.
12702 Can be set by the action argument to `org-scan-tag's and `org-map-entries'.")
12704 (defvar org-scanner-tags nil
12705 "The current tag list while the tags scanner is running.")
12706 (defvar org-trust-scanner-tags nil
12707 "Should `org-get-tags-at' use the tags for the scanner.
12708 This is for internal dynamical scoping only.
12709 When this is non-nil, the function `org-get-tags-at' will return the value
12710 of `org-scanner-tags' instead of building the list by itself. This
12711 can lead to large speed-ups when the tags scanner is used in a file with
12712 many entries, and when the list of tags is retrieved, for example to
12713 obtain a list of properties. Building the tags list for each entry in such
12714 a file becomes an N^2 operation - but with this variable set, it scales
12715 as N.")
12717 (defun org-scan-tags (action matcher &optional todo-only)
12718 "Scan headline tags with inheritance and produce output ACTION.
12720 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
12721 or `agenda' to produce an entry list for an agenda view. It can also be
12722 a Lisp form or a function that should be called at each matched headline, in
12723 this case the return value is a list of all return values from these calls.
12725 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
12726 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
12727 only lines with a TODO keyword are included in the output."
12728 (require 'org-agenda)
12729 (let* ((re (concat "^" org-outline-regexp " *\\(\\<\\("
12730 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
12731 (org-re
12732 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
12733 (props (list 'face 'default
12734 'done-face 'org-agenda-done
12735 'undone-face 'default
12736 'mouse-face 'highlight
12737 'org-not-done-regexp org-not-done-regexp
12738 'org-todo-regexp org-todo-regexp
12739 'org-complex-heading-regexp org-complex-heading-regexp
12740 'help-echo
12741 (format "mouse-2 or RET jump to org file %s"
12742 (abbreviate-file-name
12743 (or (buffer-file-name (buffer-base-buffer))
12744 (buffer-name (buffer-base-buffer)))))))
12745 (case-fold-search nil)
12746 (org-map-continue-from nil)
12747 lspos tags tags-list
12748 (tags-alist (list (cons 0 org-file-tags)))
12749 (llast 0) rtn rtn1 level category i txt
12750 todo marker entry priority)
12751 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
12752 (setq action (list 'lambda nil action)))
12753 (save-excursion
12754 (goto-char (point-min))
12755 (when (eq action 'sparse-tree)
12756 (org-overview)
12757 (org-remove-occur-highlights))
12758 (while (re-search-forward re nil t)
12759 (catch :skip
12760 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
12761 tags (if (match-end 4) (org-match-string-no-properties 4)))
12762 (goto-char (setq lspos (match-beginning 0)))
12763 (setq level (org-reduced-level (funcall outline-level))
12764 category (org-get-category))
12765 (setq i llast llast level)
12766 ;; remove tag lists from same and sublevels
12767 (while (>= i level)
12768 (when (setq entry (assoc i tags-alist))
12769 (setq tags-alist (delete entry tags-alist)))
12770 (setq i (1- i)))
12771 ;; add the next tags
12772 (when tags
12773 (setq tags (org-split-string tags ":")
12774 tags-alist
12775 (cons (cons level tags) tags-alist)))
12776 ;; compile tags for current headline
12777 (setq tags-list
12778 (if org-use-tag-inheritance
12779 (apply 'append (mapcar 'cdr (reverse tags-alist)))
12780 tags)
12781 org-scanner-tags tags-list)
12782 (when org-use-tag-inheritance
12783 (setcdr (car tags-alist)
12784 (mapcar (lambda (x)
12785 (setq x (copy-sequence x))
12786 (org-add-prop-inherited x))
12787 (cdar tags-alist))))
12788 (when (and tags org-use-tag-inheritance
12789 (or (not (eq t org-use-tag-inheritance))
12790 org-tags-exclude-from-inheritance))
12791 ;; selective inheritance, remove uninherited ones
12792 (setcdr (car tags-alist)
12793 (org-remove-uninherited-tags (cdar tags-alist))))
12794 (when (and
12796 ;; eval matcher only when the todo condition is OK
12797 (and (or (not todo-only) (member todo org-not-done-keywords))
12798 (let ((case-fold-search t)) (eval matcher)))
12800 ;; Call the skipper, but return t if it does not skip,
12801 ;; so that the `and' form continues evaluating
12802 (progn
12803 (unless (eq action 'sparse-tree) (org-agenda-skip))
12806 ;; Check if timestamps are deselecting this entry
12807 (or (not todo-only)
12808 (and (member todo org-not-done-keywords)
12809 (or (not org-agenda-tags-todo-honor-ignore-options)
12810 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
12812 ;; Extra check for the archive tag
12813 ;; FIXME: Does the skipper already do this????
12815 (not (member org-archive-tag tags-list))
12816 ;; we have an archive tag, should we use this anyway?
12817 (or (not org-agenda-skip-archived-trees)
12818 (and (eq action 'agenda) org-agenda-archives-mode))))
12820 ;; select this headline
12822 (cond
12823 ((eq action 'sparse-tree)
12824 (and org-highlight-sparse-tree-matches
12825 (org-get-heading) (match-end 0)
12826 (org-highlight-new-match
12827 (match-beginning 0) (match-beginning 1)))
12828 (org-show-context 'tags-tree))
12829 ((eq action 'agenda)
12830 (setq txt (org-agenda-format-item
12832 (concat
12833 (if (eq org-tags-match-list-sublevels 'indented)
12834 (make-string (1- level) ?.) "")
12835 (org-get-heading))
12836 category
12837 tags-list
12839 priority (org-get-priority txt))
12840 (goto-char lspos)
12841 (setq marker (org-agenda-new-marker))
12842 (org-add-props txt props
12843 'org-marker marker 'org-hd-marker marker 'org-category category
12844 'todo-state todo
12845 'priority priority 'type "tagsmatch")
12846 (push txt rtn))
12847 ((functionp action)
12848 (setq org-map-continue-from nil)
12849 (save-excursion
12850 (setq rtn1 (funcall action))
12851 (push rtn1 rtn)))
12852 (t (error "Invalid action")))
12854 ;; if we are to skip sublevels, jump to end of subtree
12855 (unless org-tags-match-list-sublevels
12856 (org-end-of-subtree t)
12857 (backward-char 1))))
12858 ;; Get the correct position from where to continue
12859 (if org-map-continue-from
12860 (goto-char org-map-continue-from)
12861 (and (= (point) lspos) (end-of-line 1)))))
12862 (when (and (eq action 'sparse-tree)
12863 (not org-sparse-tree-open-archived-trees))
12864 (org-hide-archived-subtrees (point-min) (point-max)))
12865 (nreverse rtn)))
12867 (defun org-remove-uninherited-tags (tags)
12868 "Remove all tags that are not inherited from the list TAGS."
12869 (cond
12870 ((eq org-use-tag-inheritance t)
12871 (if org-tags-exclude-from-inheritance
12872 (org-delete-all org-tags-exclude-from-inheritance tags)
12873 tags))
12874 ((not org-use-tag-inheritance) nil)
12875 ((stringp org-use-tag-inheritance)
12876 (delq nil (mapcar
12877 (lambda (x)
12878 (if (and (string-match org-use-tag-inheritance x)
12879 (not (member x org-tags-exclude-from-inheritance)))
12880 x nil))
12881 tags)))
12882 ((listp org-use-tag-inheritance)
12883 (delq nil (mapcar
12884 (lambda (x)
12885 (if (member x org-use-tag-inheritance) x nil))
12886 tags)))))
12888 (defvar todo-only) ;; dynamically scoped
12890 (defun org-match-sparse-tree (&optional todo-only match)
12891 "Create a sparse tree according to tags string MATCH.
12892 MATCH can contain positive and negative selection of tags, like
12893 \"+WORK+URGENT-WITHBOSS\".
12894 If optional argument TODO-ONLY is non-nil, only select lines that are
12895 also TODO lines."
12896 (interactive "P")
12897 (org-prepare-agenda-buffers (list (current-buffer)))
12898 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
12900 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
12902 (defvar org-cached-props nil)
12903 (defun org-cached-entry-get (pom property)
12904 (if (or (eq t org-use-property-inheritance)
12905 (and (stringp org-use-property-inheritance)
12906 (string-match org-use-property-inheritance property))
12907 (and (listp org-use-property-inheritance)
12908 (member property org-use-property-inheritance)))
12909 ;; Caching is not possible, check it directly
12910 (org-entry-get pom property 'inherit)
12911 ;; Get all properties, so that we can do complicated checks easily
12912 (cdr (assoc property (or org-cached-props
12913 (setq org-cached-props
12914 (org-entry-properties pom)))))))
12916 (defun org-global-tags-completion-table (&optional files)
12917 "Return the list of all tags in all agenda buffer/files.
12918 Optional FILES argument is a list of files to which can be used
12919 instead of the agenda files."
12920 (save-excursion
12921 (org-uniquify
12922 (delq nil
12923 (apply 'append
12924 (mapcar
12925 (lambda (file)
12926 (set-buffer (find-file-noselect file))
12927 (append (org-get-buffer-tags)
12928 (mapcar (lambda (x) (if (stringp (car-safe x))
12929 (list (car-safe x)) nil))
12930 org-tag-alist)))
12931 (if (and files (car files))
12932 files
12933 (org-agenda-files))))))))
12935 (defun org-make-tags-matcher (match)
12936 "Create the TAGS/TODO matcher form for the selection string MATCH."
12937 ;; todo-only is scoped dynamically into this function, and the function
12938 ;; may change it if the matcher asks for it.
12939 (unless match
12940 ;; Get a new match request, with completion
12941 (let ((org-last-tags-completion-table
12942 (org-global-tags-completion-table)))
12943 (setq match (org-completing-read-no-i
12944 "Match: " 'org-tags-completion-function nil nil nil
12945 'org-tags-history))))
12947 ;; Parse the string and create a lisp form
12948 (let ((match0 match)
12949 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
12950 minus tag mm
12951 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
12952 orterms term orlist re-p str-p level-p level-op time-p
12953 prop-p pn pv po gv rest)
12954 (if (string-match "/+" match)
12955 ;; match contains also a todo-matching request
12956 (progn
12957 (setq tagsmatch (substring match 0 (match-beginning 0))
12958 todomatch (substring match (match-end 0)))
12959 (if (string-match "^!" todomatch)
12960 (setq todo-only t todomatch (substring todomatch 1)))
12961 (if (string-match "^\\s-*$" todomatch)
12962 (setq todomatch nil)))
12963 ;; only matching tags
12964 (setq tagsmatch match todomatch nil))
12966 ;; Make the tags matcher
12967 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
12968 (setq tagsmatcher t)
12969 (setq orterms (org-split-string tagsmatch "|") orlist nil)
12970 (while (setq term (pop orterms))
12971 (while (and (equal (substring term -1) "\\") orterms)
12972 (setq term (concat term "|" (pop orterms)))) ; repair bad split
12973 (while (string-match re term)
12974 (setq rest (substring term (match-end 0))
12975 minus (and (match-end 1)
12976 (equal (match-string 1 term) "-"))
12977 tag (save-match-data (replace-regexp-in-string
12978 "\\\\-" "-"
12979 (match-string 2 term)))
12980 re-p (equal (string-to-char tag) ?{)
12981 level-p (match-end 4)
12982 prop-p (match-end 5)
12983 mm (cond
12984 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
12985 (level-p
12986 (setq level-op (org-op-to-function (match-string 3 term)))
12987 `(,level-op level ,(string-to-number
12988 (match-string 4 term))))
12989 (prop-p
12990 (setq pn (match-string 5 term)
12991 po (match-string 6 term)
12992 pv (match-string 7 term)
12993 re-p (equal (string-to-char pv) ?{)
12994 str-p (equal (string-to-char pv) ?\")
12995 time-p (save-match-data
12996 (string-match "^\"[[<].*[]>]\"$" pv))
12997 pv (if (or re-p str-p) (substring pv 1 -1) pv))
12998 (if time-p (setq pv (org-matcher-time pv)))
12999 (setq po (org-op-to-function po (if time-p 'time str-p)))
13000 (cond
13001 ((equal pn "CATEGORY")
13002 (setq gv '(get-text-property (point) 'org-category)))
13003 ((equal pn "TODO")
13004 (setq gv 'todo))
13006 (setq gv `(org-cached-entry-get nil ,pn))))
13007 (if re-p
13008 (if (eq po 'org<>)
13009 `(not (string-match ,pv (or ,gv "")))
13010 `(string-match ,pv (or ,gv "")))
13011 (if str-p
13012 `(,po (or ,gv "") ,pv)
13013 `(,po (string-to-number (or ,gv ""))
13014 ,(string-to-number pv) ))))
13015 (t `(member ,tag tags-list)))
13016 mm (if minus (list 'not mm) mm)
13017 term rest)
13018 (push mm tagsmatcher))
13019 (push (if (> (length tagsmatcher) 1)
13020 (cons 'and tagsmatcher)
13021 (car tagsmatcher))
13022 orlist)
13023 (setq tagsmatcher nil))
13024 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
13025 (setq tagsmatcher
13026 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
13027 ;; Make the todo matcher
13028 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
13029 (setq todomatcher t)
13030 (setq orterms (org-split-string todomatch "|") orlist nil)
13031 (while (setq term (pop orterms))
13032 (while (string-match re term)
13033 (setq minus (and (match-end 1)
13034 (equal (match-string 1 term) "-"))
13035 kwd (match-string 2 term)
13036 re-p (equal (string-to-char kwd) ?{)
13037 term (substring term (match-end 0))
13038 mm (if re-p
13039 `(string-match ,(substring kwd 1 -1) todo)
13040 (list 'equal 'todo kwd))
13041 mm (if minus (list 'not mm) mm))
13042 (push mm todomatcher))
13043 (push (if (> (length todomatcher) 1)
13044 (cons 'and todomatcher)
13045 (car todomatcher))
13046 orlist)
13047 (setq todomatcher nil))
13048 (setq todomatcher (if (> (length orlist) 1)
13049 (cons 'or orlist) (car orlist))))
13051 ;; Return the string and lisp forms of the matcher
13052 (setq matcher (if todomatcher
13053 (list 'and tagsmatcher todomatcher)
13054 tagsmatcher))
13055 (cons match0 matcher)))
13057 (defun org-op-to-function (op &optional stringp)
13058 "Turn an operator into the appropriate function."
13059 (setq op
13060 (cond
13061 ((equal op "<" ) '(< string< org-time<))
13062 ((equal op ">" ) '(> org-string> org-time>))
13063 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
13064 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
13065 ((member op '("=" "==")) '(= string= org-time=))
13066 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
13067 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
13069 (defun org<> (a b) (not (= a b)))
13070 (defun org-string<= (a b) (or (string= a b) (string< a b)))
13071 (defun org-string>= (a b) (not (string< a b)))
13072 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
13073 (defun org-string<> (a b) (not (string= a b)))
13074 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
13075 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
13076 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
13077 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
13078 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
13079 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
13080 (defun org-2ft (s)
13081 "Convert S to a floating point time.
13082 If S is already a number, just return it. If it is a string, parse
13083 it as a time string and apply `float-time' to it. If S is nil, just return 0."
13084 (cond
13085 ((numberp s) s)
13086 ((stringp s)
13087 (condition-case nil
13088 (float-time (apply 'encode-time (org-parse-time-string s)))
13089 (error 0.)))
13090 (t 0.)))
13092 (defun org-time-today ()
13093 "Time in seconds today at 0:00.
13094 Returns the float number of seconds since the beginning of the
13095 epoch to the beginning of today (00:00)."
13096 (float-time (apply 'encode-time
13097 (append '(0 0 0) (nthcdr 3 (decode-time))))))
13099 (defun org-matcher-time (s)
13100 "Interpret a time comparison value."
13101 (save-match-data
13102 (cond
13103 ((string= s "<now>") (float-time))
13104 ((string= s "<today>") (org-time-today))
13105 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
13106 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
13107 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
13108 (+ (org-time-today)
13109 (* (string-to-number (match-string 1 s))
13110 (cdr (assoc (match-string 2 s)
13111 '(("d" . 86400.0) ("w" . 604800.0)
13112 ("m" . 2678400.0) ("y" . 31557600.0)))))))
13113 (t (org-2ft s)))))
13115 (defun org-match-any-p (re list)
13116 "Does re match any element of list?"
13117 (setq list (mapcar (lambda (x) (string-match re x)) list))
13118 (delq nil list))
13120 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
13121 (defvar org-tags-overlay (make-overlay 1 1))
13122 (org-detach-overlay org-tags-overlay)
13124 (defun org-get-local-tags-at (&optional pos)
13125 "Get a list of tags defined in the current headline."
13126 (org-get-tags-at pos 'local))
13128 (defun org-get-local-tags ()
13129 "Get a list of tags defined in the current headline."
13130 (org-get-tags-at nil 'local))
13132 (defun org-get-tags-at (&optional pos local)
13133 "Get a list of all headline tags applicable at POS.
13134 POS defaults to point. If tags are inherited, the list contains
13135 the targets in the same sequence as the headlines appear, i.e.
13136 the tags of the current headline come last.
13137 When LOCAL is non-nil, only return tags from the current headline,
13138 ignore inherited ones."
13139 (interactive)
13140 (if (and org-trust-scanner-tags
13141 (or (not pos) (equal pos (point)))
13142 (not local))
13143 org-scanner-tags
13144 (let (tags ltags lastpos parent)
13145 (save-excursion
13146 (save-restriction
13147 (widen)
13148 (goto-char (or pos (point)))
13149 (save-match-data
13150 (catch 'done
13151 (condition-case nil
13152 (progn
13153 (org-back-to-heading t)
13154 (while (not (equal lastpos (point)))
13155 (setq lastpos (point))
13156 (when (looking-at
13157 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
13158 (setq ltags (org-split-string
13159 (org-match-string-no-properties 1) ":"))
13160 (when parent
13161 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
13162 (setq tags (append
13163 (if parent
13164 (org-remove-uninherited-tags ltags)
13165 ltags)
13166 tags)))
13167 (or org-use-tag-inheritance (throw 'done t))
13168 (if local (throw 'done t))
13169 (or (org-up-heading-safe) (error nil))
13170 (setq parent t)))
13171 (error nil)))))
13172 (if local
13173 tags
13174 (append (org-remove-uninherited-tags org-file-tags) tags))))))
13176 (defun org-add-prop-inherited (s)
13177 (add-text-properties 0 (length s) '(inherited t) s)
13180 (defun org-toggle-tag (tag &optional onoff)
13181 "Toggle the tag TAG for the current line.
13182 If ONOFF is `on' or `off', don't toggle but set to this state."
13183 (let (res current)
13184 (save-excursion
13185 (org-back-to-heading t)
13186 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
13187 (point-at-eol) t)
13188 (progn
13189 (setq current (match-string 1))
13190 (replace-match ""))
13191 (setq current ""))
13192 (setq current (nreverse (org-split-string current ":")))
13193 (cond
13194 ((eq onoff 'on)
13195 (setq res t)
13196 (or (member tag current) (push tag current)))
13197 ((eq onoff 'off)
13198 (or (not (member tag current)) (setq current (delete tag current))))
13199 (t (if (member tag current)
13200 (setq current (delete tag current))
13201 (setq res t)
13202 (push tag current))))
13203 (end-of-line 1)
13204 (if current
13205 (progn
13206 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
13207 (org-set-tags nil t))
13208 (delete-horizontal-space))
13209 (run-hooks 'org-after-tags-change-hook))
13210 res))
13212 (defun org-align-tags-here (to-col)
13213 ;; Assumes that this is a headline
13214 (let ((pos (point)) (col (current-column)) ncol tags-l p)
13215 (beginning-of-line 1)
13216 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13217 (< pos (match-beginning 2)))
13218 (progn
13219 (setq tags-l (- (match-end 2) (match-beginning 2)))
13220 (goto-char (match-beginning 1))
13221 (insert " ")
13222 (delete-region (point) (1+ (match-beginning 2)))
13223 (setq ncol (max (current-column)
13224 (1+ col)
13225 (if (> to-col 0)
13226 to-col
13227 (- (abs to-col) tags-l))))
13228 (setq p (point))
13229 (insert (make-string (- ncol (current-column)) ?\ ))
13230 (setq ncol (current-column))
13231 (when indent-tabs-mode (tabify p (point-at-eol)))
13232 (org-move-to-column (min ncol col) t))
13233 (goto-char pos))))
13235 (defun org-set-tags-command (&optional arg just-align)
13236 "Call the set-tags command for the current entry."
13237 (interactive "P")
13238 (if (org-on-heading-p)
13239 (org-set-tags arg just-align)
13240 (save-excursion
13241 (org-back-to-heading t)
13242 (org-set-tags arg just-align))))
13244 (defun org-set-tags-to (data)
13245 "Set the tags of the current entry to DATA, replacing the current tags.
13246 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
13247 If DATA is nil or the empty string, any tags will be removed."
13248 (interactive "sTags: ")
13249 (setq data
13250 (cond
13251 ((eq data nil) "")
13252 ((equal data "") "")
13253 ((stringp data)
13254 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
13255 ":"))
13256 ((listp data)
13257 (concat ":" (mapconcat 'identity data ":") ":"))
13258 (t nil)))
13259 (when data
13260 (save-excursion
13261 (org-back-to-heading t)
13262 (when (looking-at org-complex-heading-regexp)
13263 (if (match-end 5)
13264 (progn
13265 (goto-char (match-beginning 5))
13266 (insert data)
13267 (delete-region (point) (point-at-eol))
13268 (org-set-tags nil 'align))
13269 (goto-char (point-at-eol))
13270 (insert " " data)
13271 (org-set-tags nil 'align)))
13272 (beginning-of-line 1)
13273 (if (looking-at ".*?\\([ \t]+\\)$")
13274 (delete-region (match-beginning 1) (match-end 1))))))
13276 (defun org-align-all-tags ()
13277 "Align the tags i all headings."
13278 (interactive)
13279 (save-excursion
13280 (or (ignore-errors (org-back-to-heading t))
13281 (outline-next-heading))
13282 (if (org-on-heading-p)
13283 (org-set-tags t)
13284 (message "No headings"))))
13286 (defvar org-indent-indentation-per-level)
13287 (defun org-set-tags (&optional arg just-align)
13288 "Set the tags for the current headline.
13289 With prefix ARG, realign all tags in headings in the current buffer."
13290 (interactive "P")
13291 (let* ((re org-outline-regexp-bol)
13292 (current (org-get-tags-string))
13293 (col (current-column))
13294 (org-setting-tags t)
13295 table current-tags inherited-tags ; computed below when needed
13296 tags p0 c0 c1 rpl di tc level)
13297 (if arg
13298 (save-excursion
13299 (goto-char (point-min))
13300 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
13301 (while (re-search-forward re nil t)
13302 (org-set-tags nil t)
13303 (end-of-line 1)))
13304 (message "All tags realigned to column %d" org-tags-column))
13305 (if just-align
13306 (setq tags current)
13307 ;; Get a new set of tags from the user
13308 (save-excursion
13309 (setq table (append org-tag-persistent-alist
13310 (or org-tag-alist (org-get-buffer-tags))
13311 (and
13312 org-complete-tags-always-offer-all-agenda-tags
13313 (org-global-tags-completion-table
13314 (org-agenda-files))))
13315 org-last-tags-completion-table table
13316 current-tags (org-split-string current ":")
13317 inherited-tags (nreverse
13318 (nthcdr (length current-tags)
13319 (nreverse (org-get-tags-at))))
13320 tags
13321 (if (or (eq t org-use-fast-tag-selection)
13322 (and org-use-fast-tag-selection
13323 (delq nil (mapcar 'cdr table))))
13324 (org-fast-tag-selection
13325 current-tags inherited-tags table
13326 (if org-fast-tag-selection-include-todo
13327 org-todo-key-alist))
13328 (let ((org-add-colon-after-tag-completion t))
13329 (org-trim
13330 (org-icompleting-read "Tags: "
13331 'org-tags-completion-function
13332 nil nil current 'org-tags-history))))))
13333 (while (string-match "[-+&]+" tags)
13334 ;; No boolean logic, just a list
13335 (setq tags (replace-match ":" t t tags))))
13337 (setq tags (replace-regexp-in-string "[,]" ":" tags))
13339 (if org-tags-sort-function
13340 (setq tags (mapconcat 'identity
13341 (sort (org-split-string
13342 tags (org-re "[^[:alnum:]_@#%]+"))
13343 org-tags-sort-function) ":")))
13345 (if (string-match "\\`[\t ]*\\'" tags)
13346 (setq tags "")
13347 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
13348 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
13350 ;; Insert new tags at the correct column
13351 (beginning-of-line 1)
13352 (setq level (or (and (looking-at org-outline-regexp)
13353 (- (match-end 0) (point) 1))
13355 (cond
13356 ((and (equal current "") (equal tags "")))
13357 ((re-search-forward
13358 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
13359 (point-at-eol) t)
13360 (if (equal tags "")
13361 (setq rpl "")
13362 (goto-char (match-beginning 0))
13363 (setq c0 (current-column)
13364 ;; compute offset for the case of org-indent-mode active
13365 di (if org-indent-mode
13366 (* (1- org-indent-indentation-per-level) (1- level))
13368 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
13369 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
13370 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
13371 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
13372 (replace-match rpl t t)
13373 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
13374 tags)
13375 (t (error "Tags alignment failed")))
13376 (org-move-to-column col)
13377 (unless just-align
13378 (run-hooks 'org-after-tags-change-hook)))))
13380 (defun org-change-tag-in-region (beg end tag off)
13381 "Add or remove TAG for each entry in the region.
13382 This works in the agenda, and also in an org-mode buffer."
13383 (interactive
13384 (list (region-beginning) (region-end)
13385 (let ((org-last-tags-completion-table
13386 (if (eq major-mode 'org-mode)
13387 (org-get-buffer-tags)
13388 (org-global-tags-completion-table))))
13389 (org-icompleting-read
13390 "Tag: " 'org-tags-completion-function nil nil nil
13391 'org-tags-history))
13392 (progn
13393 (message "[s]et or [r]emove? ")
13394 (equal (read-char-exclusive) ?r))))
13395 (if (fboundp 'deactivate-mark) (deactivate-mark))
13396 (let ((agendap (equal major-mode 'org-agenda-mode))
13397 l1 l2 m buf pos newhead (cnt 0))
13398 (goto-char end)
13399 (setq l2 (1- (org-current-line)))
13400 (goto-char beg)
13401 (setq l1 (org-current-line))
13402 (loop for l from l1 to l2 do
13403 (org-goto-line l)
13404 (setq m (get-text-property (point) 'org-hd-marker))
13405 (when (or (and (eq major-mode 'org-mode) (org-on-heading-p))
13406 (and agendap m))
13407 (setq buf (if agendap (marker-buffer m) (current-buffer))
13408 pos (if agendap m (point)))
13409 (with-current-buffer buf
13410 (save-excursion
13411 (save-restriction
13412 (goto-char pos)
13413 (setq cnt (1+ cnt))
13414 (org-toggle-tag tag (if off 'off 'on))
13415 (setq newhead (org-get-heading)))))
13416 (and agendap (org-agenda-change-all-lines newhead m))))
13417 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
13419 (defun org-tags-completion-function (string predicate &optional flag)
13420 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
13421 (confirm (lambda (x) (stringp (car x)))))
13422 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
13423 (setq s1 (match-string 1 string)
13424 s2 (match-string 2 string))
13425 (setq s1 "" s2 string))
13426 (cond
13427 ((eq flag nil)
13428 ;; try completion
13429 (setq rtn (try-completion s2 ctable confirm))
13430 (if (stringp rtn)
13431 (setq rtn
13432 (concat s1 s2 (substring rtn (length s2))
13433 (if (and org-add-colon-after-tag-completion
13434 (assoc rtn ctable))
13435 ":" ""))))
13436 rtn)
13437 ((eq flag t)
13438 ;; all-completions
13439 (all-completions s2 ctable confirm)
13441 ((eq flag 'lambda)
13442 ;; exact match?
13443 (assoc s2 ctable)))
13446 (defun org-fast-tag-insert (kwd tags face &optional end)
13447 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
13448 (insert (format "%-12s" (concat kwd ":"))
13449 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
13450 (or end "")))
13452 (defun org-fast-tag-show-exit (flag)
13453 (save-excursion
13454 (org-goto-line 3)
13455 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
13456 (replace-match ""))
13457 (when flag
13458 (end-of-line 1)
13459 (org-move-to-column (- (window-width) 19) t)
13460 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
13462 (defun org-set-current-tags-overlay (current prefix)
13463 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
13464 (if (featurep 'xemacs)
13465 (org-overlay-display org-tags-overlay (concat prefix s)
13466 'secondary-selection)
13467 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
13468 (org-overlay-display org-tags-overlay (concat prefix s)))))
13470 (defvar org-last-tag-selection-key nil)
13471 (defun org-fast-tag-selection (current inherited table &optional todo-table)
13472 "Fast tag selection with single keys.
13473 CURRENT is the current list of tags in the headline, INHERITED is the
13474 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
13475 possibly with grouping information. TODO-TABLE is a similar table with
13476 TODO keywords, should these have keys assigned to them.
13477 If the keys are nil, a-z are automatically assigned.
13478 Returns the new tags string, or nil to not change the current settings."
13479 (let* ((fulltable (append table todo-table))
13480 (maxlen (apply 'max (mapcar
13481 (lambda (x)
13482 (if (stringp (car x)) (string-width (car x)) 0))
13483 fulltable)))
13484 (buf (current-buffer))
13485 (expert (eq org-fast-tag-selection-single-key 'expert))
13486 (buffer-tags nil)
13487 (fwidth (+ maxlen 3 1 3))
13488 (ncol (/ (- (window-width) 4) fwidth))
13489 (i-face 'org-done)
13490 (c-face 'org-todo)
13491 tg cnt e c char c1 c2 ntable tbl rtn
13492 ov-start ov-end ov-prefix
13493 (exit-after-next org-fast-tag-selection-single-key)
13494 (done-keywords org-done-keywords)
13495 groups ingroup)
13496 (save-excursion
13497 (beginning-of-line 1)
13498 (if (looking-at
13499 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13500 (setq ov-start (match-beginning 1)
13501 ov-end (match-end 1)
13502 ov-prefix "")
13503 (setq ov-start (1- (point-at-eol))
13504 ov-end (1+ ov-start))
13505 (skip-chars-forward "^\n\r")
13506 (setq ov-prefix
13507 (concat
13508 (buffer-substring (1- (point)) (point))
13509 (if (> (current-column) org-tags-column)
13511 (make-string (- org-tags-column (current-column)) ?\ ))))))
13512 (move-overlay org-tags-overlay ov-start ov-end)
13513 (save-window-excursion
13514 (if expert
13515 (set-buffer (get-buffer-create " *Org tags*"))
13516 (delete-other-windows)
13517 (split-window-vertically)
13518 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
13519 (erase-buffer)
13520 (org-set-local 'org-done-keywords done-keywords)
13521 (org-fast-tag-insert "Inherited" inherited i-face "\n")
13522 (org-fast-tag-insert "Current" current c-face "\n\n")
13523 (org-fast-tag-show-exit exit-after-next)
13524 (org-set-current-tags-overlay current ov-prefix)
13525 (setq tbl fulltable char ?a cnt 0)
13526 (while (setq e (pop tbl))
13527 (cond
13528 ((equal (car e) :startgroup)
13529 (push '() groups) (setq ingroup t)
13530 (when (not (= cnt 0))
13531 (setq cnt 0)
13532 (insert "\n"))
13533 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
13534 ((equal (car e) :endgroup)
13535 (setq ingroup nil cnt 0)
13536 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
13537 ((equal e '(:newline))
13538 (when (not (= cnt 0))
13539 (setq cnt 0)
13540 (insert "\n")
13541 (setq e (car tbl))
13542 (while (equal (car tbl) '(:newline))
13543 (insert "\n")
13544 (setq tbl (cdr tbl)))))
13546 (setq tg (copy-sequence (car e)) c2 nil)
13547 (if (cdr e)
13548 (setq c (cdr e))
13549 ;; automatically assign a character.
13550 (setq c1 (string-to-char
13551 (downcase (substring
13552 tg (if (= (string-to-char tg) ?@) 1 0)))))
13553 (if (or (rassoc c1 ntable) (rassoc c1 table))
13554 (while (or (rassoc char ntable) (rassoc char table))
13555 (setq char (1+ char)))
13556 (setq c2 c1))
13557 (setq c (or c2 char)))
13558 (if ingroup (push tg (car groups)))
13559 (setq tg (org-add-props tg nil 'face
13560 (cond
13561 ((not (assoc tg table))
13562 (org-get-todo-face tg))
13563 ((member tg current) c-face)
13564 ((member tg inherited) i-face)
13565 (t nil))))
13566 (if (and (= cnt 0) (not ingroup)) (insert " "))
13567 (insert "[" c "] " tg (make-string
13568 (- fwidth 4 (length tg)) ?\ ))
13569 (push (cons tg c) ntable)
13570 (when (= (setq cnt (1+ cnt)) ncol)
13571 (insert "\n")
13572 (if ingroup (insert " "))
13573 (setq cnt 0)))))
13574 (setq ntable (nreverse ntable))
13575 (insert "\n")
13576 (goto-char (point-min))
13577 (if (not expert) (org-fit-window-to-buffer))
13578 (setq rtn
13579 (catch 'exit
13580 (while t
13581 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
13582 (if (not groups) "no " "")
13583 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
13584 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13585 (setq org-last-tag-selection-key c)
13586 (cond
13587 ((= c ?\r) (throw 'exit t))
13588 ((= c ?!)
13589 (setq groups (not groups))
13590 (goto-char (point-min))
13591 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
13592 ((= c ?\C-c)
13593 (if (not expert)
13594 (org-fast-tag-show-exit
13595 (setq exit-after-next (not exit-after-next)))
13596 (setq expert nil)
13597 (delete-other-windows)
13598 (set-window-buffer (split-window-vertically) " *Org tags*")
13599 (org-switch-to-buffer-other-window " *Org tags*")
13600 (org-fit-window-to-buffer)))
13601 ((or (= c ?\C-g)
13602 (and (= c ?q) (not (rassoc c ntable))))
13603 (org-detach-overlay org-tags-overlay)
13604 (setq quit-flag t))
13605 ((= c ?\ )
13606 (setq current nil)
13607 (if exit-after-next (setq exit-after-next 'now)))
13608 ((= c ?\t)
13609 (condition-case nil
13610 (setq tg (org-icompleting-read
13611 "Tag: "
13612 (or buffer-tags
13613 (with-current-buffer buf
13614 (org-get-buffer-tags)))))
13615 (quit (setq tg "")))
13616 (when (string-match "\\S-" tg)
13617 (add-to-list 'buffer-tags (list tg))
13618 (if (member tg current)
13619 (setq current (delete tg current))
13620 (push tg current)))
13621 (if exit-after-next (setq exit-after-next 'now)))
13622 ((setq e (rassoc c todo-table) tg (car e))
13623 (with-current-buffer buf
13624 (save-excursion (org-todo tg)))
13625 (if exit-after-next (setq exit-after-next 'now)))
13626 ((setq e (rassoc c ntable) tg (car e))
13627 (if (member tg current)
13628 (setq current (delete tg current))
13629 (loop for g in groups do
13630 (if (member tg g)
13631 (mapc (lambda (x)
13632 (setq current (delete x current)))
13633 g)))
13634 (push tg current))
13635 (if exit-after-next (setq exit-after-next 'now))))
13637 ;; Create a sorted list
13638 (setq current
13639 (sort current
13640 (lambda (a b)
13641 (assoc b (cdr (memq (assoc a ntable) ntable))))))
13642 (if (eq exit-after-next 'now) (throw 'exit t))
13643 (goto-char (point-min))
13644 (beginning-of-line 2)
13645 (delete-region (point) (point-at-eol))
13646 (org-fast-tag-insert "Current" current c-face)
13647 (org-set-current-tags-overlay current ov-prefix)
13648 (while (re-search-forward
13649 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
13650 (setq tg (match-string 1))
13651 (add-text-properties
13652 (match-beginning 1) (match-end 1)
13653 (list 'face
13654 (cond
13655 ((member tg current) c-face)
13656 ((member tg inherited) i-face)
13657 (t (get-text-property (match-beginning 1) 'face))))))
13658 (goto-char (point-min)))))
13659 (org-detach-overlay org-tags-overlay)
13660 (if rtn
13661 (mapconcat 'identity current ":")
13662 nil))))
13664 (defun org-get-tags-string ()
13665 "Get the TAGS string in the current headline."
13666 (unless (org-on-heading-p t)
13667 (error "Not on a heading"))
13668 (save-excursion
13669 (beginning-of-line 1)
13670 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13671 (org-match-string-no-properties 1)
13672 "")))
13674 (defun org-get-tags ()
13675 "Get the list of tags specified in the current headline."
13676 (org-split-string (org-get-tags-string) ":"))
13678 (defun org-get-buffer-tags ()
13679 "Get a table of all tags used in the buffer, for completion."
13680 (let (tags)
13681 (save-excursion
13682 (goto-char (point-min))
13683 (while (re-search-forward
13684 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
13685 (when (equal (char-after (point-at-bol 0)) ?*)
13686 (mapc (lambda (x) (add-to-list 'tags x))
13687 (org-split-string (org-match-string-no-properties 1) ":")))))
13688 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
13689 (mapcar 'list tags)))
13691 ;;;; The mapping API
13693 ;;;###autoload
13694 (defun org-map-entries (func &optional match scope &rest skip)
13695 "Call FUNC at each headline selected by MATCH in SCOPE.
13697 FUNC is a function or a lisp form. The function will be called without
13698 arguments, with the cursor positioned at the beginning of the headline.
13699 The return values of all calls to the function will be collected and
13700 returned as a list.
13702 The call to FUNC will be wrapped into a save-excursion form, so FUNC
13703 does not need to preserve point. After evaluation, the cursor will be
13704 moved to the end of the line (presumably of the headline of the
13705 processed entry) and search continues from there. Under some
13706 circumstances, this may not produce the wanted results. For example,
13707 if you have removed (e.g. archived) the current (sub)tree it could
13708 mean that the next entry will be skipped entirely. In such cases, you
13709 can specify the position from where search should continue by making
13710 FUNC set the variable `org-map-continue-from' to the desired buffer
13711 position.
13713 MATCH is a tags/property/todo match as it is used in the agenda tags view.
13714 Only headlines that are matched by this query will be considered during
13715 the iteration. When MATCH is nil or t, all headlines will be
13716 visited by the iteration.
13718 SCOPE determines the scope of this command. It can be any of:
13720 nil The current buffer, respecting the restriction if any
13721 tree The subtree started with the entry at point
13722 region The entries within the active region, if any
13723 file The current buffer, without restriction
13724 file-with-archives
13725 The current buffer, and any archives associated with it
13726 agenda All agenda files
13727 agenda-with-archives
13728 All agenda files with any archive files associated with them
13729 \(file1 file2 ...)
13730 If this is a list, all files in the list will be scanned
13732 The remaining args are treated as settings for the skipping facilities of
13733 the scanner. The following items can be given here:
13735 archive skip trees with the archive tag.
13736 comment skip trees with the COMMENT keyword
13737 function or Emacs Lisp form:
13738 will be used as value for `org-agenda-skip-function', so whenever
13739 the function returns t, FUNC will not be called for that
13740 entry and search will continue from the point where the
13741 function leaves it.
13743 If your function needs to retrieve the tags including inherited tags
13744 at the *current* entry, you can use the value of the variable
13745 `org-scanner-tags' which will be much faster than getting the value
13746 with `org-get-tags-at'. If your function gets properties with
13747 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
13748 to t around the call to `org-entry-properties' to get the same speedup.
13749 Note that if your function moves around to retrieve tags and properties at
13750 a *different* entry, you cannot use these techniques."
13751 (unless (and (eq scope 'region) (not (org-region-active-p)))
13752 (let* ((org-agenda-archives-mode nil) ; just to make sure
13753 (org-agenda-skip-archived-trees (memq 'archive skip))
13754 (org-agenda-skip-comment-trees (memq 'comment skip))
13755 (org-agenda-skip-function
13756 (car (org-delete-all '(comment archive) skip)))
13757 (org-tags-match-list-sublevels t)
13758 matcher file res
13759 org-todo-keywords-for-agenda
13760 org-done-keywords-for-agenda
13761 org-todo-keyword-alist-for-agenda
13762 org-drawers-for-agenda
13763 org-tag-alist-for-agenda)
13765 (cond
13766 ((eq match t) (setq matcher t))
13767 ((eq match nil) (setq matcher t))
13768 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
13770 (save-excursion
13771 (save-restriction
13772 (cond ((eq scope 'tree)
13773 (org-back-to-heading t)
13774 (org-narrow-to-subtree)
13775 (setq scope nil))
13776 ((and (eq scope 'region) (org-region-active-p))
13777 (narrow-to-region (region-beginning)
13778 (save-excursion
13779 (goto-char (region-end))
13780 (unless (and (bolp) (org-at-heading-p))
13781 (outline-next-heading))
13782 (point)))
13783 (setq scope nil)))
13785 (if (not scope)
13786 (progn
13787 (org-prepare-agenda-buffers
13788 (list (buffer-file-name (current-buffer))))
13789 (setq res (org-scan-tags func matcher)))
13790 ;; Get the right scope
13791 (cond
13792 ((and scope (listp scope) (symbolp (car scope)))
13793 (setq scope (eval scope)))
13794 ((eq scope 'agenda)
13795 (setq scope (org-agenda-files t)))
13796 ((eq scope 'agenda-with-archives)
13797 (setq scope (org-agenda-files t))
13798 (setq scope (org-add-archive-files scope)))
13799 ((eq scope 'file)
13800 (setq scope (list (buffer-file-name))))
13801 ((eq scope 'file-with-archives)
13802 (setq scope (org-add-archive-files (list (buffer-file-name))))))
13803 (org-prepare-agenda-buffers scope)
13804 (while (setq file (pop scope))
13805 (with-current-buffer (org-find-base-buffer-visiting file)
13806 (save-excursion
13807 (save-restriction
13808 (widen)
13809 (goto-char (point-min))
13810 (setq res (append res (org-scan-tags func matcher))))))))))
13811 res)))
13813 ;;;; Properties
13815 ;;; Setting and retrieving properties
13817 (defconst org-special-properties
13818 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
13819 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM")
13820 "The special properties valid in Org-mode.
13822 These are properties that are not defined in the property drawer,
13823 but in some other way.")
13825 (defconst org-default-properties
13826 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
13827 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
13828 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
13829 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
13830 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
13831 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
13832 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
13833 "Some properties that are used by Org-mode for various purposes.
13834 Being in this list makes sure that they are offered for completion.")
13836 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
13837 "Regular expression matching the first line of a property drawer.")
13839 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
13840 "Regular expression matching the last line of a property drawer.")
13842 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
13843 "Regular expression matching the first line of a property drawer.")
13845 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
13846 "Regular expression matching the first line of a property drawer.")
13848 (defconst org-property-drawer-re
13849 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
13850 org-property-end-re "\\)\n?")
13851 "Matches an entire property drawer.")
13853 (defconst org-clock-drawer-re
13854 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
13855 org-property-end-re "\\)\n?")
13856 "Matches an entire clock drawer.")
13858 (defsubst org-re-property (property)
13859 "Return a regexp matching PROPERTY.
13860 Match group 1 will be set to the value "
13861 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
13863 (defun org-property-action ()
13864 "Do an action on properties."
13865 (interactive)
13866 (let (c)
13867 (org-at-property-p)
13868 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
13869 (setq c (read-char-exclusive))
13870 (cond
13871 ((equal c ?s)
13872 (call-interactively 'org-set-property))
13873 ((equal c ?d)
13874 (call-interactively 'org-delete-property))
13875 ((equal c ?D)
13876 (call-interactively 'org-delete-property-globally))
13877 ((equal c ?c)
13878 (call-interactively 'org-compute-property-at-point))
13879 (t (error "No such property action %c" c)))))
13881 (defun org-set-effort (&optional value)
13882 "Set the effort property of the current entry.
13883 With numerical prefix arg, use the nth allowed value, 0 stands for the 10th
13884 allowed value."
13885 (interactive "P")
13886 (if (equal value 0) (setq value 10))
13887 (let* ((completion-ignore-case t)
13888 (prop org-effort-property)
13889 (cur (org-entry-get nil prop))
13890 (allowed (org-property-get-allowed-values nil prop 'table))
13891 (existing (mapcar 'list (org-property-values prop)))
13893 (val (cond
13894 ((stringp value) value)
13895 ((and allowed (integerp value))
13896 (or (car (nth (1- value) allowed))
13897 (car (org-last allowed))))
13898 (allowed
13899 (message "Select 1-9,0, [RET%s]: %s"
13900 (if cur (concat "=" cur) "")
13901 (mapconcat 'car allowed " "))
13902 (setq rpl (read-char-exclusive))
13903 (if (equal rpl ?\r)
13905 (setq rpl (- rpl ?0))
13906 (if (equal rpl 0) (setq rpl 10))
13907 (if (and (> rpl 0) (<= rpl (length allowed)))
13908 (car (nth (1- rpl) allowed))
13909 (org-completing-read "Effort: " allowed nil))))
13911 (let (org-completion-use-ido org-completion-use-iswitchb)
13912 (org-completing-read
13913 (concat "Effort " (if (and cur (string-match "\\S-" cur))
13914 (concat "[" cur "]") "")
13915 ": ")
13916 existing nil nil "" nil cur))))))
13917 (unless (equal (org-entry-get nil prop) val)
13918 (org-entry-put nil prop val))
13919 (message "%s is now %s" prop val)))
13921 (defun org-at-property-p ()
13922 "Is cursor inside a property drawer?"
13923 (save-excursion
13924 (beginning-of-line 1)
13925 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
13926 (save-match-data ;; Used by calling procedures
13927 (let ((p (point))
13928 (range (unless (org-before-first-heading-p)
13929 (org-get-property-block))))
13930 (and range (<= (car range) p) (< p (cdr range))))))))
13932 (defun org-get-property-block (&optional beg end force)
13933 "Return the (beg . end) range of the body of the property drawer.
13934 BEG and END can be beginning and end of subtree, if not given
13935 they will be found.
13936 If the drawer does not exist and FORCE is non-nil, create the drawer."
13937 (catch 'exit
13938 (save-excursion
13939 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
13940 (end (or end (progn (outline-next-heading) (point)))))
13941 (goto-char beg)
13942 (if (re-search-forward org-property-start-re end t)
13943 (setq beg (1+ (match-end 0)))
13944 (if force
13945 (save-excursion
13946 (org-insert-property-drawer)
13947 (setq end (progn (outline-next-heading) (point))))
13948 (throw 'exit nil))
13949 (goto-char beg)
13950 (if (re-search-forward org-property-start-re end t)
13951 (setq beg (1+ (match-end 0)))))
13952 (if (re-search-forward org-property-end-re end t)
13953 (setq end (match-beginning 0))
13954 (or force (throw 'exit nil))
13955 (goto-char beg)
13956 (setq end beg)
13957 (org-indent-line-function)
13958 (insert ":END:\n"))
13959 (cons beg end)))))
13961 (defun org-entry-properties (&optional pom which specific)
13962 "Get all properties of the entry at point-or-marker POM.
13963 This includes the TODO keyword, the tags, time strings for deadline,
13964 scheduled, and clocking, and any additional properties defined in the
13965 entry. The return value is an alist, keys may occur multiple times
13966 if the property key was used several times.
13967 POM may also be nil, in which case the current entry is used.
13968 If WHICH is nil or `all', get all properties. If WHICH is
13969 `special' or `standard', only get that subclass. If WHICH
13970 is a string only get exactly this property. SPECIFIC can be a string, the
13971 specific property we are interested in. Specifying it can speed
13972 things up because then unnecessary parsing is avoided."
13973 (setq which (or which 'all))
13974 (org-with-point-at pom
13975 (let ((clockstr (substring org-clock-string 0 -1))
13976 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
13977 (case-fold-search nil)
13978 beg end range props sum-props key key1 value string clocksum)
13979 (save-excursion
13980 (when (condition-case nil
13981 (and (eq major-mode 'org-mode) (org-back-to-heading t))
13982 (error nil))
13983 (setq beg (point))
13984 (setq sum-props (get-text-property (point) 'org-summaries))
13985 (setq clocksum (get-text-property (point) :org-clock-minutes))
13986 (outline-next-heading)
13987 (setq end (point))
13988 (when (memq which '(all special))
13989 ;; Get the special properties, like TODO and tags
13990 (goto-char beg)
13991 (when (and (or (not specific) (string= specific "TODO"))
13992 (looking-at org-todo-line-regexp) (match-end 2))
13993 (push (cons "TODO" (org-match-string-no-properties 2)) props))
13994 (when (and (or (not specific) (string= specific "PRIORITY"))
13995 (looking-at org-priority-regexp))
13996 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
13997 (when (or (not specific) (string= specific "FILE"))
13998 (push (cons "FILE" buffer-file-name) props))
13999 (when (and (or (not specific) (string= specific "TAGS"))
14000 (setq value (org-get-tags-string))
14001 (string-match "\\S-" value))
14002 (push (cons "TAGS" value) props))
14003 (when (and (or (not specific) (string= specific "ALLTAGS"))
14004 (setq value (org-get-tags-at)))
14005 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
14006 ":"))
14007 props))
14008 (when (or (not specific) (string= specific "BLOCKED"))
14009 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
14010 (when (or (not specific)
14011 (member specific
14012 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
14013 "TIMESTAMP" "TIMESTAMP_IA")))
14014 (catch 'match
14015 (while (re-search-forward org-maybe-keyword-time-regexp end t)
14016 (setq key (if (match-end 1)
14017 (substring (org-match-string-no-properties 1)
14018 0 -1))
14019 string (if (equal key clockstr)
14020 (org-no-properties
14021 (org-trim
14022 (buffer-substring
14023 (match-beginning 3) (goto-char
14024 (point-at-eol)))))
14025 (substring (org-match-string-no-properties 3)
14026 1 -1)))
14027 ;; Get the correct property name from the key. This is
14028 ;; necessary if the user has configured time keywords.
14029 (setq key1 (concat key ":"))
14030 (cond
14031 ((not key)
14032 (setq key
14033 (if (= (char-after (match-beginning 3)) ?\[)
14034 "TIMESTAMP_IA" "TIMESTAMP")))
14035 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
14036 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
14037 ((equal key1 org-closed-string) (setq key "CLOSED"))
14038 ((equal key1 org-clock-string) (setq key "CLOCK")))
14039 (if (and specific (equal key specific) (not (equal key "CLOCK")))
14040 (progn
14041 (push (cons key string) props)
14042 ;; no need to search further if match is found
14043 (throw 'match t))
14044 (when (or (equal key "CLOCK") (not (assoc key props)))
14045 (push (cons key string) props))))))
14048 (when (memq which '(all standard))
14049 ;; Get the standard properties, like :PROP: ...
14050 (setq range (org-get-property-block beg end))
14051 (when range
14052 (goto-char (car range))
14053 (while (re-search-forward
14054 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
14055 (cdr range) t)
14056 (setq key (org-match-string-no-properties 1)
14057 value (org-trim (or (org-match-string-no-properties 2) "")))
14058 (unless (member key excluded)
14059 (push (cons key (or value "")) props)))))
14060 (if clocksum
14061 (push (cons "CLOCKSUM"
14062 (org-columns-number-to-string (/ (float clocksum) 60.)
14063 'add_times))
14064 props))
14065 (unless (assoc "CATEGORY" props)
14066 (push (cons "CATEGORY" (org-get-category)) props))
14067 (append sum-props (nreverse props)))))))
14069 (defun org-entry-get (pom property &optional inherit literal-nil)
14070 "Get value of PROPERTY for entry at point-or-marker POM.
14071 If INHERIT is non-nil and the entry does not have the property,
14072 then also check higher levels of the hierarchy.
14073 If INHERIT is the symbol `selective', use inheritance only if the setting
14074 in `org-use-property-inheritance' selects PROPERTY for inheritance.
14075 If the property is present but empty, the return value is the empty string.
14076 If the property is not present at all, nil is returned.
14078 If LITERAL-NIL is set, return the string value \"nil\" as a string,
14079 do not interpret it as the list atom nil. This is used for inheritance
14080 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
14081 (org-with-point-at pom
14082 (if (and inherit (if (eq inherit 'selective)
14083 (org-property-inherit-p property)
14085 (org-entry-get-with-inheritance property literal-nil)
14086 (if (member property org-special-properties)
14087 ;; We need a special property. Use `org-entry-properties' to
14088 ;; retrieve it, but specify the wanted property
14089 (cdr (assoc property (org-entry-properties nil 'special property)))
14090 (let ((range (unless (org-before-first-heading-p)
14091 (org-get-property-block))))
14092 (when (and range (goto-char (car range)))
14093 ((lambda (val) (when val (if literal-nil val (org-not-nil val))))
14094 (cond
14095 ((re-search-forward
14096 (org-re-property property) (cdr range) t)
14097 (if (match-end 1) (org-match-string-no-properties 1) ""))
14098 ((re-search-forward
14099 (org-re-property (concat property "+")) (cdr range) t)
14100 (cdr (assoc
14101 property
14102 (org-update-property-plist
14103 (concat property "+")
14104 (if (match-end 1) (org-match-string-no-properties 1) "")
14105 (list (or (assoc property org-file-properties)
14106 (assoc property org-global-properties)
14107 (assoc property org-global-properties-fixed)
14108 ))))))))))))))
14110 (defun org-property-or-variable-value (var &optional inherit)
14111 "Check if there is a property fixing the value of VAR.
14112 If yes, return this value. If not, return the current value of the variable."
14113 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14114 (if (and prop (stringp prop) (string-match "\\S-" prop))
14115 (read prop)
14116 (symbol-value var))))
14118 (defun org-entry-delete (pom property)
14119 "Delete the property PROPERTY from entry at point-or-marker POM."
14120 (org-with-point-at pom
14121 (if (member property org-special-properties)
14122 nil ; cannot delete these properties.
14123 (let ((range (org-get-property-block)))
14124 (if (and range
14125 (goto-char (car range))
14126 (re-search-forward
14127 (org-re-property property)
14128 (cdr range) t))
14129 (progn
14130 (delete-region (match-beginning 0) (1+ (point-at-eol)))
14132 nil)))))
14134 ;; Multi-values properties are properties that contain multiple values
14135 ;; These values are assumed to be single words, separated by whitespace.
14136 (defun org-entry-add-to-multivalued-property (pom property value)
14137 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
14138 (let* ((old (org-entry-get pom property))
14139 (values (and old (org-split-string old "[ \t]"))))
14140 (setq value (org-entry-protect-space value))
14141 (unless (member value values)
14142 (setq values (cons value values))
14143 (org-entry-put pom property
14144 (mapconcat 'identity values " ")))))
14146 (defun org-entry-remove-from-multivalued-property (pom property value)
14147 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
14148 (let* ((old (org-entry-get pom property))
14149 (values (and old (org-split-string old "[ \t]"))))
14150 (setq value (org-entry-protect-space value))
14151 (when (member value values)
14152 (setq values (delete value values))
14153 (org-entry-put pom property
14154 (mapconcat 'identity values " ")))))
14156 (defun org-entry-member-in-multivalued-property (pom property value)
14157 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
14158 (let* ((old (org-entry-get pom property))
14159 (values (and old (org-split-string old "[ \t]"))))
14160 (setq value (org-entry-protect-space value))
14161 (member value values)))
14163 (defun org-entry-get-multivalued-property (pom property)
14164 "Return a list of values in a multivalued property."
14165 (let* ((value (org-entry-get pom property))
14166 (values (and value (org-split-string value "[ \t]"))))
14167 (mapcar 'org-entry-restore-space values)))
14169 (defun org-entry-put-multivalued-property (pom property &rest values)
14170 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
14171 VALUES should be a list of strings. Spaces will be protected."
14172 (org-entry-put pom property
14173 (mapconcat 'org-entry-protect-space values " "))
14174 (let* ((value (org-entry-get pom property))
14175 (values (and value (org-split-string value "[ \t]"))))
14176 (mapcar 'org-entry-restore-space values)))
14178 (defun org-entry-protect-space (s)
14179 "Protect spaces and newline in string S."
14180 (while (string-match " " s)
14181 (setq s (replace-match "%20" t t s)))
14182 (while (string-match "\n" s)
14183 (setq s (replace-match "%0A" t t s)))
14186 (defun org-entry-restore-space (s)
14187 "Restore spaces and newline in string S."
14188 (while (string-match "%20" s)
14189 (setq s (replace-match " " t t s)))
14190 (while (string-match "%0A" s)
14191 (setq s (replace-match "\n" t t s)))
14194 (defvar org-entry-property-inherited-from (make-marker)
14195 "Marker pointing to the entry from where a property was inherited.
14196 Each call to `org-entry-get-with-inheritance' will set this marker to the
14197 location of the entry where the inheritance search matched. If there was
14198 no match, the marker will point nowhere.
14199 Note that also `org-entry-get' calls this function, if the INHERIT flag
14200 is set.")
14202 (defun org-entry-get-with-inheritance (property &optional literal-nil)
14203 "Get entry property, and search higher levels if not present.
14204 The search will stop at the first ancestor which has the property defined.
14205 If the value found is \"nil\", return nil to show that the property
14206 should be considered as undefined (this is the meaning of nil here).
14207 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
14208 (move-marker org-entry-property-inherited-from nil)
14209 (let (tmp)
14210 (unless (org-before-first-heading-p)
14211 (save-excursion
14212 (save-restriction
14213 (widen)
14214 (catch 'ex
14215 (while t
14216 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
14217 (org-back-to-heading t)
14218 (move-marker org-entry-property-inherited-from (point))
14219 (throw 'ex tmp))
14220 (or (org-up-heading-safe) (throw 'ex nil)))))))
14221 (setq tmp (or tmp
14222 (cdr (assoc property org-file-properties))
14223 (cdr (assoc property org-global-properties))
14224 (cdr (assoc property org-global-properties-fixed))))
14225 (if literal-nil tmp (org-not-nil tmp))))
14227 (defvar org-property-changed-functions nil
14228 "Hook called when the value of a property has changed.
14229 Each hook function should accept two arguments, the name of the property
14230 and the new value.")
14232 (defun org-entry-put (pom property value)
14233 "Set PROPERTY to VALUE for entry at point-or-marker POM."
14234 (org-with-point-at pom
14235 (org-back-to-heading t)
14236 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
14237 range)
14238 (cond
14239 ((equal property "TODO")
14240 (when (and (stringp value) (string-match "\\S-" value)
14241 (not (member value org-todo-keywords-1)))
14242 (error "\"%s\" is not a valid TODO state" value))
14243 (if (or (not value)
14244 (not (string-match "\\S-" value)))
14245 (setq value 'none))
14246 (org-todo value)
14247 (org-set-tags nil 'align))
14248 ((equal property "PRIORITY")
14249 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
14250 (string-to-char value) ?\ ))
14251 (org-set-tags nil 'align))
14252 ((equal property "SCHEDULED")
14253 (if (re-search-forward org-scheduled-time-regexp end t)
14254 (cond
14255 ((eq value 'earlier) (org-timestamp-change -1 'day))
14256 ((eq value 'later) (org-timestamp-change 1 'day))
14257 (t (call-interactively 'org-schedule)))
14258 (call-interactively 'org-schedule)))
14259 ((equal property "DEADLINE")
14260 (if (re-search-forward org-deadline-time-regexp end t)
14261 (cond
14262 ((eq value 'earlier) (org-timestamp-change -1 'day))
14263 ((eq value 'later) (org-timestamp-change 1 'day))
14264 (t (call-interactively 'org-deadline)))
14265 (call-interactively 'org-deadline)))
14266 ((member property org-special-properties)
14267 (error "The %s property can not yet be set with `org-entry-put'"
14268 property))
14269 (t ; a non-special property
14270 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
14271 (setq range (org-get-property-block beg end 'force))
14272 (goto-char (car range))
14273 (if (re-search-forward
14274 (org-re-property property) (cdr range) t)
14275 (progn
14276 (delete-region (match-beginning 0) (match-end 0))
14277 (goto-char (match-beginning 0)))
14278 (goto-char (cdr range))
14279 (insert "\n")
14280 (backward-char 1)
14281 (org-indent-line-function))
14282 (insert ":" property ":")
14283 (and value (insert " " value))
14284 (org-indent-line-function)))))
14285 (run-hook-with-args 'org-property-changed-functions property value)))
14287 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
14288 "Get all property keys in the current buffer.
14289 With INCLUDE-SPECIALS, also list the special properties that reflect things
14290 like tags and TODO state.
14291 With INCLUDE-DEFAULTS, also include properties that has special meaning
14292 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
14293 and others.
14294 With INCLUDE-COLUMNS, also include property names given in COLUMN
14295 formats in the current buffer."
14296 (let (rtn range cfmt s p)
14297 (save-excursion
14298 (save-restriction
14299 (widen)
14300 (goto-char (point-min))
14301 (while (re-search-forward org-property-start-re nil t)
14302 (setq range (org-get-property-block))
14303 (goto-char (car range))
14304 (while (re-search-forward
14305 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
14306 (cdr range) t)
14307 (add-to-list 'rtn (org-match-string-no-properties 1)))
14308 (outline-next-heading))))
14310 (when include-specials
14311 (setq rtn (append org-special-properties rtn)))
14313 (when include-defaults
14314 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
14315 (add-to-list 'rtn org-effort-property))
14317 (when include-columns
14318 (save-excursion
14319 (save-restriction
14320 (widen)
14321 (goto-char (point-min))
14322 (while (re-search-forward
14323 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
14324 nil t)
14325 (setq cfmt (match-string 2) s 0)
14326 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
14327 cfmt s)
14328 (setq s (match-end 0)
14329 p (match-string 1 cfmt))
14330 (unless (or (equal p "ITEM")
14331 (member p org-special-properties))
14332 (add-to-list 'rtn (match-string 1 cfmt))))))))
14334 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
14336 (defun org-property-values (key)
14337 "Return a list of all values of property KEY in the current buffer."
14338 (save-excursion
14339 (save-restriction
14340 (widen)
14341 (goto-char (point-min))
14342 (let ((re (org-re-property key))
14343 values)
14344 (while (re-search-forward re nil t)
14345 (add-to-list 'values (org-trim (match-string 1))))
14346 (delete "" values)))))
14348 (defun org-insert-property-drawer ()
14349 "Insert a property drawer into the current entry."
14350 (interactive)
14351 (org-back-to-heading t)
14352 (looking-at org-outline-regexp)
14353 (let ((indent (if org-adapt-indentation
14354 (- (match-end 0)(match-beginning 0))
14356 (beg (point))
14357 (re (concat "^[ \t]*" org-keyword-time-regexp))
14358 end hiddenp)
14359 (outline-next-heading)
14360 (setq end (point))
14361 (goto-char beg)
14362 (while (re-search-forward re end t))
14363 (setq hiddenp (outline-invisible-p))
14364 (end-of-line 1)
14365 (and (equal (char-after) ?\n) (forward-char 1))
14366 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
14367 (if (member (match-string 1) '("CLOCK:" ":END:"))
14368 ;; just skip this line
14369 (beginning-of-line 2)
14370 ;; Drawer start, find the end
14371 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
14372 (beginning-of-line 1)))
14373 (org-skip-over-state-notes)
14374 (skip-chars-backward " \t\n\r")
14375 (if (eq (char-before) ?*) (forward-char 1))
14376 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
14377 (beginning-of-line 0)
14378 (org-indent-to-column indent)
14379 (beginning-of-line 2)
14380 (org-indent-to-column indent)
14381 (beginning-of-line 0)
14382 (if hiddenp
14383 (save-excursion
14384 (org-back-to-heading t)
14385 (hide-entry))
14386 (org-flag-drawer t))))
14388 (defvar org-property-set-functions-alist nil
14389 "Property set function alist.
14390 Each entry should have the following format:
14392 (PROPERTY . READ-FUNCTION)
14394 The read function will be called with the same argument as
14395 `org-completing-read'.")
14397 (defun org-set-property-function (property)
14398 "Get the function that should be used to set PROPERTY.
14399 This is computed according to `org-property-set-functions-alist'."
14400 (or (cdr (assoc property org-property-set-functions-alist))
14401 'org-completing-read))
14403 (defun org-read-property-value (property)
14404 "Read PROPERTY value from user."
14405 (let* ((completion-ignore-case t)
14406 (allowed (org-property-get-allowed-values nil property 'table))
14407 (cur (org-entry-get nil property))
14408 (prompt (concat property " value"
14409 (if (and cur (string-match "\\S-" cur))
14410 (concat " [" cur "]") "") ": "))
14411 (set-function (org-set-property-function property))
14412 (val (if allowed
14413 (funcall set-function prompt allowed nil
14414 (not (get-text-property 0 'org-unrestricted
14415 (caar allowed))))
14416 (let (org-completion-use-ido org-completion-use-iswitchb)
14417 (funcall set-function prompt
14418 (mapcar 'list (org-property-values property))
14419 nil nil "" nil cur)))))
14420 (if (equal val "")
14422 val)))
14424 (defvar org-last-set-property nil)
14425 (defun org-read-property-name ()
14426 "Read a property name."
14427 (let* ((completion-ignore-case t)
14428 (keys (org-buffer-property-keys nil t t))
14429 (default-prop (or (save-excursion
14430 (save-match-data
14431 (beginning-of-line)
14432 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
14433 (null (string= (match-string 1) "END"))
14434 (match-string 1))))
14435 org-last-set-property))
14436 (property (org-icompleting-read
14437 (concat "Property"
14438 (if default-prop (concat " [" default-prop "]") "")
14439 ": ")
14440 (mapcar 'list keys)
14441 nil nil nil nil
14442 default-prop
14444 (if (member property keys)
14445 property
14446 (or (cdr (assoc (downcase property)
14447 (mapcar (lambda (x) (cons (downcase x) x))
14448 keys)))
14449 property))))
14451 (defun org-set-property (property value)
14452 "In the current entry, set PROPERTY to VALUE.
14453 When called interactively, this will prompt for a property name, offering
14454 completion on existing and default properties. And then it will prompt
14455 for a value, offering completion either on allowed values (via an inherited
14456 xxx_ALL property) or on existing values in other instances of this property
14457 in the current file."
14458 (interactive (list nil nil))
14459 (let* ((property (or property (org-read-property-name)))
14460 (value (or value (org-read-property-value property)))
14461 (fn (assoc property org-properties-postprocess-alist)))
14462 (setq org-last-set-property property)
14463 ;; Possibly postprocess the inserted value:
14464 (when fn (setq value (funcall (cadr fn) value)))
14465 (unless (equal (org-entry-get nil property) value)
14466 (org-entry-put nil property value))))
14468 (defun org-delete-property (property)
14469 "In the current entry, delete PROPERTY."
14470 (interactive
14471 (let* ((completion-ignore-case t)
14472 (prop (org-icompleting-read "Property: "
14473 (org-entry-properties nil 'standard))))
14474 (list prop)))
14475 (message "Property %s %s" property
14476 (if (org-entry-delete nil property)
14477 "deleted"
14478 "was not present in the entry")))
14480 (defun org-delete-property-globally (property)
14481 "Remove PROPERTY globally, from all entries."
14482 (interactive
14483 (let* ((completion-ignore-case t)
14484 (prop (org-icompleting-read
14485 "Globally remove property: "
14486 (mapcar 'list (org-buffer-property-keys)))))
14487 (list prop)))
14488 (save-excursion
14489 (save-restriction
14490 (widen)
14491 (goto-char (point-min))
14492 (let ((cnt 0))
14493 (while (re-search-forward
14494 (org-re-property property)
14495 nil t)
14496 (setq cnt (1+ cnt))
14497 (replace-match ""))
14498 (message "Property \"%s\" removed from %d entries" property cnt)))))
14500 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
14502 (defun org-compute-property-at-point ()
14503 "Compute the property at point.
14504 This looks for an enclosing column format, extracts the operator and
14505 then applies it to the property in the column format's scope."
14506 (interactive)
14507 (unless (org-at-property-p)
14508 (error "Not at a property"))
14509 (let ((prop (org-match-string-no-properties 2)))
14510 (org-columns-get-format-and-top-level)
14511 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
14512 (error "No operator defined for property %s" prop))
14513 (org-columns-compute prop)))
14515 (defvar org-property-allowed-value-functions nil
14516 "Hook for functions supplying allowed values for a specific property.
14517 The functions must take a single argument, the name of the property, and
14518 return a flat list of allowed values. If \":ETC\" is one of
14519 the values, this means that these values are intended as defaults for
14520 completion, but that other values should be allowed too.
14521 The functions must return nil if they are not responsible for this
14522 property.")
14524 (defun org-property-get-allowed-values (pom property &optional table)
14525 "Get allowed values for the property PROPERTY.
14526 When TABLE is non-nil, return an alist that can directly be used for
14527 completion."
14528 (let (vals)
14529 (cond
14530 ((equal property "TODO")
14531 (setq vals (org-with-point-at pom
14532 (append org-todo-keywords-1 '("")))))
14533 ((equal property "PRIORITY")
14534 (let ((n org-lowest-priority))
14535 (while (>= n org-highest-priority)
14536 (push (char-to-string n) vals)
14537 (setq n (1- n)))))
14538 ((member property org-special-properties))
14539 ((setq vals (run-hook-with-args-until-success
14540 'org-property-allowed-value-functions property)))
14542 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
14543 (when (and vals (string-match "\\S-" vals))
14544 (setq vals (car (read-from-string (concat "(" vals ")"))))
14545 (setq vals (mapcar (lambda (x)
14546 (cond ((stringp x) x)
14547 ((numberp x) (number-to-string x))
14548 ((symbolp x) (symbol-name x))
14549 (t "???")))
14550 vals)))))
14551 (when (member ":ETC" vals)
14552 (setq vals (remove ":ETC" vals))
14553 (org-add-props (car vals) '(org-unrestricted t)))
14554 (if table (mapcar 'list vals) vals)))
14556 (defun org-property-previous-allowed-value (&optional previous)
14557 "Switch to the next allowed value for this property."
14558 (interactive)
14559 (org-property-next-allowed-value t))
14561 (defun org-property-next-allowed-value (&optional previous)
14562 "Switch to the next allowed value for this property."
14563 (interactive)
14564 (unless (org-at-property-p)
14565 (error "Not at a property"))
14566 (let* ((key (match-string 2))
14567 (value (match-string 3))
14568 (allowed (or (org-property-get-allowed-values (point) key)
14569 (and (member value '("[ ]" "[-]" "[X]"))
14570 '("[ ]" "[X]"))))
14571 nval)
14572 (unless allowed
14573 (error "Allowed values for this property have not been defined"))
14574 (if previous (setq allowed (reverse allowed)))
14575 (if (member value allowed)
14576 (setq nval (car (cdr (member value allowed)))))
14577 (setq nval (or nval (car allowed)))
14578 (if (equal nval value)
14579 (error "Only one allowed value for this property"))
14580 (org-at-property-p)
14581 (replace-match (concat " :" key ": " nval) t t)
14582 (org-indent-line-function)
14583 (beginning-of-line 1)
14584 (skip-chars-forward " \t")
14585 (run-hook-with-args 'org-property-changed-functions key nval)))
14587 (defun org-find-olp (path &optional this-buffer)
14588 "Return a marker pointing to the entry at outline path OLP.
14589 If anything goes wrong, throw an error.
14590 You can wrap this call to catch the error like this:
14592 (condition-case msg
14593 (org-mobile-locate-entry (match-string 4))
14594 (error (nth 1 msg)))
14596 The return value will then be either a string with the error message,
14597 or a marker if everything is OK.
14599 If THIS-BUFFER is set, the outline path does not contain a file,
14600 only headings."
14601 (let* ((file (if this-buffer buffer-file-name (pop path)))
14602 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
14603 (level 1)
14604 (lmin 1)
14605 (lmax 1)
14606 limit re end found pos heading cnt flevel)
14607 (unless buffer (error "File not found :%s" file))
14608 (with-current-buffer buffer
14609 (save-excursion
14610 (save-restriction
14611 (widen)
14612 (setq limit (point-max))
14613 (goto-char (point-min))
14614 (while (setq heading (pop path))
14615 (setq re (format org-complex-heading-regexp-format
14616 (regexp-quote heading)))
14617 (setq cnt 0 pos (point))
14618 (while (re-search-forward re end t)
14619 (setq level (- (match-end 1) (match-beginning 1)))
14620 (if (and (>= level lmin) (<= level lmax))
14621 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
14622 (when (= cnt 0) (error "Heading not found on level %d: %s"
14623 lmax heading))
14624 (when (> cnt 1) (error "Heading not unique on level %d: %s"
14625 lmax heading))
14626 (goto-char found)
14627 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
14628 (setq end (save-excursion (org-end-of-subtree t t))))
14629 (when (org-on-heading-p)
14630 (move-marker (make-marker) (point))))))))
14632 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
14633 "Find node HEADING in BUFFER.
14634 Return a marker to the heading if it was found, or nil if not.
14635 If POS-ONLY is set, return just the position instead of a marker.
14637 The heading text must match exact, but it may have a TODO keyword,
14638 a priority cookie and tags in the standard locations."
14639 (with-current-buffer (or buffer (current-buffer))
14640 (save-excursion
14641 (save-restriction
14642 (widen)
14643 (goto-char (point-min))
14644 (let (case-fold-search)
14645 (if (re-search-forward
14646 (format org-complex-heading-regexp-format
14647 (regexp-quote heading)) nil t)
14648 (if pos-only
14649 (match-beginning 0)
14650 (move-marker (make-marker) (match-beginning 0)))))))))
14652 (defun org-find-exact-heading-in-directory (heading &optional dir)
14653 "Find Org node headline HEADING in all .org files in directory DIR.
14654 When the target headline is found, return a marker to this location."
14655 (let ((files (directory-files (or dir default-directory)
14656 nil "\\`[^.#].*\\.org\\'"))
14657 file visiting m buffer)
14658 (catch 'found
14659 (while (setq file (pop files))
14660 (message "trying %s" file)
14661 (setq visiting (org-find-base-buffer-visiting file))
14662 (setq buffer (or visiting (find-file-noselect file)))
14663 (setq m (org-find-exact-headline-in-buffer
14664 heading buffer))
14665 (when (and (not m) (not visiting)) (kill-buffer buffer))
14666 (and m (throw 'found m))))))
14668 (defun org-find-entry-with-id (ident)
14669 "Locate the entry that contains the ID property with exact value IDENT.
14670 IDENT can be a string, a symbol or a number, this function will search for
14671 the string representation of it.
14672 Return the position where this entry starts, or nil if there is no such entry."
14673 (interactive "sID: ")
14674 (let ((id (cond
14675 ((stringp ident) ident)
14676 ((symbol-name ident) (symbol-name ident))
14677 ((numberp ident) (number-to-string ident))
14678 (t (error "IDENT %s must be a string, symbol or number" ident))))
14679 (case-fold-search nil))
14680 (save-excursion
14681 (save-restriction
14682 (widen)
14683 (goto-char (point-min))
14684 (when (re-search-forward
14685 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
14686 nil t)
14687 (org-back-to-heading t)
14688 (point))))))
14690 ;;;; Timestamps
14692 (defvar org-last-changed-timestamp nil)
14693 (defvar org-last-inserted-timestamp nil
14694 "The last time stamp inserted with `org-insert-time-stamp'.")
14695 (defvar org-time-was-given) ; dynamically scoped parameter
14696 (defvar org-end-time-was-given) ; dynamically scoped parameter
14697 (defvar org-ts-what) ; dynamically scoped parameter
14699 (defun org-time-stamp (arg &optional inactive)
14700 "Prompt for a date/time and insert a time stamp.
14701 If the user specifies a time like HH:MM, or if this command is called
14702 with a prefix argument, the time stamp will contain date and time.
14703 Otherwise, only the date will be included. All parts of a date not
14704 specified by the user will be filled in from the current date/time.
14705 So if you press just return without typing anything, the time stamp
14706 will represent the current date/time. If there is already a timestamp
14707 at the cursor, it will be modified."
14708 (interactive "P")
14709 (let* ((ts nil)
14710 (default-time
14711 ;; Default time is either today, or, when entering a range,
14712 ;; the range start.
14713 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
14714 (save-excursion
14715 (re-search-backward
14716 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
14717 (- (point) 20) t)))
14718 (apply 'encode-time (org-parse-time-string (match-string 1)))
14719 (current-time)))
14720 (default-input (and ts (org-get-compact-tod ts)))
14721 (repeater (save-excursion
14722 (save-match-data
14723 (beginning-of-line)
14724 (when (re-search-forward
14725 "\\([.+-]+[0-9]+[dwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[dwmy]\\)?\\) ?"
14726 (save-excursion (progn (end-of-line) (point))) t)
14727 (match-string 0)))))
14728 org-time-was-given org-end-time-was-given time)
14729 (cond
14730 ((and (org-at-timestamp-p t)
14731 (memq last-command '(org-time-stamp org-time-stamp-inactive))
14732 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
14733 (insert "--")
14734 (setq time (let ((this-command this-command))
14735 (org-read-date arg 'totime nil nil
14736 default-time default-input)))
14737 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
14738 ((org-at-timestamp-p t)
14739 (setq time (let ((this-command this-command))
14740 (org-read-date arg 'totime nil nil default-time default-input)))
14741 (when (org-at-timestamp-p t) ; just to get the match data
14742 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
14743 (replace-match "")
14744 (setq org-last-changed-timestamp
14745 (org-insert-time-stamp
14746 time (or org-time-was-given arg)
14747 inactive nil nil (list org-end-time-was-given)))
14748 (when repeater (goto-char (1- (point))) (insert " " repeater)
14749 (setq org-last-changed-timestamp
14750 (concat (substring org-last-inserted-timestamp 0 -1)
14751 " " repeater ">"))))
14752 (message "Timestamp updated"))
14754 (setq time (let ((this-command this-command))
14755 (org-read-date arg 'totime nil nil default-time default-input)))
14756 (org-insert-time-stamp time (or org-time-was-given arg) inactive
14757 nil nil (list org-end-time-was-given))))))
14759 ;; FIXME: can we use this for something else, like computing time differences?
14760 (defun org-get-compact-tod (s)
14761 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
14762 (let* ((t1 (match-string 1 s))
14763 (h1 (string-to-number (match-string 2 s)))
14764 (m1 (string-to-number (match-string 3 s)))
14765 (t2 (and (match-end 4) (match-string 5 s)))
14766 (h2 (and t2 (string-to-number (match-string 6 s))))
14767 (m2 (and t2 (string-to-number (match-string 7 s))))
14768 dh dm)
14769 (if (not t2)
14771 (setq dh (- h2 h1) dm (- m2 m1))
14772 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
14773 (concat t1 "+" (number-to-string dh)
14774 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
14776 (defun org-time-stamp-inactive (&optional arg)
14777 "Insert an inactive time stamp.
14778 An inactive time stamp is enclosed in square brackets instead of angle
14779 brackets. It is inactive in the sense that it does not trigger agenda entries,
14780 does not link to the calendar and cannot be changed with the S-cursor keys.
14781 So these are more for recording a certain time/date."
14782 (interactive "P")
14783 (org-time-stamp arg 'inactive))
14785 (defvar org-date-ovl (make-overlay 1 1))
14786 (overlay-put org-date-ovl 'face 'org-warning)
14787 (org-detach-overlay org-date-ovl)
14789 (defvar org-ans1) ; dynamically scoped parameter
14790 (defvar org-ans2) ; dynamically scoped parameter
14792 (defvar org-plain-time-of-day-regexp) ; defined below
14794 (defvar org-overriding-default-time nil) ; dynamically scoped
14795 (defvar org-read-date-overlay nil)
14796 (defvar org-dcst nil) ; dynamically scoped
14797 (defvar org-read-date-history nil)
14798 (defvar org-read-date-final-answer nil)
14799 (defvar org-read-date-analyze-futurep nil)
14800 (defvar org-read-date-analyze-forced-year nil)
14802 (defun org-read-date (&optional with-time to-time from-string prompt
14803 default-time default-input)
14804 "Read a date, possibly a time, and make things smooth for the user.
14805 The prompt will suggest to enter an ISO date, but you can also enter anything
14806 which will at least partially be understood by `parse-time-string'.
14807 Unrecognized parts of the date will default to the current day, month, year,
14808 hour and minute. If this command is called to replace a timestamp at point,
14809 of to enter the second timestamp of a range, the default time is taken
14810 from the existing stamp. Furthermore, the command prefers the future,
14811 so if you are giving a date where the year is not given, and the day-month
14812 combination is already past in the current year, it will assume you
14813 mean next year. For details, see the manual. A few examples:
14815 3-2-5 --> 2003-02-05
14816 feb 15 --> currentyear-02-15
14817 2/15 --> currentyear-02-15
14818 sep 12 9 --> 2009-09-12
14819 12:45 --> today 12:45
14820 22 sept 0:34 --> currentyear-09-22 0:34
14821 12 --> currentyear-currentmonth-12
14822 Fri --> nearest Friday (today or later)
14823 etc.
14825 Furthermore you can specify a relative date by giving, as the *first* thing
14826 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
14827 change in days weeks, months, years.
14828 With a single plus or minus, the date is relative to today. With a double
14829 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
14830 +4d --> four days from today
14831 +4 --> same as above
14832 +2w --> two weeks from today
14833 ++5 --> five days from default date
14835 The function understands only English month and weekday abbreviations,
14836 but this can be configured with the variables `parse-time-months' and
14837 `parse-time-weekdays'.
14839 While prompting, a calendar is popped up - you can also select the
14840 date with the mouse (button 1). The calendar shows a period of three
14841 months. To scroll it to other months, use the keys `>' and `<'.
14842 If you don't like the calendar, turn it off with
14843 \(setq org-read-date-popup-calendar nil)
14845 With optional argument TO-TIME, the date will immediately be converted
14846 to an internal time.
14847 With an optional argument WITH-TIME, the prompt will suggest to also
14848 insert a time. Note that when WITH-TIME is not set, you can still
14849 enter a time, and this function will inform the calling routine about
14850 this change. The calling routine may then choose to change the format
14851 used to insert the time stamp into the buffer to include the time.
14852 With optional argument FROM-STRING, read from this string instead from
14853 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
14854 the time/date that is used for everything that is not specified by the
14855 user."
14856 (require 'parse-time)
14857 (let* ((org-time-stamp-rounding-minutes
14858 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
14859 (org-dcst org-display-custom-times)
14860 (ct (org-current-time))
14861 (def (or org-overriding-default-time default-time ct))
14862 (defdecode (decode-time def))
14863 (dummy (progn
14864 (when (< (nth 2 defdecode) org-extend-today-until)
14865 (setcar (nthcdr 2 defdecode) -1)
14866 (setcar (nthcdr 1 defdecode) 59)
14867 (setq def (apply 'encode-time defdecode)
14868 defdecode (decode-time def)))))
14869 (calendar-frame-setup nil)
14870 (calendar-setup nil)
14871 (calendar-move-hook nil)
14872 (calendar-view-diary-initially-flag nil)
14873 (calendar-view-holidays-initially-flag nil)
14874 (timestr (format-time-string
14875 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
14876 (prompt (concat (if prompt (concat prompt " ") "")
14877 (format "Date+time [%s]: " timestr)))
14878 ans (org-ans0 "") org-ans1 org-ans2 final)
14880 (cond
14881 (from-string (setq ans from-string))
14882 (org-read-date-popup-calendar
14883 (save-excursion
14884 (save-window-excursion
14885 (calendar)
14886 (unwind-protect
14887 (progn
14888 (calendar-forward-day (- (time-to-days def)
14889 (calendar-absolute-from-gregorian
14890 (calendar-current-date))))
14891 (org-eval-in-calendar nil t)
14892 (let* ((old-map (current-local-map))
14893 (map (copy-keymap calendar-mode-map))
14894 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
14895 (org-defkey map (kbd "RET") 'org-calendar-select)
14896 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
14897 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
14898 (org-defkey minibuffer-local-map [(meta shift left)]
14899 (lambda () (interactive)
14900 (org-eval-in-calendar '(calendar-backward-month 1))))
14901 (org-defkey minibuffer-local-map [(meta shift right)]
14902 (lambda () (interactive)
14903 (org-eval-in-calendar '(calendar-forward-month 1))))
14904 (org-defkey minibuffer-local-map [(meta shift up)]
14905 (lambda () (interactive)
14906 (org-eval-in-calendar '(calendar-backward-year 1))))
14907 (org-defkey minibuffer-local-map [(meta shift down)]
14908 (lambda () (interactive)
14909 (org-eval-in-calendar '(calendar-forward-year 1))))
14910 (org-defkey minibuffer-local-map [?\e (shift left)]
14911 (lambda () (interactive)
14912 (org-eval-in-calendar '(calendar-backward-month 1))))
14913 (org-defkey minibuffer-local-map [?\e (shift right)]
14914 (lambda () (interactive)
14915 (org-eval-in-calendar '(calendar-forward-month 1))))
14916 (org-defkey minibuffer-local-map [?\e (shift up)]
14917 (lambda () (interactive)
14918 (org-eval-in-calendar '(calendar-backward-year 1))))
14919 (org-defkey minibuffer-local-map [?\e (shift down)]
14920 (lambda () (interactive)
14921 (org-eval-in-calendar '(calendar-forward-year 1))))
14922 (org-defkey minibuffer-local-map [(shift up)]
14923 (lambda () (interactive)
14924 (org-eval-in-calendar '(calendar-backward-week 1))))
14925 (org-defkey minibuffer-local-map [(shift down)]
14926 (lambda () (interactive)
14927 (org-eval-in-calendar '(calendar-forward-week 1))))
14928 (org-defkey minibuffer-local-map [(shift left)]
14929 (lambda () (interactive)
14930 (org-eval-in-calendar '(calendar-backward-day 1))))
14931 (org-defkey minibuffer-local-map [(shift right)]
14932 (lambda () (interactive)
14933 (org-eval-in-calendar '(calendar-forward-day 1))))
14934 (org-defkey minibuffer-local-map ">"
14935 (lambda () (interactive)
14936 (org-eval-in-calendar '(scroll-calendar-left 1))))
14937 (org-defkey minibuffer-local-map "<"
14938 (lambda () (interactive)
14939 (org-eval-in-calendar '(scroll-calendar-right 1))))
14940 (org-defkey minibuffer-local-map "\C-v"
14941 (lambda () (interactive)
14942 (org-eval-in-calendar
14943 '(calendar-scroll-left-three-months 1))))
14944 (org-defkey minibuffer-local-map "\M-v"
14945 (lambda () (interactive)
14946 (org-eval-in-calendar
14947 '(calendar-scroll-right-three-months 1))))
14948 (run-hooks 'org-read-date-minibuffer-setup-hook)
14949 (unwind-protect
14950 (progn
14951 (use-local-map map)
14952 (add-hook 'post-command-hook 'org-read-date-display)
14953 (setq org-ans0 (read-string prompt default-input
14954 'org-read-date-history nil))
14955 ;; org-ans0: from prompt
14956 ;; org-ans1: from mouse click
14957 ;; org-ans2: from calendar motion
14958 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
14959 (remove-hook 'post-command-hook 'org-read-date-display)
14960 (use-local-map old-map)
14961 (when org-read-date-overlay
14962 (delete-overlay org-read-date-overlay)
14963 (setq org-read-date-overlay nil)))))
14964 (bury-buffer "*Calendar*")))))
14966 (t ; Naked prompt only
14967 (unwind-protect
14968 (setq ans (read-string prompt default-input
14969 'org-read-date-history timestr))
14970 (when org-read-date-overlay
14971 (delete-overlay org-read-date-overlay)
14972 (setq org-read-date-overlay nil)))))
14974 (setq final (org-read-date-analyze ans def defdecode))
14976 (when org-read-date-analyze-forced-year
14977 (message "Year was forced into %s"
14978 (if org-read-date-force-compatible-dates
14979 "compatible range (1970-2037)"
14980 "range representable on this machine"))
14981 (ding))
14983 ;; One round trip to get rid of 34th of August and stuff like that....
14984 (setq final (decode-time (apply 'encode-time final)))
14986 (setq org-read-date-final-answer ans)
14988 (if to-time
14989 (apply 'encode-time final)
14990 (if (and (boundp 'org-time-was-given) org-time-was-given)
14991 (format "%04d-%02d-%02d %02d:%02d"
14992 (nth 5 final) (nth 4 final) (nth 3 final)
14993 (nth 2 final) (nth 1 final))
14994 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
14996 (defvar def)
14997 (defvar defdecode)
14998 (defvar with-time)
14999 (defun org-read-date-display ()
15000 "Display the current date prompt interpretation in the minibuffer."
15001 (when org-read-date-display-live
15002 (when org-read-date-overlay
15003 (delete-overlay org-read-date-overlay))
15004 (let ((p (point)))
15005 (end-of-line 1)
15006 (while (not (equal (buffer-substring
15007 (max (point-min) (- (point) 4)) (point))
15008 " "))
15009 (insert " "))
15010 (goto-char p))
15011 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
15012 " " (or org-ans1 org-ans2)))
15013 (org-end-time-was-given nil)
15014 (f (org-read-date-analyze ans def defdecode))
15015 (fmts (if org-dcst
15016 org-time-stamp-custom-formats
15017 org-time-stamp-formats))
15018 (fmt (if (or with-time
15019 (and (boundp 'org-time-was-given) org-time-was-given))
15020 (cdr fmts)
15021 (car fmts)))
15022 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
15023 (when (and org-end-time-was-given
15024 (string-match org-plain-time-of-day-regexp txt))
15025 (setq txt (concat (substring txt 0 (match-end 0)) "-"
15026 org-end-time-was-given
15027 (substring txt (match-end 0)))))
15028 (when org-read-date-analyze-futurep
15029 (setq txt (concat txt " (=>F)")))
15030 (setq org-read-date-overlay
15031 (make-overlay (1- (point-at-eol)) (point-at-eol)))
15032 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
15034 (defun org-read-date-analyze (ans def defdecode)
15035 "Analyze the combined answer of the date prompt."
15036 ;; FIXME: cleanup and comment
15037 (let ((nowdecode (decode-time (current-time)))
15038 delta deltan deltaw deltadef year month day
15039 hour minute second wday pm h2 m2 tl wday1
15040 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
15041 (setq org-read-date-analyze-futurep nil
15042 org-read-date-analyze-forced-year nil)
15043 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
15044 (setq ans "+0"))
15046 (when (setq delta (org-read-date-get-relative ans (current-time) def))
15047 (setq ans (replace-match "" t t ans)
15048 deltan (car delta)
15049 deltaw (nth 1 delta)
15050 deltadef (nth 2 delta)))
15052 ;; Check if there is an iso week date in there
15053 ;; If yes, store the info and postpone interpreting it until the rest
15054 ;; of the parsing is done
15055 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
15056 (setq iso-year (if (match-end 1)
15057 (org-small-year-to-year
15058 (string-to-number (match-string 1 ans))))
15059 iso-weekday (if (match-end 3)
15060 (string-to-number (match-string 3 ans)))
15061 iso-week (string-to-number (match-string 2 ans)))
15062 (setq ans (replace-match "" t t ans)))
15064 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
15065 (when (string-match
15066 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
15067 (setq year (if (match-end 2)
15068 (string-to-number (match-string 2 ans))
15069 (progn (setq kill-year t)
15070 (string-to-number (format-time-string "%Y"))))
15071 month (string-to-number (match-string 3 ans))
15072 day (string-to-number (match-string 4 ans)))
15073 (if (< year 100) (setq year (+ 2000 year)))
15074 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15075 t nil ans)))
15077 ;; Help matching dottet european dates
15078 (when (string-match
15079 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\. ?\\([1-9][0-9][0-9][0-9]\\)?" ans)
15080 (setq year (if (match-end 3)
15081 (string-to-number (match-string 3 ans))
15082 (progn (setq kill-year t)
15083 (string-to-number (format-time-string "%Y"))))
15084 day (string-to-number (match-string 1 ans))
15085 month (string-to-number (match-string 2 ans))
15086 ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15087 t nil ans)))
15089 ;; Help matching american dates, like 5/30 or 5/30/7
15090 (when (string-match
15091 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
15092 (setq year (if (match-end 4)
15093 (string-to-number (match-string 4 ans))
15094 (progn (setq kill-year t)
15095 (string-to-number (format-time-string "%Y"))))
15096 month (string-to-number (match-string 1 ans))
15097 day (string-to-number (match-string 2 ans)))
15098 (if (< year 100) (setq year (+ 2000 year)))
15099 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15100 t nil ans)))
15101 ;; Help matching am/pm times, because `parse-time-string' does not do that.
15102 ;; If there is a time with am/pm, and *no* time without it, we convert
15103 ;; so that matching will be successful.
15104 (loop for i from 1 to 2 do ; twice, for end time as well
15105 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
15106 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
15107 (setq hour (string-to-number (match-string 1 ans))
15108 minute (if (match-end 3)
15109 (string-to-number (match-string 3 ans))
15111 pm (equal ?p
15112 (string-to-char (downcase (match-string 4 ans)))))
15113 (if (and (= hour 12) (not pm))
15114 (setq hour 0)
15115 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
15116 (setq ans (replace-match (format "%02d:%02d" hour minute)
15117 t t ans))))
15119 ;; Check if a time range is given as a duration
15120 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
15121 (setq hour (string-to-number (match-string 1 ans))
15122 h2 (+ hour (string-to-number (match-string 3 ans)))
15123 minute (string-to-number (match-string 2 ans))
15124 m2 (+ minute (if (match-end 5) (string-to-number
15125 (match-string 5 ans))0)))
15126 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
15127 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
15128 t t ans)))
15130 ;; Check if there is a time range
15131 (when (boundp 'org-end-time-was-given)
15132 (setq org-time-was-given nil)
15133 (when (and (string-match org-plain-time-of-day-regexp ans)
15134 (match-end 8))
15135 (setq org-end-time-was-given (match-string 8 ans))
15136 (setq ans (concat (substring ans 0 (match-beginning 7))
15137 (substring ans (match-end 7))))))
15139 (setq tl (parse-time-string ans)
15140 day (or (nth 3 tl) (nth 3 defdecode))
15141 month (or (nth 4 tl)
15142 (if (and org-read-date-prefer-future
15143 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
15144 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
15145 (nth 4 defdecode)))
15146 year (or (and (not kill-year) (nth 5 tl))
15147 (if (and org-read-date-prefer-future
15148 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
15149 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
15150 (nth 5 defdecode)))
15151 hour (or (nth 2 tl) (nth 2 defdecode))
15152 minute (or (nth 1 tl) (nth 1 defdecode))
15153 second (or (nth 0 tl) 0)
15154 wday (nth 6 tl))
15156 (when (and (eq org-read-date-prefer-future 'time)
15157 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
15158 (equal day (nth 3 nowdecode))
15159 (equal month (nth 4 nowdecode))
15160 (equal year (nth 5 nowdecode))
15161 (nth 2 tl)
15162 (or (< (nth 2 tl) (nth 2 nowdecode))
15163 (and (= (nth 2 tl) (nth 2 nowdecode))
15164 (nth 1 tl)
15165 (< (nth 1 tl) (nth 1 nowdecode)))))
15166 (setq day (1+ day)
15167 futurep t))
15169 ;; Special date definitions below
15170 (cond
15171 (iso-week
15172 ;; There was an iso week
15173 (require 'cal-iso)
15174 (setq futurep nil)
15175 (setq year (or iso-year year)
15176 day (or iso-weekday wday 1)
15177 wday nil ; to make sure that the trigger below does not match
15178 iso-date (calendar-gregorian-from-absolute
15179 (calendar-absolute-from-iso
15180 (list iso-week day year))))
15181 ; FIXME: Should we also push ISO weeks into the future?
15182 ; (when (and org-read-date-prefer-future
15183 ; (not iso-year)
15184 ; (< (calendar-absolute-from-gregorian iso-date)
15185 ; (time-to-days (current-time))))
15186 ; (setq year (1+ year)
15187 ; iso-date (calendar-gregorian-from-absolute
15188 ; (calendar-absolute-from-iso
15189 ; (list iso-week day year)))))
15190 (setq month (car iso-date)
15191 year (nth 2 iso-date)
15192 day (nth 1 iso-date)))
15193 (deltan
15194 (setq futurep nil)
15195 (unless deltadef
15196 (let ((now (decode-time (current-time))))
15197 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
15198 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
15199 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
15200 ((equal deltaw "m") (setq month (+ month deltan)))
15201 ((equal deltaw "y") (setq year (+ year deltan)))))
15202 ((and wday (not (nth 3 tl)))
15203 (setq futurep nil)
15204 ;; Weekday was given, but no day, so pick that day in the week
15205 ;; on or after the derived date.
15206 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
15207 (unless (equal wday wday1)
15208 (setq day (+ day (% (- wday wday1 -7) 7))))))
15209 (if (and (boundp 'org-time-was-given)
15210 (nth 2 tl))
15211 (setq org-time-was-given t))
15212 (if (< year 100) (setq year (+ 2000 year)))
15213 ;; Check of the date is representable
15214 (if org-read-date-force-compatible-dates
15215 (progn
15216 (if (< year 1970)
15217 (setq year 1970 org-read-date-analyze-forced-year t))
15218 (if (> year 2037)
15219 (setq year 2037 org-read-date-analyze-forced-year t)))
15220 (condition-case nil
15221 (ignore (encode-time second minute hour day month year))
15222 (error
15223 (setq year (nth 5 defdecode))
15224 (setq org-read-date-analyze-forced-year t))))
15225 (setq org-read-date-analyze-futurep futurep)
15226 (list second minute hour day month year)))
15228 (defvar parse-time-weekdays)
15230 (defun org-read-date-get-relative (s today default)
15231 "Check string S for special relative date string.
15232 TODAY and DEFAULT are internal times, for today and for a default.
15233 Return shift list (N what def-flag)
15234 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
15235 N is the number of WHATs to shift.
15236 DEF-FLAG is t when a double ++ or -- indicates shift relative to
15237 the DEFAULT date rather than TODAY."
15238 (require 'parse-time)
15239 (when (and
15240 (string-match
15241 (concat
15242 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
15243 "\\([0-9]+\\)?"
15244 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
15245 "\\([ \t]\\|$\\)") s)
15246 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
15247 (let* ((dir (if (> (match-end 1) (match-beginning 1))
15248 (string-to-char (substring (match-string 1 s) -1))
15249 ?+))
15250 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
15251 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
15252 (what (if (match-end 3) (match-string 3 s) "d"))
15253 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
15254 (date (if rel default today))
15255 (wday (nth 6 (decode-time date)))
15256 delta)
15257 (if wday1
15258 (progn
15259 (setq delta (mod (+ 7 (- wday1 wday)) 7))
15260 (if (= dir ?-) (setq delta (- delta 7)))
15261 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
15262 (list delta "d" rel))
15263 (list (* n (if (= dir ?-) -1 1)) what rel)))))
15265 (defun org-order-calendar-date-args (arg1 arg2 arg3)
15266 "Turn a user-specified date into the internal representation.
15267 The internal representation needed by the calendar is (month day year).
15268 This is a wrapper to handle the brain-dead convention in calendar that
15269 user function argument order change dependent on argument order."
15270 (if (boundp 'calendar-date-style)
15271 (cond
15272 ((eq calendar-date-style 'american)
15273 (list arg1 arg2 arg3))
15274 ((eq calendar-date-style 'european)
15275 (list arg2 arg1 arg3))
15276 ((eq calendar-date-style 'iso)
15277 (list arg2 arg3 arg1)))
15278 (with-no-warnings ;; european-calendar-style is obsolete as of version 23.1
15279 (if (org-bound-and-true-p european-calendar-style)
15280 (list arg2 arg1 arg3)
15281 (list arg1 arg2 arg3)))))
15283 (defun org-eval-in-calendar (form &optional keepdate)
15284 "Eval FORM in the calendar window and return to current window.
15285 Also, store the cursor date in variable org-ans2."
15286 (let ((sf (selected-frame))
15287 (sw (selected-window)))
15288 (select-window (get-buffer-window "*Calendar*" t))
15289 (eval form)
15290 (when (and (not keepdate) (calendar-cursor-to-date))
15291 (let* ((date (calendar-cursor-to-date))
15292 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15293 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
15294 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
15295 (select-window sw)
15296 (org-select-frame-set-input-focus sf)))
15298 (defun org-calendar-select ()
15299 "Return to `org-read-date' with the date currently selected.
15300 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15301 (interactive)
15302 (when (calendar-cursor-to-date)
15303 (let* ((date (calendar-cursor-to-date))
15304 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15305 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15306 (if (active-minibuffer-window) (exit-minibuffer))))
15308 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
15309 "Insert a date stamp for the date given by the internal TIME.
15310 WITH-HM means use the stamp format that includes the time of the day.
15311 INACTIVE means use square brackets instead of angular ones, so that the
15312 stamp will not contribute to the agenda.
15313 PRE and POST are optional strings to be inserted before and after the
15314 stamp.
15315 The command returns the inserted time stamp."
15316 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
15317 stamp)
15318 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
15319 (insert-before-markers (or pre ""))
15320 (when (listp extra)
15321 (setq extra (car extra))
15322 (if (and (stringp extra)
15323 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
15324 (setq extra (format "-%02d:%02d"
15325 (string-to-number (match-string 1 extra))
15326 (string-to-number (match-string 2 extra))))
15327 (setq extra nil)))
15328 (when extra
15329 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
15330 (insert-before-markers (setq stamp (format-time-string fmt time)))
15331 (insert-before-markers (or post ""))
15332 (setq org-last-inserted-timestamp stamp)))
15334 (defun org-toggle-time-stamp-overlays ()
15335 "Toggle the use of custom time stamp formats."
15336 (interactive)
15337 (setq org-display-custom-times (not org-display-custom-times))
15338 (unless org-display-custom-times
15339 (let ((p (point-min)) (bmp (buffer-modified-p)))
15340 (while (setq p (next-single-property-change p 'display))
15341 (if (and (get-text-property p 'display)
15342 (eq (get-text-property p 'face) 'org-date))
15343 (remove-text-properties
15344 p (setq p (next-single-property-change p 'display))
15345 '(display t))))
15346 (set-buffer-modified-p bmp)))
15347 (if (featurep 'xemacs)
15348 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
15349 (org-restart-font-lock)
15350 (setq org-table-may-need-update t)
15351 (if org-display-custom-times
15352 (message "Time stamps are overlayed with custom format")
15353 (message "Time stamp overlays removed")))
15355 (defun org-display-custom-time (beg end)
15356 "Overlay modified time stamp format over timestamp between BEG and END."
15357 (let* ((ts (buffer-substring beg end))
15358 t1 w1 with-hm tf time str w2 (off 0))
15359 (save-match-data
15360 (setq t1 (org-parse-time-string ts t))
15361 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)?\\'" ts)
15362 (setq off (- (match-end 0) (match-beginning 0)))))
15363 (setq end (- end off))
15364 (setq w1 (- end beg)
15365 with-hm (and (nth 1 t1) (nth 2 t1))
15366 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
15367 time (org-fix-decoded-time t1)
15368 str (org-add-props
15369 (format-time-string
15370 (substring tf 1 -1) (apply 'encode-time time))
15371 nil 'mouse-face 'highlight)
15372 w2 (length str))
15373 (if (not (= w2 w1))
15374 (add-text-properties (1+ beg) (+ 2 beg)
15375 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
15376 (if (featurep 'xemacs)
15377 (progn
15378 (put-text-property beg end 'invisible t)
15379 (put-text-property beg end 'end-glyph (make-glyph str)))
15380 (put-text-property beg end 'display str))))
15382 (defun org-translate-time (string)
15383 "Translate all timestamps in STRING to custom format.
15384 But do this only if the variable `org-display-custom-times' is set."
15385 (when org-display-custom-times
15386 (save-match-data
15387 (let* ((start 0)
15388 (re org-ts-regexp-both)
15389 t1 with-hm inactive tf time str beg end)
15390 (while (setq start (string-match re string start))
15391 (setq beg (match-beginning 0)
15392 end (match-end 0)
15393 t1 (save-match-data
15394 (org-parse-time-string (substring string beg end) t))
15395 with-hm (and (nth 1 t1) (nth 2 t1))
15396 inactive (equal (substring string beg (1+ beg)) "[")
15397 tf (funcall (if with-hm 'cdr 'car)
15398 org-time-stamp-custom-formats)
15399 time (org-fix-decoded-time t1)
15400 str (format-time-string
15401 (concat
15402 (if inactive "[" "<") (substring tf 1 -1)
15403 (if inactive "]" ">"))
15404 (apply 'encode-time time))
15405 string (replace-match str t t string)
15406 start (+ start (length str)))))))
15407 string)
15409 (defun org-fix-decoded-time (time)
15410 "Set 0 instead of nil for the first 6 elements of time.
15411 Don't touch the rest."
15412 (let ((n 0))
15413 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
15415 (defun org-days-to-time (timestamp-string)
15416 "Difference between TIMESTAMP-STRING and now in days."
15417 (- (time-to-days (org-time-string-to-time timestamp-string))
15418 (time-to-days (current-time))))
15420 (defun org-deadline-close (timestamp-string &optional ndays)
15421 "Is the time in TIMESTAMP-STRING close to the current date?"
15422 (setq ndays (or ndays (org-get-wdays timestamp-string)))
15423 (and (< (org-days-to-time timestamp-string) ndays)
15424 (not (org-entry-is-done-p))))
15426 (defun org-get-wdays (ts)
15427 "Get the deadline lead time appropriate for timestring TS."
15428 (cond
15429 ((<= org-deadline-warning-days 0)
15430 ;; 0 or negative, enforce this value no matter what
15431 (- org-deadline-warning-days))
15432 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\| \\)" ts)
15433 ;; lead time is specified.
15434 (floor (* (string-to-number (match-string 1 ts))
15435 (cdr (assoc (match-string 2 ts)
15436 '(("d" . 1) ("w" . 7)
15437 ("m" . 30.4) ("y" . 365.25)))))))
15438 ;; go for the default.
15439 (t org-deadline-warning-days)))
15441 (defun org-calendar-select-mouse (ev)
15442 "Return to `org-read-date' with the date currently selected.
15443 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15444 (interactive "e")
15445 (mouse-set-point ev)
15446 (when (calendar-cursor-to-date)
15447 (let* ((date (calendar-cursor-to-date))
15448 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15449 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15450 (if (active-minibuffer-window) (exit-minibuffer))))
15452 (defun org-check-deadlines (ndays)
15453 "Check if there are any deadlines due or past due.
15454 A deadline is considered due if it happens within `org-deadline-warning-days'
15455 days from today's date. If the deadline appears in an entry marked DONE,
15456 it is not shown. The prefix arg NDAYS can be used to test that many
15457 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
15458 (interactive "P")
15459 (let* ((org-warn-days
15460 (cond
15461 ((equal ndays '(4)) 100000)
15462 (ndays (prefix-numeric-value ndays))
15463 (t (abs org-deadline-warning-days))))
15464 (case-fold-search nil)
15465 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
15466 (callback
15467 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
15469 (message "%d deadlines past-due or due within %d days"
15470 (org-occur regexp nil callback)
15471 org-warn-days)))
15473 (defun org-check-before-date (date)
15474 "Check if there are deadlines or scheduled entries before DATE."
15475 (interactive (list (org-read-date)))
15476 (let ((case-fold-search nil)
15477 (regexp (concat "\\<\\(" org-deadline-string
15478 "\\|" org-scheduled-string
15479 "\\) *<\\([^>]+\\)>"))
15480 (callback
15481 (lambda () (time-less-p
15482 (org-time-string-to-time (match-string 2))
15483 (org-time-string-to-time date)))))
15484 (message "%d entries before %s"
15485 (org-occur regexp nil callback) date)))
15487 (defun org-check-after-date (date)
15488 "Check if there are deadlines or scheduled entries after DATE."
15489 (interactive (list (org-read-date)))
15490 (let ((case-fold-search nil)
15491 (regexp (concat "\\<\\(" org-deadline-string
15492 "\\|" org-scheduled-string
15493 "\\) *<\\([^>]+\\)>"))
15494 (callback
15495 (lambda () (not
15496 (time-less-p
15497 (org-time-string-to-time (match-string 2))
15498 (org-time-string-to-time date))))))
15499 (message "%d entries after %s"
15500 (org-occur regexp nil callback) date)))
15502 (defun org-evaluate-time-range (&optional to-buffer)
15503 "Evaluate a time range by computing the difference between start and end.
15504 Normally the result is just printed in the echo area, but with prefix arg
15505 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
15506 If the time range is actually in a table, the result is inserted into the
15507 next column.
15508 For time difference computation, a year is assumed to be exactly 365
15509 days in order to avoid rounding problems."
15510 (interactive "P")
15512 (org-clock-update-time-maybe)
15513 (save-excursion
15514 (unless (org-at-date-range-p t)
15515 (goto-char (point-at-bol))
15516 (re-search-forward org-tr-regexp-both (point-at-eol) t))
15517 (if (not (org-at-date-range-p t))
15518 (error "Not at a time-stamp range, and none found in current line")))
15519 (let* ((ts1 (match-string 1))
15520 (ts2 (match-string 2))
15521 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
15522 (match-end (match-end 0))
15523 (time1 (org-time-string-to-time ts1))
15524 (time2 (org-time-string-to-time ts2))
15525 (t1 (org-float-time time1))
15526 (t2 (org-float-time time2))
15527 (diff (abs (- t2 t1)))
15528 (negative (< (- t2 t1) 0))
15529 ;; (ys (floor (* 365 24 60 60)))
15530 (ds (* 24 60 60))
15531 (hs (* 60 60))
15532 (fy "%dy %dd %02d:%02d")
15533 (fy1 "%dy %dd")
15534 (fd "%dd %02d:%02d")
15535 (fd1 "%dd")
15536 (fh "%02d:%02d")
15537 y d h m align)
15538 (if havetime
15539 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
15541 d (floor (/ diff ds)) diff (mod diff ds)
15542 h (floor (/ diff hs)) diff (mod diff hs)
15543 m (floor (/ diff 60)))
15544 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
15546 d (floor (+ (/ diff ds) 0.5))
15547 h 0 m 0))
15548 (if (not to-buffer)
15549 (message "%s" (org-make-tdiff-string y d h m))
15550 (if (org-at-table-p)
15551 (progn
15552 (goto-char match-end)
15553 (setq align t)
15554 (and (looking-at " *|") (goto-char (match-end 0))))
15555 (goto-char match-end))
15556 (if (looking-at
15557 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
15558 (replace-match ""))
15559 (if negative (insert " -"))
15560 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
15561 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
15562 (insert " " (format fh h m))))
15563 (if align (org-table-align))
15564 (message "Time difference inserted")))))
15566 (defun org-make-tdiff-string (y d h m)
15567 (let ((fmt "")
15568 (l nil))
15569 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
15570 l (push y l)))
15571 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
15572 l (push d l)))
15573 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
15574 l (push h l)))
15575 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
15576 l (push m l)))
15577 (apply 'format fmt (nreverse l))))
15579 (defun org-time-string-to-time (s &optional buffer pos)
15580 (condition-case errdata
15581 (apply 'encode-time (org-parse-time-string s))
15582 (error (error "Bad timestamp `%s'%s\nError was: %s"
15583 s (if (not (and buffer pos))
15585 (format " at %d in buffer `%s'" pos buffer))
15586 (cdr errdata)))))
15588 (defun org-time-string-to-seconds (s)
15589 (org-float-time (org-time-string-to-time s)))
15591 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
15592 "Convert a time stamp to an absolute day number.
15593 If there is a specifier for a cyclic time stamp, get the closest date to
15594 DAYNR.
15595 PREFER and SHOW-ALL are passed through to `org-closest-date'.
15596 The variable date is bound by the calendar when this is called."
15597 (cond
15598 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
15599 (if (org-diary-sexp-entry (match-string 1 s) "" date)
15600 daynr
15601 (+ daynr 1000)))
15602 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
15603 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
15604 (time-to-days (current-time))) (match-string 0 s)
15605 prefer show-all))
15606 (t (time-to-days
15607 (condition-case errdata
15608 (apply 'encode-time (org-parse-time-string s))
15609 (error (error "Bad timestamp `%s'%s\nError was: %s"
15610 s (if (not (and buffer pos))
15612 (format " at %d in buffer `%s'" pos buffer))
15613 (cdr errdata))))))))
15615 (defun org-days-to-iso-week (days)
15616 "Return the iso week number."
15617 (require 'cal-iso)
15618 (car (calendar-iso-from-absolute days)))
15620 (defun org-small-year-to-year (year)
15621 "Convert 2-digit years into 4-digit years.
15622 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
15623 The year 2000 cannot be abbreviated. Any year larger than 99
15624 is returned unchanged."
15625 (if (< year 38)
15626 (setq year (+ 2000 year))
15627 (if (< year 100)
15628 (setq year (+ 1900 year))))
15629 year)
15631 (defun org-time-from-absolute (d)
15632 "Return the time corresponding to date D.
15633 D may be an absolute day number, or a calendar-type list (month day year)."
15634 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
15635 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
15637 (defun org-calendar-holiday ()
15638 "List of holidays, for Diary display in Org-mode."
15639 (require 'holidays)
15640 (let ((hl (funcall
15641 (if (fboundp 'calendar-check-holidays)
15642 'calendar-check-holidays 'check-calendar-holidays) date)))
15643 (if hl (mapconcat 'identity hl "; "))))
15645 (defun org-diary-sexp-entry (sexp entry date)
15646 "Process a SEXP diary ENTRY for DATE."
15647 (require 'diary-lib)
15648 (let ((result (if calendar-debug-sexp
15649 (let ((stack-trace-on-error t))
15650 (eval (car (read-from-string sexp))))
15651 (condition-case nil
15652 (eval (car (read-from-string sexp)))
15653 (error
15654 (beep)
15655 (message "Bad sexp at line %d in %s: %s"
15656 (org-current-line)
15657 (buffer-file-name) sexp)
15658 (sleep-for 2))))))
15659 (cond ((stringp result) (split-string result "; "))
15660 ((and (consp result)
15661 (not (consp (cdr result)))
15662 (stringp (cdr result))) (cdr result))
15663 ((and (consp result)
15664 (stringp (car result))) result)
15665 (result entry)
15666 (t nil))))
15668 (defun org-diary-to-ical-string (frombuf)
15669 "Get iCalendar entries from diary entries in buffer FROMBUF.
15670 This uses the icalendar.el library."
15671 (let* ((tmpdir (if (featurep 'xemacs)
15672 (temp-directory)
15673 temporary-file-directory))
15674 (tmpfile (make-temp-name
15675 (expand-file-name "orgics" tmpdir)))
15676 buf rtn b e)
15677 (with-current-buffer frombuf
15678 (icalendar-export-region (point-min) (point-max) tmpfile)
15679 (setq buf (find-buffer-visiting tmpfile))
15680 (set-buffer buf)
15681 (goto-char (point-min))
15682 (if (re-search-forward "^BEGIN:VEVENT" nil t)
15683 (setq b (match-beginning 0)))
15684 (goto-char (point-max))
15685 (if (re-search-backward "^END:VEVENT" nil t)
15686 (setq e (match-end 0)))
15687 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
15688 (kill-buffer buf)
15689 (delete-file tmpfile)
15690 rtn))
15692 (defun org-closest-date (start current change prefer show-all)
15693 "Find the date closest to CURRENT that is consistent with START and CHANGE.
15694 When PREFER is `past', return a date that is either CURRENT or past.
15695 When PREFER is `future', return a date that is either CURRENT or future.
15696 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
15697 ;; Make the proper lists from the dates
15698 (catch 'exit
15699 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
15700 dn dw sday cday n1 n2 n0
15701 d m y y1 y2 date1 date2 nmonths nm ny m2)
15703 (setq start (org-date-to-gregorian start)
15704 current (org-date-to-gregorian
15705 (if show-all
15706 current
15707 (time-to-days (current-time))))
15708 sday (calendar-absolute-from-gregorian start)
15709 cday (calendar-absolute-from-gregorian current))
15711 (if (<= cday sday) (throw 'exit sday))
15713 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
15714 (setq dn (string-to-number (match-string 1 change))
15715 dw (cdr (assoc (match-string 2 change) a1)))
15716 (error "Invalid change specifier: %s" change))
15717 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
15718 (cond
15719 ((eq dw 'day)
15720 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
15721 n2 (+ n1 dn)))
15722 ((eq dw 'year)
15723 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
15724 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
15725 (setq date1 (list m d y1)
15726 n1 (calendar-absolute-from-gregorian date1)
15727 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
15728 n2 (calendar-absolute-from-gregorian date2)))
15729 ((eq dw 'month)
15730 ;; approx number of month between the two dates
15731 (setq nmonths (floor (/ (- cday sday) 30.436875)))
15732 ;; How often does dn fit in there?
15733 (setq d (nth 1 start) m (car start) y (nth 2 start)
15734 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
15735 m (+ m nm)
15736 ny (floor (/ m 12))
15737 y (+ y ny)
15738 m (- m (* ny 12)))
15739 (while (> m 12) (setq m (- m 12) y (1+ y)))
15740 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
15741 (setq m2 (+ m dn) y2 y)
15742 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
15743 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
15744 (while (<= n2 cday)
15745 (setq n1 n2 m m2 y y2)
15746 (setq m2 (+ m dn) y2 y)
15747 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
15748 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
15749 ;; Make sure n1 is the earlier date
15750 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
15751 (if show-all
15752 (cond
15753 ((eq prefer 'past) (if (= cday n2) n2 n1))
15754 ((eq prefer 'future) (if (= cday n1) n1 n2))
15755 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
15756 (cond
15757 ((eq prefer 'past) (if (= cday n2) n2 n1))
15758 ((eq prefer 'future) (if (= cday n1) n1 n2))
15759 (t (if (= cday n1) n1 n2)))))))
15761 (defun org-date-to-gregorian (date)
15762 "Turn any specification of DATE into a Gregorian date for the calendar."
15763 (cond ((integerp date) (calendar-gregorian-from-absolute date))
15764 ((and (listp date) (= (length date) 3)) date)
15765 ((stringp date)
15766 (setq date (org-parse-time-string date))
15767 (list (nth 4 date) (nth 3 date) (nth 5 date)))
15768 ((listp date)
15769 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
15771 (defun org-parse-time-string (s &optional nodefault)
15772 "Parse the standard Org-mode time string.
15773 This should be a lot faster than the normal `parse-time-string'.
15774 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
15775 hour and minute fields will be nil if not given."
15776 (if (string-match org-ts-regexp0 s)
15777 (list 0
15778 (if (or (match-beginning 8) (not nodefault))
15779 (string-to-number (or (match-string 8 s) "0")))
15780 (if (or (match-beginning 7) (not nodefault))
15781 (string-to-number (or (match-string 7 s) "0")))
15782 (string-to-number (match-string 4 s))
15783 (string-to-number (match-string 3 s))
15784 (string-to-number (match-string 2 s))
15785 nil nil nil)
15786 (error "Not a standard Org-mode time string: %s" s)))
15788 (defun org-timestamp-up (&optional arg)
15789 "Increase the date item at the cursor by one.
15790 If the cursor is on the year, change the year. If it is on the month,
15791 the day or the time, change that.
15792 With prefix ARG, change by that many units."
15793 (interactive "p")
15794 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
15796 (defun org-timestamp-down (&optional arg)
15797 "Decrease the date item at the cursor by one.
15798 If the cursor is on the year, change the year. If it is on the month,
15799 the day or the time, change that.
15800 With prefix ARG, change by that many units."
15801 (interactive "p")
15802 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
15804 (defun org-timestamp-up-day (&optional arg)
15805 "Increase the date in the time stamp by one day.
15806 With prefix ARG, change that many days."
15807 (interactive "p")
15808 (if (and (not (org-at-timestamp-p t))
15809 (org-on-heading-p))
15810 (org-todo 'up)
15811 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
15813 (defun org-timestamp-down-day (&optional arg)
15814 "Decrease the date in the time stamp by one day.
15815 With prefix ARG, change that many days."
15816 (interactive "p")
15817 (if (and (not (org-at-timestamp-p t))
15818 (org-on-heading-p))
15819 (org-todo 'down)
15820 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
15822 (defun org-at-timestamp-p (&optional inactive-ok)
15823 "Determine if the cursor is in or at a timestamp."
15824 (interactive)
15825 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
15826 (pos (point))
15827 (ans (or (looking-at tsr)
15828 (save-excursion
15829 (skip-chars-backward "^[<\n\r\t")
15830 (if (> (point) (point-min)) (backward-char 1))
15831 (and (looking-at tsr)
15832 (> (- (match-end 0) pos) -1))))))
15833 (and ans
15834 (boundp 'org-ts-what)
15835 (setq org-ts-what
15836 (cond
15837 ((= pos (match-beginning 0)) 'bracket)
15838 ;; Point is considered to be "on the bracket" whether
15839 ;; it's really on it or right after it.
15840 ((or (= pos (1- (match-end 0)))
15841 (= pos (match-end 0))) 'bracket)
15842 ((org-pos-in-match-range pos 2) 'year)
15843 ((org-pos-in-match-range pos 3) 'month)
15844 ((org-pos-in-match-range pos 7) 'hour)
15845 ((org-pos-in-match-range pos 8) 'minute)
15846 ((or (org-pos-in-match-range pos 4)
15847 (org-pos-in-match-range pos 5)) 'day)
15848 ((and (> pos (or (match-end 8) (match-end 5)))
15849 (< pos (match-end 0)))
15850 (- pos (or (match-end 8) (match-end 5))))
15851 (t 'day))))
15852 ans))
15854 (defun org-toggle-timestamp-type ()
15855 "Toggle the type (<active> or [inactive]) of a time stamp."
15856 (interactive)
15857 (when (org-at-timestamp-p t)
15858 (let ((beg (match-beginning 0)) (end (match-end 0))
15859 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
15860 (save-excursion
15861 (goto-char beg)
15862 (while (re-search-forward "[][<>]" end t)
15863 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
15864 t t)))
15865 (message "Timestamp is now %sactive"
15866 (if (equal (char-after beg) ?<) "" "in")))))
15868 (defun org-timestamp-change (n &optional what updown)
15869 "Change the date in the time stamp at point.
15870 The date will be changed by N times WHAT. WHAT can be `day', `month',
15871 `year', `minute', `second'. If WHAT is not given, the cursor position
15872 in the timestamp determines what will be changed."
15873 (let ((origin (point)) origin-cat
15874 with-hm inactive
15875 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
15876 org-ts-what
15877 extra rem
15878 ts time time0)
15879 (if (not (org-at-timestamp-p t))
15880 (error "Not at a timestamp"))
15881 (if (and (not what) (eq org-ts-what 'bracket))
15882 (org-toggle-timestamp-type)
15883 ;; Point isn't on brackets. Remember the part of the time-stamp
15884 ;; the point was in. Indeed, size of time-stamps may change,
15885 ;; but point must be kept in the same category nonetheless.
15886 (setq origin-cat org-ts-what)
15887 (if (and (not what) (not (eq org-ts-what 'day))
15888 org-display-custom-times
15889 (get-text-property (point) 'display)
15890 (not (get-text-property (1- (point)) 'display)))
15891 (setq org-ts-what 'day))
15892 (setq org-ts-what (or what org-ts-what)
15893 inactive (= (char-after (match-beginning 0)) ?\[)
15894 ts (match-string 0))
15895 (replace-match "")
15896 (if (string-match
15897 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)*\\)[]>]"
15899 (setq extra (match-string 1 ts)))
15900 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
15901 (setq with-hm t))
15902 (setq time0 (org-parse-time-string ts))
15903 (when (and updown
15904 (eq org-ts-what 'minute)
15905 (not current-prefix-arg))
15906 ;; This looks like s-up and s-down. Change by one rounding step.
15907 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
15908 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
15909 (setcar (cdr time0) (+ (nth 1 time0)
15910 (if (> n 0) (- rem) (- dm rem))))))
15911 (setq time
15912 (encode-time (or (car time0) 0)
15913 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
15914 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
15915 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
15916 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
15917 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
15918 (nthcdr 6 time0)))
15919 (when (and (member org-ts-what '(hour minute))
15920 extra
15921 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
15922 (setq extra (org-modify-ts-extra
15923 extra
15924 (if (eq org-ts-what 'hour) 2 5)
15925 n dm)))
15926 (when (integerp org-ts-what)
15927 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
15928 (if (eq what 'calendar)
15929 (let ((cal-date (org-get-date-from-calendar)))
15930 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
15931 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
15932 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
15933 (setcar time0 (or (car time0) 0))
15934 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
15935 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
15936 (setq time (apply 'encode-time time0))))
15937 ;; Insert the new time-stamp, and ensure point stays in the same
15938 ;; category as before (i.e. not after the last position in that
15939 ;; category).
15940 (let ((pos (point)))
15941 ;; Stay before inserted string. `save-excursion' is of no use.
15942 (setq org-last-changed-timestamp
15943 (org-insert-time-stamp time with-hm inactive nil nil extra))
15944 (goto-char pos))
15945 (save-match-data
15946 (looking-at org-ts-regexp3)
15947 (goto-char (cond
15948 ;; `day' category ends before `hour' if any, or at
15949 ;; the end of the day name.
15950 ((eq origin-cat 'day)
15951 (min (or (match-beginning 7) (1- (match-end 5))) origin))
15952 ((eq origin-cat 'hour) (min (match-end 7) origin))
15953 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
15954 ((integerp origin-cat) (min (1- (match-end 0)) origin))
15955 ;; `year' and `month' have both fixed size: point
15956 ;; couldn't have moved into another part.
15957 (t origin))))
15958 ;; Update clock if on a CLOCK line.
15959 (org-clock-update-time-maybe)
15960 ;; Try to recenter the calendar window, if any.
15961 (if (and org-calendar-follow-timestamp-change
15962 (get-buffer-window "*Calendar*" t)
15963 (memq org-ts-what '(day month year)))
15964 (org-recenter-calendar (time-to-days time))))))
15966 (defun org-modify-ts-extra (s pos n dm)
15967 "Change the different parts of the lead-time and repeat fields in timestamp."
15968 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
15969 ng h m new rem)
15970 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
15971 (cond
15972 ((or (org-pos-in-match-range pos 2)
15973 (org-pos-in-match-range pos 3))
15974 (setq m (string-to-number (match-string 3 s))
15975 h (string-to-number (match-string 2 s)))
15976 (if (org-pos-in-match-range pos 2)
15977 (setq h (+ h n))
15978 (setq n (* dm (org-no-warnings (signum n))))
15979 (when (not (= 0 (setq rem (% m dm))))
15980 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
15981 (setq m (+ m n)))
15982 (if (< m 0) (setq m (+ m 60) h (1- h)))
15983 (if (> m 59) (setq m (- m 60) h (1+ h)))
15984 (setq h (min 24 (max 0 h)))
15985 (setq ng 1 new (format "-%02d:%02d" h m)))
15986 ((org-pos-in-match-range pos 6)
15987 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
15988 ((org-pos-in-match-range pos 5)
15989 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
15991 ((org-pos-in-match-range pos 9)
15992 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
15993 ((org-pos-in-match-range pos 8)
15994 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
15996 (when ng
15997 (setq s (concat
15998 (substring s 0 (match-beginning ng))
16000 (substring s (match-end ng))))))
16003 (defun org-recenter-calendar (date)
16004 "If the calendar is visible, recenter it to DATE."
16005 (let* ((win (selected-window))
16006 (cwin (get-buffer-window "*Calendar*" t))
16007 (calendar-move-hook nil))
16008 (when cwin
16009 (select-window cwin)
16010 (calendar-goto-date (if (listp date) date
16011 (calendar-gregorian-from-absolute date)))
16012 (select-window win))))
16014 (defun org-goto-calendar (&optional arg)
16015 "Go to the Emacs calendar at the current date.
16016 If there is a time stamp in the current line, go to that date.
16017 A prefix ARG can be used to force the current date."
16018 (interactive "P")
16019 (let ((tsr org-ts-regexp) diff
16020 (calendar-move-hook nil)
16021 (calendar-view-holidays-initially-flag nil)
16022 (calendar-view-diary-initially-flag nil))
16023 (if (or (org-at-timestamp-p)
16024 (save-excursion
16025 (beginning-of-line 1)
16026 (looking-at (concat ".*" tsr))))
16027 (let ((d1 (time-to-days (current-time)))
16028 (d2 (time-to-days
16029 (org-time-string-to-time (match-string 1)))))
16030 (setq diff (- d2 d1))))
16031 (calendar)
16032 (calendar-goto-today)
16033 (if (and diff (not arg)) (calendar-forward-day diff))))
16035 (defun org-get-date-from-calendar ()
16036 "Return a list (month day year) of date at point in calendar."
16037 (with-current-buffer "*Calendar*"
16038 (save-match-data
16039 (calendar-cursor-to-date))))
16041 (defun org-date-from-calendar ()
16042 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
16043 If there is already a time stamp at the cursor position, update it."
16044 (interactive)
16045 (if (org-at-timestamp-p t)
16046 (org-timestamp-change 0 'calendar)
16047 (let ((cal-date (org-get-date-from-calendar)))
16048 (org-insert-time-stamp
16049 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
16051 (defun org-minutes-to-hh:mm-string (m)
16052 "Compute H:MM from a number of minutes."
16053 (let ((h (/ m 60)))
16054 (setq m (- m (* 60 h)))
16055 (format org-time-clocksum-format h m)))
16057 (defun org-hh:mm-string-to-minutes (s)
16058 "Convert a string H:MM to a number of minutes.
16059 If the string is just a number, interpret it as minutes.
16060 In fact, the first hh:mm or number in the string will be taken,
16061 there can be extra stuff in the string.
16062 If no number is found, the return value is 0."
16063 (cond
16064 ((integerp s) s)
16065 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
16066 (+ (* (string-to-number (match-string 1 s)) 60)
16067 (string-to-number (match-string 2 s))))
16068 ((string-match "\\([0-9]+\\)" s)
16069 (string-to-number (match-string 1 s)))
16070 (t 0)))
16072 (defcustom org-effort-durations
16073 `(("h" . 60)
16074 ("d" . ,(* 60 8))
16075 ("w" . ,(* 60 8 5))
16076 ("m" . ,(* 60 8 5 4))
16077 ("y" . ,(* 60 8 5 40)))
16078 "Conversion factor to minutes for an effort modifier.
16080 Each entry has the form (MODIFIER . MINUTES).
16082 In an effort string, a number followed by MODIFIER is multiplied
16083 by the specified number of MINUTES to obtain an effort in
16084 minutes.
16086 For example, if the value of this variable is ((\"hours\" . 60)), then an
16087 effort string \"2hours\" is equivalent to 120 minutes."
16088 :group 'org-agenda
16089 :type '(alist :key-type (string :tag "Modifier")
16090 :value-type (number :tag "Minutes")))
16092 (defun org-duration-string-to-minutes (s)
16093 "Convert a duration string S to minutes.
16095 A bare number is interpreted as minutes, modifiers can be set by
16096 customizing `org-effort-durations' (which see).
16098 Entries containing a colon are interpreted as H:MM by
16099 `org-hh:mm-string-to-minutes'."
16100 (let ((result 0)
16101 (re (concat "\\([0-9]+\\) *\\("
16102 (regexp-opt (mapcar 'car org-effort-durations))
16103 "\\)")))
16104 (while (string-match re s)
16105 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
16106 (string-to-number (match-string 1 s))))
16107 (setq s (replace-match "" nil t s)))
16108 (incf result (org-hh:mm-string-to-minutes s))
16109 result))
16111 ;;;; Files
16113 (defun org-save-all-org-buffers ()
16114 "Save all Org-mode buffers without user confirmation."
16115 (interactive)
16116 (message "Saving all Org-mode buffers...")
16117 (save-some-buffers t (lambda () (eq major-mode 'org-mode)))
16118 (when (featurep 'org-id) (org-id-locations-save))
16119 (message "Saving all Org-mode buffers... done"))
16121 (defun org-revert-all-org-buffers ()
16122 "Revert all Org-mode buffers.
16123 Prompt for confirmation when there are unsaved changes.
16124 Be sure you know what you are doing before letting this function
16125 overwrite your changes.
16127 This function is useful in a setup where one tracks org files
16128 with a version control system, to revert on one machine after pulling
16129 changes from another. I believe the procedure must be like this:
16131 1. M-x org-save-all-org-buffers
16132 2. Pull changes from the other machine, resolve conflicts
16133 3. M-x org-revert-all-org-buffers"
16134 (interactive)
16135 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
16136 (error "Abort"))
16137 (save-excursion
16138 (save-window-excursion
16139 (mapc
16140 (lambda (b)
16141 (when (and (with-current-buffer b (eq major-mode 'org-mode))
16142 (with-current-buffer b buffer-file-name))
16143 (org-pop-to-buffer-same-window b)
16144 (revert-buffer t 'no-confirm)))
16145 (buffer-list))
16146 (when (and (featurep 'org-id) org-id-track-globally)
16147 (org-id-locations-load)))))
16149 ;;;; Agenda files
16151 ;;;###autoload
16152 (defun org-switchb (&optional arg)
16153 "Switch between Org buffers.
16154 With one prefix argument, restrict available buffers to files.
16155 With two prefix arguments, restrict available buffers to agenda files.
16157 Defaults to `iswitchb' for buffer name completion.
16158 Set `org-completion-use-ido' to make it use ido instead."
16159 (interactive "P")
16160 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
16161 ((equal arg '(16)) (org-buffer-list 'agenda))
16162 (t (org-buffer-list))))
16163 (org-completion-use-iswitchb org-completion-use-iswitchb)
16164 (org-completion-use-ido org-completion-use-ido))
16165 (unless (or org-completion-use-ido org-completion-use-iswitchb)
16166 (setq org-completion-use-iswitchb t))
16167 (org-pop-to-buffer-same-window
16168 (org-icompleting-read "Org buffer: "
16169 (mapcar 'list (mapcar 'buffer-name blist))
16170 nil t))))
16172 ;;; Define some older names previously used for this functionality
16173 ;;;###autoload
16174 (defalias 'org-ido-switchb 'org-switchb)
16175 ;;;###autoload
16176 (defalias 'org-iswitchb 'org-switchb)
16178 (defun org-buffer-list (&optional predicate exclude-tmp)
16179 "Return a list of Org buffers.
16180 PREDICATE can be `export', `files' or `agenda'.
16182 export restrict the list to Export buffers.
16183 files restrict the list to buffers visiting Org files.
16184 agenda restrict the list to buffers visiting agenda files.
16186 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
16187 (let* ((bfn nil)
16188 (agenda-files (and (eq predicate 'agenda)
16189 (mapcar 'file-truename (org-agenda-files t))))
16190 (filter
16191 (cond
16192 ((eq predicate 'files)
16193 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
16194 ((eq predicate 'export)
16195 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
16196 ((eq predicate 'agenda)
16197 (lambda (b)
16198 (with-current-buffer b
16199 (and (eq major-mode 'org-mode)
16200 (setq bfn (buffer-file-name b))
16201 (member (file-truename bfn) agenda-files)))))
16202 (t (lambda (b) (with-current-buffer b
16203 (or (eq major-mode 'org-mode)
16204 (string-match "\*Org .*Export"
16205 (buffer-name b)))))))))
16206 (delq nil
16207 (mapcar
16208 (lambda(b)
16209 (if (and (funcall filter b)
16210 (or (not exclude-tmp)
16211 (not (string-match "tmp" (buffer-name b)))))
16213 nil))
16214 (buffer-list)))))
16216 (defun org-agenda-files (&optional unrestricted archives)
16217 "Get the list of agenda files.
16218 Optional UNRESTRICTED means return the full list even if a restriction
16219 is currently in place.
16220 When ARCHIVES is t, include all archive files that are really being
16221 used by the agenda files. If ARCHIVE is `ifmode', do this only if
16222 `org-agenda-archives-mode' is t."
16223 (let ((files
16224 (cond
16225 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
16226 ((stringp org-agenda-files) (org-read-agenda-file-list))
16227 ((listp org-agenda-files) org-agenda-files)
16228 (t (error "Invalid value of `org-agenda-files'")))))
16229 (setq files (apply 'append
16230 (mapcar (lambda (f)
16231 (if (file-directory-p f)
16232 (directory-files
16233 f t org-agenda-file-regexp)
16234 (list f)))
16235 files)))
16236 (when org-agenda-skip-unavailable-files
16237 (setq files (delq nil
16238 (mapcar (function
16239 (lambda (file)
16240 (and (file-readable-p file) file)))
16241 files))))
16242 (when (or (eq archives t)
16243 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
16244 (setq files (org-add-archive-files files)))
16245 files))
16247 (defun org-agenda-file-p (&optional file)
16248 "Return non-nil, if FILE is an agenda file.
16249 If FILE is omitted, use the file associated with the current
16250 buffer."
16251 (member (or file (buffer-file-name))
16252 (org-agenda-files t)))
16254 (defun org-edit-agenda-file-list ()
16255 "Edit the list of agenda files.
16256 Depending on setup, this either uses customize to edit the variable
16257 `org-agenda-files', or it visits the file that is holding the list. In the
16258 latter case, the buffer is set up in a way that saving it automatically kills
16259 the buffer and restores the previous window configuration."
16260 (interactive)
16261 (if (stringp org-agenda-files)
16262 (let ((cw (current-window-configuration)))
16263 (find-file org-agenda-files)
16264 (org-set-local 'org-window-configuration cw)
16265 (org-add-hook 'after-save-hook
16266 (lambda ()
16267 (set-window-configuration
16268 (prog1 org-window-configuration
16269 (kill-buffer (current-buffer))))
16270 (org-install-agenda-files-menu)
16271 (message "New agenda file list installed"))
16272 nil 'local)
16273 (message "%s" (substitute-command-keys
16274 "Edit list and finish with \\[save-buffer]")))
16275 (customize-variable 'org-agenda-files)))
16277 (defun org-store-new-agenda-file-list (list)
16278 "Set new value for the agenda file list and save it correctly."
16279 (if (stringp org-agenda-files)
16280 (let ((fe (org-read-agenda-file-list t)) b u)
16281 (while (setq b (find-buffer-visiting org-agenda-files))
16282 (kill-buffer b))
16283 (with-temp-file org-agenda-files
16284 (insert
16285 (mapconcat
16286 (lambda (f) ;; Keep un-expanded entries.
16287 (if (setq u (assoc f fe))
16288 (cdr u)
16290 list "\n")
16291 "\n")))
16292 (let ((org-mode-hook nil) (org-inhibit-startup t)
16293 (org-insert-mode-line-in-empty-file nil))
16294 (setq org-agenda-files list)
16295 (customize-save-variable 'org-agenda-files org-agenda-files))))
16297 (defun org-read-agenda-file-list (&optional pair-with-expansion)
16298 "Read the list of agenda files from a file.
16299 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
16300 filenames, used by `org-store-new-agenda-file-list' to write back
16301 un-expanded file names."
16302 (when (file-directory-p org-agenda-files)
16303 (error "`org-agenda-files' cannot be a single directory"))
16304 (when (stringp org-agenda-files)
16305 (with-temp-buffer
16306 (insert-file-contents org-agenda-files)
16307 (mapcar
16308 (lambda (f)
16309 (let ((e (expand-file-name (substitute-in-file-name f)
16310 org-directory)))
16311 (if pair-with-expansion
16312 (cons e f)
16313 e)))
16314 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
16316 ;;;###autoload
16317 (defun org-cycle-agenda-files ()
16318 "Cycle through the files in `org-agenda-files'.
16319 If the current buffer visits an agenda file, find the next one in the list.
16320 If the current buffer does not, find the first agenda file."
16321 (interactive)
16322 (let* ((fs (org-agenda-files t))
16323 (files (append fs (list (car fs))))
16324 (tcf (if buffer-file-name (file-truename buffer-file-name)))
16325 file)
16326 (unless files (error "No agenda files"))
16327 (catch 'exit
16328 (while (setq file (pop files))
16329 (if (equal (file-truename file) tcf)
16330 (when (car files)
16331 (find-file (car files))
16332 (throw 'exit t))))
16333 (find-file (car fs)))
16334 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
16336 (defun org-agenda-file-to-front (&optional to-end)
16337 "Move/add the current file to the top of the agenda file list.
16338 If the file is not present in the list, it is added to the front. If it is
16339 present, it is moved there. With optional argument TO-END, add/move to the
16340 end of the list."
16341 (interactive "P")
16342 (let ((org-agenda-skip-unavailable-files nil)
16343 (file-alist (mapcar (lambda (x)
16344 (cons (file-truename x) x))
16345 (org-agenda-files t)))
16346 (ctf (file-truename buffer-file-name))
16347 x had)
16348 (setq x (assoc ctf file-alist) had x)
16350 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
16351 (if to-end
16352 (setq file-alist (append (delq x file-alist) (list x)))
16353 (setq file-alist (cons x (delq x file-alist))))
16354 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
16355 (org-install-agenda-files-menu)
16356 (message "File %s to %s of agenda file list"
16357 (if had "moved" "added") (if to-end "end" "front"))))
16359 (defun org-remove-file (&optional file)
16360 "Remove current file from the list of files in variable `org-agenda-files'.
16361 These are the files which are being checked for agenda entries.
16362 Optional argument FILE means use this file instead of the current."
16363 (interactive)
16364 (let* ((org-agenda-skip-unavailable-files nil)
16365 (file (or file buffer-file-name))
16366 (true-file (file-truename file))
16367 (afile (abbreviate-file-name file))
16368 (files (delq nil (mapcar
16369 (lambda (x)
16370 (if (equal true-file
16371 (file-truename x))
16372 nil x))
16373 (org-agenda-files t)))))
16374 (if (not (= (length files) (length (org-agenda-files t))))
16375 (progn
16376 (org-store-new-agenda-file-list files)
16377 (org-install-agenda-files-menu)
16378 (message "Removed file: %s" afile))
16379 (message "File was not in list: %s (not removed)" afile))))
16381 (defun org-file-menu-entry (file)
16382 (vector file (list 'find-file file) t))
16384 (defun org-check-agenda-file (file)
16385 "Make sure FILE exists. If not, ask user what to do."
16386 (when (not (file-exists-p file))
16387 (message "non-existent agenda file %s. [R]emove from list or [A]bort?"
16388 (abbreviate-file-name file))
16389 (let ((r (downcase (read-char-exclusive))))
16390 (cond
16391 ((equal r ?r)
16392 (org-remove-file file)
16393 (throw 'nextfile t))
16394 (t (error "Abort"))))))
16396 (defun org-get-agenda-file-buffer (file)
16397 "Get a buffer visiting FILE. If the buffer needs to be created, add
16398 it to the list of buffers which might be released later."
16399 (let ((buf (org-find-base-buffer-visiting file)))
16400 (if buf
16401 buf ; just return it
16402 ;; Make a new buffer and remember it
16403 (setq buf (find-file-noselect file))
16404 (if buf (push buf org-agenda-new-buffers))
16405 buf)))
16407 (defun org-release-buffers (blist)
16408 "Release all buffers in list, asking the user for confirmation when needed.
16409 When a buffer is unmodified, it is just killed. When modified, it is saved
16410 \(if the user agrees) and then killed."
16411 (let (buf file)
16412 (while (setq buf (pop blist))
16413 (setq file (buffer-file-name buf))
16414 (when (and (buffer-modified-p buf)
16415 file
16416 (y-or-n-p (format "Save file %s? " file)))
16417 (with-current-buffer buf (save-buffer)))
16418 (kill-buffer buf))))
16420 (defun org-prepare-agenda-buffers (files)
16421 "Create buffers for all agenda files, protect archived trees and comments."
16422 (interactive)
16423 (let ((pa '(:org-archived t))
16424 (pc '(:org-comment t))
16425 (pall '(:org-archived t :org-comment t))
16426 (inhibit-read-only t)
16427 (rea (concat ":" org-archive-tag ":"))
16428 bmp file re)
16429 (save-excursion
16430 (save-restriction
16431 (while (setq file (pop files))
16432 (catch 'nextfile
16433 (if (bufferp file)
16434 (set-buffer file)
16435 (org-check-agenda-file file)
16436 (set-buffer (org-get-agenda-file-buffer file)))
16437 (widen)
16438 (setq bmp (buffer-modified-p))
16439 (org-refresh-category-properties)
16440 (setq org-todo-keywords-for-agenda
16441 (append org-todo-keywords-for-agenda org-todo-keywords-1))
16442 (setq org-done-keywords-for-agenda
16443 (append org-done-keywords-for-agenda org-done-keywords))
16444 (setq org-todo-keyword-alist-for-agenda
16445 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
16446 (setq org-drawers-for-agenda
16447 (append org-drawers-for-agenda org-drawers))
16448 (setq org-tag-alist-for-agenda
16449 (append org-tag-alist-for-agenda org-tag-alist))
16451 (save-excursion
16452 (remove-text-properties (point-min) (point-max) pall)
16453 (when org-agenda-skip-archived-trees
16454 (goto-char (point-min))
16455 (while (re-search-forward rea nil t)
16456 (if (org-on-heading-p t)
16457 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
16458 (goto-char (point-min))
16459 (setq re (format org-heading-keyword-regexp-format
16460 org-comment-string))
16461 (while (re-search-forward re nil t)
16462 (add-text-properties
16463 (match-beginning 0) (org-end-of-subtree t) pc)))
16464 (set-buffer-modified-p bmp)))))
16465 (setq org-todo-keywords-for-agenda
16466 (org-uniquify org-todo-keywords-for-agenda))
16467 (setq org-todo-keyword-alist-for-agenda
16468 (org-uniquify org-todo-keyword-alist-for-agenda)
16469 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
16471 ;;;; Embedded LaTeX
16473 (defvar org-cdlatex-mode-map (make-sparse-keymap)
16474 "Keymap for the minor `org-cdlatex-mode'.")
16476 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
16477 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
16478 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
16479 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
16480 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
16482 (defvar org-cdlatex-texmathp-advice-is-done nil
16483 "Flag remembering if we have applied the advice to texmathp already.")
16485 (define-minor-mode org-cdlatex-mode
16486 "Toggle the minor `org-cdlatex-mode'.
16487 This mode supports entering LaTeX environment and math in LaTeX fragments
16488 in Org-mode.
16489 \\{org-cdlatex-mode-map}"
16490 nil " OCDL" nil
16491 (when org-cdlatex-mode
16492 (require 'cdlatex)
16493 (run-hooks 'cdlatex-mode-hook)
16494 (cdlatex-compute-tables))
16495 (unless org-cdlatex-texmathp-advice-is-done
16496 (setq org-cdlatex-texmathp-advice-is-done t)
16497 (defadvice texmathp (around org-math-always-on activate)
16498 "Always return t in org-mode buffers.
16499 This is because we want to insert math symbols without dollars even outside
16500 the LaTeX math segments. If Orgmode thinks that point is actually inside
16501 an embedded LaTeX fragment, let texmathp do its job.
16502 \\[org-cdlatex-mode-map]"
16503 (interactive)
16504 (let (p)
16505 (cond
16506 ((not (eq major-mode 'org-mode)) ad-do-it)
16507 ((eq this-command 'cdlatex-math-symbol)
16508 (setq ad-return-value t
16509 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
16511 (let ((p (org-inside-LaTeX-fragment-p)))
16512 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
16513 (setq ad-return-value t
16514 texmathp-why '("Org-mode embedded math" . 0))
16515 (if p ad-do-it)))))))))
16517 (defun turn-on-org-cdlatex ()
16518 "Unconditionally turn on `org-cdlatex-mode'."
16519 (org-cdlatex-mode 1))
16521 (defun org-inside-LaTeX-fragment-p ()
16522 "Test if point is inside a LaTeX fragment.
16523 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
16524 sequence appearing also before point.
16525 Even though the matchers for math are configurable, this function assumes
16526 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
16527 delimiters are skipped when they have been removed by customization.
16528 The return value is nil, or a cons cell with the delimiter and the
16529 position of this delimiter.
16531 This function does a reasonably good job, but can locally be fooled by
16532 for example currency specifications. For example it will assume being in
16533 inline math after \"$22.34\". The LaTeX fragment formatter will only format
16534 fragments that are properly closed, but during editing, we have to live
16535 with the uncertainty caused by missing closing delimiters. This function
16536 looks only before point, not after."
16537 (catch 'exit
16538 (let ((pos (point))
16539 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
16540 (lim (progn
16541 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
16542 (point)))
16543 dd-on str (start 0) m re)
16544 (goto-char pos)
16545 (when dodollar
16546 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
16547 re (nth 1 (assoc "$" org-latex-regexps)))
16548 (while (string-match re str start)
16549 (cond
16550 ((= (match-end 0) (length str))
16551 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
16552 ((= (match-end 0) (- (length str) 5))
16553 (throw 'exit nil))
16554 (t (setq start (match-end 0))))))
16555 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
16556 (goto-char pos)
16557 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
16558 (and (match-beginning 2) (throw 'exit nil))
16559 ;; count $$
16560 (while (re-search-backward "\\$\\$" lim t)
16561 (setq dd-on (not dd-on)))
16562 (goto-char pos)
16563 (if dd-on (cons "$$" m))))))
16565 (defun org-inside-latex-macro-p ()
16566 "Is point inside a LaTeX macro or its arguments?"
16567 (save-match-data
16568 (org-in-regexp
16569 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
16571 (defun org-try-cdlatex-tab ()
16572 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
16573 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
16574 - inside a LaTeX fragment, or
16575 - after the first word in a line, where an abbreviation expansion could
16576 insert a LaTeX environment."
16577 (when org-cdlatex-mode
16578 (cond
16579 ;; Before any word on the line: No expansion possible.
16580 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
16581 ;; Just after first word on the line: Expand it. Make sure it
16582 ;; cannot happen on headlines, though.
16583 ((save-excursion
16584 (skip-chars-backward "a-zA-Z0-9*")
16585 (skip-chars-backward " \t")
16586 (and (bolp) (not (org-at-heading-p))))
16587 (cdlatex-tab) t)
16588 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
16590 (defun org-cdlatex-underscore-caret (&optional arg)
16591 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
16592 Revert to the normal definition outside of these fragments."
16593 (interactive "P")
16594 (if (org-inside-LaTeX-fragment-p)
16595 (call-interactively 'cdlatex-sub-superscript)
16596 (let (org-cdlatex-mode)
16597 (call-interactively (key-binding (vector last-input-event))))))
16599 (defun org-cdlatex-math-modify (&optional arg)
16600 "Execute `cdlatex-math-modify' in LaTeX fragments.
16601 Revert to the normal definition outside of these fragments."
16602 (interactive "P")
16603 (if (org-inside-LaTeX-fragment-p)
16604 (call-interactively 'cdlatex-math-modify)
16605 (let (org-cdlatex-mode)
16606 (call-interactively (key-binding (vector last-input-event))))))
16608 (defvar org-latex-fragment-image-overlays nil
16609 "List of overlays carrying the images of latex fragments.")
16610 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
16612 (defun org-remove-latex-fragment-image-overlays ()
16613 "Remove all overlays with LaTeX fragment images in current buffer."
16614 (mapc 'delete-overlay org-latex-fragment-image-overlays)
16615 (setq org-latex-fragment-image-overlays nil))
16617 (defun org-preview-latex-fragment (&optional subtree)
16618 "Preview the LaTeX fragment at point, or all locally or globally.
16619 If the cursor is in a LaTeX fragment, create the image and overlay
16620 it over the source code. If there is no fragment at point, display
16621 all fragments in the current text, from one headline to the next. With
16622 prefix SUBTREE, display all fragments in the current subtree. With a
16623 double prefix arg \\[universal-argument] \\[universal-argument], or when \
16624 the cursor is before the first headline,
16625 display all fragments in the buffer.
16626 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
16627 (interactive "P")
16628 (org-remove-latex-fragment-image-overlays)
16629 (save-excursion
16630 (save-restriction
16631 (let (beg end at msg)
16632 (cond
16633 ((or (equal subtree '(16))
16634 (not (save-excursion
16635 (re-search-backward org-outline-regexp-bol nil t))))
16636 (setq beg (point-min) end (point-max)
16637 msg "Creating images for buffer...%s"))
16638 ((equal subtree '(4))
16639 (org-back-to-heading)
16640 (setq beg (point) end (org-end-of-subtree t)
16641 msg "Creating images for subtree...%s"))
16643 (if (setq at (org-inside-LaTeX-fragment-p))
16644 (goto-char (max (point-min) (- (cdr at) 2)))
16645 (org-back-to-heading))
16646 (setq beg (point) end (progn (outline-next-heading) (point))
16647 msg (if at "Creating image...%s"
16648 "Creating images for entry...%s"))))
16649 (message msg "")
16650 (narrow-to-region beg end)
16651 (goto-char beg)
16652 (org-format-latex
16653 (concat "ltxpng/" (file-name-sans-extension
16654 (file-name-nondirectory
16655 buffer-file-name)))
16656 default-directory 'overlays msg at 'forbuffer 'dvipng)
16657 (message msg "done. Use `C-c C-c' to remove images.")))))
16659 (defvar org-latex-regexps
16660 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
16661 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
16662 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
16663 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
16664 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
16665 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
16666 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
16667 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
16668 "Regular expressions for matching embedded LaTeX.")
16670 (defvar org-export-have-math nil) ;; dynamic scoping
16671 (defun org-format-latex (prefix &optional dir overlays msg at
16672 forbuffer processing-type)
16673 "Replace LaTeX fragments with links to an image, and produce images.
16674 Some of the options can be changed using the variable
16675 `org-format-latex-options'."
16676 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
16677 (let* ((prefixnodir (file-name-nondirectory prefix))
16678 (absprefix (expand-file-name prefix dir))
16679 (todir (file-name-directory absprefix))
16680 (opt org-format-latex-options)
16681 (matchers (plist-get opt :matchers))
16682 (re-list org-latex-regexps)
16683 (org-format-latex-header-extra
16684 (plist-get (org-infile-export-plist) :latex-header-extra))
16685 (cnt 0) txt hash link beg end re e checkdir
16686 executables-checked string
16687 m n block-type block linkfile movefile ov)
16688 ;; Check the different regular expressions
16689 (while (setq e (pop re-list))
16690 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
16691 block (if block-type "\n\n" ""))
16692 (when (member m matchers)
16693 (goto-char (point-min))
16694 (while (re-search-forward re nil t)
16695 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
16696 (not (get-text-property (match-beginning n)
16697 'org-protected))
16698 (or (not overlays)
16699 (not (eq (get-char-property (match-beginning n)
16700 'org-overlay-type)
16701 'org-latex-overlay))))
16702 (setq org-export-have-math t)
16703 (cond
16704 ((eq processing-type 'verbatim)
16705 ;; Leave the text verbatim, just protect it
16706 (add-text-properties (match-beginning n) (match-end n)
16707 '(org-protected t)))
16708 ((eq processing-type 'mathjax)
16709 ;; Prepare for MathJax processing
16710 (setq string (match-string n))
16711 (if (member m '("$" "$1"))
16712 (save-excursion
16713 (delete-region (match-beginning n) (match-end n))
16714 (goto-char (match-beginning n))
16715 (insert (org-add-props (concat "\\(" (substring string 1 -1)
16716 "\\)")
16717 '(org-protected t))))
16718 (add-text-properties (match-beginning n) (match-end n)
16719 '(org-protected t))))
16720 ((eq processing-type 'dvipng)
16721 ;; Process to an image
16722 (setq txt (match-string n)
16723 beg (match-beginning n) end (match-end n)
16724 cnt (1+ cnt))
16725 (let (print-length print-level) ; make sure full list is printed
16726 (setq hash (sha1 (prin1-to-string
16727 (list org-format-latex-header
16728 org-format-latex-header-extra
16729 org-export-latex-default-packages-alist
16730 org-export-latex-packages-alist
16731 org-format-latex-options
16732 forbuffer txt)))
16733 linkfile (format "%s_%s.png" prefix hash)
16734 movefile (format "%s_%s.png" absprefix hash)))
16735 (setq link (concat block "[[file:" linkfile "]]" block))
16736 (if msg (message msg cnt))
16737 (goto-char beg)
16738 (unless checkdir ; make sure the directory exists
16739 (setq checkdir t)
16740 (or (file-directory-p todir) (make-directory todir t)))
16742 (unless executables-checked
16743 (org-check-external-command
16744 "latex" "needed to convert LaTeX fragments to images")
16745 (org-check-external-command
16746 "dvipng" "needed to convert LaTeX fragments to images")
16747 (setq executables-checked t))
16749 (unless (file-exists-p movefile)
16750 (org-create-formula-image
16751 txt movefile opt forbuffer))
16752 (if overlays
16753 (progn
16754 (mapc (lambda (o)
16755 (if (eq (overlay-get o 'org-overlay-type)
16756 'org-latex-overlay)
16757 (delete-overlay o)))
16758 (overlays-in beg end))
16759 (setq ov (make-overlay beg end))
16760 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
16761 (if (featurep 'xemacs)
16762 (progn
16763 (overlay-put ov 'invisible t)
16764 (overlay-put
16765 ov 'end-glyph
16766 (make-glyph (vector 'png :file movefile))))
16767 (overlay-put
16768 ov 'display
16769 (list 'image :type 'png :file movefile :ascent 'center)))
16770 (push ov org-latex-fragment-image-overlays)
16771 (goto-char end))
16772 (delete-region beg end)
16773 (insert (org-add-props link
16774 (list 'org-latex-src
16775 (replace-regexp-in-string
16776 "\"" "" txt)
16777 'org-latex-src-embed-type
16778 (if block-type 'paragraph 'character))))))
16779 ((eq processing-type 'mathml)
16780 ;; Process to MathML
16781 (unless executables-checked
16782 (unless (save-match-data (org-format-latex-mathml-available-p))
16783 (error "LaTeX to MathML converter not configured"))
16784 (setq executables-checked t))
16785 (setq txt (match-string n)
16786 beg (match-beginning n) end (match-end n)
16787 cnt (1+ cnt))
16788 (if msg (message msg cnt))
16789 (goto-char beg)
16790 (delete-region beg end)
16791 (insert (org-format-latex-as-mathml
16792 txt block-type prefix dir)))
16794 (error "Unknown conversion type %s for latex fragments"
16795 processing-type)))))))))
16797 (defun org-create-math-formula (latex-frag &optional mathml-file)
16798 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
16799 Use `org-latex-to-mathml-convert-command'. If the conversion is
16800 sucessful, return the portion between \"<math...> </math>\"
16801 elements otherwise return nil. When MATHML-FILE is specified,
16802 write the results in to that file. When invoked as an
16803 interactive command, prompt for LATEX-FRAG, with initial value
16804 set to the current active region and echo the results for user
16805 inspection."
16806 (interactive (list (let ((frag (when (region-active-p)
16807 (buffer-substring-no-properties
16808 (region-beginning) (region-end)))))
16809 (read-string "LaTeX Fragment: " frag nil frag))))
16810 (unless latex-frag (error "Invalid latex-frag"))
16811 (let* ((tmp-in-file (file-relative-name
16812 (make-temp-name (expand-file-name "ltxmathml-in"))))
16813 (ignore (write-region latex-frag nil tmp-in-file))
16814 (tmp-out-file (file-relative-name
16815 (make-temp-name (expand-file-name "ltxmathml-out"))))
16816 (cmd (format-spec
16817 org-latex-to-mathml-convert-command
16818 `((?j . ,(shell-quote-argument
16819 (expand-file-name org-latex-to-mathml-jar-file)))
16820 (?I . ,(shell-quote-argument tmp-in-file))
16821 (?o . ,(shell-quote-argument tmp-out-file)))))
16822 mathml shell-command-output)
16823 (when (org-called-interactively-p 'any)
16824 (unless (org-format-latex-mathml-available-p)
16825 (error "LaTeX to MathML converter not configured")))
16826 (message "Running %s" cmd)
16827 (setq shell-command-output (shell-command-to-string cmd))
16828 (setq mathml
16829 (when (file-readable-p tmp-out-file)
16830 (with-current-buffer (find-file-noselect tmp-out-file t)
16831 (goto-char (point-min))
16832 (when (re-search-forward
16833 (concat
16834 (regexp-quote
16835 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
16836 "\\(.\\|\n\\)*"
16837 (regexp-quote "</math>")) nil t)
16838 (prog1 (match-string 0) (kill-buffer))))))
16839 (cond
16840 (mathml
16841 (setq mathml
16842 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
16843 (when mathml-file
16844 (write-region mathml nil mathml-file))
16845 (when (org-called-interactively-p 'any)
16846 (message mathml)))
16847 ((message "LaTeX to MathML conversion failed")
16848 (message shell-command-output)))
16849 (delete-file tmp-in-file)
16850 (when (file-exists-p tmp-out-file)
16851 (delete-file tmp-out-file))
16852 mathml))
16854 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
16855 prefix &optional dir)
16856 "Use `org-create-math-formula' but check local cache first."
16857 (let* ((absprefix (expand-file-name prefix dir))
16858 (print-length nil) (print-level nil)
16859 (formula-id (concat
16860 "formula-"
16861 (sha1
16862 (prin1-to-string
16863 (list latex-frag
16864 org-latex-to-mathml-convert-command)))))
16865 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
16866 (formula-cache-dir (file-name-directory formula-cache)))
16868 (unless (file-directory-p formula-cache-dir)
16869 (make-directory formula-cache-dir t))
16871 (unless (file-exists-p formula-cache)
16872 (org-create-math-formula latex-frag formula-cache))
16874 (if (file-exists-p formula-cache)
16875 ;; Successful conversion. Return the link to MathML file.
16876 (org-add-props
16877 (format "[[file:%s]]" (file-relative-name formula-cache dir))
16878 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
16879 'org-latex-src-embed-type (if latex-frag-type
16880 'paragraph 'character)))
16881 ;; Failed conversion. Return the LaTeX fragment verbatim
16882 (add-text-properties
16883 0 (1- (length latex-frag)) '(org-protected t) latex-frag)
16884 latex-frag)))
16886 ;; This function borrows from Ganesh Swami's latex2png.el
16887 (defun org-create-formula-image (string tofile options buffer)
16888 "This calls dvipng."
16889 (require 'org-latex)
16890 (let* ((tmpdir (if (featurep 'xemacs)
16891 (temp-directory)
16892 temporary-file-directory))
16893 (texfilebase (make-temp-name
16894 (expand-file-name "orgtex" tmpdir)))
16895 (texfile (concat texfilebase ".tex"))
16896 (dvifile (concat texfilebase ".dvi"))
16897 (pngfile (concat texfilebase ".png"))
16898 (fnh (if (featurep 'xemacs)
16899 (font-height (get-face-font 'default))
16900 (face-attribute 'default :height nil)))
16901 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
16902 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
16903 (fg (or (plist-get options (if buffer :foreground :html-foreground))
16904 "Black"))
16905 (bg (or (plist-get options (if buffer :background :html-background))
16906 "Transparent")))
16907 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
16908 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
16909 (with-temp-file texfile
16910 (insert (org-splice-latex-header
16911 org-format-latex-header
16912 org-export-latex-default-packages-alist
16913 org-export-latex-packages-alist t
16914 org-format-latex-header-extra))
16915 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")
16916 (require 'org-latex)
16917 (org-export-latex-fix-inputenc))
16918 (let ((dir default-directory))
16919 (condition-case nil
16920 (progn
16921 (cd tmpdir)
16922 (call-process "latex" nil nil nil texfile))
16923 (error nil))
16924 (cd dir))
16925 (if (not (file-exists-p dvifile))
16926 (progn (message "Failed to create dvi file from %s" texfile) nil)
16927 (condition-case nil
16928 (call-process "dvipng" nil nil nil
16929 "-fg" fg "-bg" bg
16930 "-D" dpi
16931 ;;"-x" scale "-y" scale
16932 "-T" "tight"
16933 "-o" pngfile
16934 dvifile)
16935 (error nil))
16936 (if (not (file-exists-p pngfile))
16937 (if org-format-latex-signal-error
16938 (error "Failed to create png file from %s" texfile)
16939 (message "Failed to create png file from %s" texfile)
16940 nil)
16941 ;; Use the requested file name and clean up
16942 (copy-file pngfile tofile 'replace)
16943 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
16944 (delete-file (concat texfilebase e)))
16945 pngfile))))
16947 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
16948 "Fill a LaTeX header template TPL.
16949 In the template, the following place holders will be recognized:
16951 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
16952 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
16953 [PACKAGES] \\usepackage statements for PKG
16954 [NO-PACKAGES] do not include PKG
16955 [EXTRA] the string EXTRA
16956 [NO-EXTRA] do not include EXTRA
16958 For backward compatibility, if both the positive and the negative place
16959 holder is missing, the positive one (without the \"NO-\") will be
16960 assumed to be present at the end of the template.
16961 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
16962 EXTRA is a string.
16963 SNIPPETS-P indicates if this is run to create snippet images for HTML."
16964 (let (rpl (end ""))
16965 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
16966 (setq rpl (if (or (match-end 1) (not def-pkg))
16967 "" (org-latex-packages-to-string def-pkg snippets-p t))
16968 tpl (replace-match rpl t t tpl))
16969 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
16971 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
16972 (setq rpl (if (or (match-end 1) (not pkg))
16973 "" (org-latex-packages-to-string pkg snippets-p t))
16974 tpl (replace-match rpl t t tpl))
16975 (if pkg (setq end
16976 (concat end "\n"
16977 (org-latex-packages-to-string pkg snippets-p)))))
16979 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
16980 (setq rpl (if (or (match-end 1) (not extra))
16981 "" (concat extra "\n"))
16982 tpl (replace-match rpl t t tpl))
16983 (if (and extra (string-match "\\S-" extra))
16984 (setq end (concat end "\n" extra))))
16986 (if (string-match "\\S-" end)
16987 (concat tpl "\n" end)
16988 tpl)))
16990 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
16991 "Turn an alist of packages into a string with the \\usepackage macros."
16992 (setq pkg (mapconcat (lambda(p)
16993 (cond
16994 ((stringp p) p)
16995 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
16996 (format "%% Package %s omitted" (cadr p)))
16997 ((equal "" (car p))
16998 (format "\\usepackage{%s}" (cadr p)))
17000 (format "\\usepackage[%s]{%s}"
17001 (car p) (cadr p)))))
17003 "\n"))
17004 (if newline (concat pkg "\n") pkg))
17006 (defun org-dvipng-color (attr)
17007 "Return an rgb color specification for dvipng."
17008 (apply 'format "rgb %s %s %s"
17009 (mapcar 'org-normalize-color
17010 (color-values (face-attribute 'default attr nil)))))
17012 (defun org-normalize-color (value)
17013 "Return string to be used as color value for an RGB component."
17014 (format "%g" (/ value 65535.0)))
17016 ;; Image display
17019 (defvar org-inline-image-overlays nil)
17020 (make-variable-buffer-local 'org-inline-image-overlays)
17022 (defun org-toggle-inline-images (&optional include-linked)
17023 "Toggle the display of inline images.
17024 INCLUDE-LINKED is passed to `org-display-inline-images'."
17025 (interactive "P")
17026 (if org-inline-image-overlays
17027 (progn
17028 (org-remove-inline-images)
17029 (message "Inline image display turned off"))
17030 (org-display-inline-images include-linked)
17031 (if org-inline-image-overlays
17032 (message "%d images displayed inline"
17033 (length org-inline-image-overlays))
17034 (message "No images to display inline"))))
17036 (defun org-display-inline-images (&optional include-linked refresh beg end)
17037 "Display inline images.
17038 Normally only links without a description part are inlined, because this
17039 is how it will work for export. When INCLUDE-LINKED is set, also links
17040 with a description part will be inlined. This can be nice for a quick
17041 look at those images, but it does not reflect what exported files will look
17042 like.
17043 When REFRESH is set, refresh existing images between BEG and END.
17044 This will create new image displays only if necessary.
17045 BEG and END default to the buffer boundaries."
17046 (interactive "P")
17047 (unless refresh
17048 (org-remove-inline-images)
17049 (if (fboundp 'clear-image-cache) (clear-image-cache)))
17050 (save-excursion
17051 (save-restriction
17052 (widen)
17053 (setq beg (or beg (point-min)) end (or end (point-max)))
17054 (goto-char (point-min))
17055 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
17056 (substring (org-image-file-name-regexp) 0 -2)
17057 "\\)\\]" (if include-linked "" "\\]")))
17058 old file ov img)
17059 (while (re-search-forward re end t)
17060 (setq old (get-char-property-and-overlay (match-beginning 1)
17061 'org-image-overlay))
17062 (setq file (expand-file-name
17063 (concat (or (match-string 3) "") (match-string 4))))
17064 (when (file-exists-p file)
17065 (if (and (car-safe old) refresh)
17066 (image-refresh (overlay-get (cdr old) 'display))
17067 (setq img (save-match-data (create-image file)))
17068 (when img
17069 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
17070 (overlay-put ov 'display img)
17071 (overlay-put ov 'face 'default)
17072 (overlay-put ov 'org-image-overlay t)
17073 (overlay-put ov 'modification-hooks
17074 (list 'org-display-inline-modification-hook))
17075 (push ov org-inline-image-overlays)))))))))
17077 (defun org-display-inline-modification-hook (ov after beg end &optional len)
17078 "Remove inline-display overlay if a corresponding region is modified."
17079 (let ((inhibit-modification-hooks t))
17080 (when (and ov after)
17081 (delete ov org-inline-image-overlays)
17082 (delete-overlay ov))))
17084 (defun org-remove-inline-images ()
17085 "Remove inline display of images."
17086 (interactive)
17087 (mapc 'delete-overlay org-inline-image-overlays)
17088 (setq org-inline-image-overlays nil))
17090 ;;;; Key bindings
17092 ;; Remap outline keys
17093 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
17094 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
17096 ;; Make `C-c C-x' a prefix key
17097 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
17099 ;; TAB key with modifiers
17100 (org-defkey org-mode-map "\C-i" 'org-cycle)
17101 (org-defkey org-mode-map [(tab)] 'org-cycle)
17102 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
17103 (org-defkey org-mode-map [(meta tab)] 'pcomplete)
17104 (org-defkey org-mode-map "\M-\t" 'pcomplete)
17105 (org-defkey org-mode-map "\M-\C-i" 'pcomplete)
17106 ;; The following line is necessary under Suse GNU/Linux
17107 (unless (featurep 'xemacs)
17108 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
17109 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
17110 (define-key org-mode-map [backtab] 'org-shifttab)
17112 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
17113 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
17114 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
17116 ;; Cursor keys with modifiers
17117 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
17118 (org-defkey org-mode-map [(meta right)] 'org-metaright)
17119 (org-defkey org-mode-map [(meta up)] 'org-metaup)
17120 (org-defkey org-mode-map [(meta down)] 'org-metadown)
17122 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
17123 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
17124 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
17125 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
17127 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
17128 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
17129 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
17130 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
17132 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
17133 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
17134 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
17135 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
17137 ;; Babel keys
17138 (define-key org-mode-map org-babel-key-prefix org-babel-map)
17139 (mapc (lambda (pair)
17140 (define-key org-babel-map (car pair) (cdr pair)))
17141 org-babel-key-bindings)
17143 ;;; Extra keys for tty access.
17144 ;; We only set them when really needed because otherwise the
17145 ;; menus don't show the simple keys
17147 (when (or org-use-extra-keys
17148 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
17149 (not window-system))
17150 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
17151 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
17152 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
17153 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
17154 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
17155 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
17156 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
17157 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
17158 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
17159 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
17160 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
17161 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
17162 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
17163 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
17164 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
17165 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
17166 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
17167 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
17168 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
17169 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
17170 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
17171 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
17172 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
17173 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
17174 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
17175 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
17176 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
17177 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
17179 ;; All the other keys
17181 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
17182 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
17183 (if (boundp 'narrow-map)
17184 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
17185 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
17186 (if (boundp 'narrow-map)
17187 (org-defkey narrow-map "b" 'org-narrow-to-block)
17188 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
17189 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-same-level)
17190 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-same-level)
17191 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
17192 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
17193 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
17194 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
17195 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
17196 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
17197 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
17198 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
17199 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
17200 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
17201 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
17202 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
17203 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
17204 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
17205 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
17206 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
17207 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
17208 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
17209 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
17210 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
17211 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
17212 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
17213 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
17214 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
17215 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
17216 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
17217 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
17218 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
17219 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
17220 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
17221 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
17222 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
17223 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
17224 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
17225 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
17226 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
17227 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
17228 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
17229 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
17230 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
17231 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
17232 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
17233 (org-defkey org-mode-map "\C-c^" 'org-sort)
17234 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
17235 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
17236 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
17237 (org-defkey org-mode-map "\C-m" 'org-return)
17238 (org-defkey org-mode-map "\C-j" 'org-return-indent)
17239 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
17240 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
17241 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
17242 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
17243 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
17244 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
17245 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
17246 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
17247 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
17248 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
17249 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
17250 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
17251 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
17252 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
17253 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
17254 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
17255 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
17256 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
17257 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
17258 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
17259 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
17261 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
17262 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
17263 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
17264 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
17266 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
17267 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
17268 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
17269 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
17270 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
17271 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
17272 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
17273 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
17274 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
17275 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
17276 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
17277 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
17278 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
17279 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
17280 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
17281 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
17282 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
17283 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
17285 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
17286 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
17287 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
17288 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
17289 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
17291 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
17293 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
17295 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
17296 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
17298 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
17301 (when (featurep 'xemacs)
17302 (org-defkey org-mode-map 'button3 'popup-mode-menu))
17305 (defconst org-speed-commands-default
17307 ("Outline Navigation")
17308 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
17309 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
17310 ("f" . (org-speed-move-safe 'org-forward-same-level))
17311 ("b" . (org-speed-move-safe 'org-backward-same-level))
17312 ("u" . (org-speed-move-safe 'outline-up-heading))
17313 ("j" . org-goto)
17314 ("g" . (org-refile t))
17315 ("Outline Visibility")
17316 ("c" . org-cycle)
17317 ("C" . org-shifttab)
17318 (" " . org-display-outline-path)
17319 ("Outline Structure Editing")
17320 ("U" . org-shiftmetaup)
17321 ("D" . org-shiftmetadown)
17322 ("r" . org-metaright)
17323 ("l" . org-metaleft)
17324 ("R" . org-shiftmetaright)
17325 ("L" . org-shiftmetaleft)
17326 ("i" . (progn (forward-char 1) (call-interactively
17327 'org-insert-heading-respect-content)))
17328 ("^" . org-sort)
17329 ("w" . org-refile)
17330 ("a" . org-archive-subtree-default-with-confirmation)
17331 ("." . org-mark-subtree)
17332 ("Clock Commands")
17333 ("I" . org-clock-in)
17334 ("O" . org-clock-out)
17335 ("Meta Data Editing")
17336 ("t" . org-todo)
17337 ("0" . (org-priority ?\ ))
17338 ("1" . (org-priority ?A))
17339 ("2" . (org-priority ?B))
17340 ("3" . (org-priority ?C))
17341 (";" . org-set-tags-command)
17342 ("e" . org-set-effort)
17343 ("Agenda Views etc")
17344 ("v" . org-agenda)
17345 ("/" . org-sparse-tree)
17346 ("Misc")
17347 ("o" . org-open-at-point)
17348 ("?" . org-speed-command-help)
17349 ("<" . (org-agenda-set-restriction-lock 'subtree))
17350 (">" . (org-agenda-remove-restriction-lock))
17352 "The default speed commands.")
17354 (defun org-print-speed-command (e)
17355 (if (> (length (car e)) 1)
17356 (progn
17357 (princ "\n")
17358 (princ (car e))
17359 (princ "\n")
17360 (princ (make-string (length (car e)) ?-))
17361 (princ "\n"))
17362 (princ (car e))
17363 (princ " ")
17364 (if (symbolp (cdr e))
17365 (princ (symbol-name (cdr e)))
17366 (prin1 (cdr e)))
17367 (princ "\n")))
17369 (defun org-speed-command-help ()
17370 "Show the available speed commands."
17371 (interactive)
17372 (if (not org-use-speed-commands)
17373 (error "Speed commands are not activated, customize `org-use-speed-commands'")
17374 (with-output-to-temp-buffer "*Help*"
17375 (princ "User-defined Speed commands\n===========================\n")
17376 (mapc 'org-print-speed-command org-speed-commands-user)
17377 (princ "\n")
17378 (princ "Built-in Speed commands\n=======================\n")
17379 (mapc 'org-print-speed-command org-speed-commands-default))
17380 (with-current-buffer "*Help*"
17381 (setq truncate-lines t))))
17383 (defun org-speed-move-safe (cmd)
17384 "Execute CMD, but make sure that the cursor always ends up in a headline.
17385 If not, return to the original position and throw an error."
17386 (interactive)
17387 (let ((pos (point)))
17388 (call-interactively cmd)
17389 (unless (and (bolp) (org-on-heading-p))
17390 (goto-char pos)
17391 (error "Boundary reached while executing %s" cmd))))
17393 (defvar org-self-insert-command-undo-counter 0)
17395 (defvar org-table-auto-blank-field) ; defined in org-table.el
17396 (defvar org-speed-command nil)
17398 (defun org-speed-command-default-hook (keys)
17399 "Hook for activating single-letter speed commands.
17400 `org-speed-commands-default' specifies a minimal command set.
17401 Use `org-speed-commands-user' for further customization."
17402 (when (or (and (bolp) (looking-at org-outline-regexp))
17403 (and (functionp org-use-speed-commands)
17404 (funcall org-use-speed-commands)))
17405 (cdr (assoc keys (append org-speed-commands-user
17406 org-speed-commands-default)))))
17408 (defun org-babel-speed-command-hook (keys)
17409 "Hook for activating single-letter code block commands."
17410 (when (and (bolp) (looking-at org-babel-src-block-regexp))
17411 (cdr (assoc keys org-babel-key-bindings))))
17413 (defcustom org-speed-command-hook
17414 '(org-speed-command-default-hook org-babel-speed-command-hook)
17415 "Hook for activating speed commands at strategic locations.
17416 Hook functions are called in sequence until a valid handler is
17417 found.
17419 Each hook takes a single argument, a user-pressed command key
17420 which is also a `self-insert-command' from the global map.
17422 Within the hook, examine the cursor position and the command key
17423 and return nil or a valid handler as appropriate. Handler could
17424 be one of an interactive command, a function, or a form.
17426 Set `org-use-speed-commands' to non-nil value to enable this
17427 hook. The default setting is `org-speed-command-default-hook'."
17428 :group 'org-structure
17429 :type 'hook)
17431 (defun org-self-insert-command (N)
17432 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
17433 If the cursor is in a table looking at whitespace, the whitespace is
17434 overwritten, and the table is not marked as requiring realignment."
17435 (interactive "p")
17436 (org-check-before-invisible-edit 'insert)
17437 (cond
17438 ((and org-use-speed-commands
17439 (setq org-speed-command
17440 (run-hook-with-args-until-success
17441 'org-speed-command-hook (this-command-keys))))
17442 (cond
17443 ((commandp org-speed-command)
17444 (setq this-command org-speed-command)
17445 (call-interactively org-speed-command))
17446 ((functionp org-speed-command)
17447 (funcall org-speed-command))
17448 ((and org-speed-command (listp org-speed-command))
17449 (eval org-speed-command))
17450 (t (let (org-use-speed-commands)
17451 (call-interactively 'org-self-insert-command)))))
17452 ((and
17453 (org-table-p)
17454 (progn
17455 ;; check if we blank the field, and if that triggers align
17456 (and (featurep 'org-table) org-table-auto-blank-field
17457 (member last-command
17458 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
17459 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
17460 ;; got extra space, this field does not determine column width
17461 (let (org-table-may-need-update) (org-table-blank-field))
17462 ;; no extra space, this field may determine column width
17463 (org-table-blank-field)))
17465 (eq N 1)
17466 (looking-at "[^|\n]* |"))
17467 (let (org-table-may-need-update)
17468 (goto-char (1- (match-end 0)))
17469 (delete-char -1)
17470 (goto-char (match-beginning 0))
17471 (self-insert-command N)))
17473 (setq org-table-may-need-update t)
17474 (self-insert-command N)
17475 (org-fix-tags-on-the-fly)
17476 (if org-self-insert-cluster-for-undo
17477 (if (not (eq last-command 'org-self-insert-command))
17478 (setq org-self-insert-command-undo-counter 1)
17479 (if (>= org-self-insert-command-undo-counter 20)
17480 (setq org-self-insert-command-undo-counter 1)
17481 (and (> org-self-insert-command-undo-counter 0)
17482 buffer-undo-list (listp buffer-undo-list)
17483 (not (cadr buffer-undo-list)) ; remove nil entry
17484 (setcdr buffer-undo-list (cddr buffer-undo-list)))
17485 (setq org-self-insert-command-undo-counter
17486 (1+ org-self-insert-command-undo-counter))))))))
17488 (defun org-check-before-invisible-edit (kind)
17489 "Check is editing if kind KIND would be dangerous with invisible text around.
17490 The detailed reaction depends on the user option `org-catch-invisible-edits'."
17491 ;; First, try to get out of here as quickly as possible, to reduce overhead
17492 (if (and org-catch-invisible-edits
17493 (or (not (boundp 'visible-mode)) (not visible-mode))
17494 (or (get-char-property (point) 'invisible)
17495 (get-char-property (max (point-min) (1- (point))) 'invisible)))
17496 ;; OK, we need to take a closer look
17497 (let* ((invisible-at-point (get-char-property (point) 'invisible))
17498 (invisible-before-point (if (bobp) nil (get-char-property
17499 (1- (point)) 'invisible)))
17500 (border-and-ok-direction
17502 ;; Check if we are acting predictably before invisible text
17503 (and invisible-at-point (not invisible-before-point)
17504 (memq kind '(insert delete-backward)))
17505 ;; Check if we are acting predictably after invisible text
17506 ;; This works not well, and I have turned it off. It seems
17507 ;; better to always show and stop after invisible text.
17508 ;; (and (not invisible-at-point) invisible-before-point
17509 ;; (memq kind '(insert delete)))
17512 (when (or (memq invisible-at-point '(outline org-hide-block))
17513 (memq invisible-before-point '(outline org-hide-block)))
17514 (if (eq org-catch-invisible-edits 'error)
17515 (error "Editing in invisible areas is prohibited - make visible first"))
17516 ;; Make the area visible
17517 (save-excursion
17518 (if invisible-before-point
17519 (goto-char (previous-single-char-property-change
17520 (point) 'invisible)))
17521 (org-cycle))
17522 (cond
17523 ((eq org-catch-invisible-edits 'show)
17524 ;; That's it, we do the edit after showing
17525 (message
17526 "Unfolding invisible region around point before editing")
17527 (sit-for 1))
17528 ((and (eq org-catch-invisible-edits 'smart)
17529 border-and-ok-direction)
17530 (message "Unfolding invisible region around point before editing"))
17532 ;; Don't do the edit, make the user repeat it in full visibility
17533 (error "Edit in invisible region aborted, repeat to confirm with text visible")))))))
17535 (defun org-fix-tags-on-the-fly ()
17536 (when (and (equal (char-after (point-at-bol)) ?*)
17537 (org-on-heading-p))
17538 (org-align-tags-here org-tags-column)))
17540 (defun org-delete-backward-char (N)
17541 "Like `delete-backward-char', insert whitespace at field end in tables.
17542 When deleting backwards, in tables this function will insert whitespace in
17543 front of the next \"|\" separator, to keep the table aligned. The table will
17544 still be marked for re-alignment if the field did fill the entire column,
17545 because, in this case the deletion might narrow the column."
17546 (interactive "p")
17547 (org-check-before-invisible-edit 'delete-backward)
17548 (if (and (org-table-p)
17549 (eq N 1)
17550 (string-match "|" (buffer-substring (point-at-bol) (point)))
17551 (looking-at ".*?|"))
17552 (let ((pos (point))
17553 (noalign (looking-at "[^|\n\r]* |"))
17554 (c org-table-may-need-update))
17555 (backward-delete-char N)
17556 (if (not overwrite-mode)
17557 (progn
17558 (skip-chars-forward "^|")
17559 (insert " ")
17560 (goto-char (1- pos))))
17561 ;; noalign: if there were two spaces at the end, this field
17562 ;; does not determine the width of the column.
17563 (if noalign (setq org-table-may-need-update c)))
17564 (backward-delete-char N)
17565 (org-fix-tags-on-the-fly)))
17567 (defun org-delete-char (N)
17568 "Like `delete-char', but insert whitespace at field end in tables.
17569 When deleting characters, in tables this function will insert whitespace in
17570 front of the next \"|\" separator, to keep the table aligned. The table will
17571 still be marked for re-alignment if the field did fill the entire column,
17572 because, in this case the deletion might narrow the column."
17573 (interactive "p")
17574 (org-check-before-invisible-edit 'delete)
17575 (if (and (org-table-p)
17576 (not (bolp))
17577 (not (= (char-after) ?|))
17578 (eq N 1))
17579 (if (looking-at ".*?|")
17580 (let ((pos (point))
17581 (noalign (looking-at "[^|\n\r]* |"))
17582 (c org-table-may-need-update))
17583 (replace-match (concat
17584 (substring (match-string 0) 1 -1)
17585 " |"))
17586 (goto-char pos)
17587 ;; noalign: if there were two spaces at the end, this field
17588 ;; does not determine the width of the column.
17589 (if noalign (setq org-table-may-need-update c)))
17590 (delete-char N))
17591 (delete-char N)
17592 (org-fix-tags-on-the-fly)))
17594 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
17595 (put 'org-self-insert-command 'delete-selection t)
17596 (put 'orgtbl-self-insert-command 'delete-selection t)
17597 (put 'org-delete-char 'delete-selection 'supersede)
17598 (put 'org-delete-backward-char 'delete-selection 'supersede)
17599 (put 'org-yank 'delete-selection 'yank)
17601 ;; Make `flyspell-mode' delay after some commands
17602 (put 'org-self-insert-command 'flyspell-delayed t)
17603 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
17604 (put 'org-delete-char 'flyspell-delayed t)
17605 (put 'org-delete-backward-char 'flyspell-delayed t)
17607 ;; Make pabbrev-mode expand after org-mode commands
17608 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
17609 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
17611 ;; How to do this: Measure non-white length of current string
17612 ;; If equal to column width, we should realign.
17614 (defun org-remap (map &rest commands)
17615 "In MAP, remap the functions given in COMMANDS.
17616 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
17617 (let (new old)
17618 (while commands
17619 (setq old (pop commands) new (pop commands))
17620 (if (fboundp 'command-remapping)
17621 (org-defkey map (vector 'remap old) new)
17622 (substitute-key-definition old new map global-map)))))
17624 (when (eq org-enable-table-editor 'optimized)
17625 ;; If the user wants maximum table support, we need to hijack
17626 ;; some standard editing functions
17627 (org-remap org-mode-map
17628 'self-insert-command 'org-self-insert-command
17629 'delete-char 'org-delete-char
17630 'delete-backward-char 'org-delete-backward-char)
17631 (org-defkey org-mode-map "|" 'org-force-self-insert))
17633 (defvar org-ctrl-c-ctrl-c-hook nil
17634 "Hook for functions attaching themselves to `C-c C-c'.
17636 This can be used to add additional functionality to the C-c C-c
17637 key which executes context-dependent commands. This hook is run
17638 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
17639 run after the last test.
17641 Each function will be called with no arguments. The function
17642 must check if the context is appropriate for it to act. If yes,
17643 it should do its thing and then return a non-nil value. If the
17644 context is wrong, just do nothing and return nil.")
17646 (defvar org-ctrl-c-ctrl-c-final-hook nil
17647 "Hook for functions attaching themselves to `C-c C-c'.
17649 This can be used to add additional functionality to the C-c C-c
17650 key which executes context-dependent commands. This hook is run
17651 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
17652 before the first test.
17654 Each function will be called with no arguments. The function
17655 must check if the context is appropriate for it to act. If yes,
17656 it should do its thing and then return a non-nil value. If the
17657 context is wrong, just do nothing and return nil.")
17659 (defvar org-tab-first-hook nil
17660 "Hook for functions to attach themselves to TAB.
17661 See `org-ctrl-c-ctrl-c-hook' for more information.
17662 This hook runs as the first action when TAB is pressed, even before
17663 `org-cycle' messes around with the `outline-regexp' to cater for
17664 inline tasks and plain list item folding.
17665 If any function in this hook returns t, any other actions that
17666 would have been caused by TAB (such as table field motion or visibility
17667 cycling) will not occur.")
17669 (defvar org-tab-after-check-for-table-hook nil
17670 "Hook for functions to attach themselves to TAB.
17671 See `org-ctrl-c-ctrl-c-hook' for more information.
17672 This hook runs after it has been established that the cursor is not in a
17673 table, but before checking if the cursor is in a headline or if global cycling
17674 should be done.
17675 If any function in this hook returns t, not other actions like visibility
17676 cycling will be done.")
17678 (defvar org-tab-after-check-for-cycling-hook nil
17679 "Hook for functions to attach themselves to TAB.
17680 See `org-ctrl-c-ctrl-c-hook' for more information.
17681 This hook runs after it has been established that not table field motion and
17682 not visibility should be done because of current context. This is probably
17683 the place where a package like yasnippets can hook in.")
17685 (defvar org-tab-before-tab-emulation-hook nil
17686 "Hook for functions to attach themselves to TAB.
17687 See `org-ctrl-c-ctrl-c-hook' for more information.
17688 This hook runs after every other options for TAB have been exhausted, but
17689 before indentation and \t insertion takes place.")
17691 (defvar org-metaleft-hook nil
17692 "Hook for functions attaching themselves to `M-left'.
17693 See `org-ctrl-c-ctrl-c-hook' for more information.")
17694 (defvar org-metaright-hook nil
17695 "Hook for functions attaching themselves to `M-right'.
17696 See `org-ctrl-c-ctrl-c-hook' for more information.")
17697 (defvar org-metaup-hook nil
17698 "Hook for functions attaching themselves to `M-up'.
17699 See `org-ctrl-c-ctrl-c-hook' for more information.")
17700 (defvar org-metadown-hook nil
17701 "Hook for functions attaching themselves to `M-down'.
17702 See `org-ctrl-c-ctrl-c-hook' for more information.")
17703 (defvar org-shiftmetaleft-hook nil
17704 "Hook for functions attaching themselves to `M-S-left'.
17705 See `org-ctrl-c-ctrl-c-hook' for more information.")
17706 (defvar org-shiftmetaright-hook nil
17707 "Hook for functions attaching themselves to `M-S-right'.
17708 See `org-ctrl-c-ctrl-c-hook' for more information.")
17709 (defvar org-shiftmetaup-hook nil
17710 "Hook for functions attaching themselves to `M-S-up'.
17711 See `org-ctrl-c-ctrl-c-hook' for more information.")
17712 (defvar org-shiftmetadown-hook nil
17713 "Hook for functions attaching themselves to `M-S-down'.
17714 See `org-ctrl-c-ctrl-c-hook' for more information.")
17715 (defvar org-metareturn-hook nil
17716 "Hook for functions attaching themselves to `M-RET'.
17717 See `org-ctrl-c-ctrl-c-hook' for more information.")
17718 (defvar org-shiftup-hook nil
17719 "Hook for functions attaching themselves to `S-up'.
17720 See `org-ctrl-c-ctrl-c-hook' for more information.")
17721 (defvar org-shiftup-final-hook nil
17722 "Hook for functions attaching themselves to `S-up'.
17723 This one runs after all other options except shift-select have been excluded.
17724 See `org-ctrl-c-ctrl-c-hook' for more information.")
17725 (defvar org-shiftdown-hook nil
17726 "Hook for functions attaching themselves to `S-down'.
17727 See `org-ctrl-c-ctrl-c-hook' for more information.")
17728 (defvar org-shiftdown-final-hook nil
17729 "Hook for functions attaching themselves to `S-down'.
17730 This one runs after all other options except shift-select have been excluded.
17731 See `org-ctrl-c-ctrl-c-hook' for more information.")
17732 (defvar org-shiftleft-hook nil
17733 "Hook for functions attaching themselves to `S-left'.
17734 See `org-ctrl-c-ctrl-c-hook' for more information.")
17735 (defvar org-shiftleft-final-hook nil
17736 "Hook for functions attaching themselves to `S-left'.
17737 This one runs after all other options except shift-select have been excluded.
17738 See `org-ctrl-c-ctrl-c-hook' for more information.")
17739 (defvar org-shiftright-hook nil
17740 "Hook for functions attaching themselves to `S-right'.
17741 See `org-ctrl-c-ctrl-c-hook' for more information.")
17742 (defvar org-shiftright-final-hook nil
17743 "Hook for functions attaching themselves to `S-right'.
17744 This one runs after all other options except shift-select have been excluded.
17745 See `org-ctrl-c-ctrl-c-hook' for more information.")
17747 (defun org-modifier-cursor-error ()
17748 "Throw an error, a modified cursor command was applied in wrong context."
17749 (error "This command is active in special context like tables, headlines or items"))
17751 (defun org-shiftselect-error ()
17752 "Throw an error because Shift-Cursor command was applied in wrong context."
17753 (if (and (boundp 'shift-select-mode) shift-select-mode)
17754 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
17755 (error "This command works only in special context like headlines or timestamps")))
17757 (defun org-call-for-shift-select (cmd)
17758 (let ((this-command-keys-shift-translated t))
17759 (call-interactively cmd)))
17761 (defun org-shifttab (&optional arg)
17762 "Global visibility cycling or move to previous table field.
17763 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
17764 on context.
17765 See the individual commands for more information."
17766 (interactive "P")
17767 (cond
17768 ((org-at-table-p) (call-interactively 'org-table-previous-field))
17769 ((integerp arg)
17770 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
17771 (message "Content view to level: %d" arg)
17772 (org-content (prefix-numeric-value arg2))
17773 (setq org-cycle-global-status 'overview)))
17774 (t (call-interactively 'org-global-cycle))))
17776 (defun org-shiftmetaleft ()
17777 "Promote subtree or delete table column.
17778 Calls `org-promote-subtree', `org-outdent-item',
17779 or `org-table-delete-column', depending on context.
17780 See the individual commands for more information."
17781 (interactive)
17782 (cond
17783 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
17784 ((org-at-table-p) (call-interactively 'org-table-delete-column))
17785 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
17786 ((org-at-item-p) (call-interactively 'org-outdent-item-tree))
17787 (t (org-modifier-cursor-error))))
17789 (defun org-shiftmetaright ()
17790 "Demote subtree or insert table column.
17791 Calls `org-demote-subtree', `org-indent-item',
17792 or `org-table-insert-column', depending on context.
17793 See the individual commands for more information."
17794 (interactive)
17795 (cond
17796 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
17797 ((org-at-table-p) (call-interactively 'org-table-insert-column))
17798 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
17799 ((org-at-item-p) (call-interactively 'org-indent-item-tree))
17800 (t (org-modifier-cursor-error))))
17802 (defun org-shiftmetaup (&optional arg)
17803 "Move subtree up or kill table row.
17804 Calls `org-move-subtree-up' or `org-table-kill-row' or
17805 `org-move-item-up' depending on context. See the individual commands
17806 for more information."
17807 (interactive "P")
17808 (cond
17809 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
17810 ((org-at-table-p) (call-interactively 'org-table-kill-row))
17811 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
17812 ((org-at-item-p) (call-interactively 'org-move-item-up))
17813 (t (org-modifier-cursor-error))))
17815 (defun org-shiftmetadown (&optional arg)
17816 "Move subtree down or insert table row.
17817 Calls `org-move-subtree-down' or `org-table-insert-row' or
17818 `org-move-item-down', depending on context. See the individual
17819 commands for more information."
17820 (interactive "P")
17821 (cond
17822 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
17823 ((org-at-table-p) (call-interactively 'org-table-insert-row))
17824 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
17825 ((org-at-item-p) (call-interactively 'org-move-item-down))
17826 (t (org-modifier-cursor-error))))
17828 (defsubst org-hidden-tree-error ()
17829 (error
17830 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
17832 (defun org-metaleft (&optional arg)
17833 "Promote heading or move table column to left.
17834 Calls `org-do-promote' or `org-table-move-column', depending on context.
17835 With no specific context, calls the Emacs default `backward-word'.
17836 See the individual commands for more information."
17837 (interactive "P")
17838 (cond
17839 ((run-hook-with-args-until-success 'org-metaleft-hook))
17840 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
17841 ((org-with-limited-levels
17842 (or (org-on-heading-p)
17843 (and (org-region-active-p)
17844 (save-excursion
17845 (goto-char (region-beginning))
17846 (org-on-heading-p)))))
17847 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
17848 (call-interactively 'org-do-promote))
17849 ;; At an inline task.
17850 ((org-on-heading-p)
17851 (call-interactively 'org-inlinetask-promote))
17852 ((or (org-at-item-p)
17853 (and (org-region-active-p)
17854 (save-excursion
17855 (goto-char (region-beginning))
17856 (org-at-item-p))))
17857 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
17858 (call-interactively 'org-outdent-item))
17859 (t (call-interactively 'backward-word))))
17861 (defun org-metaright (&optional arg)
17862 "Demote subtree or move table column to right.
17863 Calls `org-do-demote' or `org-table-move-column', depending on context.
17864 With no specific context, calls the Emacs default `forward-word'.
17865 See the individual commands for more information."
17866 (interactive "P")
17867 (cond
17868 ((run-hook-with-args-until-success 'org-metaright-hook))
17869 ((org-at-table-p) (call-interactively 'org-table-move-column))
17870 ((org-with-limited-levels
17871 (or (org-on-heading-p)
17872 (and (org-region-active-p)
17873 (save-excursion
17874 (goto-char (region-beginning))
17875 (org-on-heading-p)))))
17876 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
17877 (call-interactively 'org-do-demote))
17878 ;; At an inline task.
17879 ((org-on-heading-p)
17880 (call-interactively 'org-inlinetask-demote))
17881 ((or (org-at-item-p)
17882 (and (org-region-active-p)
17883 (save-excursion
17884 (goto-char (region-beginning))
17885 (org-at-item-p))))
17886 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
17887 (call-interactively 'org-indent-item))
17888 (t (call-interactively 'forward-word))))
17890 (defun org-check-for-hidden (what)
17891 "Check if there are hidden headlines/items in the current visual line.
17892 WHAT can be either `headlines' or `items'. If the current line is
17893 an outline or item heading and it has a folded subtree below it,
17894 this function returns t, nil otherwise."
17895 (let ((re (cond
17896 ((eq what 'headlines) org-outline-regexp-bol)
17897 ((eq what 'items) (org-item-beginning-re))
17898 (t (error "This should not happen"))))
17899 beg end)
17900 (save-excursion
17901 (catch 'exit
17902 (unless (org-region-active-p)
17903 (setq beg (point-at-bol))
17904 (beginning-of-line 2)
17905 (while (and (not (eobp)) ;; this is like `next-line'
17906 (get-char-property (1- (point)) 'invisible))
17907 (beginning-of-line 2))
17908 (setq end (point))
17909 (goto-char beg)
17910 (goto-char (point-at-eol))
17911 (setq end (max end (point)))
17912 (while (re-search-forward re end t)
17913 (if (get-char-property (match-beginning 0) 'invisible)
17914 (throw 'exit t))))
17915 nil))))
17917 (defun org-metaup (&optional arg)
17918 "Move subtree up or move table row up.
17919 Calls `org-move-subtree-up' or `org-table-move-row' or
17920 `org-move-item-up', depending on context. See the individual commands
17921 for more information."
17922 (interactive "P")
17923 (cond
17924 ((run-hook-with-args-until-success 'org-metaup-hook))
17925 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
17926 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
17927 ((org-at-item-p) (call-interactively 'org-move-item-up))
17928 (t (transpose-lines 1) (beginning-of-line -1))))
17930 (defun org-metadown (&optional arg)
17931 "Move subtree down or move table row down.
17932 Calls `org-move-subtree-down' or `org-table-move-row' or
17933 `org-move-item-down', depending on context. See the individual
17934 commands for more information."
17935 (interactive "P")
17936 (cond
17937 ((run-hook-with-args-until-success 'org-metadown-hook))
17938 ((org-at-table-p) (call-interactively 'org-table-move-row))
17939 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
17940 ((org-at-item-p) (call-interactively 'org-move-item-down))
17941 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
17943 (defun org-shiftup (&optional arg)
17944 "Increase item in timestamp or increase priority of current headline.
17945 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
17946 depending on context. See the individual commands for more information."
17947 (interactive "P")
17948 (cond
17949 ((run-hook-with-args-until-success 'org-shiftup-hook))
17950 ((and org-support-shift-select (org-region-active-p))
17951 (org-call-for-shift-select 'previous-line))
17952 ((org-at-timestamp-p t)
17953 (call-interactively (if org-edit-timestamp-down-means-later
17954 'org-timestamp-down 'org-timestamp-up)))
17955 ((and (not (eq org-support-shift-select 'always))
17956 org-enable-priority-commands
17957 (org-on-heading-p))
17958 (call-interactively 'org-priority-up))
17959 ((and (not org-support-shift-select) (org-at-item-p))
17960 (call-interactively 'org-previous-item))
17961 ((org-clocktable-try-shift 'up arg))
17962 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
17963 (org-support-shift-select
17964 (org-call-for-shift-select 'previous-line))
17965 (t (org-shiftselect-error))))
17967 (defun org-shiftdown (&optional arg)
17968 "Decrease item in timestamp or decrease priority of current headline.
17969 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
17970 depending on context. See the individual commands for more information."
17971 (interactive "P")
17972 (cond
17973 ((run-hook-with-args-until-success 'org-shiftdown-hook))
17974 ((and org-support-shift-select (org-region-active-p))
17975 (org-call-for-shift-select 'next-line))
17976 ((org-at-timestamp-p t)
17977 (call-interactively (if org-edit-timestamp-down-means-later
17978 'org-timestamp-up 'org-timestamp-down)))
17979 ((and (not (eq org-support-shift-select 'always))
17980 org-enable-priority-commands
17981 (org-on-heading-p))
17982 (call-interactively 'org-priority-down))
17983 ((and (not org-support-shift-select) (org-at-item-p))
17984 (call-interactively 'org-next-item))
17985 ((org-clocktable-try-shift 'down arg))
17986 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
17987 (org-support-shift-select
17988 (org-call-for-shift-select 'next-line))
17989 (t (org-shiftselect-error))))
17991 (defun org-shiftright (&optional arg)
17992 "Cycle the thing at point or in the current line, depending on context.
17993 Depending on context, this does one of the following:
17995 - switch a timestamp at point one day into the future
17996 - on a headline, switch to the next TODO keyword.
17997 - on an item, switch entire list to the next bullet type
17998 - on a property line, switch to the next allowed value
17999 - on a clocktable definition line, move time block into the future"
18000 (interactive "P")
18001 (cond
18002 ((run-hook-with-args-until-success 'org-shiftright-hook))
18003 ((and org-support-shift-select (org-region-active-p))
18004 (org-call-for-shift-select 'forward-char))
18005 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
18006 ((and (not (eq org-support-shift-select 'always))
18007 (org-on-heading-p))
18008 (let ((org-inhibit-logging
18009 (not org-treat-S-cursor-todo-selection-as-state-change))
18010 (org-inhibit-blocking
18011 (not org-treat-S-cursor-todo-selection-as-state-change)))
18012 (org-call-with-arg 'org-todo 'right)))
18013 ((or (and org-support-shift-select
18014 (not (eq org-support-shift-select 'always))
18015 (org-at-item-bullet-p))
18016 (and (not org-support-shift-select) (org-at-item-p)))
18017 (org-call-with-arg 'org-cycle-list-bullet nil))
18018 ((and (not (eq org-support-shift-select 'always))
18019 (org-at-property-p))
18020 (call-interactively 'org-property-next-allowed-value))
18021 ((org-clocktable-try-shift 'right arg))
18022 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
18023 (org-support-shift-select
18024 (org-call-for-shift-select 'forward-char))
18025 (t (org-shiftselect-error))))
18027 (defun org-shiftleft (&optional arg)
18028 "Cycle the thing at point or in the current line, depending on context.
18029 Depending on context, this does one of the following:
18031 - switch a timestamp at point one day into the past
18032 - on a headline, switch to the previous TODO keyword.
18033 - on an item, switch entire list to the previous bullet type
18034 - on a property line, switch to the previous allowed value
18035 - on a clocktable definition line, move time block into the past"
18036 (interactive "P")
18037 (cond
18038 ((run-hook-with-args-until-success 'org-shiftleft-hook))
18039 ((and org-support-shift-select (org-region-active-p))
18040 (org-call-for-shift-select 'backward-char))
18041 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
18042 ((and (not (eq org-support-shift-select 'always))
18043 (org-on-heading-p))
18044 (let ((org-inhibit-logging
18045 (not org-treat-S-cursor-todo-selection-as-state-change))
18046 (org-inhibit-blocking
18047 (not org-treat-S-cursor-todo-selection-as-state-change)))
18048 (org-call-with-arg 'org-todo 'left)))
18049 ((or (and org-support-shift-select
18050 (not (eq org-support-shift-select 'always))
18051 (org-at-item-bullet-p))
18052 (and (not org-support-shift-select) (org-at-item-p)))
18053 (org-call-with-arg 'org-cycle-list-bullet 'previous))
18054 ((and (not (eq org-support-shift-select 'always))
18055 (org-at-property-p))
18056 (call-interactively 'org-property-previous-allowed-value))
18057 ((org-clocktable-try-shift 'left arg))
18058 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
18059 (org-support-shift-select
18060 (org-call-for-shift-select 'backward-char))
18061 (t (org-shiftselect-error))))
18063 (defun org-shiftcontrolright ()
18064 "Switch to next TODO set."
18065 (interactive)
18066 (cond
18067 ((and org-support-shift-select (org-region-active-p))
18068 (org-call-for-shift-select 'forward-word))
18069 ((and (not (eq org-support-shift-select 'always))
18070 (org-on-heading-p))
18071 (org-call-with-arg 'org-todo 'nextset))
18072 (org-support-shift-select
18073 (org-call-for-shift-select 'forward-word))
18074 (t (org-shiftselect-error))))
18076 (defun org-shiftcontrolleft ()
18077 "Switch to previous TODO set."
18078 (interactive)
18079 (cond
18080 ((and org-support-shift-select (org-region-active-p))
18081 (org-call-for-shift-select 'backward-word))
18082 ((and (not (eq org-support-shift-select 'always))
18083 (org-on-heading-p))
18084 (org-call-with-arg 'org-todo 'previousset))
18085 (org-support-shift-select
18086 (org-call-for-shift-select 'backward-word))
18087 (t (org-shiftselect-error))))
18089 (defun org-shiftcontrolup ()
18090 "Change timestamps synchronously up in CLOCK log lines."
18091 (interactive)
18092 (cond ((and (not org-support-shift-select)
18093 (org-at-clock-log-p)
18094 (org-at-timestamp-p t))
18095 (org-clock-timestamps-up))
18096 (t (org-shiftselect-error))))
18098 (defun org-shiftcontroldown ()
18099 "Change timestamps synchronously down in CLOCK log lines."
18100 (interactive)
18101 (cond ((and (not org-support-shift-select)
18102 (org-at-clock-log-p)
18103 (org-at-timestamp-p t))
18104 (org-clock-timestamps-down))
18105 (t (org-shiftselect-error))))
18107 (defun org-ctrl-c-ret ()
18108 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
18109 (interactive)
18110 (cond
18111 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
18112 (t (call-interactively 'org-insert-heading))))
18114 (defun org-find-visible ()
18115 (let ((s (point)))
18116 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
18117 (get-char-property s 'invisible)))
18119 (defun org-find-invisible ()
18120 (let ((s (point)))
18121 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
18122 (not (get-char-property s 'invisible))))
18125 (defun org-copy-visible (beg end)
18126 "Copy the visible parts of the region."
18127 (interactive "r")
18128 (let (snippets s)
18129 (save-excursion
18130 (save-restriction
18131 (narrow-to-region beg end)
18132 (setq s (goto-char (point-min)))
18133 (while (not (= (point) (point-max)))
18134 (goto-char (org-find-invisible))
18135 (push (buffer-substring s (point)) snippets)
18136 (setq s (goto-char (org-find-visible))))))
18137 (kill-new (apply 'concat (nreverse snippets)))))
18139 (defun org-copy-special ()
18140 "Copy region in table or copy current subtree.
18141 Calls `org-table-copy' or `org-copy-subtree', depending on context.
18142 See the individual commands for more information."
18143 (interactive)
18144 (call-interactively
18145 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
18147 (defun org-cut-special ()
18148 "Cut region in table or cut current subtree.
18149 Calls `org-table-copy' or `org-cut-subtree', depending on context.
18150 See the individual commands for more information."
18151 (interactive)
18152 (call-interactively
18153 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
18155 (defun org-paste-special (arg)
18156 "Paste rectangular region into table, or past subtree relative to level.
18157 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
18158 See the individual commands for more information."
18159 (interactive "P")
18160 (if (org-at-table-p)
18161 (org-table-paste-rectangle)
18162 (org-paste-subtree arg)))
18164 (defun org-edit-special (&optional arg)
18165 "Call a special editor for the stuff at point.
18166 When at a table, call the formula editor with `org-table-edit-formulas'.
18167 When at the first line of an src example, call `org-edit-src-code'.
18168 When in an #+include line, visit the include file. Otherwise call
18169 `ffap' to visit the file at point."
18170 (interactive)
18171 ;; possibly prep session before editing source
18172 (when arg
18173 (let* ((info (org-babel-get-src-block-info))
18174 (lang (nth 0 info))
18175 (params (nth 2 info))
18176 (session (cdr (assoc :session params))))
18177 (when (and info session) ;; we are in a source-code block with a session
18178 (funcall
18179 (intern (concat "org-babel-prep-session:" lang)) session params))))
18180 (cond ;; proceed with `org-edit-special'
18181 ((save-excursion
18182 (beginning-of-line 1)
18183 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
18184 (find-file (org-trim (match-string 1))))
18185 ((org-edit-src-code))
18186 ((org-edit-fixed-width-region))
18187 ((org-at-table.el-p)
18188 (org-edit-src-code))
18189 ((or (org-at-table-p)
18190 (save-excursion
18191 (beginning-of-line 1)
18192 (looking-at "[ \t]*#\\+TBLFM:")))
18193 (call-interactively 'org-table-edit-formulas))
18194 (t (call-interactively 'ffap))))
18196 (defvar org-table-coordinate-overlays) ; defined in org-table.el
18197 (defun org-ctrl-c-ctrl-c (&optional arg)
18198 "Set tags in headline, or update according to changed information at point.
18200 This command does many different things, depending on context:
18202 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
18203 this is what we do.
18205 - If the cursor is on a statistics cookie, update it.
18207 - If the cursor is in a headline, prompt for tags and insert them
18208 into the current line, aligned to `org-tags-column'. When called
18209 with prefix arg, realign all tags in the current buffer.
18211 - If the cursor is in one of the special #+KEYWORD lines, this
18212 triggers scanning the buffer for these lines and updating the
18213 information.
18215 - If the cursor is inside a table, realign the table. This command
18216 works even if the automatic table editor has been turned off.
18218 - If the cursor is on a #+TBLFM line, re-apply the formulas to
18219 the entire table.
18221 - If the cursor is at a footnote reference or definition, jump to
18222 the corresponding definition or references, respectively.
18224 - If the cursor is a the beginning of a dynamic block, update it.
18226 - If the current buffer is a capture buffer, close note and file it.
18228 - If the cursor is on a <<<target>>>, update radio targets and
18229 corresponding links in this buffer.
18231 - If the cursor is on a numbered item in a plain list, renumber the
18232 ordered list.
18234 - If the cursor is on a checkbox, toggle it.
18236 - If the cursor is on a code block, evaluate it. The variable
18237 `org-confirm-babel-evaluate' can be used to control prompting
18238 before code block evaluation, by default every code block
18239 evaluation requires confirmation. Code block evaluation can be
18240 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
18241 (interactive "P")
18242 (let ((org-enable-table-editor t))
18243 (cond
18244 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
18245 org-occur-highlights
18246 org-latex-fragment-image-overlays)
18247 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
18248 (org-remove-occur-highlights)
18249 (org-remove-latex-fragment-image-overlays)
18250 (message "Temporary highlights/overlays removed from current buffer"))
18251 ((and (local-variable-p 'org-finish-function (current-buffer))
18252 (fboundp org-finish-function))
18253 (funcall org-finish-function))
18254 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
18255 ((org-in-regexp org-ts-regexp-both)
18256 (org-timestamp-change 0 'day))
18257 ((or (looking-at org-property-start-re)
18258 (org-at-property-p))
18259 (call-interactively 'org-property-action))
18260 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
18261 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
18262 (or (org-on-heading-p) (org-at-item-p)))
18263 (call-interactively 'org-update-statistics-cookies))
18264 ((org-on-heading-p) (call-interactively 'org-set-tags))
18265 ((org-at-table.el-p)
18266 (message "Use C-c ' to edit table.el tables"))
18267 ((org-at-table-p)
18268 (org-table-maybe-eval-formula)
18269 (if arg
18270 (call-interactively 'org-table-recalculate)
18271 (org-table-maybe-recalculate-line))
18272 (call-interactively 'org-table-align)
18273 (orgtbl-send-table 'maybe))
18274 ((or (org-footnote-at-reference-p)
18275 (org-footnote-at-definition-p))
18276 (call-interactively 'org-footnote-action))
18277 ((org-at-item-checkbox-p)
18278 ;; Cursor at a checkbox: repair list and update checkboxes. Send
18279 ;; list only if at top item.
18280 (let* ((cbox (match-string 1))
18281 (struct (org-list-struct))
18282 (old-struct (copy-tree struct))
18283 (parents (org-list-parents-alist struct))
18284 (orderedp (org-entry-get nil "ORDERED"))
18285 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
18286 block-item)
18287 ;; Use a light version of `org-toggle-checkbox' to avoid
18288 ;; computing list structure twice.
18289 (org-list-set-checkbox (point-at-bol) struct
18290 (cond
18291 ((equal arg '(16)) "[-]")
18292 ((equal arg '(4)) nil)
18293 ((equal "[X]" cbox) "[ ]")
18294 (t "[X]")))
18295 ;; Replicate `org-list-write-struct', while grabbing a return
18296 ;; value from `org-list-struct-fix-box'.
18297 (org-list-struct-fix-ind struct parents 2)
18298 (org-list-struct-fix-item-end struct)
18299 (let ((prevs (org-list-prevs-alist struct)))
18300 (org-list-struct-fix-bul struct prevs)
18301 (org-list-struct-fix-ind struct parents)
18302 (setq block-item
18303 (org-list-struct-fix-box struct parents prevs orderedp)))
18304 (org-list-struct-apply-struct struct old-struct)
18305 (org-update-checkbox-count-maybe)
18306 (when block-item
18307 (message
18308 "Checkboxes were removed due to unchecked box at line %d"
18309 (org-current-line block-item)))
18310 (when firstp (org-list-send-list 'maybe))))
18311 ((org-at-item-p)
18312 ;; Cursor at an item: repair list. Do checkbox related actions
18313 ;; only if function was called with an argument. Send list only
18314 ;; if at top item.
18315 (let* ((struct (org-list-struct))
18316 (firstp (= (org-list-get-top-point struct) (point-at-bol))))
18317 (when arg (org-list-set-checkbox (point-at-bol) struct "[ ]"))
18318 (org-list-write-struct struct (org-list-parents-alist struct))
18319 (when arg (org-update-checkbox-count-maybe))
18320 (when firstp (org-list-send-list 'maybe))))
18321 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
18322 ;; Dynamic block
18323 (beginning-of-line 1)
18324 (save-excursion (org-update-dblock)))
18325 ((save-excursion
18326 (beginning-of-line 1)
18327 (looking-at "[ \t]*#\\+\\([A-Z]+\\)"))
18328 (cond
18329 ((equal (match-string 1) "TBLFM")
18330 ;; Recalculate the table before this line
18331 (save-excursion
18332 (beginning-of-line 1)
18333 (skip-chars-backward " \r\n\t")
18334 (if (org-at-table-p)
18335 (org-call-with-arg 'org-table-recalculate (or arg t)))))
18337 (let ((org-inhibit-startup-visibility-stuff t)
18338 (org-startup-align-all-tables nil))
18339 (when (boundp 'org-table-coordinate-overlays)
18340 (mapc 'delete-overlay org-table-coordinate-overlays)
18341 (setq org-table-coordinate-overlays nil))
18342 (org-save-outline-visibility 'use-markers (org-mode-restart)))
18343 (message "Local setup has been refreshed"))))
18344 ((org-clock-update-time-maybe))
18346 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
18347 (error "C-c C-c can do nothing useful at this location"))))))
18349 (defun org-mode-restart ()
18350 "Restart Org-mode, to scan again for special lines.
18351 Also updates the keyword regular expressions."
18352 (interactive)
18353 (org-mode)
18354 (message "Org-mode restarted"))
18356 (defun org-kill-note-or-show-branches ()
18357 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
18358 (interactive)
18359 (if (not org-finish-function)
18360 (progn
18361 (hide-subtree)
18362 (call-interactively 'show-branches))
18363 (let ((org-note-abort t))
18364 (funcall org-finish-function))))
18366 (defun org-return (&optional indent)
18367 "Goto next table row or insert a newline.
18368 Calls `org-table-next-row' or `newline', depending on context.
18369 See the individual commands for more information."
18370 (interactive)
18371 (cond
18372 ((bobp) (if indent (newline-and-indent) (newline)))
18373 ((org-at-table-p)
18374 (org-table-justify-field-maybe)
18375 (call-interactively 'org-table-next-row))
18376 ;; when `newline-and-indent' is called within a list, make sure
18377 ;; text moved stays inside the item.
18378 ((and (org-in-item-p) indent)
18379 (if (and (org-at-item-p) (>= (point) (match-end 0)))
18380 (progn
18381 (save-match-data (newline))
18382 (org-indent-line-to (length (match-string 0))))
18383 (let ((ind (org-get-indentation)))
18384 (newline)
18385 (if (org-looking-back org-list-end-re)
18386 (org-indent-line-function)
18387 (org-indent-line-to ind)))))
18388 ((and org-return-follows-link
18389 (let ((tprop (get-text-property (point) 'face)))
18390 (or (eq tprop 'org-link)
18391 (and (listp tprop) (memq 'org-link tprop)))))
18392 (call-interactively 'org-open-at-point))
18393 ((and (org-at-heading-p)
18394 (looking-at
18395 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
18396 (org-show-entry)
18397 (end-of-line 1)
18398 (newline))
18399 (t (if indent (newline-and-indent) (newline)))))
18401 (defun org-return-indent ()
18402 "Goto next table row or insert a newline and indent.
18403 Calls `org-table-next-row' or `newline-and-indent', depending on
18404 context. See the individual commands for more information."
18405 (interactive)
18406 (org-return t))
18408 (defun org-ctrl-c-star ()
18409 "Compute table, or change heading status of lines.
18410 Calls `org-table-recalculate' or `org-toggle-heading',
18411 depending on context."
18412 (interactive)
18413 (cond
18414 ((org-at-table-p)
18415 (call-interactively 'org-table-recalculate))
18417 ;; Convert all lines in region to list items
18418 (call-interactively 'org-toggle-heading))))
18420 (defun org-ctrl-c-minus ()
18421 "Insert separator line in table or modify bullet status of line.
18422 Also turns a plain line or a region of lines into list items.
18423 Calls `org-table-insert-hline', `org-toggle-item', or
18424 `org-cycle-list-bullet', depending on context."
18425 (interactive)
18426 (cond
18427 ((org-at-table-p)
18428 (call-interactively 'org-table-insert-hline))
18429 ((org-region-active-p)
18430 (call-interactively 'org-toggle-item))
18431 ((org-in-item-p)
18432 (call-interactively 'org-cycle-list-bullet))
18434 (call-interactively 'org-toggle-item))))
18436 (defun org-toggle-item (arg)
18437 "Convert headings or normal lines to items, items to normal lines.
18438 If there is no active region, only the current line is considered.
18440 If the first non blank line in the region is an headline, convert
18441 all headlines to items, shifting text accordingly.
18443 If it is an item, convert all items to normal lines.
18445 If it is normal text, change region into an item. With a prefix
18446 argument ARG, change each line in region into an item."
18447 (interactive "P")
18448 (let ((shift-text
18449 (function
18450 ;; Shift text in current section to IND, from point to END.
18451 ;; The function leaves point to END line.
18452 (lambda (ind end)
18453 (let ((min-i 1000) (end (copy-marker end)))
18454 ;; First determine the minimum indentation (MIN-I) of
18455 ;; the text.
18456 (save-excursion
18457 (catch 'exit
18458 (while (< (point) end)
18459 (let ((i (org-get-indentation)))
18460 (cond
18461 ;; Skip blank lines and inline tasks.
18462 ((looking-at "^[ \t]*$"))
18463 ((looking-at org-outline-regexp-bol))
18464 ;; We can't find less than 0 indentation.
18465 ((zerop i) (throw 'exit (setq min-i 0)))
18466 ((< i min-i) (setq min-i i))))
18467 (forward-line))))
18468 ;; Then indent each line so that a line indented to
18469 ;; MIN-I becomes indented to IND. Ignore blank lines
18470 ;; and inline tasks in the process.
18471 (let ((delta (- ind min-i)))
18472 (while (< (point) end)
18473 (unless (or (looking-at "^[ \t]*$")
18474 (looking-at org-outline-regexp-bol))
18475 (org-indent-line-to (+ (org-get-indentation) delta)))
18476 (forward-line)))))))
18477 (skip-blanks
18478 (function
18479 ;; Return beginning of first non-blank line, starting from
18480 ;; line at POS.
18481 (lambda (pos)
18482 (save-excursion
18483 (goto-char pos)
18484 (skip-chars-forward " \r\t\n")
18485 (point-at-bol)))))
18486 beg end)
18487 ;; Determine boundaries of changes.
18488 (if (org-region-active-p)
18489 (setq beg (funcall skip-blanks (region-beginning))
18490 end (copy-marker (region-end)))
18491 (setq beg (funcall skip-blanks (point-at-bol))
18492 end (copy-marker (point-at-eol))))
18493 ;; Depending on the starting line, choose an action on the text
18494 ;; between BEG and END.
18495 (org-with-limited-levels
18496 (save-excursion
18497 (goto-char beg)
18498 (cond
18499 ;; Case 1. Start at an item: de-itemize. Note that it only
18500 ;; happens when a region is active: `org-ctrl-c-minus'
18501 ;; would call `org-cycle-list-bullet' otherwise.
18502 ((org-at-item-p)
18503 (while (< (point) end)
18504 (when (org-at-item-p)
18505 (skip-chars-forward " \t")
18506 (delete-region (point) (match-end 0)))
18507 (forward-line)))
18508 ;; Case 2. Start at an heading: convert to items.
18509 ((org-on-heading-p)
18510 (let* ((bul (org-list-bullet-string "-"))
18511 (bul-len (length bul))
18512 ;; Indentation of the first heading. It should be
18513 ;; relative to the indentation of its parent, if any.
18514 (start-ind (save-excursion
18515 (cond
18516 ((not org-adapt-indentation) 0)
18517 ((not (outline-previous-heading)) 0)
18518 (t (length (match-string 0))))))
18519 ;; Level of first heading. Further headings will be
18520 ;; compared to it to determine hierarchy in the list.
18521 (ref-level (org-reduced-level (org-outline-level))))
18522 (while (< (point) end)
18523 (let* ((level (org-reduced-level (org-outline-level)))
18524 (delta (max 0 (- level ref-level))))
18525 ;; If current headline is less indented than the first
18526 ;; one, set it as reference, in order to preserve
18527 ;; subtrees.
18528 (when (< level ref-level) (setq ref-level level))
18529 (replace-match bul t t)
18530 (org-indent-line-to (+ start-ind (* delta bul-len)))
18531 ;; Ensure all text down to END (or SECTION-END) belongs
18532 ;; to the newly created item.
18533 (let ((section-end (save-excursion
18534 (or (outline-next-heading) (point)))))
18535 (forward-line)
18536 (funcall shift-text
18537 (+ start-ind (* (1+ delta) bul-len))
18538 (min end section-end)))))))
18539 ;; Case 3. Normal line with ARG: turn each non-item line into
18540 ;; an item.
18541 (arg
18542 (while (< (point) end)
18543 (unless (or (org-on-heading-p) (org-at-item-p))
18544 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
18545 (replace-match
18546 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
18547 (forward-line)))
18548 ;; Case 4. Normal line without ARG: make the first line of
18549 ;; region an item, and shift indentation of others
18550 ;; lines to set them as item's body.
18551 (t (let* ((bul (org-list-bullet-string "-"))
18552 (bul-len (length bul))
18553 (ref-ind (org-get-indentation)))
18554 (skip-chars-forward " \t")
18555 (insert bul)
18556 (forward-line)
18557 (while (< (point) end)
18558 ;; Ensure that lines less indented than first one
18559 ;; still get included in item body.
18560 (funcall shift-text
18561 (+ ref-ind bul-len)
18562 (min end (save-excursion (or (outline-next-heading)
18563 (point)))))
18564 (forward-line)))))))))
18566 (defun org-toggle-heading (&optional nstars)
18567 "Convert headings to normal text, or items or text to headings.
18568 If there is no active region, only the current line is considered.
18570 If the first non blank line is an headline, remove the stars from
18571 all headlines in the region.
18573 If it is a plain list item, turn all plain list items into headings.
18575 If it is a normal line, turn each and every normal line (i.e. not
18576 an heading or an item) in the region into a heading.
18578 When converting a line into a heading, the number of stars is chosen
18579 such that the lines become children of the current entry. However,
18580 when a prefix argument is given, its value determines the number of
18581 stars to add."
18582 (interactive "P")
18583 (let ((skip-blanks
18584 (function
18585 ;; Return beginning of first non-blank line, starting from
18586 ;; line at POS.
18587 (lambda (pos)
18588 (save-excursion
18589 (goto-char pos)
18590 (skip-chars-forward " \r\t\n")
18591 (point-at-bol)))))
18592 beg end)
18593 ;; Determine boundaries of changes. If region ends at a bol, do
18594 ;; not consider the last line to be in the region.
18595 (if (org-region-active-p)
18596 (setq beg (funcall skip-blanks (region-beginning))
18597 end (copy-marker (save-excursion
18598 (goto-char (region-end))
18599 (if (bolp) (point) (point-at-eol)))))
18600 (setq beg (funcall skip-blanks (point-at-bol))
18601 end (copy-marker (point-at-eol))))
18602 ;; Ensure inline tasks don't count as headings.
18603 (org-with-limited-levels
18604 (save-excursion
18605 (goto-char beg)
18606 (cond
18607 ;; Case 1. Started at an heading: de-star headings.
18608 ((org-on-heading-p)
18609 (while (< (point) end)
18610 (when (org-on-heading-p t)
18611 (looking-at org-outline-regexp) (replace-match ""))
18612 (forward-line)))
18613 ;; Case 2. Started at an item: change items into headlines.
18614 ;; One star will be added by `org-list-to-subtree'.
18615 ((org-at-item-p)
18616 (let* ((stars (make-string
18617 (if nstars
18618 ;; subtract the star that will be added again by
18619 ;; `org-list-to-subtree'
18620 (1- (prefix-numeric-value current-prefix-arg))
18621 (or (org-current-level) 0))
18622 ?*))
18623 (add-stars
18624 (cond (nstars "") ; stars from prefix only
18625 ((equal stars "") "") ; before first heading
18626 (org-odd-levels-only "*") ; inside heading, odd
18627 (t "")))) ; inside heading, oddeven
18628 (while (< (point) end)
18629 (when (org-at-item-p)
18630 ;; Pay attention to cases when region ends before list.
18631 (let* ((struct (org-list-struct))
18632 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
18633 (save-restriction
18634 (narrow-to-region (point) list-end)
18635 (insert
18636 (org-list-to-subtree
18637 (org-list-parse-list t)
18638 '(:istart (concat stars add-stars (funcall get-stars depth))
18639 :icount (concat stars add-stars (funcall get-stars depth))))))))
18640 (forward-line))))
18641 ;; Case 3. Started at normal text: make every line an heading,
18642 ;; skipping headlines and items.
18643 (t (let* ((stars (make-string
18644 (if nstars
18645 (prefix-numeric-value current-prefix-arg)
18646 (or (org-current-level) 0))
18647 ?*))
18648 (add-stars
18649 (cond (nstars "") ; stars from prefix only
18650 ((equal stars "") "*") ; before first heading
18651 (org-odd-levels-only "**") ; inside heading, odd
18652 (t "*"))) ; inside heading, oddeven
18653 (rpl (concat stars add-stars " ")))
18654 (while (< (point) end)
18655 (when (and (not (org-on-heading-p)) (not (org-at-item-p))
18656 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
18657 (replace-match (concat rpl (match-string 2))))
18658 (forward-line)))))))))
18660 (defun org-meta-return (&optional arg)
18661 "Insert a new heading or wrap a region in a table.
18662 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
18663 See the individual commands for more information."
18664 (interactive "P")
18665 (cond
18666 ((run-hook-with-args-until-success 'org-metareturn-hook))
18667 ((org-at-table-p)
18668 (call-interactively 'org-table-wrap-region))
18669 (t (call-interactively 'org-insert-heading))))
18671 ;;; Menu entries
18673 ;; Define the Org-mode menus
18674 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
18675 '("Tbl"
18676 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
18677 ["Next Field" org-cycle (org-at-table-p)]
18678 ["Previous Field" org-shifttab (org-at-table-p)]
18679 ["Next Row" org-return (org-at-table-p)]
18680 "--"
18681 ["Blank Field" org-table-blank-field (org-at-table-p)]
18682 ["Edit Field" org-table-edit-field (org-at-table-p)]
18683 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
18684 "--"
18685 ("Column"
18686 ["Move Column Left" org-metaleft (org-at-table-p)]
18687 ["Move Column Right" org-metaright (org-at-table-p)]
18688 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
18689 ["Insert Column" org-shiftmetaright (org-at-table-p)])
18690 ("Row"
18691 ["Move Row Up" org-metaup (org-at-table-p)]
18692 ["Move Row Down" org-metadown (org-at-table-p)]
18693 ["Delete Row" org-shiftmetaup (org-at-table-p)]
18694 ["Insert Row" org-shiftmetadown (org-at-table-p)]
18695 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
18696 "--"
18697 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
18698 ("Rectangle"
18699 ["Copy Rectangle" org-copy-special (org-at-table-p)]
18700 ["Cut Rectangle" org-cut-special (org-at-table-p)]
18701 ["Paste Rectangle" org-paste-special (org-at-table-p)]
18702 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
18703 "--"
18704 ("Calculate"
18705 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
18706 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
18707 ["Edit Formulas" org-edit-special (org-at-table-p)]
18708 "--"
18709 ["Recalculate line" org-table-recalculate (org-at-table-p)]
18710 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
18711 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
18712 "--"
18713 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
18714 "--"
18715 ["Sum Column/Rectangle" org-table-sum
18716 (or (org-at-table-p) (org-region-active-p))]
18717 ["Which Column?" org-table-current-column (org-at-table-p)])
18718 ["Debug Formulas"
18719 org-table-toggle-formula-debugger
18720 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
18721 ["Show Col/Row Numbers"
18722 org-table-toggle-coordinate-overlays
18723 :style toggle
18724 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
18725 "--"
18726 ["Create" org-table-create (and (not (org-at-table-p))
18727 org-enable-table-editor)]
18728 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
18729 ["Import from File" org-table-import (not (org-at-table-p))]
18730 ["Export to File" org-table-export (org-at-table-p)]
18731 "--"
18732 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
18734 (easy-menu-define org-org-menu org-mode-map "Org menu"
18735 '("Org"
18736 ("Show/Hide"
18737 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
18738 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
18739 ["Sparse Tree..." org-sparse-tree t]
18740 ["Reveal Context" org-reveal t]
18741 ["Show All" show-all t]
18742 "--"
18743 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
18744 "--"
18745 ["New Heading" org-insert-heading t]
18746 ("Navigate Headings"
18747 ["Up" outline-up-heading t]
18748 ["Next" outline-next-visible-heading t]
18749 ["Previous" outline-previous-visible-heading t]
18750 ["Next Same Level" outline-forward-same-level t]
18751 ["Previous Same Level" outline-backward-same-level t]
18752 "--"
18753 ["Jump" org-goto t])
18754 ("Edit Structure"
18755 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
18756 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
18757 "--"
18758 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
18759 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
18760 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
18761 "--"
18762 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
18763 "--"
18764 ["Copy visible text" org-copy-visible t]
18765 "--"
18766 ["Promote Heading" org-metaleft (not (org-at-table-p))]
18767 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
18768 ["Demote Heading" org-metaright (not (org-at-table-p))]
18769 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
18770 "--"
18771 ["Sort Region/Children" org-sort (not (org-at-table-p))]
18772 "--"
18773 ["Convert to odd levels" org-convert-to-odd-levels t]
18774 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
18775 ("Editing"
18776 ["Emphasis..." org-emphasize t]
18777 ["Edit Source Example" org-edit-special t]
18778 "--"
18779 ["Footnote new/jump" org-footnote-action t]
18780 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
18781 ("Archive"
18782 ["Archive (default method)" org-archive-subtree-default t]
18783 "--"
18784 ["Move Subtree to Archive file" org-advertized-archive-subtree t]
18785 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
18786 ["Move subtree to Archive sibling" org-archive-to-archive-sibling t]
18788 "--"
18789 ("Hyperlinks"
18790 ["Store Link (Global)" org-store-link t]
18791 ["Find existing link to here" org-occur-link-in-agenda-files t]
18792 ["Insert Link" org-insert-link t]
18793 ["Follow Link" org-open-at-point t]
18794 "--"
18795 ["Next link" org-next-link t]
18796 ["Previous link" org-previous-link t]
18797 "--"
18798 ["Descriptive Links"
18799 org-toggle-link-display
18800 :style radio
18801 :selected org-descriptive-links
18803 ["Literal Links"
18804 org-toggle-link-display
18805 :style radio
18806 :selected (not org-descriptive-links)])
18807 "--"
18808 ("TODO Lists"
18809 ["TODO/DONE/-" org-todo t]
18810 ("Select keyword"
18811 ["Next keyword" org-shiftright (org-on-heading-p)]
18812 ["Previous keyword" org-shiftleft (org-on-heading-p)]
18813 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
18814 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
18815 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
18816 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
18817 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
18818 "--"
18819 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
18820 :selected org-enforce-todo-dependencies :style toggle :active t]
18821 "Settings for tree at point"
18822 ["Do Children sequentially" org-toggle-ordered-property :style radio
18823 :selected (org-entry-get nil "ORDERED")
18824 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
18825 ["Do Children parallel" org-toggle-ordered-property :style radio
18826 :selected (not (org-entry-get nil "ORDERED"))
18827 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
18828 "--"
18829 ["Set Priority" org-priority t]
18830 ["Priority Up" org-shiftup t]
18831 ["Priority Down" org-shiftdown t]
18832 "--"
18833 ["Get news from all feeds" org-feed-update-all t]
18834 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
18835 ["Customize feeds" (customize-variable 'org-feed-alist) t])
18836 ("TAGS and Properties"
18837 ["Set Tags" org-set-tags-command t]
18838 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
18839 "--"
18840 ["Set property" org-set-property t]
18841 ["Column view of properties" org-columns t]
18842 ["Insert Column View DBlock" org-insert-columns-dblock t])
18843 ("Dates and Scheduling"
18844 ["Timestamp" org-time-stamp t]
18845 ["Timestamp (inactive)" org-time-stamp-inactive t]
18846 ("Change Date"
18847 ["1 Day Later" org-shiftright t]
18848 ["1 Day Earlier" org-shiftleft t]
18849 ["1 ... Later" org-shiftup t]
18850 ["1 ... Earlier" org-shiftdown t])
18851 ["Compute Time Range" org-evaluate-time-range t]
18852 ["Schedule Item" org-schedule t]
18853 ["Deadline" org-deadline t]
18854 "--"
18855 ["Custom time format" org-toggle-time-stamp-overlays
18856 :style radio :selected org-display-custom-times]
18857 "--"
18858 ["Goto Calendar" org-goto-calendar t]
18859 ["Date from Calendar" org-date-from-calendar t]
18860 "--"
18861 ["Start/Restart Timer" org-timer-start t]
18862 ["Pause/Continue Timer" org-timer-pause-or-continue t]
18863 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
18864 ["Insert Timer String" org-timer t]
18865 ["Insert Timer Item" org-timer-item t])
18866 ("Logging work"
18867 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
18868 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
18869 ["Clock out" org-clock-out t]
18870 ["Clock cancel" org-clock-cancel t]
18871 "--"
18872 ["Mark as default task" org-clock-mark-default-task t]
18873 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
18874 ["Goto running clock" org-clock-goto t]
18875 "--"
18876 ["Display times" org-clock-display t]
18877 ["Create clock table" org-clock-report t]
18878 "--"
18879 ["Record DONE time"
18880 (progn (setq org-log-done (not org-log-done))
18881 (message "Switching to %s will %s record a timestamp"
18882 (car org-done-keywords)
18883 (if org-log-done "automatically" "not")))
18884 :style toggle :selected org-log-done])
18885 "--"
18886 ["Agenda Command..." org-agenda t]
18887 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
18888 ("File List for Agenda")
18889 ("Special views current file"
18890 ["TODO Tree" org-show-todo-tree t]
18891 ["Check Deadlines" org-check-deadlines t]
18892 ["Timeline" org-timeline t]
18893 ["Tags/Property tree" org-match-sparse-tree t])
18894 "--"
18895 ["Export/Publish..." org-export t]
18896 ("LaTeX"
18897 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
18898 :selected org-cdlatex-mode]
18899 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
18900 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
18901 ["Modify math symbol" org-cdlatex-math-modify
18902 (org-inside-LaTeX-fragment-p)]
18903 ["Insert citation" org-reftex-citation t]
18904 "--"
18905 ["Template for BEAMER" org-insert-beamer-options-template t])
18906 "--"
18907 ("MobileOrg"
18908 ["Push Files and Views" org-mobile-push t]
18909 ["Get Captured and Flagged" org-mobile-pull t]
18910 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
18911 "--"
18912 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
18913 "--"
18914 ("Documentation"
18915 ["Show Version" org-version t]
18916 ["Info Documentation" org-info t])
18917 ("Customize"
18918 ["Browse Org Group" org-customize t]
18919 "--"
18920 ["Expand This Menu" org-create-customize-menu
18921 (fboundp 'customize-menu-create)])
18922 ["Send bug report" org-submit-bug-report t]
18923 "--"
18924 ("Refresh/Reload"
18925 ["Refresh setup current buffer" org-mode-restart t]
18926 ["Reload Org (after update)" org-reload t]
18927 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
18930 (defun org-info (&optional node)
18931 "Read documentation for Org-mode in the info system.
18932 With optional NODE, go directly to that node."
18933 (interactive)
18934 (info (format "(org)%s" (or node ""))))
18936 ;;;###autoload
18937 (defun org-submit-bug-report ()
18938 "Submit a bug report on Org-mode via mail.
18940 Don't hesitate to report any problems or inaccurate documentation.
18942 If you don't have setup sending mail from (X)Emacs, please copy the
18943 output buffer into your mail program, as it gives us important
18944 information about your Org-mode version and configuration."
18945 (interactive)
18946 (require 'reporter)
18947 (org-load-modules-maybe)
18948 (org-require-autoloaded-modules)
18949 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
18950 (reporter-submit-bug-report
18951 "emacs-orgmode@gnu.org"
18952 (org-version)
18953 (let (list)
18954 (save-window-excursion
18955 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
18956 (delete-other-windows)
18957 (erase-buffer)
18958 (insert "You are about to submit a bug report to the Org-mode mailing list.
18960 We would like to add your full Org-mode and Outline configuration to the
18961 bug report. This greatly simplifies the work of the maintainer and
18962 other experts on the mailing list.
18964 HOWEVER, some variables you have customized may contain private
18965 information. The names of customers, colleagues, or friends, might
18966 appear in the form of file names, tags, todo states, or search strings.
18967 If you answer yes to the prompt, you might want to check and remove
18968 such private information before sending the email.")
18969 (add-text-properties (point-min) (point-max) '(face org-warning))
18970 (when (yes-or-no-p "Include your Org-mode configuration ")
18971 (mapatoms
18972 (lambda (v)
18973 (and (boundp v)
18974 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
18975 (or (and (symbol-value v)
18976 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
18977 (and
18978 (get v 'custom-type) (get v 'standard-value)
18979 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
18980 (push v list)))))
18981 (kill-buffer (get-buffer "*Warn about privacy*"))
18982 list))
18983 nil nil
18984 "Remember to cover the basics, that is, what you expected to happen and
18985 what in fact did happen. You don't know how to make a good report? See
18987 http://orgmode.org/manual/Feedback.html#Feedback
18989 Your bug report will be posted to the Org-mode mailing list.
18990 ------------------------------------------------------------------------")
18991 (save-excursion
18992 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
18993 (replace-match "\\1Bug: \\3 [\\2]")))))
18996 (defun org-install-agenda-files-menu ()
18997 (let ((bl (buffer-list)))
18998 (save-excursion
18999 (while bl
19000 (set-buffer (pop bl))
19001 (if (eq major-mode 'org-mode) (setq bl nil)))
19002 (when (eq major-mode 'org-mode)
19003 (easy-menu-change
19004 '("Org") "File List for Agenda"
19005 (append
19006 (list
19007 ["Edit File List" (org-edit-agenda-file-list) t]
19008 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
19009 ["Remove Current File from List" org-remove-file t]
19010 ["Cycle through agenda files" org-cycle-agenda-files t]
19011 ["Occur in all agenda files" org-occur-in-agenda-files t]
19012 "--")
19013 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
19015 ;;;; Documentation
19017 ;;;###autoload
19018 (defun org-require-autoloaded-modules ()
19019 (interactive)
19020 (mapc 'require
19021 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
19022 org-docbook org-exp org-html org-icalendar
19023 org-id org-latex
19024 org-publish org-remember org-table
19025 org-timer org-xoxo)))
19027 ;;;###autoload
19028 (defun org-reload (&optional uncompiled)
19029 "Reload all org lisp files.
19030 With prefix arg UNCOMPILED, load the uncompiled versions."
19031 (interactive "P")
19032 (require 'find-func)
19033 (let* ((file-re "^\\(org\\|orgtbl\\)\\(\\.el\\|-.*\\.el\\)")
19034 (dir-org (file-name-directory (org-find-library-name "org")))
19035 (dir-org-contrib (ignore-errors
19036 (file-name-directory
19037 (org-find-library-name "org-contribdir"))))
19038 (babel-files
19039 (mapcar (lambda (el) (concat "ob" (when el (format "-%s" el)) ".el"))
19040 (append (list nil "comint" "eval" "exp" "keys"
19041 "lob" "ref" "table" "tangle")
19042 (delq nil
19043 (mapcar
19044 (lambda (lang)
19045 (when (cdr lang) (symbol-name (car lang))))
19046 org-babel-load-languages)))))
19047 (files
19048 (append (directory-files dir-org t file-re)
19049 babel-files
19050 (and dir-org-contrib
19051 (directory-files dir-org-contrib t file-re))))
19052 (remove-re (concat (if (featurep 'xemacs)
19053 "org-colview" "org-colview-xemacs")
19054 "\\'")))
19055 (setq files (mapcar 'file-name-sans-extension files))
19056 (setq files (mapcar
19057 (lambda (x) (if (string-match remove-re x) nil x))
19058 files))
19059 (setq files (delq nil files))
19060 (mapc
19061 (lambda (f)
19062 (when (featurep (intern (file-name-nondirectory f)))
19063 (if (and (not uncompiled)
19064 (file-exists-p (concat f ".elc")))
19065 (load (concat f ".elc") nil nil t)
19066 (load (concat f ".el") nil nil t))))
19067 files))
19068 (org-version))
19070 ;;;###autoload
19071 (defun org-customize ()
19072 "Call the customize function with org as argument."
19073 (interactive)
19074 (org-load-modules-maybe)
19075 (org-require-autoloaded-modules)
19076 (customize-browse 'org))
19078 (defun org-create-customize-menu ()
19079 "Create a full customization menu for Org-mode, insert it into the menu."
19080 (interactive)
19081 (org-load-modules-maybe)
19082 (org-require-autoloaded-modules)
19083 (if (fboundp 'customize-menu-create)
19084 (progn
19085 (easy-menu-change
19086 '("Org") "Customize"
19087 `(["Browse Org group" org-customize t]
19088 "--"
19089 ,(customize-menu-create 'org)
19090 ["Set" Custom-set t]
19091 ["Save" Custom-save t]
19092 ["Reset to Current" Custom-reset-current t]
19093 ["Reset to Saved" Custom-reset-saved t]
19094 ["Reset to Standard Settings" Custom-reset-standard t]))
19095 (message "\"Org\"-menu now contains full customization menu"))
19096 (error "Cannot expand menu (outdated version of cus-edit.el)")))
19098 ;;;; Miscellaneous stuff
19100 ;;; Generally useful functions
19102 (defun org-get-at-bol (property)
19103 "Get text property PROPERTY at beginning of line."
19104 (get-text-property (point-at-bol) property))
19106 (defun org-find-text-property-in-string (prop s)
19107 "Return the first non-nil value of property PROP in string S."
19108 (or (get-text-property 0 prop s)
19109 (get-text-property (or (next-single-property-change 0 prop s) 0)
19110 prop s)))
19112 (defun org-display-warning (message) ;; Copied from Emacs-Muse
19113 "Display the given MESSAGE as a warning."
19114 (if (fboundp 'display-warning)
19115 (display-warning 'org message
19116 (if (featurep 'xemacs) 'warning :warning))
19117 (let ((buf (get-buffer-create "*Org warnings*")))
19118 (with-current-buffer buf
19119 (goto-char (point-max))
19120 (insert "Warning (Org): " message)
19121 (unless (bolp)
19122 (newline)))
19123 (display-buffer buf)
19124 (sit-for 0))))
19126 (defun org-eval (form)
19127 "Eval FORM and return result."
19128 (condition-case error
19129 (eval form)
19130 (error (format "%%![Error: %s]" error))))
19132 (defun org-in-commented-line ()
19133 "Is point in a line starting with `#'?"
19134 (equal (char-after (point-at-bol)) ?#))
19136 (defun org-in-indented-comment-line ()
19137 "Is point in a line starting with `#' after some white space?"
19138 (save-excursion
19139 (save-match-data
19140 (goto-char (point-at-bol))
19141 (looking-at "[ \t]*#"))))
19143 (defun org-in-verbatim-emphasis ()
19144 (save-match-data
19145 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
19147 (defun org-goto-marker-or-bmk (marker &optional bookmark)
19148 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
19149 (if (and marker (marker-buffer marker)
19150 (buffer-live-p (marker-buffer marker)))
19151 (progn
19152 (org-pop-to-buffer-same-window (marker-buffer marker))
19153 (if (or (> marker (point-max)) (< marker (point-min)))
19154 (widen))
19155 (goto-char marker)
19156 (org-show-context 'org-goto))
19157 (if bookmark
19158 (bookmark-jump bookmark)
19159 (error "Cannot find location"))))
19161 (defun org-quote-csv-field (s)
19162 "Quote field for inclusion in CSV material."
19163 (if (string-match "[\",]" s)
19164 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
19167 (defun org-force-self-insert (N)
19168 "Needed to enforce self-insert under remapping."
19169 (interactive "p")
19170 (self-insert-command N))
19172 (defun org-string-width (s)
19173 "Compute width of string, ignoring invisible characters.
19174 This ignores character with invisibility property `org-link', and also
19175 characters with property `org-cwidth', because these will become invisible
19176 upon the next fontification round."
19177 (let (b l)
19178 (when (or (eq t buffer-invisibility-spec)
19179 (assq 'org-link buffer-invisibility-spec))
19180 (while (setq b (text-property-any 0 (length s)
19181 'invisible 'org-link s))
19182 (setq s (concat (substring s 0 b)
19183 (substring s (or (next-single-property-change
19184 b 'invisible s) (length s)))))))
19185 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
19186 (setq s (concat (substring s 0 b)
19187 (substring s (or (next-single-property-change
19188 b 'org-cwidth s) (length s))))))
19189 (setq l (string-width s) b -1)
19190 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
19191 (setq l (- l (get-text-property b 'org-dwidth-n s))))
19194 (defun org-shorten-string (s maxlength)
19195 "Shorten string S so tht it is no longer than MAXLENGTH characters.
19196 If the string is shorter or has length MAXLENGTH, just return the
19197 original string. If it is longer, the functions finds a space in the
19198 string, breaks this string off at that locations and adds three dots
19199 as ellipsis. Including the ellipsis, the string will not be longer
19200 than MAXLENGTH. If finding a good breaking point in the string does
19201 not work, the string is just chopped off in the middle of a word
19202 if necessary."
19203 (if (<= (length s) maxlength)
19205 (let* ((n (max (- maxlength 4) 1))
19206 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
19207 (if (string-match re s)
19208 (concat (match-string 1 s) "...")
19209 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
19211 (defun org-get-indentation (&optional line)
19212 "Get the indentation of the current line, interpreting tabs.
19213 When LINE is given, assume it represents a line and compute its indentation."
19214 (if line
19215 (if (string-match "^ *" (org-remove-tabs line))
19216 (match-end 0))
19217 (save-excursion
19218 (beginning-of-line 1)
19219 (skip-chars-forward " \t")
19220 (current-column))))
19222 (defun org-get-string-indentation (s)
19223 "What indentation has S due to SPACE and TAB at the beginning of the string?"
19224 (let ((n -1) (i 0) (w tab-width) c)
19225 (catch 'exit
19226 (while (< (setq n (1+ n)) (length s))
19227 (setq c (aref s n))
19228 (cond ((= c ?\ ) (setq i (1+ i)))
19229 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
19230 (t (throw 'exit t)))))
19233 (defun org-remove-tabs (s &optional width)
19234 "Replace tabulators in S with spaces.
19235 Assumes that s is a single line, starting in column 0."
19236 (setq width (or width tab-width))
19237 (while (string-match "\t" s)
19238 (setq s (replace-match
19239 (make-string
19240 (- (* width (/ (+ (match-beginning 0) width) width))
19241 (match-beginning 0)) ?\ )
19242 t t s)))
19245 (defun org-fix-indentation (line ind)
19246 "Fix indentation in LINE.
19247 IND is a cons cell with target and minimum indentation.
19248 If the current indentation in LINE is smaller than the minimum,
19249 leave it alone. If it is larger than ind, set it to the target."
19250 (let* ((l (org-remove-tabs line))
19251 (i (org-get-indentation l))
19252 (i1 (car ind)) (i2 (cdr ind)))
19253 (if (>= i i2) (setq l (substring line i2)))
19254 (if (> i1 0)
19255 (concat (make-string i1 ?\ ) l)
19256 l)))
19258 (defun org-remove-indentation (code &optional n)
19259 "Remove the maximum common indentation from the lines in CODE.
19260 N may optionally be the number of spaces to remove."
19261 (with-temp-buffer
19262 (insert code)
19263 (org-do-remove-indentation n)
19264 (buffer-string)))
19266 (defun org-do-remove-indentation (&optional n)
19267 "Remove the maximum common indentation from the buffer."
19268 (untabify (point-min) (point-max))
19269 (let ((min 10000) re)
19270 (if n
19271 (setq min n)
19272 (goto-char (point-min))
19273 (while (re-search-forward "^ *[^ \n]" nil t)
19274 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
19275 (unless (or (= min 0) (= min 10000))
19276 (setq re (format "^ \\{%d\\}" min))
19277 (goto-char (point-min))
19278 (while (re-search-forward re nil t)
19279 (replace-match "")
19280 (end-of-line 1))
19281 min)))
19283 (defun org-fill-template (template alist)
19284 "Find each %key of ALIST in TEMPLATE and replace it."
19285 (let ((case-fold-search nil)
19286 entry key value)
19287 (setq alist (sort (copy-sequence alist)
19288 (lambda (a b) (< (length (car a)) (length (car b))))))
19289 (while (setq entry (pop alist))
19290 (setq template
19291 (replace-regexp-in-string
19292 (concat "%" (regexp-quote (car entry)))
19293 (cdr entry) template t t)))
19294 template))
19296 (defun org-base-buffer (buffer)
19297 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
19298 (if (not buffer)
19299 buffer
19300 (or (buffer-base-buffer buffer)
19301 buffer)))
19303 (defun org-trim (s)
19304 "Remove whitespace at beginning and end of string."
19305 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
19306 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
19309 (defun org-wrap (string &optional width lines)
19310 "Wrap string to either a number of lines, or a width in characters.
19311 If WIDTH is non-nil, the string is wrapped to that width, however many lines
19312 that costs. If there is a word longer than WIDTH, the text is actually
19313 wrapped to the length of that word.
19314 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
19315 many lines, whatever width that takes.
19316 The return value is a list of lines, without newlines at the end."
19317 (let* ((words (org-split-string string "[ \t\n]+"))
19318 (maxword (apply 'max (mapcar 'org-string-width words)))
19319 w ll)
19320 (cond (width
19321 (org-do-wrap words (max maxword width)))
19322 (lines
19323 (setq w maxword)
19324 (setq ll (org-do-wrap words maxword))
19325 (if (<= (length ll) lines)
19327 (setq ll words)
19328 (while (> (length ll) lines)
19329 (setq w (1+ w))
19330 (setq ll (org-do-wrap words w)))
19331 ll))
19332 (t (error "Cannot wrap this")))))
19334 (defun org-do-wrap (words width)
19335 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
19336 (let (lines line)
19337 (while words
19338 (setq line (pop words))
19339 (while (and words (< (+ (length line) (length (car words))) width))
19340 (setq line (concat line " " (pop words))))
19341 (setq lines (push line lines)))
19342 (nreverse lines)))
19344 (defun org-split-string (string &optional separators)
19345 "Splits STRING into substrings at SEPARATORS.
19346 No empty strings are returned if there are matches at the beginning
19347 and end of string."
19348 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
19349 (start 0)
19350 notfirst
19351 (list nil))
19352 (while (and (string-match rexp string
19353 (if (and notfirst
19354 (= start (match-beginning 0))
19355 (< start (length string)))
19356 (1+ start) start))
19357 (< (match-beginning 0) (length string)))
19358 (setq notfirst t)
19359 (or (eq (match-beginning 0) 0)
19360 (and (eq (match-beginning 0) (match-end 0))
19361 (eq (match-beginning 0) start))
19362 (setq list
19363 (cons (substring string start (match-beginning 0))
19364 list)))
19365 (setq start (match-end 0)))
19366 (or (eq start (length string))
19367 (setq list
19368 (cons (substring string start)
19369 list)))
19370 (nreverse list)))
19372 (defun org-quote-vert (s)
19373 "Replace \"|\" with \"\\vert\"."
19374 (while (string-match "|" s)
19375 (setq s (replace-match "\\vert" t t s)))
19378 (defun org-uuidgen-p (s)
19379 "Is S an ID created by UUIDGEN?"
19380 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
19382 (defun org-context ()
19383 "Return a list of contexts of the current cursor position.
19384 If several contexts apply, all are returned.
19385 Each context entry is a list with a symbol naming the context, and
19386 two positions indicating start and end of the context. Possible
19387 contexts are:
19389 :headline anywhere in a headline
19390 :headline-stars on the leading stars in a headline
19391 :todo-keyword on a TODO keyword (including DONE) in a headline
19392 :tags on the TAGS in a headline
19393 :priority on the priority cookie in a headline
19394 :item on the first line of a plain list item
19395 :item-bullet on the bullet/number of a plain list item
19396 :checkbox on the checkbox in a plain list item
19397 :table in an org-mode table
19398 :table-special on a special filed in a table
19399 :table-table in a table.el table
19400 :link on a hyperlink
19401 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
19402 :target on a <<target>>
19403 :radio-target on a <<<radio-target>>>
19404 :latex-fragment on a LaTeX fragment
19405 :latex-preview on a LaTeX fragment with overlayed preview image
19407 This function expects the position to be visible because it uses font-lock
19408 faces as a help to recognize the following contexts: :table-special, :link,
19409 and :keyword."
19410 (let* ((f (get-text-property (point) 'face))
19411 (faces (if (listp f) f (list f)))
19412 (p (point)) clist o)
19413 ;; First the large context
19414 (cond
19415 ((org-on-heading-p t)
19416 (push (list :headline (point-at-bol) (point-at-eol)) clist)
19417 (when (progn
19418 (beginning-of-line 1)
19419 (looking-at org-todo-line-tags-regexp))
19420 (push (org-point-in-group p 1 :headline-stars) clist)
19421 (push (org-point-in-group p 2 :todo-keyword) clist)
19422 (push (org-point-in-group p 4 :tags) clist))
19423 (goto-char p)
19424 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
19425 (if (looking-at "\\[#[A-Z0-9]\\]")
19426 (push (org-point-in-group p 0 :priority) clist)))
19428 ((org-at-item-p)
19429 (push (org-point-in-group p 2 :item-bullet) clist)
19430 (push (list :item (point-at-bol)
19431 (save-excursion (org-end-of-item) (point)))
19432 clist)
19433 (and (org-at-item-checkbox-p)
19434 (push (org-point-in-group p 0 :checkbox) clist)))
19436 ((org-at-table-p)
19437 (push (list :table (org-table-begin) (org-table-end)) clist)
19438 (if (memq 'org-formula faces)
19439 (push (list :table-special
19440 (previous-single-property-change p 'face)
19441 (next-single-property-change p 'face)) clist)))
19442 ((org-at-table-p 'any)
19443 (push (list :table-table) clist)))
19444 (goto-char p)
19446 ;; Now the small context
19447 (cond
19448 ((org-at-timestamp-p)
19449 (push (org-point-in-group p 0 :timestamp) clist))
19450 ((memq 'org-link faces)
19451 (push (list :link
19452 (previous-single-property-change p 'face)
19453 (next-single-property-change p 'face)) clist))
19454 ((memq 'org-special-keyword faces)
19455 (push (list :keyword
19456 (previous-single-property-change p 'face)
19457 (next-single-property-change p 'face)) clist))
19458 ((org-on-target-p)
19459 (push (org-point-in-group p 0 :target) clist)
19460 (goto-char (1- (match-beginning 0)))
19461 (if (looking-at org-radio-target-regexp)
19462 (push (org-point-in-group p 0 :radio-target) clist))
19463 (goto-char p))
19464 ((setq o (car (delq nil
19465 (mapcar
19466 (lambda (x)
19467 (if (memq x org-latex-fragment-image-overlays) x))
19468 (overlays-at (point))))))
19469 (push (list :latex-fragment
19470 (overlay-start o) (overlay-end o)) clist)
19471 (push (list :latex-preview
19472 (overlay-start o) (overlay-end o)) clist))
19473 ((org-inside-LaTeX-fragment-p)
19474 ;; FIXME: positions wrong.
19475 (push (list :latex-fragment (point) (point)) clist)))
19477 (setq clist (nreverse (delq nil clist)))
19478 clist))
19480 ;; FIXME: Compare with at-regexp-p Do we need both?
19481 (defun org-in-regexp (re &optional nlines visually)
19482 "Check if point is inside a match of regexp.
19483 Normally only the current line is checked, but you can include NLINES extra
19484 lines both before and after point into the search.
19485 If VISUALLY is set, require that the cursor is not after the match but
19486 really on, so that the block visually is on the match."
19487 (catch 'exit
19488 (let ((pos (point))
19489 (eol (point-at-eol (+ 1 (or nlines 0))))
19490 (inc (if visually 1 0)))
19491 (save-excursion
19492 (beginning-of-line (- 1 (or nlines 0)))
19493 (while (re-search-forward re eol t)
19494 (if (and (<= (match-beginning 0) pos)
19495 (>= (+ inc (match-end 0)) pos))
19496 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
19498 (defun org-at-regexp-p (regexp)
19499 "Is point inside a match of REGEXP in the current line?"
19500 (catch 'exit
19501 (save-excursion
19502 (let ((pos (point)) (end (point-at-eol)))
19503 (beginning-of-line 1)
19504 (while (re-search-forward regexp end t)
19505 (if (and (<= (match-beginning 0) pos)
19506 (>= (match-end 0) pos))
19507 (throw 'exit t)))
19508 nil))))
19510 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
19511 "Non-nil when point is between matches of START-RE and END-RE.
19513 Also return a non-nil value when point is on one of the matches.
19515 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
19516 buffer positions. Default values are the positions of headlines
19517 surrounding the point.
19519 The functions returns a cons cell whose car (resp. cdr) is the
19520 position before START-RE (resp. after END-RE)."
19521 (save-match-data
19522 (let ((pos (point))
19523 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
19524 (limit-down (or lim-down (save-excursion (outline-next-heading))))
19525 beg end)
19526 (save-excursion
19527 ;; Point is on a block when on START-RE or if START-RE can be
19528 ;; found before it...
19529 (and (or (org-at-regexp-p start-re)
19530 (re-search-backward start-re limit-up t))
19531 (setq beg (match-beginning 0))
19532 ;; ... and END-RE after it...
19533 (goto-char (match-end 0))
19534 (re-search-forward end-re limit-down t)
19535 (> (setq end (match-end 0)) pos)
19536 ;; ... without another START-RE in-between.
19537 (goto-char (match-beginning 0))
19538 (not (re-search-backward start-re (1+ beg) t))
19539 ;; Return value.
19540 (cons beg end))))))
19542 (defun org-in-block-p (names)
19543 "Non-nil when point belongs to a block whose name belongs to NAMES.
19545 NAMES is a list of strings containing names of blocks.
19547 Return first block name matched, or nil. Beware that in case of
19548 nested blocks, the returned name may not belong to the closest
19549 block from point."
19550 (save-match-data
19551 (catch 'exit
19552 (let ((case-fold-search t)
19553 (lim-up (save-excursion (outline-previous-heading)))
19554 (lim-down (save-excursion (outline-next-heading))))
19555 (mapc (lambda (name)
19556 (let ((n (regexp-quote name)))
19557 (when (org-between-regexps-p
19558 (concat "^[ \t]*#\\+begin_" n)
19559 (concat "^[ \t]*#\\+end_" n)
19560 lim-up lim-down)
19561 (throw 'exit n))))
19562 names))
19563 nil)))
19565 (defun org-occur-in-agenda-files (regexp &optional nlines)
19566 "Call `multi-occur' with buffers for all agenda files."
19567 (interactive "sOrg-files matching: \np")
19568 (let* ((files (org-agenda-files))
19569 (tnames (mapcar 'file-truename files))
19570 (extra org-agenda-text-search-extra-files)
19572 (when (eq (car extra) 'agenda-archives)
19573 (setq extra (cdr extra))
19574 (setq files (org-add-archive-files files)))
19575 (while (setq f (pop extra))
19576 (unless (member (file-truename f) tnames)
19577 (add-to-list 'files f 'append)
19578 (add-to-list 'tnames (file-truename f) 'append)))
19579 (multi-occur
19580 (mapcar (lambda (x)
19581 (with-current-buffer
19582 (or (get-file-buffer x) (find-file-noselect x))
19583 (widen)
19584 (current-buffer)))
19585 files)
19586 regexp)))
19588 (if (boundp 'occur-mode-find-occurrence-hook)
19589 ;; Emacs 23
19590 (add-hook 'occur-mode-find-occurrence-hook
19591 (lambda ()
19592 (when (eq major-mode 'org-mode)
19593 (org-reveal))))
19594 ;; Emacs 22
19595 (defadvice occur-mode-goto-occurrence
19596 (after org-occur-reveal activate)
19597 (and (eq major-mode 'org-mode) (org-reveal)))
19598 (defadvice occur-mode-goto-occurrence-other-window
19599 (after org-occur-reveal activate)
19600 (and (eq major-mode 'org-mode) (org-reveal)))
19601 (defadvice occur-mode-display-occurrence
19602 (after org-occur-reveal activate)
19603 (when (eq major-mode 'org-mode)
19604 (let ((pos (occur-mode-find-occurrence)))
19605 (with-current-buffer (marker-buffer pos)
19606 (save-excursion
19607 (goto-char pos)
19608 (org-reveal)))))))
19610 (defun org-occur-link-in-agenda-files ()
19611 "Create a link and search for it in the agendas.
19612 The link is not stored in `org-stored-links', it is just created
19613 for the search purpose."
19614 (interactive)
19615 (let ((link (condition-case nil
19616 (org-store-link nil)
19617 (error "Unable to create a link to here"))))
19618 (org-occur-in-agenda-files (regexp-quote link))))
19620 (defun org-uniquify (list)
19621 "Remove duplicate elements from LIST."
19622 (let (res)
19623 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
19624 res))
19626 (defun org-delete-all (elts list)
19627 "Remove all elements in ELTS from LIST."
19628 (while elts
19629 (setq list (delete (pop elts) list)))
19630 list)
19632 (defun org-count (cl-item cl-seq)
19633 "Count the number of occurrences of ITEM in SEQ.
19634 Taken from `count' in cl-seq.el with all keyword arguments removed."
19635 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
19636 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
19637 (while (< cl-start cl-end)
19638 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
19639 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
19640 (setq cl-start (1+ cl-start)))
19641 cl-count))
19643 (defun org-remove-if (predicate seq)
19644 "Remove everything from SEQ that fulfills PREDICATE."
19645 (let (res e)
19646 (while seq
19647 (setq e (pop seq))
19648 (if (not (funcall predicate e)) (push e res)))
19649 (nreverse res)))
19651 (defun org-remove-if-not (predicate seq)
19652 "Remove everything from SEQ that does not fulfill PREDICATE."
19653 (let (res e)
19654 (while seq
19655 (setq e (pop seq))
19656 (if (funcall predicate e) (push e res)))
19657 (nreverse res)))
19659 (defun org-reduce (cl-func cl-seq &rest cl-keys)
19660 "Reduce two-argument FUNCTION across SEQ.
19661 Taken from `reduce' in cl-seq.el with all keyword arguments but
19662 \":initial-value\" removed."
19663 (let ((cl-accum (cond ((memq :initial-value cl-keys)
19664 (cadr (memq :initial-value cl-keys)))
19665 (cl-seq (pop cl-seq))
19666 (t (funcall cl-func)))))
19667 (while cl-seq
19668 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
19669 cl-accum))
19671 (defun org-back-over-empty-lines ()
19672 "Move backwards over whitespace, to the beginning of the first empty line.
19673 Returns the number of empty lines passed."
19674 (let ((pos (point)))
19675 (if (cdr (assoc 'heading org-blank-before-new-entry))
19676 (skip-chars-backward " \t\n\r")
19677 (unless (eobp)
19678 (forward-line -1)))
19679 (beginning-of-line 2)
19680 (goto-char (min (point) pos))
19681 (count-lines (point) pos)))
19683 (defun org-skip-whitespace ()
19684 (skip-chars-forward " \t\n\r"))
19686 (defun org-point-in-group (point group &optional context)
19687 "Check if POINT is in match-group GROUP.
19688 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
19689 match. If the match group does not exist or point is not inside it,
19690 return nil."
19691 (and (match-beginning group)
19692 (>= point (match-beginning group))
19693 (<= point (match-end group))
19694 (if context
19695 (list context (match-beginning group) (match-end group))
19696 t)))
19698 (defun org-switch-to-buffer-other-window (&rest args)
19699 "Switch to buffer in a second window on the current frame.
19700 In particular, do not allow pop-up frames.
19701 Returns the newly created buffer."
19702 (let (pop-up-frames special-display-buffer-names special-display-regexps
19703 special-display-function)
19704 (apply 'switch-to-buffer-other-window args)))
19706 (defun org-combine-plists (&rest plists)
19707 "Create a single property list from all plists in PLISTS.
19708 The process starts by copying the first list, and then setting properties
19709 from the other lists. Settings in the last list are the most significant
19710 ones and overrule settings in the other lists."
19711 (let ((rtn (copy-sequence (pop plists)))
19712 p v ls)
19713 (while plists
19714 (setq ls (pop plists))
19715 (while ls
19716 (setq p (pop ls) v (pop ls))
19717 (setq rtn (plist-put rtn p v))))
19718 rtn))
19720 (defun org-move-line-down (arg)
19721 "Move the current line down. With prefix argument, move it past ARG lines."
19722 (interactive "p")
19723 (let ((col (current-column))
19724 beg end pos)
19725 (beginning-of-line 1) (setq beg (point))
19726 (beginning-of-line 2) (setq end (point))
19727 (beginning-of-line (+ 1 arg))
19728 (setq pos (move-marker (make-marker) (point)))
19729 (insert (delete-and-extract-region beg end))
19730 (goto-char pos)
19731 (org-move-to-column col)))
19733 (defun org-move-line-up (arg)
19734 "Move the current line up. With prefix argument, move it past ARG lines."
19735 (interactive "p")
19736 (let ((col (current-column))
19737 beg end pos)
19738 (beginning-of-line 1) (setq beg (point))
19739 (beginning-of-line 2) (setq end (point))
19740 (beginning-of-line (- arg))
19741 (setq pos (move-marker (make-marker) (point)))
19742 (insert (delete-and-extract-region beg end))
19743 (goto-char pos)
19744 (org-move-to-column col)))
19746 (defun org-replace-escapes (string table)
19747 "Replace %-escapes in STRING with values in TABLE.
19748 TABLE is an association list with keys like \"%a\" and string values.
19749 The sequences in STRING may contain normal field width and padding information,
19750 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
19751 so values can contain further %-escapes if they are define later in TABLE."
19752 (let ((tbl (copy-alist table))
19753 (case-fold-search nil)
19754 (pchg 0)
19755 e re rpl)
19756 (while (setq e (pop tbl))
19757 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
19758 (when (and (cdr e) (string-match re (cdr e)))
19759 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
19760 (safe "SREF"))
19761 (add-text-properties 0 3 (list 'sref sref) safe)
19762 (setcdr e (replace-match safe t t (cdr e)))))
19763 (while (string-match re string)
19764 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
19765 (cdr e)))
19766 (setq string (replace-match rpl t t string))))
19767 (while (setq pchg (next-property-change pchg string))
19768 (let ((sref (get-text-property pchg 'sref string)))
19769 (when (and sref (string-match "SREF" string pchg))
19770 (setq string (replace-match sref t t string)))))
19771 string))
19773 (defun org-sublist (list start end)
19774 "Return a section of LIST, from START to END.
19775 Counting starts at 1."
19776 (let (rtn (c start))
19777 (setq list (nthcdr (1- start) list))
19778 (while (and list (<= c end))
19779 (push (pop list) rtn)
19780 (setq c (1+ c)))
19781 (nreverse rtn)))
19783 (defun org-find-base-buffer-visiting (file)
19784 "Like `find-buffer-visiting' but always return the base buffer and
19785 not an indirect buffer."
19786 (let ((buf (or (get-file-buffer file)
19787 (find-buffer-visiting file))))
19788 (if buf
19789 (or (buffer-base-buffer buf) buf)
19790 nil)))
19792 (defun org-image-file-name-regexp (&optional extensions)
19793 "Return regexp matching the file names of images.
19794 If EXTENSIONS is given, only match these."
19795 (if (and (not extensions) (fboundp 'image-file-name-regexp))
19796 (image-file-name-regexp)
19797 (let ((image-file-name-extensions
19798 (or extensions
19799 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
19800 "xbm" "xpm" "pbm" "pgm" "ppm"))))
19801 (concat "\\."
19802 (regexp-opt (nconc (mapcar 'upcase
19803 image-file-name-extensions)
19804 image-file-name-extensions)
19806 "\\'"))))
19808 (defun org-file-image-p (file &optional extensions)
19809 "Return non-nil if FILE is an image."
19810 (save-match-data
19811 (string-match (org-image-file-name-regexp extensions) file)))
19813 (defun org-get-cursor-date ()
19814 "Return the date at cursor in as a time.
19815 This works in the calendar and in the agenda, anywhere else it just
19816 returns the current time."
19817 (let (date day defd)
19818 (cond
19819 ((eq major-mode 'calendar-mode)
19820 (setq date (calendar-cursor-to-date)
19821 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
19822 ((eq major-mode 'org-agenda-mode)
19823 (setq day (get-text-property (point) 'day))
19824 (if day
19825 (setq date (calendar-gregorian-from-absolute day)
19826 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
19827 (nth 2 date))))))
19828 (or defd (current-time))))
19830 (defvar org-agenda-action-marker (make-marker)
19831 "Marker pointing to the entry for the next agenda action.")
19833 (defun org-mark-entry-for-agenda-action ()
19834 "Mark the current entry as target of an agenda action.
19835 Agenda actions are actions executed from the agenda with the key `k',
19836 which make use of the date at the cursor."
19837 (interactive)
19838 (move-marker org-agenda-action-marker
19839 (save-excursion (org-back-to-heading t) (point))
19840 (current-buffer))
19841 (message
19842 "Entry marked for action; press `k' at desired date in agenda or calendar"))
19844 (defun org-mark-subtree ()
19845 "Mark the current subtree.
19846 This puts point at the start of the current subtree, and mark at the end.
19848 If point is in an inline task, mark that task instead."
19849 (interactive)
19850 (let ((inline-task-p
19851 (and (featurep 'org-inlinetask)
19852 (org-inlinetask-in-task-p)))
19853 (beg))
19854 ;; Get beginning of subtree
19855 (cond
19856 (inline-task-p (org-inlinetask-goto-beginning))
19857 ((org-at-heading-p) (beginning-of-line))
19858 (t (org-with-limited-levels (outline-previous-visible-heading 1))))
19859 (setq beg (point))
19860 ;; Get end of it
19861 (if inline-task-p
19862 (org-inlinetask-goto-end)
19863 (org-end-of-subtree))
19864 ;; Mark zone
19865 (push-mark (point) nil t)
19866 (goto-char beg)))
19868 ;;; Paragraph filling stuff.
19869 ;; We want this to be just right, so use the full arsenal.
19871 (defun org-indent-line-function ()
19872 "Indent line depending on context."
19873 (interactive)
19874 (let* ((pos (point))
19875 (itemp (org-at-item-p))
19876 (case-fold-search t)
19877 (org-drawer-regexp (or org-drawer-regexp "\000"))
19878 (inline-task-p (and (featurep 'org-inlinetask)
19879 (org-inlinetask-in-task-p)))
19880 (inline-re (and inline-task-p
19881 (org-inlinetask-outline-regexp)))
19882 column)
19883 (beginning-of-line 1)
19884 (cond
19885 ;; Comments
19886 ((looking-at "# ") (setq column 0))
19887 ;; Headings
19888 ((looking-at org-outline-regexp) (setq column 0))
19889 ;; Included files
19890 ((looking-at "#\\+include:") (setq column 0))
19891 ;; Footnote definition
19892 ((looking-at org-footnote-definition-re) (setq column 0))
19893 ;; Literal examples
19894 ((looking-at "[ \t]*:\\( \\|$\\)")
19895 (setq column (org-get-indentation))) ; do nothing
19896 ;; Lists
19897 ((ignore-errors (goto-char (org-in-item-p)))
19898 (setq column (if itemp
19899 (org-get-indentation)
19900 (org-list-item-body-column (point))))
19901 (goto-char pos))
19902 ;; Drawers
19903 ((and (looking-at "[ \t]*:END:")
19904 (save-excursion (re-search-backward org-drawer-regexp nil t)))
19905 (save-excursion
19906 (goto-char (1- (match-beginning 1)))
19907 (setq column (current-column))))
19908 ;; Special blocks
19909 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
19910 (save-excursion
19911 (re-search-backward
19912 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
19913 (setq column (org-get-indentation (match-string 0))))
19914 ((and (not (looking-at "[ \t]*#\\+begin_"))
19915 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
19916 (save-excursion
19917 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
19918 (setq column
19919 (cond ((equal (downcase (match-string 1)) "src")
19920 ;; src blocks: let `org-edit-src-exit' handle them
19921 (org-get-indentation))
19922 ((equal (downcase (match-string 1)) "example")
19923 (max (org-get-indentation)
19924 (org-get-indentation (match-string 0))))
19926 (org-get-indentation (match-string 0))))))
19927 ;; This line has nothing special, look at the previous relevant
19928 ;; line to compute indentation
19930 (beginning-of-line 0)
19931 (while (and (not (bobp))
19932 (not (looking-at org-drawer-regexp))
19933 ;; When point started in an inline task, do not move
19934 ;; above task starting line.
19935 (not (and inline-task-p (looking-at inline-re)))
19936 ;; Skip drawers, blocks, empty lines, verbatim,
19937 ;; comments, tables, footnotes definitions, lists,
19938 ;; inline tasks.
19939 (or (and (looking-at "[ \t]*:END:")
19940 (re-search-backward org-drawer-regexp nil t))
19941 (and (looking-at "[ \t]*#\\+end_")
19942 (re-search-backward "[ \t]*#\\+begin_"nil t))
19943 (looking-at "[ \t]*[\n:#|]")
19944 (looking-at org-footnote-definition-re)
19945 (and (ignore-errors (goto-char (org-in-item-p)))
19946 (goto-char
19947 (org-list-get-top-point (org-list-struct))))
19948 (and (not inline-task-p)
19949 (featurep 'org-inlinetask)
19950 (org-inlinetask-in-task-p)
19951 (or (org-inlinetask-goto-beginning) t))))
19952 (beginning-of-line 0))
19953 (cond
19954 ;; There was an heading above.
19955 ((looking-at "\\*+[ \t]+")
19956 (if (not org-adapt-indentation)
19957 (setq column 0)
19958 (goto-char (match-end 0))
19959 (setq column (current-column))))
19960 ;; A drawer had started and is unfinished
19961 ((looking-at org-drawer-regexp)
19962 (goto-char (1- (match-beginning 1)))
19963 (setq column (current-column)))
19964 ;; Else, nothing noticeable found: get indentation and go on.
19965 (t (setq column (org-get-indentation))))))
19966 ;; Now apply indentation and move cursor accordingly
19967 (goto-char pos)
19968 (if (<= (current-column) (current-indentation))
19969 (org-indent-line-to column)
19970 (save-excursion (org-indent-line-to column)))
19971 ;; Special polishing for properties, see `org-property-format'
19972 (setq column (current-column))
19973 (beginning-of-line 1)
19974 (if (looking-at
19975 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
19976 (replace-match (concat (match-string 1)
19977 (format org-property-format
19978 (match-string 2) (match-string 3)))
19979 t t))
19980 (org-move-to-column column)))
19982 (defvar org-adaptive-fill-regexp-backup adaptive-fill-regexp
19983 "Variable to store copy of `adaptive-fill-regexp'.
19984 Since `adaptive-fill-regexp' is set to never match, we need to
19985 store a backup of its value before entering `org-mode' so that
19986 the functionality can be provided as a fall-back.")
19988 (defun org-set-autofill-regexps ()
19989 (interactive)
19990 ;; In the paragraph separator we include headlines, because filling
19991 ;; text in a line directly attached to a headline would otherwise
19992 ;; fill the headline as well.
19993 (org-set-local 'comment-start-skip "^#+[ \t]*")
19994 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|#]")
19995 ;; The paragraph starter includes hand-formatted lists.
19996 (org-set-local
19997 'paragraph-start
19998 (concat
19999 "\f" "\\|"
20000 "[ ]*$" "\\|"
20001 org-outline-regexp "\\|"
20002 "[ \t]*#" "\\|"
20003 (org-item-re) "\\|"
20004 "[ \t]*[:|]" "\\|"
20005 "\\$\\$" "\\|"
20006 "\\\\\\(begin\\|end\\|[][]\\)"))
20007 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
20008 ;; But only if the user has not turned off tables or fixed-width regions
20009 (org-set-local
20010 'auto-fill-inhibit-regexp
20011 (concat org-outline-regexp
20012 "\\|#\\+"
20013 "\\|[ \t]*" org-keyword-time-regexp
20014 (if (or org-enable-table-editor org-enable-fixed-width-editor)
20015 (concat
20016 "\\|[ \t]*["
20017 (if org-enable-table-editor "|" "")
20018 (if org-enable-fixed-width-editor ":" "")
20019 "]"))))
20020 ;; We use our own fill-paragraph function, to make sure that tables
20021 ;; and fixed-width regions are not wrapped. That function will pass
20022 ;; through to `fill-paragraph' when appropriate.
20023 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
20024 ;; Prevent auto-fill from inserting unwanted new items.
20025 (if (boundp 'fill-nobreak-predicate)
20026 (org-set-local 'fill-nobreak-predicate
20027 (if (memq 'org-fill-item-nobreak-p fill-nobreak-predicate)
20028 fill-nobreak-predicate
20029 (cons 'org-fill-item-nobreak-p fill-nobreak-predicate))))
20030 ;; Adaptive filling: To get full control, first make sure that
20031 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
20032 (unless (local-variable-p 'adaptive-fill-regexp (current-buffer))
20033 (org-set-local 'org-adaptive-fill-regexp-backup
20034 adaptive-fill-regexp))
20035 (org-set-local 'adaptive-fill-regexp "\000")
20036 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
20037 (org-set-local 'adaptive-fill-function
20038 'org-adaptive-fill-function)
20039 (org-set-local
20040 'align-mode-rules-list
20041 '((org-in-buffer-settings
20042 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
20043 (modes . '(org-mode))))))
20045 (defun org-fill-item-nobreak-p ()
20046 "Non-nil when a line break at point would insert a new item."
20047 (and (looking-at (org-item-re)) (org-list-in-valid-context-p)))
20049 (defun org-fill-paragraph (&optional justify)
20050 "Re-align a table, pass through to fill-paragraph if no table."
20051 (let ((table-p (org-at-table-p))
20052 (table.el-p (org-at-table.el-p))
20053 (itemp (org-in-item-p)))
20054 (cond ((and (equal (char-after (point-at-bol)) ?*)
20055 (save-excursion (goto-char (point-at-bol))
20056 (looking-at org-outline-regexp)))
20057 t) ; skip headlines
20058 (table.el-p t) ; skip table.el tables
20059 (table-p (org-table-align) t) ; align Org tables
20060 (itemp ; align text in items
20061 (let* ((struct (save-excursion (goto-char itemp)
20062 (org-list-struct)))
20063 (parents (org-list-parents-alist struct))
20064 (children (org-list-get-children itemp struct parents))
20065 beg end prev next prefix)
20066 ;; Determine in which part of item point is: before
20067 ;; first child, after last child, between two
20068 ;; sub-lists, or simply in item if there's no child.
20069 (cond
20070 ((not children)
20071 (setq prefix (make-string (org-list-item-body-column itemp) ?\ )
20072 beg itemp
20073 end (org-list-get-item-end itemp struct)))
20074 ((< (point) (setq next (car children)))
20075 (setq prefix (make-string (org-list-item-body-column itemp) ?\ )
20076 beg itemp
20077 end next))
20078 ((> (point) (setq prev (car (last children))))
20079 (setq beg (org-list-get-item-end prev struct)
20080 end (org-list-get-item-end itemp struct)
20081 prefix (save-excursion
20082 (goto-char beg)
20083 (skip-chars-forward " \t")
20084 (make-string (current-column) ?\ ))))
20085 (t (catch 'exit
20086 (while (setq next (pop children))
20087 (if (> (point) next)
20088 (setq prev next)
20089 (setq beg (org-list-get-item-end prev struct)
20090 end next
20091 prefix (save-excursion
20092 (goto-char beg)
20093 (skip-chars-forward " \t")
20094 (make-string (current-column) ?\ )))
20095 (throw 'exit nil))))))
20096 ;; Use `fill-paragraph' with buffer narrowed to item
20097 ;; without any child, and with our computed PREFIX.
20098 (flet ((fill-context-prefix (from to &optional flr) prefix))
20099 (save-restriction
20100 (narrow-to-region beg end)
20101 (save-excursion (fill-paragraph justify)))) t))
20102 ;; Special case where point is not in a list but is on
20103 ;; a paragraph adjacent to a list: make sure this paragraph
20104 ;; doesn't get merged with the end of the list by narrowing
20105 ;; buffer first.
20106 ((save-excursion (forward-paragraph -1)
20107 (setq itemp (org-in-item-p)))
20108 (let ((struct (save-excursion (goto-char itemp)
20109 (org-list-struct))))
20110 (save-restriction
20111 (narrow-to-region (org-list-get-bottom-point struct)
20112 (save-excursion (forward-paragraph 1)
20113 (point)))
20114 (fill-paragraph justify) t)))
20115 ;; Else simply call `fill-paragraph'.
20116 (t nil))))
20118 ;; For reference, this is the default value of adaptive-fill-regexp
20119 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
20121 (defun org-adaptive-fill-function ()
20122 "Return a fill prefix for org-mode files."
20123 (let (itemp)
20124 (save-excursion
20125 (cond
20126 ;; Comment line
20127 ((looking-at "#[ \t]+")
20128 (match-string-no-properties 0))
20129 ;; Plain list item
20130 ((org-at-item-p)
20131 (make-string (org-list-item-body-column (point-at-bol)) ?\ ))
20132 ;; Point is in a list after `backward-paragraph': original
20133 ;; point wasn't in the list, or filling would have been taken
20134 ;; care of by `org-auto-fill-function', but the list and the
20135 ;; real paragraph are not separated by a blank line. Thus, move
20136 ;; point after the list to go back to real paragraph and
20137 ;; determine fill-prefix.
20138 ((setq itemp (org-in-item-p))
20139 (goto-char itemp)
20140 (let* ((struct (org-list-struct))
20141 (bottom (org-list-get-bottom-point struct)))
20142 (goto-char bottom)
20143 (make-string (org-get-indentation) ?\ )))
20144 ;; Other text
20145 ((looking-at org-adaptive-fill-regexp-backup)
20146 (match-string-no-properties 0))))))
20148 (defun org-auto-fill-function ()
20149 "Auto-fill function."
20150 (let (itemp prefix)
20151 ;; When in a list, compute an appropriate fill-prefix and make
20152 ;; sure it will be used by `do-auto-fill'.
20153 (if (setq itemp (org-in-item-p))
20154 (progn
20155 (setq prefix (make-string (org-list-item-body-column itemp) ?\ ))
20156 (flet ((fill-context-prefix (from to &optional flr) prefix))
20157 (do-auto-fill)))
20158 ;; Else just use `do-auto-fill'.
20159 (do-auto-fill))))
20161 ;;; Other stuff.
20163 (defun org-toggle-fixed-width-section (arg)
20164 "Toggle the fixed-width export.
20165 If there is no active region, the QUOTE keyword at the current headline is
20166 inserted or removed. When present, it causes the text between this headline
20167 and the next to be exported as fixed-width text, and unmodified.
20168 If there is an active region, this command adds or removes a colon as the
20169 first character of this line. If the first character of a line is a colon,
20170 this line is also exported in fixed-width font."
20171 (interactive "P")
20172 (let* ((cc 0)
20173 (regionp (org-region-active-p))
20174 (beg (if regionp (region-beginning) (point)))
20175 (end (if regionp (region-end)))
20176 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
20177 (case-fold-search nil)
20178 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
20179 off)
20180 (if regionp
20181 (save-excursion
20182 (goto-char beg)
20183 (setq cc (current-column))
20184 (beginning-of-line 1)
20185 (setq off (looking-at re))
20186 (while (> nlines 0)
20187 (setq nlines (1- nlines))
20188 (beginning-of-line 1)
20189 (cond
20190 (arg
20191 (org-move-to-column cc t)
20192 (insert ": \n")
20193 (forward-line -1))
20194 ((and off (looking-at re))
20195 (replace-match "" t t nil 1))
20196 ((not off) (org-move-to-column cc t) (insert ": ")))
20197 (forward-line 1)))
20198 (save-excursion
20199 (org-back-to-heading)
20200 (cond
20201 ((looking-at (format org-heading-keyword-regexp-format
20202 org-quote-string))
20203 (goto-char (match-end 1))
20204 (looking-at (concat " +" org-quote-string))
20205 (replace-match "" t t)
20206 (when (eolp) (insert " ")))
20207 ((looking-at org-outline-regexp)
20208 (goto-char (match-end 0))
20209 (insert org-quote-string " ")))))))
20211 (defun org-reftex-citation ()
20212 "Use reftex-citation to insert a citation into the buffer.
20213 This looks for a line like
20215 #+BIBLIOGRAPHY: foo plain option:-d
20217 and derives from it that foo.bib is the bibliography file relevant
20218 for this document. It then installs the necessary environment for RefTeX
20219 to work in this buffer and calls `reftex-citation' to insert a citation
20220 into the buffer.
20222 Export of such citations to both LaTeX and HTML is handled by the contributed
20223 package org-exp-bibtex by Taru Karttunen."
20224 (interactive)
20225 (let ((reftex-docstruct-symbol 'rds)
20226 (reftex-cite-format "\\cite{%l}")
20227 rds bib)
20228 (save-excursion
20229 (save-restriction
20230 (widen)
20231 (let ((case-fold-search t)
20232 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
20233 (if (not (save-excursion
20234 (or (re-search-forward re nil t)
20235 (re-search-backward re nil t))))
20236 (error "No bibliography defined in file")
20237 (setq bib (concat (match-string 1) ".bib")
20238 rds (list (list 'bib bib)))))))
20239 (call-interactively 'reftex-citation)))
20241 ;;;; Functions extending outline functionality
20243 (defun org-beginning-of-line (&optional arg)
20244 "Go to the beginning of the current line. If that is invisible, continue
20245 to a visible line beginning. This makes the function of C-a more intuitive.
20246 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
20247 first attempt, and only move to after the tags when the cursor is already
20248 beyond the end of the headline."
20249 (interactive "P")
20250 (let ((pos (point))
20251 (special (if (consp org-special-ctrl-a/e)
20252 (car org-special-ctrl-a/e)
20253 org-special-ctrl-a/e))
20254 refpos)
20255 (if (org-bound-and-true-p line-move-visual)
20256 (beginning-of-visual-line 1)
20257 (beginning-of-line 1))
20258 (if (and arg (fboundp 'move-beginning-of-line))
20259 (call-interactively 'move-beginning-of-line)
20260 (if (bobp)
20262 (backward-char 1)
20263 (if (org-truely-invisible-p)
20264 (while (and (not (bobp)) (org-truely-invisible-p))
20265 (backward-char 1)
20266 (beginning-of-line 1))
20267 (forward-char 1))))
20268 (when special
20269 (cond
20270 ((and (looking-at org-complex-heading-regexp)
20271 (= (char-after (match-end 1)) ?\ ))
20272 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
20273 (point-at-eol)))
20274 (goto-char
20275 (if (eq special t)
20276 (cond ((> pos refpos) refpos)
20277 ((= pos (point)) refpos)
20278 (t (point)))
20279 (cond ((> pos (point)) (point))
20280 ((not (eq last-command this-command)) (point))
20281 (t refpos)))))
20282 ((org-at-item-p)
20283 (goto-char
20284 (if (eq special t)
20285 (cond ((> pos (match-end 0)) (match-end 0))
20286 ((= pos (point)) (match-end 0))
20287 (t (point)))
20288 (cond ((> pos (point)) (point))
20289 ((not (eq last-command this-command)) (point))
20290 (t (match-end 0))))))))
20291 (org-no-warnings
20292 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
20294 (defun org-end-of-line (&optional arg)
20295 "Go to the end of the line.
20296 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
20297 first attempt, and only move to after the tags when the cursor is already
20298 beyond the end of the headline."
20299 (interactive "P")
20300 (let ((special (if (consp org-special-ctrl-a/e)
20301 (cdr org-special-ctrl-a/e)
20302 org-special-ctrl-a/e)))
20303 (cond
20304 ((or (not special) arg
20305 (not (or (org-on-heading-p) (org-at-item-p))))
20306 (call-interactively
20307 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
20308 ((fboundp 'move-end-of-line) 'move-end-of-line)
20309 (t 'end-of-line))))
20310 ((org-on-heading-p)
20311 (let ((pos (point)))
20312 (beginning-of-line 1)
20313 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
20314 (if (eq special t)
20315 (if (or (< pos (match-beginning 1))
20316 (= pos (match-end 0)))
20317 (goto-char (match-beginning 1))
20318 (goto-char (match-end 0)))
20319 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
20320 (goto-char (match-end 0))
20321 (goto-char (match-beginning 1))))
20322 (call-interactively (if (fboundp 'move-end-of-line)
20323 'move-end-of-line
20324 'end-of-line)))))
20325 ;; At an item: Move before any hidden text.
20326 (t (call-interactively 'end-of-line)))
20327 (org-no-warnings
20328 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
20330 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
20331 (define-key org-mode-map "\C-e" 'org-end-of-line)
20333 (defun org-backward-sentence (&optional arg)
20334 "Go to beginning of sentence, or beginning of table field.
20335 This will call `backward-sentence' or `org-table-beginning-of-field',
20336 depending on context."
20337 (interactive "P")
20338 (cond
20339 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
20340 (t (call-interactively 'backward-sentence))))
20342 (defun org-forward-sentence (&optional arg)
20343 "Go to end of sentence, or end of table field.
20344 This will call `forward-sentence' or `org-table-end-of-field',
20345 depending on context."
20346 (interactive "P")
20347 (cond
20348 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
20349 (t (call-interactively 'forward-sentence))))
20351 (define-key org-mode-map "\M-a" 'org-backward-sentence)
20352 (define-key org-mode-map "\M-e" 'org-forward-sentence)
20354 (defun org-kill-line (&optional arg)
20355 "Kill line, to tags or end of line."
20356 (interactive "P")
20357 (cond
20358 ((or (not org-special-ctrl-k)
20359 (bolp)
20360 (not (org-on-heading-p)))
20361 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
20362 org-ctrl-k-protect-subtree)
20363 (if (or (eq org-ctrl-k-protect-subtree 'error)
20364 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
20365 (error "C-k aborted - would kill hidden subtree")))
20366 (call-interactively 'kill-line))
20367 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
20368 (kill-region (point) (match-beginning 1))
20369 (org-set-tags nil t))
20370 (t (kill-region (point) (point-at-eol)))))
20372 (define-key org-mode-map "\C-k" 'org-kill-line)
20374 (defun org-yank (&optional arg)
20375 "Yank. If the kill is a subtree, treat it specially.
20376 This command will look at the current kill and check if is a single
20377 subtree, or a series of subtrees[1]. If it passes the test, and if the
20378 cursor is at the beginning of a line or after the stars of a currently
20379 empty headline, then the yank is handled specially. How exactly depends
20380 on the value of the following variables, both set by default.
20382 org-yank-folded-subtrees
20383 When set, the subtree(s) will be folded after insertion, but only
20384 if doing so would now swallow text after the yanked text.
20386 org-yank-adjusted-subtrees
20387 When set, the subtree will be promoted or demoted in order to
20388 fit into the local outline tree structure, which means that the level
20389 will be adjusted so that it becomes the smaller one of the two
20390 *visible* surrounding headings.
20392 Any prefix to this command will cause `yank' to be called directly with
20393 no special treatment. In particular, a simple \\[universal-argument] prefix \
20394 will just
20395 plainly yank the text as it is.
20397 \[1] The test checks if the first non-white line is a heading
20398 and if there are no other headings with fewer stars."
20399 (interactive "P")
20400 (org-yank-generic 'yank arg))
20402 (defun org-yank-generic (command arg)
20403 "Perform some yank-like command.
20405 This function implements the behavior described in the `org-yank'
20406 documentation. However, it has been generalized to work for any
20407 interactive command with similar behavior."
20409 ;; pretend to be command COMMAND
20410 (setq this-command command)
20412 (if arg
20413 (call-interactively command)
20415 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
20416 (and (org-kill-is-subtree-p)
20417 (or (bolp)
20418 (and (looking-at "[ \t]*$")
20419 (string-match
20420 "\\`\\*+\\'"
20421 (buffer-substring (point-at-bol) (point)))))))
20422 swallowp)
20423 (cond
20424 ((and subtreep org-yank-folded-subtrees)
20425 (let ((beg (point))
20426 end)
20427 (if (and subtreep org-yank-adjusted-subtrees)
20428 (org-paste-subtree nil nil 'for-yank)
20429 (call-interactively command))
20431 (setq end (point))
20432 (goto-char beg)
20433 (when (and (bolp) subtreep
20434 (not (setq swallowp
20435 (org-yank-folding-would-swallow-text beg end))))
20436 (org-with-limited-levels
20437 (or (looking-at org-outline-regexp)
20438 (re-search-forward org-outline-regexp-bol end t))
20439 (while (and (< (point) end) (looking-at org-outline-regexp))
20440 (hide-subtree)
20441 (org-cycle-show-empty-lines 'folded)
20442 (condition-case nil
20443 (outline-forward-same-level 1)
20444 (error (goto-char end))))))
20445 (when swallowp
20446 (message
20447 "Inserted text not folded because that would swallow text"))
20449 (goto-char end)
20450 (skip-chars-forward " \t\n\r")
20451 (beginning-of-line 1)
20452 (push-mark beg 'nomsg)))
20453 ((and subtreep org-yank-adjusted-subtrees)
20454 (let ((beg (point-at-bol)))
20455 (org-paste-subtree nil nil 'for-yank)
20456 (push-mark beg 'nomsg)))
20458 (call-interactively command))))))
20460 (defun org-yank-folding-would-swallow-text (beg end)
20461 "Would hide-subtree at BEG swallow any text after END?"
20462 (let (level)
20463 (org-with-limited-levels
20464 (save-excursion
20465 (goto-char beg)
20466 (when (or (looking-at org-outline-regexp)
20467 (re-search-forward org-outline-regexp-bol end t))
20468 (setq level (org-outline-level)))
20469 (goto-char end)
20470 (skip-chars-forward " \t\r\n\v\f")
20471 (if (or (eobp)
20472 (and (bolp) (looking-at org-outline-regexp)
20473 (<= (org-outline-level) level)))
20474 nil ; Nothing would be swallowed
20475 t))))) ; something would swallow
20477 (define-key org-mode-map "\C-y" 'org-yank)
20479 (defun org-truely-invisible-p ()
20480 "Check if point is at a character currently not visible.
20481 This version does not only check the character property, but also
20482 `visible-mode'."
20483 ;; Early versions of noutline don't have `outline-invisible-p'.
20484 (if (org-bound-and-true-p visible-mode)
20486 (outline-invisible-p)))
20488 (defun org-invisible-p2 ()
20489 "Check if point is at a character currently not visible."
20490 (save-excursion
20491 (if (and (eolp) (not (bobp))) (backward-char 1))
20492 ;; Early versions of noutline don't have `outline-invisible-p'.
20493 (outline-invisible-p)))
20495 (defun org-back-to-heading (&optional invisible-ok)
20496 "Call `outline-back-to-heading', but provide a better error message."
20497 (condition-case nil
20498 (outline-back-to-heading invisible-ok)
20499 (error (error "Before first headline at position %d in buffer %s"
20500 (point) (current-buffer)))))
20502 (defun org-beginning-of-defun ()
20503 "Go to the beginning of the subtree, i.e. back to the heading."
20504 (org-back-to-heading))
20505 (defun org-end-of-defun ()
20506 "Go to the end of the subtree."
20507 (org-end-of-subtree nil t))
20509 (defun org-before-first-heading-p ()
20510 "Before first heading?"
20511 (save-excursion
20512 (end-of-line)
20513 (null (re-search-backward org-outline-regexp-bol nil t))))
20515 (defun org-on-heading-p (&optional ignored)
20516 (outline-on-heading-p t))
20517 (defun org-at-heading-p (&optional ignored)
20518 (outline-on-heading-p t))
20520 (defun org-point-at-end-of-empty-headline ()
20521 "If point is at the end of an empty headline, return t, else nil.
20522 If the heading only contains a TODO keyword, it is still still considered
20523 empty."
20524 (and (looking-at "[ \t]*$")
20525 (save-excursion
20526 (beginning-of-line 1)
20527 (let ((case-fold-search nil))
20528 (looking-at org-todo-line-regexp)))
20529 (string= (match-string 3) "")))
20531 (defun org-at-heading-or-item-p ()
20532 (or (org-on-heading-p) (org-at-item-p)))
20534 (defun org-on-target-p ()
20535 (or (org-in-regexp org-radio-target-regexp)
20536 (org-in-regexp org-target-regexp)))
20538 (defun org-up-heading-all (arg)
20539 "Move to the heading line of which the present line is a subheading.
20540 This function considers both visible and invisible heading lines.
20541 With argument, move up ARG levels."
20542 (if (fboundp 'outline-up-heading-all)
20543 (outline-up-heading-all arg) ; emacs 21 version of outline.el
20544 (outline-up-heading arg t))) ; emacs 22 version of outline.el
20546 (defun org-up-heading-safe ()
20547 "Move to the heading line of which the present line is a subheading.
20548 This version will not throw an error. It will return the level of the
20549 headline found, or nil if no higher level is found.
20551 Also, this function will be a lot faster than `outline-up-heading',
20552 because it relies on stars being the outline starters. This can really
20553 make a significant difference in outlines with very many siblings."
20554 (let (start-level re)
20555 (org-back-to-heading t)
20556 (setq start-level (funcall outline-level))
20557 (if (equal start-level 1)
20559 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
20560 (if (re-search-backward re nil t)
20561 (funcall outline-level)))))
20563 (defun org-first-sibling-p ()
20564 "Is this heading the first child of its parents?"
20565 (interactive)
20566 (let ((re org-outline-regexp-bol)
20567 level l)
20568 (unless (org-at-heading-p t)
20569 (error "Not at a heading"))
20570 (setq level (funcall outline-level))
20571 (save-excursion
20572 (if (not (re-search-backward re nil t))
20574 (setq l (funcall outline-level))
20575 (< l level)))))
20577 (defun org-goto-sibling (&optional previous)
20578 "Goto the next sibling, even if it is invisible.
20579 When PREVIOUS is set, go to the previous sibling instead. Returns t
20580 when a sibling was found. When none is found, return nil and don't
20581 move point."
20582 (let ((fun (if previous 're-search-backward 're-search-forward))
20583 (pos (point))
20584 (re org-outline-regexp-bol)
20585 level l)
20586 (when (condition-case nil (org-back-to-heading t) (error nil))
20587 (setq level (funcall outline-level))
20588 (catch 'exit
20589 (or previous (forward-char 1))
20590 (while (funcall fun re nil t)
20591 (setq l (funcall outline-level))
20592 (when (< l level) (goto-char pos) (throw 'exit nil))
20593 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
20594 (goto-char pos)
20595 nil))))
20597 (defun org-show-siblings ()
20598 "Show all siblings of the current headline."
20599 (save-excursion
20600 (while (org-goto-sibling) (org-flag-heading nil)))
20601 (save-excursion
20602 (while (org-goto-sibling 'previous)
20603 (org-flag-heading nil))))
20605 (defun org-goto-first-child ()
20606 "Goto the first child, even if it is invisible.
20607 Return t when a child was found. Otherwise don't move point and
20608 return nil."
20609 (let (level (pos (point)) (re org-outline-regexp-bol))
20610 (when (condition-case nil (org-back-to-heading t) (error nil))
20611 (setq level (outline-level))
20612 (forward-char 1)
20613 (if (and (re-search-forward re nil t) (> (outline-level) level))
20614 (progn (goto-char (match-beginning 0)) t)
20615 (goto-char pos) nil))))
20617 (defun org-show-hidden-entry ()
20618 "Show an entry where even the heading is hidden."
20619 (save-excursion
20620 (org-show-entry)))
20622 (defun org-flag-heading (flag &optional entry)
20623 "Flag the current heading. FLAG non-nil means make invisible.
20624 When ENTRY is non-nil, show the entire entry."
20625 (save-excursion
20626 (org-back-to-heading t)
20627 ;; Check if we should show the entire entry
20628 (if entry
20629 (progn
20630 (org-show-entry)
20631 (save-excursion
20632 (and (outline-next-heading)
20633 (org-flag-heading nil))))
20634 (outline-flag-region (max (point-min) (1- (point)))
20635 (save-excursion (outline-end-of-heading) (point))
20636 flag))))
20638 (defun org-get-next-sibling ()
20639 "Move to next heading of the same level, and return point.
20640 If there is no such heading, return nil.
20641 This is like outline-next-sibling, but invisible headings are ok."
20642 (let ((level (funcall outline-level)))
20643 (outline-next-heading)
20644 (while (and (not (eobp)) (> (funcall outline-level) level))
20645 (outline-next-heading))
20646 (if (or (eobp) (< (funcall outline-level) level))
20648 (point))))
20650 (defun org-get-last-sibling ()
20651 "Move to previous heading of the same level, and return point.
20652 If there is no such heading, return nil."
20653 (let ((opoint (point))
20654 (level (funcall outline-level)))
20655 (outline-previous-heading)
20656 (when (and (/= (point) opoint) (outline-on-heading-p t))
20657 (while (and (> (funcall outline-level) level)
20658 (not (bobp)))
20659 (outline-previous-heading))
20660 (if (< (funcall outline-level) level)
20662 (point)))))
20664 (defun org-end-of-subtree (&optional invisible-OK to-heading)
20665 ;; This contains an exact copy of the original function, but it uses
20666 ;; `org-back-to-heading', to make it work also in invisible
20667 ;; trees. And is uses an invisible-OK argument.
20668 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
20669 ;; Furthermore, when used inside Org, finding the end of a large subtree
20670 ;; with many children and grandchildren etc, this can be much faster
20671 ;; than the outline version.
20672 (org-back-to-heading invisible-OK)
20673 (let ((first t)
20674 (level (funcall outline-level)))
20675 (if (and (eq major-mode 'org-mode) (< level 1000))
20676 ;; A true heading (not a plain list item), in Org-mode
20677 ;; This means we can easily find the end by looking
20678 ;; only for the right number of stars. Using a regexp to do
20679 ;; this is so much faster than using a Lisp loop.
20680 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
20681 (forward-char 1)
20682 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
20683 ;; something else, do it the slow way
20684 (while (and (not (eobp))
20685 (or first (> (funcall outline-level) level)))
20686 (setq first nil)
20687 (outline-next-heading)))
20688 (unless to-heading
20689 (if (memq (preceding-char) '(?\n ?\^M))
20690 (progn
20691 ;; Go to end of line before heading
20692 (forward-char -1)
20693 (if (memq (preceding-char) '(?\n ?\^M))
20694 ;; leave blank line before heading
20695 (forward-char -1))))))
20696 (point))
20698 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
20699 "Use Org version in org-mode, for dramatic speed-up."
20700 (if (eq major-mode 'org-mode)
20701 (progn
20702 (org-end-of-subtree nil t)
20703 (unless (eobp) (backward-char 1)))
20704 ad-do-it))
20706 (defun org-end-of-meta-data-and-drawers ()
20707 "Jump to the first text after meta data and drawers in the current entry.
20708 This will move over empty lines, lines with planning time stamps,
20709 clocking lines, and drawers."
20710 (org-back-to-heading t)
20711 (let ((end (save-excursion (outline-next-heading) (point)))
20712 (re (concat "\\(" org-drawer-regexp "\\)"
20713 "\\|" "[ \t]*" org-keyword-time-regexp)))
20714 (forward-line 1)
20715 (while (re-search-forward re end t)
20716 (if (not (match-end 1))
20717 ;; empty or planning line
20718 (forward-line 1)
20719 ;; a drawer, find the end
20720 (re-search-forward "^[ \t]*:END:" end 'move)
20721 (forward-line 1)))
20722 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
20723 (point)))
20725 (defun org-forward-same-level (arg &optional invisible-ok)
20726 "Move forward to the arg'th subheading at same level as this one.
20727 Stop at the first and last subheadings of a superior heading.
20728 Normally this only looks at visible headings, but when INVISIBLE-OK is non-nil
20729 it wil also look at invisible ones."
20730 (interactive "p")
20731 (org-back-to-heading invisible-ok)
20732 (org-on-heading-p)
20733 (let* ((level (- (match-end 0) (match-beginning 0) 1))
20734 (re (format "^\\*\\{1,%d\\} " level))
20736 (forward-char 1)
20737 (while (> arg 0)
20738 (while (and (re-search-forward re nil 'move)
20739 (setq l (- (match-end 0) (match-beginning 0) 1))
20740 (= l level)
20741 (not invisible-ok)
20742 (progn (backward-char 1) (outline-invisible-p)))
20743 (if (< l level) (setq arg 1)))
20744 (setq arg (1- arg)))
20745 (beginning-of-line 1)))
20747 (defun org-backward-same-level (arg &optional invisible-ok)
20748 "Move backward to the arg'th subheading at same level as this one.
20749 Stop at the first and last subheadings of a superior heading."
20750 (interactive "p")
20751 (org-back-to-heading)
20752 (org-on-heading-p)
20753 (let* ((level (- (match-end 0) (match-beginning 0) 1))
20754 (re (format "^\\*\\{1,%d\\} " level))
20756 (while (> arg 0)
20757 (while (and (re-search-backward re nil 'move)
20758 (setq l (- (match-end 0) (match-beginning 0) 1))
20759 (= l level)
20760 (not invisible-ok)
20761 (outline-invisible-p))
20762 (if (< l level) (setq arg 1)))
20763 (setq arg (1- arg)))))
20765 (defun org-show-subtree ()
20766 "Show everything after this heading at deeper levels."
20767 (outline-flag-region
20768 (point)
20769 (save-excursion
20770 (org-end-of-subtree t t))
20771 nil))
20773 (defun org-show-entry ()
20774 "Show the body directly following this heading.
20775 Show the heading too, if it is currently invisible."
20776 (interactive)
20777 (save-excursion
20778 (condition-case nil
20779 (progn
20780 (org-back-to-heading t)
20781 (outline-flag-region
20782 (max (point-min) (1- (point)))
20783 (save-excursion
20784 (if (re-search-forward
20785 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
20786 (match-beginning 1)
20787 (point-max)))
20788 nil)
20789 (org-cycle-hide-drawers 'children))
20790 (error nil))))
20792 (defun org-make-options-regexp (kwds &optional extra)
20793 "Make a regular expression for keyword lines."
20794 (concat
20796 "#?[ \t]*\\+\\("
20797 (mapconcat 'regexp-quote kwds "\\|")
20798 (if extra (concat "\\|" extra))
20799 "\\):[ \t]*"
20800 "\\(.*\\)"))
20802 ;; Make isearch reveal the necessary context
20803 (defun org-isearch-end ()
20804 "Reveal context after isearch exits."
20805 (when isearch-success ; only if search was successful
20806 (if (featurep 'xemacs)
20807 ;; Under XEmacs, the hook is run in the correct place,
20808 ;; we directly show the context.
20809 (org-show-context 'isearch)
20810 ;; In Emacs the hook runs *before* restoring the overlays.
20811 ;; So we have to use a one-time post-command-hook to do this.
20812 ;; (Emacs 22 has a special variable, see function `org-mode')
20813 (unless (and (boundp 'isearch-mode-end-hook-quit)
20814 isearch-mode-end-hook-quit)
20815 ;; Only when the isearch was not quitted.
20816 (org-add-hook 'post-command-hook 'org-isearch-post-command
20817 'append 'local)))))
20819 (defun org-isearch-post-command ()
20820 "Remove self from hook, and show context."
20821 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
20822 (org-show-context 'isearch))
20825 ;;;; Integration with and fixes for other packages
20827 ;;; Imenu support
20829 (defvar org-imenu-markers nil
20830 "All markers currently used by Imenu.")
20831 (make-variable-buffer-local 'org-imenu-markers)
20833 (defun org-imenu-new-marker (&optional pos)
20834 "Return a new marker for use by Imenu, and remember the marker."
20835 (let ((m (make-marker)))
20836 (move-marker m (or pos (point)))
20837 (push m org-imenu-markers)
20840 (defun org-imenu-get-tree ()
20841 "Produce the index for Imenu."
20842 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
20843 (setq org-imenu-markers nil)
20844 (let* ((n org-imenu-depth)
20845 (re (concat "^" (org-get-limited-outline-regexp)))
20846 (subs (make-vector (1+ n) nil))
20847 (last-level 0)
20848 m level head)
20849 (save-excursion
20850 (save-restriction
20851 (widen)
20852 (goto-char (point-max))
20853 (while (re-search-backward re nil t)
20854 (setq level (org-reduced-level (funcall outline-level)))
20855 (when (<= level n)
20856 (looking-at org-complex-heading-regexp)
20857 (setq head (org-link-display-format
20858 (org-match-string-no-properties 4))
20859 m (org-imenu-new-marker))
20860 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
20861 (if (>= level last-level)
20862 (push (cons head m) (aref subs level))
20863 (push (cons head (aref subs (1+ level))) (aref subs level))
20864 (loop for i from (1+ level) to n do (aset subs i nil)))
20865 (setq last-level level)))))
20866 (aref subs 1)))
20868 (eval-after-load "imenu"
20869 '(progn
20870 (add-hook 'imenu-after-jump-hook
20871 (lambda ()
20872 (if (eq major-mode 'org-mode)
20873 (org-show-context 'org-goto))))))
20875 (defun org-link-display-format (link)
20876 "Replace a link with either the description, or the link target
20877 if no description is present"
20878 (save-match-data
20879 (if (string-match org-bracket-link-analytic-regexp link)
20880 (replace-match (if (match-end 5)
20881 (match-string 5 link)
20882 (concat (match-string 1 link)
20883 (match-string 3 link)))
20884 nil t link)
20885 link)))
20887 (defun org-toggle-link-display ()
20888 "Toggle the literal or descriptive display of links."
20889 (interactive)
20890 (if org-descriptive-links
20891 (progn (org-remove-from-invisibility-spec '(org-link))
20892 (org-restart-font-lock)
20893 (setq org-descriptive-links nil))
20894 (progn (add-to-invisibility-spec '(org-link))
20895 (org-restart-font-lock)
20896 (setq org-descriptive-links t))))
20898 ;; Speedbar support
20900 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
20901 "Overlay marking the agenda restriction line in speedbar.")
20902 (overlay-put org-speedbar-restriction-lock-overlay
20903 'face 'org-agenda-restriction-lock)
20904 (overlay-put org-speedbar-restriction-lock-overlay
20905 'help-echo "Agendas are currently limited to this item.")
20906 (org-detach-overlay org-speedbar-restriction-lock-overlay)
20908 (defun org-speedbar-set-agenda-restriction ()
20909 "Restrict future agenda commands to the location at point in speedbar.
20910 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
20911 (interactive)
20912 (require 'org-agenda)
20913 (let (p m tp np dir txt)
20914 (cond
20915 ((setq p (text-property-any (point-at-bol) (point-at-eol)
20916 'org-imenu t))
20917 (setq m (get-text-property p 'org-imenu-marker))
20918 (with-current-buffer (marker-buffer m)
20919 (goto-char m)
20920 (org-agenda-set-restriction-lock 'subtree)))
20921 ((setq p (text-property-any (point-at-bol) (point-at-eol)
20922 'speedbar-function 'speedbar-find-file))
20923 (setq tp (previous-single-property-change
20924 (1+ p) 'speedbar-function)
20925 np (next-single-property-change
20926 tp 'speedbar-function)
20927 dir (speedbar-line-directory)
20928 txt (buffer-substring-no-properties (or tp (point-min))
20929 (or np (point-max))))
20930 (with-current-buffer (find-file-noselect
20931 (let ((default-directory dir))
20932 (expand-file-name txt)))
20933 (unless (eq major-mode 'org-mode)
20934 (error "Cannot restrict to non-Org-mode file"))
20935 (org-agenda-set-restriction-lock 'file)))
20936 (t (error "Don't know how to restrict Org-mode's agenda")))
20937 (move-overlay org-speedbar-restriction-lock-overlay
20938 (point-at-bol) (point-at-eol))
20939 (setq current-prefix-arg nil)
20940 (org-agenda-maybe-redo)))
20942 (eval-after-load "speedbar"
20943 '(progn
20944 (speedbar-add-supported-extension ".org")
20945 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
20946 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
20947 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
20948 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
20949 (add-hook 'speedbar-visiting-tag-hook
20950 (lambda () (and (eq major-mode 'org-mode) (org-show-context 'org-goto))))))
20952 ;;; Fixes and Hacks for problems with other packages
20954 ;; Make flyspell not check words in links, to not mess up our keymap
20955 (defun org-mode-flyspell-verify ()
20956 "Don't let flyspell put overlays at active buttons, or on
20957 {todo,all-time,additional-option-like}-keywords."
20958 (let ((pos (max (1- (point)) (point-min)))
20959 (word (thing-at-point 'word)))
20960 (and (not (get-text-property pos 'keymap))
20961 (not (get-text-property pos 'org-no-flyspell))
20962 (not (member word org-todo-keywords-1))
20963 (not (member word org-all-time-keywords))
20964 (not (member word org-additional-option-like-keywords)))))
20966 (defun org-remove-flyspell-overlays-in (beg end)
20967 "Remove flyspell overlays in region."
20968 (and (org-bound-and-true-p flyspell-mode)
20969 (fboundp 'flyspell-delete-region-overlays)
20970 (flyspell-delete-region-overlays beg end))
20971 (add-text-properties beg end '(org-no-flyspell t)))
20973 ;; Make `bookmark-jump' shows the jump location if it was hidden.
20974 (eval-after-load "bookmark"
20975 '(if (boundp 'bookmark-after-jump-hook)
20976 ;; We can use the hook
20977 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
20978 ;; Hook not available, use advice
20979 (defadvice bookmark-jump (after org-make-visible activate)
20980 "Make the position visible."
20981 (org-bookmark-jump-unhide))))
20983 ;; Make sure saveplace shows the location if it was hidden
20984 (eval-after-load "saveplace"
20985 '(defadvice save-place-find-file-hook (after org-make-visible activate)
20986 "Make the position visible."
20987 (org-bookmark-jump-unhide)))
20989 ;; Make sure ecb shows the location if it was hidden
20990 (eval-after-load "ecb"
20991 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
20992 "Make hierarchy visible when jumping into location from ECB tree buffer."
20993 (if (eq major-mode 'org-mode)
20994 (org-show-context))))
20996 (defun org-bookmark-jump-unhide ()
20997 "Unhide the current position, to show the bookmark location."
20998 (and (eq major-mode 'org-mode)
20999 (or (outline-invisible-p)
21000 (save-excursion (goto-char (max (point-min) (1- (point))))
21001 (outline-invisible-p)))
21002 (org-show-context 'bookmark-jump)))
21004 ;; Make session.el ignore our circular variable
21005 (eval-after-load "session"
21006 '(add-to-list 'session-globals-exclude 'org-mark-ring))
21008 ;;;; Experimental code
21010 (defun org-closed-in-range ()
21011 "Sparse tree of items closed in a certain time range.
21012 Still experimental, may disappear in the future."
21013 (interactive)
21014 ;; Get the time interval from the user.
21015 (let* ((time1 (org-float-time
21016 (org-read-date nil 'to-time nil "Starting date: ")))
21017 (time2 (org-float-time
21018 (org-read-date nil 'to-time nil "End date:")))
21019 ;; callback function
21020 (callback (lambda ()
21021 (let ((time
21022 (org-float-time
21023 (apply 'encode-time
21024 (org-parse-time-string
21025 (match-string 1))))))
21026 ;; check if time in interval
21027 (and (>= time time1) (<= time time2))))))
21028 ;; make tree, check each match with the callback
21029 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
21031 ;;;; Finish up
21033 (provide 'org)
21035 (run-hooks 'org-load-hook)
21037 ;;; org.el ends here