show installation path or org-install.el to avoid mishaps with multiple installations
[org-mode.git] / lisp / org.el
blob13801484cffd5ed283d057808fa4d6a8ae49f724
1 ;;; org.el --- Outline-based notes management and organizer
3 ;; Carstens outline-mode for keeping track of everything.
4 ;; Copyright (C) 2004-2012 Free Software Foundation, Inc.
5 ;;
6 ;; Author: Carsten Dominik <carsten at orgmode dot org>
7 ;; Maintainer: Bastien Guerry <bzg at gnu dot org>
8 ;; Keywords: outlines, hypermedia, calendar, wp
9 ;; Homepage: http://orgmode.org
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)
78 (require 'format-spec)
80 ;; Emacs 22 calendar compatibility: Make sure the new variables are available
81 (when (fboundp 'defvaralias)
82 (unless (boundp 'calendar-view-holidays-initially-flag)
83 (defvaralias 'calendar-view-holidays-initially-flag
84 'view-calendar-holidays-initially))
85 (unless (boundp 'calendar-view-diary-initially-flag)
86 (defvaralias 'calendar-view-diary-initially-flag
87 'view-diary-entries-initially))
88 (unless (boundp 'diary-fancy-buffer)
89 (defvaralias 'diary-fancy-buffer 'fancy-diary-buffer)))
91 (require 'outline) (require 'noutline)
92 ;; Other stuff we need.
93 (require 'time-date)
94 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
95 (require 'easymenu)
96 (require 'overlay)
98 (require 'org-macs)
99 (require 'org-entities)
100 (require 'org-compat)
101 (require 'org-faces)
102 (require 'org-list)
103 (require 'org-pcomplete)
104 (require 'org-src)
105 (require 'org-footnote)
107 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
108 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
109 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
110 (declare-function org-pop-to-buffer-same-window "org-compat" (&optional buffer-or-name norecord label))
111 (declare-function org-at-clock-log-p "org-clock" ())
112 (declare-function org-clock-timestamps-up "org-clock" ())
113 (declare-function org-clock-timestamps-down "org-clock" ())
114 (declare-function find-library-name "find-func")
116 ;; babel
117 (require 'ob)
118 (require 'ob-table)
119 (require 'ob-lob)
120 (require 'ob-ref)
121 (require 'ob-tangle)
122 (require 'ob-comint)
123 (require 'ob-keys)
125 ;; load languages based on value of `org-babel-load-languages'
126 (defvar org-babel-load-languages)
127 ;;;###autoload
128 (defun org-babel-do-load-languages (sym value)
129 "Load the languages defined in `org-babel-load-languages'."
130 (set-default sym value)
131 (mapc (lambda (pair)
132 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
133 (if active
134 (progn
135 (require (intern (concat "ob-" lang))))
136 (progn
137 (funcall 'fmakunbound
138 (intern (concat "org-babel-execute:" lang)))
139 (funcall 'fmakunbound
140 (intern (concat "org-babel-expand-body:" lang)))))))
141 org-babel-load-languages))
143 (defcustom org-babel-load-languages '((emacs-lisp . t))
144 "Languages which can be evaluated in Org-mode buffers.
145 This list can be used to load support for any of the languages
146 below, note that each language will depend on a different set of
147 system executables and/or Emacs modes. When a language is
148 \"loaded\", then code blocks in that language can be evaluated
149 with `org-babel-execute-src-block' bound by default to C-c
150 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
151 be set to remove code block evaluation from the C-c C-c
152 keybinding. By default only Emacs Lisp (which has no
153 requirements) is loaded."
154 :group 'org-babel
155 :set 'org-babel-do-load-languages
156 :version "24.1"
157 :type '(alist :tag "Babel Languages"
158 :key-type
159 (choice
160 (const :tag "Awk" awk)
161 (const :tag "C" C)
162 (const :tag "R" R)
163 (const :tag "Asymptote" asymptote)
164 (const :tag "Calc" calc)
165 (const :tag "Clojure" clojure)
166 (const :tag "CSS" css)
167 (const :tag "Ditaa" ditaa)
168 (const :tag "Dot" dot)
169 (const :tag "Emacs Lisp" emacs-lisp)
170 (const :tag "Fortran" fortran)
171 (const :tag "Gnuplot" gnuplot)
172 (const :tag "Haskell" haskell)
173 (const :tag "IO" io)
174 (const :tag "Java" java)
175 (const :tag "Javascript" js)
176 (const :tag "LaTeX" latex)
177 (const :tag "Ledger" ledger)
178 (const :tag "Lilypond" lilypond)
179 (const :tag "Maxima" maxima)
180 (const :tag "Matlab" matlab)
181 (const :tag "Mscgen" mscgen)
182 (const :tag "Ocaml" ocaml)
183 (const :tag "Octave" octave)
184 (const :tag "Org" org)
185 (const :tag "Perl" perl)
186 (const :tag "Pico Lisp" picolisp)
187 (const :tag "PlantUML" plantuml)
188 (const :tag "Python" python)
189 (const :tag "Ruby" ruby)
190 (const :tag "Sass" sass)
191 (const :tag "Scala" scala)
192 (const :tag "Scheme" scheme)
193 (const :tag "Screen" screen)
194 (const :tag "Shell Script" sh)
195 (const :tag "Shen" shen)
196 (const :tag "Sql" sql)
197 (const :tag "Sqlite" sqlite))
198 :value-type (boolean :tag "Activate" :value t)))
200 ;;;; Customization variables
201 (defcustom org-clone-delete-id nil
202 "Remove ID property of clones of a subtree.
203 When non-nil, clones of a subtree don't inherit the ID property.
204 Otherwise they inherit the ID property with a new unique
205 identifier."
206 :type 'boolean
207 :version "24.1"
208 :group 'org-id)
210 ;;; Version
212 ;;;###autoload
213 (defun org-version (&optional here)
214 "Show the org-mode version in the echo area.
215 With prefix arg HERE, insert it at point."
216 (interactive "P")
217 (let* ((origin default-directory)
218 (version (if (boundp 'org-release) org-release "N/A"))
219 (git-version (if (boundp 'org-git-version) org-git-version "N/A"))
220 (org-install (ignore-errors (find-library-name "org-install"))))
221 (setq version (format "Org-mode version %s (%s @ %s)"
222 version
223 git-version
224 (if org-install org-install "org-install.el can not be found!")))
225 (if here (insert version))
226 (message version)))
228 ;;; Compatibility constants
230 ;;; The custom variables
232 (defgroup org nil
233 "Outline-based notes management and organizer."
234 :tag "Org"
235 :group 'outlines
236 :group 'calendar)
238 (defcustom org-mode-hook nil
239 "Mode hook for Org-mode, run after the mode was turned on."
240 :group 'org
241 :type 'hook)
243 (defcustom org-load-hook nil
244 "Hook that is run after org.el has been loaded."
245 :group 'org
246 :type 'hook)
248 (defcustom org-log-buffer-setup-hook nil
249 "Hook that is run after an Org log buffer is created."
250 :group 'org
251 :version "24.1"
252 :type 'hook)
254 (defvar org-modules) ; defined below
255 (defvar org-modules-loaded nil
256 "Have the modules been loaded already?")
258 (defun org-load-modules-maybe (&optional force)
259 "Load all extensions listed in `org-modules'."
260 (when (or force (not org-modules-loaded))
261 (mapc (lambda (ext)
262 (condition-case nil (require ext)
263 (error (message "Problems while trying to load feature `%s'" ext))))
264 org-modules)
265 (setq org-modules-loaded t)))
267 (defun org-set-modules (var value)
268 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
269 (set var value)
270 (when (featurep 'org)
271 (org-load-modules-maybe 'force)))
273 (when (org-bound-and-true-p org-modules)
274 (let ((a (member 'org-infojs org-modules)))
275 (and a (setcar a 'org-jsinfo))))
277 (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)
278 "Modules that should always be loaded together with org.el.
279 If a description starts with <C>, the file is not part of Emacs
280 and loading it will require that you have downloaded and properly installed
281 the org-mode distribution.
283 You can also use this system to load external packages (i.e. neither Org
284 core modules, nor modules from the CONTRIB directory). Just add symbols
285 to the end of the list. If the package is called org-xyz.el, then you need
286 to add the symbol `xyz', and the package must have a call to
288 (provide 'org-xyz)"
289 :group 'org
290 :set 'org-set-modules
291 :type
292 '(set :greedy t
293 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
294 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
295 (const :tag " crypt: Encryption of subtrees" org-crypt)
296 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
297 (const :tag " docview: Links to doc-view buffers" org-docview)
298 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
299 (const :tag " id: Global IDs for identifying entries" org-id)
300 (const :tag " info: Links to Info nodes" org-info)
301 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
302 (const :tag " habit: Track your consistency with habits" org-habit)
303 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
304 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
305 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
306 (const :tag " mew Links to Mew folders/messages" org-mew)
307 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
308 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
309 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
310 (const :tag " special-blocks: Turn blocks into LaTeX envs and HTML divs" org-special-blocks)
311 (const :tag " vm: Links to VM folders/messages" org-vm)
312 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
313 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
314 (const :tag " mouse: Additional mouse support" org-mouse)
315 (const :tag " TaskJuggler: Export tasks to a TaskJuggler project" org-taskjuggler)
317 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
318 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
319 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
320 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
321 (const :tag "C collector: Collect properties into tables" org-collector)
322 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
323 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
324 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
325 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
326 (const :tag "C eval: Include command output as text" org-eval)
327 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
328 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
329 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
330 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
331 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
333 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
335 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
336 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
337 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
338 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
339 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
340 (const :tag "C mac-link-grabber Grab links and URLs from various Mac applications" org-mac-link-grabber)
341 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
342 (const :tag "C mtags: Support for muse-like tags" org-mtags)
343 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
344 (const :tag "C registry: A registry for Org-mode links" org-registry)
345 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
346 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
347 (const :tag "C secretary: Team management with org-mode" org-secretary)
348 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
349 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
350 (const :tag "C track: Keep up with Org-mode development" org-track)
351 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
352 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
353 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
355 (defcustom org-support-shift-select nil
356 "Non-nil means make shift-cursor commands select text when possible.
358 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
359 start selecting a region, or enlarge regions started in this way.
360 In Org-mode, in special contexts, these same keys are used for
361 other purposes, important enough to compete with shift selection.
362 Org tries to balance these needs by supporting `shift-select-mode'
363 outside these special contexts, under control of this variable.
365 The default of this variable is nil, to avoid confusing behavior. Shifted
366 cursor keys will then execute Org commands in the following contexts:
367 - on a headline, changing TODO state (left/right) and priority (up/down)
368 - on a time stamp, changing the time
369 - in a plain list item, changing the bullet type
370 - in a property definition line, switching between allowed values
371 - in the BEGIN line of a clock table (changing the time block).
372 Outside these contexts, the commands will throw an error.
374 When this variable is t and the cursor is not in a special
375 context, Org-mode will support shift-selection for making and
376 enlarging regions. To make this more effective, the bullet
377 cycling will no longer happen anywhere in an item line, but only
378 if the cursor is exactly on the bullet.
380 If you set this variable to the symbol `always', then the keys
381 will not be special in headlines, property lines, and item lines,
382 to make shift selection work there as well. If this is what you
383 want, you can use the following alternative commands: `C-c C-t'
384 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
385 can be used to switch TODO sets, `C-c -' to cycle item bullet
386 types, and properties can be edited by hand or in column view.
388 However, when the cursor is on a timestamp, shift-cursor commands
389 will still edit the time stamp - this is just too good to give up.
391 XEmacs user should have this variable set to nil, because
392 `shift-select-mode' is in Emacs 23 or later only."
393 :group 'org
394 :type '(choice
395 (const :tag "Never" nil)
396 (const :tag "When outside special context" t)
397 (const :tag "Everywhere except timestamps" always)))
399 (defcustom org-loop-over-headlines-in-active-region nil
400 "Shall some commands act upon headlines in the active region?
402 When set to `t', some commands will be performed in all headlines
403 within the active region.
405 When set to `start-level', some commands will be performed in all
406 headlines within the active region, provided that these headlines
407 are of the same level than the first one.
409 When set to a string, those commands will be performed on the
410 matching headlines within the active region. Such string must be
411 a tags/property/todo match as it is used in the agenda tags view.
413 The list of commands is: `org-schedule', `org-deadline',
414 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
415 `org-archive-to-archive-sibling'. The archiving commands skip
416 already archived entries."
417 :type '(choice (const :tag "Don't loop" nil)
418 (const :tag "All headlines in active region" t)
419 (const :tag "In active region, headlines at the same level than the first one" 'start-level)
420 (string :tag "Tags/Property/Todo matcher"))
421 :version "24.1"
422 :group 'org-todo
423 :group 'org-archive)
425 (defgroup org-startup nil
426 "Options concerning startup of Org-mode."
427 :tag "Org Startup"
428 :group 'org)
430 (defcustom org-startup-folded t
431 "Non-nil means entering Org-mode will switch to OVERVIEW.
432 This can also be configured on a per-file basis by adding one of
433 the following lines anywhere in the buffer:
435 #+STARTUP: fold (or `overview', this is equivalent)
436 #+STARTUP: nofold (or `showall', this is equivalent)
437 #+STARTUP: content
438 #+STARTUP: showeverything"
439 :group 'org-startup
440 :type '(choice
441 (const :tag "nofold: show all" nil)
442 (const :tag "fold: overview" t)
443 (const :tag "content: all headlines" content)
444 (const :tag "show everything, even drawers" showeverything)))
446 (defcustom org-startup-truncated t
447 "Non-nil means entering Org-mode will set `truncate-lines'.
448 This is useful since some lines containing links can be very long and
449 uninteresting. Also tables look terrible when wrapped."
450 :group 'org-startup
451 :type 'boolean)
453 (defcustom org-startup-indented nil
454 "Non-nil means turn on `org-indent-mode' on startup.
455 This can also be configured on a per-file basis by adding one of
456 the following lines anywhere in the buffer:
458 #+STARTUP: indent
459 #+STARTUP: noindent"
460 :group 'org-structure
461 :type '(choice
462 (const :tag "Not" nil)
463 (const :tag "Globally (slow on startup in large files)" t)))
465 (defcustom org-use-sub-superscripts t
466 "Non-nil means interpret \"_\" and \"^\" for export.
467 When this option is turned on, you can use TeX-like syntax for sub- and
468 superscripts. Several characters after \"_\" or \"^\" will be
469 considered as a single item - so grouping with {} is normally not
470 needed. For example, the following things will be parsed as single
471 sub- or superscripts.
473 10^24 or 10^tau several digits will be considered 1 item.
474 10^-12 or 10^-tau a leading sign with digits or a word
475 x^2-y^3 will be read as x^2 - y^3, because items are
476 terminated by almost any nonword/nondigit char.
477 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
479 Still, ambiguity is possible - so when in doubt use {} to enclose the
480 sub/superscript. If you set this variable to the symbol `{}',
481 the braces are *required* in order to trigger interpretations as
482 sub/superscript. This can be helpful in documents that need \"_\"
483 frequently in plain text.
485 Not all export backends support this, but HTML does.
487 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
488 :group 'org-startup
489 :group 'org-export-translation
490 :version "24.1"
491 :type '(choice
492 (const :tag "Always interpret" t)
493 (const :tag "Only with braces" {})
494 (const :tag "Never interpret" nil)))
496 (if (fboundp 'defvaralias)
497 (defvaralias 'org-export-with-sub-superscripts 'org-use-sub-superscripts))
500 (defcustom org-startup-with-beamer-mode nil
501 "Non-nil means turn on `org-beamer-mode' on startup.
502 This can also be configured on a per-file basis by adding one of
503 the following lines anywhere in the buffer:
505 #+STARTUP: beamer"
506 :group 'org-startup
507 :version "24.1"
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 :version "24.1"
529 :type 'boolean)
531 (defcustom org-insert-mode-line-in-empty-file nil
532 "Non-nil means insert the first line setting Org-mode in empty files.
533 When the function `org-mode' is called interactively in an empty file, this
534 normally means that the file name does not automatically trigger Org-mode.
535 To ensure that the file will always be in Org-mode in the future, a
536 line enforcing Org-mode will be inserted into the buffer, if this option
537 has been set."
538 :group 'org-startup
539 :type 'boolean)
541 (defcustom org-replace-disputed-keys nil
542 "Non-nil means use alternative key bindings for some keys.
543 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
544 These keys are also used by other packages like shift-selection-mode'
545 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
546 If you want to use Org-mode together with one of these other modes,
547 or more generally if you would like to move some Org-mode commands to
548 other keys, set this variable and configure the keys with the variable
549 `org-disputed-keys'.
551 This option is only relevant at load-time of Org-mode, and must be set
552 *before* org.el is loaded. Changing it requires a restart of Emacs to
553 become effective."
554 :group 'org-startup
555 :type 'boolean)
557 (defcustom org-use-extra-keys nil
558 "Non-nil means use extra key sequence definitions for certain commands.
559 This happens automatically if you run XEmacs or if `window-system'
560 is nil. This variable lets you do the same manually. You must
561 set it before loading org.
563 Example: on Carbon Emacs 22 running graphically, with an external
564 keyboard on a Powerbook, the default way of setting M-left might
565 not work for either Alt or ESC. Setting this variable will make
566 it work for ESC."
567 :group 'org-startup
568 :type 'boolean)
570 (if (fboundp 'defvaralias)
571 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
573 (defcustom org-disputed-keys
574 '(([(shift up)] . [(meta p)])
575 ([(shift down)] . [(meta n)])
576 ([(shift left)] . [(meta -)])
577 ([(shift right)] . [(meta +)])
578 ([(control shift right)] . [(meta shift +)])
579 ([(control shift left)] . [(meta shift -)]))
580 "Keys for which Org-mode and other modes compete.
581 This is an alist, cars are the default keys, second element specifies
582 the alternative to use when `org-replace-disputed-keys' is t.
584 Keys can be specified in any syntax supported by `define-key'.
585 The value of this option takes effect only at Org-mode's startup,
586 therefore you'll have to restart Emacs to apply it after changing."
587 :group 'org-startup
588 :type 'alist)
590 (defun org-key (key)
591 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
592 Or return the original if not disputed.
593 Also apply the translations defined in `org-xemacs-key-equivalents'."
594 (when org-replace-disputed-keys
595 (let* ((nkey (key-description key))
596 (x (org-find-if (lambda (x)
597 (equal (key-description (car x)) nkey))
598 org-disputed-keys)))
599 (setq key (if x (cdr x) key))))
600 (when (featurep 'xemacs)
601 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
602 key)
604 (defun org-find-if (predicate seq)
605 (catch 'exit
606 (while seq
607 (if (funcall predicate (car seq))
608 (throw 'exit (car seq))
609 (pop seq)))))
611 (defun org-defkey (keymap key def)
612 "Define a key, possibly translated, as returned by `org-key'."
613 (define-key keymap (org-key key) def))
615 (defcustom org-ellipsis nil
616 "The ellipsis to use in the Org-mode outline.
617 When nil, just use the standard three dots. When a string, use that instead,
618 When a face, use the standard 3 dots, but with the specified face.
619 The change affects only Org-mode (which will then use its own display table).
620 Changing this requires executing `M-x org-mode' in a buffer to become
621 effective."
622 :group 'org-startup
623 :type '(choice (const :tag "Default" nil)
624 (face :tag "Face" :value org-warning)
625 (string :tag "String" :value "...#")))
627 (defvar org-display-table nil
628 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
630 (defgroup org-keywords nil
631 "Keywords in Org-mode."
632 :tag "Org Keywords"
633 :group 'org)
635 (defcustom org-deadline-string "DEADLINE:"
636 "String to mark deadline entries.
637 A deadline is this string, followed by a time stamp. Should be a word,
638 terminated by a colon. You can insert a schedule keyword and
639 a timestamp with \\[org-deadline].
640 Changes become only effective after restarting Emacs."
641 :group 'org-keywords
642 :type 'string)
644 (defcustom org-scheduled-string "SCHEDULED:"
645 "String to mark scheduled TODO entries.
646 A schedule is this string, followed by a time stamp. Should be a word,
647 terminated by a colon. You can insert a schedule keyword and
648 a timestamp with \\[org-schedule].
649 Changes become only effective after restarting Emacs."
650 :group 'org-keywords
651 :type 'string)
653 (defcustom org-closed-string "CLOSED:"
654 "String used as the prefix for timestamps logging closing a TODO entry."
655 :group 'org-keywords
656 :type 'string)
658 (defcustom org-clock-string "CLOCK:"
659 "String used as prefix for timestamps clocking work hours on an item."
660 :group 'org-keywords
661 :type 'string)
663 (defcustom org-comment-string "COMMENT"
664 "Entries starting with this keyword will never be exported.
665 An entry can be toggled between COMMENT and normal with
666 \\[org-toggle-comment].
667 Changes become only effective after restarting Emacs."
668 :group 'org-keywords
669 :type 'string)
671 (defcustom org-quote-string "QUOTE"
672 "Entries starting with this keyword will be exported in fixed-width font.
673 Quoting applies only to the text in the entry following the headline, and does
674 not extend beyond the next headline, even if that is lower level.
675 An entry can be toggled between QUOTE and normal with
676 \\[org-toggle-fixed-width-section]."
677 :group 'org-keywords
678 :type 'string)
680 (defconst org-repeat-re
681 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)"
682 "Regular expression for specifying repeated events.
683 After a match, group 1 contains the repeat expression.")
685 (defgroup org-structure nil
686 "Options concerning the general structure of Org-mode files."
687 :tag "Org Structure"
688 :group 'org)
690 (defgroup org-reveal-location nil
691 "Options about how to make context of a location visible."
692 :tag "Org Reveal Location"
693 :group 'org-structure)
695 (defconst org-context-choice
696 '(choice
697 (const :tag "Always" t)
698 (const :tag "Never" nil)
699 (repeat :greedy t :tag "Individual contexts"
700 (cons
701 (choice :tag "Context"
702 (const agenda)
703 (const org-goto)
704 (const occur-tree)
705 (const tags-tree)
706 (const link-search)
707 (const mark-goto)
708 (const bookmark-jump)
709 (const isearch)
710 (const default))
711 (boolean))))
712 "Contexts for the reveal options.")
714 (defcustom org-show-hierarchy-above '((default . t))
715 "Non-nil means show full hierarchy when revealing a location.
716 Org-mode often shows locations in an org-mode file which might have
717 been invisible before. When this is set, the hierarchy of headings
718 above the exposed location is shown.
719 Turning this off for example for sparse trees makes them very compact.
720 Instead of t, this can also be an alist specifying this option for different
721 contexts. Valid contexts are
722 agenda when exposing an entry from the agenda
723 org-goto when using the command `org-goto' on key C-c C-j
724 occur-tree when using the command `org-occur' on key C-c /
725 tags-tree when constructing a sparse tree based on tags matches
726 link-search when exposing search matches associated with a link
727 mark-goto when exposing the jump goal of a mark
728 bookmark-jump when exposing a bookmark location
729 isearch when exiting from an incremental search
730 default default for all contexts not set explicitly"
731 :group 'org-reveal-location
732 :type org-context-choice)
734 (defcustom org-show-following-heading '((default . nil))
735 "Non-nil means show following heading when revealing a location.
736 Org-mode often shows locations in an org-mode file which might have
737 been invisible before. When this is set, the heading following the
738 match is shown.
739 Turning this off for example for sparse trees makes them very compact,
740 but makes it harder to edit the location of the match. In such a case,
741 use the command \\[org-reveal] to show more context.
742 Instead of t, this can also be an alist specifying this option for different
743 contexts. See `org-show-hierarchy-above' for valid contexts."
744 :group 'org-reveal-location
745 :type org-context-choice)
747 (defcustom org-show-siblings '((default . nil) (isearch t))
748 "Non-nil means show all sibling heading when revealing a location.
749 Org-mode often shows locations in an org-mode file which might have
750 been invisible before. When this is set, the sibling of the current entry
751 heading are all made visible. If `org-show-hierarchy-above' is t,
752 the same happens on each level of the hierarchy above the current entry.
754 By default this is on for the isearch context, off for all other contexts.
755 Turning this off for example for sparse trees makes them very compact,
756 but makes it harder to edit the location of the match. In such a case,
757 use the command \\[org-reveal] to show more context.
758 Instead of t, this can also be an alist specifying this option for different
759 contexts. See `org-show-hierarchy-above' for valid contexts."
760 :group 'org-reveal-location
761 :type org-context-choice)
763 (defcustom org-show-entry-below '((default . nil))
764 "Non-nil means show the entry below a headline when revealing a location.
765 Org-mode often shows locations in an org-mode file which might have
766 been invisible before. When this is set, the text below the headline that is
767 exposed is also shown.
769 By default this is off for all contexts.
770 Instead of t, this can also be an alist specifying this option for different
771 contexts. See `org-show-hierarchy-above' for valid contexts."
772 :group 'org-reveal-location
773 :type org-context-choice)
775 (defcustom org-indirect-buffer-display 'other-window
776 "How should indirect tree buffers be displayed?
777 This applies to indirect buffers created with the commands
778 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
779 Valid values are:
780 current-window Display in the current window
781 other-window Just display in another window.
782 dedicated-frame Create one new frame, and re-use it each time.
783 new-frame Make a new frame each time. Note that in this case
784 previously-made indirect buffers are kept, and you need to
785 kill these buffers yourself."
786 :group 'org-structure
787 :group 'org-agenda-windows
788 :type '(choice
789 (const :tag "In current window" current-window)
790 (const :tag "In current frame, other window" other-window)
791 (const :tag "Each time a new frame" new-frame)
792 (const :tag "One dedicated frame" dedicated-frame)))
794 (defcustom org-use-speed-commands nil
795 "Non-nil means activate single letter commands at beginning of a headline.
796 This may also be a function to test for appropriate locations where speed
797 commands should be active."
798 :group 'org-structure
799 :type '(choice
800 (const :tag "Never" nil)
801 (const :tag "At beginning of headline stars" t)
802 (function)))
804 (defcustom org-speed-commands-user nil
805 "Alist of additional speed commands.
806 This list will be checked before `org-speed-commands-default'
807 when the variable `org-use-speed-commands' is non-nil
808 and when the cursor is at the beginning of a headline.
809 The car if each entry is a string with a single letter, which must
810 be assigned to `self-insert-command' in the global map.
811 The cdr is either a command to be called interactively, a function
812 to be called, or a form to be evaluated.
813 An entry that is just a list with a single string will be interpreted
814 as a descriptive headline that will be added when listing the speed
815 commands in the Help buffer using the `?' speed command."
816 :group 'org-structure
817 :type '(repeat :value ("k" . ignore)
818 (choice :value ("k" . ignore)
819 (list :tag "Descriptive Headline" (string :tag "Headline"))
820 (cons :tag "Letter and Command"
821 (string :tag "Command letter")
822 (choice
823 (function)
824 (sexp))))))
826 (defgroup org-cycle nil
827 "Options concerning visibility cycling in Org-mode."
828 :tag "Org Cycle"
829 :group 'org-structure)
831 (defcustom org-cycle-skip-children-state-if-no-children t
832 "Non-nil means skip CHILDREN state in entries that don't have any."
833 :group 'org-cycle
834 :type 'boolean)
836 (defcustom org-cycle-max-level nil
837 "Maximum level which should still be subject to visibility cycling.
838 Levels higher than this will, for cycling, be treated as text, not a headline.
839 When `org-odd-levels-only' is set, a value of N in this variable actually
840 means 2N-1 stars as the limiting headline.
841 When nil, cycle all levels.
842 Note that the limiting level of cycling is also influenced by
843 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
844 `org-inlinetask-min-level' is, cycling will be limited to levels one less
845 than its value."
846 :group 'org-cycle
847 :type '(choice
848 (const :tag "No limit" nil)
849 (integer :tag "Maximum level")))
851 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK" "RESULTS")
852 "Names of drawers. Drawers are not opened by cycling on the headline above.
853 Drawers only open with a TAB on the drawer line itself. A drawer looks like
854 this:
855 :DRAWERNAME:
856 .....
857 :END:
858 The drawer \"PROPERTIES\" is special for capturing properties through
859 the property API.
861 Drawers can be defined on the per-file basis with a line like:
863 #+DRAWERS: HIDDEN STATE PROPERTIES"
864 :group 'org-structure
865 :group 'org-cycle
866 :type '(repeat (string :tag "Drawer Name")))
868 (defcustom org-hide-block-startup nil
869 "Non-nil means entering Org-mode will fold all blocks.
870 This can also be set in on a per-file basis with
872 #+STARTUP: hideblocks
873 #+STARTUP: showblocks"
874 :group 'org-startup
875 :group 'org-cycle
876 :type 'boolean)
878 (defcustom org-cycle-global-at-bob nil
879 "Cycle globally if cursor is at beginning of buffer and not at a headline.
880 This makes it possible to do global cycling without having to use S-TAB or
881 \\[universal-argument] TAB. For this special case to work, the first line \
882 of the buffer
883 must not be a headline - it may be empty or some other text. When used in
884 this way, `org-cycle-hook' is disables temporarily, to make sure the
885 cursor stays at the beginning of the buffer.
886 When this option is nil, don't do anything special at the beginning
887 of the buffer."
888 :group 'org-cycle
889 :type 'boolean)
891 (defcustom org-cycle-level-after-item/entry-creation t
892 "Non-nil means cycle entry level or item indentation in new empty entries.
894 When the cursor is at the end of an empty headline, i.e with only stars
895 and maybe a TODO keyword, TAB will then switch the entry to become a child,
896 and then all possible ancestor states, before returning to the original state.
897 This makes data entry extremely fast: M-RET to create a new headline,
898 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
900 When the cursor is at the end of an empty plain list item, one TAB will
901 make it a subitem, two or more tabs will back up to make this an item
902 higher up in the item hierarchy."
903 :group 'org-cycle
904 :type 'boolean)
906 (defcustom org-cycle-emulate-tab t
907 "Where should `org-cycle' emulate TAB.
908 nil Never
909 white Only in completely white lines
910 whitestart Only at the beginning of lines, before the first non-white char
911 t Everywhere except in headlines
912 exc-hl-bol Everywhere except at the start of a headline
913 If TAB is used in a place where it does not emulate TAB, the current subtree
914 visibility is cycled."
915 :group 'org-cycle
916 :type '(choice (const :tag "Never" nil)
917 (const :tag "Only in completely white lines" white)
918 (const :tag "Before first char in a line" whitestart)
919 (const :tag "Everywhere except in headlines" t)
920 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
923 (defcustom org-cycle-separator-lines 2
924 "Number of empty lines needed to keep an empty line between collapsed trees.
925 If you leave an empty line between the end of a subtree and the following
926 headline, this empty line is hidden when the subtree is folded.
927 Org-mode will leave (exactly) one empty line visible if the number of
928 empty lines is equal or larger to the number given in this variable.
929 So the default 2 means at least 2 empty lines after the end of a subtree
930 are needed to produce free space between a collapsed subtree and the
931 following headline.
933 If the number is negative, and the number of empty lines is at least -N,
934 all empty lines are shown.
936 Special case: when 0, never leave empty lines in collapsed view."
937 :group 'org-cycle
938 :type 'integer)
939 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
941 (defcustom org-pre-cycle-hook nil
942 "Hook that is run before visibility cycling is happening.
943 The function(s) in this hook must accept a single argument which indicates
944 the new state that will be set right after running this hook. The
945 argument is a symbol. Before a global state change, it can have the values
946 `overview', `content', or `all'. Before a local state change, it can have
947 the values `folded', `children', or `subtree'."
948 :group 'org-cycle
949 :type 'hook)
951 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
952 org-cycle-hide-drawers
953 org-cycle-show-empty-lines
954 org-optimize-window-after-visibility-change)
955 "Hook that is run after `org-cycle' has changed the buffer visibility.
956 The function(s) in this hook must accept a single argument which indicates
957 the new state that was set by the most recent `org-cycle' command. The
958 argument is a symbol. After a global state change, it can have the values
959 `overview', `content', or `all'. After a local state change, it can have
960 the values `folded', `children', or `subtree'."
961 :group 'org-cycle
962 :type 'hook)
964 (defgroup org-edit-structure nil
965 "Options concerning structure editing in Org-mode."
966 :tag "Org Edit Structure"
967 :group 'org-structure)
969 (defcustom org-odd-levels-only nil
970 "Non-nil means skip even levels and only use odd levels for the outline.
971 This has the effect that two stars are being added/taken away in
972 promotion/demotion commands. It also influences how levels are
973 handled by the exporters.
974 Changing it requires restart of `font-lock-mode' to become effective
975 for fontification also in regions already fontified.
976 You may also set this on a per-file basis by adding one of the following
977 lines to the buffer:
979 #+STARTUP: odd
980 #+STARTUP: oddeven"
981 :group 'org-edit-structure
982 :group 'org-appearance
983 :type 'boolean)
985 (defcustom org-adapt-indentation t
986 "Non-nil means adapt indentation to outline node level.
988 When this variable is set, Org assumes that you write outlines by
989 indenting text in each node to align with the headline (after the stars).
990 The following issues are influenced by this variable:
992 - When this is set and the *entire* text in an entry is indented, the
993 indentation is increased by one space in a demotion command, and
994 decreased by one in a promotion command. If any line in the entry
995 body starts with text at column 0, indentation is not changed at all.
997 - Property drawers and planning information is inserted indented when
998 this variable s set. When nil, they will not be indented.
1000 - TAB indents a line relative to context. The lines below a headline
1001 will be indented when this variable is set.
1003 Note that this is all about true indentation, by adding and removing
1004 space characters. See also `org-indent.el' which does level-dependent
1005 indentation in a virtual way, i.e. at display time in Emacs."
1006 :group 'org-edit-structure
1007 :type 'boolean)
1009 (defcustom org-special-ctrl-a/e nil
1010 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1012 When t, `C-a' will bring back the cursor to the beginning of the
1013 headline text, i.e. after the stars and after a possible TODO
1014 keyword. In an item, this will be the position after bullet and
1015 check-box, if any. When the cursor is already at that position,
1016 another `C-a' will bring it to the beginning of the line.
1018 `C-e' will jump to the end of the headline, ignoring the presence
1019 of tags in the headline. A second `C-e' will then jump to the
1020 true end of the line, after any tags. This also means that, when
1021 this variable is non-nil, `C-e' also will never jump beyond the
1022 end of the heading of a folded section, i.e. not after the
1023 ellipses.
1025 When set to the symbol `reversed', the first `C-a' or `C-e' works
1026 normally, going to the true line boundary first. Only a directly
1027 following, identical keypress will bring the cursor to the
1028 special positions.
1030 This may also be a cons cell where the behavior for `C-a' and
1031 `C-e' is set separately."
1032 :group 'org-edit-structure
1033 :type '(choice
1034 (const :tag "off" nil)
1035 (const :tag "on: after stars/bullet and before tags first" t)
1036 (const :tag "reversed: true line boundary first" reversed)
1037 (cons :tag "Set C-a and C-e separately"
1038 (choice :tag "Special C-a"
1039 (const :tag "off" nil)
1040 (const :tag "on: after stars/bullet first" t)
1041 (const :tag "reversed: before stars/bullet first" reversed))
1042 (choice :tag "Special C-e"
1043 (const :tag "off" nil)
1044 (const :tag "on: before tags first" t)
1045 (const :tag "reversed: after tags first" reversed)))))
1046 (if (fboundp 'defvaralias)
1047 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
1049 (defcustom org-special-ctrl-k nil
1050 "Non-nil means `C-k' will behave specially in headlines.
1051 When nil, `C-k' will call the default `kill-line' command.
1052 When t, the following will happen while the cursor is in the headline:
1054 - When the cursor is at the beginning of a headline, kill the entire
1055 line and possible the folded subtree below the line.
1056 - When in the middle of the headline text, kill the headline up to the tags.
1057 - When after the headline text, kill the tags."
1058 :group 'org-edit-structure
1059 :type 'boolean)
1061 (defcustom org-ctrl-k-protect-subtree nil
1062 "Non-nil means, do not delete a hidden subtree with C-k.
1063 When set to the symbol `error', simply throw an error when C-k is
1064 used to kill (part-of) a headline that has hidden text behind it.
1065 Any other non-nil value will result in a query to the user, if it is
1066 OK to kill that hidden subtree. When nil, kill without remorse."
1067 :group 'org-edit-structure
1068 :version "24.1"
1069 :type '(choice
1070 (const :tag "Do not protect hidden subtrees" nil)
1071 (const :tag "Protect hidden subtrees with a security query" t)
1072 (const :tag "Never kill a hidden subtree with C-k" error)))
1074 (defcustom org-catch-invisible-edits nil
1075 "Check if in invisible region before inserting or deleting a character.
1076 Valid values are:
1078 nil Do not check, so just do invisible edits.
1079 error Throw an error and do nothing.
1080 show Make point visible, and do the requested edit.
1081 show-and-error Make point visible, then throw an error and abort the edit.
1082 smart Make point visible, and do insertion/deletion if it is
1083 adjacent to visible text and the change feels predictable.
1084 Never delete a previously invisible character or add in the
1085 middle or right after an invisible region. Basically, this
1086 allows insertion and backward-delete right before ellipses.
1087 FIXME: maybe in this case we should not even show?"
1088 :group 'org-edit-structure
1089 :version "24.1"
1090 :type '(choice
1091 (const :tag "Do not check" nil)
1092 (const :tag "Throw error when trying to edit" error)
1093 (const :tag "Unhide, but do not do the edit" show-and-error)
1094 (const :tag "Show invisible part and do the edit" show)
1095 (const :tag "Be smart and do the right thing" smart)))
1097 (defcustom org-yank-folded-subtrees t
1098 "Non-nil means when yanking subtrees, fold them.
1099 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1100 it starts with a heading and all other headings in it are either children
1101 or siblings, then fold all the subtrees. However, do this only if no
1102 text after the yank would be swallowed into a folded tree by this action."
1103 :group 'org-edit-structure
1104 :type 'boolean)
1106 (defcustom org-yank-adjusted-subtrees nil
1107 "Non-nil means when yanking subtrees, adjust the level.
1108 With this setting, `org-paste-subtree' is used to insert the subtree, see
1109 this function for details."
1110 :group 'org-edit-structure
1111 :type 'boolean)
1113 (defcustom org-M-RET-may-split-line '((default . t))
1114 "Non-nil means M-RET will split the line at the cursor position.
1115 When nil, it will go to the end of the line before making a
1116 new line.
1117 You may also set this option in a different way for different
1118 contexts. Valid contexts are:
1120 headline when creating a new headline
1121 item when creating a new item
1122 table in a table field
1123 default the value to be used for all contexts not explicitly
1124 customized"
1125 :group 'org-structure
1126 :group 'org-table
1127 :type '(choice
1128 (const :tag "Always" t)
1129 (const :tag "Never" nil)
1130 (repeat :greedy t :tag "Individual contexts"
1131 (cons
1132 (choice :tag "Context"
1133 (const headline)
1134 (const item)
1135 (const table)
1136 (const default))
1137 (boolean)))))
1140 (defcustom org-insert-heading-respect-content nil
1141 "Non-nil means insert new headings after the current subtree.
1142 When nil, the new heading is created directly after the current line.
1143 The commands \\[org-insert-heading-respect-content] and
1144 \\[org-insert-todo-heading-respect-content] turn this variable on
1145 for the duration of the command."
1146 :group 'org-structure
1147 :type 'boolean)
1149 (defcustom org-blank-before-new-entry '((heading . auto)
1150 (plain-list-item . auto))
1151 "Should `org-insert-heading' leave a blank line before new heading/item?
1152 The value is an alist, with `heading' and `plain-list-item' as CAR,
1153 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1154 which case Org will look at the surrounding headings/items and try to
1155 make an intelligent decision whether to insert a blank line or not.
1157 For plain lists, if the variable `org-empty-line-terminates-plain-lists' is
1158 set, the setting here is ignored and no empty line is inserted, to avoid
1159 breaking the list structure."
1160 :group 'org-edit-structure
1161 :type '(list
1162 (cons (const heading)
1163 (choice (const :tag "Never" nil)
1164 (const :tag "Always" t)
1165 (const :tag "Auto" auto)))
1166 (cons (const plain-list-item)
1167 (choice (const :tag "Never" nil)
1168 (const :tag "Always" t)
1169 (const :tag "Auto" auto)))))
1171 (defcustom org-insert-heading-hook nil
1172 "Hook being run after inserting a new heading."
1173 :group 'org-edit-structure
1174 :type 'hook)
1176 (defcustom org-enable-fixed-width-editor t
1177 "Non-nil means lines starting with \":\" are treated as fixed-width.
1178 This currently only means they are never auto-wrapped.
1179 When nil, such lines will be treated like ordinary lines.
1180 See also the QUOTE keyword."
1181 :group 'org-edit-structure
1182 :type 'boolean)
1184 (defcustom org-goto-auto-isearch t
1185 "Non-nil means typing characters in `org-goto' starts incremental search."
1186 :group 'org-edit-structure
1187 :type 'boolean)
1189 (defgroup org-sparse-trees nil
1190 "Options concerning sparse trees in Org-mode."
1191 :tag "Org Sparse Trees"
1192 :group 'org-structure)
1194 (defcustom org-highlight-sparse-tree-matches t
1195 "Non-nil means highlight all matches that define a sparse tree.
1196 The highlights will automatically disappear the next time the buffer is
1197 changed by an edit command."
1198 :group 'org-sparse-trees
1199 :type 'boolean)
1201 (defcustom org-remove-highlights-with-change t
1202 "Non-nil means any change to the buffer will remove temporary highlights.
1203 Such highlights are created by `org-occur' and `org-clock-display'.
1204 When nil, `C-c C-c needs to be used to get rid of the highlights.
1205 The highlights created by `org-preview-latex-fragment' always need
1206 `C-c C-c' to be removed."
1207 :group 'org-sparse-trees
1208 :group 'org-time
1209 :type 'boolean)
1212 (defcustom org-occur-hook '(org-first-headline-recenter)
1213 "Hook that is run after `org-occur' has constructed a sparse tree.
1214 This can be used to recenter the window to show as much of the structure
1215 as possible."
1216 :group 'org-sparse-trees
1217 :type 'hook)
1219 (defgroup org-imenu-and-speedbar nil
1220 "Options concerning imenu and speedbar in Org-mode."
1221 :tag "Org Imenu and Speedbar"
1222 :group 'org-structure)
1224 (defcustom org-imenu-depth 2
1225 "The maximum level for Imenu access to Org-mode headlines.
1226 This also applied for speedbar access."
1227 :group 'org-imenu-and-speedbar
1228 :type 'integer)
1230 (defgroup org-table nil
1231 "Options concerning tables in Org-mode."
1232 :tag "Org Table"
1233 :group 'org)
1235 (defcustom org-enable-table-editor 'optimized
1236 "Non-nil means lines starting with \"|\" are handled by the table editor.
1237 When nil, such lines will be treated like ordinary lines.
1239 When equal to the symbol `optimized', the table editor will be optimized to
1240 do the following:
1241 - Automatic overwrite mode in front of whitespace in table fields.
1242 This makes the structure of the table stay in tact as long as the edited
1243 field does not exceed the column width.
1244 - Minimize the number of realigns. Normally, the table is aligned each time
1245 TAB or RET are pressed to move to another field. With optimization this
1246 happens only if changes to a field might have changed the column width.
1247 Optimization requires replacing the functions `self-insert-command',
1248 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1249 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1250 very good at guessing when a re-align will be necessary, but you can always
1251 force one with \\[org-ctrl-c-ctrl-c].
1253 If you would like to use the optimized version in Org-mode, but the
1254 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1256 This variable can be used to turn on and off the table editor during a session,
1257 but in order to toggle optimization, a restart is required.
1259 See also the variable `org-table-auto-blank-field'."
1260 :group 'org-table
1261 :type '(choice
1262 (const :tag "off" nil)
1263 (const :tag "on" t)
1264 (const :tag "on, optimized" optimized)))
1266 (defcustom org-self-insert-cluster-for-undo t
1267 "Non-nil means cluster self-insert commands for undo when possible.
1268 If this is set, then, like in the Emacs command loop, 20 consecutive
1269 characters will be undone together.
1270 This is configurable, because there is some impact on typing performance."
1271 :group 'org-table
1272 :type 'boolean)
1274 (defcustom org-table-tab-recognizes-table.el t
1275 "Non-nil means TAB will automatically notice a table.el table.
1276 When it sees such a table, it moves point into it and - if necessary -
1277 calls `table-recognize-table'."
1278 :group 'org-table-editing
1279 :type 'boolean)
1281 (defgroup org-link nil
1282 "Options concerning links in Org-mode."
1283 :tag "Org Link"
1284 :group 'org)
1286 (defvar org-link-abbrev-alist-local nil
1287 "Buffer-local version of `org-link-abbrev-alist', which see.
1288 The value of this is taken from the #+LINK lines.")
1289 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1291 (defcustom org-link-abbrev-alist nil
1292 "Alist of link abbreviations.
1293 The car of each element is a string, to be replaced at the start of a link.
1294 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1295 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1297 [[linkkey:tag][description]]
1299 The 'linkkey' must be a word word, starting with a letter, followed
1300 by letters, numbers, '-' or '_'.
1302 If REPLACE is a string, the tag will simply be appended to create the link.
1303 If the string contains \"%s\", the tag will be inserted there. Alternatively,
1304 the placeholder \"%h\" will cause a url-encoded version of the tag to
1305 be inserted at that point (see the function `url-hexify-string').
1307 REPLACE may also be a function that will be called with the tag as the
1308 only argument to create the link, which should be returned as a string.
1310 See the manual for examples."
1311 :group 'org-link
1312 :type '(repeat
1313 (cons
1314 (string :tag "Protocol")
1315 (choice
1316 (string :tag "Format")
1317 (function)))))
1319 (defcustom org-descriptive-links t
1320 "Non-nil means Org will display descriptive links.
1321 E.g. [[http://orgmode.org][Org website]] will be displayed as
1322 \"Org Website\", hiding the link itself and just displaying its
1323 description. When set to `nil', Org will display the full links
1324 literally.
1326 You can interactively set the value of this variable by calling
1327 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1328 :group 'org-link
1329 :type 'boolean)
1331 (defcustom org-link-file-path-type 'adaptive
1332 "How the path name in file links should be stored.
1333 Valid values are:
1335 relative Relative to the current directory, i.e. the directory of the file
1336 into which the link is being inserted.
1337 absolute Absolute path, if possible with ~ for home directory.
1338 noabbrev Absolute path, no abbreviation of home directory.
1339 adaptive Use relative path for files in the current directory and sub-
1340 directories of it. For other files, use an absolute path."
1341 :group 'org-link
1342 :type '(choice
1343 (const relative)
1344 (const absolute)
1345 (const noabbrev)
1346 (const adaptive)))
1348 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1349 "Types of links that should be activated in Org-mode files.
1350 This is a list of symbols, each leading to the activation of a certain link
1351 type. In principle, it does not hurt to turn on most link types - there may
1352 be a small gain when turning off unused link types. The types are:
1354 bracket The recommended [[link][description]] or [[link]] links with hiding.
1355 angle Links in angular brackets that may contain whitespace like
1356 <bbdb:Carsten Dominik>.
1357 plain Plain links in normal text, no whitespace, like http://google.com.
1358 radio Text that is matched by a radio target, see manual for details.
1359 tag Tag settings in a headline (link to tag search).
1360 date Time stamps (link to calendar).
1361 footnote Footnote labels.
1363 Changing this variable requires a restart of Emacs to become effective."
1364 :group 'org-link
1365 :type '(set :greedy t
1366 (const :tag "Double bracket links" bracket)
1367 (const :tag "Angular bracket links" angle)
1368 (const :tag "Plain text links" plain)
1369 (const :tag "Radio target matches" radio)
1370 (const :tag "Tags" tag)
1371 (const :tag "Timestamps" date)
1372 (const :tag "Footnotes" footnote)))
1374 (defcustom org-make-link-description-function nil
1375 "Function to use to generate link descriptions from links.
1376 If nil the link location will be used. This function must take
1377 two parameters; the first is the link and the second the
1378 description `org-insert-link' has generated, and should return the
1379 description to use."
1380 :group 'org-link
1381 :type 'function)
1383 (defgroup org-link-store nil
1384 "Options concerning storing links in Org-mode."
1385 :tag "Org Store Link"
1386 :group 'org-link)
1388 (defcustom org-email-link-description-format "Email %c: %.30s"
1389 "Format of the description part of a link to an email or usenet message.
1390 The following %-escapes will be replaced by corresponding information:
1392 %F full \"From\" field
1393 %f name, taken from \"From\" field, address if no name
1394 %T full \"To\" field
1395 %t first name in \"To\" field, address if no name
1396 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1397 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1398 %s subject
1399 %d date
1400 %m message-id.
1402 You may use normal field width specification between the % and the letter.
1403 This is for example useful to limit the length of the subject.
1405 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1406 :group 'org-link-store
1407 :type 'string)
1409 (defcustom org-from-is-user-regexp
1410 (let (r1 r2)
1411 (when (and user-mail-address (not (string= user-mail-address "")))
1412 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1413 (when (and user-full-name (not (string= user-full-name "")))
1414 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1415 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1416 "Regexp matched against the \"From:\" header of an email or usenet message.
1417 It should match if the message is from the user him/herself."
1418 :group 'org-link-store
1419 :type 'regexp)
1421 (defcustom org-link-to-org-use-id 'create-if-interactive-and-no-custom-id
1422 "Non-nil means storing a link to an Org file will use entry IDs.
1424 Note that before this variable is even considered, org-id must be loaded,
1425 so please customize `org-modules' and turn it on.
1427 The variable can have the following values:
1429 t Create an ID if needed to make a link to the current entry.
1431 create-if-interactive
1432 If `org-store-link' is called directly (interactively, as a user
1433 command), do create an ID to support the link. But when doing the
1434 job for remember, only use the ID if it already exists. The
1435 purpose of this setting is to avoid proliferation of unwanted
1436 IDs, just because you happen to be in an Org file when you
1437 call `org-remember' that automatically and preemptively
1438 creates a link. If you do want to get an ID link in a remember
1439 template to an entry not having an ID, create it first by
1440 explicitly creating a link to it, using `C-c C-l' first.
1442 create-if-interactive-and-no-custom-id
1443 Like create-if-interactive, but do not create an ID if there is
1444 a CUSTOM_ID property defined in the entry. This is the default.
1446 use-existing
1447 Use existing ID, do not create one.
1449 nil Never use an ID to make a link, instead link using a text search for
1450 the headline text."
1451 :group 'org-link-store
1452 :type '(choice
1453 (const :tag "Create ID to make link" t)
1454 (const :tag "Create if storing link interactively"
1455 create-if-interactive)
1456 (const :tag "Create if storing link interactively and no CUSTOM_ID is present"
1457 create-if-interactive-and-no-custom-id)
1458 (const :tag "Only use existing" use-existing)
1459 (const :tag "Do not use ID to create link" nil)))
1461 (defcustom org-context-in-file-links t
1462 "Non-nil means file links from `org-store-link' contain context.
1463 A search string will be added to the file name with :: as separator and
1464 used to find the context when the link is activated by the command
1465 `org-open-at-point'. When this option is t, the entire active region
1466 will be placed in the search string of the file link. If set to a
1467 positive integer, only the first n lines of context will be stored.
1469 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1470 negates this setting for the duration of the command."
1471 :group 'org-link-store
1472 :type '(choice boolean integer))
1474 (defcustom org-keep-stored-link-after-insertion nil
1475 "Non-nil means keep link in list for entire session.
1477 The command `org-store-link' adds a link pointing to the current
1478 location to an internal list. These links accumulate during a session.
1479 The command `org-insert-link' can be used to insert links into any
1480 Org-mode file (offering completion for all stored links). When this
1481 option is nil, every link which has been inserted once using \\[org-insert-link]
1482 will be removed from the list, to make completing the unused links
1483 more efficient."
1484 :group 'org-link-store
1485 :type 'boolean)
1487 (defgroup org-link-follow nil
1488 "Options concerning following links in Org-mode."
1489 :tag "Org Follow Link"
1490 :group 'org-link)
1492 (defcustom org-link-translation-function nil
1493 "Function to translate links with different syntax to Org syntax.
1494 This can be used to translate links created for example by the Planner
1495 or emacs-wiki packages to Org syntax.
1496 The function must accept two parameters, a TYPE containing the link
1497 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1498 which is everything after the link protocol. It should return a cons
1499 with possibly modified values of type and path.
1500 Org contains a function for this, so if you set this variable to
1501 `org-translate-link-from-planner', you should be able follow many
1502 links created by planner."
1503 :group 'org-link-follow
1504 :type 'function)
1506 (defcustom org-follow-link-hook nil
1507 "Hook that is run after a link has been followed."
1508 :group 'org-link-follow
1509 :type 'hook)
1511 (defcustom org-tab-follows-link nil
1512 "Non-nil means on links TAB will follow the link.
1513 Needs to be set before org.el is loaded.
1514 This really should not be used, it does not make sense, and the
1515 implementation is bad."
1516 :group 'org-link-follow
1517 :type 'boolean)
1519 (defcustom org-return-follows-link nil
1520 "Non-nil means on links RET will follow the link."
1521 :group 'org-link-follow
1522 :type 'boolean)
1524 (defcustom org-mouse-1-follows-link
1525 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1526 "Non-nil means mouse-1 on a link will follow the link.
1527 A longer mouse click will still set point. Does not work on XEmacs.
1528 Needs to be set before org.el is loaded."
1529 :group 'org-link-follow
1530 :type 'boolean)
1532 (defcustom org-mark-ring-length 4
1533 "Number of different positions to be recorded in the ring.
1534 Changing this requires a restart of Emacs to work correctly."
1535 :group 'org-link-follow
1536 :type 'integer)
1538 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1539 "Non-nil means internal links in Org files must exactly match a headline.
1540 When nil, the link search tries to match a phrase with all words
1541 in the search text."
1542 :group 'org-link-follow
1543 :version "24.1"
1544 :type '(choice
1545 (const :tag "Use fuzzy text search" nil)
1546 (const :tag "Match only exact headline" t)
1547 (const :tag "Match exact headline or query to create it"
1548 query-to-create)))
1550 (defcustom org-link-frame-setup
1551 '((vm . vm-visit-folder-other-frame)
1552 (vm-imap . vm-visit-imap-folder-other-frame)
1553 (gnus . org-gnus-no-new-news)
1554 (file . find-file-other-window)
1555 (wl . wl-other-frame))
1556 "Setup the frame configuration for following links.
1557 When following a link with Emacs, it may often be useful to display
1558 this link in another window or frame. This variable can be used to
1559 set this up for the different types of links.
1560 For VM, use any of
1561 `vm-visit-folder'
1562 `vm-visit-folder-other-window'
1563 `vm-visit-folder-other-frame'
1564 For Gnus, use any of
1565 `gnus'
1566 `gnus-other-frame'
1567 `org-gnus-no-new-news'
1568 For FILE, use any of
1569 `find-file'
1570 `find-file-other-window'
1571 `find-file-other-frame'
1572 For Wanderlust use any of
1573 `wl'
1574 `wl-other-frame'
1575 For the calendar, use the variable `calendar-setup'.
1576 For BBDB, it is currently only possible to display the matches in
1577 another window."
1578 :group 'org-link-follow
1579 :type '(list
1580 (cons (const vm)
1581 (choice
1582 (const vm-visit-folder)
1583 (const vm-visit-folder-other-window)
1584 (const vm-visit-folder-other-frame)))
1585 (cons (const gnus)
1586 (choice
1587 (const gnus)
1588 (const gnus-other-frame)
1589 (const org-gnus-no-new-news)))
1590 (cons (const file)
1591 (choice
1592 (const find-file)
1593 (const find-file-other-window)
1594 (const find-file-other-frame)))
1595 (cons (const wl)
1596 (choice
1597 (const wl)
1598 (const wl-other-frame)))))
1600 (defcustom org-display-internal-link-with-indirect-buffer nil
1601 "Non-nil means use indirect buffer to display infile links.
1602 Activating internal links (from one location in a file to another location
1603 in the same file) normally just jumps to the location. When the link is
1604 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1605 is displayed in
1606 another window. When this option is set, the other window actually displays
1607 an indirect buffer clone of the current buffer, to avoid any visibility
1608 changes to the current buffer."
1609 :group 'org-link-follow
1610 :type 'boolean)
1612 (defcustom org-open-non-existing-files nil
1613 "Non-nil means `org-open-file' will open non-existing files.
1614 When nil, an error will be generated.
1615 This variable applies only to external applications because they
1616 might choke on non-existing files. If the link is to a file that
1617 will be opened in Emacs, the variable is ignored."
1618 :group 'org-link-follow
1619 :type 'boolean)
1621 (defcustom org-open-directory-means-index-dot-org nil
1622 "Non-nil means a link to a directory really means to index.org.
1623 When nil, following a directory link will run dired or open a finder/explorer
1624 window on that directory."
1625 :group 'org-link-follow
1626 :type 'boolean)
1628 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1629 "Function and arguments to call for following mailto links.
1630 This is a list with the first element being a Lisp function, and the
1631 remaining elements being arguments to the function. In string arguments,
1632 %a will be replaced by the address, and %s will be replaced by the subject
1633 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1634 :group 'org-link-follow
1635 :type '(choice
1636 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1637 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1638 (const :tag "message-mail" (message-mail "%a" "%s"))
1639 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1641 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1642 "Non-nil means ask for confirmation before executing shell links.
1643 Shell links can be dangerous: just think about a link
1645 [[shell:rm -rf ~/*][Google Search]]
1647 This link would show up in your Org-mode document as \"Google Search\",
1648 but really it would remove your entire home directory.
1649 Therefore we advise against setting this variable to nil.
1650 Just change it to `y-or-n-p' if you want to confirm with a
1651 single keystroke rather than having to type \"yes\"."
1652 :group 'org-link-follow
1653 :type '(choice
1654 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1655 (const :tag "with y-or-n (faster)" y-or-n-p)
1656 (const :tag "no confirmation (dangerous)" nil)))
1657 (put 'org-confirm-shell-link-function
1658 'safe-local-variable
1659 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1661 (defcustom org-confirm-shell-link-not-regexp ""
1662 "A regexp to skip confirmation for shell links."
1663 :group 'org-link-follow
1664 :version "24.1"
1665 :type 'regexp)
1667 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1668 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1669 Elisp links can be dangerous: just think about a link
1671 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1673 This link would show up in your Org-mode document as \"Google Search\",
1674 but really it would remove your entire home directory.
1675 Therefore we advise against setting this variable to nil.
1676 Just change it to `y-or-n-p' if you want to confirm with a
1677 single keystroke rather than having to type \"yes\"."
1678 :group 'org-link-follow
1679 :type '(choice
1680 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1681 (const :tag "with y-or-n (faster)" y-or-n-p)
1682 (const :tag "no confirmation (dangerous)" nil)))
1683 (put 'org-confirm-shell-link-function
1684 'safe-local-variable
1685 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1687 (defcustom org-confirm-elisp-link-not-regexp ""
1688 "A regexp to skip confirmation for Elisp links."
1689 :group 'org-link-follow
1690 :version "24.1"
1691 :type 'regexp)
1693 (defconst org-file-apps-defaults-gnu
1694 '((remote . emacs)
1695 (system . mailcap)
1696 (t . mailcap))
1697 "Default file applications on a UNIX or GNU/Linux system.
1698 See `org-file-apps'.")
1700 (defconst org-file-apps-defaults-macosx
1701 '((remote . emacs)
1702 (t . "open %s")
1703 (system . "open %s")
1704 ("ps.gz" . "gv %s")
1705 ("eps.gz" . "gv %s")
1706 ("dvi" . "xdvi %s")
1707 ("fig" . "xfig %s"))
1708 "Default file applications on a MacOS X system.
1709 The system \"open\" is known as a default, but we use X11 applications
1710 for some files for which the OS does not have a good default.
1711 See `org-file-apps'.")
1713 (defconst org-file-apps-defaults-windowsnt
1714 (list
1715 '(remote . emacs)
1716 (cons t
1717 (list (if (featurep 'xemacs)
1718 'mswindows-shell-execute
1719 'w32-shell-execute)
1720 "open" 'file))
1721 (cons 'system
1722 (list (if (featurep 'xemacs)
1723 'mswindows-shell-execute
1724 'w32-shell-execute)
1725 "open" 'file)))
1726 "Default file applications on a Windows NT system.
1727 The system \"open\" is used for most files.
1728 See `org-file-apps'.")
1730 (defcustom org-file-apps
1732 (auto-mode . emacs)
1733 ("\\.mm\\'" . default)
1734 ("\\.x?html?\\'" . default)
1735 ("\\.pdf\\'" . default)
1737 "External applications for opening `file:path' items in a document.
1738 Org-mode uses system defaults for different file types, but
1739 you can use this variable to set the application for a given file
1740 extension. The entries in this list are cons cells where the car identifies
1741 files and the cdr the corresponding command. Possible values for the
1742 file identifier are
1743 \"string\" A string as a file identifier can be interpreted in different
1744 ways, depending on its contents:
1746 - Alphanumeric characters only:
1747 Match links with this file extension.
1748 Example: (\"pdf\" . \"evince %s\")
1749 to open PDFs with evince.
1751 - Regular expression: Match links where the
1752 filename matches the regexp. If you want to
1753 use groups here, use shy groups.
1755 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1756 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1757 to open *.html and *.xhtml with firefox.
1759 - Regular expression which contains (non-shy) groups:
1760 Match links where the whole link, including \"::\", and
1761 anything after that, matches the regexp.
1762 In a custom command string, %1, %2, etc. are replaced with
1763 the parts of the link that were matched by the groups.
1764 For backwards compatibility, if a command string is given
1765 that does not use any of the group matches, this case is
1766 handled identically to the second one (i.e. match against
1767 file name only).
1768 In a custom lisp form, you can access the group matches with
1769 (match-string n link).
1771 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1772 to open [[file:document.pdf::5]] with evince at page 5.
1774 `directory' Matches a directory
1775 `remote' Matches a remote file, accessible through tramp or efs.
1776 Remote files most likely should be visited through Emacs
1777 because external applications cannot handle such paths.
1778 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1779 so all files Emacs knows how to handle. Using this with
1780 command `emacs' will open most files in Emacs. Beware that this
1781 will also open html files inside Emacs, unless you add
1782 (\"html\" . default) to the list as well.
1783 t Default for files not matched by any of the other options.
1784 `system' The system command to open files, like `open' on Windows
1785 and Mac OS X, and mailcap under GNU/Linux. This is the command
1786 that will be selected if you call `C-c C-o' with a double
1787 \\[universal-argument] \\[universal-argument] prefix.
1789 Possible values for the command are:
1790 `emacs' The file will be visited by the current Emacs process.
1791 `default' Use the default application for this file type, which is the
1792 association for t in the list, most likely in the system-specific
1793 part.
1794 This can be used to overrule an unwanted setting in the
1795 system-specific variable.
1796 `system' Use the system command for opening files, like \"open\".
1797 This command is specified by the entry whose car is `system'.
1798 Most likely, the system-specific version of this variable
1799 does define this command, but you can overrule/replace it
1800 here.
1801 string A command to be executed by a shell; %s will be replaced
1802 by the path to the file.
1803 sexp A Lisp form which will be evaluated. The file path will
1804 be available in the Lisp variable `file'.
1805 For more examples, see the system specific constants
1806 `org-file-apps-defaults-macosx'
1807 `org-file-apps-defaults-windowsnt'
1808 `org-file-apps-defaults-gnu'."
1809 :group 'org-link-follow
1810 :type '(repeat
1811 (cons (choice :value ""
1812 (string :tag "Extension")
1813 (const :tag "System command to open files" system)
1814 (const :tag "Default for unrecognized files" t)
1815 (const :tag "Remote file" remote)
1816 (const :tag "Links to a directory" directory)
1817 (const :tag "Any files that have Emacs modes"
1818 auto-mode))
1819 (choice :value ""
1820 (const :tag "Visit with Emacs" emacs)
1821 (const :tag "Use default" default)
1822 (const :tag "Use the system command" system)
1823 (string :tag "Command")
1824 (sexp :tag "Lisp form")))))
1828 (defgroup org-refile nil
1829 "Options concerning refiling entries in Org-mode."
1830 :tag "Org Refile"
1831 :group 'org)
1833 (defcustom org-directory "~/org"
1834 "Directory with org files.
1835 This is just a default location to look for Org files. There is no need
1836 at all to put your files into this directory. It is only used in the
1837 following situations:
1839 1. When a remember template specifies a target file that is not an
1840 absolute path. The path will then be interpreted relative to
1841 `org-directory'
1842 2. When a remember note is filed away in an interactive way (when exiting the
1843 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1844 with `org-directory' as the default path."
1845 :group 'org-refile
1846 :group 'org-remember
1847 :type 'directory)
1849 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1850 "Default target for storing notes.
1851 Used as a fall back file for org-remember.el and org-capture.el, for
1852 templates that do not specify a target file."
1853 :group 'org-refile
1854 :group 'org-remember
1855 :type '(choice
1856 (const :tag "Default from remember-data-file" nil)
1857 file))
1859 (defcustom org-goto-interface 'outline
1860 "The default interface to be used for `org-goto'.
1861 Allowed values are:
1862 outline The interface shows an outline of the relevant file
1863 and the correct heading is found by moving through
1864 the outline or by searching with incremental search.
1865 outline-path-completion Headlines in the current buffer are offered via
1866 completion. This is the interface also used by
1867 the refile command."
1868 :group 'org-refile
1869 :type '(choice
1870 (const :tag "Outline" outline)
1871 (const :tag "Outline-path-completion" outline-path-completion)))
1873 (defcustom org-goto-max-level 5
1874 "Maximum target level when running `org-goto' with refile interface."
1875 :group 'org-refile
1876 :type 'integer)
1878 (defcustom org-reverse-note-order nil
1879 "Non-nil means store new notes at the beginning of a file or entry.
1880 When nil, new notes will be filed to the end of a file or entry.
1881 This can also be a list with cons cells of regular expressions that
1882 are matched against file names, and values."
1883 :group 'org-remember
1884 :group 'org-refile
1885 :type '(choice
1886 (const :tag "Reverse always" t)
1887 (const :tag "Reverse never" nil)
1888 (repeat :tag "By file name regexp"
1889 (cons regexp boolean))))
1891 (defcustom org-log-refile nil
1892 "Information to record when a task is refiled.
1894 Possible values are:
1896 nil Don't add anything
1897 time Add a time stamp to the task
1898 note Prompt for a note and add it with template `org-log-note-headings'
1900 This option can also be set with on a per-file-basis with
1902 #+STARTUP: nologrefile
1903 #+STARTUP: logrefile
1904 #+STARTUP: lognoterefile
1906 You can have local logging settings for a subtree by setting the LOGGING
1907 property to one or more of these keywords.
1909 When bulk-refiling from the agenda, the value `note' is forbidden and
1910 will temporarily be changed to `time'."
1911 :group 'org-refile
1912 :group 'org-progress
1913 :version "24.1"
1914 :type '(choice
1915 (const :tag "No logging" nil)
1916 (const :tag "Record timestamp" time)
1917 (const :tag "Record timestamp with note." note)))
1919 (defcustom org-refile-targets nil
1920 "Targets for refiling entries with \\[org-refile].
1921 This is a list of cons cells. Each cell contains:
1922 - a specification of the files to be considered, either a list of files,
1923 or a symbol whose function or variable value will be used to retrieve
1924 a file name or a list of file names. If you use `org-agenda-files' for
1925 that, all agenda files will be scanned for targets. Nil means consider
1926 headings in the current buffer.
1927 - A specification of how to find candidate refile targets. This may be
1928 any of:
1929 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1930 This tag has to be present in all target headlines, inheritance will
1931 not be considered.
1932 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1933 todo keyword.
1934 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1935 headlines that are refiling targets.
1936 - a cons cell (:level . N). Any headline of level N is considered a target.
1937 Note that, when `org-odd-levels-only' is set, level corresponds to
1938 order in hierarchy, not to the number of stars.
1939 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1940 Note that, when `org-odd-levels-only' is set, level corresponds to
1941 order in hierarchy, not to the number of stars.
1943 Each element of this list generates a set of possible targets.
1944 The union of these sets is presented (with completion) to
1945 the user by `org-refile'.
1947 You can set the variable `org-refile-target-verify-function' to a function
1948 to verify each headline found by the simple criteria above.
1950 When this variable is nil, all top-level headlines in the current buffer
1951 are used, equivalent to the value `((nil . (:level . 1))'."
1952 :group 'org-refile
1953 :type '(repeat
1954 (cons
1955 (choice :value org-agenda-files
1956 (const :tag "All agenda files" org-agenda-files)
1957 (const :tag "Current buffer" nil)
1958 (function) (variable) (file))
1959 (choice :tag "Identify target headline by"
1960 (cons :tag "Specific tag" (const :value :tag) (string))
1961 (cons :tag "TODO keyword" (const :value :todo) (string))
1962 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1963 (cons :tag "Level number" (const :value :level) (integer))
1964 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1966 (defcustom org-refile-target-verify-function nil
1967 "Function to verify if the headline at point should be a refile target.
1968 The function will be called without arguments, with point at the
1969 beginning of the headline. It should return t and leave point
1970 where it is if the headline is a valid target for refiling.
1972 If the target should not be selected, the function must return nil.
1973 In addition to this, it may move point to a place from where the search
1974 should be continued. For example, the function may decide that the entire
1975 subtree of the current entry should be excluded and move point to the end
1976 of the subtree."
1977 :group 'org-refile
1978 :type 'function)
1980 (defcustom org-refile-use-cache nil
1981 "Non-nil means cache refile targets to speed up the process.
1982 The cache for a particular file will be updated automatically when
1983 the buffer has been killed, or when any of the marker used for flagging
1984 refile targets no longer points at a live buffer.
1985 If you have added new entries to a buffer that might themselves be targets,
1986 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
1987 find that easier, `C-u C-u C-u C-c C-w'."
1988 :group 'org-refile
1989 :version "24.1"
1990 :type 'boolean)
1992 (defcustom org-refile-use-outline-path nil
1993 "Non-nil means provide refile targets as paths.
1994 So a level 3 headline will be available as level1/level2/level3.
1996 When the value is `file', also include the file name (without directory)
1997 into the path. In this case, you can also stop the completion after
1998 the file name, to get entries inserted as top level in the file.
2000 When `full-file-path', include the full file path."
2001 :group 'org-refile
2002 :type '(choice
2003 (const :tag "Not" nil)
2004 (const :tag "Yes" t)
2005 (const :tag "Start with file name" file)
2006 (const :tag "Start with full file path" full-file-path)))
2008 (defcustom org-outline-path-complete-in-steps t
2009 "Non-nil means complete the outline path in hierarchical steps.
2010 When Org-mode uses the refile interface to select an outline path
2011 \(see variable `org-refile-use-outline-path'), the completion of
2012 the path can be done is a single go, or if can be done in steps down
2013 the headline hierarchy. Going in steps is probably the best if you
2014 do not use a special completion package like `ido' or `icicles'.
2015 However, when using these packages, going in one step can be very
2016 fast, while still showing the whole path to the entry."
2017 :group 'org-refile
2018 :type 'boolean)
2020 (defcustom org-refile-allow-creating-parent-nodes nil
2021 "Non-nil means allow to create new nodes as refile targets.
2022 New nodes are then created by adding \"/new node name\" to the completion
2023 of an existing node. When the value of this variable is `confirm',
2024 new node creation must be confirmed by the user (recommended)
2025 When nil, the completion must match an existing entry.
2027 Note that, if the new heading is not seen by the criteria
2028 listed in `org-refile-targets', multiple instances of the same
2029 heading would be created by trying again to file under the new
2030 heading."
2031 :group 'org-refile
2032 :type '(choice
2033 (const :tag "Never" nil)
2034 (const :tag "Always" t)
2035 (const :tag "Prompt for confirmation" confirm)))
2037 (defcustom org-refile-active-region-within-subtree nil
2038 "Non-nil means also refile active region within a subtree.
2040 By default `org-refile' doesn't allow refiling regions if they
2041 don't contain a set of subtrees, but it might be convenient to
2042 do so sometimes: in that case, the first line of the region is
2043 converted to a headline before refiling."
2044 :group 'org-refile
2045 :version "24.1"
2046 :type 'boolean)
2048 (defgroup org-todo nil
2049 "Options concerning TODO items in Org-mode."
2050 :tag "Org TODO"
2051 :group 'org)
2053 (defgroup org-progress nil
2054 "Options concerning Progress logging in Org-mode."
2055 :tag "Org Progress"
2056 :group 'org-time)
2058 (defvar org-todo-interpretation-widgets
2059 '((:tag "Sequence (cycling hits every state)" sequence)
2060 (:tag "Type (cycling directly to DONE)" type))
2061 "The available interpretation symbols for customizing `org-todo-keywords'.
2062 Interested libraries should add to this list.")
2064 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2065 "List of TODO entry keyword sequences and their interpretation.
2066 \\<org-mode-map>This is a list of sequences.
2068 Each sequence starts with a symbol, either `sequence' or `type',
2069 indicating if the keywords should be interpreted as a sequence of
2070 action steps, or as different types of TODO items. The first
2071 keywords are states requiring action - these states will select a headline
2072 for inclusion into the global TODO list Org-mode produces. If one of
2073 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2074 signify that no further action is necessary. If \"|\" is not found,
2075 the last keyword is treated as the only DONE state of the sequence.
2077 The command \\[org-todo] cycles an entry through these states, and one
2078 additional state where no keyword is present. For details about this
2079 cycling, see the manual.
2081 TODO keywords and interpretation can also be set on a per-file basis with
2082 the special #+SEQ_TODO and #+TYP_TODO lines.
2084 Each keyword can optionally specify a character for fast state selection
2085 \(in combination with the variable `org-use-fast-todo-selection')
2086 and specifiers for state change logging, using the same syntax
2087 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
2088 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2089 indicates to record a time stamp each time this state is selected.
2091 Each keyword may also specify if a timestamp or a note should be
2092 recorded when entering or leaving the state, by adding additional
2093 characters in the parenthesis after the keyword. This looks like this:
2094 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2095 record only the time of the state change. With X and Y being either
2096 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2097 Y when leaving the state if and only if the *target* state does not
2098 define X. You may omit any of the fast-selection key or X or /Y,
2099 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2101 For backward compatibility, this variable may also be just a list
2102 of keywords - in this case the interpretation (sequence or type) will be
2103 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2104 :group 'org-todo
2105 :group 'org-keywords
2106 :type '(choice
2107 (repeat :tag "Old syntax, just keywords"
2108 (string :tag "Keyword"))
2109 (repeat :tag "New syntax"
2110 (cons
2111 (choice
2112 :tag "Interpretation"
2113 ;;Quick and dirty way to see
2114 ;;`org-todo-interpretations'. This takes the
2115 ;;place of item arguments
2116 :convert-widget
2117 (lambda (widget)
2118 (widget-put widget
2119 :args (mapcar
2120 #'(lambda (x)
2121 (widget-convert
2122 (cons 'const x)))
2123 org-todo-interpretation-widgets))
2124 widget))
2125 (repeat
2126 (string :tag "Keyword"))))))
2128 (defvar org-todo-keywords-1 nil
2129 "All TODO and DONE keywords active in a buffer.")
2130 (make-variable-buffer-local 'org-todo-keywords-1)
2131 (defvar org-todo-keywords-for-agenda nil)
2132 (defvar org-done-keywords-for-agenda nil)
2133 (defvar org-drawers-for-agenda nil)
2134 (defvar org-todo-keyword-alist-for-agenda nil)
2135 (defvar org-tag-alist-for-agenda nil)
2136 (defvar org-agenda-contributing-files nil)
2137 (defvar org-not-done-keywords nil)
2138 (make-variable-buffer-local 'org-not-done-keywords)
2139 (defvar org-done-keywords nil)
2140 (make-variable-buffer-local 'org-done-keywords)
2141 (defvar org-todo-heads nil)
2142 (make-variable-buffer-local 'org-todo-heads)
2143 (defvar org-todo-sets nil)
2144 (make-variable-buffer-local 'org-todo-sets)
2145 (defvar org-todo-log-states nil)
2146 (make-variable-buffer-local 'org-todo-log-states)
2147 (defvar org-todo-kwd-alist nil)
2148 (make-variable-buffer-local 'org-todo-kwd-alist)
2149 (defvar org-todo-key-alist nil)
2150 (make-variable-buffer-local 'org-todo-key-alist)
2151 (defvar org-todo-key-trigger nil)
2152 (make-variable-buffer-local 'org-todo-key-trigger)
2154 (defcustom org-todo-interpretation 'sequence
2155 "Controls how TODO keywords are interpreted.
2156 This variable is in principle obsolete and is only used for
2157 backward compatibility, if the interpretation of todo keywords is
2158 not given already in `org-todo-keywords'. See that variable for
2159 more information."
2160 :group 'org-todo
2161 :group 'org-keywords
2162 :type '(choice (const sequence)
2163 (const type)))
2165 (defcustom org-use-fast-todo-selection t
2166 "Non-nil means use the fast todo selection scheme with C-c C-t.
2167 This variable describes if and under what circumstances the cycling
2168 mechanism for TODO keywords will be replaced by a single-key, direct
2169 selection scheme.
2171 When nil, fast selection is never used.
2173 When the symbol `prefix', it will be used when `org-todo' is called with
2174 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
2175 in an agenda buffer.
2177 When t, fast selection is used by default. In this case, the prefix
2178 argument forces cycling instead.
2180 In all cases, the special interface is only used if access keys have actually
2181 been assigned by the user, i.e. if keywords in the configuration are followed
2182 by a letter in parenthesis, like TODO(t)."
2183 :group 'org-todo
2184 :type '(choice
2185 (const :tag "Never" nil)
2186 (const :tag "By default" t)
2187 (const :tag "Only with C-u C-c C-t" prefix)))
2189 (defcustom org-provide-todo-statistics t
2190 "Non-nil means update todo statistics after insert and toggle.
2191 ALL-HEADLINES means update todo statistics by including headlines
2192 with no TODO keyword as well, counting them as not done.
2193 A list of TODO keywords means the same, but skip keywords that are
2194 not in this list.
2196 When this is set, todo statistics is updated in the parent of the
2197 current entry each time a todo state is changed."
2198 :group 'org-todo
2199 :type '(choice
2200 (const :tag "Yes, only for TODO entries" t)
2201 (const :tag "Yes, including all entries" 'all-headlines)
2202 (repeat :tag "Yes, for TODOs in this list"
2203 (string :tag "TODO keyword"))
2204 (other :tag "No TODO statistics" nil)))
2206 (defcustom org-hierarchical-todo-statistics t
2207 "Non-nil means TODO statistics covers just direct children.
2208 When nil, all entries in the subtree are considered.
2209 This has only an effect if `org-provide-todo-statistics' is set.
2210 To set this to nil for only a single subtree, use a COOKIE_DATA
2211 property and include the word \"recursive\" into the value."
2212 :group 'org-todo
2213 :type 'boolean)
2215 (defcustom org-after-todo-state-change-hook nil
2216 "Hook which is run after the state of a TODO item was changed.
2217 The new state (a string with a TODO keyword, or nil) is available in the
2218 Lisp variable `org-state'."
2219 :group 'org-todo
2220 :type 'hook)
2222 (defvar org-blocker-hook nil
2223 "Hook for functions that are allowed to block a state change.
2225 Each function gets as its single argument a property list, see
2226 `org-trigger-hook' for more information about this list.
2228 If any of the functions in this hook returns nil, the state change
2229 is blocked.")
2231 (defvar org-trigger-hook nil
2232 "Hook for functions that are triggered by a state change.
2234 Each function gets as its single argument a property list with at least
2235 the following elements:
2237 (:type type-of-change :position pos-at-entry-start
2238 :from old-state :to new-state)
2240 Depending on the type, more properties may be present.
2242 This mechanism is currently implemented for:
2244 TODO state changes
2245 ------------------
2246 :type todo-state-change
2247 :from previous state (keyword as a string), or nil, or a symbol
2248 'todo' or 'done', to indicate the general type of state.
2249 :to new state, like in :from")
2251 (defcustom org-enforce-todo-dependencies nil
2252 "Non-nil means undone TODO entries will block switching the parent to DONE.
2253 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2254 be blocked if any prior sibling is not yet done.
2255 Finally, if the parent is blocked because of ordered siblings of its own,
2256 the child will also be blocked."
2257 :set (lambda (var val)
2258 (set var val)
2259 (if val
2260 (add-hook 'org-blocker-hook
2261 'org-block-todo-from-children-or-siblings-or-parent)
2262 (remove-hook 'org-blocker-hook
2263 'org-block-todo-from-children-or-siblings-or-parent)))
2264 :group 'org-todo
2265 :type 'boolean)
2267 (defcustom org-enforce-todo-checkbox-dependencies nil
2268 "Non-nil means unchecked boxes will block switching the parent to DONE.
2269 When this is nil, checkboxes have no influence on switching TODO states.
2270 When non-nil, you first need to check off all check boxes before the TODO
2271 entry can be switched to DONE.
2272 This variable needs to be set before org.el is loaded, and you need to
2273 restart Emacs after a change to make the change effective. The only way
2274 to change is while Emacs is running is through the customize interface."
2275 :set (lambda (var val)
2276 (set var val)
2277 (if val
2278 (add-hook 'org-blocker-hook
2279 'org-block-todo-from-checkboxes)
2280 (remove-hook 'org-blocker-hook
2281 'org-block-todo-from-checkboxes)))
2282 :group 'org-todo
2283 :type 'boolean)
2285 (defcustom org-treat-insert-todo-heading-as-state-change nil
2286 "Non-nil means inserting a TODO heading is treated as state change.
2287 So when the command \\[org-insert-todo-heading] is used, state change
2288 logging will apply if appropriate. When nil, the new TODO item will
2289 be inserted directly, and no logging will take place."
2290 :group 'org-todo
2291 :type 'boolean)
2293 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2294 "Non-nil means switching TODO states with S-cursor counts as state change.
2295 This is the default behavior. However, setting this to nil allows a
2296 convenient way to select a TODO state and bypass any logging associated
2297 with that."
2298 :group 'org-todo
2299 :type 'boolean)
2301 (defcustom org-todo-state-tags-triggers nil
2302 "Tag changes that should be triggered by TODO state changes.
2303 This is a list. Each entry is
2305 (state-change (tag . flag) .......)
2307 State-change can be a string with a state, and empty string to indicate the
2308 state that has no TODO keyword, or it can be one of the symbols `todo'
2309 or `done', meaning any not-done or done state, respectively."
2310 :group 'org-todo
2311 :group 'org-tags
2312 :type '(repeat
2313 (cons (choice :tag "When changing to"
2314 (const :tag "Not-done state" todo)
2315 (const :tag "Done state" done)
2316 (string :tag "State"))
2317 (repeat
2318 (cons :tag "Tag action"
2319 (string :tag "Tag")
2320 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2322 (defcustom org-log-done nil
2323 "Information to record when a task moves to the DONE state.
2325 Possible values are:
2327 nil Don't add anything, just change the keyword
2328 time Add a time stamp to the task
2329 note Prompt for a note and add it with template `org-log-note-headings'
2331 This option can also be set with on a per-file-basis with
2333 #+STARTUP: nologdone
2334 #+STARTUP: logdone
2335 #+STARTUP: lognotedone
2337 You can have local logging settings for a subtree by setting the LOGGING
2338 property to one or more of these keywords."
2339 :group 'org-todo
2340 :group 'org-progress
2341 :type '(choice
2342 (const :tag "No logging" nil)
2343 (const :tag "Record CLOSED timestamp" time)
2344 (const :tag "Record CLOSED timestamp with note." note)))
2346 ;; Normalize old uses of org-log-done.
2347 (cond
2348 ((eq org-log-done t) (setq org-log-done 'time))
2349 ((and (listp org-log-done) (memq 'done org-log-done))
2350 (setq org-log-done 'note)))
2352 (defcustom org-log-reschedule nil
2353 "Information to record when the scheduling date of a tasks is modified.
2355 Possible values are:
2357 nil Don't add anything, just change the date
2358 time Add a time stamp to the task
2359 note Prompt for a note and add it with template `org-log-note-headings'
2361 This option can also be set with on a per-file-basis with
2363 #+STARTUP: nologreschedule
2364 #+STARTUP: logreschedule
2365 #+STARTUP: lognotereschedule"
2366 :group 'org-todo
2367 :group 'org-progress
2368 :type '(choice
2369 (const :tag "No logging" nil)
2370 (const :tag "Record timestamp" time)
2371 (const :tag "Record timestamp with note." note)))
2373 (defcustom org-log-redeadline nil
2374 "Information to record when the deadline date of a tasks is modified.
2376 Possible values are:
2378 nil Don't add anything, just change the date
2379 time Add a time stamp to the task
2380 note Prompt for a note and add it with template `org-log-note-headings'
2382 This option can also be set with on a per-file-basis with
2384 #+STARTUP: nologredeadline
2385 #+STARTUP: logredeadline
2386 #+STARTUP: lognoteredeadline
2388 You can have local logging settings for a subtree by setting the LOGGING
2389 property to one or more of these keywords."
2390 :group 'org-todo
2391 :group 'org-progress
2392 :type '(choice
2393 (const :tag "No logging" nil)
2394 (const :tag "Record timestamp" time)
2395 (const :tag "Record timestamp with note." note)))
2397 (defcustom org-log-note-clock-out nil
2398 "Non-nil means record a note when clocking out of an item.
2399 This can also be configured on a per-file basis by adding one of
2400 the following lines anywhere in the buffer:
2402 #+STARTUP: lognoteclock-out
2403 #+STARTUP: nolognoteclock-out"
2404 :group 'org-todo
2405 :group 'org-progress
2406 :type 'boolean)
2408 (defcustom org-log-done-with-time t
2409 "Non-nil means the CLOSED time stamp will contain date and time.
2410 When nil, only the date will be recorded."
2411 :group 'org-progress
2412 :type 'boolean)
2414 (defcustom org-log-note-headings
2415 '((done . "CLOSING NOTE %t")
2416 (state . "State %-12s from %-12S %t")
2417 (note . "Note taken on %t")
2418 (reschedule . "Rescheduled from %S on %t")
2419 (delschedule . "Not scheduled, was %S on %t")
2420 (redeadline . "New deadline from %S on %t")
2421 (deldeadline . "Removed deadline, was %S on %t")
2422 (refile . "Refiled on %t")
2423 (clock-out . ""))
2424 "Headings for notes added to entries.
2425 The value is an alist, with the car being a symbol indicating the note
2426 context, and the cdr is the heading to be used. The heading may also be the
2427 empty string.
2428 %t in the heading will be replaced by a time stamp.
2429 %T will be an active time stamp instead the default inactive one
2430 %d will be replaced by a short-format time stamp.
2431 %D will be replaced by an active short-format time stamp.
2432 %s will be replaced by the new TODO state, in double quotes.
2433 %S will be replaced by the old TODO state, in double quotes.
2434 %u will be replaced by the user name.
2435 %U will be replaced by the full user name.
2437 In fact, it is not a good idea to change the `state' entry, because
2438 agenda log mode depends on the format of these entries."
2439 :group 'org-todo
2440 :group 'org-progress
2441 :type '(list :greedy t
2442 (cons (const :tag "Heading when closing an item" done) string)
2443 (cons (const :tag
2444 "Heading when changing todo state (todo sequence only)"
2445 state) string)
2446 (cons (const :tag "Heading when just taking a note" note) string)
2447 (cons (const :tag "Heading when clocking out" clock-out) string)
2448 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2449 (cons (const :tag "Heading when rescheduling" reschedule) string)
2450 (cons (const :tag "Heading when changing deadline" redeadline) string)
2451 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2452 (cons (const :tag "Heading when refiling" refile) string)))
2454 (unless (assq 'note org-log-note-headings)
2455 (push '(note . "%t") org-log-note-headings))
2457 (defcustom org-log-into-drawer nil
2458 "Non-nil means insert state change notes and time stamps into a drawer.
2459 When nil, state changes notes will be inserted after the headline and
2460 any scheduling and clock lines, but not inside a drawer.
2462 The value of this variable should be the name of the drawer to use.
2463 LOGBOOK is proposed as the default drawer for this purpose, you can
2464 also set this to a string to define the drawer of your choice.
2466 A value of t is also allowed, representing \"LOGBOOK\".
2468 If this variable is set, `org-log-state-notes-insert-after-drawers'
2469 will be ignored.
2471 You can set the property LOG_INTO_DRAWER to overrule this setting for
2472 a subtree."
2473 :group 'org-todo
2474 :group 'org-progress
2475 :type '(choice
2476 (const :tag "Not into a drawer" nil)
2477 (const :tag "LOGBOOK" t)
2478 (string :tag "Other")))
2480 (if (fboundp 'defvaralias)
2481 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2483 (defun org-log-into-drawer ()
2484 "Return the value of `org-log-into-drawer', but let properties overrule.
2485 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2486 used instead of the default value."
2487 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit)))
2488 (cond
2489 ((or (not p) (equal p "nil")) org-log-into-drawer)
2490 ((equal p "t") "LOGBOOK")
2491 (t p))))
2493 (defcustom org-log-state-notes-insert-after-drawers nil
2494 "Non-nil means insert state change notes after any drawers in entry.
2495 Only the drawers that *immediately* follow the headline and the
2496 deadline/scheduled line are skipped.
2497 When nil, insert notes right after the heading and perhaps the line
2498 with deadline/scheduling if present.
2500 This variable will have no effect if `org-log-into-drawer' is
2501 set."
2502 :group 'org-todo
2503 :group 'org-progress
2504 :type 'boolean)
2506 (defcustom org-log-states-order-reversed t
2507 "Non-nil means the latest state note will be directly after heading.
2508 When nil, the state change notes will be ordered according to time."
2509 :group 'org-todo
2510 :group 'org-progress
2511 :type 'boolean)
2513 (defcustom org-todo-repeat-to-state nil
2514 "The TODO state to which a repeater should return the repeating task.
2515 By default this is the first task in a TODO sequence, or the previous state
2516 in a TODO_TYP set. But you can specify another task here.
2517 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2518 :group 'org-todo
2519 :version "24.1"
2520 :type '(choice (const :tag "Head of sequence" nil)
2521 (string :tag "Specific state")))
2523 (defcustom org-log-repeat 'time
2524 "Non-nil means record moving through the DONE state when triggering repeat.
2525 An auto-repeating task is immediately switched back to TODO when
2526 marked DONE. If you are not logging state changes (by adding \"@\"
2527 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2528 record a closing note, there will be no record of the task moving
2529 through DONE. This variable forces taking a note anyway.
2531 nil Don't force a record
2532 time Record a time stamp
2533 note Record a note
2535 This option can also be set with on a per-file-basis with
2537 #+STARTUP: logrepeat
2538 #+STARTUP: lognoterepeat
2539 #+STARTUP: nologrepeat
2541 You can have local logging settings for a subtree by setting the LOGGING
2542 property to one or more of these keywords."
2543 :group 'org-todo
2544 :group 'org-progress
2545 :type '(choice
2546 (const :tag "Don't force a record" nil)
2547 (const :tag "Force recording the DONE state" time)
2548 (const :tag "Force recording a note with the DONE state" note)))
2551 (defgroup org-priorities nil
2552 "Priorities in Org-mode."
2553 :tag "Org Priorities"
2554 :group 'org-todo)
2556 (defcustom org-enable-priority-commands t
2557 "Non-nil means priority commands are active.
2558 When nil, these commands will be disabled, so that you never accidentally
2559 set a priority."
2560 :group 'org-priorities
2561 :type 'boolean)
2563 (defcustom org-highest-priority ?A
2564 "The highest priority of TODO items. A character like ?A, ?B etc.
2565 Must have a smaller ASCII number than `org-lowest-priority'."
2566 :group 'org-priorities
2567 :type 'character)
2569 (defcustom org-lowest-priority ?C
2570 "The lowest priority of TODO items. A character like ?A, ?B etc.
2571 Must have a larger ASCII number than `org-highest-priority'."
2572 :group 'org-priorities
2573 :type 'character)
2575 (defcustom org-default-priority ?B
2576 "The default priority of TODO items.
2577 This is the priority an item gets if no explicit priority is given.
2578 When starting to cycle on an empty priority the first step in the cycle
2579 depends on `org-priority-start-cycle-with-default'. The resulting first
2580 step priority must not exceed the range from `org-highest-priority' to
2581 `org-lowest-priority' which means that `org-default-priority' has to be
2582 in this range exclusive or inclusive the range boundaries. Else the
2583 first step refuses to set the default and the second will fall back
2584 to (depending on the command used) the highest or lowest priority."
2585 :group 'org-priorities
2586 :type 'character)
2588 (defcustom org-priority-start-cycle-with-default t
2589 "Non-nil means start with default priority when starting to cycle.
2590 When this is nil, the first step in the cycle will be (depending on the
2591 command used) one higher or lower than the default priority.
2592 See also `org-default-priority'."
2593 :group 'org-priorities
2594 :type 'boolean)
2596 (defcustom org-get-priority-function nil
2597 "Function to extract the priority from a string.
2598 The string is normally the headline. If this is nil Org computes the
2599 priority from the priority cookie like [#A] in the headline. It returns
2600 an integer, increasing by 1000 for each priority level.
2601 The user can set a different function here, which should take a string
2602 as an argument and return the numeric priority."
2603 :group 'org-priorities
2604 :version "24.1"
2605 :type 'function)
2607 (defgroup org-time nil
2608 "Options concerning time stamps and deadlines in Org-mode."
2609 :tag "Org Time"
2610 :group 'org)
2612 (defcustom org-insert-labeled-timestamps-at-point nil
2613 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2614 When nil, these labeled time stamps are forces into the second line of an
2615 entry, just after the headline. When scheduling from the global TODO list,
2616 the time stamp will always be forced into the second line."
2617 :group 'org-time
2618 :type 'boolean)
2620 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2621 "Formats for `format-time-string' which are used for time stamps.
2622 It is not recommended to change this constant.")
2624 (defcustom org-time-stamp-rounding-minutes '(0 5)
2625 "Number of minutes to round time stamps to.
2626 These are two values, the first applies when first creating a time stamp.
2627 The second applies when changing it with the commands `S-up' and `S-down'.
2628 When changing the time stamp, this means that it will change in steps
2629 of N minutes, as given by the second value.
2631 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2632 numbers should be factors of 60, so for example 5, 10, 15.
2634 When this is larger than 1, you can still force an exact time stamp by using
2635 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2636 and by using a prefix arg to `S-up/down' to specify the exact number
2637 of minutes to shift."
2638 :group 'org-time
2639 :get #'(lambda (var) ; Make sure both elements are there
2640 (if (integerp (default-value var))
2641 (list (default-value var) 5)
2642 (default-value var)))
2643 :type '(list
2644 (integer :tag "when inserting times")
2645 (integer :tag "when modifying times")))
2647 ;; Normalize old customizations of this variable.
2648 (when (integerp org-time-stamp-rounding-minutes)
2649 (setq org-time-stamp-rounding-minutes
2650 (list org-time-stamp-rounding-minutes
2651 org-time-stamp-rounding-minutes)))
2653 (defcustom org-display-custom-times nil
2654 "Non-nil means overlay custom formats over all time stamps.
2655 The formats are defined through the variable `org-time-stamp-custom-formats'.
2656 To turn this on on a per-file basis, insert anywhere in the file:
2657 #+STARTUP: customtime"
2658 :group 'org-time
2659 :set 'set-default
2660 :type 'sexp)
2661 (make-variable-buffer-local 'org-display-custom-times)
2663 (defcustom org-time-stamp-custom-formats
2664 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2665 "Custom formats for time stamps. See `format-time-string' for the syntax.
2666 These are overlaid over the default ISO format if the variable
2667 `org-display-custom-times' is set. Time like %H:%M should be at the
2668 end of the second format. The custom formats are also honored by export
2669 commands, if custom time display is turned on at the time of export."
2670 :group 'org-time
2671 :type 'sexp)
2673 (defun org-time-stamp-format (&optional long inactive)
2674 "Get the right format for a time string."
2675 (let ((f (if long (cdr org-time-stamp-formats)
2676 (car org-time-stamp-formats))))
2677 (if inactive
2678 (concat "[" (substring f 1 -1) "]")
2679 f)))
2681 (defcustom org-time-clocksum-format "%d:%02d"
2682 "The format string used when creating CLOCKSUM lines.
2683 This is also used when org-mode generates a time duration."
2684 :group 'org-time
2685 :type 'string)
2687 (defcustom org-time-clocksum-use-fractional nil
2688 "If non-nil, \\[org-clock-display] uses fractional times.
2689 org-mode generates a time duration."
2690 :group 'org-time
2691 :type 'boolean)
2693 (defcustom org-time-clocksum-fractional-format "%.2f"
2694 "The format string used when creating CLOCKSUM lines, or when
2695 org-mode generates a time duration."
2696 :group 'org-time
2697 :type 'string)
2699 (defcustom org-deadline-warning-days 14
2700 "No. of days before expiration during which a deadline becomes active.
2701 This variable governs the display in sparse trees and in the agenda.
2702 When 0 or negative, it means use this number (the absolute value of it)
2703 even if a deadline has a different individual lead time specified.
2705 Custom commands can set this variable in the options section."
2706 :group 'org-time
2707 :group 'org-agenda-daily/weekly
2708 :type 'integer)
2710 (defcustom org-read-date-prefer-future t
2711 "Non-nil means assume future for incomplete date input from user.
2712 This affects the following situations:
2713 1. The user gives a month but not a year.
2714 For example, if it is April and you enter \"feb 2\", this will be read
2715 as Feb 2, *next* year. \"May 5\", however, will be this year.
2716 2. The user gives a day, but no month.
2717 For example, if today is the 15th, and you enter \"3\", Org-mode will
2718 read this as the third of *next* month. However, if you enter \"17\",
2719 it will be considered as *this* month.
2721 If you set this variable to the symbol `time', then also the following
2722 will work:
2724 3. If the user gives a time, but no day. If the time is before now,
2725 to will be interpreted as tomorrow.
2727 Currently none of this works for ISO week specifications.
2729 When this option is nil, the current day, month and year will always be
2730 used as defaults.
2732 See also `org-agenda-jump-prefer-future'."
2733 :group 'org-time
2734 :type '(choice
2735 (const :tag "Never" nil)
2736 (const :tag "Check month and day" t)
2737 (const :tag "Check month, day, and time" time)))
2739 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
2740 "Should the agenda jump command prefer the future for incomplete dates?
2741 The default is to do the same as configured in `org-read-date-prefer-future'.
2742 But you can also set a deviating value here.
2743 This may t or nil, or the symbol `org-read-date-prefer-future'."
2744 :group 'org-agenda
2745 :group 'org-time
2746 :version "24.1"
2747 :type '(choice
2748 (const :tag "Use org-read-date-prefer-future"
2749 org-read-date-prefer-future)
2750 (const :tag "Never" nil)
2751 (const :tag "Always" t)))
2753 (defcustom org-read-date-force-compatible-dates t
2754 "Should date/time prompt force dates that are guaranteed to work in Emacs?
2756 Depending on the system Emacs is running on, certain dates cannot
2757 be represented with the type used internally to represent time.
2758 Dates between 1970-1-1 and 2038-1-1 can always be represented
2759 correctly. Some systems allow for earlier dates, some for later,
2760 some for both. One way to find out it to insert any date into an
2761 Org buffer, putting the cursor on the year and hitting S-up and
2762 S-down to test the range.
2764 When this variable is set to t, the date/time prompt will not let
2765 you specify dates outside the 1970-2037 range, so it is certain that
2766 these dates will work in whatever version of Emacs you are
2767 running, and also that you can move a file from one Emacs implementation
2768 to another. WHenever Org is forcing the year for you, it will display
2769 a message and beep.
2771 When this variable is nil, Org will check if the date is
2772 representable in the specific Emacs implementation you are using.
2773 If not, it will force a year, usually the current year, and beep
2774 to remind you. Currently this setting is not recommended because
2775 the likelihood that you will open your Org files in an Emacs that
2776 has limited date range is not negligible.
2778 A workaround for this problem is to use diary sexp dates for time
2779 stamps outside of this range."
2780 :group 'org-time
2781 :version "24.1"
2782 :type 'boolean)
2784 (defcustom org-read-date-display-live t
2785 "Non-nil means display current interpretation of date prompt live.
2786 This display will be in an overlay, in the minibuffer."
2787 :group 'org-time
2788 :type 'boolean)
2790 (defcustom org-read-date-popup-calendar t
2791 "Non-nil means pop up a calendar when prompting for a date.
2792 In the calendar, the date can be selected with mouse-1. However, the
2793 minibuffer will also be active, and you can simply enter the date as well.
2794 When nil, only the minibuffer will be available."
2795 :group 'org-time
2796 :type 'boolean)
2797 (if (fboundp 'defvaralias)
2798 (defvaralias 'org-popup-calendar-for-date-prompt
2799 'org-read-date-popup-calendar))
2801 (defcustom org-read-date-minibuffer-setup-hook nil
2802 "Hook to be used to set up keys for the date/time interface.
2803 Add key definitions to `minibuffer-local-map', which will be a temporary
2804 copy."
2805 :group 'org-time
2806 :type 'hook)
2808 (defcustom org-extend-today-until 0
2809 "The hour when your day really ends. Must be an integer.
2810 This has influence for the following applications:
2811 - When switching the agenda to \"today\". It it is still earlier than
2812 the time given here, the day recognized as TODAY is actually yesterday.
2813 - When a date is read from the user and it is still before the time given
2814 here, the current date and time will be assumed to be yesterday, 23:59.
2815 Also, timestamps inserted in remember templates follow this rule.
2817 IMPORTANT: This is a feature whose implementation is and likely will
2818 remain incomplete. Really, it is only here because past midnight seems to
2819 be the favorite working time of John Wiegley :-)"
2820 :group 'org-time
2821 :type 'integer)
2823 (defcustom org-use-effective-time nil
2824 "If non-nil, consider `org-extend-today-until' when creating timestamps.
2825 For example, if `org-extend-today-until' is 8, and it's 4am, then the
2826 \"effective time\" of any timestamps between midnight and 8am will be
2827 23:59 of the previous day."
2828 :group 'org-time
2829 :version "24.1"
2830 :type 'boolean)
2832 (defcustom org-edit-timestamp-down-means-later nil
2833 "Non-nil means S-down will increase the time in a time stamp.
2834 When nil, S-up will increase."
2835 :group 'org-time
2836 :type 'boolean)
2838 (defcustom org-calendar-follow-timestamp-change t
2839 "Non-nil means make the calendar window follow timestamp changes.
2840 When a timestamp is modified and the calendar window is visible, it will be
2841 moved to the new date."
2842 :group 'org-time
2843 :type 'boolean)
2845 (defgroup org-tags nil
2846 "Options concerning tags in Org-mode."
2847 :tag "Org Tags"
2848 :group 'org)
2850 (defcustom org-tag-alist nil
2851 "List of tags allowed in Org-mode files.
2852 When this list is nil, Org-mode will base TAG input on what is already in the
2853 buffer.
2854 The value of this variable is an alist, the car of each entry must be a
2855 keyword as a string, the cdr may be a character that is used to select
2856 that tag through the fast-tag-selection interface.
2857 See the manual for details."
2858 :group 'org-tags
2859 :type '(repeat
2860 (choice
2861 (cons (string :tag "Tag name")
2862 (character :tag "Access char"))
2863 (list :tag "Start radio group"
2864 (const :startgroup)
2865 (option (string :tag "Group description")))
2866 (list :tag "End radio group"
2867 (const :endgroup)
2868 (option (string :tag "Group description")))
2869 (const :tag "New line" (:newline)))))
2871 (defcustom org-tag-persistent-alist nil
2872 "List of tags that will always appear in all Org-mode files.
2873 This is in addition to any in buffer settings or customizations
2874 of `org-tag-alist'.
2875 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2876 The value of this variable is an alist, the car of each entry must be a
2877 keyword as a string, the cdr may be a character that is used to select
2878 that tag through the fast-tag-selection interface.
2879 See the manual for details.
2880 To disable these tags on a per-file basis, insert anywhere in the file:
2881 #+STARTUP: noptag"
2882 :group 'org-tags
2883 :type '(repeat
2884 (choice
2885 (cons (string :tag "Tag name")
2886 (character :tag "Access char"))
2887 (const :tag "Start radio group" (:startgroup))
2888 (const :tag "End radio group" (:endgroup))
2889 (const :tag "New line" (:newline)))))
2891 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
2892 "If non-nil, always offer completion for all tags of all agenda files.
2893 Instead of customizing this variable directly, you might want to
2894 set it locally for capture buffers, because there no list of
2895 tags in that file can be created dynamically (there are none).
2897 (add-hook 'org-capture-mode-hook
2898 (lambda ()
2899 (set (make-local-variable
2900 'org-complete-tags-always-offer-all-agenda-tags)
2901 t)))"
2902 :group 'org-tags
2903 :version "24.1"
2904 :type 'boolean)
2906 (defvar org-file-tags nil
2907 "List of tags that can be inherited by all entries in the file.
2908 The tags will be inherited if the variable `org-use-tag-inheritance'
2909 says they should be.
2910 This variable is populated from #+FILETAGS lines.")
2912 (defcustom org-use-fast-tag-selection 'auto
2913 "Non-nil means use fast tag selection scheme.
2914 This is a special interface to select and deselect tags with single keys.
2915 When nil, fast selection is never used.
2916 When the symbol `auto', fast selection is used if and only if selection
2917 characters for tags have been configured, either through the variable
2918 `org-tag-alist' or through a #+TAGS line in the buffer.
2919 When t, fast selection is always used and selection keys are assigned
2920 automatically if necessary."
2921 :group 'org-tags
2922 :type '(choice
2923 (const :tag "Always" t)
2924 (const :tag "Never" nil)
2925 (const :tag "When selection characters are configured" 'auto)))
2927 (defcustom org-fast-tag-selection-single-key nil
2928 "Non-nil means fast tag selection exits after first change.
2929 When nil, you have to press RET to exit it.
2930 During fast tag selection, you can toggle this flag with `C-c'.
2931 This variable can also have the value `expert'. In this case, the window
2932 displaying the tags menu is not even shown, until you press C-c again."
2933 :group 'org-tags
2934 :type '(choice
2935 (const :tag "No" nil)
2936 (const :tag "Yes" t)
2937 (const :tag "Expert" expert)))
2939 (defvar org-fast-tag-selection-include-todo nil
2940 "Non-nil means fast tags selection interface will also offer TODO states.
2941 This is an undocumented feature, you should not rely on it.")
2943 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2944 "The column to which tags should be indented in a headline.
2945 If this number is positive, it specifies the column. If it is negative,
2946 it means that the tags should be flushright to that column. For example,
2947 -80 works well for a normal 80 character screen.
2948 When 0, place tags directly after headline text, with only one space in
2949 between."
2950 :group 'org-tags
2951 :type 'integer)
2953 (defcustom org-auto-align-tags t
2954 "Non-nil keeps tags aligned when modifying headlines.
2955 Some operations (i.e. demoting) change the length of a headline and
2956 therefore shift the tags around. With this option turned on, after
2957 each such operation the tags are again aligned to `org-tags-column'."
2958 :group 'org-tags
2959 :type 'boolean)
2961 (defcustom org-use-tag-inheritance t
2962 "Non-nil means tags in levels apply also for sublevels.
2963 When nil, only the tags directly given in a specific line apply there.
2964 This may also be a list of tags that should be inherited, or a regexp that
2965 matches tags that should be inherited. Additional control is possible
2966 with the variable `org-tags-exclude-from-inheritance' which gives an
2967 explicit list of tags to be excluded from inheritance., even if the value of
2968 `org-use-tag-inheritance' would select it for inheritance.
2970 If this option is t, a match early-on in a tree can lead to a large
2971 number of matches in the subtree when constructing the agenda or creating
2972 a sparse tree. If you only want to see the first match in a tree during
2973 a search, check out the variable `org-tags-match-list-sublevels'."
2974 :group 'org-tags
2975 :type '(choice
2976 (const :tag "Not" nil)
2977 (const :tag "Always" t)
2978 (repeat :tag "Specific tags" (string :tag "Tag"))
2979 (regexp :tag "Tags matched by regexp")))
2981 (defcustom org-tags-exclude-from-inheritance nil
2982 "List of tags that should never be inherited.
2983 This is a way to exclude a few tags from inheritance. For way to do
2984 the opposite, to actively allow inheritance for selected tags,
2985 see the variable `org-use-tag-inheritance'."
2986 :group 'org-tags
2987 :type '(repeat (string :tag "Tag")))
2989 (defun org-tag-inherit-p (tag)
2990 "Check if TAG is one that should be inherited."
2991 (cond
2992 ((member tag org-tags-exclude-from-inheritance) nil)
2993 ((eq org-use-tag-inheritance t) t)
2994 ((not org-use-tag-inheritance) nil)
2995 ((stringp org-use-tag-inheritance)
2996 (string-match org-use-tag-inheritance tag))
2997 ((listp org-use-tag-inheritance)
2998 (member tag org-use-tag-inheritance))
2999 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3001 (defcustom org-tags-match-list-sublevels t
3002 "Non-nil means list also sublevels of headlines matching a search.
3003 This variable applies to tags/property searches, and also to stuck
3004 projects because this search is based on a tags match as well.
3006 When set to the symbol `indented', sublevels are indented with
3007 leading dots.
3009 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3010 the sublevels of a headline matching a tag search often also match
3011 the same search. Listing all of them can create very long lists.
3012 Setting this variable to nil causes subtrees of a match to be skipped.
3014 This variable is semi-obsolete and probably should always be true. It
3015 is better to limit inheritance to certain tags using the variables
3016 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3017 :group 'org-tags
3018 :type '(choice
3019 (const :tag "No, don't list them" nil)
3020 (const :tag "Yes, do list them" t)
3021 (const :tag "List them, indented with leading dots" indented)))
3023 (defcustom org-tags-sort-function nil
3024 "When set, tags are sorted using this function as a comparator."
3025 :group 'org-tags
3026 :type '(choice
3027 (const :tag "No sorting" nil)
3028 (const :tag "Alphabetical" string<)
3029 (const :tag "Reverse alphabetical" string>)
3030 (function :tag "Custom function" nil)))
3032 (defvar org-tags-history nil
3033 "History of minibuffer reads for tags.")
3034 (defvar org-last-tags-completion-table nil
3035 "The last used completion table for tags.")
3036 (defvar org-after-tags-change-hook nil
3037 "Hook that is run after the tags in a line have changed.")
3039 (defgroup org-properties nil
3040 "Options concerning properties in Org-mode."
3041 :tag "Org Properties"
3042 :group 'org)
3044 (defcustom org-property-format "%-10s %s"
3045 "How property key/value pairs should be formatted by `indent-line'.
3046 When `indent-line' hits a property definition, it will format the line
3047 according to this format, mainly to make sure that the values are
3048 lined-up with respect to each other."
3049 :group 'org-properties
3050 :type 'string)
3052 (defcustom org-properties-postprocess-alist nil
3053 "Alist of properties and functions to adjust inserted values.
3054 Elements of this alist must be of the form
3056 ([string] [function])
3058 where [string] must be a property name and [function] must be a
3059 lambda expression: this lambda expression must take one argument,
3060 the value to adjust, and return the new value as a string.
3062 For example, this element will allow the property \"Remaining\"
3063 to be updated wrt the relation between the \"Effort\" property
3064 and the clock summary:
3066 ((\"Remaining\" (lambda(value)
3067 (let ((clocksum (org-clock-sum-current-item))
3068 (effort (org-duration-string-to-minutes
3069 (org-entry-get (point) \"Effort\"))))
3070 (org-minutes-to-hh:mm-string (- effort clocksum))))))"
3071 :group 'org-properties
3072 :version "24.1"
3073 :type 'alist)
3075 (defcustom org-use-property-inheritance nil
3076 "Non-nil means properties apply also for sublevels.
3078 This setting is chiefly used during property searches. Turning it on can
3079 cause significant overhead when doing a search, which is why it is not
3080 on by default.
3082 When nil, only the properties directly given in the current entry count.
3083 When t, every property is inherited. The value may also be a list of
3084 properties that should have inheritance, or a regular expression matching
3085 properties that should be inherited.
3087 However, note that some special properties use inheritance under special
3088 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3089 and the properties ending in \"_ALL\" when they are used as descriptor
3090 for valid values of a property.
3092 Note for programmers:
3093 When querying an entry with `org-entry-get', you can control if inheritance
3094 should be used. By default, `org-entry-get' looks only at the local
3095 properties. You can request inheritance by setting the inherit argument
3096 to t (to force inheritance) or to `selective' (to respect the setting
3097 in this variable)."
3098 :group 'org-properties
3099 :type '(choice
3100 (const :tag "Not" nil)
3101 (const :tag "Always" t)
3102 (repeat :tag "Specific properties" (string :tag "Property"))
3103 (regexp :tag "Properties matched by regexp")))
3105 (defun org-property-inherit-p (property)
3106 "Check if PROPERTY is one that should be inherited."
3107 (cond
3108 ((eq org-use-property-inheritance t) t)
3109 ((not org-use-property-inheritance) nil)
3110 ((stringp org-use-property-inheritance)
3111 (string-match org-use-property-inheritance property))
3112 ((listp org-use-property-inheritance)
3113 (member property org-use-property-inheritance))
3114 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3116 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3117 "The default column format, if no other format has been defined.
3118 This variable can be set on the per-file basis by inserting a line
3120 #+COLUMNS: %25ITEM ....."
3121 :group 'org-properties
3122 :type 'string)
3124 (defcustom org-columns-ellipses ".."
3125 "The ellipses to be used when a field in column view is truncated.
3126 When this is the empty string, as many characters as possible are shown,
3127 but then there will be no visual indication that the field has been truncated.
3128 When this is a string of length N, the last N characters of a truncated
3129 field are replaced by this string. If the column is narrower than the
3130 ellipses string, only part of the ellipses string will be shown."
3131 :group 'org-properties
3132 :type 'string)
3134 (defcustom org-columns-modify-value-for-display-function nil
3135 "Function that modifies values for display in column view.
3136 For example, it can be used to cut out a certain part from a time stamp.
3137 The function must take 2 arguments:
3139 column-title The title of the column (*not* the property name)
3140 value The value that should be modified.
3142 The function should return the value that should be displayed,
3143 or nil if the normal value should be used."
3144 :group 'org-properties
3145 :type 'function)
3147 (defcustom org-effort-property "Effort"
3148 "The property that is being used to keep track of effort estimates.
3149 Effort estimates given in this property need to have the format H:MM."
3150 :group 'org-properties
3151 :group 'org-progress
3152 :type '(string :tag "Property"))
3154 (defconst org-global-properties-fixed
3155 '(("VISIBILITY_ALL" . "folded children content all")
3156 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3157 "List of property/value pairs that can be inherited by any entry.
3159 These are fixed values, for the preset properties. The user variable
3160 that can be used to add to this list is `org-global-properties'.
3162 The entries in this list are cons cells where the car is a property
3163 name and cdr is a string with the value. If the value represents
3164 multiple items like an \"_ALL\" property, separate the items by
3165 spaces.")
3167 (defcustom org-global-properties nil
3168 "List of property/value pairs that can be inherited by any entry.
3170 This list will be combined with the constant `org-global-properties-fixed'.
3172 The entries in this list are cons cells where the car is a property
3173 name and cdr is a string with the value.
3175 You can set buffer-local values for the same purpose in the variable
3176 `org-file-properties' this by adding lines like
3178 #+PROPERTY: NAME VALUE"
3179 :group 'org-properties
3180 :type '(repeat
3181 (cons (string :tag "Property")
3182 (string :tag "Value"))))
3184 (defvar org-file-properties nil
3185 "List of property/value pairs that can be inherited by any entry.
3186 Valid for the current buffer.
3187 This variable is populated from #+PROPERTY lines.")
3188 (make-variable-buffer-local 'org-file-properties)
3190 (defgroup org-agenda nil
3191 "Options concerning agenda views in Org-mode."
3192 :tag "Org Agenda"
3193 :group 'org)
3195 (defvar org-category nil
3196 "Variable used by org files to set a category for agenda display.
3197 Such files should use a file variable to set it, for example
3199 # -*- mode: org; org-category: \"ELisp\"
3201 or contain a special line
3203 #+CATEGORY: ELisp
3205 If the file does not specify a category, then file's base name
3206 is used instead.")
3207 (make-variable-buffer-local 'org-category)
3208 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3210 (defcustom org-agenda-files nil
3211 "The files to be used for agenda display.
3212 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3213 \\[org-remove-file]. You can also use customize to edit the list.
3215 If an entry is a directory, all files in that directory that are matched by
3216 `org-agenda-file-regexp' will be part of the file list.
3218 If the value of the variable is not a list but a single file name, then
3219 the list of agenda files is actually stored and maintained in that file, one
3220 agenda file per line. In this file paths can be given relative to
3221 `org-directory'. Tilde expansion and environment variable substitution
3222 are also made."
3223 :group 'org-agenda
3224 :type '(choice
3225 (repeat :tag "List of files and directories" file)
3226 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3228 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3229 "Regular expression to match files for `org-agenda-files'.
3230 If any element in the list in that variable contains a directory instead
3231 of a normal file, all files in that directory that are matched by this
3232 regular expression will be included."
3233 :group 'org-agenda
3234 :type 'regexp)
3236 (defcustom org-agenda-text-search-extra-files nil
3237 "List of extra files to be searched by text search commands.
3238 These files will be search in addition to the agenda files by the
3239 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3240 Note that these files will only be searched for text search commands,
3241 not for the other agenda views like todo lists, tag searches or the weekly
3242 agenda. This variable is intended to list notes and possibly archive files
3243 that should also be searched by these two commands.
3244 In fact, if the first element in the list is the symbol `agenda-archives',
3245 than all archive files of all agenda files will be added to the search
3246 scope."
3247 :group 'org-agenda
3248 :type '(set :greedy t
3249 (const :tag "Agenda Archives" agenda-archives)
3250 (repeat :inline t (file))))
3252 (if (fboundp 'defvaralias)
3253 (defvaralias 'org-agenda-multi-occur-extra-files
3254 'org-agenda-text-search-extra-files))
3256 (defcustom org-agenda-skip-unavailable-files nil
3257 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3258 A nil value means to remove them, after a query, from the list."
3259 :group 'org-agenda
3260 :type 'boolean)
3262 (defcustom org-calendar-to-agenda-key [?c]
3263 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3264 The command `org-calendar-goto-agenda' will be bound to this key. The
3265 default is the character `c' because then `c' can be used to switch back and
3266 forth between agenda and calendar."
3267 :group 'org-agenda
3268 :type 'sexp)
3270 (defcustom org-calendar-agenda-action-key [?k]
3271 "The key to be installed in `calendar-mode-map' for agenda-action.
3272 The command `org-agenda-action' will be bound to this key. The
3273 default is the character `k' because we use the same key in the agenda."
3274 :group 'org-agenda
3275 :type 'sexp)
3277 (defcustom org-calendar-insert-diary-entry-key [?i]
3278 "The key to be installed in `calendar-mode-map' for adding diary entries.
3279 This option is irrelevant until `org-agenda-diary-file' has been configured
3280 to point to an Org-mode file. When that is the case, the command
3281 `org-agenda-diary-entry' will be bound to the key given here, by default
3282 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3283 if you want to continue doing this, you need to change this to a different
3284 key."
3285 :group 'org-agenda
3286 :type 'sexp)
3288 (defcustom org-agenda-diary-file 'diary-file
3289 "File to which to add new entries with the `i' key in agenda and calendar.
3290 When this is the symbol `diary-file', the functionality in the Emacs
3291 calendar will be used to add entries to the `diary-file'. But when this
3292 points to a file, `org-agenda-diary-entry' will be used instead."
3293 :group 'org-agenda
3294 :type '(choice
3295 (const :tag "The standard Emacs diary file" diary-file)
3296 (file :tag "Special Org file diary entries")))
3298 (eval-after-load "calendar"
3299 '(progn
3300 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3301 'org-calendar-goto-agenda)
3302 (org-defkey calendar-mode-map org-calendar-agenda-action-key
3303 'org-agenda-action)
3304 (add-hook 'calendar-mode-hook
3305 (lambda ()
3306 (unless (eq org-agenda-diary-file 'diary-file)
3307 (define-key calendar-mode-map
3308 org-calendar-insert-diary-entry-key
3309 'org-agenda-diary-entry))))))
3311 (defgroup org-latex nil
3312 "Options for embedding LaTeX code into Org-mode."
3313 :tag "Org LaTeX"
3314 :group 'org)
3316 (defcustom org-format-latex-options
3317 '(:foreground default :background default :scale 1.0
3318 :html-foreground "Black" :html-background "Transparent"
3319 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3320 "Options for creating images from LaTeX fragments.
3321 This is a property list with the following properties:
3322 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3323 `default' means use the foreground of the default face.
3324 :background the background color, or \"Transparent\".
3325 `default' means use the background of the default face.
3326 :scale a scaling factor for the size of the images, to get more pixels
3327 :html-foreground, :html-background, :html-scale
3328 the same numbers for HTML export.
3329 :matchers a list indicating which matchers should be used to
3330 find LaTeX fragments. Valid members of this list are:
3331 \"begin\" find environments
3332 \"$1\" find single characters surrounded by $.$
3333 \"$\" find math expressions surrounded by $...$
3334 \"$$\" find math expressions surrounded by $$....$$
3335 \"\\(\" find math expressions surrounded by \\(...\\)
3336 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3337 :group 'org-latex
3338 :type 'plist)
3340 (defcustom org-format-latex-signal-error t
3341 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3342 When nil, just push out a message."
3343 :group 'org-latex
3344 :version "24.1"
3345 :type 'boolean)
3347 (defcustom org-latex-to-mathml-jar-file nil
3348 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3349 Use this to specify additional executable file say a jar file.
3351 When using MathToWeb as the converter, specify the full-path to
3352 your mathtoweb.jar file."
3353 :group 'org-latex
3354 :version "24.1"
3355 :type '(choice
3356 (const :tag "None" nil)
3357 (file :tag "JAR file" :must-match t)))
3359 (defcustom org-latex-to-mathml-convert-command nil
3360 "Command to convert LaTeX fragments to MathML.
3361 Replace format-specifiers in the command as noted below and use
3362 `shell-command' to convert LaTeX to MathML.
3363 %j: Executable file in fully expanded form as specified by
3364 `org-latex-to-mathml-jar-file'.
3365 %I: Input LaTeX file in fully expanded form
3366 %o: Output MathML file
3367 This command is used by `org-create-math-formula'.
3369 When using MathToWeb as the converter, set this to
3370 \"java -jar %j -unicode -force -df %o %I\"."
3371 :group 'org-latex
3372 :version "24.1"
3373 :type '(choice
3374 (const :tag "None" nil)
3375 (string :tag "\nShell command")))
3377 (defun org-format-latex-mathml-available-p ()
3378 "Return t if `org-latex-to-mathml-convert-command' is usable."
3379 (save-match-data
3380 (when (and (boundp 'org-latex-to-mathml-convert-command)
3381 org-latex-to-mathml-convert-command)
3382 (let ((executable (car (split-string
3383 org-latex-to-mathml-convert-command))))
3384 (when (executable-find executable)
3385 (if (string-match
3386 "%j" org-latex-to-mathml-convert-command)
3387 (file-readable-p org-latex-to-mathml-jar-file)
3388 t))))))
3390 (defcustom org-format-latex-header "\\documentclass{article}
3391 \\usepackage[usenames]{color}
3392 \\usepackage{amsmath}
3393 \\usepackage[mathscr]{eucal}
3394 \\pagestyle{empty} % do not remove
3395 \[PACKAGES]
3396 \[DEFAULT-PACKAGES]
3397 % The settings below are copied from fullpage.sty
3398 \\setlength{\\textwidth}{\\paperwidth}
3399 \\addtolength{\\textwidth}{-3cm}
3400 \\setlength{\\oddsidemargin}{1.5cm}
3401 \\addtolength{\\oddsidemargin}{-2.54cm}
3402 \\setlength{\\evensidemargin}{\\oddsidemargin}
3403 \\setlength{\\textheight}{\\paperheight}
3404 \\addtolength{\\textheight}{-\\headheight}
3405 \\addtolength{\\textheight}{-\\headsep}
3406 \\addtolength{\\textheight}{-\\footskip}
3407 \\addtolength{\\textheight}{-3cm}
3408 \\setlength{\\topmargin}{1.5cm}
3409 \\addtolength{\\topmargin}{-2.54cm}"
3410 "The document header used for processing LaTeX fragments.
3411 It is imperative that this header make sure that no page number
3412 appears on the page. The package defined in the variables
3413 `org-export-latex-default-packages-alist' and `org-export-latex-packages-alist'
3414 will either replace the placeholder \"[PACKAGES]\" in this header, or they
3415 will be appended."
3416 :group 'org-latex
3417 :type 'string)
3419 (defvar org-format-latex-header-extra nil)
3421 (defun org-set-packages-alist (var val)
3422 "Set the packages alist and make sure it has 3 elements per entry."
3423 (set var (mapcar (lambda (x)
3424 (if (and (consp x) (= (length x) 2))
3425 (list (car x) (nth 1 x) t)
3427 val)))
3429 (defun org-get-packages-alist (var)
3431 "Get the packages alist and make sure it has 3 elements per entry."
3432 (mapcar (lambda (x)
3433 (if (and (consp x) (= (length x) 2))
3434 (list (car x) (nth 1 x) t)
3436 (default-value var)))
3438 ;; The following variables are defined here because is it also used
3439 ;; when formatting latex fragments. Originally it was part of the
3440 ;; LaTeX exporter, which is why the name includes "export".
3441 (defcustom org-export-latex-default-packages-alist
3442 '(("AUTO" "inputenc" t)
3443 ("T1" "fontenc" t)
3444 ("" "fixltx2e" nil)
3445 ("" "graphicx" t)
3446 ("" "longtable" nil)
3447 ("" "float" nil)
3448 ("" "wrapfig" nil)
3449 ("" "soul" t)
3450 ("" "textcomp" t)
3451 ("" "marvosym" t)
3452 ("" "wasysym" t)
3453 ("" "latexsym" t)
3454 ("" "amssymb" t)
3455 ("" "hyperref" nil)
3456 "\\tolerance=1000"
3458 "Alist of default packages to be inserted in the header.
3459 Change this only if one of the packages here causes an incompatibility
3460 with another package you are using.
3461 The packages in this list are needed by one part or another of Org-mode
3462 to function properly.
3464 - inputenc, fontenc: for basic font and character selection
3465 - textcomp, marvosymb, wasysym, latexsym, amssym: for various symbols used
3466 for interpreting the entities in `org-entities'. You can skip some of these
3467 packages if you don't use any of the symbols in it.
3468 - graphicx: for including images
3469 - float, wrapfig: for figure placement
3470 - longtable: for long tables
3471 - hyperref: for cross references
3473 Therefore you should not modify this variable unless you know what you
3474 are doing. The one reason to change it anyway is that you might be loading
3475 some other package that conflicts with one of the default packages.
3476 Each cell is of the format \( \"options\" \"package\" snippet-flag\).
3477 If SNIPPET-FLAG is t, the package also needs to be included when
3478 compiling LaTeX snippets into images for inclusion into HTML."
3479 :group 'org-export-latex
3480 :set 'org-set-packages-alist
3481 :get 'org-get-packages-alist
3482 :version "24.1"
3483 :type '(repeat
3484 (choice
3485 (list :tag "options/package pair"
3486 (string :tag "options")
3487 (string :tag "package")
3488 (boolean :tag "Snippet"))
3489 (string :tag "A line of LaTeX"))))
3491 (defcustom org-export-latex-packages-alist nil
3492 "Alist of packages to be inserted in every LaTeX header.
3493 These will be inserted after `org-export-latex-default-packages-alist'.
3494 Each cell is of the format \( \"options\" \"package\" snippet-flag \).
3495 SNIPPET-FLAG, when t, indicates that this package is also needed when
3496 turning LaTeX snippets into images for inclusion into HTML.
3497 Make sure that you only list packages here which:
3498 - you want in every file
3499 - do not conflict with the default packages in
3500 `org-export-latex-default-packages-alist'
3501 - do not conflict with the setup in `org-format-latex-header'."
3502 :group 'org-export-latex
3503 :set 'org-set-packages-alist
3504 :get 'org-get-packages-alist
3505 :type '(repeat
3506 (choice
3507 (list :tag "options/package pair"
3508 (string :tag "options")
3509 (string :tag "package")
3510 (boolean :tag "Snippet"))
3511 (string :tag "A line of LaTeX"))))
3514 (defgroup org-appearance nil
3515 "Settings for Org-mode appearance."
3516 :tag "Org Appearance"
3517 :group 'org)
3519 (defcustom org-level-color-stars-only nil
3520 "Non-nil means fontify only the stars in each headline.
3521 When nil, the entire headline is fontified.
3522 Changing it requires restart of `font-lock-mode' to become effective
3523 also in regions already fontified."
3524 :group 'org-appearance
3525 :type 'boolean)
3527 (defcustom org-hide-leading-stars nil
3528 "Non-nil means hide the first N-1 stars in a headline.
3529 This works by using the face `org-hide' for these stars. This
3530 face is white for a light background, and black for a dark
3531 background. You may have to customize the face `org-hide' to
3532 make this work.
3533 Changing it requires restart of `font-lock-mode' to become effective
3534 also in regions already fontified.
3535 You may also set this on a per-file basis by adding one of the following
3536 lines to the buffer:
3538 #+STARTUP: hidestars
3539 #+STARTUP: showstars"
3540 :group 'org-appearance
3541 :type 'boolean)
3543 (defcustom org-hidden-keywords nil
3544 "List of symbols corresponding to keywords to be hidden the org buffer.
3545 For example, a value '(title) for this list will make the document's title
3546 appear in the buffer without the initial #+TITLE: keyword."
3547 :group 'org-appearance
3548 :version "24.1"
3549 :type '(set (const :tag "#+AUTHOR" author)
3550 (const :tag "#+DATE" date)
3551 (const :tag "#+EMAIL" email)
3552 (const :tag "#+TITLE" title)))
3554 (defcustom org-fontify-done-headline nil
3555 "Non-nil means change the face of a headline if it is marked DONE.
3556 Normally, only the TODO/DONE keyword indicates the state of a headline.
3557 When this is non-nil, the headline after the keyword is set to the
3558 `org-headline-done' as an additional indication."
3559 :group 'org-appearance
3560 :type 'boolean)
3562 (defcustom org-fontify-emphasized-text t
3563 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3564 Changing this variable requires a restart of Emacs to take effect."
3565 :group 'org-appearance
3566 :type 'boolean)
3568 (defcustom org-fontify-whole-heading-line nil
3569 "Non-nil means fontify the whole line for headings.
3570 This is useful when setting a background color for the
3571 org-level-* faces."
3572 :group 'org-appearance
3573 :type 'boolean)
3575 (defcustom org-highlight-latex-fragments-and-specials nil
3576 "Non-nil means fontify what is treated specially by the exporters."
3577 :group 'org-appearance
3578 :type 'boolean)
3580 (defcustom org-hide-emphasis-markers nil
3581 "Non-nil mean font-lock should hide the emphasis marker characters."
3582 :group 'org-appearance
3583 :type 'boolean)
3585 (defcustom org-pretty-entities nil
3586 "Non-nil means show entities as UTF8 characters.
3587 When nil, the \\name form remains in the buffer."
3588 :group 'org-appearance
3589 :version "24.1"
3590 :type 'boolean)
3592 (defcustom org-pretty-entities-include-sub-superscripts t
3593 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3594 :group 'org-appearance
3595 :version "24.1"
3596 :type 'boolean)
3598 (defvar org-emph-re nil
3599 "Regular expression for matching emphasis.
3600 After a match, the match groups contain these elements:
3601 0 The match of the full regular expression, including the characters
3602 before and after the proper match
3603 1 The character before the proper match, or empty at beginning of line
3604 2 The proper match, including the leading and trailing markers
3605 3 The leading marker like * or /, indicating the type of highlighting
3606 4 The text between the emphasis markers, not including the markers
3607 5 The character after the match, empty at the end of a line")
3608 (defvar org-verbatim-re nil
3609 "Regular expression for matching verbatim text.")
3610 (defvar org-emphasis-regexp-components) ; defined just below
3611 (defvar org-emphasis-alist) ; defined just below
3612 (defun org-set-emph-re (var val)
3613 "Set variable and compute the emphasis regular expression."
3614 (set var val)
3615 (when (and (boundp 'org-emphasis-alist)
3616 (boundp 'org-emphasis-regexp-components)
3617 org-emphasis-alist org-emphasis-regexp-components)
3618 (let* ((e org-emphasis-regexp-components)
3619 (pre (car e))
3620 (post (nth 1 e))
3621 (border (nth 2 e))
3622 (body (nth 3 e))
3623 (nl (nth 4 e))
3624 (body1 (concat body "*?"))
3625 (markers (mapconcat 'car org-emphasis-alist ""))
3626 (vmarkers (mapconcat
3627 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3628 org-emphasis-alist "")))
3629 ;; make sure special characters appear at the right position in the class
3630 (if (string-match "\\^" markers)
3631 (setq markers (concat (replace-match "" t t markers) "^")))
3632 (if (string-match "-" markers)
3633 (setq markers (concat (replace-match "" t t markers) "-")))
3634 (if (string-match "\\^" vmarkers)
3635 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3636 (if (string-match "-" vmarkers)
3637 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3638 (if (> nl 0)
3639 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3640 (int-to-string nl) "\\}")))
3641 ;; Make the regexp
3642 (setq org-emph-re
3643 (concat "\\([" pre "]\\|^\\)"
3644 "\\("
3645 "\\([" markers "]\\)"
3646 "\\("
3647 "[^" border "]\\|"
3648 "[^" border "]"
3649 body1
3650 "[^" border "]"
3651 "\\)"
3652 "\\3\\)"
3653 "\\([" post "]\\|$\\)"))
3654 (setq org-verbatim-re
3655 (concat "\\([" pre "]\\|^\\)"
3656 "\\("
3657 "\\([" vmarkers "]\\)"
3658 "\\("
3659 "[^" border "]\\|"
3660 "[^" border "]"
3661 body1
3662 "[^" border "]"
3663 "\\)"
3664 "\\3\\)"
3665 "\\([" post "]\\|$\\)")))))
3667 (defcustom org-emphasis-regexp-components
3668 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
3669 "Components used to build the regular expression for emphasis.
3670 This is a list with five entries. Terminology: In an emphasis string
3671 like \" *strong word* \", we call the initial space PREMATCH, the final
3672 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3673 and \"trong wor\" is the body. The different components in this variable
3674 specify what is allowed/forbidden in each part:
3676 pre Chars allowed as prematch. Beginning of line will be allowed too.
3677 post Chars allowed as postmatch. End of line will be allowed too.
3678 border The chars *forbidden* as border characters.
3679 body-regexp A regexp like \".\" to match a body character. Don't use
3680 non-shy groups here, and don't allow newline here.
3681 newline The maximum number of newlines allowed in an emphasis exp.
3683 Use customize to modify this, or restart Emacs after changing it."
3684 :group 'org-appearance
3685 :set 'org-set-emph-re
3686 :type '(list
3687 (sexp :tag "Allowed chars in pre ")
3688 (sexp :tag "Allowed chars in post ")
3689 (sexp :tag "Forbidden chars in border ")
3690 (sexp :tag "Regexp for body ")
3691 (integer :tag "number of newlines allowed")
3692 (option (boolean :tag "Please ignore this button"))))
3694 (defcustom org-emphasis-alist
3695 `(("*" bold "<b>" "</b>")
3696 ("/" italic "<i>" "</i>")
3697 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
3698 ("=" org-code "<code>" "</code>" verbatim)
3699 ("~" org-verbatim "<code>" "</code>" verbatim)
3700 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
3701 "<del>" "</del>")
3703 "Special syntax for emphasized text.
3704 Text starting and ending with a special character will be emphasized, for
3705 example *bold*, _underlined_ and /italic/. This variable sets the marker
3706 characters, the face to be used by font-lock for highlighting in Org-mode
3707 Emacs buffers, and the HTML tags to be used for this.
3708 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
3709 For DocBook export, see the variable `org-export-docbook-emphasis-alist'.
3710 Use customize to modify this, or restart Emacs after changing it."
3711 :group 'org-appearance
3712 :set 'org-set-emph-re
3713 :type '(repeat
3714 (list
3715 (string :tag "Marker character")
3716 (choice
3717 (face :tag "Font-lock-face")
3718 (plist :tag "Face property list"))
3719 (string :tag "HTML start tag")
3720 (string :tag "HTML end tag")
3721 (option (const verbatim)))))
3723 (defvar org-protecting-blocks
3724 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
3725 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
3726 This is needed for font-lock setup.")
3728 ;;; Miscellaneous options
3730 (defgroup org-completion nil
3731 "Completion in Org-mode."
3732 :tag "Org Completion"
3733 :group 'org)
3735 (defcustom org-completion-use-ido nil
3736 "Non-nil means use ido completion wherever possible.
3737 Note that `ido-mode' must be active for this variable to be relevant.
3738 If you decide to turn this variable on, you might well want to turn off
3739 `org-outline-path-complete-in-steps'.
3740 See also `org-completion-use-iswitchb'."
3741 :group 'org-completion
3742 :type 'boolean)
3744 (defcustom org-completion-use-iswitchb nil
3745 "Non-nil means use iswitchb completion wherever possible.
3746 Note that `iswitchb-mode' must be active for this variable to be relevant.
3747 If you decide to turn this variable on, you might well want to turn off
3748 `org-outline-path-complete-in-steps'.
3749 Note that this variable has only an effect if `org-completion-use-ido' is nil."
3750 :group 'org-completion
3751 :type 'boolean)
3753 (defcustom org-completion-fallback-command 'hippie-expand
3754 "The expansion command called by \\[pcomplete] in normal context.
3755 Normal means, no org-mode-specific context."
3756 :group 'org-completion
3757 :type 'function)
3759 ;;; Functions and variables from their packages
3760 ;; Declared here to avoid compiler warnings
3762 ;; XEmacs only
3763 (defvar outline-mode-menu-heading)
3764 (defvar outline-mode-menu-show)
3765 (defvar outline-mode-menu-hide)
3766 (defvar zmacs-regions) ; XEmacs regions
3768 ;; Emacs only
3769 (defvar mark-active)
3771 ;; Various packages
3772 (declare-function calendar-absolute-from-iso "cal-iso" (date))
3773 (declare-function calendar-forward-day "cal-move" (arg))
3774 (declare-function calendar-goto-date "cal-move" (date))
3775 (declare-function calendar-goto-today "cal-move" ())
3776 (declare-function calendar-iso-from-absolute "cal-iso" (date))
3777 (defvar calc-embedded-close-formula)
3778 (defvar calc-embedded-open-formula)
3779 (declare-function cdlatex-tab "ext:cdlatex" ())
3780 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
3781 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3782 (defvar font-lock-unfontify-region-function)
3783 (declare-function iswitchb-read-buffer "iswitchb"
3784 (prompt &optional default require-match start matches-set))
3785 (defvar iswitchb-temp-buflist)
3786 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
3787 (defvar org-agenda-tags-todo-honor-ignore-options)
3788 (declare-function org-agenda-skip "org-agenda" ())
3789 (declare-function
3790 org-agenda-format-item "org-agenda"
3791 (extra txt &optional category tags dotime noprefix remove-re habitp))
3792 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
3793 (declare-function org-agenda-change-all-lines "org-agenda"
3794 (newhead hdmarker &optional fixface just-this))
3795 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
3796 (declare-function org-agenda-maybe-redo "org-agenda" ())
3797 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
3798 (beg end))
3799 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
3800 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
3801 "org-agenda" (&optional end))
3802 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
3803 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
3804 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
3805 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
3806 (declare-function org-indent-mode "org-indent" (&optional arg))
3807 (declare-function parse-time-string "parse-time" (string))
3808 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
3809 (declare-function org-export-latex-fix-inputenc "org-latex" ())
3810 (declare-function orgtbl-send-table "org-table" (&optional maybe))
3811 (defvar remember-data-file)
3812 (defvar texmathp-why)
3813 (declare-function speedbar-line-directory "speedbar" (&optional depth))
3814 (declare-function table--at-cell-p "table" (position &optional object at-column))
3816 (defvar w3m-current-url)
3817 (defvar w3m-current-title)
3819 (defvar org-latex-regexps)
3821 ;;; Autoload and prepare some org modules
3823 ;; Some table stuff that needs to be defined here, because it is used
3824 ;; by the functions setting up org-mode or checking for table context.
3826 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
3827 "Detect an org-type or table-type table.")
3828 (defconst org-table-line-regexp "^[ \t]*|"
3829 "Detect an org-type table line.")
3830 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
3831 "Detect an org-type table line.")
3832 (defconst org-table-hline-regexp "^[ \t]*|-"
3833 "Detect an org-type table hline.")
3834 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
3835 "Detect a table-type table hline.")
3836 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
3837 "Detect the first line outside a table when searching from within it.
3838 This works for both table types.")
3840 ;; Autoload the functions in org-table.el that are needed by functions here.
3842 (eval-and-compile
3843 (org-autoload "org-table"
3844 '(org-table-align org-table-begin org-table-blank-field
3845 org-table-convert org-table-convert-region org-table-copy-down
3846 org-table-copy-region org-table-create
3847 org-table-create-or-convert-from-region
3848 org-table-create-with-table.el org-table-current-dline
3849 org-table-cut-region org-table-delete-column org-table-edit-field
3850 org-table-edit-formulas org-table-end org-table-eval-formula
3851 org-table-export org-table-field-info
3852 org-table-get-stored-formulas org-table-goto-column
3853 org-table-hline-and-move org-table-import org-table-insert-column
3854 org-table-insert-hline org-table-insert-row org-table-iterate
3855 org-table-justify-field-maybe org-table-kill-row
3856 org-table-maybe-eval-formula org-table-maybe-recalculate-line
3857 org-table-move-column org-table-move-column-left
3858 org-table-move-column-right org-table-move-row
3859 org-table-move-row-down org-table-move-row-up
3860 org-table-next-field org-table-next-row org-table-paste-rectangle
3861 org-table-previous-field org-table-recalculate
3862 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
3863 org-table-toggle-coordinate-overlays
3864 org-table-toggle-formula-debugger org-table-wrap-region
3865 orgtbl-mode turn-on-orgtbl org-table-to-lisp
3866 orgtbl-to-generic orgtbl-to-tsv orgtbl-to-csv orgtbl-to-latex
3867 orgtbl-to-orgtbl orgtbl-to-html orgtbl-to-texinfo)))
3869 (defun org-at-table-p (&optional table-type)
3870 "Return t if the cursor is inside an org-type table.
3871 If TABLE-TYPE is non-nil, also check for table.el-type tables."
3872 (if org-enable-table-editor
3873 (save-excursion
3874 (beginning-of-line 1)
3875 (looking-at (if table-type org-table-any-line-regexp
3876 org-table-line-regexp)))
3877 nil))
3878 (defsubst org-table-p () (org-at-table-p))
3880 (defun org-at-table.el-p ()
3881 "Return t if and only if we are at a table.el table."
3882 (and (org-at-table-p 'any)
3883 (save-excursion
3884 (goto-char (org-table-begin 'any))
3885 (looking-at org-table1-hline-regexp))))
3886 (defun org-table-recognize-table.el ()
3887 "If there is a table.el table nearby, recognize it and move into it."
3888 (if org-table-tab-recognizes-table.el
3889 (if (org-at-table.el-p)
3890 (progn
3891 (beginning-of-line 1)
3892 (if (looking-at org-table-dataline-regexp)
3894 (if (looking-at org-table1-hline-regexp)
3895 (progn
3896 (beginning-of-line 2)
3897 (if (looking-at org-table-any-border-regexp)
3898 (beginning-of-line -1)))))
3899 (if (re-search-forward "|" (org-table-end t) t)
3900 (progn
3901 (require 'table)
3902 (if (table--at-cell-p (point))
3904 (message "recognizing table.el table...")
3905 (table-recognize-table)
3906 (message "recognizing table.el table...done")))
3907 (error "This should not happen"))
3909 nil)
3910 nil))
3912 (defun org-at-table-hline-p ()
3913 "Return t if the cursor is inside a hline in a table."
3914 (if org-enable-table-editor
3915 (save-excursion
3916 (beginning-of-line 1)
3917 (looking-at org-table-hline-regexp))
3918 nil))
3920 (defvar org-table-clean-did-remove-column nil)
3922 (defun org-table-map-tables (function &optional quietly)
3923 "Apply FUNCTION to the start of all tables in the buffer."
3924 (save-excursion
3925 (save-restriction
3926 (widen)
3927 (goto-char (point-min))
3928 (while (re-search-forward org-table-any-line-regexp nil t)
3929 (unless quietly
3930 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
3931 (beginning-of-line 1)
3932 (when (and (looking-at org-table-line-regexp)
3933 ;; Exclude tables in src/example/verbatim/clocktable blocks
3934 (not (org-in-block-p '("src" "example"))))
3935 (save-excursion (funcall function))
3936 (or (looking-at org-table-line-regexp)
3937 (forward-char 1)))
3938 (re-search-forward org-table-any-border-regexp nil 1))))
3939 (unless quietly (message "Mapping tables: done")))
3941 ;; Declare and autoload functions from org-exp.el & Co
3943 (declare-function org-default-export-plist "org-exp")
3944 (declare-function org-infile-export-plist "org-exp")
3945 (declare-function org-get-current-options "org-exp")
3946 (eval-and-compile
3947 (org-autoload "org-exp"
3948 '(org-export org-export-visible
3949 org-insert-export-options-template
3950 org-table-clean-before-export))
3951 (org-autoload "org-ascii"
3952 '(org-export-as-ascii org-export-ascii-preprocess
3953 org-export-as-ascii-to-buffer org-replace-region-by-ascii
3954 org-export-region-as-ascii))
3955 (org-autoload "org-latex"
3956 '(org-export-as-latex-batch org-export-as-latex-to-buffer
3957 org-replace-region-by-latex org-export-region-as-latex
3958 org-export-as-latex org-export-as-pdf
3959 org-export-as-pdf-and-open))
3960 (org-autoload "org-html"
3961 '(org-export-as-html-and-open
3962 org-export-as-html-batch org-export-as-html-to-buffer
3963 org-replace-region-by-html org-export-region-as-html
3964 org-export-as-html))
3965 (org-autoload "org-docbook"
3966 '(org-export-as-docbook-batch org-export-as-docbook-to-buffer
3967 org-replace-region-by-docbook org-export-region-as-docbook
3968 org-export-as-docbook-pdf org-export-as-docbook-pdf-and-open
3969 org-export-as-docbook))
3970 (org-autoload "org-icalendar"
3971 '(org-export-icalendar-this-file
3972 org-export-icalendar-all-agenda-files
3973 org-export-icalendar-combine-agenda-files))
3974 (org-autoload "org-xoxo" '(org-export-as-xoxo))
3975 (org-autoload "org-beamer" '(org-beamer-mode org-beamer-sectioning)))
3977 ;; Declare and autoload functions from org-agenda.el
3979 (eval-and-compile
3980 (org-autoload "org-agenda"
3981 '(org-agenda org-agenda-list org-search-view
3982 org-todo-list org-tags-view org-agenda-list-stuck-projects
3983 org-diary org-agenda-to-appt
3984 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
3986 ;; Autoload org-remember
3988 (eval-and-compile
3989 (org-autoload "org-remember"
3990 '(org-remember-insinuate org-remember-annotation
3991 org-remember-apply-template org-remember org-remember-handler)))
3993 (eval-and-compile
3994 (org-autoload "org-capture"
3995 '(org-capture org-capture-insert-template-here
3996 org-capture-import-remember-templates)))
3998 ;; Autoload org-clock.el
4000 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
4001 (beg end))
4002 (declare-function org-clock-update-mode-line "org-clock" ())
4003 (declare-function org-resolve-clocks "org-clock"
4004 (&optional also-non-dangling-p prompt last-valid))
4005 (defvar org-clock-start-time)
4006 (defvar org-clock-marker (make-marker)
4007 "Marker recording the last clock-in.")
4008 (defvar org-clock-hd-marker (make-marker)
4009 "Marker recording the last clock-in, but the headline position.")
4010 (defvar org-clock-heading ""
4011 "The heading of the current clock entry.")
4012 (defun org-clock-is-active ()
4013 "Return non-nil if clock is currently running.
4014 The return value is actually the clock marker."
4015 (marker-buffer org-clock-marker))
4017 (eval-and-compile
4018 (org-autoload
4019 "org-clock"
4020 '(org-clock-in org-clock-out org-clock-cancel
4021 org-clock-goto org-clock-sum org-clock-display
4022 org-clock-remove-overlays org-clock-report
4023 org-clocktable-shift org-dblock-write:clocktable
4024 org-get-clocktable org-resolve-clocks)))
4026 (defun org-clock-update-time-maybe ()
4027 "If this is a CLOCK line, update it and return t.
4028 Otherwise, return nil."
4029 (interactive)
4030 (save-excursion
4031 (beginning-of-line 1)
4032 (skip-chars-forward " \t")
4033 (when (looking-at org-clock-string)
4034 (let ((re (concat "[ \t]*" org-clock-string
4035 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
4036 "\\([ \t]*=>.*\\)?\\)?"))
4037 ts te h m s neg)
4038 (cond
4039 ((not (looking-at re))
4040 nil)
4041 ((not (match-end 2))
4042 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4043 (> org-clock-marker (point))
4044 (<= org-clock-marker (point-at-eol)))
4045 ;; The clock is running here
4046 (setq org-clock-start-time
4047 (apply 'encode-time
4048 (org-parse-time-string (match-string 1))))
4049 (org-clock-update-mode-line)))
4051 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
4052 (end-of-line 1)
4053 (setq ts (match-string 1)
4054 te (match-string 3))
4055 (setq s (- (org-float-time
4056 (apply 'encode-time (org-parse-time-string te)))
4057 (org-float-time
4058 (apply 'encode-time (org-parse-time-string ts))))
4059 neg (< s 0)
4060 s (abs s)
4061 h (floor (/ s 3600))
4062 s (- s (* 3600 h))
4063 m (floor (/ s 60))
4064 s (- s (* 60 s)))
4065 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
4066 t))))))
4068 (defun org-check-running-clock ()
4069 "Check if the current buffer contains the running clock.
4070 If yes, offer to stop it and to save the buffer with the changes."
4071 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4072 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4073 (buffer-name))))
4074 (org-clock-out)
4075 (when (y-or-n-p "Save changed buffer?")
4076 (save-buffer))))
4078 (defun org-clocktable-try-shift (dir n)
4079 "Check if this line starts a clock table, if yes, shift the time block."
4080 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4081 (org-clocktable-shift dir n)))
4083 ;; Autoload org-timer.el
4085 (eval-and-compile
4086 (org-autoload
4087 "org-timer"
4088 '(org-timer-start org-timer org-timer-item
4089 org-timer-change-times-in-region
4090 org-timer-set-timer
4091 org-timer-reset-timers
4092 org-timer-show-remaining-time)))
4094 ;; Autoload org-feed.el
4096 (eval-and-compile
4097 (org-autoload
4098 "org-feed"
4099 '(org-feed-update org-feed-update-all org-feed-goto-inbox)))
4102 ;; Autoload org-indent.el
4104 ;; Define the variable already here, to make sure we have it.
4105 (defvar org-indent-mode nil
4106 "Non-nil if Org-Indent mode is enabled.
4107 Use the command `org-indent-mode' to change this variable.")
4109 (eval-and-compile
4110 (org-autoload
4111 "org-indent"
4112 '(org-indent-mode)))
4114 ;; Autoload org-mobile.el
4116 (eval-and-compile
4117 (org-autoload
4118 "org-mobile"
4119 '(org-mobile-push org-mobile-pull org-mobile-create-sumo-agenda)))
4121 ;; Autoload archiving code
4122 ;; The stuff that is needed for cycling and tags has to be defined here.
4124 (defgroup org-archive nil
4125 "Options concerning archiving in Org-mode."
4126 :tag "Org Archive"
4127 :group 'org-structure)
4129 (defcustom org-archive-location "%s_archive::"
4130 "The location where subtrees should be archived.
4132 The value of this variable is a string, consisting of two parts,
4133 separated by a double-colon. The first part is a filename and
4134 the second part is a headline.
4136 When the filename is omitted, archiving happens in the same file.
4137 %s in the filename will be replaced by the current file
4138 name (without the directory part). Archiving to a different file
4139 is useful to keep archived entries from contributing to the
4140 Org-mode Agenda.
4142 The archived entries will be filed as subtrees of the specified
4143 headline. When the headline is omitted, the subtrees are simply
4144 filed away at the end of the file, as top-level entries. Also in
4145 the heading you can use %s to represent the file name, this can be
4146 useful when using the same archive for a number of different files.
4148 Here are a few examples:
4149 \"%s_archive::\"
4150 If the current file is Projects.org, archive in file
4151 Projects.org_archive, as top-level trees. This is the default.
4153 \"::* Archived Tasks\"
4154 Archive in the current file, under the top-level headline
4155 \"* Archived Tasks\".
4157 \"~/org/archive.org::\"
4158 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4160 \"~/org/archive.org::* From %s\"
4161 Archive in file ~/org/archive.org (absolute path), under headlines
4162 \"From FILENAME\" where file name is the current file name.
4164 \"basement::** Finished Tasks\"
4165 Archive in file ./basement (relative path), as level 3 trees
4166 below the level 2 heading \"** Finished Tasks\".
4168 You may set this option on a per-file basis by adding to the buffer a
4169 line like
4171 #+ARCHIVE: basement::** Finished Tasks
4173 You may also define it locally for a subtree by setting an ARCHIVE property
4174 in the entry. If such a property is found in an entry, or anywhere up
4175 the hierarchy, it will be used."
4176 :group 'org-archive
4177 :type 'string)
4179 (defcustom org-archive-tag "ARCHIVE"
4180 "The tag that marks a subtree as archived.
4181 An archived subtree does not open during visibility cycling, and does
4182 not contribute to the agenda listings.
4183 After changing this, font-lock must be restarted in the relevant buffers to
4184 get the proper fontification."
4185 :group 'org-archive
4186 :group 'org-keywords
4187 :type 'string)
4189 (defcustom org-agenda-skip-archived-trees t
4190 "Non-nil means the agenda will skip any items located in archived trees.
4191 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4192 variable is no longer recommended, you should leave it at the value t.
4193 Instead, use the key `v' to cycle the archives-mode in the agenda."
4194 :group 'org-archive
4195 :group 'org-agenda-skip
4196 :type 'boolean)
4198 (defcustom org-columns-skip-archived-trees t
4199 "Non-nil means ignore archived trees when creating column view."
4200 :group 'org-archive
4201 :group 'org-properties
4202 :type 'boolean)
4204 (defcustom org-cycle-open-archived-trees nil
4205 "Non-nil means `org-cycle' will open archived trees.
4206 An archived tree is a tree marked with the tag ARCHIVE.
4207 When nil, archived trees will stay folded. You can still open them with
4208 normal outline commands like `show-all', but not with the cycling commands."
4209 :group 'org-archive
4210 :group 'org-cycle
4211 :type 'boolean)
4213 (defcustom org-sparse-tree-open-archived-trees nil
4214 "Non-nil means sparse tree construction shows matches in archived trees.
4215 When nil, matches in these trees are highlighted, but the trees are kept in
4216 collapsed state."
4217 :group 'org-archive
4218 :group 'org-sparse-trees
4219 :type 'boolean)
4221 (defun org-cycle-hide-archived-subtrees (state)
4222 "Re-hide all archived subtrees after a visibility state change."
4223 (when (and (not org-cycle-open-archived-trees)
4224 (not (memq state '(overview folded))))
4225 (save-excursion
4226 (let* ((globalp (memq state '(contents all)))
4227 (beg (if globalp (point-min) (point)))
4228 (end (if globalp (point-max) (org-end-of-subtree t))))
4229 (org-hide-archived-subtrees beg end)
4230 (goto-char beg)
4231 (if (looking-at (concat ".*:" org-archive-tag ":"))
4232 (message "%s" (substitute-command-keys
4233 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4235 (defun org-force-cycle-archived ()
4236 "Cycle subtree even if it is archived."
4237 (interactive)
4238 (setq this-command 'org-cycle)
4239 (let ((org-cycle-open-archived-trees t))
4240 (call-interactively 'org-cycle)))
4242 (defun org-hide-archived-subtrees (beg end)
4243 "Re-hide all archived subtrees after a visibility state change."
4244 (save-excursion
4245 (let* ((re (concat ":" org-archive-tag ":")))
4246 (goto-char beg)
4247 (while (re-search-forward re end t)
4248 (when (org-at-heading-p)
4249 (org-flag-subtree t)
4250 (org-end-of-subtree t))))))
4252 (defun org-flag-subtree (flag)
4253 (save-excursion
4254 (org-back-to-heading t)
4255 (outline-end-of-heading)
4256 (outline-flag-region (point)
4257 (progn (org-end-of-subtree t) (point))
4258 flag)))
4260 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4262 (eval-and-compile
4263 (org-autoload "org-archive"
4264 '(org-add-archive-files org-archive-subtree
4265 org-archive-to-archive-sibling org-toggle-archive-tag
4266 org-archive-subtree-default
4267 org-archive-subtree-default-with-confirmation)))
4269 ;; Autoload Column View Code
4271 (declare-function org-columns-number-to-string "org-colview")
4272 (declare-function org-columns-get-format-and-top-level "org-colview")
4273 (declare-function org-columns-compute "org-colview")
4275 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4276 '(org-columns-number-to-string org-columns-get-format-and-top-level
4277 org-columns-compute org-agenda-columns org-columns-remove-overlays
4278 org-columns org-insert-columns-dblock org-dblock-write:columnview))
4280 ;; Autoload ID code
4282 (declare-function org-id-store-link "org-id")
4283 (declare-function org-id-locations-load "org-id")
4284 (declare-function org-id-locations-save "org-id")
4285 (defvar org-id-track-globally)
4286 (org-autoload "org-id"
4287 '(org-id-get-create org-id-new org-id-copy org-id-get
4288 org-id-get-with-outline-path-completion
4289 org-id-get-with-outline-drilling org-id-store-link
4290 org-id-goto org-id-find org-id-store-link))
4292 ;; Autoload Plotting Code
4294 (org-autoload "org-plot"
4295 '(org-plot/gnuplot))
4297 ;;; Variables for pre-computed regular expressions, all buffer local
4299 (defvar org-drawer-regexp nil
4300 "Matches first line of a hidden block.")
4301 (make-variable-buffer-local 'org-drawer-regexp)
4302 (defvar org-todo-regexp nil
4303 "Matches any of the TODO state keywords.")
4304 (make-variable-buffer-local 'org-todo-regexp)
4305 (defvar org-not-done-regexp nil
4306 "Matches any of the TODO state keywords except the last one.")
4307 (make-variable-buffer-local 'org-not-done-regexp)
4308 (defvar org-not-done-heading-regexp nil
4309 "Matches a TODO headline that is not done.")
4310 (make-variable-buffer-local 'org-not-done-regexp)
4311 (defvar org-todo-line-regexp nil
4312 "Matches a headline and puts TODO state into group 2 if present.")
4313 (make-variable-buffer-local 'org-todo-line-regexp)
4314 (defvar org-complex-heading-regexp nil
4315 "Matches a headline and puts everything into groups:
4316 group 1: the stars
4317 group 2: The todo keyword, maybe
4318 group 3: Priority cookie
4319 group 4: True headline
4320 group 5: Tags")
4321 (make-variable-buffer-local 'org-complex-heading-regexp)
4322 (defvar org-complex-heading-regexp-format nil
4323 "Printf format to make regexp to match an exact headline.
4324 This regexp will match the headline of any node which has the
4325 exact headline text that is put into the format, but may have any
4326 TODO state, priority and tags.")
4327 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4328 (defvar org-todo-line-tags-regexp nil
4329 "Matches a headline and puts TODO state into group 2 if present.
4330 Also put tags into group 4 if tags are present.")
4331 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4332 (defvar org-ds-keyword-length 12
4333 "Maximum length of the Deadline and SCHEDULED keywords.")
4334 (make-variable-buffer-local 'org-ds-keyword-length)
4335 (defvar org-deadline-regexp nil
4336 "Matches the DEADLINE keyword.")
4337 (make-variable-buffer-local 'org-deadline-regexp)
4338 (defvar org-deadline-time-regexp nil
4339 "Matches the DEADLINE keyword together with a time stamp.")
4340 (make-variable-buffer-local 'org-deadline-time-regexp)
4341 (defvar org-deadline-line-regexp nil
4342 "Matches the DEADLINE keyword and the rest of the line.")
4343 (make-variable-buffer-local 'org-deadline-line-regexp)
4344 (defvar org-scheduled-regexp nil
4345 "Matches the SCHEDULED keyword.")
4346 (make-variable-buffer-local 'org-scheduled-regexp)
4347 (defvar org-scheduled-time-regexp nil
4348 "Matches the SCHEDULED keyword together with a time stamp.")
4349 (make-variable-buffer-local 'org-scheduled-time-regexp)
4350 (defvar org-closed-time-regexp nil
4351 "Matches the CLOSED keyword together with a time stamp.")
4352 (make-variable-buffer-local 'org-closed-time-regexp)
4354 (defvar org-keyword-time-regexp nil
4355 "Matches any of the 4 keywords, together with the time stamp.")
4356 (make-variable-buffer-local 'org-keyword-time-regexp)
4357 (defvar org-keyword-time-not-clock-regexp nil
4358 "Matches any of the 3 keywords, together with the time stamp.")
4359 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4360 (defvar org-maybe-keyword-time-regexp nil
4361 "Matches a timestamp, possibly preceded by a keyword.")
4362 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4363 (defvar org-planning-or-clock-line-re nil
4364 "Matches a line with planning or clock info.")
4365 (make-variable-buffer-local 'org-planning-or-clock-line-re)
4366 (defvar org-all-time-keywords nil
4367 "List of time keywords.")
4368 (make-variable-buffer-local 'org-all-time-keywords)
4370 (defconst org-plain-time-of-day-regexp
4371 (concat
4372 "\\(\\<[012]?[0-9]"
4373 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4374 "\\(--?"
4375 "\\(\\<[012]?[0-9]"
4376 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4377 "\\)?")
4378 "Regular expression to match a plain time or time range.
4379 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4380 groups carry important information:
4381 0 the full match
4382 1 the first time, range or not
4383 8 the second time, if it is a range.")
4385 (defconst org-plain-time-extension-regexp
4386 (concat
4387 "\\(\\<[012]?[0-9]"
4388 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4389 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4390 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4391 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4392 groups carry important information:
4393 0 the full match
4394 7 hours of duration
4395 9 minutes of duration")
4397 (defconst org-stamp-time-of-day-regexp
4398 (concat
4399 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4400 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4401 "\\(--?"
4402 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4403 "Regular expression to match a timestamp time or time range.
4404 After a match, the following groups carry important information:
4405 0 the full match
4406 1 date plus weekday, for back referencing to make sure both times are on the same day
4407 2 the first time, range or not
4408 4 the second time, if it is a range.")
4410 (defconst org-startup-options
4411 '(("fold" org-startup-folded t)
4412 ("overview" org-startup-folded t)
4413 ("nofold" org-startup-folded nil)
4414 ("showall" org-startup-folded nil)
4415 ("showeverything" org-startup-folded showeverything)
4416 ("content" org-startup-folded content)
4417 ("indent" org-startup-indented t)
4418 ("noindent" org-startup-indented nil)
4419 ("hidestars" org-hide-leading-stars t)
4420 ("showstars" org-hide-leading-stars nil)
4421 ("odd" org-odd-levels-only t)
4422 ("oddeven" org-odd-levels-only nil)
4423 ("align" org-startup-align-all-tables t)
4424 ("noalign" org-startup-align-all-tables nil)
4425 ("inlineimages" org-startup-with-inline-images t)
4426 ("noinlineimages" org-startup-with-inline-images nil)
4427 ("customtime" org-display-custom-times t)
4428 ("logdone" org-log-done time)
4429 ("lognotedone" org-log-done note)
4430 ("nologdone" org-log-done nil)
4431 ("lognoteclock-out" org-log-note-clock-out t)
4432 ("nolognoteclock-out" org-log-note-clock-out nil)
4433 ("logrepeat" org-log-repeat state)
4434 ("lognoterepeat" org-log-repeat note)
4435 ("nologrepeat" org-log-repeat nil)
4436 ("logreschedule" org-log-reschedule time)
4437 ("lognotereschedule" org-log-reschedule note)
4438 ("nologreschedule" org-log-reschedule nil)
4439 ("logredeadline" org-log-redeadline time)
4440 ("lognoteredeadline" org-log-redeadline note)
4441 ("nologredeadline" org-log-redeadline nil)
4442 ("logrefile" org-log-refile time)
4443 ("lognoterefile" org-log-refile note)
4444 ("nologrefile" org-log-refile nil)
4445 ("fninline" org-footnote-define-inline t)
4446 ("nofninline" org-footnote-define-inline nil)
4447 ("fnlocal" org-footnote-section nil)
4448 ("fnauto" org-footnote-auto-label t)
4449 ("fnprompt" org-footnote-auto-label nil)
4450 ("fnconfirm" org-footnote-auto-label confirm)
4451 ("fnplain" org-footnote-auto-label plain)
4452 ("fnadjust" org-footnote-auto-adjust t)
4453 ("nofnadjust" org-footnote-auto-adjust nil)
4454 ("constcgs" constants-unit-system cgs)
4455 ("constSI" constants-unit-system SI)
4456 ("noptag" org-tag-persistent-alist nil)
4457 ("hideblocks" org-hide-block-startup t)
4458 ("nohideblocks" org-hide-block-startup nil)
4459 ("beamer" org-startup-with-beamer-mode t)
4460 ("entitiespretty" org-pretty-entities t)
4461 ("entitiesplain" org-pretty-entities nil))
4462 "Variable associated with STARTUP options for org-mode.
4463 Each element is a list of three items: The startup options as written
4464 in the #+STARTUP line, the corresponding variable, and the value to
4465 set this variable to if the option is found. An optional forth element PUSH
4466 means to push this value onto the list in the variable.")
4468 (defun org-update-property-plist (key val props)
4469 "Update PROPS with KEY and VAL."
4470 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4471 (key (if appending (substring key 0 (- (length key) 1)) key))
4472 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4473 (previous (cdr (assoc key props))))
4474 (if appending
4475 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4476 (cons (cons key val) remainder))))
4478 (defconst org-block-regexp
4479 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4480 "Regular expression for hiding blocks.")
4481 (defconst org-heading-keyword-regexp-format
4482 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4483 "Printf format for a regexp matching an headline with some keyword.
4484 This regexp will match the headline of any node which has the
4485 exact keyword that is put into the format. The keyword isn't in
4486 any group by default, but the stars and the body are.")
4487 (defconst org-heading-keyword-maybe-regexp-format
4488 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4489 "Printf format for a regexp matching an headline, possibly with some keyword.
4490 This regexp can match any headline with the specified keyword, or
4491 without a keyword. The keyword isn't in any group by default,
4492 but the stars and the body are.")
4494 (defun org-set-regexps-and-options ()
4495 "Precompute regular expressions for current buffer."
4496 (when (eq major-mode 'org-mode)
4497 (org-set-local 'org-todo-kwd-alist nil)
4498 (org-set-local 'org-todo-key-alist nil)
4499 (org-set-local 'org-todo-key-trigger nil)
4500 (org-set-local 'org-todo-keywords-1 nil)
4501 (org-set-local 'org-done-keywords nil)
4502 (org-set-local 'org-todo-heads nil)
4503 (org-set-local 'org-todo-sets nil)
4504 (org-set-local 'org-todo-log-states nil)
4505 (org-set-local 'org-file-properties nil)
4506 (org-set-local 'org-file-tags nil)
4507 (let ((re (org-make-options-regexp
4508 '("CATEGORY" "TODO" "COLUMNS"
4509 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
4510 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE" "LATEX_CLASS"
4511 "OPTIONS")
4512 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4513 (splitre "[ \t]+")
4514 (scripts org-use-sub-superscripts)
4515 kwds kws0 kwsa key log value cat arch tags const links hw dws
4516 tail sep kws1 prio props ftags drawers beamer-p
4517 ext-setup-or-nil setup-contents (start 0))
4518 (save-excursion
4519 (save-restriction
4520 (widen)
4521 (goto-char (point-min))
4522 (while (or (and ext-setup-or-nil
4523 (string-match re ext-setup-or-nil start)
4524 (setq start (match-end 0)))
4525 (and (setq ext-setup-or-nil nil start 0)
4526 (re-search-forward re nil t)))
4527 (setq key (upcase (match-string 1 ext-setup-or-nil))
4528 value (org-match-string-no-properties 2 ext-setup-or-nil))
4529 (if (stringp value) (setq value (org-trim value)))
4530 (cond
4531 ((equal key "CATEGORY")
4532 (setq cat value))
4533 ((member key '("SEQ_TODO" "TODO"))
4534 (push (cons 'sequence (org-split-string value splitre)) kwds))
4535 ((equal key "TYP_TODO")
4536 (push (cons 'type (org-split-string value splitre)) kwds))
4537 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4538 ;; general TODO-like setup
4539 (push (cons (intern (downcase (match-string 1 key)))
4540 (org-split-string value splitre)) kwds))
4541 ((equal key "TAGS")
4542 (setq tags (append tags (if tags '("\\n") nil)
4543 (org-split-string value splitre))))
4544 ((equal key "COLUMNS")
4545 (org-set-local 'org-columns-default-format value))
4546 ((equal key "LINK")
4547 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4548 (push (cons (match-string 1 value)
4549 (org-trim (match-string 2 value)))
4550 links)))
4551 ((equal key "PRIORITIES")
4552 (setq prio (org-split-string value " +")))
4553 ((equal key "PROPERTY")
4554 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4555 (setq props (org-update-property-plist (match-string 1 value)
4556 (match-string 2 value)
4557 props))))
4558 ((equal key "FILETAGS")
4559 (when (string-match "\\S-" value)
4560 (setq ftags
4561 (append
4562 ftags
4563 (apply 'append
4564 (mapcar (lambda (x) (org-split-string x ":"))
4565 (org-split-string value)))))))
4566 ((equal key "DRAWERS")
4567 (setq drawers (delete-dups (append org-drawers (org-split-string value splitre)))))
4568 ((equal key "CONSTANTS")
4569 (setq const (append const (org-split-string value splitre))))
4570 ((equal key "STARTUP")
4571 (let ((opts (org-split-string value splitre))
4572 l var val)
4573 (while (setq l (pop opts))
4574 (when (setq l (assoc l org-startup-options))
4575 (setq var (nth 1 l) val (nth 2 l))
4576 (if (not (nth 3 l))
4577 (set (make-local-variable var) val)
4578 (if (not (listp (symbol-value var)))
4579 (set (make-local-variable var) nil))
4580 (set (make-local-variable var) (symbol-value var))
4581 (add-to-list var val))))))
4582 ((equal key "ARCHIVE")
4583 (setq arch value)
4584 (remove-text-properties 0 (length arch)
4585 '(face t fontified t) arch))
4586 ((equal key "LATEX_CLASS")
4587 (setq beamer-p (equal value "beamer")))
4588 ((equal key "OPTIONS")
4589 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4590 (setq scripts (read (match-string 2 value)))))
4591 ((equal key "SETUPFILE")
4592 (setq setup-contents (org-file-contents
4593 (expand-file-name
4594 (org-remove-double-quotes value))
4595 'noerror))
4596 (if (not ext-setup-or-nil)
4597 (setq ext-setup-or-nil setup-contents start 0)
4598 (setq ext-setup-or-nil
4599 (concat (substring ext-setup-or-nil 0 start)
4600 "\n" setup-contents "\n"
4601 (substring ext-setup-or-nil start)))))))
4602 ;; search for property blocks
4603 (goto-char (point-min))
4604 (while (re-search-forward org-block-regexp nil t)
4605 (when (equal "PROPERTY" (upcase (match-string 1)))
4606 (setq value (replace-regexp-in-string
4607 "[\n\r]" " " (match-string 4)))
4608 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4609 (setq props (org-update-property-plist (match-string 1 value)
4610 (match-string 2 value)
4611 props)))))))
4612 (org-set-local 'org-use-sub-superscripts scripts)
4613 (when cat
4614 (org-set-local 'org-category (intern cat))
4615 (push (cons "CATEGORY" cat) props))
4616 (when prio
4617 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4618 (setq prio (mapcar 'string-to-char prio))
4619 (org-set-local 'org-highest-priority (nth 0 prio))
4620 (org-set-local 'org-lowest-priority (nth 1 prio))
4621 (org-set-local 'org-default-priority (nth 2 prio)))
4622 (and props (org-set-local 'org-file-properties (nreverse props)))
4623 (and ftags (org-set-local 'org-file-tags
4624 (mapcar 'org-add-prop-inherited ftags)))
4625 (and drawers (org-set-local 'org-drawers drawers))
4626 (and arch (org-set-local 'org-archive-location arch))
4627 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4628 ;; Process the TODO keywords
4629 (unless kwds
4630 ;; Use the global values as if they had been given locally.
4631 (setq kwds (default-value 'org-todo-keywords))
4632 (if (stringp (car kwds))
4633 (setq kwds (list (cons org-todo-interpretation
4634 (default-value 'org-todo-keywords)))))
4635 (setq kwds (reverse kwds)))
4636 (setq kwds (nreverse kwds))
4637 (let (inter kws kw)
4638 (while (setq kws (pop kwds))
4639 (let ((kws (or
4640 (run-hook-with-args-until-success
4641 'org-todo-setup-filter-hook kws)
4642 kws)))
4643 (setq inter (pop kws) sep (member "|" kws)
4644 kws0 (delete "|" (copy-sequence kws))
4645 kwsa nil
4646 kws1 (mapcar
4647 (lambda (x)
4648 ;; 1 2
4649 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4650 (progn
4651 (setq kw (match-string 1 x)
4652 key (and (match-end 2) (match-string 2 x))
4653 log (org-extract-log-state-settings x))
4654 (push (cons kw (and key (string-to-char key))) kwsa)
4655 (and log (push log org-todo-log-states))
4657 (error "Invalid TODO keyword %s" x)))
4658 kws0)
4659 kwsa (if kwsa (append '((:startgroup))
4660 (nreverse kwsa)
4661 '((:endgroup))))
4662 hw (car kws1)
4663 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4664 tail (list inter hw (car dws) (org-last dws))))
4665 (add-to-list 'org-todo-heads hw 'append)
4666 (push kws1 org-todo-sets)
4667 (setq org-done-keywords (append org-done-keywords dws nil))
4668 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4669 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4670 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4671 (setq org-todo-sets (nreverse org-todo-sets)
4672 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4673 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4674 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4675 ;; Process the constants
4676 (when const
4677 (let (e cst)
4678 (while (setq e (pop const))
4679 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4680 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4681 (setq org-table-formula-constants-local cst)))
4683 ;; Process the tags.
4684 (when tags
4685 (let (e tgs)
4686 (while (setq e (pop tags))
4687 (cond
4688 ((equal e "{") (push '(:startgroup) tgs))
4689 ((equal e "}") (push '(:endgroup) tgs))
4690 ((equal e "\\n") (push '(:newline) tgs))
4691 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4692 (push (cons (match-string 1 e)
4693 (string-to-char (match-string 2 e)))
4694 tgs))
4695 (t (push (list e) tgs))))
4696 (org-set-local 'org-tag-alist nil)
4697 (while (setq e (pop tgs))
4698 (or (and (stringp (car e))
4699 (assoc (car e) org-tag-alist))
4700 (push e org-tag-alist)))))
4702 ;; Compute the regular expressions and other local variables.
4703 ;; Using `org-outline-regexp-bol' would complicate them much,
4704 ;; because of the fixed white space at the end of that string.
4705 (if (not org-done-keywords)
4706 (setq org-done-keywords (and org-todo-keywords-1
4707 (list (org-last org-todo-keywords-1)))))
4708 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4709 (length org-scheduled-string)
4710 (length org-clock-string)
4711 (length org-closed-string)))
4712 org-drawer-regexp
4713 (concat "^[ \t]*:\\("
4714 (mapconcat 'regexp-quote org-drawers "\\|")
4715 "\\):[ \t]*$")
4716 org-not-done-keywords
4717 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4718 org-todo-regexp
4719 (concat "\\("
4720 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4721 "\\)")
4722 org-not-done-regexp
4723 (concat "\\("
4724 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4725 "\\)")
4726 org-not-done-heading-regexp
4727 (format org-heading-keyword-regexp-format org-not-done-regexp)
4728 org-todo-line-regexp
4729 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
4730 org-complex-heading-regexp
4731 (concat "^\\(\\*+\\)"
4732 "\\(?: +" org-todo-regexp "\\)?"
4733 "\\(?: +\\(\\[#.\\]\\)\\)?"
4734 "\\(?: +\\(.*?\\)\\)?"
4735 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
4736 "[ \t]*$")
4737 org-complex-heading-regexp-format
4738 (concat "^\\(\\*+\\)"
4739 "\\(?: +" org-todo-regexp "\\)?"
4740 "\\(?: +\\(\\[#.\\]\\)\\)?"
4741 "\\(?: +"
4742 ;; Stats cookies can be stuck to body.
4743 "\\(?:\\[[0-9%%/]+\\] *\\)?"
4744 "\\(%s\\)"
4745 "\\(?: *\\[[0-9%%/]+\\]\\)?"
4746 "\\)"
4747 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
4748 "[ \t]*$")
4749 org-todo-line-tags-regexp
4750 (concat "^\\(\\*+\\)"
4751 "\\(?: +" org-todo-regexp "\\)?"
4752 "\\(?: +\\(.*?\\)\\)?"
4753 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
4754 "[ \t]*$")
4755 org-deadline-regexp (concat "\\<" org-deadline-string)
4756 org-deadline-time-regexp
4757 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4758 org-deadline-line-regexp
4759 (concat "\\<\\(" org-deadline-string "\\).*")
4760 org-scheduled-regexp
4761 (concat "\\<" org-scheduled-string)
4762 org-scheduled-time-regexp
4763 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4764 org-closed-time-regexp
4765 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4766 org-keyword-time-regexp
4767 (concat "\\<\\(" org-scheduled-string
4768 "\\|" org-deadline-string
4769 "\\|" org-closed-string
4770 "\\|" org-clock-string "\\)"
4771 " *[[<]\\([^]>]+\\)[]>]")
4772 org-keyword-time-not-clock-regexp
4773 (concat "\\<\\(" org-scheduled-string
4774 "\\|" org-deadline-string
4775 "\\|" org-closed-string
4776 "\\)"
4777 " *[[<]\\([^]>]+\\)[]>]")
4778 org-maybe-keyword-time-regexp
4779 (concat "\\(\\<\\(" org-scheduled-string
4780 "\\|" org-deadline-string
4781 "\\|" org-closed-string
4782 "\\|" org-clock-string "\\)\\)?"
4783 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4784 org-planning-or-clock-line-re
4785 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
4786 "\\|" org-deadline-string
4787 "\\|" org-closed-string "\\|" org-clock-string
4788 "\\)\\>\\)")
4789 org-all-time-keywords
4790 (mapcar (lambda (w) (substring w 0 -1))
4791 (list org-scheduled-string org-deadline-string
4792 org-clock-string org-closed-string))
4794 (org-compute-latex-and-specials-regexp)
4795 (org-set-font-lock-defaults))))
4797 (defun org-file-contents (file &optional noerror)
4798 "Return the contents of FILE, as a string."
4799 (if (or (not file)
4800 (not (file-readable-p file)))
4801 (if noerror
4802 (progn
4803 (message "Cannot read file \"%s\"" file)
4804 (ding) (sit-for 2)
4806 (error "Cannot read file \"%s\"" file))
4807 (with-temp-buffer
4808 (insert-file-contents file)
4809 (buffer-string))))
4811 (defun org-extract-log-state-settings (x)
4812 "Extract the log state setting from a TODO keyword string.
4813 This will extract info from a string like \"WAIT(w@/!)\"."
4814 (let (kw key log1 log2)
4815 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4816 (setq kw (match-string 1 x)
4817 key (and (match-end 2) (match-string 2 x))
4818 log1 (and (match-end 3) (match-string 3 x))
4819 log2 (and (match-end 4) (match-string 4 x)))
4820 (and (or log1 log2)
4821 (list kw
4822 (and log1 (if (equal log1 "!") 'time 'note))
4823 (and log2 (if (equal log2 "!") 'time 'note)))))))
4825 (defun org-remove-keyword-keys (list)
4826 "Remove a pair of parenthesis at the end of each string in LIST."
4827 (mapcar (lambda (x)
4828 (if (string-match "(.*)$" x)
4829 (substring x 0 (match-beginning 0))
4831 list))
4833 (defun org-assign-fast-keys (alist)
4834 "Assign fast keys to a keyword-key alist.
4835 Respect keys that are already there."
4836 (let (new e (alt ?0))
4837 (while (setq e (pop alist))
4838 (if (or (memq (car e) '(:newline :endgroup :startgroup))
4839 (cdr e)) ;; Key already assigned.
4840 (push e new)
4841 (let ((clist (string-to-list (downcase (car e))))
4842 (used (append new alist)))
4843 (when (= (car clist) ?@)
4844 (pop clist))
4845 (while (and clist (rassoc (car clist) used))
4846 (pop clist))
4847 (unless clist
4848 (while (rassoc alt used)
4849 (incf alt)))
4850 (push (cons (car e) (or (car clist) alt)) new))))
4851 (nreverse new)))
4853 ;;; Some variables used in various places
4855 (defvar org-window-configuration nil
4856 "Used in various places to store a window configuration.")
4857 (defvar org-selected-window nil
4858 "Used in various places to store a window configuration.")
4859 (defvar org-finish-function nil
4860 "Function to be called when `C-c C-c' is used.
4861 This is for getting out of special buffers like remember.")
4864 ;; FIXME: Occasionally check by commenting these, to make sure
4865 ;; no other functions uses these, forgetting to let-bind them.
4866 (defvar entry)
4867 (defvar org-last-state)
4868 (defvar date)
4870 ;; Defined somewhere in this file, but used before definition.
4871 (defvar org-entities) ;; defined in org-entities.el
4872 (defvar org-struct-menu)
4873 (defvar org-org-menu)
4874 (defvar org-tbl-menu)
4876 ;;;; Define the Org-mode
4878 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4879 (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"))
4882 ;; We use a before-change function to check if a table might need
4883 ;; an update.
4884 (defvar org-table-may-need-update t
4885 "Indicates that a table might need an update.
4886 This variable is set by `org-before-change-function'.
4887 `org-table-align' sets it back to nil.")
4888 (defun org-before-change-function (beg end)
4889 "Every change indicates that a table might need an update."
4890 (setq org-table-may-need-update t))
4891 (defvar org-mode-map)
4892 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4893 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
4894 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4895 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
4896 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
4897 (defvar org-table-buffer-is-an nil)
4899 ;; `org-outline-regexp' ought to be a defconst but is let-binding in
4900 ;; some places -- e.g. see the macro org-with-limited-levels.
4902 ;; In Org buffers, the value of `outline-regexp' is that of
4903 ;; `org-outline-regexp'. The only function still directly relying on
4904 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
4905 ;; job when `orgstruct-mode' is active.
4906 (defvar org-outline-regexp "\\*+ "
4907 "Regexp to match Org headlines.")
4908 (defconst org-outline-regexp-bol "^\\*+ "
4909 "Regexp to match Org headlines.
4910 This is similar to `org-outline-regexp' but additionally makes
4911 sure that we are at the beginning of the line.")
4913 (defconst org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4914 "Matches an headline, putting stars and text into groups.
4915 Stars are put in group 1 and the trimmed body in group 2.")
4917 (defvar bidi-paragraph-direction)
4918 (defvar buffer-face-mode-face)
4920 ;;;###autoload
4921 (define-derived-mode org-mode outline-mode "Org"
4922 "Outline-based notes management and organizer, alias
4923 \"Carsten's outline-mode for keeping track of everything.\"
4925 Org-mode develops organizational tasks around a NOTES file which
4926 contains information about projects as plain text. Org-mode is
4927 implemented on top of outline-mode, which is ideal to keep the content
4928 of large files well structured. It supports ToDo items, deadlines and
4929 time stamps, which magically appear in the diary listing of the Emacs
4930 calendar. Tables are easily created with a built-in table editor.
4931 Plain text URL-like links connect to websites, emails (VM), Usenet
4932 messages (Gnus), BBDB entries, and any files related to the project.
4933 For printing and sharing of notes, an Org-mode file (or a part of it)
4934 can be exported as a structured ASCII or HTML file.
4936 The following commands are available:
4938 \\{org-mode-map}"
4940 ;; Get rid of Outline menus, they are not needed
4941 ;; Need to do this here because define-derived-mode sets up
4942 ;; the keymap so late. Still, it is a waste to call this each time
4943 ;; we switch another buffer into org-mode.
4944 (if (featurep 'xemacs)
4945 (when (boundp 'outline-mode-menu-heading)
4946 ;; Assume this is Greg's port, it uses easymenu
4947 (easy-menu-remove outline-mode-menu-heading)
4948 (easy-menu-remove outline-mode-menu-show)
4949 (easy-menu-remove outline-mode-menu-hide))
4950 (define-key org-mode-map [menu-bar headings] 'undefined)
4951 (define-key org-mode-map [menu-bar hide] 'undefined)
4952 (define-key org-mode-map [menu-bar show] 'undefined))
4954 (org-load-modules-maybe)
4955 (easy-menu-add org-org-menu)
4956 (easy-menu-add org-tbl-menu)
4957 (org-install-agenda-files-menu)
4958 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
4959 (add-to-invisibility-spec '(org-cwidth))
4960 (add-to-invisibility-spec '(org-hide-block . t))
4961 (when (featurep 'xemacs)
4962 (org-set-local 'line-move-ignore-invisible t))
4963 (org-set-local 'outline-regexp org-outline-regexp)
4964 (org-set-local 'outline-level 'org-outline-level)
4965 (setq bidi-paragraph-direction 'left-to-right)
4966 (when (and org-ellipsis
4967 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
4968 (fboundp 'make-glyph-code))
4969 (unless org-display-table
4970 (setq org-display-table (make-display-table)))
4971 (set-display-table-slot
4972 org-display-table 4
4973 (vconcat (mapcar
4974 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
4975 org-ellipsis)))
4976 (if (stringp org-ellipsis) org-ellipsis "..."))))
4977 (setq buffer-display-table org-display-table))
4978 (org-set-regexps-and-options)
4979 (when (and org-tag-faces (not org-tags-special-faces-re))
4980 ;; tag faces set outside customize.... force initialization.
4981 (org-set-tag-faces 'org-tag-faces org-tag-faces))
4982 ;; Calc embedded
4983 (org-set-local 'calc-embedded-open-mode "# ")
4984 (modify-syntax-entry ?@ "w")
4985 (if org-startup-truncated (setq truncate-lines t))
4986 (org-set-local 'font-lock-unfontify-region-function
4987 'org-unfontify-region)
4988 ;; Activate before-change-function
4989 (org-set-local 'org-table-may-need-update t)
4990 (org-add-hook 'before-change-functions 'org-before-change-function nil
4991 'local)
4992 ;; Check for running clock before killing a buffer
4993 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
4994 ;; Paragraphs and auto-filling
4995 (org-set-autofill-regexps)
4996 (setq indent-line-function 'org-indent-line-function)
4997 (org-update-radio-target-regexp)
4998 ;; Beginning/end of defun
4999 (org-set-local 'beginning-of-defun-function 'org-beginning-of-defun)
5000 (org-set-local 'end-of-defun-function 'org-end-of-defun)
5001 ;; Next error for sparse trees
5002 (org-set-local 'next-error-function 'org-occur-next-match)
5003 ;; Make sure dependence stuff works reliably, even for users who set it
5004 ;; too late :-(
5005 (if org-enforce-todo-dependencies
5006 (add-hook 'org-blocker-hook
5007 'org-block-todo-from-children-or-siblings-or-parent)
5008 (remove-hook 'org-blocker-hook
5009 'org-block-todo-from-children-or-siblings-or-parent))
5010 (if org-enforce-todo-checkbox-dependencies
5011 (add-hook 'org-blocker-hook
5012 'org-block-todo-from-checkboxes)
5013 (remove-hook 'org-blocker-hook
5014 'org-block-todo-from-checkboxes))
5016 ;; Comment characters
5017 (org-set-local 'comment-start "#")
5018 (org-set-local 'comment-padding " ")
5020 ;; Align options lines
5021 (org-set-local
5022 'align-mode-rules-list
5023 '((org-in-buffer-settings
5024 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5025 (modes . '(org-mode)))))
5027 ;; Imenu
5028 (org-set-local 'imenu-create-index-function
5029 'org-imenu-get-tree)
5031 ;; Make isearch reveal context
5032 (if (or (featurep 'xemacs)
5033 (not (boundp 'outline-isearch-open-invisible-function)))
5034 ;; Emacs 21 and XEmacs make use of the hook
5035 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5036 ;; Emacs 22 deals with this through a special variable
5037 (org-set-local 'outline-isearch-open-invisible-function
5038 (lambda (&rest ignore) (org-show-context 'isearch))))
5040 ;; Turn on org-beamer-mode?
5041 (and org-startup-with-beamer-mode (org-beamer-mode 1))
5043 ;; Setup the pcomplete hooks
5044 (set (make-local-variable 'pcomplete-command-completion-function)
5045 'org-pcomplete-initial)
5046 (set (make-local-variable 'pcomplete-command-name-function)
5047 'org-command-at-point)
5048 (set (make-local-variable 'pcomplete-default-completion-function)
5049 'ignore)
5050 (set (make-local-variable 'pcomplete-parse-arguments-function)
5051 'org-parse-arguments)
5052 (set (make-local-variable 'pcomplete-termination-string) "")
5053 (when (>= emacs-major-version 23)
5054 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5056 ;; If empty file that did not turn on org-mode automatically, make it to.
5057 (if (and org-insert-mode-line-in-empty-file
5058 (org-called-interactively-p 'any)
5059 (= (point-min) (point-max)))
5060 (insert "# -*- mode: org -*-\n\n"))
5061 (unless org-inhibit-startup
5062 (when org-startup-align-all-tables
5063 (let ((bmp (buffer-modified-p)))
5064 (org-table-map-tables 'org-table-align 'quietly)
5065 (set-buffer-modified-p bmp)))
5066 (when org-startup-with-inline-images
5067 (org-display-inline-images))
5068 (when org-startup-indented
5069 (require 'org-indent)
5070 (org-indent-mode 1))
5071 (unless org-inhibit-startup-visibility-stuff
5072 (org-set-startup-visibility))))
5074 (when (fboundp 'abbrev-table-put)
5075 (abbrev-table-put org-mode-abbrev-table
5076 :parents (list text-mode-abbrev-table)))
5078 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5080 (defun org-current-time ()
5081 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
5082 (if (> (car org-time-stamp-rounding-minutes) 1)
5083 (let ((r (car org-time-stamp-rounding-minutes))
5084 (time (decode-time)))
5085 (apply 'encode-time
5086 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5087 (nthcdr 2 time))))
5088 (current-time)))
5090 (defun org-today ()
5091 "Return today date, considering `org-extend-today-until'."
5092 (time-to-days
5093 (time-subtract (current-time)
5094 (list 0 (* 3600 org-extend-today-until) 0))))
5096 ;;;; Font-Lock stuff, including the activators
5098 (defvar org-mouse-map (make-sparse-keymap))
5099 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5100 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5101 (when org-mouse-1-follows-link
5102 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5103 (when org-tab-follows-link
5104 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5105 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5107 (require 'font-lock)
5109 (defconst org-non-link-chars "]\t\n\r<>")
5110 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5111 "shell" "elisp" "doi" "message"))
5112 (defvar org-link-types-re nil
5113 "Matches a link that has a url-like prefix like \"http:\"")
5114 (defvar org-link-re-with-space nil
5115 "Matches a link with spaces, optional angular brackets around it.")
5116 (defvar org-link-re-with-space2 nil
5117 "Matches a link with spaces, optional angular brackets around it.")
5118 (defvar org-link-re-with-space3 nil
5119 "Matches a link with spaces, only for internal part in bracket links.")
5120 (defvar org-angle-link-re nil
5121 "Matches link with angular brackets, spaces are allowed.")
5122 (defvar org-plain-link-re nil
5123 "Matches plain link, without spaces.")
5124 (defvar org-bracket-link-regexp nil
5125 "Matches a link in double brackets.")
5126 (defvar org-bracket-link-analytic-regexp nil
5127 "Regular expression used to analyze links.
5128 Here is what the match groups contain after a match:
5129 1: http:
5130 2: http
5131 3: path
5132 4: [desc]
5133 5: desc")
5134 (defvar org-bracket-link-analytic-regexp++ nil
5135 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5136 (defvar org-any-link-re nil
5137 "Regular expression matching any link.")
5139 (defcustom org-match-sexp-depth 3
5140 "Number of stacked braces for sub/superscript matching.
5141 This has to be set before loading org.el to be effective."
5142 :group 'org-export-translation ; ??????????????????????????/
5143 :type 'integer)
5145 (defun org-create-multibrace-regexp (left right n)
5146 "Create a regular expression which will match a balanced sexp.
5147 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5148 as single character strings.
5149 The regexp returned will match the entire expression including the
5150 delimiters. It will also define a single group which contains the
5151 match except for the outermost delimiters. The maximum depth of
5152 stacked delimiters is N. Escaping delimiters is not possible."
5153 (let* ((nothing (concat "[^" left right "]*?"))
5154 (or "\\|")
5155 (re nothing)
5156 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5157 (while (> n 1)
5158 (setq n (1- n)
5159 re (concat re or next)
5160 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5161 (concat left "\\(" re "\\)" right)))
5163 (defvar org-match-substring-regexp
5164 (concat
5165 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5166 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5167 "\\|"
5168 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5169 "\\|"
5170 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5171 "The regular expression matching a sub- or superscript.")
5173 (defvar org-match-substring-with-braces-regexp
5174 (concat
5175 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5176 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5177 "\\)")
5178 "The regular expression matching a sub- or superscript, forcing braces.")
5180 (defun org-make-link-regexps ()
5181 "Update the link regular expressions.
5182 This should be called after the variable `org-link-types' has changed."
5183 (setq org-link-types-re
5184 (concat
5185 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5186 org-link-re-with-space
5187 (concat
5188 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5189 "\\([^" org-non-link-chars " ]"
5190 "[^" org-non-link-chars "]*"
5191 "[^" org-non-link-chars " ]\\)>?")
5192 org-link-re-with-space2
5193 (concat
5194 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5195 "\\([^" org-non-link-chars " ]"
5196 "[^\t\n\r]*"
5197 "[^" org-non-link-chars " ]\\)>?")
5198 org-link-re-with-space3
5199 (concat
5200 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5201 "\\([^" org-non-link-chars " ]"
5202 "[^\t\n\r]*\\)")
5203 org-angle-link-re
5204 (concat
5205 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5206 "\\([^" org-non-link-chars " ]"
5207 "[^" org-non-link-chars "]*"
5208 "\\)>")
5209 org-plain-link-re
5210 (concat
5211 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5212 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5213 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5214 org-bracket-link-regexp
5215 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5216 org-bracket-link-analytic-regexp
5217 (concat
5218 "\\[\\["
5219 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5220 "\\([^]]+\\)"
5221 "\\]"
5222 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5223 "\\]")
5224 org-bracket-link-analytic-regexp++
5225 (concat
5226 "\\[\\["
5227 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5228 "\\([^]]+\\)"
5229 "\\]"
5230 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5231 "\\]")
5232 org-any-link-re
5233 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5234 org-angle-link-re "\\)\\|\\("
5235 org-plain-link-re "\\)")))
5237 (org-make-link-regexps)
5239 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5240 "Regular expression for fast time stamp matching.")
5241 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5242 "Regular expression for fast time stamp matching.")
5243 (defconst org-ts-regexp0
5244 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5245 "Regular expression matching time strings for analysis.
5246 This one does not require the space after the date, so it can be used
5247 on a string that terminates immediately after the date.")
5248 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5249 "Regular expression matching time strings for analysis.")
5250 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5251 "Regular expression matching time stamps, with groups.")
5252 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5253 "Regular expression matching time stamps (also [..]), with groups.")
5254 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5255 "Regular expression matching a time stamp range.")
5256 (defconst org-tr-regexp-both
5257 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5258 "Regular expression matching a time stamp range.")
5259 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5260 org-ts-regexp "\\)?")
5261 "Regular expression matching a time stamp or time stamp range.")
5262 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5263 org-ts-regexp-both "\\)?")
5264 "Regular expression matching a time stamp or time stamp range.
5265 The time stamps may be either active or inactive.")
5267 (defvar org-emph-face nil)
5269 (defun org-do-emphasis-faces (limit)
5270 "Run through the buffer and add overlays to emphasized strings."
5271 (let (rtn a)
5272 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5273 (if (not (= (char-after (match-beginning 3))
5274 (char-after (match-beginning 4))))
5275 (progn
5276 (setq rtn t)
5277 (setq a (assoc (match-string 3) org-emphasis-alist))
5278 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5279 'face
5280 (nth 1 a))
5281 (and (nth 4 a)
5282 (org-remove-flyspell-overlays-in
5283 (match-beginning 0) (match-end 0)))
5284 (add-text-properties (match-beginning 2) (match-end 2)
5285 '(font-lock-multiline t org-emphasis t))
5286 (when org-hide-emphasis-markers
5287 (add-text-properties (match-end 4) (match-beginning 5)
5288 '(invisible org-link))
5289 (add-text-properties (match-beginning 3) (match-end 3)
5290 '(invisible org-link)))))
5291 (backward-char 1))
5292 rtn))
5294 (defun org-emphasize (&optional char)
5295 "Insert or change an emphasis, i.e. a font like bold or italic.
5296 If there is an active region, change that region to a new emphasis.
5297 If there is no region, just insert the marker characters and position
5298 the cursor between them.
5299 CHAR should be either the marker character, or the first character of the
5300 HTML tag associated with that emphasis. If CHAR is a space, the means
5301 to remove the emphasis of the selected region.
5302 If char is not given (for example in an interactive call) it
5303 will be prompted for."
5304 (interactive)
5305 (let ((eal org-emphasis-alist) e det
5306 (erc org-emphasis-regexp-components)
5307 (prompt "")
5308 (string "") beg end move tag c s)
5309 (if (org-region-active-p)
5310 (setq beg (region-beginning) end (region-end)
5311 string (buffer-substring beg end))
5312 (setq move t))
5314 (while (setq e (pop eal))
5315 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5316 c (aref tag 0))
5317 (push (cons c (string-to-char (car e))) det)
5318 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5319 (substring tag 1)))))
5320 (setq det (nreverse det))
5321 (unless char
5322 (message "%s" (concat "Emphasis marker or tag:" prompt))
5323 (setq char (read-char-exclusive)))
5324 (setq char (or (cdr (assoc char det)) char))
5325 (if (equal char ?\ )
5326 (setq s "" move nil)
5327 (unless (assoc (char-to-string char) org-emphasis-alist)
5328 (error "No such emphasis marker: \"%c\"" char))
5329 (setq s (char-to-string char)))
5330 (while (and (> (length string) 1)
5331 (equal (substring string 0 1) (substring string -1))
5332 (assoc (substring string 0 1) org-emphasis-alist))
5333 (setq string (substring string 1 -1)))
5334 (setq string (concat s string s))
5335 (if beg (delete-region beg end))
5336 (unless (or (bolp)
5337 (string-match (concat "[" (nth 0 erc) "\n]")
5338 (char-to-string (char-before (point)))))
5339 (insert " "))
5340 (unless (or (eobp)
5341 (string-match (concat "[" (nth 1 erc) "\n]")
5342 (char-to-string (char-after (point)))))
5343 (insert " ") (backward-char 1))
5344 (insert string)
5345 (and move (backward-char 1))))
5347 (defconst org-nonsticky-props
5348 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
5350 (defsubst org-rear-nonsticky-at (pos)
5351 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5353 (defun org-activate-plain-links (limit)
5354 "Run through the buffer and add overlays to links."
5355 (catch 'exit
5356 (let (f)
5357 (if (re-search-forward org-plain-link-re limit t)
5358 (progn
5359 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5360 (setq f (get-text-property (match-beginning 0) 'face))
5361 (if (or (eq f 'org-tag)
5362 (and (listp f) (memq 'org-tag f)))
5364 (add-text-properties (match-beginning 0) (match-end 0)
5365 (list 'mouse-face 'highlight
5366 'face 'org-link
5367 'keymap org-mouse-map))
5368 (org-rear-nonsticky-at (match-end 0)))
5369 t)))))
5371 (defun org-activate-code (limit)
5372 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5373 (progn
5374 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5375 (remove-text-properties (match-beginning 0) (match-end 0)
5376 '(display t invisible t intangible t))
5377 t)))
5379 (defcustom org-src-fontify-natively nil
5380 "When non-nil, fontify code in code blocks."
5381 :type 'boolean
5382 :version "24.1"
5383 :group 'org-appearance
5384 :group 'org-babel)
5386 (defun org-fontify-meta-lines-and-blocks (limit)
5387 (condition-case nil
5388 (org-fontify-meta-lines-and-blocks-1 limit)
5389 (error (message "org-mode fontification error"))))
5391 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5392 "Fontify #+ lines and blocks, in the correct ways."
5393 (let ((case-fold-search t))
5394 (if (re-search-forward
5395 "^\\([ \t]*#\\+\\(\\([a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5396 limit t)
5397 (let ((beg (match-beginning 0))
5398 (block-start (match-end 0))
5399 (block-end nil)
5400 (lang (match-string 7))
5401 (beg1 (line-beginning-position 2))
5402 (dc1 (downcase (match-string 2)))
5403 (dc3 (downcase (match-string 3)))
5404 end end1 quoting block-type ovl)
5405 (cond
5406 ((member dc1 '("html:" "ascii:" "latex:" "docbook:"))
5407 ;; a single line of backend-specific content
5408 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5409 (remove-text-properties (match-beginning 0) (match-end 0)
5410 '(display t invisible t intangible t))
5411 (add-text-properties (match-beginning 1) (match-end 3)
5412 '(font-lock-fontified t face org-meta-line))
5413 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5414 '(font-lock-fontified t face org-block))
5415 ; for backend-specific code
5417 ((and (match-end 4) (equal dc3 "begin"))
5418 ;; Truly a block
5419 (setq block-type (downcase (match-string 5))
5420 quoting (member block-type org-protecting-blocks))
5421 (when (re-search-forward
5422 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5423 nil t) ;; on purpose, we look further than LIMIT
5424 (setq end (min (point-max) (match-end 0))
5425 end1 (min (point-max) (1- (match-beginning 0))))
5426 (setq block-end (match-beginning 0))
5427 (when quoting
5428 (remove-text-properties beg end
5429 '(display t invisible t intangible t)))
5430 (add-text-properties
5431 beg end
5432 '(font-lock-fontified t font-lock-multiline t))
5433 (add-text-properties beg beg1 '(face org-meta-line))
5434 (add-text-properties end1 (min (point-max) (1+ end))
5435 '(face org-meta-line)) ; for end_src
5436 (cond
5437 ((and lang (not (string= lang "")) org-src-fontify-natively)
5438 (org-src-font-lock-fontify-block lang block-start block-end)
5439 ;; remove old background overlays
5440 (mapc (lambda (ov)
5441 (if (eq (overlay-get ov 'face) 'org-block-background)
5442 (delete-overlay ov)))
5443 (overlays-at (/ (+ beg1 block-end) 2)))
5444 ;; add a background overlay
5445 (setq ovl (make-overlay beg1 block-end))
5446 (overlay-put ovl 'face 'org-block-background)
5447 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5448 (quoting
5449 (add-text-properties beg1 (min (point-max) (1+ end1))
5450 '(face org-block))) ; end of source block
5451 ((not org-fontify-quote-and-verse-blocks))
5452 ((string= block-type "quote")
5453 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5454 ((string= block-type "verse")
5455 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5456 (add-text-properties beg beg1 '(face org-block-begin-line))
5457 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5458 '(face org-block-end-line))
5460 ((member dc1 '("title:" "author:" "email:" "date:"))
5461 (add-text-properties
5462 beg (match-end 3)
5463 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5464 '(font-lock-fontified t invisible t)
5465 '(font-lock-fontified t face org-document-info-keyword)))
5466 (add-text-properties
5467 (match-beginning 6) (match-end 6)
5468 (if (string-equal dc1 "title:")
5469 '(font-lock-fontified t face org-document-title)
5470 '(font-lock-fontified t face org-document-info))))
5471 ((not (member (char-after beg) '(?\ ?\t)))
5472 ;; just any other in-buffer setting, but not indented
5473 (add-text-properties
5474 beg (match-end 0)
5475 '(font-lock-fontified t face org-meta-line))
5477 ((or (member dc1 '("begin:" "end:" "caption:" "label:"
5478 "orgtbl:" "tblfm:" "tblname:" "results:"
5479 "call:" "header:" "headers:" "name:"))
5480 (and (match-end 4) (equal dc3 "attr")))
5481 (add-text-properties
5482 beg (match-end 0)
5483 '(font-lock-fontified t face org-meta-line))
5485 ((member dc3 '(" " ""))
5486 (add-text-properties
5487 beg (match-end 0)
5488 '(font-lock-fontified t face font-lock-comment-face)))
5489 (t nil))))))
5491 (defun org-strip-protective-commas (beg end)
5492 "Strip protective commas between BEG and END in the current buffer."
5493 (interactive "r")
5494 (save-excursion
5495 (save-match-data
5496 (goto-char beg)
5497 (let ((front-line (save-excursion
5498 (re-search-forward
5499 "[^[:space:]]" end t)
5500 (goto-char (match-beginning 0))
5501 (current-column))))
5502 (while (re-search-forward "^[ \t]*\\(,\\)\\([*]\\|#\\+\\)" end t)
5503 (goto-char (match-beginning 1))
5504 (when (= (current-column) front-line)
5505 (replace-match "" nil nil nil 1)))))))
5507 (defun org-activate-angle-links (limit)
5508 "Run through the buffer and add overlays to links."
5509 (if (re-search-forward org-angle-link-re limit t)
5510 (progn
5511 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5512 (add-text-properties (match-beginning 0) (match-end 0)
5513 (list 'mouse-face 'highlight
5514 'keymap org-mouse-map))
5515 (org-rear-nonsticky-at (match-end 0))
5516 t)))
5518 (defun org-activate-footnote-links (limit)
5519 "Run through the buffer and add overlays to footnotes."
5520 (let ((fn (org-footnote-next-reference-or-definition limit)))
5521 (when fn
5522 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5523 (org-remove-flyspell-overlays-in beg end)
5524 (add-text-properties beg end
5525 (list 'mouse-face 'highlight
5526 'keymap org-mouse-map
5527 'help-echo
5528 (if (= (point-at-bol) beg)
5529 "Footnote definition"
5530 "Footnote reference")
5531 'font-lock-fontified t
5532 'font-lock-multiline t
5533 'face 'org-footnote))))))
5535 (defun org-activate-bracket-links (limit)
5536 "Run through the buffer and add overlays to bracketed links."
5537 (if (re-search-forward org-bracket-link-regexp limit t)
5538 (let* ((help (concat "LINK: "
5539 (org-match-string-no-properties 1)))
5540 ;; FIXME: above we should remove the escapes.
5541 ;; but that requires another match, protecting match data,
5542 ;; a lot of overhead for font-lock.
5543 (ip (org-maybe-intangible
5544 (list 'invisible 'org-link
5545 'keymap org-mouse-map 'mouse-face 'highlight
5546 'font-lock-multiline t 'help-echo help)))
5547 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5548 'font-lock-multiline t 'help-echo help)))
5549 ;; We need to remove the invisible property here. Table narrowing
5550 ;; may have made some of this invisible.
5551 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5552 (remove-text-properties (match-beginning 0) (match-end 0)
5553 '(invisible nil))
5554 (if (match-end 3)
5555 (progn
5556 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5557 (org-rear-nonsticky-at (match-beginning 3))
5558 (add-text-properties (match-beginning 3) (match-end 3) vp)
5559 (org-rear-nonsticky-at (match-end 3))
5560 (add-text-properties (match-end 3) (match-end 0) ip)
5561 (org-rear-nonsticky-at (match-end 0)))
5562 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5563 (org-rear-nonsticky-at (match-beginning 1))
5564 (add-text-properties (match-beginning 1) (match-end 1) vp)
5565 (org-rear-nonsticky-at (match-end 1))
5566 (add-text-properties (match-end 1) (match-end 0) ip)
5567 (org-rear-nonsticky-at (match-end 0)))
5568 t)))
5570 (defun org-activate-dates (limit)
5571 "Run through the buffer and add overlays to dates."
5572 (if (re-search-forward org-tsr-regexp-both limit t)
5573 (progn
5574 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5575 (add-text-properties (match-beginning 0) (match-end 0)
5576 (list 'mouse-face 'highlight
5577 'keymap org-mouse-map))
5578 (org-rear-nonsticky-at (match-end 0))
5579 (when org-display-custom-times
5580 (if (match-end 3)
5581 (org-display-custom-time (match-beginning 3) (match-end 3)))
5582 (org-display-custom-time (match-beginning 1) (match-end 1)))
5583 t)))
5585 (defvar org-target-link-regexp nil
5586 "Regular expression matching radio targets in plain text.")
5587 (make-variable-buffer-local 'org-target-link-regexp)
5588 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5589 "Regular expression matching a link target.")
5590 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5591 "Regular expression matching a radio target.")
5592 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5593 "Regular expression matching any target.")
5595 (defun org-activate-target-links (limit)
5596 "Run through the buffer and add overlays to target matches."
5597 (when org-target-link-regexp
5598 (let ((case-fold-search t))
5599 (if (re-search-forward org-target-link-regexp limit t)
5600 (progn
5601 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5602 (add-text-properties (match-beginning 0) (match-end 0)
5603 (list 'mouse-face 'highlight
5604 'keymap org-mouse-map
5605 'help-echo "Radio target link"
5606 'org-linked-text t))
5607 (org-rear-nonsticky-at (match-end 0))
5608 t)))))
5610 (defun org-update-radio-target-regexp ()
5611 "Find all radio targets in this file and update the regular expression."
5612 (interactive)
5613 (when (memq 'radio org-activate-links)
5614 (setq org-target-link-regexp
5615 (org-make-target-link-regexp (org-all-targets 'radio)))
5616 (org-restart-font-lock)))
5618 (defun org-hide-wide-columns (limit)
5619 (let (s e)
5620 (setq s (text-property-any (point) (or limit (point-max))
5621 'org-cwidth t))
5622 (when s
5623 (setq e (next-single-property-change s 'org-cwidth))
5624 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5625 (goto-char e)
5626 t)))
5628 (defvar org-latex-and-specials-regexp nil
5629 "Regular expression for highlighting export special stuff.")
5630 (defvar org-match-substring-regexp)
5631 (defvar org-match-substring-with-braces-regexp)
5633 ;; This should be with the exporter code, but we also use if for font-locking
5634 (defconst org-export-html-special-string-regexps
5635 '(("\\\\-" . "&shy;")
5636 ("---\\([^-]\\)" . "&mdash;\\1")
5637 ("--\\([^-]\\)" . "&ndash;\\1")
5638 ("\\.\\.\\." . "&hellip;"))
5639 "Regular expressions for special string conversion.")
5642 (defun org-compute-latex-and-specials-regexp ()
5643 "Compute regular expression for stuff treated specially by exporters."
5644 (if (not org-highlight-latex-fragments-and-specials)
5645 (org-set-local 'org-latex-and-specials-regexp nil)
5646 (require 'org-exp)
5647 (let*
5648 ((matchers (plist-get org-format-latex-options :matchers))
5649 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5650 org-latex-regexps)))
5651 (org-export-allow-BIND nil)
5652 (options (org-combine-plists (org-default-export-plist)
5653 (org-infile-export-plist)))
5654 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5655 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5656 (org-export-with-TeX-macros (plist-get options :TeX-macros))
5657 (org-export-html-expand (plist-get options :expand-quoted-html))
5658 (org-export-with-special-strings (plist-get options :special-strings))
5659 (re-sub
5660 (cond
5661 ((equal org-export-with-sub-superscripts '{})
5662 (list org-match-substring-with-braces-regexp))
5663 (org-export-with-sub-superscripts
5664 (list org-match-substring-regexp))
5665 (t nil)))
5666 (re-latex
5667 (if org-export-with-LaTeX-fragments
5668 (mapcar (lambda (x) (nth 1 x)) latexs)))
5669 (re-macros
5670 (if org-export-with-TeX-macros
5671 (list (concat "\\\\"
5672 (regexp-opt
5673 (append
5675 (delq nil
5676 (mapcar 'car-safe
5677 (append org-entities-user
5678 org-entities)))
5679 (if (boundp 'org-latex-entities)
5680 (mapcar (lambda (x)
5681 (or (car-safe x) x))
5682 org-latex-entities)
5683 nil))
5684 'words))) ; FIXME
5686 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5687 (re-special (if org-export-with-special-strings
5688 (mapcar (lambda (x) (car x))
5689 org-export-html-special-string-regexps)))
5690 (re-rest
5691 (delq nil
5692 (list
5693 (if org-export-html-expand "@<[^>\n]+>")
5694 ))))
5695 (org-set-local
5696 'org-latex-and-specials-regexp
5697 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5698 re-rest) "\\|")))))
5700 (defun org-do-latex-and-special-faces (limit)
5701 "Run through the buffer and add overlays to links."
5702 (when org-latex-and-specials-regexp
5703 (let (rtn d)
5704 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5705 limit t))
5706 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5707 'face))
5708 '(org-code org-verbatim underline)))
5709 (progn
5710 (setq rtn t
5711 d (cond ((member (char-after (1+ (match-beginning 0)))
5712 '(?_ ?^)) 1)
5713 (t 0)))
5714 (font-lock-prepend-text-property
5715 (+ d (match-beginning 0)) (match-end 0)
5716 'face 'org-latex-and-export-specials)
5717 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5718 '(font-lock-multiline t)))))
5719 rtn)))
5721 (defun org-restart-font-lock ()
5722 "Restart `font-lock-mode', to force refontification."
5723 (when (and (boundp 'font-lock-mode) font-lock-mode)
5724 (font-lock-mode -1)
5725 (font-lock-mode 1)))
5727 (defun org-all-targets (&optional radio)
5728 "Return a list of all targets in this file.
5729 With optional argument RADIO, only find radio targets."
5730 (let ((re (if radio org-radio-target-regexp org-target-regexp))
5731 rtn)
5732 (save-excursion
5733 (goto-char (point-min))
5734 (while (re-search-forward re nil t)
5735 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
5736 rtn)))
5738 (defun org-make-target-link-regexp (targets)
5739 "Make regular expression matching all strings in TARGETS.
5740 The regular expression finds the targets also if there is a line break
5741 between words."
5742 (and targets
5743 (concat
5744 "\\<\\("
5745 (mapconcat
5746 (lambda (x)
5747 (setq x (regexp-quote x))
5748 (while (string-match " +" x)
5749 (setq x (replace-match "\\s-+" t t x)))
5751 targets
5752 "\\|")
5753 "\\)\\>")))
5755 (defun org-activate-tags (limit)
5756 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
5757 (progn
5758 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5759 (add-text-properties (match-beginning 1) (match-end 1)
5760 (list 'mouse-face 'highlight
5761 'keymap org-mouse-map))
5762 (org-rear-nonsticky-at (match-end 1))
5763 t)))
5765 (defun org-outline-level ()
5766 "Compute the outline level of the heading at point.
5767 This function assumes that the cursor is at the beginning of a line matched
5768 by `outline-regexp'. Otherwise it returns garbage.
5769 If this is called at a normal headline, the level is the number of stars.
5770 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
5771 (save-excursion
5772 (looking-at org-outline-regexp)
5773 (1- (- (match-end 0) (match-beginning 0)))))
5775 (defvar org-font-lock-keywords nil)
5777 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\+?\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
5778 "Regular expression matching a property line.")
5780 (defvar org-font-lock-hook nil
5781 "Functions to be called for special font lock stuff.")
5783 (defvar org-font-lock-set-keywords-hook nil
5784 "Functions that can manipulate `org-font-lock-extra-keywords'.
5785 This is called after `org-font-lock-extra-keywords' is defined, but before
5786 it is installed to be used by font lock. This can be useful if something
5787 needs to be inserted at a specific position in the font-lock sequence.")
5789 (defun org-font-lock-hook (limit)
5790 (run-hook-with-args 'org-font-lock-hook limit))
5792 (defun org-set-font-lock-defaults ()
5793 (let* ((em org-fontify-emphasized-text)
5794 (lk org-activate-links)
5795 (org-font-lock-extra-keywords
5796 (list
5797 ;; Call the hook
5798 '(org-font-lock-hook)
5799 ;; Headlines
5800 `(,(if org-fontify-whole-heading-line
5801 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
5802 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
5803 (1 (org-get-level-face 1))
5804 (2 (org-get-level-face 2))
5805 (3 (org-get-level-face 3)))
5806 ;; Table lines
5807 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5808 (1 'org-table t))
5809 ;; Table internals
5810 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5811 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5812 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5813 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
5814 ;; Drawers
5815 (list org-drawer-regexp '(0 'org-special-keyword t))
5816 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5817 ;; Properties
5818 (list org-property-re
5819 '(1 'org-special-keyword t)
5820 '(3 'org-property-value t))
5821 ;; Links
5822 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5823 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5824 (if (memq 'plain lk) '(org-activate-plain-links))
5825 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5826 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5827 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5828 (if (memq 'footnote lk) '(org-activate-footnote-links))
5829 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5830 '(org-hide-wide-columns (0 nil append))
5831 ;; TODO keyword
5832 (list (format org-heading-keyword-regexp-format
5833 org-todo-regexp)
5834 '(2 (org-get-todo-face 2) t))
5835 ;; DONE
5836 (if org-fontify-done-headline
5837 (list (format org-heading-keyword-regexp-format
5838 (concat
5839 "\\(?:"
5840 (mapconcat 'regexp-quote org-done-keywords "\\|")
5841 "\\)"))
5842 '(2 'org-headline-done t))
5843 nil)
5844 ;; Priorities
5845 '(org-font-lock-add-priority-faces)
5846 ;; Tags
5847 '(org-font-lock-add-tag-faces)
5848 ;; Special keywords
5849 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5850 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5851 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5852 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5853 ;; Emphasis
5854 (if em
5855 (if (featurep 'xemacs)
5856 '(org-do-emphasis-faces (0 nil append))
5857 '(org-do-emphasis-faces)))
5858 ;; Checkboxes
5859 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
5860 1 'org-checkbox prepend)
5861 (if (cdr (assq 'checkbox org-list-automatic-rules))
5862 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5863 (0 (org-get-checkbox-statistics-face) t)))
5864 ;; Description list items
5865 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
5866 1 'bold prepend)
5867 ;; ARCHIVEd headings
5868 (list (concat
5869 org-outline-regexp-bol
5870 "\\(.*:" org-archive-tag ":.*\\)")
5871 '(1 'org-archived prepend))
5872 ;; Specials
5873 '(org-do-latex-and-special-faces)
5874 '(org-fontify-entities)
5875 '(org-raise-scripts)
5876 ;; Code
5877 '(org-activate-code (1 'org-code t))
5878 ;; COMMENT
5879 (list (format org-heading-keyword-regexp-format
5880 (concat "\\("
5881 org-comment-string "\\|" org-quote-string
5882 "\\)"))
5883 '(2 'org-special-keyword t))
5884 '("^#.*" (0 'font-lock-comment-face t))
5885 ;; Blocks and meta lines
5886 '(org-fontify-meta-lines-and-blocks)
5888 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5889 (run-hooks 'org-font-lock-set-keywords-hook)
5890 ;; Now set the full font-lock-keywords
5891 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5892 (org-set-local 'font-lock-defaults
5893 '(org-font-lock-keywords t nil nil backward-paragraph))
5894 (kill-local-variable 'font-lock-keywords) nil))
5896 (defun org-toggle-pretty-entities ()
5897 "Toggle the composition display of entities as UTF8 characters."
5898 (interactive)
5899 (org-set-local 'org-pretty-entities (not org-pretty-entities))
5900 (org-restart-font-lock)
5901 (if org-pretty-entities
5902 (message "Entities are displayed as UTF8 characters")
5903 (save-restriction
5904 (widen)
5905 (org-decompose-region (point-min) (point-max))
5906 (message "Entities are displayed plain"))))
5908 (defun org-fontify-entities (limit)
5909 "Find an entity to fontify."
5910 (let (ee)
5911 (when org-pretty-entities
5912 (catch 'match
5913 (while (re-search-forward
5914 "\\\\\\(frac[13][24]\\|[a-zA-Z]+\\)\\($\\|[^[:alpha:]\n]\\)"
5915 limit t)
5916 (if (and (not (org-in-indented-comment-line))
5917 (setq ee (org-entity-get (match-string 1)))
5918 (= (length (nth 6 ee)) 1))
5919 (progn
5920 (add-text-properties
5921 (match-beginning 0) (match-end 1)
5922 (list 'font-lock-fontified t))
5923 (compose-region (match-beginning 0) (match-end 1)
5924 (nth 6 ee) nil)
5925 (backward-char 1)
5926 (throw 'match t))))
5927 nil))))
5929 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
5930 "Fontify string S like in Org-mode."
5931 (with-temp-buffer
5932 (insert s)
5933 (let ((org-odd-levels-only odd-levels))
5934 (org-mode)
5935 (font-lock-fontify-buffer)
5936 (buffer-string))))
5938 (defvar org-m nil)
5939 (defvar org-l nil)
5940 (defvar org-f nil)
5941 (defun org-get-level-face (n)
5942 "Get the right face for match N in font-lock matching of headlines."
5943 (setq org-l (- (match-end 2) (match-beginning 1) 1))
5944 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
5945 (if org-cycle-level-faces
5946 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
5947 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
5948 (cond
5949 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
5950 ((eq n 2) org-f)
5951 (t (if org-level-color-stars-only nil org-f))))
5954 (defun org-get-todo-face (kwd)
5955 "Get the right face for a TODO keyword KWD.
5956 If KWD is a number, get the corresponding match group."
5957 (if (numberp kwd) (setq kwd (match-string kwd)))
5958 (or (org-face-from-face-or-color
5959 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
5960 (and (member kwd org-done-keywords) 'org-done)
5961 'org-todo))
5963 (defun org-face-from-face-or-color (context inherit face-or-color)
5964 "Create a face list that inherits INHERIT, but sets the foreground color.
5965 When FACE-OR-COLOR is not a string, just return it."
5966 (if (stringp face-or-color)
5967 (list :inherit inherit
5968 (cdr (assoc context org-faces-easy-properties))
5969 face-or-color)
5970 face-or-color))
5972 (defun org-font-lock-add-tag-faces (limit)
5973 "Add the special tag faces."
5974 (when (and org-tag-faces org-tags-special-faces-re)
5975 (while (re-search-forward org-tags-special-faces-re limit t)
5976 (add-text-properties (match-beginning 1) (match-end 1)
5977 (list 'face (org-get-tag-face 1)
5978 'font-lock-fontified t))
5979 (backward-char 1))))
5981 (defun org-font-lock-add-priority-faces (limit)
5982 "Add the special priority faces."
5983 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
5984 (add-text-properties
5985 (match-beginning 0) (match-end 0)
5986 (list 'face (or (org-face-from-face-or-color
5987 'priority 'org-special-keyword
5988 (cdr (assoc (char-after (match-beginning 1))
5989 org-priority-faces)))
5990 'org-special-keyword)
5991 'font-lock-fontified t))))
5993 (defun org-get-tag-face (kwd)
5994 "Get the right face for a TODO keyword KWD.
5995 If KWD is a number, get the corresponding match group."
5996 (if (numberp kwd) (setq kwd (match-string kwd)))
5997 (or (org-face-from-face-or-color
5998 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
5999 'org-tag))
6001 (defun org-unfontify-region (beg end &optional maybe_loudly)
6002 "Remove fontification and activation overlays from links."
6003 (font-lock-default-unfontify-region beg end)
6004 (let* ((buffer-undo-list t)
6005 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6006 (inhibit-modification-hooks t)
6007 deactivate-mark buffer-file-name buffer-file-truename)
6008 (org-decompose-region beg end)
6009 (remove-text-properties beg end
6010 '(mouse-face t keymap t org-linked-text t
6011 invisible t intangible t
6012 org-no-flyspell t org-emphasis t))
6013 (org-remove-font-lock-display-properties beg end)))
6015 (defconst org-script-display '(((raise -0.3) (height 0.7))
6016 ((raise 0.3) (height 0.7))
6017 ((raise -0.5))
6018 ((raise 0.5)))
6019 "Display properties for showing superscripts and subscripts.")
6021 (defun org-remove-font-lock-display-properties (beg end)
6022 "Remove specific display properties that have been added by font lock.
6023 The will remove the raise properties that are used to show superscripts
6024 and subscripts."
6025 (let (next prop)
6026 (while (< beg end)
6027 (setq next (next-single-property-change beg 'display nil end)
6028 prop (get-text-property beg 'display))
6029 (if (member prop org-script-display)
6030 (put-text-property beg next 'display nil))
6031 (setq beg next))))
6033 (defun org-raise-scripts (limit)
6034 "Add raise properties to sub/superscripts."
6035 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6036 (if (re-search-forward
6037 (if (eq org-use-sub-superscripts t)
6038 org-match-substring-regexp
6039 org-match-substring-with-braces-regexp)
6040 limit t)
6041 (let* ((pos (point)) table-p comment-p
6042 (mpos (match-beginning 3))
6043 (emph-p (get-text-property mpos 'org-emphasis))
6044 (link-p (get-text-property mpos 'mouse-face))
6045 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6046 (goto-char (point-at-bol))
6047 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6048 comment-p (org-looking-at-p "[ \t]*#"))
6049 (goto-char pos)
6050 ;; FIXME: Should we go back one character here, for a_b^c
6051 ;; (goto-char (1- pos)) ;????????????????????
6052 (if (or comment-p emph-p link-p keyw-p)
6054 (put-text-property (match-beginning 3) (match-end 0)
6055 'display
6056 (if (equal (char-after (match-beginning 2)) ?^)
6057 (nth (if table-p 3 1) org-script-display)
6058 (nth (if table-p 2 0) org-script-display)))
6059 (add-text-properties (match-beginning 2) (match-end 2)
6060 (list 'invisible t
6061 'org-dwidth t 'org-dwidth-n 1))
6062 (if (and (eq (char-after (match-beginning 3)) ?{)
6063 (eq (char-before (match-end 3)) ?}))
6064 (progn
6065 (add-text-properties
6066 (match-beginning 3) (1+ (match-beginning 3))
6067 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6068 (add-text-properties
6069 (1- (match-end 3)) (match-end 3)
6070 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6071 t)))))
6073 ;;;; Visibility cycling, including org-goto and indirect buffer
6075 ;;; Cycling
6077 (defvar org-cycle-global-status nil)
6078 (make-variable-buffer-local 'org-cycle-global-status)
6079 (defvar org-cycle-subtree-status nil)
6080 (make-variable-buffer-local 'org-cycle-subtree-status)
6082 ;;;###autoload
6084 (defvar org-inlinetask-min-level)
6086 (defun org-cycle (&optional arg)
6087 "TAB-action and visibility cycling for Org-mode.
6089 This is the command invoked in Org-mode by the TAB key. Its main purpose
6090 is outline visibility cycling, but it also invokes other actions
6091 in special contexts.
6093 - When this function is called with a prefix argument, rotate the entire
6094 buffer through 3 states (global cycling)
6095 1. OVERVIEW: Show only top-level headlines.
6096 2. CONTENTS: Show all headlines of all levels, but no body text.
6097 3. SHOW ALL: Show everything.
6098 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6099 determined by the variable `org-startup-folded', and by any VISIBILITY
6100 properties in the buffer.
6101 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6102 including any drawers.
6104 - When inside a table, re-align the table and move to the next field.
6106 - When point is at the beginning of a headline, rotate the subtree started
6107 by this line through 3 different states (local cycling)
6108 1. FOLDED: Only the main headline is shown.
6109 2. CHILDREN: The main headline and the direct children are shown.
6110 From this state, you can move to one of the children
6111 and zoom in further.
6112 3. SUBTREE: Show the entire subtree, including body text.
6113 If there is no subtree, switch directly from CHILDREN to FOLDED.
6115 - When point is at the beginning of an empty headline and the variable
6116 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6117 of the headline by demoting and promoting it to likely levels. This
6118 speeds up creation document structure by pressing TAB once or several
6119 times right after creating a new headline.
6121 - When there is a numeric prefix, go up to a heading with level ARG, do
6122 a `show-subtree' and return to the previous cursor position. If ARG
6123 is negative, go up that many levels.
6125 - When point is not at the beginning of a headline, execute the global
6126 binding for TAB, which is re-indenting the line. See the option
6127 `org-cycle-emulate-tab' for details.
6129 - Special case: if point is at the beginning of the buffer and there is
6130 no headline in line 1, this function will act as if called with prefix arg
6131 (C-u TAB, same as S-TAB) also when called without prefix arg.
6132 But only if also the variable `org-cycle-global-at-bob' is t."
6133 (interactive "P")
6134 (org-load-modules-maybe)
6135 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6136 (and org-cycle-level-after-item/entry-creation
6137 (or (org-cycle-level)
6138 (org-cycle-item-indentation))))
6139 (let* ((limit-level
6140 (or org-cycle-max-level
6141 (and (boundp 'org-inlinetask-min-level)
6142 org-inlinetask-min-level
6143 (1- org-inlinetask-min-level))))
6144 (nstars (and limit-level
6145 (if org-odd-levels-only
6146 (and limit-level (1- (* limit-level 2)))
6147 limit-level)))
6148 (org-outline-regexp
6149 (if (not (eq major-mode 'org-mode))
6150 outline-regexp
6151 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6152 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6153 (not (looking-at org-outline-regexp))))
6154 (org-cycle-hook
6155 (if bob-special
6156 (delq 'org-optimize-window-after-visibility-change
6157 (copy-sequence org-cycle-hook))
6158 org-cycle-hook))
6159 (pos (point)))
6161 (if (or bob-special (equal arg '(4)))
6162 ;; special case: use global cycling
6163 (setq arg t))
6165 (cond
6167 ((equal arg '(16))
6168 (setq last-command 'dummy)
6169 (org-set-startup-visibility)
6170 (message "Startup visibility, plus VISIBILITY properties"))
6172 ((equal arg '(64))
6173 (show-all)
6174 (message "Entire buffer visible, including drawers"))
6176 ;; Table: enter it or move to the next field.
6177 ((org-at-table-p 'any)
6178 (if (org-at-table.el-p)
6179 (message "Use C-c ' to edit table.el tables")
6180 (if arg (org-table-edit-field t)
6181 (org-table-justify-field-maybe)
6182 (call-interactively 'org-table-next-field))))
6184 ((run-hook-with-args-until-success
6185 'org-tab-after-check-for-table-hook))
6187 ;; Global cycling: delegate to `org-cycle-internal-global'.
6188 ((eq arg t) (org-cycle-internal-global))
6190 ;; Drawers: delegate to `org-flag-drawer'.
6191 ((and org-drawers org-drawer-regexp
6192 (save-excursion
6193 (beginning-of-line 1)
6194 (looking-at org-drawer-regexp)))
6195 (org-flag-drawer ; toggle block visibility
6196 (not (get-char-property (match-end 0) 'invisible))))
6198 ;; Show-subtree, ARG levels up from here.
6199 ((integerp arg)
6200 (save-excursion
6201 (org-back-to-heading)
6202 (outline-up-heading (if (< arg 0) (- arg)
6203 (- (funcall outline-level) arg)))
6204 (org-show-subtree)))
6206 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6207 ((and (featurep 'org-inlinetask)
6208 (org-inlinetask-at-task-p)
6209 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6210 (org-inlinetask-toggle-visibility))
6212 ((org-try-cdlatex-tab))
6214 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6215 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6216 (save-excursion (beginning-of-line 1)
6217 (looking-at org-outline-regexp)))
6218 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6219 (org-cycle-internal-local))
6221 ;; From there: TAB emulation and template completion.
6222 (buffer-read-only (org-back-to-heading))
6224 ((run-hook-with-args-until-success
6225 'org-tab-after-check-for-cycling-hook))
6227 ((org-try-structure-completion))
6229 ((run-hook-with-args-until-success
6230 'org-tab-before-tab-emulation-hook))
6232 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6233 (or (not (bolp))
6234 (not (looking-at org-outline-regexp))))
6235 (call-interactively (global-key-binding "\t")))
6237 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6238 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6239 (or (and (eq org-cycle-emulate-tab 'white)
6240 (= (match-end 0) (point-at-eol)))
6241 (and (eq org-cycle-emulate-tab 'whitestart)
6242 (>= (match-end 0) pos))))
6244 (eq org-cycle-emulate-tab t))
6245 (call-interactively (global-key-binding "\t")))
6247 (t (save-excursion
6248 (org-back-to-heading)
6249 (org-cycle)))))))
6251 (defun org-cycle-internal-global ()
6252 "Do the global cycling action."
6253 ;; Hack to avoid display of messages for .org attachments in Gnus
6254 (let ((ga (string-match "\\*fontification" (buffer-name))))
6255 (cond
6256 ((and (eq last-command this-command)
6257 (eq org-cycle-global-status 'overview))
6258 ;; We just created the overview - now do table of contents
6259 ;; This can be slow in very large buffers, so indicate action
6260 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6261 (unless ga (message "CONTENTS..."))
6262 (org-content)
6263 (unless ga (message "CONTENTS...done"))
6264 (setq org-cycle-global-status 'contents)
6265 (run-hook-with-args 'org-cycle-hook 'contents))
6267 ((and (eq last-command this-command)
6268 (eq org-cycle-global-status 'contents))
6269 ;; We just showed the table of contents - now show everything
6270 (run-hook-with-args 'org-pre-cycle-hook 'all)
6271 (show-all)
6272 (unless ga (message "SHOW ALL"))
6273 (setq org-cycle-global-status 'all)
6274 (run-hook-with-args 'org-cycle-hook 'all))
6277 ;; Default action: go to overview
6278 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6279 (org-overview)
6280 (unless ga (message "OVERVIEW"))
6281 (setq org-cycle-global-status 'overview)
6282 (run-hook-with-args 'org-cycle-hook 'overview)))))
6284 (defun org-cycle-internal-local ()
6285 "Do the local cycling action."
6286 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6287 ;; First, determine end of headline (EOH), end of subtree or item
6288 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6289 (save-excursion
6290 (if (org-at-item-p)
6291 (progn
6292 (beginning-of-line)
6293 (setq struct (org-list-struct))
6294 (setq eoh (point-at-eol))
6295 (setq eos (org-list-get-item-end-before-blank (point) struct))
6296 (setq has-children (org-list-has-child-p (point) struct)))
6297 (org-back-to-heading)
6298 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6299 (setq eos (save-excursion
6300 (org-end-of-subtree t)
6301 (unless (eobp)
6302 (skip-chars-forward " \t\n"))
6303 (if (eobp) (point) (1- (point)))))
6304 (setq has-children
6305 (or (save-excursion
6306 (let ((level (funcall outline-level)))
6307 (outline-next-heading)
6308 (and (org-at-heading-p t)
6309 (> (funcall outline-level) level))))
6310 (save-excursion
6311 (org-list-search-forward (org-item-beginning-re) eos t)))))
6312 ;; Determine end invisible part of buffer (EOL)
6313 (beginning-of-line 2)
6314 ;; XEmacs doesn't have `next-single-char-property-change'
6315 (if (featurep 'xemacs)
6316 (while (and (not (eobp)) ;; this is like `next-line'
6317 (get-char-property (1- (point)) 'invisible))
6318 (beginning-of-line 2))
6319 (while (and (not (eobp)) ;; this is like `next-line'
6320 (get-char-property (1- (point)) 'invisible))
6321 (goto-char (next-single-char-property-change (point) 'invisible))
6322 (and (eolp) (beginning-of-line 2))))
6323 (setq eol (point)))
6324 ;; Find out what to do next and set `this-command'
6325 (cond
6326 ((= eos eoh)
6327 ;; Nothing is hidden behind this heading
6328 (run-hook-with-args 'org-pre-cycle-hook 'empty)
6329 (message "EMPTY ENTRY")
6330 (setq org-cycle-subtree-status nil)
6331 (save-excursion
6332 (goto-char eos)
6333 (outline-next-heading)
6334 (if (outline-invisible-p) (org-flag-heading nil))))
6335 ((and (or (>= eol eos)
6336 (not (string-match "\\S-" (buffer-substring eol eos))))
6337 (or has-children
6338 (not (setq children-skipped
6339 org-cycle-skip-children-state-if-no-children))))
6340 ;; Entire subtree is hidden in one line: children view
6341 (run-hook-with-args 'org-pre-cycle-hook 'children)
6342 (if (org-at-item-p)
6343 (org-list-set-item-visibility (point-at-bol) struct 'children)
6344 (org-show-entry)
6345 (org-with-limited-levels (show-children))
6346 ;; FIXME: This slows down the func way too much.
6347 ;; How keep drawers hidden in subtree anyway?
6348 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6349 ;; (org-cycle-hide-drawers 'subtree))
6351 ;; Fold every list in subtree to top-level items.
6352 (when (eq org-cycle-include-plain-lists 'integrate)
6353 (save-excursion
6354 (org-back-to-heading)
6355 (while (org-list-search-forward (org-item-beginning-re) eos t)
6356 (beginning-of-line 1)
6357 (let* ((struct (org-list-struct))
6358 (prevs (org-list-prevs-alist struct))
6359 (end (org-list-get-bottom-point struct)))
6360 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6361 (org-list-get-all-items (point) struct prevs))
6362 (goto-char end))))))
6363 (message "CHILDREN")
6364 (save-excursion
6365 (goto-char eos)
6366 (outline-next-heading)
6367 (if (outline-invisible-p) (org-flag-heading nil)))
6368 (setq org-cycle-subtree-status 'children)
6369 (run-hook-with-args 'org-cycle-hook 'children))
6370 ((or children-skipped
6371 (and (eq last-command this-command)
6372 (eq org-cycle-subtree-status 'children)))
6373 ;; We just showed the children, or no children are there,
6374 ;; now show everything.
6375 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
6376 (outline-flag-region eoh eos nil)
6377 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6378 (setq org-cycle-subtree-status 'subtree)
6379 (run-hook-with-args 'org-cycle-hook 'subtree))
6381 ;; Default action: hide the subtree.
6382 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6383 (outline-flag-region eoh eos t)
6384 (message "FOLDED")
6385 (setq org-cycle-subtree-status 'folded)
6386 (run-hook-with-args 'org-cycle-hook 'folded)))))
6388 ;;;###autoload
6389 (defun org-global-cycle (&optional arg)
6390 "Cycle the global visibility. For details see `org-cycle'.
6391 With \\[universal-argument] prefix arg, switch to startup visibility.
6392 With a numeric prefix, show all headlines up to that level."
6393 (interactive "P")
6394 (let ((org-cycle-include-plain-lists
6395 (if (eq major-mode 'org-mode) org-cycle-include-plain-lists nil)))
6396 (cond
6397 ((integerp arg)
6398 (show-all)
6399 (hide-sublevels arg)
6400 (setq org-cycle-global-status 'contents))
6401 ((equal arg '(4))
6402 (org-set-startup-visibility)
6403 (message "Startup visibility, plus VISIBILITY properties."))
6405 (org-cycle '(4))))))
6407 (defun org-set-startup-visibility ()
6408 "Set the visibility required by startup options and properties."
6409 (cond
6410 ((eq org-startup-folded t)
6411 (org-cycle '(4)))
6412 ((eq org-startup-folded 'content)
6413 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6414 (org-cycle '(4)) (org-cycle '(4)))))
6415 (unless (eq org-startup-folded 'showeverything)
6416 (if org-hide-block-startup (org-hide-block-all))
6417 (org-set-visibility-according-to-property 'no-cleanup)
6418 (org-cycle-hide-archived-subtrees 'all)
6419 (org-cycle-hide-drawers 'all)
6420 (org-cycle-show-empty-lines t)))
6422 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6423 "Switch subtree visibilities according to :VISIBILITY: property."
6424 (interactive)
6425 (let (org-show-entry-below state)
6426 (save-excursion
6427 (goto-char (point-min))
6428 (while (re-search-forward
6429 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6430 nil t)
6431 (setq state (match-string 1))
6432 (save-excursion
6433 (org-back-to-heading t)
6434 (hide-subtree)
6435 (org-reveal)
6436 (cond
6437 ((equal state '("fold" "folded"))
6438 (hide-subtree))
6439 ((equal state "children")
6440 (org-show-hidden-entry)
6441 (show-children))
6442 ((equal state "content")
6443 (save-excursion
6444 (save-restriction
6445 (org-narrow-to-subtree)
6446 (org-content))))
6447 ((member state '("all" "showall"))
6448 (show-subtree)))))
6449 (unless no-cleanup
6450 (org-cycle-hide-archived-subtrees 'all)
6451 (org-cycle-hide-drawers 'all)
6452 (org-cycle-show-empty-lines 'all)))))
6454 ;; This function uses outline-regexp instead of the more fundamental
6455 ;; org-outline-regexp so that org-cycle-global works outside of Org
6456 ;; buffers, where outline-regexp is needed.
6457 (defun org-overview ()
6458 "Switch to overview mode, showing only top-level headlines.
6459 Really, this shows all headlines with level equal or greater than the level
6460 of the first headline in the buffer. This is important, because if the
6461 first headline is not level one, then (hide-sublevels 1) gives confusing
6462 results."
6463 (interactive)
6464 (let ((level (save-excursion
6465 (goto-char (point-min))
6466 (if (re-search-forward (concat "^" outline-regexp) nil t)
6467 (progn
6468 (goto-char (match-beginning 0))
6469 (funcall outline-level))))))
6470 (and level (hide-sublevels level))))
6472 (defun org-content (&optional arg)
6473 "Show all headlines in the buffer, like a table of contents.
6474 With numerical argument N, show content up to level N."
6475 (interactive "P")
6476 (save-excursion
6477 ;; Visit all headings and show their offspring
6478 (and (integerp arg) (org-overview))
6479 (goto-char (point-max))
6480 (catch 'exit
6481 (while (and (progn (condition-case nil
6482 (outline-previous-visible-heading 1)
6483 (error (goto-char (point-min))))
6485 (looking-at org-outline-regexp))
6486 (if (integerp arg)
6487 (show-children (1- arg))
6488 (show-branches))
6489 (if (bobp) (throw 'exit nil))))))
6492 (defun org-optimize-window-after-visibility-change (state)
6493 "Adjust the window after a change in outline visibility.
6494 This function is the default value of the hook `org-cycle-hook'."
6495 (when (get-buffer-window (current-buffer))
6496 (cond
6497 ((eq state 'content) nil)
6498 ((eq state 'all) nil)
6499 ((eq state 'folded) nil)
6500 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6501 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6503 (defun org-remove-empty-overlays-at (pos)
6504 "Remove outline overlays that do not contain non-white stuff."
6505 (mapc
6506 (lambda (o)
6507 (and (eq 'outline (overlay-get o 'invisible))
6508 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6509 (overlay-end o))))
6510 (delete-overlay o)))
6511 (overlays-at pos)))
6513 (defun org-clean-visibility-after-subtree-move ()
6514 "Fix visibility issues after moving a subtree."
6515 ;; First, find a reasonable region to look at:
6516 ;; Start two siblings above, end three below
6517 (let* ((beg (save-excursion
6518 (and (org-get-last-sibling)
6519 (org-get-last-sibling))
6520 (point)))
6521 (end (save-excursion
6522 (and (org-get-next-sibling)
6523 (org-get-next-sibling)
6524 (org-get-next-sibling))
6525 (if (org-at-heading-p)
6526 (point-at-eol)
6527 (point))))
6528 (level (looking-at "\\*+"))
6529 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6530 (save-excursion
6531 (save-restriction
6532 (narrow-to-region beg end)
6533 (when re
6534 ;; Properly fold already folded siblings
6535 (goto-char (point-min))
6536 (while (re-search-forward re nil t)
6537 (if (and (not (outline-invisible-p))
6538 (save-excursion
6539 (goto-char (point-at-eol)) (outline-invisible-p)))
6540 (hide-entry))))
6541 (org-cycle-show-empty-lines 'overview)
6542 (org-cycle-hide-drawers 'overview)))))
6544 (defun org-cycle-show-empty-lines (state)
6545 "Show empty lines above all visible headlines.
6546 The region to be covered depends on STATE when called through
6547 `org-cycle-hook'. Lisp program can use t for STATE to get the
6548 entire buffer covered. Note that an empty line is only shown if there
6549 are at least `org-cycle-separator-lines' empty lines before the headline."
6550 (when (not (= org-cycle-separator-lines 0))
6551 (save-excursion
6552 (let* ((n (abs org-cycle-separator-lines))
6553 (re (cond
6554 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6555 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6556 (t (let ((ns (number-to-string (- n 2))))
6557 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6558 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6559 beg end b e)
6560 (cond
6561 ((memq state '(overview contents t))
6562 (setq beg (point-min) end (point-max)))
6563 ((memq state '(children folded))
6564 (setq beg (point) end (progn (org-end-of-subtree t t)
6565 (beginning-of-line 2)
6566 (point)))))
6567 (when beg
6568 (goto-char beg)
6569 (while (re-search-forward re end t)
6570 (unless (get-char-property (match-end 1) 'invisible)
6571 (setq e (match-end 1))
6572 (if (< org-cycle-separator-lines 0)
6573 (setq b (save-excursion
6574 (goto-char (match-beginning 0))
6575 (org-back-over-empty-lines)
6576 (if (save-excursion
6577 (goto-char (max (point-min) (1- (point))))
6578 (org-at-heading-p))
6579 (1- (point))
6580 (point))))
6581 (setq b (match-beginning 1)))
6582 (outline-flag-region b e nil)))))))
6583 ;; Never hide empty lines at the end of the file.
6584 (save-excursion
6585 (goto-char (point-max))
6586 (outline-previous-heading)
6587 (outline-end-of-heading)
6588 (if (and (looking-at "[ \t\n]+")
6589 (= (match-end 0) (point-max)))
6590 (outline-flag-region (point) (match-end 0) nil))))
6592 (defun org-show-empty-lines-in-parent ()
6593 "Move to the parent and re-show empty lines before visible headlines."
6594 (save-excursion
6595 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6596 (org-cycle-show-empty-lines context))))
6598 (defun org-files-list ()
6599 "Return `org-agenda-files' list, plus all open org-mode files.
6600 This is useful for operations that need to scan all of a user's
6601 open and agenda-wise Org files."
6602 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6603 (dolist (buf (buffer-list))
6604 (with-current-buffer buf
6605 (if (and (eq major-mode 'org-mode) (buffer-file-name))
6606 (let ((file (expand-file-name (buffer-file-name))))
6607 (unless (member file files)
6608 (push file files))))))
6609 files))
6611 (defsubst org-entry-beginning-position ()
6612 "Return the beginning position of the current entry."
6613 (save-excursion (outline-back-to-heading t) (point)))
6615 (defsubst org-entry-end-position ()
6616 "Return the end position of the current entry."
6617 (save-excursion (outline-next-heading) (point)))
6619 (defun org-cycle-hide-drawers (state)
6620 "Re-hide all drawers after a visibility state change."
6621 (when (and (eq major-mode 'org-mode)
6622 (not (memq state '(overview folded contents))))
6623 (save-excursion
6624 (let* ((globalp (memq state '(contents all)))
6625 (beg (if globalp (point-min) (point)))
6626 (end (if globalp (point-max)
6627 (if (eq state 'children)
6628 (save-excursion (outline-next-heading) (point))
6629 (org-end-of-subtree t)))))
6630 (goto-char beg)
6631 (while (re-search-forward org-drawer-regexp end t)
6632 (org-flag-drawer t))))))
6634 (defun org-flag-drawer (flag)
6635 (save-excursion
6636 (beginning-of-line 1)
6637 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6638 (let ((b (match-end 0)))
6639 (if (re-search-forward
6640 "^[ \t]*:END:"
6641 (save-excursion (outline-next-heading) (point)) t)
6642 (outline-flag-region b (point-at-eol) flag)
6643 (error ":END: line missing at position %s" b))))))
6645 (defun org-subtree-end-visible-p ()
6646 "Is the end of the current subtree visible?"
6647 (pos-visible-in-window-p
6648 (save-excursion (org-end-of-subtree t) (point))))
6650 (defun org-first-headline-recenter (&optional N)
6651 "Move cursor to the first headline and recenter the headline.
6652 Optional argument N means put the headline into the Nth line of the window."
6653 (goto-char (point-min))
6654 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
6655 (beginning-of-line)
6656 (recenter (prefix-numeric-value N))))
6658 ;;; Saving and restoring visibility
6660 (defun org-outline-overlay-data (&optional use-markers)
6661 "Return a list of the locations of all outline overlays.
6662 These are overlays with the `invisible' property value `outline'.
6663 The return value is a list of cons cells, with start and stop
6664 positions for each overlay.
6665 If USE-MARKERS is set, return the positions as markers."
6666 (let (beg end)
6667 (save-excursion
6668 (save-restriction
6669 (widen)
6670 (delq nil
6671 (mapcar (lambda (o)
6672 (when (eq (overlay-get o 'invisible) 'outline)
6673 (setq beg (overlay-start o)
6674 end (overlay-end o))
6675 (and beg end (> end beg)
6676 (if use-markers
6677 (cons (move-marker (make-marker) beg)
6678 (move-marker (make-marker) end))
6679 (cons beg end)))))
6680 (overlays-in (point-min) (point-max))))))))
6682 (defun org-set-outline-overlay-data (data)
6683 "Create visibility overlays for all positions in DATA.
6684 DATA should have been made by `org-outline-overlay-data'."
6685 (let (o)
6686 (save-excursion
6687 (save-restriction
6688 (widen)
6689 (show-all)
6690 (mapc (lambda (c)
6691 (outline-flag-region (car c) (cdr c) t))
6692 data)))))
6694 ;;; Folding of blocks
6696 (defvar org-hide-block-overlays nil
6697 "Overlays hiding blocks.")
6698 (make-variable-buffer-local 'org-hide-block-overlays)
6700 (defun org-block-map (function &optional start end)
6701 "Call FUNCTION at the head of all source blocks in the current buffer.
6702 Optional arguments START and END can be used to limit the range."
6703 (let ((start (or start (point-min)))
6704 (end (or end (point-max))))
6705 (save-excursion
6706 (goto-char start)
6707 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
6708 (save-excursion
6709 (save-match-data
6710 (goto-char (match-beginning 0))
6711 (funcall function)))))))
6713 (defun org-hide-block-toggle-all ()
6714 "Toggle the visibility of all blocks in the current buffer."
6715 (org-block-map #'org-hide-block-toggle))
6717 (defun org-hide-block-all ()
6718 "Fold all blocks in the current buffer."
6719 (interactive)
6720 (org-show-block-all)
6721 (org-block-map #'org-hide-block-toggle-maybe))
6723 (defun org-show-block-all ()
6724 "Unfold all blocks in the current buffer."
6725 (interactive)
6726 (mapc 'delete-overlay org-hide-block-overlays)
6727 (setq org-hide-block-overlays nil))
6729 (defun org-hide-block-toggle-maybe ()
6730 "Toggle visibility of block at point."
6731 (interactive)
6732 (let ((case-fold-search t))
6733 (if (save-excursion
6734 (beginning-of-line 1)
6735 (looking-at org-block-regexp))
6736 (progn (org-hide-block-toggle)
6737 t) ;; to signal that we took action
6738 nil))) ;; to signal that we did not
6740 (defun org-hide-block-toggle (&optional force)
6741 "Toggle the visibility of the current block."
6742 (interactive)
6743 (save-excursion
6744 (beginning-of-line)
6745 (if (re-search-forward org-block-regexp nil t)
6746 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
6747 (end (match-end 0)) ;; end of entire body
6749 (if (memq t (mapcar (lambda (overlay)
6750 (eq (overlay-get overlay 'invisible)
6751 'org-hide-block))
6752 (overlays-at start)))
6753 (if (or (not force) (eq force 'off))
6754 (mapc (lambda (ov)
6755 (when (member ov org-hide-block-overlays)
6756 (setq org-hide-block-overlays
6757 (delq ov org-hide-block-overlays)))
6758 (when (eq (overlay-get ov 'invisible)
6759 'org-hide-block)
6760 (delete-overlay ov)))
6761 (overlays-at start)))
6762 (setq ov (make-overlay start end))
6763 (overlay-put ov 'invisible 'org-hide-block)
6764 ;; make the block accessible to isearch
6765 (overlay-put
6766 ov 'isearch-open-invisible
6767 (lambda (ov)
6768 (when (member ov org-hide-block-overlays)
6769 (setq org-hide-block-overlays
6770 (delq ov org-hide-block-overlays)))
6771 (when (eq (overlay-get ov 'invisible)
6772 'org-hide-block)
6773 (delete-overlay ov))))
6774 (push ov org-hide-block-overlays)))
6775 (error "Not looking at a source block"))))
6777 ;; org-tab-after-check-for-cycling-hook
6778 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
6779 ;; Remove overlays when changing major mode
6780 (add-hook 'org-mode-hook
6781 (lambda () (org-add-hook 'change-major-mode-hook
6782 'org-show-block-all 'append 'local)))
6784 ;;; Org-goto
6786 (defvar org-goto-window-configuration nil)
6787 (defvar org-goto-marker nil)
6788 (defvar org-goto-map
6789 (let ((map (make-sparse-keymap)))
6790 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
6791 (while (setq cmd (pop cmds))
6792 (substitute-key-definition cmd cmd map global-map)))
6793 (suppress-keymap map)
6794 (org-defkey map "\C-m" 'org-goto-ret)
6795 (org-defkey map [(return)] 'org-goto-ret)
6796 (org-defkey map [(left)] 'org-goto-left)
6797 (org-defkey map [(right)] 'org-goto-right)
6798 (org-defkey map [(control ?g)] 'org-goto-quit)
6799 (org-defkey map "\C-i" 'org-cycle)
6800 (org-defkey map [(tab)] 'org-cycle)
6801 (org-defkey map [(down)] 'outline-next-visible-heading)
6802 (org-defkey map [(up)] 'outline-previous-visible-heading)
6803 (if org-goto-auto-isearch
6804 (if (fboundp 'define-key-after)
6805 (define-key-after map [t] 'org-goto-local-auto-isearch)
6806 nil)
6807 (org-defkey map "q" 'org-goto-quit)
6808 (org-defkey map "n" 'outline-next-visible-heading)
6809 (org-defkey map "p" 'outline-previous-visible-heading)
6810 (org-defkey map "f" 'outline-forward-same-level)
6811 (org-defkey map "b" 'outline-backward-same-level)
6812 (org-defkey map "u" 'outline-up-heading))
6813 (org-defkey map "/" 'org-occur)
6814 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
6815 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
6816 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
6817 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
6818 (org-defkey map "\C-c\C-u" 'outline-up-heading)
6819 map))
6821 (defconst org-goto-help
6822 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
6823 RET=jump to location [Q]uit and return to previous location
6824 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
6826 (defvar org-goto-start-pos) ; dynamically scoped parameter
6828 ;; FIXME: Docstring does not mention both interfaces
6829 (defun org-goto (&optional alternative-interface)
6830 "Look up a different location in the current file, keeping current visibility.
6832 When you want look-up or go to a different location in a document, the
6833 fastest way is often to fold the entire buffer and then dive into the tree.
6834 This method has the disadvantage, that the previous location will be folded,
6835 which may not be what you want.
6837 This command works around this by showing a copy of the current buffer
6838 in an indirect buffer, in overview mode. You can dive into the tree in
6839 that copy, use org-occur and incremental search to find a location.
6840 When pressing RET or `Q', the command returns to the original buffer in
6841 which the visibility is still unchanged. After RET it will also jump to
6842 the location selected in the indirect buffer and expose the headline
6843 hierarchy above."
6844 (interactive "P")
6845 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
6846 (org-refile-use-outline-path t)
6847 (org-refile-target-verify-function nil)
6848 (interface
6849 (if (not alternative-interface)
6850 org-goto-interface
6851 (if (eq org-goto-interface 'outline)
6852 'outline-path-completion
6853 'outline)))
6854 (org-goto-start-pos (point))
6855 (selected-point
6856 (if (eq interface 'outline)
6857 (car (org-get-location (current-buffer) org-goto-help))
6858 (let ((pa (org-refile-get-location "Goto" nil nil t)))
6859 (org-refile-check-position pa)
6860 (nth 3 pa)))))
6861 (if selected-point
6862 (progn
6863 (org-mark-ring-push org-goto-start-pos)
6864 (goto-char selected-point)
6865 (if (or (outline-invisible-p) (org-invisible-p2))
6866 (org-show-context 'org-goto)))
6867 (message "Quit"))))
6869 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
6870 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
6871 (defvar org-goto-local-auto-isearch-map) ; defined below
6873 (defun org-get-location (buf help)
6874 "Let the user select a location in the Org-mode buffer BUF.
6875 This function uses a recursive edit. It returns the selected position
6876 or nil."
6877 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
6878 (isearch-hide-immediately nil)
6879 (isearch-search-fun-function
6880 (lambda () 'org-goto-local-search-headings))
6881 (org-goto-selected-point org-goto-exit-command)
6882 (pop-up-frames nil)
6883 (special-display-buffer-names nil)
6884 (special-display-regexps nil)
6885 (special-display-function nil))
6886 (save-excursion
6887 (save-window-excursion
6888 (delete-other-windows)
6889 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
6890 (org-pop-to-buffer-same-window
6891 (condition-case nil
6892 (make-indirect-buffer (current-buffer) "*org-goto*")
6893 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
6894 (with-output-to-temp-buffer "*Help*"
6895 (princ help))
6896 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
6897 (setq buffer-read-only nil)
6898 (let ((org-startup-truncated t)
6899 (org-startup-folded nil)
6900 (org-startup-align-all-tables nil))
6901 (org-mode)
6902 (org-overview))
6903 (setq buffer-read-only t)
6904 (if (and (boundp 'org-goto-start-pos)
6905 (integer-or-marker-p org-goto-start-pos))
6906 (let ((org-show-hierarchy-above t)
6907 (org-show-siblings t)
6908 (org-show-following-heading t))
6909 (goto-char org-goto-start-pos)
6910 (and (outline-invisible-p) (org-show-context)))
6911 (goto-char (point-min)))
6912 (let (org-special-ctrl-a/e) (org-beginning-of-line))
6913 (message "Select location and press RET")
6914 (use-local-map org-goto-map)
6915 (recursive-edit)
6917 (kill-buffer "*org-goto*")
6918 (cons org-goto-selected-point org-goto-exit-command)))
6920 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
6921 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
6922 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
6923 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
6925 (defun org-goto-local-search-headings (string bound noerror)
6926 "Search and make sure that any matches are in headlines."
6927 (catch 'return
6928 (while (if isearch-forward
6929 (search-forward string bound noerror)
6930 (search-backward string bound noerror))
6931 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
6932 (and (member :headline context)
6933 (not (member :tags context))))
6934 (throw 'return (point))))))
6936 (defun org-goto-local-auto-isearch ()
6937 "Start isearch."
6938 (interactive)
6939 (goto-char (point-min))
6940 (let ((keys (this-command-keys)))
6941 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
6942 (isearch-mode t)
6943 (isearch-process-search-char (string-to-char keys)))))
6945 (defun org-goto-ret (&optional arg)
6946 "Finish `org-goto' by going to the new location."
6947 (interactive "P")
6948 (setq org-goto-selected-point (point)
6949 org-goto-exit-command 'return)
6950 (throw 'exit nil))
6952 (defun org-goto-left ()
6953 "Finish `org-goto' by going to the new location."
6954 (interactive)
6955 (if (org-at-heading-p)
6956 (progn
6957 (beginning-of-line 1)
6958 (setq org-goto-selected-point (point)
6959 org-goto-exit-command 'left)
6960 (throw 'exit nil))
6961 (error "Not on a heading")))
6963 (defun org-goto-right ()
6964 "Finish `org-goto' by going to the new location."
6965 (interactive)
6966 (if (org-at-heading-p)
6967 (progn
6968 (setq org-goto-selected-point (point)
6969 org-goto-exit-command 'right)
6970 (throw 'exit nil))
6971 (error "Not on a heading")))
6973 (defun org-goto-quit ()
6974 "Finish `org-goto' without cursor motion."
6975 (interactive)
6976 (setq org-goto-selected-point nil)
6977 (setq org-goto-exit-command 'quit)
6978 (throw 'exit nil))
6980 ;;; Indirect buffer display of subtrees
6982 (defvar org-indirect-dedicated-frame nil
6983 "This is the frame being used for indirect tree display.")
6984 (defvar org-last-indirect-buffer nil)
6986 (defun org-tree-to-indirect-buffer (&optional arg)
6987 "Create indirect buffer and narrow it to current subtree.
6988 With numerical prefix ARG, go up to this level and then take that tree.
6989 If ARG is negative, go up that many levels.
6990 If `org-indirect-buffer-display' is not `new-frame', the command removes the
6991 indirect buffer previously made with this command, to avoid proliferation of
6992 indirect buffers. However, when you call the command with a \
6993 \\[universal-argument] prefix, or
6994 when `org-indirect-buffer-display' is `new-frame', the last buffer
6995 is kept so that you can work with several indirect buffers at the same time.
6996 If `org-indirect-buffer-display' is `dedicated-frame', the \
6997 \\[universal-argument] prefix also
6998 requests that a new frame be made for the new buffer, so that the dedicated
6999 frame is not changed."
7000 (interactive "P")
7001 (let ((cbuf (current-buffer))
7002 (cwin (selected-window))
7003 (pos (point))
7004 beg end level heading ibuf)
7005 (save-excursion
7006 (org-back-to-heading t)
7007 (when (numberp arg)
7008 (setq level (org-outline-level))
7009 (if (< arg 0) (setq arg (+ level arg)))
7010 (while (> (setq level (org-outline-level)) arg)
7011 (outline-up-heading 1 t)))
7012 (setq beg (point)
7013 heading (org-get-heading))
7014 (org-end-of-subtree t t)
7015 (if (org-at-heading-p) (backward-char 1))
7016 (setq end (point)))
7017 (if (and (buffer-live-p org-last-indirect-buffer)
7018 (not (eq org-indirect-buffer-display 'new-frame))
7019 (not arg))
7020 (kill-buffer org-last-indirect-buffer))
7021 (setq ibuf (org-get-indirect-buffer cbuf)
7022 org-last-indirect-buffer ibuf)
7023 (cond
7024 ((or (eq org-indirect-buffer-display 'new-frame)
7025 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7026 (select-frame (make-frame))
7027 (delete-other-windows)
7028 (org-pop-to-buffer-same-window ibuf)
7029 (org-set-frame-title heading))
7030 ((eq org-indirect-buffer-display 'dedicated-frame)
7031 (raise-frame
7032 (select-frame (or (and org-indirect-dedicated-frame
7033 (frame-live-p org-indirect-dedicated-frame)
7034 org-indirect-dedicated-frame)
7035 (setq org-indirect-dedicated-frame (make-frame)))))
7036 (delete-other-windows)
7037 (org-pop-to-buffer-same-window ibuf)
7038 (org-set-frame-title (concat "Indirect: " heading)))
7039 ((eq org-indirect-buffer-display 'current-window)
7040 (org-pop-to-buffer-same-window ibuf))
7041 ((eq org-indirect-buffer-display 'other-window)
7042 (pop-to-buffer ibuf))
7043 (t (error "Invalid value")))
7044 (if (featurep 'xemacs)
7045 (save-excursion (org-mode) (turn-on-font-lock)))
7046 (narrow-to-region beg end)
7047 (show-all)
7048 (goto-char pos)
7049 (run-hook-with-args 'org-cycle-hook 'all)
7050 (and (window-live-p cwin) (select-window cwin))))
7052 (defun org-get-indirect-buffer (&optional buffer)
7053 (setq buffer (or buffer (current-buffer)))
7054 (let ((n 1) (base (buffer-name buffer)) bname)
7055 (while (buffer-live-p
7056 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7057 (setq n (1+ n)))
7058 (condition-case nil
7059 (make-indirect-buffer buffer bname 'clone)
7060 (error (make-indirect-buffer buffer bname)))))
7062 (defun org-set-frame-title (title)
7063 "Set the title of the current frame to the string TITLE."
7064 ;; FIXME: how to name a single frame in XEmacs???
7065 (unless (featurep 'xemacs)
7066 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7068 ;;;; Structure editing
7070 ;;; Inserting headlines
7072 (defun org-previous-line-empty-p ()
7073 (save-excursion
7074 (and (not (bobp))
7075 (or (beginning-of-line 0) t)
7076 (save-match-data
7077 (looking-at "[ \t]*$")))))
7079 (defun org-insert-heading (&optional force-heading invisible-ok)
7080 "Insert a new heading or item with same depth at point.
7081 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
7082 If point is at the beginning of a headline, insert a sibling before the
7083 current headline. If point is not at the beginning, split the line,
7084 create the new headline with the text in the current line after point
7085 \(but see also the variable `org-M-RET-may-split-line').
7087 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7088 This is important for non-interactive uses of the command."
7089 (interactive "P")
7090 (if (or (= (buffer-size) 0)
7091 (and (not (save-excursion
7092 (and (ignore-errors (org-back-to-heading invisible-ok))
7093 (org-at-heading-p))))
7094 (or force-heading (not (org-in-item-p)))))
7095 (progn
7096 (insert "\n* ")
7097 (run-hooks 'org-insert-heading-hook))
7098 (when (or force-heading (not (org-insert-item)))
7099 (let* ((empty-line-p nil)
7100 (level nil)
7101 (on-heading (org-at-heading-p))
7102 (head (save-excursion
7103 (condition-case nil
7104 (progn
7105 (org-back-to-heading invisible-ok)
7106 (when (and (not on-heading)
7107 (featurep 'org-inlinetask)
7108 (integerp org-inlinetask-min-level)
7109 (>= (length (match-string 0))
7110 org-inlinetask-min-level))
7111 ;; Find a heading level before the inline task
7112 (while (and (setq level (org-up-heading-safe))
7113 (>= level org-inlinetask-min-level)))
7114 (if (org-at-heading-p)
7115 (org-back-to-heading invisible-ok)
7116 (error "This should not happen")))
7117 (setq empty-line-p (org-previous-line-empty-p))
7118 (match-string 0))
7119 (error "*"))))
7120 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7121 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7122 pos hide-previous previous-pos)
7123 (cond
7124 ((and (org-at-heading-p) (bolp)
7125 (or (bobp)
7126 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
7127 ;; insert before the current line
7128 (open-line (if blank 2 1)))
7129 ((and (bolp)
7130 (not org-insert-heading-respect-content)
7131 (or (bobp)
7132 (save-excursion
7133 (backward-char 1) (not (outline-invisible-p)))))
7134 ;; insert right here
7135 nil)
7137 ;; somewhere in the line
7138 (save-excursion
7139 (setq previous-pos (point-at-bol))
7140 (end-of-line)
7141 (setq hide-previous (outline-invisible-p)))
7142 (and org-insert-heading-respect-content (org-show-subtree))
7143 (let ((split
7144 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
7145 (save-excursion
7146 (let ((p (point)))
7147 (goto-char (point-at-bol))
7148 (and (looking-at org-complex-heading-regexp)
7149 (match-beginning 4)
7150 (> p (match-beginning 4)))))))
7151 tags pos)
7152 (cond
7153 (org-insert-heading-respect-content
7154 (org-end-of-subtree nil t)
7155 (when (featurep 'org-inlinetask)
7156 (while (and (not (eobp))
7157 (looking-at "\\(\\*+\\)[ \t]+")
7158 (>= (length (match-string 1))
7159 org-inlinetask-min-level))
7160 (org-end-of-subtree nil t)))
7161 (or (bolp) (newline))
7162 (or (org-previous-line-empty-p)
7163 (and blank (newline)))
7164 (open-line 1))
7165 ((org-at-heading-p)
7166 (when hide-previous
7167 (show-children)
7168 (org-show-entry))
7169 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7170 (setq tags (and (match-end 2) (match-string 2)))
7171 (and (match-end 1)
7172 (delete-region (match-beginning 1) (match-end 1)))
7173 (setq pos (point-at-bol))
7174 (or split (end-of-line 1))
7175 (delete-horizontal-space)
7176 (if (string-match "\\`\\*+\\'"
7177 (buffer-substring (point-at-bol) (point)))
7178 (insert " "))
7179 (newline (if blank 2 1))
7180 (when tags
7181 (save-excursion
7182 (goto-char pos)
7183 (end-of-line 1)
7184 (insert " " tags)
7185 (org-set-tags nil 'align))))
7187 (or split (end-of-line 1))
7188 (newline (if blank 2 1)))))))
7189 (insert head) (just-one-space)
7190 (setq pos (point))
7191 (end-of-line 1)
7192 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7193 (when (and org-insert-heading-respect-content hide-previous)
7194 (save-excursion
7195 (goto-char previous-pos)
7196 (hide-subtree)))
7197 (run-hooks 'org-insert-heading-hook)))))
7199 (defun org-get-heading (&optional no-tags no-todo)
7200 "Return the heading of the current entry, without the stars.
7201 When NO-TAGS is non-nil, don't include tags.
7202 When NO-TODO is non-nil, don't include TODO keywords."
7203 (save-excursion
7204 (org-back-to-heading t)
7205 (cond
7206 ((and no-tags no-todo)
7207 (looking-at org-complex-heading-regexp)
7208 (match-string 4))
7209 (no-tags
7210 (looking-at (concat org-outline-regexp
7211 "\\(.*?\\)"
7212 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7213 (match-string 1))
7214 (no-todo
7215 (looking-at org-todo-line-regexp)
7216 (match-string 3))
7217 (t (looking-at org-heading-regexp)
7218 (match-string 2)))))
7220 (defun org-heading-components ()
7221 "Return the components of the current heading.
7222 This is a list with the following elements:
7223 - the level as an integer
7224 - the reduced level, different if `org-odd-levels-only' is set.
7225 - the TODO keyword, or nil
7226 - the priority character, like ?A, or nil if no priority is given
7227 - the headline text itself, or the tags string if no headline text
7228 - the tags string, or nil."
7229 (save-excursion
7230 (org-back-to-heading t)
7231 (if (let (case-fold-search) (looking-at org-complex-heading-regexp))
7232 (list (length (match-string 1))
7233 (org-reduced-level (length (match-string 1)))
7234 (org-match-string-no-properties 2)
7235 (and (match-end 3) (aref (match-string 3) 2))
7236 (org-match-string-no-properties 4)
7237 (org-match-string-no-properties 5)))))
7239 (defun org-get-entry ()
7240 "Get the entry text, after heading, entire subtree."
7241 (save-excursion
7242 (org-back-to-heading t)
7243 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7245 (defun org-insert-heading-after-current ()
7246 "Insert a new heading with same level as current, after current subtree."
7247 (interactive)
7248 (org-back-to-heading)
7249 (org-insert-heading)
7250 (org-move-subtree-down)
7251 (end-of-line 1))
7253 (defun org-insert-heading-respect-content ()
7254 (interactive)
7255 (let ((org-insert-heading-respect-content t))
7256 (org-insert-heading t)))
7258 (defun org-insert-todo-heading-respect-content (&optional force-state)
7259 (interactive "P")
7260 (let ((org-insert-heading-respect-content t))
7261 (org-insert-todo-heading force-state t)))
7263 (defun org-insert-todo-heading (arg &optional force-heading)
7264 "Insert a new heading with the same level and TODO state as current heading.
7265 If the heading has no TODO state, or if the state is DONE, use the first
7266 state (TODO by default). Also with prefix arg, force first state."
7267 (interactive "P")
7268 (when (or force-heading (not (org-insert-item 'checkbox)))
7269 (org-insert-heading force-heading)
7270 (save-excursion
7271 (org-back-to-heading)
7272 (outline-previous-heading)
7273 (looking-at org-todo-line-regexp))
7274 (let*
7275 ((new-mark-x
7276 (if (or arg
7277 (not (match-beginning 2))
7278 (member (match-string 2) org-done-keywords))
7279 (car org-todo-keywords-1)
7280 (match-string 2)))
7281 (new-mark
7283 (run-hook-with-args-until-success
7284 'org-todo-get-default-hook new-mark-x nil)
7285 new-mark-x)))
7286 (beginning-of-line 1)
7287 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7288 (if org-treat-insert-todo-heading-as-state-change
7289 (org-todo new-mark)
7290 (insert new-mark " "))))
7291 (when org-provide-todo-statistics
7292 (org-update-parent-todo-statistics))))
7294 (defun org-insert-subheading (arg)
7295 "Insert a new subheading and demote it.
7296 Works for outline headings and for plain lists alike."
7297 (interactive "P")
7298 (org-insert-heading arg)
7299 (cond
7300 ((org-at-heading-p) (org-do-demote))
7301 ((org-at-item-p) (org-indent-item))))
7303 (defun org-insert-todo-subheading (arg)
7304 "Insert a new subheading with TODO keyword or checkbox and demote it.
7305 Works for outline headings and for plain lists alike."
7306 (interactive "P")
7307 (org-insert-todo-heading arg)
7308 (cond
7309 ((org-at-heading-p) (org-do-demote))
7310 ((org-at-item-p) (org-indent-item))))
7312 ;;; Promotion and Demotion
7314 (defvar org-after-demote-entry-hook nil
7315 "Hook run after an entry has been demoted.
7316 The cursor will be at the beginning of the entry.
7317 When a subtree is being demoted, the hook will be called for each node.")
7319 (defvar org-after-promote-entry-hook nil
7320 "Hook run after an entry has been promoted.
7321 The cursor will be at the beginning of the entry.
7322 When a subtree is being promoted, the hook will be called for each node.")
7324 (defun org-promote-subtree ()
7325 "Promote the entire subtree.
7326 See also `org-promote'."
7327 (interactive)
7328 (save-excursion
7329 (org-with-limited-levels (org-map-tree 'org-promote)))
7330 (org-fix-position-after-promote))
7332 (defun org-demote-subtree ()
7333 "Demote the entire subtree. See `org-demote'.
7334 See also `org-promote'."
7335 (interactive)
7336 (save-excursion
7337 (org-with-limited-levels (org-map-tree 'org-demote)))
7338 (org-fix-position-after-promote))
7341 (defun org-do-promote ()
7342 "Promote the current heading higher up the tree.
7343 If the region is active in `transient-mark-mode', promote all headings
7344 in the region."
7345 (interactive)
7346 (save-excursion
7347 (if (org-region-active-p)
7348 (org-map-region 'org-promote (region-beginning) (region-end))
7349 (org-promote)))
7350 (org-fix-position-after-promote))
7352 (defun org-do-demote ()
7353 "Demote the current heading lower down the tree.
7354 If the region is active in `transient-mark-mode', demote all headings
7355 in the region."
7356 (interactive)
7357 (save-excursion
7358 (if (org-region-active-p)
7359 (org-map-region 'org-demote (region-beginning) (region-end))
7360 (org-demote)))
7361 (org-fix-position-after-promote))
7363 (defun org-fix-position-after-promote ()
7364 "Make sure that after pro/demotion cursor position is right."
7365 (let ((pos (point)))
7366 (when (save-excursion
7367 (beginning-of-line 1)
7368 (looking-at org-todo-line-regexp)
7369 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7370 (cond ((eobp) (insert " "))
7371 ((eolp) (insert " "))
7372 ((equal (char-after) ?\ ) (forward-char 1))))))
7374 (defun org-current-level ()
7375 "Return the level of the current entry, or nil if before the first headline.
7376 The level is the number of stars at the beginning of the headline."
7377 (save-excursion
7378 (org-with-limited-levels
7379 (if (ignore-errors (org-back-to-heading t))
7380 (funcall outline-level)))))
7382 (defun org-get-previous-line-level ()
7383 "Return the outline depth of the last headline before the current line.
7384 Returns 0 for the first headline in the buffer, and nil if before the
7385 first headline."
7386 (let ((current-level (org-current-level))
7387 (prev-level (when (> (line-number-at-pos) 1)
7388 (save-excursion
7389 (beginning-of-line 0)
7390 (org-current-level)))))
7391 (cond ((null current-level) nil) ; Before first headline
7392 ((null prev-level) 0) ; At first headline
7393 (prev-level))))
7395 (defun org-reduced-level (l)
7396 "Compute the effective level of a heading.
7397 This takes into account the setting of `org-odd-levels-only'."
7398 (cond
7399 ((zerop l) 0)
7400 (org-odd-levels-only (1+ (floor (/ l 2))))
7401 (t l)))
7403 (defun org-level-increment ()
7404 "Return the number of stars that will be added or removed at a
7405 time to headlines when structure editing, based on the value of
7406 `org-odd-levels-only'."
7407 (if org-odd-levels-only 2 1))
7409 (defun org-get-valid-level (level &optional change)
7410 "Rectify a level change under the influence of `org-odd-levels-only'
7411 LEVEL is a current level, CHANGE is by how much the level should be
7412 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7413 even level numbers will become the next higher odd number."
7414 (if org-odd-levels-only
7415 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7416 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7417 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7418 (max 1 (+ level (or change 0)))))
7420 (if (boundp 'define-obsolete-function-alias)
7421 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7422 (define-obsolete-function-alias 'org-get-legal-level
7423 'org-get-valid-level)
7424 (define-obsolete-function-alias 'org-get-legal-level
7425 'org-get-valid-level "23.1")))
7427 (defun org-promote ()
7428 "Promote the current heading higher up the tree.
7429 If the region is active in `transient-mark-mode', promote all headings
7430 in the region."
7431 (org-back-to-heading t)
7432 (let* ((level (save-match-data (funcall outline-level)))
7433 (after-change-functions (remove 'flyspell-after-change-function
7434 after-change-functions))
7435 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7436 (diff (abs (- level (length up-head) -1))))
7437 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
7438 (replace-match up-head nil t)
7439 ;; Fixup tag positioning
7440 (and org-auto-align-tags (org-set-tags nil t))
7441 (if org-adapt-indentation (org-fixup-indentation (- diff)))
7442 (run-hooks 'org-after-promote-entry-hook)))
7444 (defun org-demote ()
7445 "Demote the current heading lower down the tree.
7446 If the region is active in `transient-mark-mode', demote all headings
7447 in the region."
7448 (org-back-to-heading t)
7449 (let* ((level (save-match-data (funcall outline-level)))
7450 (after-change-functions (remove 'flyspell-after-change-function
7451 after-change-functions))
7452 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7453 (diff (abs (- level (length down-head) -1))))
7454 (replace-match down-head nil t)
7455 ;; Fixup tag positioning
7456 (and org-auto-align-tags (org-set-tags nil t))
7457 (if org-adapt-indentation (org-fixup-indentation diff))
7458 (run-hooks 'org-after-demote-entry-hook)))
7460 (defun org-cycle-level ()
7461 "Cycle the level of an empty headline through possible states.
7462 This goes first to child, then to parent, level, then up the hierarchy.
7463 After top level, it switches back to sibling level."
7464 (interactive)
7465 (let ((org-adapt-indentation nil))
7466 (when (org-point-at-end-of-empty-headline)
7467 (setq this-command 'org-cycle-level) ; Only needed for caching
7468 (let ((cur-level (org-current-level))
7469 (prev-level (org-get-previous-line-level)))
7470 (cond
7471 ;; If first headline in file, promote to top-level.
7472 ((= prev-level 0)
7473 (loop repeat (/ (- cur-level 1) (org-level-increment))
7474 do (org-do-promote)))
7475 ;; If same level as prev, demote one.
7476 ((= prev-level cur-level)
7477 (org-do-demote))
7478 ;; If parent is top-level, promote to top level if not already.
7479 ((= prev-level 1)
7480 (loop repeat (/ (- cur-level 1) (org-level-increment))
7481 do (org-do-promote)))
7482 ;; If top-level, return to prev-level.
7483 ((= cur-level 1)
7484 (loop repeat (/ (- prev-level 1) (org-level-increment))
7485 do (org-do-demote)))
7486 ;; If less than prev-level, promote one.
7487 ((< cur-level prev-level)
7488 (org-do-promote))
7489 ;; If deeper than prev-level, promote until higher than
7490 ;; prev-level.
7491 ((> cur-level prev-level)
7492 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7493 do (org-do-promote))))
7494 t))))
7496 (defun org-map-tree (fun)
7497 "Call FUN for every heading underneath the current one."
7498 (org-back-to-heading)
7499 (let ((level (funcall outline-level)))
7500 (save-excursion
7501 (funcall fun)
7502 (while (and (progn
7503 (outline-next-heading)
7504 (> (funcall outline-level) level))
7505 (not (eobp)))
7506 (funcall fun)))))
7508 (defun org-map-region (fun beg end)
7509 "Call FUN for every heading between BEG and END."
7510 (let ((org-ignore-region t))
7511 (save-excursion
7512 (setq end (copy-marker end))
7513 (goto-char beg)
7514 (if (and (re-search-forward org-outline-regexp-bol nil t)
7515 (< (point) end))
7516 (funcall fun))
7517 (while (and (progn
7518 (outline-next-heading)
7519 (< (point) end))
7520 (not (eobp)))
7521 (funcall fun)))))
7523 (defvar org-property-end-re) ; silence byte-compiler
7524 (defun org-fixup-indentation (diff)
7525 "Change the indentation in the current entry by DIFF.
7526 However, if any line in the current entry has no indentation, or if it
7527 would end up with no indentation after the change, nothing at all is done."
7528 (save-excursion
7529 (let ((end (save-excursion (outline-next-heading)
7530 (point-marker)))
7531 (prohibit (if (> diff 0)
7532 "^\\S-"
7533 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7534 col)
7535 (unless (save-excursion (end-of-line 1)
7536 (re-search-forward prohibit end t))
7537 (while (and (< (point) end)
7538 (re-search-forward "^[ \t]+" end t))
7539 (goto-char (match-end 0))
7540 (setq col (current-column))
7541 (if (< diff 0) (replace-match ""))
7542 (org-indent-to-column (+ diff col))))
7543 (move-marker end nil))))
7545 (defun org-convert-to-odd-levels ()
7546 "Convert an org-mode file with all levels allowed to one with odd levels.
7547 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7548 level 5 etc."
7549 (interactive)
7550 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7551 (let ((outline-level 'org-outline-level)
7552 (org-odd-levels-only nil) n)
7553 (save-excursion
7554 (goto-char (point-min))
7555 (while (re-search-forward "^\\*\\*+ " nil t)
7556 (setq n (- (length (match-string 0)) 2))
7557 (while (>= (setq n (1- n)) 0)
7558 (org-demote))
7559 (end-of-line 1))))))
7561 (defun org-convert-to-oddeven-levels ()
7562 "Convert an org-mode file with only odd levels to one with odd/even levels.
7563 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7564 file contains a section with an even level, conversion would
7565 destroy the structure of the file. An error is signaled in this
7566 case."
7567 (interactive)
7568 (goto-char (point-min))
7569 ;; First check if there are no even levels
7570 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7571 (org-show-context t)
7572 (error "Not all levels are odd in this file. Conversion not possible"))
7573 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
7574 (let ((outline-regexp org-outline-regexp)
7575 (outline-level 'org-outline-level)
7576 (org-odd-levels-only nil) n)
7577 (save-excursion
7578 (goto-char (point-min))
7579 (while (re-search-forward "^\\*\\*+ " nil t)
7580 (setq n (/ (1- (length (match-string 0))) 2))
7581 (while (>= (setq n (1- n)) 0)
7582 (org-promote))
7583 (end-of-line 1))))))
7585 (defun org-tr-level (n)
7586 "Make N odd if required."
7587 (if org-odd-levels-only (1+ (/ n 2)) n))
7589 ;;; Vertical tree motion, cutting and pasting of subtrees
7591 (defun org-move-subtree-up (&optional arg)
7592 "Move the current subtree up past ARG headlines of the same level."
7593 (interactive "p")
7594 (org-move-subtree-down (- (prefix-numeric-value arg))))
7596 (defun org-move-subtree-down (&optional arg)
7597 "Move the current subtree down past ARG headlines of the same level."
7598 (interactive "p")
7599 (setq arg (prefix-numeric-value arg))
7600 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
7601 'org-get-last-sibling))
7602 (ins-point (make-marker))
7603 (cnt (abs arg))
7604 (col (current-column))
7605 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
7606 ;; Select the tree
7607 (org-back-to-heading)
7608 (setq beg0 (point))
7609 (save-excursion
7610 (setq ne-beg (org-back-over-empty-lines))
7611 (setq beg (point)))
7612 (save-match-data
7613 (save-excursion (outline-end-of-heading)
7614 (setq folded (outline-invisible-p)))
7615 (outline-end-of-subtree))
7616 (outline-next-heading)
7617 (setq ne-end (org-back-over-empty-lines))
7618 (setq end (point))
7619 (goto-char beg0)
7620 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
7621 ;; include less whitespace
7622 (save-excursion
7623 (goto-char beg)
7624 (forward-line (- ne-beg ne-end))
7625 (setq beg (point))))
7626 ;; Find insertion point, with error handling
7627 (while (> cnt 0)
7628 (or (and (funcall movfunc) (looking-at org-outline-regexp))
7629 (progn (goto-char beg0)
7630 (error "Cannot move past superior level or buffer limit")))
7631 (setq cnt (1- cnt)))
7632 (if (> arg 0)
7633 ;; Moving forward - still need to move over subtree
7634 (progn (org-end-of-subtree t t)
7635 (save-excursion
7636 (org-back-over-empty-lines)
7637 (or (bolp) (newline)))))
7638 (setq ne-ins (org-back-over-empty-lines))
7639 (move-marker ins-point (point))
7640 (setq txt (buffer-substring beg end))
7641 (org-save-markers-in-region beg end)
7642 (delete-region beg end)
7643 (org-remove-empty-overlays-at beg)
7644 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
7645 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
7646 (and (not (bolp)) (looking-at "\n") (forward-char 1))
7647 (let ((bbb (point)))
7648 (insert-before-markers txt)
7649 (org-reinstall-markers-in-region bbb)
7650 (move-marker ins-point bbb))
7651 (or (bolp) (insert "\n"))
7652 (setq ins-end (point))
7653 (goto-char ins-point)
7654 (org-skip-whitespace)
7655 (when (and (< arg 0)
7656 (org-first-sibling-p)
7657 (> ne-ins ne-beg))
7658 ;; Move whitespace back to beginning
7659 (save-excursion
7660 (goto-char ins-end)
7661 (let ((kill-whole-line t))
7662 (kill-line (- ne-ins ne-beg)) (point)))
7663 (insert (make-string (- ne-ins ne-beg) ?\n)))
7664 (move-marker ins-point nil)
7665 (if folded
7666 (hide-subtree)
7667 (org-show-entry)
7668 (show-children)
7669 (org-cycle-hide-drawers 'children))
7670 (org-clean-visibility-after-subtree-move)
7671 ;; move back to the initial column we were at
7672 (move-to-column col)))
7674 (defvar org-subtree-clip ""
7675 "Clipboard for cut and paste of subtrees.
7676 This is actually only a copy of the kill, because we use the normal kill
7677 ring. We need it to check if the kill was created by `org-copy-subtree'.")
7679 (defvar org-subtree-clip-folded nil
7680 "Was the last copied subtree folded?
7681 This is used to fold the tree back after pasting.")
7683 (defun org-cut-subtree (&optional n)
7684 "Cut the current subtree into the clipboard.
7685 With prefix arg N, cut this many sequential subtrees.
7686 This is a short-hand for marking the subtree and then cutting it."
7687 (interactive "p")
7688 (org-copy-subtree n 'cut))
7690 (defun org-copy-subtree (&optional n cut force-store-markers)
7691 "Cut the current subtree into the clipboard.
7692 With prefix arg N, cut this many sequential subtrees.
7693 This is a short-hand for marking the subtree and then copying it.
7694 If CUT is non-nil, actually cut the subtree.
7695 If FORCE-STORE-MARKERS is non-nil, store the relative locations
7696 of some markers in the region, even if CUT is non-nil. This is
7697 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
7698 (interactive "p")
7699 (let (beg end folded (beg0 (point)))
7700 (if (org-called-interactively-p 'any)
7701 (org-back-to-heading nil) ; take what looks like a subtree
7702 (org-back-to-heading t)) ; take what is really there
7703 (org-back-over-empty-lines)
7704 (setq beg (point))
7705 (skip-chars-forward " \t\r\n")
7706 (save-match-data
7707 (save-excursion (outline-end-of-heading)
7708 (setq folded (outline-invisible-p)))
7709 (condition-case nil
7710 (org-forward-same-level (1- n) t)
7711 (error nil))
7712 (org-end-of-subtree t t))
7713 (org-back-over-empty-lines)
7714 (setq end (point))
7715 (goto-char beg0)
7716 (when (> end beg)
7717 (setq org-subtree-clip-folded folded)
7718 (when (or cut force-store-markers)
7719 (org-save-markers-in-region beg end))
7720 (if cut (kill-region beg end) (copy-region-as-kill beg end))
7721 (setq org-subtree-clip (current-kill 0))
7722 (message "%s: Subtree(s) with %d characters"
7723 (if cut "Cut" "Copied")
7724 (length org-subtree-clip)))))
7726 (defun org-paste-subtree (&optional level tree for-yank)
7727 "Paste the clipboard as a subtree, with modification of headline level.
7728 The entire subtree is promoted or demoted in order to match a new headline
7729 level.
7731 If the cursor is at the beginning of a headline, the same level as
7732 that headline is used to paste the tree
7734 If not, the new level is derived from the *visible* headings
7735 before and after the insertion point, and taken to be the inferior headline
7736 level of the two. So if the previous visible heading is level 3 and the
7737 next is level 4 (or vice versa), level 4 will be used for insertion.
7738 This makes sure that the subtree remains an independent subtree and does
7739 not swallow low level entries.
7741 You can also force a different level, either by using a numeric prefix
7742 argument, or by inserting the heading marker by hand. For example, if the
7743 cursor is after \"*****\", then the tree will be shifted to level 5.
7745 If optional TREE is given, use this text instead of the kill ring.
7747 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
7748 move back over whitespace before inserting, and move point to the end of
7749 the inserted text when done."
7750 (interactive "P")
7751 (setq tree (or tree (and kill-ring (current-kill 0))))
7752 (unless (org-kill-is-subtree-p tree)
7753 (error "%s"
7754 (substitute-command-keys
7755 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
7756 (org-with-limited-levels
7757 (let* ((visp (not (outline-invisible-p)))
7758 (txt tree)
7759 (^re_ "\\(\\*+\\)[ \t]*")
7760 (old-level (if (string-match org-outline-regexp-bol txt)
7761 (- (match-end 0) (match-beginning 0) 1)
7762 -1))
7763 (force-level (cond (level (prefix-numeric-value level))
7764 ((and (looking-at "[ \t]*$")
7765 (string-match
7766 "^\\*+$" (buffer-substring
7767 (point-at-bol) (point))))
7768 (- (match-end 1) (match-beginning 1)))
7769 ((and (bolp)
7770 (looking-at org-outline-regexp))
7771 (- (match-end 0) (point) 1))
7772 (t nil)))
7773 (previous-level (save-excursion
7774 (condition-case nil
7775 (progn
7776 (outline-previous-visible-heading 1)
7777 (if (looking-at ^re_)
7778 (- (match-end 0) (match-beginning 0) 1)
7780 (error 1))))
7781 (next-level (save-excursion
7782 (condition-case nil
7783 (progn
7784 (or (looking-at org-outline-regexp)
7785 (outline-next-visible-heading 1))
7786 (if (looking-at ^re_)
7787 (- (match-end 0) (match-beginning 0) 1)
7789 (error 1))))
7790 (new-level (or force-level (max previous-level next-level)))
7791 (shift (if (or (= old-level -1)
7792 (= new-level -1)
7793 (= old-level new-level))
7795 (- new-level old-level)))
7796 (delta (if (> shift 0) -1 1))
7797 (func (if (> shift 0) 'org-demote 'org-promote))
7798 (org-odd-levels-only nil)
7799 beg end newend)
7800 ;; Remove the forced level indicator
7801 (if force-level
7802 (delete-region (point-at-bol) (point)))
7803 ;; Paste
7804 (beginning-of-line (if (bolp) 1 2))
7805 (unless for-yank (org-back-over-empty-lines))
7806 (setq beg (point))
7807 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
7808 (insert-before-markers txt)
7809 (unless (string-match "\n\\'" txt) (insert "\n"))
7810 (setq newend (point))
7811 (org-reinstall-markers-in-region beg)
7812 (setq end (point))
7813 (goto-char beg)
7814 (skip-chars-forward " \t\n\r")
7815 (setq beg (point))
7816 (if (and (outline-invisible-p) visp)
7817 (save-excursion (outline-show-heading)))
7818 ;; Shift if necessary
7819 (unless (= shift 0)
7820 (save-restriction
7821 (narrow-to-region beg end)
7822 (while (not (= shift 0))
7823 (org-map-region func (point-min) (point-max))
7824 (setq shift (+ delta shift)))
7825 (goto-char (point-min))
7826 (setq newend (point-max))))
7827 (when (or (org-called-interactively-p 'interactive) for-yank)
7828 (message "Clipboard pasted as level %d subtree" new-level))
7829 (if (and (not for-yank) ; in this case, org-yank will decide about folding
7830 kill-ring
7831 (eq org-subtree-clip (current-kill 0))
7832 org-subtree-clip-folded)
7833 ;; The tree was folded before it was killed/copied
7834 (hide-subtree))
7835 (and for-yank (goto-char newend)))))
7837 (defun org-kill-is-subtree-p (&optional txt)
7838 "Check if the current kill is an outline subtree, or a set of trees.
7839 Returns nil if kill does not start with a headline, or if the first
7840 headline level is not the largest headline level in the tree.
7841 So this will actually accept several entries of equal levels as well,
7842 which is OK for `org-paste-subtree'.
7843 If optional TXT is given, check this string instead of the current kill."
7844 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
7845 (re (org-get-limited-outline-regexp))
7846 (^re (concat "^" re))
7847 (start-level (and kill
7848 (string-match
7849 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
7850 kill)
7851 (- (match-end 2) (match-beginning 2) 1)))
7852 (start (1+ (or (match-beginning 2) -1))))
7853 (if (not start-level)
7854 (progn
7855 nil) ;; does not even start with a heading
7856 (catch 'exit
7857 (while (setq start (string-match ^re kill (1+ start)))
7858 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
7859 (throw 'exit nil)))
7860 t))))
7862 (defvar org-markers-to-move nil
7863 "Markers that should be moved with a cut-and-paste operation.
7864 Those markers are stored together with their positions relative to
7865 the start of the region.")
7867 (defun org-save-markers-in-region (beg end)
7868 "Check markers in region.
7869 If these markers are between BEG and END, record their position relative
7870 to BEG, so that after moving the block of text, we can put the markers back
7871 into place.
7872 This function gets called just before an entry or tree gets cut from the
7873 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
7874 called immediately, to move the markers with the entries."
7875 (setq org-markers-to-move nil)
7876 (when (featurep 'org-clock)
7877 (org-clock-save-markers-for-cut-and-paste beg end))
7878 (when (featurep 'org-agenda)
7879 (org-agenda-save-markers-for-cut-and-paste beg end)))
7881 (defun org-check-and-save-marker (marker beg end)
7882 "Check if MARKER is between BEG and END.
7883 If yes, remember the marker and the distance to BEG."
7884 (when (and (marker-buffer marker)
7885 (equal (marker-buffer marker) (current-buffer)))
7886 (if (and (>= marker beg) (< marker end))
7887 (push (cons marker (- marker beg)) org-markers-to-move))))
7889 (defun org-reinstall-markers-in-region (beg)
7890 "Move all remembered markers to their position relative to BEG."
7891 (mapc (lambda (x)
7892 (move-marker (car x) (+ beg (cdr x))))
7893 org-markers-to-move)
7894 (setq org-markers-to-move nil))
7896 (defun org-narrow-to-subtree ()
7897 "Narrow buffer to the current subtree."
7898 (interactive)
7899 (save-excursion
7900 (save-match-data
7901 (org-with-limited-levels
7902 (narrow-to-region
7903 (progn (org-back-to-heading t) (point))
7904 (progn (org-end-of-subtree t t)
7905 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
7906 (point)))))))
7908 (defun org-narrow-to-block ()
7909 "Narrow buffer to the current block."
7910 (interactive)
7911 (let* ((case-fold-search t)
7912 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
7913 "^[ \t]*#\\+end_.*")))
7914 (if blockp
7915 (narrow-to-region (car blockp) (cdr blockp))
7916 (error "Not in a block"))))
7918 (eval-when-compile
7919 (defvar org-property-drawer-re))
7921 (defvar org-property-start-re) ;; defined below
7922 (defun org-clone-subtree-with-time-shift (n &optional shift)
7923 "Clone the task (subtree) at point N times.
7924 The clones will be inserted as siblings.
7926 In interactive use, the user will be prompted for the number of
7927 clones to be produced, and for a time SHIFT, which may be a
7928 repeater as used in time stamps, for example `+3d'.
7930 When a valid repeater is given and the entry contains any time
7931 stamps, the clones will become a sequence in time, with time
7932 stamps in the subtree shifted for each clone produced. If SHIFT
7933 is nil or the empty string, time stamps will be left alone. The
7934 ID property of the original subtree is removed.
7936 If the original subtree did contain time stamps with a repeater,
7937 the following will happen:
7938 - the repeater will be removed in each clone
7939 - an additional clone will be produced, with the current, unshifted
7940 date(s) in the entry.
7941 - the original entry will be placed *after* all the clones, with
7942 repeater intact.
7943 - the start days in the repeater in the original entry will be shifted
7944 to past the last clone.
7945 In this way you can spell out a number of instances of a repeating task,
7946 and still retain the repeater to cover future instances of the task."
7947 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
7948 (let (beg end template task idprop
7949 shift-n shift-what doshift nmin nmax (n-no-remove -1)
7950 (drawer-re org-drawer-regexp))
7951 (if (not (and (integerp n) (> n 0)))
7952 (error "Invalid number of replications %s" n))
7953 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
7954 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
7955 shift)))
7956 (error "Invalid shift specification %s" shift))
7957 (when doshift
7958 (setq shift-n (string-to-number (match-string 1 shift))
7959 shift-what (cdr (assoc (match-string 2 shift)
7960 '(("d" . day) ("w" . week)
7961 ("m" . month) ("y" . year))))))
7962 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
7963 (setq nmin 1 nmax n)
7964 (org-back-to-heading t)
7965 (setq beg (point))
7966 (setq idprop (org-entry-get nil "ID"))
7967 (org-end-of-subtree t t)
7968 (or (bolp) (insert "\n"))
7969 (setq end (point))
7970 (setq template (buffer-substring beg end))
7971 (when (and doshift
7972 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[dwmy][^<>\n]*>" template))
7973 (delete-region beg end)
7974 (setq end beg)
7975 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
7976 (goto-char end)
7977 (loop for n from nmin to nmax do
7978 ;; prepare clone
7979 (with-temp-buffer
7980 (insert template)
7981 (org-mode)
7982 (goto-char (point-min))
7983 (org-show-subtree)
7984 (and idprop (if org-clone-delete-id
7985 (org-entry-delete nil "ID")
7986 (org-id-get-create t)))
7987 (unless (= n 0)
7988 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
7989 (kill-whole-line))
7990 (goto-char (point-min))
7991 (while (re-search-forward drawer-re nil t)
7992 (mapc (lambda (d)
7993 (org-remove-empty-drawer-at d (point))) org-drawers)))
7994 (goto-char (point-min))
7995 (when doshift
7996 (while (re-search-forward org-ts-regexp-both nil t)
7997 (org-timestamp-change (* n shift-n) shift-what))
7998 (unless (= n n-no-remove)
7999 (goto-char (point-min))
8000 (while (re-search-forward org-ts-regexp nil t)
8001 (save-excursion
8002 (goto-char (match-beginning 0))
8003 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[dwmy]\\)")
8004 (delete-region (match-beginning 1) (match-end 1)))))))
8005 (setq task (buffer-string)))
8006 (insert task))
8007 (goto-char beg)))
8009 ;;; Outline Sorting
8011 (defun org-sort (with-case)
8012 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8013 Optional argument WITH-CASE means sort case-sensitively."
8014 (interactive "P")
8015 (cond
8016 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8017 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8019 (org-call-with-arg 'org-sort-entries with-case))))
8021 (defun org-sort-remove-invisible (s)
8022 (remove-text-properties 0 (length s) org-rm-props s)
8023 (while (string-match org-bracket-link-regexp s)
8024 (setq s (replace-match (if (match-end 2)
8025 (match-string 3 s)
8026 (match-string 1 s)) t t s)))
8029 (defvar org-priority-regexp) ; defined later in the file
8031 (defvar org-after-sorting-entries-or-items-hook nil
8032 "Hook that is run after a bunch of entries or items have been sorted.
8033 When children are sorted, the cursor is in the parent line when this
8034 hook gets called. When a region or a plain list is sorted, the cursor
8035 will be in the first entry of the sorted region/list.")
8037 (defun org-sort-entries
8038 (&optional with-case sorting-type getkey-func compare-func property)
8039 "Sort entries on a certain level of an outline tree.
8040 If there is an active region, the entries in the region are sorted.
8041 Else, if the cursor is before the first entry, sort the top-level items.
8042 Else, the children of the entry at point are sorted.
8044 Sorting can be alphabetically, numerically, by date/time as given by
8045 a time stamp, by a property or by priority.
8047 The command prompts for the sorting type unless it has been given to the
8048 function through the SORTING-TYPE argument, which needs to be a character,
8049 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F). Here is the
8050 precise meaning of each character:
8052 n Numerically, by converting the beginning of the entry/item to a number.
8053 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8054 t By date/time, either the first active time stamp in the entry, or, if
8055 none exist, by the first inactive one.
8056 s By the scheduled date/time.
8057 d By deadline date/time.
8058 c By creation time, which is assumed to be the first inactive time stamp
8059 at the beginning of a line.
8060 p By priority according to the cookie.
8061 r By the value of a property.
8063 Capital letters will reverse the sort order.
8065 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8066 called with point at the beginning of the record. It must return either
8067 a string or a number that should serve as the sorting key for that record.
8069 Comparing entries ignores case by default. However, with an optional argument
8070 WITH-CASE, the sorting considers case as well."
8071 (interactive "P")
8072 (let ((case-func (if with-case 'identity 'downcase))
8073 start beg end stars re re2
8074 txt what tmp)
8075 ;; Find beginning and end of region to sort
8076 (cond
8077 ((org-region-active-p)
8078 ;; we will sort the region
8079 (setq end (region-end)
8080 what "region")
8081 (goto-char (region-beginning))
8082 (if (not (org-at-heading-p)) (outline-next-heading))
8083 (setq start (point)))
8084 ((or (org-at-heading-p)
8085 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8086 ;; we will sort the children of the current headline
8087 (org-back-to-heading)
8088 (setq start (point)
8089 end (progn (org-end-of-subtree t t)
8090 (or (bolp) (insert "\n"))
8091 (org-back-over-empty-lines)
8092 (point))
8093 what "children")
8094 (goto-char start)
8095 (show-subtree)
8096 (outline-next-heading))
8098 ;; we will sort the top-level entries in this file
8099 (goto-char (point-min))
8100 (or (org-at-heading-p) (outline-next-heading))
8101 (setq start (point))
8102 (goto-char (point-max))
8103 (beginning-of-line 1)
8104 (when (looking-at ".*?\\S-")
8105 ;; File ends in a non-white line
8106 (end-of-line 1)
8107 (insert "\n"))
8108 (setq end (point-max))
8109 (setq what "top-level")
8110 (goto-char start)
8111 (show-all)))
8113 (setq beg (point))
8114 (if (>= beg end) (error "Nothing to sort"))
8116 (looking-at "\\(\\*+\\)")
8117 (setq stars (match-string 1)
8118 re (concat "^" (regexp-quote stars) " +")
8119 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8120 txt (buffer-substring beg end))
8121 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8122 (if (and (not (equal stars "*")) (string-match re2 txt))
8123 (error "Region to sort contains a level above the first entry"))
8125 (unless sorting-type
8126 (message
8127 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8128 [t]ime [s]cheduled [d]eadline [c]reated
8129 A/N/T/S/D/C/P/O/F means reversed:"
8130 what)
8131 (setq sorting-type (read-char-exclusive))
8133 (and (= (downcase sorting-type) ?f)
8134 (setq getkey-func
8135 (org-icompleting-read "Sort using function: "
8136 obarray 'fboundp t nil nil))
8137 (setq getkey-func (intern getkey-func)))
8139 (and (= (downcase sorting-type) ?r)
8140 (setq property
8141 (org-icompleting-read "Property: "
8142 (mapcar 'list (org-buffer-property-keys t))
8143 nil t))))
8145 (message "Sorting entries...")
8147 (save-restriction
8148 (narrow-to-region start end)
8149 (let ((dcst (downcase sorting-type))
8150 (case-fold-search nil)
8151 (now (current-time)))
8152 (sort-subr
8153 (/= dcst sorting-type)
8154 ;; This function moves to the beginning character of the "record" to
8155 ;; be sorted.
8156 (lambda nil
8157 (if (re-search-forward re nil t)
8158 (goto-char (match-beginning 0))
8159 (goto-char (point-max))))
8160 ;; This function moves to the last character of the "record" being
8161 ;; sorted.
8162 (lambda nil
8163 (save-match-data
8164 (condition-case nil
8165 (outline-forward-same-level 1)
8166 (error
8167 (goto-char (point-max))))))
8168 ;; This function returns the value that gets sorted against.
8169 (lambda nil
8170 (cond
8171 ((= dcst ?n)
8172 (if (looking-at org-complex-heading-regexp)
8173 (string-to-number (match-string 4))
8174 nil))
8175 ((= dcst ?a)
8176 (if (looking-at org-complex-heading-regexp)
8177 (funcall case-func (match-string 4))
8178 nil))
8179 ((= dcst ?t)
8180 (let ((end (save-excursion (outline-next-heading) (point))))
8181 (if (or (re-search-forward org-ts-regexp end t)
8182 (re-search-forward org-ts-regexp-both end t))
8183 (org-time-string-to-seconds (match-string 0))
8184 (org-float-time now))))
8185 ((= dcst ?c)
8186 (let ((end (save-excursion (outline-next-heading) (point))))
8187 (if (re-search-forward
8188 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8189 end t)
8190 (org-time-string-to-seconds (match-string 0))
8191 (org-float-time now))))
8192 ((= dcst ?s)
8193 (let ((end (save-excursion (outline-next-heading) (point))))
8194 (if (re-search-forward org-scheduled-time-regexp end t)
8195 (org-time-string-to-seconds (match-string 1))
8196 (org-float-time now))))
8197 ((= dcst ?d)
8198 (let ((end (save-excursion (outline-next-heading) (point))))
8199 (if (re-search-forward org-deadline-time-regexp end t)
8200 (org-time-string-to-seconds (match-string 1))
8201 (org-float-time now))))
8202 ((= dcst ?p)
8203 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8204 (string-to-char (match-string 2))
8205 org-default-priority))
8206 ((= dcst ?r)
8207 (or (org-entry-get nil property) ""))
8208 ((= dcst ?o)
8209 (if (looking-at org-complex-heading-regexp)
8210 (- 9999 (length (member (match-string 2)
8211 org-todo-keywords-1)))))
8212 ((= dcst ?f)
8213 (if getkey-func
8214 (progn
8215 (setq tmp (funcall getkey-func))
8216 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8217 tmp)
8218 (error "Invalid key function `%s'" getkey-func)))
8219 (t (error "Invalid sorting type `%c'" sorting-type))))
8221 (cond
8222 ((= dcst ?a) 'string<)
8223 ((= dcst ?f) compare-func)
8224 ((member dcst '(?p ?t ?s ?d ?c)) '<)
8225 (t nil)))))
8226 (run-hooks 'org-after-sorting-entries-or-items-hook)
8227 (message "Sorting entries...done")))
8229 (defun org-do-sort (table what &optional with-case sorting-type)
8230 "Sort TABLE of WHAT according to SORTING-TYPE.
8231 The user will be prompted for the SORTING-TYPE if the call to this
8232 function does not specify it. WHAT is only for the prompt, to indicate
8233 what is being sorted. The sorting key will be extracted from
8234 the car of the elements of the table.
8235 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8236 (unless sorting-type
8237 (message
8238 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
8239 what)
8240 (setq sorting-type (read-char-exclusive)))
8241 (let ((dcst (downcase sorting-type))
8242 extractfun comparefun)
8243 ;; Define the appropriate functions
8244 (cond
8245 ((= dcst ?n)
8246 (setq extractfun 'string-to-number
8247 comparefun (if (= dcst sorting-type) '< '>)))
8248 ((= dcst ?a)
8249 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8250 (lambda(x) (downcase (org-sort-remove-invisible x))))
8251 comparefun (if (= dcst sorting-type)
8252 'string<
8253 (lambda (a b) (and (not (string< a b))
8254 (not (string= a b)))))))
8255 ((= dcst ?t)
8256 (setq extractfun
8257 (lambda (x)
8258 (if (or (string-match org-ts-regexp x)
8259 (string-match org-ts-regexp-both x))
8260 (org-float-time
8261 (org-time-string-to-time (match-string 0 x)))
8263 comparefun (if (= dcst sorting-type) '< '>)))
8264 (t (error "Invalid sorting type `%c'" sorting-type)))
8266 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8267 table)
8268 (lambda (a b) (funcall comparefun (car a) (car b))))))
8271 ;;; The orgstruct minor mode
8273 ;; Define a minor mode which can be used in other modes in order to
8274 ;; integrate the org-mode structure editing commands.
8276 ;; This is really a hack, because the org-mode structure commands use
8277 ;; keys which normally belong to the major mode. Here is how it
8278 ;; works: The minor mode defines all the keys necessary to operate the
8279 ;; structure commands, but wraps the commands into a function which
8280 ;; tests if the cursor is currently at a headline or a plain list
8281 ;; item. If that is the case, the structure command is used,
8282 ;; temporarily setting many Org-mode variables like regular
8283 ;; expressions for filling etc. However, when any of those keys is
8284 ;; used at a different location, function uses `key-binding' to look
8285 ;; up if the key has an associated command in another currently active
8286 ;; keymap (minor modes, major mode, global), and executes that
8287 ;; command. There might be problems if any of the keys is otherwise
8288 ;; used as a prefix key.
8290 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
8291 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
8292 ;; addresses this by checking explicitly for both bindings.
8294 (defvar orgstruct-mode-map (make-sparse-keymap)
8295 "Keymap for the minor `orgstruct-mode'.")
8297 (defvar org-local-vars nil
8298 "List of local variables, for use by `orgstruct-mode'.")
8300 ;;;###autoload
8301 (define-minor-mode orgstruct-mode
8302 "Toggle the minor mode `orgstruct-mode'.
8303 This mode is for using Org-mode structure commands in other
8304 modes. The following keys behave as if Org-mode were active, if
8305 the cursor is on a headline, or on a plain list item (both as
8306 defined by Org-mode).
8308 M-up Move entry/item up
8309 M-down Move entry/item down
8310 M-left Promote
8311 M-right Demote
8312 M-S-up Move entry/item up
8313 M-S-down Move entry/item down
8314 M-S-left Promote subtree
8315 M-S-right Demote subtree
8316 M-q Fill paragraph and items like in Org-mode
8317 C-c ^ Sort entries
8318 C-c - Cycle list bullet
8319 TAB Cycle item visibility
8320 M-RET Insert new heading/item
8321 S-M-RET Insert new TODO heading / Checkbox item
8322 C-c C-c Set tags / toggle checkbox"
8323 nil " OrgStruct" nil
8324 (org-load-modules-maybe)
8325 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
8327 ;;;###autoload
8328 (defun turn-on-orgstruct ()
8329 "Unconditionally turn on `orgstruct-mode'."
8330 (orgstruct-mode 1))
8332 (defun orgstruct++-mode (&optional arg)
8333 "Toggle `orgstruct-mode', the enhanced version of it.
8334 In addition to setting orgstruct-mode, this also exports all indentation
8335 and autofilling variables from org-mode into the buffer. It will also
8336 recognize item context in multiline items.
8337 Note that turning off orgstruct-mode will *not* remove the
8338 indentation/paragraph settings. This can only be done by refreshing the
8339 major mode, for example with \\[normal-mode]."
8340 (interactive "P")
8341 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8342 (if (< arg 1)
8343 (orgstruct-mode -1)
8344 (orgstruct-mode 1)
8345 (let (var val)
8346 (mapc
8347 (lambda (x)
8348 (when (string-match
8349 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
8350 (symbol-name (car x)))
8351 (setq var (car x) val (nth 1 x))
8352 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8353 org-local-vars)
8354 (org-set-local 'orgstruct-is-++ t))))
8356 (defvar orgstruct-is-++ nil
8357 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8358 (make-variable-buffer-local 'orgstruct-is-++)
8360 ;;;###autoload
8361 (defun turn-on-orgstruct++ ()
8362 "Unconditionally turn on `orgstruct++-mode'."
8363 (orgstruct++-mode 1))
8365 (defun orgstruct-error ()
8366 "Error when there is no default binding for a structure key."
8367 (interactive)
8368 (error "This key has no function outside structure elements"))
8370 (defun orgstruct-setup ()
8371 "Setup orgstruct keymaps."
8372 (let ((nfunc 0)
8373 (bindings
8374 (list
8375 '([(meta up)] org-metaup)
8376 '([(meta down)] org-metadown)
8377 '([(meta left)] org-metaleft)
8378 '([(meta right)] org-metaright)
8379 '([(meta shift up)] org-shiftmetaup)
8380 '([(meta shift down)] org-shiftmetadown)
8381 '([(meta shift left)] org-shiftmetaleft)
8382 '([(meta shift right)] org-shiftmetaright)
8383 '([?\e (up)] org-metaup)
8384 '([?\e (down)] org-metadown)
8385 '([?\e (left)] org-metaleft)
8386 '([?\e (right)] org-metaright)
8387 '([?\e (shift up)] org-shiftmetaup)
8388 '([?\e (shift down)] org-shiftmetadown)
8389 '([?\e (shift left)] org-shiftmetaleft)
8390 '([?\e (shift right)] org-shiftmetaright)
8391 '([(shift up)] org-shiftup)
8392 '([(shift down)] org-shiftdown)
8393 '([(shift left)] org-shiftleft)
8394 '([(shift right)] org-shiftright)
8395 '("\C-c\C-c" org-ctrl-c-ctrl-c)
8396 '("\M-q" fill-paragraph)
8397 '("\C-c^" org-sort)
8398 '("\C-c-" org-cycle-list-bullet)))
8399 elt key fun cmd)
8400 (while (setq elt (pop bindings))
8401 (setq nfunc (1+ nfunc))
8402 (setq key (org-key (car elt))
8403 fun (nth 1 elt)
8404 cmd (orgstruct-make-binding fun nfunc key))
8405 (org-defkey orgstruct-mode-map key cmd))
8407 ;; Special treatment needed for TAB and RET
8408 (org-defkey orgstruct-mode-map [(tab)]
8409 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
8410 (org-defkey orgstruct-mode-map "\C-i"
8411 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
8413 (org-defkey orgstruct-mode-map "\M-\C-m"
8414 (orgstruct-make-binding 'org-insert-heading 105
8415 "\M-\C-m" [(meta return)]))
8416 (org-defkey orgstruct-mode-map [(meta return)]
8417 (orgstruct-make-binding 'org-insert-heading 106
8418 [(meta return)] "\M-\C-m"))
8420 (org-defkey orgstruct-mode-map [(shift meta return)]
8421 (orgstruct-make-binding 'org-insert-todo-heading 107
8422 [(meta return)] "\M-\C-m"))
8424 (org-defkey orgstruct-mode-map "\e\C-m"
8425 (orgstruct-make-binding 'org-insert-heading 108
8426 "\e\C-m" [?\e (return)]))
8427 (org-defkey orgstruct-mode-map [?\e (return)]
8428 (orgstruct-make-binding 'org-insert-heading 109
8429 [?\e (return)] "\e\C-m"))
8430 (org-defkey orgstruct-mode-map [?\e (shift return)]
8431 (orgstruct-make-binding 'org-insert-todo-heading 110
8432 [?\e (return)] "\e\C-m"))
8434 (unless org-local-vars
8435 (setq org-local-vars (org-get-local-variables)))
8439 (defun orgstruct-make-binding (fun n &rest keys)
8440 "Create a function for binding in the structure minor mode.
8441 FUN is the command to call inside a table. N is used to create a unique
8442 command name. KEYS are keys that should be checked in for a command
8443 to execute outside of tables."
8444 (eval
8445 (list 'defun
8446 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
8447 '(arg)
8448 (concat "In Structure, run `" (symbol-name fun) "'.\n"
8449 "Outside of structure, run the binding of `"
8450 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
8451 "'.")
8452 '(interactive "p")
8453 (list 'if
8454 `(org-context-p 'headline 'item
8455 (and orgstruct-is-++
8456 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
8457 'item-body))
8458 (list 'org-run-like-in-org-mode (list 'quote fun))
8459 (list 'let '(orgstruct-mode)
8460 (list 'call-interactively
8461 (append '(or)
8462 (mapcar (lambda (k)
8463 (list 'key-binding k))
8464 keys)
8465 '('orgstruct-error))))))))
8467 (defun org-context-p (&rest contexts)
8468 "Check if local context is any of CONTEXTS.
8469 Possible values in the list of contexts are `table', `headline', and `item'."
8470 (let ((pos (point)))
8471 (goto-char (point-at-bol))
8472 (prog1 (or (and (memq 'table contexts)
8473 (looking-at "[ \t]*|"))
8474 (and (memq 'headline contexts)
8475 (looking-at org-outline-regexp))
8476 (and (memq 'item contexts)
8477 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
8478 (and (memq 'item-body contexts)
8479 (org-in-item-p)))
8480 (goto-char pos))))
8482 (defun org-get-local-variables ()
8483 "Return a list of all local variables in an org-mode buffer."
8484 (let (varlist)
8485 (with-current-buffer (get-buffer-create "*Org tmp*")
8486 (erase-buffer)
8487 (org-mode)
8488 (setq varlist (buffer-local-variables)))
8489 (kill-buffer "*Org tmp*")
8490 (delq nil
8491 (mapcar
8492 (lambda (x)
8493 (setq x
8494 (if (symbolp x)
8495 (list x)
8496 (list (car x) (list 'quote (cdr x)))))
8497 (if (string-match
8498 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
8499 (symbol-name (car x)))
8500 x nil))
8501 varlist))))
8503 (defun org-clone-local-variables (from-buffer &optional regexp)
8504 "Clone local variables from FROM-BUFFER.
8505 Optional argument REGEXP selects variables to clone."
8506 (mapc
8507 (lambda (pair)
8508 (and (symbolp (car pair))
8509 (or (null regexp)
8510 (string-match regexp (symbol-name (car pair))))
8511 (set (make-local-variable (car pair))
8512 (cdr pair))))
8513 (buffer-local-variables from-buffer)))
8515 ;;;###autoload
8516 (defun org-run-like-in-org-mode (cmd)
8517 "Run a command, pretending that the current buffer is in Org-mode.
8518 This will temporarily bind local variables that are typically bound in
8519 Org-mode to the values they have in Org-mode, and then interactively
8520 call CMD."
8521 (org-load-modules-maybe)
8522 (unless org-local-vars
8523 (setq org-local-vars (org-get-local-variables)))
8524 (eval (list 'let org-local-vars
8525 (list 'call-interactively (list 'quote cmd)))))
8527 ;;;; Archiving
8529 (defun org-get-category (&optional pos force-refresh)
8530 "Get the category applying to position POS."
8531 (save-match-data
8532 (if force-refresh (org-refresh-category-properties))
8533 (let ((pos (or pos (point))))
8534 (or (get-text-property pos 'org-category)
8535 (progn (org-refresh-category-properties)
8536 (get-text-property pos 'org-category))))))
8538 (defun org-refresh-category-properties ()
8539 "Refresh category text properties in the buffer."
8540 (let ((def-cat (cond
8541 ((null org-category)
8542 (if buffer-file-name
8543 (file-name-sans-extension
8544 (file-name-nondirectory buffer-file-name))
8545 "???"))
8546 ((symbolp org-category) (symbol-name org-category))
8547 (t org-category)))
8548 beg end cat pos optionp)
8549 (org-unmodified
8550 (save-excursion
8551 (save-restriction
8552 (widen)
8553 (goto-char (point-min))
8554 (put-text-property (point) (point-max) 'org-category def-cat)
8555 (while (re-search-forward
8556 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8557 (setq pos (match-end 0)
8558 optionp (equal (char-after (match-beginning 0)) ?#)
8559 cat (org-trim (match-string 2)))
8560 (if optionp
8561 (setq beg (point-at-bol) end (point-max))
8562 (org-back-to-heading t)
8563 (setq beg (point) end (org-end-of-subtree t t)))
8564 (put-text-property beg end 'org-category cat)
8565 (put-text-property beg end 'org-category-position beg)
8566 (goto-char pos)))))))
8569 ;;;; Link Stuff
8571 ;;; Link abbreviations
8573 (defun org-link-expand-abbrev (link)
8574 "Apply replacements as defined in `org-link-abbrev-alist."
8575 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
8576 (let* ((key (match-string 1 link))
8577 (as (or (assoc key org-link-abbrev-alist-local)
8578 (assoc key org-link-abbrev-alist)))
8579 (tag (and (match-end 2) (match-string 3 link)))
8580 rpl)
8581 (if (not as)
8582 link
8583 (setq rpl (cdr as))
8584 (cond
8585 ((symbolp rpl) (funcall rpl tag))
8586 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
8587 ((string-match "%h" rpl)
8588 (replace-match (url-hexify-string (or tag "")) t t rpl))
8589 (t (concat rpl tag)))))
8590 link))
8592 ;;; Storing and inserting links
8594 (defvar org-insert-link-history nil
8595 "Minibuffer history for links inserted with `org-insert-link'.")
8597 (defvar org-stored-links nil
8598 "Contains the links stored with `org-store-link'.")
8600 (defvar org-store-link-plist nil
8601 "Plist with info about the most recently link created with `org-store-link'.")
8603 (defvar org-link-protocols nil
8604 "Link protocols added to Org-mode using `org-add-link-type'.")
8606 (defvar org-store-link-functions nil
8607 "List of functions that are called to create and store a link.
8608 Each function will be called in turn until one returns a non-nil
8609 value. Each function should check if it is responsible for creating
8610 this link (for example by looking at the major mode).
8611 If not, it must exit and return nil.
8612 If yes, it should return a non-nil value after a calling
8613 `org-store-link-props' with a list of properties and values.
8614 Special properties are:
8616 :type The link prefix, like \"http\". This must be given.
8617 :link The link, like \"http://www.astro.uva.nl/~dominik\".
8618 This is obligatory as well.
8619 :description Optional default description for the second pair
8620 of brackets in an Org-mode link. The user can still change
8621 this when inserting this link into an Org-mode buffer.
8623 In addition to these, any additional properties can be specified
8624 and then used in remember templates.")
8626 (defun org-add-link-type (type &optional follow export)
8627 "Add TYPE to the list of `org-link-types'.
8628 Re-compute all regular expressions depending on `org-link-types'
8630 FOLLOW and EXPORT are two functions.
8632 FOLLOW should take the link path as the single argument and do whatever
8633 is necessary to follow the link, for example find a file or display
8634 a mail message.
8636 EXPORT should format the link path for export to one of the export formats.
8637 It should be a function accepting three arguments:
8639 path the path of the link, the text after the prefix (like \"http:\")
8640 desc the description of the link, if any, or a description added by
8641 org-export-normalize-links if there is none
8642 format the export format, a symbol like `html' or `latex' or `ascii'..
8644 The function may use the FORMAT information to return different values
8645 depending on the format. The return value will be put literally into
8646 the exported file. If the return value is nil, this means Org should
8647 do what it normally does with links which do not have EXPORT defined.
8649 Org-mode has a built-in default for exporting links. If you are happy with
8650 this default, there is no need to define an export function for the link
8651 type. For a simple example of an export function, see `org-bbdb.el'."
8652 (add-to-list 'org-link-types type t)
8653 (org-make-link-regexps)
8654 (if (assoc type org-link-protocols)
8655 (setcdr (assoc type org-link-protocols) (list follow export))
8656 (push (list type follow export) org-link-protocols)))
8658 (defvar org-agenda-buffer-name)
8660 ;;;###autoload
8661 (defun org-store-link (arg)
8662 "\\<org-mode-map>Store an org-link to the current location.
8663 This link is added to `org-stored-links' and can later be inserted
8664 into an org-buffer with \\[org-insert-link].
8666 For some link types, a prefix arg is interpreted:
8667 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
8668 For file links, arg negates `org-context-in-file-links'."
8669 (interactive "P")
8670 (org-load-modules-maybe)
8671 (setq org-store-link-plist nil) ; reset
8672 (org-with-limited-levels
8673 (let (link cpltxt desc description search txt custom-id agenda-link)
8674 (cond
8676 ((run-hook-with-args-until-success 'org-store-link-functions)
8677 (setq link (plist-get org-store-link-plist :link)
8678 desc (or (plist-get org-store-link-plist :description) link)))
8680 ((org-src-edit-buffer-p)
8681 (let (label gc)
8682 (while (or (not label)
8683 (save-excursion
8684 (save-restriction
8685 (widen)
8686 (goto-char (point-min))
8687 (re-search-forward
8688 (regexp-quote (format org-coderef-label-format label))
8689 nil t))))
8690 (when label (message "Label exists already") (sit-for 2))
8691 (setq label (read-string "Code line label: " label)))
8692 (end-of-line 1)
8693 (setq link (format org-coderef-label-format label))
8694 (setq gc (- 79 (length link)))
8695 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
8696 (insert link)
8697 (setq link (concat "(" label ")") desc nil)))
8699 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
8700 ;; We are in the agenda, link to referenced location
8701 (let ((m (or (get-text-property (point) 'org-hd-marker)
8702 (get-text-property (point) 'org-marker))))
8703 (when m
8704 (org-with-point-at m
8705 (setq agenda-link
8706 (if (org-called-interactively-p 'any)
8707 (call-interactively 'org-store-link)
8708 (org-store-link nil)))))))
8710 ((eq major-mode 'calendar-mode)
8711 (let ((cd (calendar-cursor-to-date)))
8712 (setq link
8713 (format-time-string
8714 (car org-time-stamp-formats)
8715 (apply 'encode-time
8716 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
8717 nil nil nil))))
8718 (org-store-link-props :type "calendar" :date cd)))
8720 ((eq major-mode 'w3-mode)
8721 (setq cpltxt (if (and (buffer-name)
8722 (not (string-match "Untitled" (buffer-name))))
8723 (buffer-name)
8724 (url-view-url t))
8725 link (org-make-link (url-view-url t)))
8726 (org-store-link-props :type "w3" :url (url-view-url t)))
8728 ((eq major-mode 'w3m-mode)
8729 (setq cpltxt (or w3m-current-title w3m-current-url)
8730 link (org-make-link w3m-current-url))
8731 (org-store-link-props :type "w3m" :url (url-view-url t)))
8733 ((setq search (run-hook-with-args-until-success
8734 'org-create-file-search-functions))
8735 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
8736 "::" search))
8737 (setq cpltxt (or description link)))
8739 ((eq major-mode 'image-mode)
8740 (setq cpltxt (concat "file:"
8741 (abbreviate-file-name buffer-file-name))
8742 link (org-make-link cpltxt))
8743 (org-store-link-props :type "image" :file buffer-file-name))
8745 ((eq major-mode 'dired-mode)
8746 ;; link to the file in the current line
8747 (let ((file (dired-get-filename nil t)))
8748 (setq file (if file
8749 (abbreviate-file-name
8750 (expand-file-name (dired-get-filename nil t)))
8751 ;; otherwise, no file so use current directory.
8752 default-directory))
8753 (setq cpltxt (concat "file:" file)
8754 link (org-make-link cpltxt))))
8756 ((and (buffer-file-name (buffer-base-buffer)) (eq major-mode 'org-mode))
8757 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
8758 (cond
8759 ((org-in-regexp "<<\\(.*?\\)>>")
8760 (setq cpltxt
8761 (concat "file:"
8762 (abbreviate-file-name
8763 (buffer-file-name (buffer-base-buffer)))
8764 "::" (match-string 1))
8765 link (org-make-link cpltxt)))
8766 ((and (featurep 'org-id)
8767 (or (eq org-link-to-org-use-id t)
8768 (and (eq org-link-to-org-use-id 'create-if-interactive)
8769 (org-called-interactively-p 'any))
8770 (and (eq org-link-to-org-use-id
8771 'create-if-interactive-and-no-custom-id)
8772 (org-called-interactively-p 'any)
8773 (not custom-id))
8774 (and org-link-to-org-use-id
8775 (org-entry-get nil "ID"))))
8776 ;; We can make a link using the ID.
8777 (setq link (condition-case nil
8778 (prog1 (org-id-store-link)
8779 (setq desc (plist-get org-store-link-plist
8780 :description)))
8781 (error
8782 ;; probably before first headline, link to file only
8783 (concat "file:"
8784 (abbreviate-file-name
8785 (buffer-file-name (buffer-base-buffer))))))))
8787 ;; Just link to current headline
8788 (setq cpltxt (concat "file:"
8789 (abbreviate-file-name
8790 (buffer-file-name (buffer-base-buffer)))))
8791 ;; Add a context search string
8792 (when (org-xor org-context-in-file-links arg)
8793 (setq txt (cond
8794 ((org-at-heading-p) nil)
8795 ((org-region-active-p)
8796 (buffer-substring (region-beginning) (region-end)))
8797 (t nil)))
8798 (when (or (null txt) (string-match "\\S-" txt))
8799 (setq cpltxt
8800 (concat cpltxt "::"
8801 (condition-case nil
8802 (org-make-org-heading-search-string txt)
8803 (error "")))
8804 desc (or (nth 4 (ignore-errors
8805 (org-heading-components))) "NONE"))))
8806 (if (string-match "::\\'" cpltxt)
8807 (setq cpltxt (substring cpltxt 0 -2)))
8808 (setq link (org-make-link cpltxt)))))
8810 ((buffer-file-name (buffer-base-buffer))
8811 ;; Just link to this file here.
8812 (setq cpltxt (concat "file:"
8813 (abbreviate-file-name
8814 (buffer-file-name (buffer-base-buffer)))))
8815 ;; Add a context string
8816 (when (org-xor org-context-in-file-links arg)
8817 (setq txt (if (org-region-active-p)
8818 (buffer-substring (region-beginning) (region-end))
8819 (buffer-substring (point-at-bol) (point-at-eol))))
8820 ;; Only use search option if there is some text.
8821 (when (string-match "\\S-" txt)
8822 (setq cpltxt
8823 (concat cpltxt "::" (org-make-org-heading-search-string txt))
8824 desc "NONE")))
8825 (setq link (org-make-link cpltxt)))
8827 ((org-called-interactively-p 'interactive)
8828 (error "Cannot link to a buffer which is not visiting a file"))
8830 (t (setq link nil)))
8832 (if (consp link) (setq cpltxt (car link) link (cdr link)))
8833 (setq link (or link cpltxt)
8834 desc (or desc cpltxt))
8835 (if (equal desc "NONE") (setq desc nil))
8837 (if (and (or (org-called-interactively-p 'any) executing-kbd-macro) link)
8838 (progn
8839 (setq org-stored-links
8840 (cons (list link desc) org-stored-links))
8841 (message "Stored: %s" (or desc link))
8842 (when custom-id
8843 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
8844 "::#" custom-id))
8845 (setq org-stored-links
8846 (cons (list link desc) org-stored-links))))
8847 (or agenda-link (and link (org-make-link-string link desc)))))))
8849 (defun org-store-link-props (&rest plist)
8850 "Store link properties, extract names and addresses."
8851 (let (x adr)
8852 (when (setq x (plist-get plist :from))
8853 (setq adr (mail-extract-address-components x))
8854 (setq plist (plist-put plist :fromname (car adr)))
8855 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
8856 (when (setq x (plist-get plist :to))
8857 (setq adr (mail-extract-address-components x))
8858 (setq plist (plist-put plist :toname (car adr)))
8859 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
8860 (let ((from (plist-get plist :from))
8861 (to (plist-get plist :to)))
8862 (when (and from to org-from-is-user-regexp)
8863 (setq plist
8864 (plist-put plist :fromto
8865 (if (string-match org-from-is-user-regexp from)
8866 (concat "to %t")
8867 (concat "from %f"))))))
8868 (setq org-store-link-plist plist))
8870 (defun org-add-link-props (&rest plist)
8871 "Add these properties to the link property list."
8872 (let (key value)
8873 (while plist
8874 (setq key (pop plist) value (pop plist))
8875 (setq org-store-link-plist
8876 (plist-put org-store-link-plist key value)))))
8878 (defun org-email-link-description (&optional fmt)
8879 "Return the description part of an email link.
8880 This takes information from `org-store-link-plist' and formats it
8881 according to FMT (default from `org-email-link-description-format')."
8882 (setq fmt (or fmt org-email-link-description-format))
8883 (let* ((p org-store-link-plist)
8884 (to (plist-get p :toaddress))
8885 (from (plist-get p :fromaddress))
8886 (table
8887 (list
8888 (cons "%c" (plist-get p :fromto))
8889 (cons "%F" (plist-get p :from))
8890 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
8891 (cons "%T" (plist-get p :to))
8892 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
8893 (cons "%s" (plist-get p :subject))
8894 (cons "%d" (plist-get p :date))
8895 (cons "%m" (plist-get p :message-id)))))
8896 (when (string-match "%c" fmt)
8897 ;; Check if the user wrote this message
8898 (if (and org-from-is-user-regexp from to
8899 (save-match-data (string-match org-from-is-user-regexp from)))
8900 (setq fmt (replace-match "to %t" t t fmt))
8901 (setq fmt (replace-match "from %f" t t fmt))))
8902 (org-replace-escapes fmt table)))
8904 (defun org-make-org-heading-search-string (&optional string heading)
8905 "Make search string for STRING or current headline."
8906 (interactive)
8907 (let ((s (or string (org-get-heading)))
8908 (lines org-context-in-file-links))
8909 (unless (and string (not heading))
8910 ;; We are using a headline, clean up garbage in there.
8911 (if (string-match org-todo-regexp s)
8912 (setq s (replace-match "" t t s)))
8913 (if (string-match (org-re ":[[:alnum:]_@#%:]+:[ \t]*$") s)
8914 (setq s (replace-match "" t t s)))
8915 (setq s (org-trim s))
8916 (if (string-match (concat "^\\(" org-quote-string "\\|"
8917 org-comment-string "\\)") s)
8918 (setq s (replace-match "" t t s)))
8919 (while (string-match org-ts-regexp s)
8920 (setq s (replace-match "" t t s))))
8921 (or string (setq s (concat "*" s))) ; Add * for headlines
8922 (when (and string (integerp lines) (> lines 0))
8923 (let ((slines (org-split-string s "\n")))
8924 (when (< lines (length slines))
8925 (setq s (mapconcat
8926 'identity
8927 (reverse (nthcdr (- (length slines) lines)
8928 (reverse slines))) "\n")))))
8929 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
8931 (defun org-make-link (&rest strings)
8932 "Concatenate STRINGS."
8933 (apply 'concat strings))
8935 (defun org-make-link-string (link &optional description)
8936 "Make a link with brackets, consisting of LINK and DESCRIPTION."
8937 (unless (string-match "\\S-" link)
8938 (error "Empty link"))
8939 (when (and description
8940 (stringp description)
8941 (not (string-match "\\S-" description)))
8942 (setq description nil))
8943 (when (stringp description)
8944 ;; Remove brackets from the description, they are fatal.
8945 (while (string-match "\\[" description)
8946 (setq description (replace-match "{" t t description)))
8947 (while (string-match "\\]" description)
8948 (setq description (replace-match "}" t t description))))
8949 (when (equal link description)
8950 ;; No description needed, it is identical
8951 (setq description nil))
8952 (when (and (not description)
8953 (not (string-match (org-image-file-name-regexp) link))
8954 (not (equal link (org-link-escape link))))
8955 (setq description (org-extract-attributes link)))
8956 (setq link
8957 (cond ((string-match (org-image-file-name-regexp) link) link)
8958 ((string-match org-link-types-re link)
8959 (concat (match-string 1 link)
8960 (org-link-escape (substring link (match-end 1)))))
8961 (t (org-link-escape link))))
8962 (concat "[[" link "]"
8963 (if description (concat "[" description "]") "")
8964 "]"))
8966 (defconst org-link-escape-chars
8967 '(?\ ?\[ ?\] ?\; ?\= ?\+)
8968 "List of characters that should be escaped in link.
8969 This is the list that is used for internal purposes.")
8971 (defvar org-url-encoding-use-url-hexify nil)
8973 (defconst org-link-escape-chars-browser
8974 '(?\ )
8975 "List of escapes for characters that are problematic in links.
8976 This is the list that is used before handing over to the browser.")
8978 (defun org-link-escape (text &optional table merge)
8979 "Return percent escaped representation of TEXT.
8980 TEXT is a string with the text to escape.
8981 Optional argument TABLE is a list with characters that should be
8982 escaped. When nil, `org-link-escape-chars' is used.
8983 If optional argument MERGE is set, merge TABLE into
8984 `org-link-escape-chars'."
8985 (if (and org-url-encoding-use-url-hexify (not table))
8986 (url-hexify-string text)
8987 (cond
8988 ((and table merge)
8989 (mapc (lambda (defchr)
8990 (unless (member defchr table)
8991 (setq table (cons defchr table)))) org-link-escape-chars))
8992 ((null table)
8993 (setq table org-link-escape-chars)))
8994 (mapconcat
8995 (lambda (char)
8996 (if (or (member char table)
8997 (< char 32) (= char 37) (> char 126))
8998 (mapconcat (lambda (sequence-element)
8999 (format "%%%.2X" sequence-element))
9000 (or (encode-coding-char char 'utf-8)
9001 (error "Unable to percent escape character: %s"
9002 (char-to-string char))) "")
9003 (char-to-string char))) text "")))
9005 (defun org-link-unescape (str)
9006 "Unhex hexified Unicode strings as returned from the JavaScript function
9007 encodeURIComponent. E.g. `%C3%B6' is the german Umlaut `ö'."
9008 (unless (and (null str) (string= "" str))
9009 (let ((pos 0) (case-fold-search t) unhexed)
9010 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9011 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9012 (setq str (replace-match unhexed t t str))
9013 (setq pos (+ pos (length unhexed))))))
9014 str)
9016 (defun org-link-unescape-compound (hex)
9017 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German Umlaut `ö'.
9018 Note: this function also decodes single byte encodings like
9019 `%E1' (\"á\") if not followed by another `%[A-F0-9]{2}' group."
9020 (save-match-data
9021 (let* ((bytes (cdr (split-string hex "%")))
9022 (ret "")
9023 (eat 0)
9024 (sum 0))
9025 (while bytes
9026 (let* ((val (string-to-number (pop bytes) 16))
9027 (shift-xor
9028 (if (= 0 eat)
9029 (cond
9030 ((>= val 252) (cons 6 252))
9031 ((>= val 248) (cons 5 248))
9032 ((>= val 240) (cons 4 240))
9033 ((>= val 224) (cons 3 224))
9034 ((>= val 192) (cons 2 192))
9035 (t (cons 0 0)))
9036 (cons 6 128))))
9037 (if (>= val 192) (setq eat (car shift-xor)))
9038 (setq val (logxor val (cdr shift-xor)))
9039 (setq sum (+ (lsh sum (car shift-xor)) val))
9040 (if (> eat 0) (setq eat (- eat 1)))
9041 (cond
9042 ((= 0 eat) ;multi byte
9043 (setq ret (concat ret (org-char-to-string sum)))
9044 (setq sum 0))
9045 ((not bytes) ; single byte(s)
9046 (setq ret (org-link-unescape-single-byte-sequence hex))))
9047 )) ;; end (while bytes
9048 ret )))
9050 (defun org-link-unescape-single-byte-sequence (hex)
9051 "Unhexify hex-encoded single byte character sequences."
9052 (mapconcat (lambda (byte)
9053 (char-to-string (string-to-number byte 16)))
9054 (cdr (split-string hex "%")) ""))
9056 (defun org-xor (a b)
9057 "Exclusive or."
9058 (if a (not b) b))
9060 (defun org-fixup-message-id-for-http (s)
9061 "Replace special characters in a message id, so it can be used in an http query."
9062 (when (string-match "%" s)
9063 (setq s (mapconcat (lambda (c)
9064 (if (eq c ?%)
9065 "%25"
9066 (char-to-string c)))
9067 s "")))
9068 (while (string-match "<" s)
9069 (setq s (replace-match "%3C" t t s)))
9070 (while (string-match ">" s)
9071 (setq s (replace-match "%3E" t t s)))
9072 (while (string-match "@" s)
9073 (setq s (replace-match "%40" t t s)))
9076 ;;;###autoload
9077 (defun org-insert-link-global ()
9078 "Insert a link like Org-mode does.
9079 This command can be called in any mode to insert a link in Org-mode syntax."
9080 (interactive)
9081 (org-load-modules-maybe)
9082 (org-run-like-in-org-mode 'org-insert-link))
9084 (defun org-insert-link (&optional complete-file link-location default-description)
9085 "Insert a link. At the prompt, enter the link.
9087 Completion can be used to insert any of the link protocol prefixes like
9088 http or ftp in use.
9090 The history can be used to select a link previously stored with
9091 `org-store-link'. When the empty string is entered (i.e. if you just
9092 press RET at the prompt), the link defaults to the most recently
9093 stored link. As SPC triggers completion in the minibuffer, you need to
9094 use M-SPC or C-q SPC to force the insertion of a space character.
9096 You will also be prompted for a description, and if one is given, it will
9097 be displayed in the buffer instead of the link.
9099 If there is already a link at point, this command will allow you to edit link
9100 and description parts.
9102 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9103 be selected using completion. The path to the file will be relative to the
9104 current directory if the file is in the current directory or a subdirectory.
9105 Otherwise, the link will be the absolute path as completed in the minibuffer
9106 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9107 option `org-link-file-path-type'.
9109 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9110 the current directory or below.
9112 With three \\[universal-argument] prefixes, negate the meaning of
9113 `org-keep-stored-link-after-insertion'.
9115 If `org-make-link-description-function' is non-nil, this function will be
9116 called with the link target, and the result will be the default
9117 link description.
9119 If the LINK-LOCATION parameter is non-nil, this value will be
9120 used as the link location instead of reading one interactively.
9122 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9123 be used as the default description."
9124 (interactive "P")
9125 (let* ((wcf (current-window-configuration))
9126 (region (if (org-region-active-p)
9127 (buffer-substring (region-beginning) (region-end))))
9128 (remove (and region (list (region-beginning) (region-end))))
9129 (desc region)
9130 tmphist ; byte-compile incorrectly complains about this
9131 (link link-location)
9132 entry file all-prefixes)
9133 (cond
9134 (link-location) ; specified by arg, just use it.
9135 ((org-in-regexp org-bracket-link-regexp 1)
9136 ;; We do have a link at point, and we are going to edit it.
9137 (setq remove (list (match-beginning 0) (match-end 0)))
9138 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9139 (setq link (read-string "Link: "
9140 (org-link-unescape
9141 (org-match-string-no-properties 1)))))
9142 ((or (org-in-regexp org-angle-link-re)
9143 (org-in-regexp org-plain-link-re))
9144 ;; Convert to bracket link
9145 (setq remove (list (match-beginning 0) (match-end 0))
9146 link (read-string "Link: "
9147 (org-remove-angle-brackets (match-string 0)))))
9148 ((member complete-file '((4) (16)))
9149 ;; Completing read for file names.
9150 (setq link (org-file-complete-link complete-file)))
9152 ;; Read link, with completion for stored links.
9153 (with-output-to-temp-buffer "*Org Links*"
9154 (princ "Insert a link.
9155 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9156 (when org-stored-links
9157 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9158 (princ (mapconcat
9159 (lambda (x)
9160 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
9161 (reverse org-stored-links) "\n"))))
9162 (let ((cw (selected-window)))
9163 (select-window (get-buffer-window "*Org Links*" 'visible))
9164 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9165 (unless (pos-visible-in-window-p (point-max))
9166 (org-fit-window-to-buffer))
9167 (and (window-live-p cw) (select-window cw)))
9168 ;; Fake a link history, containing the stored links.
9169 (setq tmphist (append (mapcar 'car org-stored-links)
9170 org-insert-link-history))
9171 (setq all-prefixes (append (mapcar 'car org-link-abbrev-alist-local)
9172 (mapcar 'car org-link-abbrev-alist)
9173 org-link-types))
9174 (unwind-protect
9175 (progn
9176 (setq link
9177 (let ((org-completion-use-ido nil)
9178 (org-completion-use-iswitchb nil))
9179 (org-completing-read
9180 "Link: "
9181 (append
9182 (mapcar (lambda (x) (list (concat x ":")))
9183 all-prefixes)
9184 (mapcar 'car org-stored-links))
9185 nil nil nil
9186 'tmphist
9187 (car (car org-stored-links)))))
9188 (if (not (string-match "\\S-" link))
9189 (error "No link selected"))
9190 (if (or (member link all-prefixes)
9191 (and (equal ":" (substring link -1))
9192 (member (substring link 0 -1) all-prefixes)
9193 (setq link (substring link 0 -1))))
9194 (setq link (org-link-try-special-completion link))))
9195 (set-window-configuration wcf)
9196 (kill-buffer "*Org Links*"))
9197 (setq entry (assoc link org-stored-links))
9198 (or entry (push link org-insert-link-history))
9199 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9200 (not org-keep-stored-link-after-insertion))
9201 (setq org-stored-links (delq (assoc link org-stored-links)
9202 org-stored-links)))
9203 (setq desc (or desc (nth 1 entry)))))
9205 (if (string-match org-plain-link-re link)
9206 ;; URL-like link, normalize the use of angular brackets.
9207 (setq link (org-make-link (org-remove-angle-brackets link))))
9209 ;; Check if we are linking to the current file with a search option
9210 ;; If yes, simplify the link by using only the search option.
9211 (when (and buffer-file-name
9212 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
9213 (let* ((path (match-string 1 link))
9214 (case-fold-search nil)
9215 (search (match-string 2 link)))
9216 (save-match-data
9217 (if (equal (file-truename buffer-file-name) (file-truename path))
9218 ;; We are linking to this same file, with a search option
9219 (setq link search)))))
9221 ;; Check if we can/should use a relative path. If yes, simplify the link
9222 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
9223 (let* ((type (match-string 1 link))
9224 (path (match-string 2 link))
9225 (origpath path)
9226 (case-fold-search nil))
9227 (cond
9228 ((or (eq org-link-file-path-type 'absolute)
9229 (equal complete-file '(16)))
9230 (setq path (abbreviate-file-name (expand-file-name path))))
9231 ((eq org-link-file-path-type 'noabbrev)
9232 (setq path (expand-file-name path)))
9233 ((eq org-link-file-path-type 'relative)
9234 (setq path (file-relative-name path)))
9236 (save-match-data
9237 (if (string-match (concat "^" (regexp-quote
9238 (expand-file-name
9239 (file-name-as-directory
9240 default-directory))))
9241 (expand-file-name path))
9242 ;; We are linking a file with relative path name.
9243 (setq path (substring (expand-file-name path)
9244 (match-end 0)))
9245 (setq path (abbreviate-file-name (expand-file-name path)))))))
9246 (setq link (concat type path))
9247 (if (equal desc origpath)
9248 (setq desc path))))
9250 (if org-make-link-description-function
9251 (setq desc (funcall org-make-link-description-function link desc))
9252 (if default-description (setq desc default-description)))
9254 (setq desc (read-string "Description: " desc))
9255 (unless (string-match "\\S-" desc) (setq desc nil))
9256 (if remove (apply 'delete-region remove))
9257 (insert (org-make-link-string link desc))))
9259 (defun org-link-try-special-completion (type)
9260 "If there is completion support for link type TYPE, offer it."
9261 (let ((fun (intern (concat "org-" type "-complete-link"))))
9262 (if (functionp fun)
9263 (funcall fun)
9264 (read-string "Link (no completion support): " (concat type ":")))))
9266 (defun org-file-complete-link (&optional arg)
9267 "Create a file link using completion."
9268 (let (file link)
9269 (setq file (read-file-name "File: "))
9270 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9271 (pwd1 (file-name-as-directory (abbreviate-file-name
9272 (expand-file-name ".")))))
9273 (cond
9274 ((equal arg '(16))
9275 (setq link (org-make-link
9276 "file:"
9277 (abbreviate-file-name (expand-file-name file)))))
9278 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9279 (setq link (org-make-link "file:" (match-string 1 file))))
9280 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9281 (expand-file-name file))
9282 (setq link (org-make-link
9283 "file:" (match-string 1 (expand-file-name file)))))
9284 (t (setq link (org-make-link "file:" file)))))
9285 link))
9287 (defun org-completing-read (&rest args)
9288 "Completing-read with SPACE being a normal character."
9289 (let ((enable-recursive-minibuffers t)
9290 (minibuffer-local-completion-map
9291 (copy-keymap minibuffer-local-completion-map)))
9292 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
9293 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
9294 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
9295 (apply 'org-icompleting-read args)))
9297 (defun org-completing-read-no-i (&rest args)
9298 (let (org-completion-use-ido org-completion-use-iswitchb)
9299 (apply 'org-completing-read args)))
9301 (defun org-iswitchb-completing-read (prompt choices &rest args)
9302 "Use iswitch as a completing-read replacement to choose from choices.
9303 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
9304 from."
9305 (let* ((iswitchb-use-virtual-buffers nil)
9306 (iswitchb-make-buflist-hook
9307 (lambda ()
9308 (setq iswitchb-temp-buflist choices))))
9309 (iswitchb-read-buffer prompt)))
9311 (defun org-icompleting-read (&rest args)
9312 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
9313 (org-without-partial-completion
9314 (if (and org-completion-use-ido
9315 (fboundp 'ido-completing-read)
9316 (boundp 'ido-mode) ido-mode
9317 (listp (second args)))
9318 (let ((ido-enter-matching-directory nil))
9319 (apply 'ido-completing-read (concat (car args))
9320 (if (consp (car (nth 1 args)))
9321 (mapcar 'car (nth 1 args))
9322 (nth 1 args))
9323 (cddr args)))
9324 (if (and org-completion-use-iswitchb
9325 (boundp 'iswitchb-mode) iswitchb-mode
9326 (listp (second args)))
9327 (apply 'org-iswitchb-completing-read (concat (car args))
9328 (if (consp (car (nth 1 args)))
9329 (mapcar 'car (nth 1 args))
9330 (nth 1 args))
9331 (cddr args))
9332 (apply 'completing-read args)))))
9334 (defun org-extract-attributes (s)
9335 "Extract the attributes cookie from a string and set as text property."
9336 (let (a attr (start 0) key value)
9337 (save-match-data
9338 (when (string-match "{{\\([^}]+\\)}}$" s)
9339 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
9340 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
9341 (setq key (match-string 1 a) value (match-string 2 a)
9342 start (match-end 0)
9343 attr (plist-put attr (intern key) value))))
9344 (org-add-props s nil 'org-attr attr))
9347 (defun org-extract-attributes-from-string (tag)
9348 (let (key value attr)
9349 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
9350 (setq key (match-string 1 tag) value (match-string 2 tag)
9351 tag (replace-match "" t t tag)
9352 attr (plist-put attr (intern key) value)))
9353 (cons tag attr)))
9355 (defun org-attributes-to-string (plist)
9356 "Format a property list into an HTML attribute list."
9357 (let ((s "") key value)
9358 (while plist
9359 (setq key (pop plist) value (pop plist))
9360 (and value
9361 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
9364 ;;; Opening/following a link
9366 (defvar org-link-search-failed nil)
9368 (defvar org-open-link-functions nil
9369 "Hook for functions finding a plain text link.
9370 These functions must take a single argument, the link content.
9371 They will be called for links that look like [[link text][description]]
9372 when LINK TEXT does not have a protocol like \"http:\" and does not look
9373 like a filename (e.g. \"./blue.png\").
9375 These functions will be called *before* Org attempts to resolve the
9376 link by doing text searches in the current buffer - so if you want a
9377 link \"[[target]]\" to still find \"<<target>>\", your function should
9378 handle this as a special case.
9380 When the function does handle the link, it must return a non-nil value.
9381 If it decides that it is not responsible for this link, it must return
9382 nil to indicate that that Org-mode can continue with other options
9383 like exact and fuzzy text search.")
9385 (defun org-next-link ()
9386 "Move forward to the next link.
9387 If the link is in hidden text, expose it."
9388 (interactive)
9389 (when (and org-link-search-failed (eq this-command last-command))
9390 (goto-char (point-min))
9391 (message "Link search wrapped back to beginning of buffer"))
9392 (setq org-link-search-failed nil)
9393 (let* ((pos (point))
9394 (ct (org-context))
9395 (a (assoc :link ct)))
9396 (if a (goto-char (nth 2 a)))
9397 (if (re-search-forward org-any-link-re nil t)
9398 (progn
9399 (goto-char (match-beginning 0))
9400 (if (outline-invisible-p) (org-show-context)))
9401 (goto-char pos)
9402 (setq org-link-search-failed t)
9403 (error "No further link found"))))
9405 (defun org-previous-link ()
9406 "Move backward to the previous link.
9407 If the link is in hidden text, expose it."
9408 (interactive)
9409 (when (and org-link-search-failed (eq this-command last-command))
9410 (goto-char (point-max))
9411 (message "Link search wrapped back to end of buffer"))
9412 (setq org-link-search-failed nil)
9413 (let* ((pos (point))
9414 (ct (org-context))
9415 (a (assoc :link ct)))
9416 (if a (goto-char (nth 1 a)))
9417 (if (re-search-backward org-any-link-re nil t)
9418 (progn
9419 (goto-char (match-beginning 0))
9420 (if (outline-invisible-p) (org-show-context)))
9421 (goto-char pos)
9422 (setq org-link-search-failed t)
9423 (error "No further link found"))))
9425 (defun org-translate-link (s)
9426 "Translate a link string if a translation function has been defined."
9427 (if (and org-link-translation-function
9428 (fboundp org-link-translation-function)
9429 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
9430 (progn
9431 (setq s (funcall org-link-translation-function
9432 (match-string 1) (match-string 2)))
9433 (concat (car s) ":" (cdr s)))
9436 (defun org-translate-link-from-planner (type path)
9437 "Translate a link from Emacs Planner syntax so that Org can follow it.
9438 This is still an experimental function, your mileage may vary."
9439 (cond
9440 ((member type '("http" "https" "news" "ftp"))
9441 ;; standard Internet links are the same.
9442 nil)
9443 ((and (equal type "irc") (string-match "^//" path))
9444 ;; Planner has two / at the beginning of an irc link, we have 1.
9445 ;; We should have zero, actually....
9446 (setq path (substring path 1)))
9447 ((and (equal type "lisp") (string-match "^/" path))
9448 ;; Planner has a slash, we do not.
9449 (setq type "elisp" path (substring path 1)))
9450 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9451 ;; A typical message link. Planner has the id after the final slash,
9452 ;; we separate it with a hash mark
9453 (setq path (concat (match-string 1 path) "#"
9454 (org-remove-angle-brackets (match-string 2 path)))))
9456 (cons type path))
9458 (defun org-find-file-at-mouse (ev)
9459 "Open file link or URL at mouse."
9460 (interactive "e")
9461 (mouse-set-point ev)
9462 (org-open-at-point 'in-emacs))
9464 (defun org-open-at-mouse (ev)
9465 "Open file link or URL at mouse.
9466 See the docstring of `org-open-file' for details."
9467 (interactive "e")
9468 (mouse-set-point ev)
9469 (if (eq major-mode 'org-agenda-mode)
9470 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
9471 (org-open-at-point))
9473 (defvar org-window-config-before-follow-link nil
9474 "The window configuration before following a link.
9475 This is saved in case the need arises to restore it.")
9477 (defvar org-open-link-marker (make-marker)
9478 "Marker pointing to the location where `org-open-at-point; was called.")
9480 ;;;###autoload
9481 (defun org-open-at-point-global ()
9482 "Follow a link like Org-mode does.
9483 This command can be called in any mode to follow a link that has
9484 Org-mode syntax."
9485 (interactive)
9486 (org-run-like-in-org-mode 'org-open-at-point))
9488 ;;;###autoload
9489 (defun org-open-link-from-string (s &optional arg reference-buffer)
9490 "Open a link in the string S, as if it was in Org-mode."
9491 (interactive "sLink: \nP")
9492 (let ((reference-buffer (or reference-buffer (current-buffer))))
9493 (with-temp-buffer
9494 (let ((org-inhibit-startup (not reference-buffer)))
9495 (org-mode)
9496 (insert s)
9497 (goto-char (point-min))
9498 (when reference-buffer
9499 (setq org-link-abbrev-alist-local
9500 (with-current-buffer reference-buffer
9501 org-link-abbrev-alist-local)))
9502 (org-open-at-point arg reference-buffer)))))
9504 (defvar org-open-at-point-functions nil
9505 "Hook that is run when following a link at point.
9507 Functions in this hook must return t if they identify and follow
9508 a link at point. If they don't find anything interesting at point,
9509 they must return nil.")
9511 (defun org-open-at-point (&optional arg reference-buffer)
9512 "Open link at or after point.
9513 If there is no link at point, this function will search forward up to
9514 the end of the current line.
9515 Normally, files will be opened by an appropriate application. If the
9516 optional prefix argument ARG is non-nil, Emacs will visit the file.
9517 With a double prefix argument, try to open outside of Emacs, in the
9518 application the system uses for this file type."
9519 (interactive "P")
9520 ;; if in a code block, then open the block's results
9521 (unless (call-interactively #'org-babel-open-src-block-result)
9522 (org-load-modules-maybe)
9523 (move-marker org-open-link-marker (point))
9524 (setq org-window-config-before-follow-link (current-window-configuration))
9525 (org-remove-occur-highlights nil nil t)
9526 (cond
9527 ((and (org-at-heading-p)
9528 (not (org-in-regexp
9529 (concat org-plain-link-re "\\|"
9530 org-bracket-link-regexp "\\|"
9531 org-angle-link-re "\\|"
9532 "[ \t]:[^ \t\n]+:[ \t]*$")))
9533 (not (get-text-property (point) 'org-linked-text)))
9534 (or (org-offer-links-in-entry arg)
9535 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
9536 ((run-hook-with-args-until-success 'org-open-at-point-functions))
9537 ((org-at-timestamp-p t) (org-follow-timestamp-link))
9538 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
9539 (not (org-in-regexp org-bracket-link-regexp)))
9540 (org-footnote-action))
9542 (let (type path link line search (pos (point)))
9543 (catch 'match
9544 (save-excursion
9545 (skip-chars-forward "^]\n\r")
9546 (when (org-in-regexp org-bracket-link-regexp 1)
9547 (setq link (org-extract-attributes
9548 (org-link-unescape (org-match-string-no-properties 1))))
9549 (while (string-match " *\n *" link)
9550 (setq link (replace-match " " t t link)))
9551 (setq link (org-link-expand-abbrev link))
9552 (cond
9553 ((or (file-name-absolute-p link)
9554 (string-match "^\\.\\.?/" link))
9555 (setq type "file" path link))
9556 ((string-match org-link-re-with-space3 link)
9557 (setq type (match-string 1 link) path (match-string 2 link)))
9558 (t (setq type "thisfile" path link)))
9559 (throw 'match t)))
9561 (when (get-text-property (point) 'org-linked-text)
9562 (setq type "thisfile"
9563 pos (if (get-text-property (1+ (point)) 'org-linked-text)
9564 (1+ (point)) (point))
9565 path (buffer-substring
9566 (or (previous-single-property-change pos 'org-linked-text)
9567 (point-min))
9568 (or (next-single-property-change pos 'org-linked-text)
9569 (point-max))))
9570 (throw 'match t))
9572 (save-excursion
9573 (when (or (org-in-regexp org-angle-link-re)
9574 (org-in-regexp org-plain-link-re))
9575 (setq type (match-string 1)
9576 path (org-link-unescape (match-string 2)))
9577 (throw 'match t)))
9578 (save-excursion
9579 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
9580 (setq type "tags"
9581 path (match-string 1))
9582 (while (string-match ":" path)
9583 (setq path (replace-match "+" t t path)))
9584 (throw 'match t)))
9585 (when (org-in-regexp "<\\([^><\n]+\\)>")
9586 (setq type "tree-match"
9587 path (match-string 1))
9588 (throw 'match t)))
9589 (unless path
9590 (error "No link found"))
9592 ;; switch back to reference buffer
9593 ;; needed when if called in a temporary buffer through
9594 ;; org-open-link-from-string
9595 (with-current-buffer (or reference-buffer (current-buffer))
9597 ;; Remove any trailing spaces in path
9598 (if (string-match " +\\'" path)
9599 (setq path (replace-match "" t t path)))
9600 (if (and org-link-translation-function
9601 (fboundp org-link-translation-function))
9602 ;; Check if we need to translate the link
9603 (let ((tmp (funcall org-link-translation-function type path)))
9604 (setq type (car tmp) path (cdr tmp))))
9606 (cond
9608 ((assoc type org-link-protocols)
9609 (funcall (nth 1 (assoc type org-link-protocols)) path))
9611 ((equal type "mailto")
9612 (let ((cmd (car org-link-mailto-program))
9613 (args (cdr org-link-mailto-program)) args1
9614 (address path) (subject "") a)
9615 (if (string-match "\\(.*\\)::\\(.*\\)" path)
9616 (setq address (match-string 1 path)
9617 subject (org-link-escape (match-string 2 path))))
9618 (while args
9619 (cond
9620 ((not (stringp (car args))) (push (pop args) args1))
9621 (t (setq a (pop args))
9622 (if (string-match "%a" a)
9623 (setq a (replace-match address t t a)))
9624 (if (string-match "%s" a)
9625 (setq a (replace-match subject t t a)))
9626 (push a args1))))
9627 (apply cmd (nreverse args1))))
9629 ((member type '("http" "https" "ftp" "news"))
9630 (browse-url (concat type ":" (if (org-string-match-p "[[:nonascii:] ]" path)
9631 (org-link-escape
9632 path org-link-escape-chars-browser)
9633 path))))
9635 ((string= type "doi")
9636 (browse-url (concat "http://dx.doi.org/" (if (org-string-match-p "[[:nonascii:] ]" path)
9637 (org-link-escape
9638 path org-link-escape-chars-browser)
9639 path))))
9641 ((member type '("message"))
9642 (browse-url (concat type ":" path)))
9644 ((string= type "tags")
9645 (org-tags-view arg path))
9647 ((string= type "tree-match")
9648 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
9650 ((string= type "file")
9651 (if (string-match "::\\([0-9]+\\)\\'" path)
9652 (setq line (string-to-number (match-string 1 path))
9653 path (substring path 0 (match-beginning 0)))
9654 (if (string-match "::\\(.+\\)\\'" path)
9655 (setq search (match-string 1 path)
9656 path (substring path 0 (match-beginning 0)))))
9657 (if (string-match "[*?{]" (file-name-nondirectory path))
9658 (dired path)
9659 (org-open-file path arg line search)))
9661 ((string= type "shell")
9662 (let ((cmd path))
9663 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
9664 (string-match org-confirm-shell-link-not-regexp cmd))
9665 (not org-confirm-shell-link-function)
9666 (funcall org-confirm-shell-link-function
9667 (format "Execute \"%s\" in shell? "
9668 (org-add-props cmd nil
9669 'face 'org-warning))))
9670 (progn
9671 (message "Executing %s" cmd)
9672 (shell-command cmd))
9673 (error "Abort"))))
9675 ((string= type "elisp")
9676 (let ((cmd path))
9677 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
9678 (string-match org-confirm-elisp-link-not-regexp cmd))
9679 (not org-confirm-elisp-link-function)
9680 (funcall org-confirm-elisp-link-function
9681 (format "Execute \"%s\" as elisp? "
9682 (org-add-props cmd nil
9683 'face 'org-warning))))
9684 (message "%s => %s" cmd
9685 (if (equal (string-to-char cmd) ?\()
9686 (eval (read cmd))
9687 (call-interactively (read cmd))))
9688 (error "Abort"))))
9690 ((and (string= type "thisfile")
9691 (run-hook-with-args-until-success
9692 'org-open-link-functions path)))
9694 ((string= type "thisfile")
9695 (if arg
9696 (switch-to-buffer-other-window
9697 (org-get-buffer-for-internal-link (current-buffer)))
9698 (org-mark-ring-push))
9699 (let ((cmd `(org-link-search
9700 ,path
9701 ,(cond ((equal arg '(4)) ''occur)
9702 ((equal arg '(16)) ''org-occur)
9703 (t nil))
9704 ,pos)))
9705 (condition-case nil (let ((org-link-search-inhibit-query t))
9706 (eval cmd))
9707 (error (progn (widen) (eval cmd))))))
9710 (browse-url-at-point)))))))
9711 (move-marker org-open-link-marker nil)
9712 (run-hook-with-args 'org-follow-link-hook)))
9714 (defun org-offer-links-in-entry (&optional nth zero)
9715 "Offer links in the current entry and follow the selected link.
9716 If there is only one link, follow it immediately as well.
9717 If NTH is an integer, immediately pick the NTH link found.
9718 If ZERO is a string, check also this string for a link, and if
9719 there is one, offer it as link number zero."
9720 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
9721 "\\(" org-angle-link-re "\\)\\|"
9722 "\\(" org-plain-link-re "\\)"))
9723 (cnt ?0)
9724 (in-emacs (if (integerp nth) nil nth))
9725 have-zero end links link c)
9726 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
9727 (push (match-string 0 zero) links)
9728 (setq cnt (1- cnt) have-zero t))
9729 (save-excursion
9730 (org-back-to-heading t)
9731 (setq end (save-excursion (outline-next-heading) (point)))
9732 (while (re-search-forward re end t)
9733 (push (match-string 0) links))
9734 (setq links (org-uniquify (reverse links))))
9736 (cond
9737 ((null links)
9738 (message "No links"))
9739 ((equal (length links) 1)
9740 (setq link (list (car links))))
9741 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
9742 (setq link (list (nth (if have-zero nth (1- nth)) links))))
9743 (t ; we have to select a link
9744 (save-excursion
9745 (save-window-excursion
9746 (delete-other-windows)
9747 (with-output-to-temp-buffer "*Select Link*"
9748 (mapc (lambda (l)
9749 (if (not (string-match org-bracket-link-regexp l))
9750 (princ (format "[%c] %s\n" (incf cnt)
9751 (org-remove-angle-brackets l)))
9752 (if (match-end 3)
9753 (princ (format "[%c] %s (%s)\n" (incf cnt)
9754 (match-string 3 l) (match-string 1 l)))
9755 (princ (format "[%c] %s\n" (incf cnt)
9756 (match-string 1 l))))))
9757 links))
9758 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
9759 (message "Select link to open, RET to open all:")
9760 (setq c (read-char-exclusive))
9761 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
9762 (when (equal c ?q) (error "Abort"))
9763 (if (equal c ?\C-m)
9764 (setq link links)
9765 (setq nth (- c ?0))
9766 (if have-zero (setq nth (1+ nth)))
9767 (unless (and (integerp nth) (>= (length links) nth))
9768 (error "Invalid link selection"))
9769 (setq link (list (nth (1- nth) links))))))
9770 (if link
9771 (let ((buf (current-buffer)))
9772 (dolist (l link)
9773 (org-open-link-from-string l in-emacs buf))
9775 nil)))
9777 ;; Add special file links that specify the way of opening
9779 (org-add-link-type "file+sys" 'org-open-file-with-system)
9780 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
9781 (defun org-open-file-with-system (path)
9782 "Open file at PATH using the system way of opening it."
9783 (org-open-file path 'system))
9784 (defun org-open-file-with-emacs (path)
9785 "Open file at PATH in Emacs."
9786 (org-open-file path 'emacs))
9787 (defun org-remove-file-link-modifiers ()
9788 "Remove the file link modifiers in `file+sys:' and `file+emacs:' links."
9789 (goto-char (point-min))
9790 (while (re-search-forward "\\<file\\+\\(sys\\|emacs\\):" nil t)
9791 (org-if-unprotected
9792 (replace-match "file:" t t))))
9793 (eval-after-load "org-exp"
9794 '(add-hook 'org-export-preprocess-before-normalizing-links-hook
9795 'org-remove-file-link-modifiers))
9797 ;;;; Time estimates
9799 (defun org-get-effort (&optional pom)
9800 "Get the effort estimate for the current entry."
9801 (org-entry-get pom org-effort-property))
9803 ;;; File search
9805 (defvar org-create-file-search-functions nil
9806 "List of functions to construct the right search string for a file link.
9807 These functions are called in turn with point at the location to
9808 which the link should point.
9810 A function in the hook should first test if it would like to
9811 handle this file type, for example by checking the `major-mode'
9812 or the file extension. If it decides not to handle this file, it
9813 should just return nil to give other functions a chance. If it
9814 does handle the file, it must return the search string to be used
9815 when following the link. The search string will be part of the
9816 file link, given after a double colon, and `org-open-at-point'
9817 will automatically search for it. If special measures must be
9818 taken to make the search successful, another function should be
9819 added to the companion hook `org-execute-file-search-functions',
9820 which see.
9822 A function in this hook may also use `setq' to set the variable
9823 `description' to provide a suggestion for the descriptive text to
9824 be used for this link when it gets inserted into an Org-mode
9825 buffer with \\[org-insert-link].")
9827 (defvar org-execute-file-search-functions nil
9828 "List of functions to execute a file search triggered by a link.
9830 Functions added to this hook must accept a single argument, the
9831 search string that was part of the file link, the part after the
9832 double colon. The function must first check if it would like to
9833 handle this search, for example by checking the `major-mode' or
9834 the file extension. If it decides not to handle this search, it
9835 should just return nil to give other functions a chance. If it
9836 does handle the search, it must return a non-nil value to keep
9837 other functions from trying.
9839 Each function can access the current prefix argument through the
9840 variable `current-prefix-argument'. Note that a single prefix is
9841 used to force opening a link in Emacs, so it may be good to only
9842 use a numeric or double prefix to guide the search function.
9844 In case this is needed, a function in this hook can also restore
9845 the window configuration before `org-open-at-point' was called using:
9847 (set-window-configuration org-window-config-before-follow-link)")
9849 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
9850 (defun org-link-search (s &optional type avoid-pos stealth)
9851 "Search for a link search option.
9852 If S is surrounded by forward slashes, it is interpreted as a
9853 regular expression. In org-mode files, this will create an `org-occur'
9854 sparse tree. In ordinary files, `occur' will be used to list matches.
9855 If the current buffer is in `dired-mode', grep will be used to search
9856 in all files. If AVOID-POS is given, ignore matches near that position.
9858 When optional argument STEALTH is non-nil, do not modify
9859 visibility around point, thus ignoring
9860 `org-show-hierarchy-above', `org-show-following-heading' and
9861 `org-show-siblings' variables."
9862 (let ((case-fold-search t)
9863 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
9864 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
9865 (append '(("") (" ") ("\t") ("\n"))
9866 org-emphasis-alist)
9867 "\\|") "\\)"))
9868 (pos (point))
9869 (pre nil) (post nil)
9870 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
9871 (cond
9872 ;; First check if there are any special search functions
9873 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
9874 ;; Now try the builtin stuff
9875 ((and (equal (string-to-char s0) ?#)
9876 (> (length s0) 1)
9877 (save-excursion
9878 (goto-char (point-min))
9879 (and
9880 (re-search-forward
9881 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
9882 (setq type 'dedicated
9883 pos (match-beginning 0))))
9884 ;; There is an exact target for this
9885 (goto-char pos)
9886 (org-back-to-heading t)))
9887 ((save-excursion
9888 (goto-char (point-min))
9889 (and
9890 (re-search-forward
9891 (concat "<<" (regexp-quote s0) ">>") nil t)
9892 (setq type 'dedicated
9893 pos (match-beginning 0))))
9894 ;; There is an exact target for this
9895 (goto-char pos))
9896 ((save-excursion
9897 (goto-char (point-min))
9898 (and
9899 (re-search-forward
9900 (format "^[ \t]*#\\+TARGET: %s" (regexp-quote s0)) nil t)
9901 (setq type 'dedicated pos (match-beginning 0))))
9902 ;; Found an invisible target.
9903 (goto-char pos))
9904 ((save-excursion
9905 (goto-char (point-min))
9906 (and
9907 (re-search-forward
9908 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
9909 (setq type 'dedicated pos (match-beginning 0))))
9910 ;; Found an element with a matching #+name affiliated keyword.
9911 (goto-char pos))
9912 ((and (string-match "^(\\(.*\\))$" s0)
9913 (save-excursion
9914 (goto-char (point-min))
9915 (and
9916 (re-search-forward
9917 (concat "[^[]" (regexp-quote
9918 (format org-coderef-label-format
9919 (match-string 1 s0))))
9920 nil t)
9921 (setq type 'dedicated
9922 pos (1+ (match-beginning 0))))))
9923 ;; There is a coderef target for this
9924 (goto-char pos))
9925 ((string-match "^/\\(.*\\)/$" s)
9926 ;; A regular expression
9927 (cond
9928 ((eq major-mode 'org-mode)
9929 (org-occur (match-string 1 s)))
9930 ;;((eq major-mode 'dired-mode)
9931 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
9932 (t (org-do-occur (match-string 1 s)))))
9933 ((and (eq major-mode 'org-mode) org-link-search-must-match-exact-headline)
9934 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
9935 (goto-char (point-min))
9936 (cond
9937 ((let (case-fold-search)
9938 (re-search-forward (format org-complex-heading-regexp-format
9939 (regexp-quote s))
9940 nil t))
9941 ;; OK, found a match
9942 (setq type 'dedicated)
9943 (goto-char (match-beginning 0)))
9944 ((and (not org-link-search-inhibit-query)
9945 (eq org-link-search-must-match-exact-headline 'query-to-create)
9946 (y-or-n-p "No match - create this as a new heading? "))
9947 (goto-char (point-max))
9948 (or (bolp) (newline))
9949 (insert "* " s "\n")
9950 (beginning-of-line 0))
9952 (goto-char pos)
9953 (error "No match"))))
9955 ;; A normal search string
9956 (when (equal (string-to-char s) ?*)
9957 ;; Anchor on headlines, post may include tags.
9958 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
9959 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
9960 s (substring s 1)))
9961 (remove-text-properties
9962 0 (length s)
9963 '(face nil mouse-face nil keymap nil fontified nil) s)
9964 ;; Make a series of regular expressions to find a match
9965 (setq words (org-split-string s "[ \n\r\t]+")
9967 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
9968 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
9969 "\\)" markers)
9970 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
9971 re2a (concat "[ \t\r\n]" re2a_)
9972 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
9973 re4 (concat "[^a-zA-Z_]" re4_)
9975 re1 (concat pre re2 post)
9976 re3 (concat pre (if pre re4_ re4) post)
9977 re5 (concat pre ".*" re4)
9978 re2 (concat pre re2)
9979 re2a (concat pre (if pre re2a_ re2a))
9980 re4 (concat pre (if pre re4_ re4))
9981 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
9982 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
9983 re5 "\\)"
9985 (cond
9986 ((eq type 'org-occur) (org-occur reall))
9987 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
9988 (t (goto-char (point-min))
9989 (setq type 'fuzzy)
9990 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
9991 (org-search-not-self 1 re1 nil t)
9992 (org-search-not-self 1 re2 nil t)
9993 (org-search-not-self 1 re2a nil t)
9994 (org-search-not-self 1 re3 nil t)
9995 (org-search-not-self 1 re4 nil t)
9996 (org-search-not-self 1 re5 nil t)
9998 (goto-char (match-beginning 1))
9999 (goto-char pos)
10000 (error "No match"))))))
10001 (and (eq major-mode 'org-mode)
10002 (not stealth)
10003 (org-show-context 'link-search))
10004 type))
10006 (defun org-search-not-self (group &rest args)
10007 "Execute `re-search-forward', but only accept matches that do not
10008 enclose the position of `org-open-link-marker'."
10009 (let ((m org-open-link-marker))
10010 (catch 'exit
10011 (while (apply 're-search-forward args)
10012 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10013 (goto-char (match-end group))
10014 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10015 (> (match-beginning 0) (marker-position m))
10016 (< (match-end 0) (marker-position m)))
10017 (save-match-data
10018 (or (not (org-in-regexp
10019 org-bracket-link-analytic-regexp 1))
10020 (not (match-end 4)) ; no description
10021 (and (<= (match-beginning 4) (point))
10022 (>= (match-end 4) (point))))))
10023 (throw 'exit (point))))))))
10025 (defun org-get-buffer-for-internal-link (buffer)
10026 "Return a buffer to be used for displaying the link target of internal links."
10027 (cond
10028 ((not org-display-internal-link-with-indirect-buffer)
10029 buffer)
10030 ((string-match "(Clone)$" (buffer-name buffer))
10031 (message "Buffer is already a clone, not making another one")
10032 ;; we also do not modify visibility in this case
10033 buffer)
10034 (t ; make a new indirect buffer for displaying the link
10035 (let* ((bn (buffer-name buffer))
10036 (ibn (concat bn "(Clone)"))
10037 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10038 (with-current-buffer ib (org-overview))
10039 ib))))
10041 (defun org-do-occur (regexp &optional cleanup)
10042 "Call the Emacs command `occur'.
10043 If CLEANUP is non-nil, remove the printout of the regular expression
10044 in the *Occur* buffer. This is useful if the regex is long and not useful
10045 to read."
10046 (occur regexp)
10047 (when cleanup
10048 (let ((cwin (selected-window)) win beg end)
10049 (when (setq win (get-buffer-window "*Occur*"))
10050 (select-window win))
10051 (goto-char (point-min))
10052 (when (re-search-forward "match[a-z]+" nil t)
10053 (setq beg (match-end 0))
10054 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10055 (setq end (1- (match-beginning 0)))))
10056 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10057 (goto-char (point-min))
10058 (select-window cwin))))
10060 ;;; The mark ring for links jumps
10062 (defvar org-mark-ring nil
10063 "Mark ring for positions before jumps in Org-mode.")
10064 (defvar org-mark-ring-last-goto nil
10065 "Last position in the mark ring used to go back.")
10066 ;; Fill and close the ring
10067 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10068 (loop for i from 1 to org-mark-ring-length do
10069 (push (make-marker) org-mark-ring))
10070 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10071 org-mark-ring)
10073 (defun org-mark-ring-push (&optional pos buffer)
10074 "Put the current position or POS into the mark ring and rotate it."
10075 (interactive)
10076 (setq pos (or pos (point)))
10077 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10078 (move-marker (car org-mark-ring)
10079 (or pos (point))
10080 (or buffer (current-buffer)))
10081 (message "%s"
10082 (substitute-command-keys
10083 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10085 (defun org-mark-ring-goto (&optional n)
10086 "Jump to the previous position in the mark ring.
10087 With prefix arg N, jump back that many stored positions. When
10088 called several times in succession, walk through the entire ring.
10089 Org-mode commands jumping to a different position in the current file,
10090 or to another Org-mode file, automatically push the old position
10091 onto the ring."
10092 (interactive "p")
10093 (let (p m)
10094 (if (eq last-command this-command)
10095 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10096 (setq p org-mark-ring))
10097 (setq org-mark-ring-last-goto p)
10098 (setq m (car p))
10099 (org-pop-to-buffer-same-window (marker-buffer m))
10100 (goto-char m)
10101 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10103 (defun org-remove-angle-brackets (s)
10104 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10105 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10107 (defun org-add-angle-brackets (s)
10108 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10109 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10111 (defun org-remove-double-quotes (s)
10112 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10113 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10116 ;;; Following specific links
10118 (defun org-follow-timestamp-link ()
10119 (cond
10120 ((org-at-date-range-p t)
10121 (let ((org-agenda-start-on-weekday)
10122 (t1 (match-string 1))
10123 (t2 (match-string 2)))
10124 (setq t1 (time-to-days (org-time-string-to-time t1))
10125 t2 (time-to-days (org-time-string-to-time t2)))
10126 (org-agenda-list nil t1 (1+ (- t2 t1)))))
10127 ((org-at-timestamp-p t)
10128 (org-agenda-list nil (time-to-days (org-time-string-to-time
10129 (substring (match-string 1) 0 10)))
10131 (t (error "This should not happen"))))
10134 ;;; Following file links
10135 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10136 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10137 (declare-function mailcap-mime-info
10138 "mailcap" (string &optional request no-decode))
10139 (defvar org-wait nil)
10140 (defun org-open-file (path &optional in-emacs line search)
10141 "Open the file at PATH.
10142 First, this expands any special file name abbreviations. Then the
10143 configuration variable `org-file-apps' is checked if it contains an
10144 entry for this file type, and if yes, the corresponding command is launched.
10146 If no application is found, Emacs simply visits the file.
10148 With optional prefix argument IN-EMACS, Emacs will visit the file.
10149 With a double \\[universal-argument] \\[universal-argument] \
10150 prefix arg, Org tries to avoid opening in Emacs
10151 and to use an external application to visit the file.
10153 Optional LINE specifies a line to go to, optional SEARCH a string
10154 to search for. If LINE or SEARCH is given, the file will be
10155 opened in Emacs, unless an entry from org-file-apps that makes
10156 use of groups in a regexp matches.
10158 If you want to change the way frames are used when following a
10159 link, please customize `org-link-frame-setup'.
10161 If the file does not exist, an error is thrown."
10162 (let* ((file (if (equal path "")
10163 buffer-file-name
10164 (substitute-in-file-name (expand-file-name path))))
10165 (file-apps (append org-file-apps (org-default-apps)))
10166 (apps (org-remove-if
10167 'org-file-apps-entry-match-against-dlink-p file-apps))
10168 (apps-dlink (org-remove-if-not
10169 'org-file-apps-entry-match-against-dlink-p file-apps))
10170 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10171 (dirp (if remp nil (file-directory-p file)))
10172 (file (if (and dirp org-open-directory-means-index-dot-org)
10173 (concat (file-name-as-directory file) "index.org")
10174 file))
10175 (a-m-a-p (assq 'auto-mode apps))
10176 (dfile (downcase file))
10177 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10178 (link (cond ((and (eq line nil)
10179 (eq search nil))
10180 file)
10181 (line
10182 (concat file "::" (number-to-string line)))
10183 (search
10184 (concat file "::" search))))
10185 (dlink (downcase link))
10186 (old-buffer (current-buffer))
10187 (old-pos (point))
10188 (old-mode major-mode)
10189 ext cmd link-match-data)
10190 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10191 (setq ext (match-string 1 dfile))
10192 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10193 (setq ext (match-string 1 dfile))))
10194 (cond
10195 ((member in-emacs '((16) system))
10196 (setq cmd (cdr (assoc 'system apps))))
10197 (in-emacs (setq cmd 'emacs))
10199 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10200 (and dirp (cdr (assoc 'directory apps)))
10201 ; first, try matching against apps-dlink
10202 ; if we get a match here, store the match data for later
10203 (let ((match (assoc-default dlink apps-dlink
10204 'string-match)))
10205 (if match
10206 (progn (setq link-match-data (match-data))
10207 match)
10208 (progn (setq in-emacs (or in-emacs line search))
10209 nil))) ; if we have no match in apps-dlink,
10210 ; always open the file in emacs if line or search
10211 ; is given (for backwards compatibility)
10212 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10213 'string-match)
10214 (cdr (assoc ext apps))
10215 (cdr (assoc t apps))))))
10216 (when (eq cmd 'system)
10217 (setq cmd (cdr (assoc 'system apps))))
10218 (when (eq cmd 'default)
10219 (setq cmd (cdr (assoc t apps))))
10220 (when (eq cmd 'mailcap)
10221 (require 'mailcap)
10222 (mailcap-parse-mailcaps)
10223 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10224 (command (mailcap-mime-info mime-type)))
10225 (if (stringp command)
10226 (setq cmd command)
10227 (setq cmd 'emacs))))
10228 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10229 (not (file-exists-p file))
10230 (not org-open-non-existing-files))
10231 (error "No such file: %s" file))
10232 (cond
10233 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10234 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10235 (while (string-match "['\"]%s['\"]" cmd)
10236 (setq cmd (replace-match "%s" t t cmd)))
10237 (while (string-match "%s" cmd)
10238 (setq cmd (replace-match
10239 (save-match-data
10240 (shell-quote-argument
10241 (convert-standard-filename file)))
10242 t t cmd)))
10244 ;; Replace "%1", "%2" etc. in command with group matches from regex
10245 (save-match-data
10246 (let ((match-index 1)
10247 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10248 (set-match-data link-match-data)
10249 (while (<= match-index number-of-groups)
10250 (let ((regex (concat "%" (number-to-string match-index)))
10251 (replace-with (match-string match-index dlink)))
10252 (while (string-match regex cmd)
10253 (setq cmd (replace-match replace-with t t cmd))))
10254 (setq match-index (+ match-index 1)))))
10256 (save-window-excursion
10257 (start-process-shell-command cmd nil cmd)
10258 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
10260 ((or (stringp cmd)
10261 (eq cmd 'emacs))
10262 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10263 (widen)
10264 (if line (org-goto-line line)
10265 (if search (org-link-search search))))
10266 ((consp cmd)
10267 (let ((file (convert-standard-filename file)))
10268 (save-match-data
10269 (set-match-data link-match-data)
10270 (eval cmd))))
10271 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10272 (and (eq major-mode 'org-mode) (eq old-mode 'org-mode)
10273 (or (not (equal old-buffer (current-buffer)))
10274 (not (equal old-pos (point))))
10275 (org-mark-ring-push old-pos old-buffer))))
10277 (defun org-file-apps-entry-match-against-dlink-p (entry)
10278 "This function returns non-nil if `entry' uses a regular
10279 expression which should be matched against the whole link by
10280 org-open-file.
10282 It assumes that is the case when the entry uses a regular
10283 expression which has at least one grouping construct and the
10284 action is either a lisp form or a command string containing
10285 '%1', i.e. using at least one subexpression match as a
10286 parameter."
10287 (let ((selector (car entry))
10288 (action (cdr entry)))
10289 (if (stringp selector)
10290 (and (> (regexp-opt-depth selector) 0)
10291 (or (and (stringp action)
10292 (string-match "%[0-9]" action))
10293 (consp action)))
10294 nil)))
10296 (defun org-default-apps ()
10297 "Return the default applications for this operating system."
10298 (cond
10299 ((eq system-type 'darwin)
10300 org-file-apps-defaults-macosx)
10301 ((eq system-type 'windows-nt)
10302 org-file-apps-defaults-windowsnt)
10303 (t org-file-apps-defaults-gnu)))
10305 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10306 "Convert extensions to regular expressions in the cars of LIST.
10307 Also, weed out any non-string entries, because the return value is used
10308 only for regexp matching.
10309 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10310 point to the symbol `emacs', indicating that the file should
10311 be opened in Emacs."
10312 (append
10313 (delq nil
10314 (mapcar (lambda (x)
10315 (if (not (stringp (car x)))
10317 (if (string-match "\\W" (car x))
10319 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10320 list))
10321 (if add-auto-mode
10322 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10324 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10325 (defun org-file-remote-p (file)
10326 "Test whether FILE specifies a location on a remote system.
10327 Return non-nil if the location is indeed remote.
10329 For example, the filename \"/user@host:/foo\" specifies a location
10330 on the system \"/user@host:\"."
10331 (cond ((fboundp 'file-remote-p)
10332 (file-remote-p file))
10333 ((fboundp 'tramp-handle-file-remote-p)
10334 (tramp-handle-file-remote-p file))
10335 ((and (boundp 'ange-ftp-name-format)
10336 (string-match (car ange-ftp-name-format) file))
10338 (t nil)))
10341 ;;;; Refiling
10343 (defun org-get-org-file ()
10344 "Read a filename, with default directory `org-directory'."
10345 (let ((default (or org-default-notes-file remember-data-file)))
10346 (read-file-name (format "File name [%s]: " default)
10347 (file-name-as-directory org-directory)
10348 default)))
10350 (defun org-notes-order-reversed-p ()
10351 "Check if the current file should receive notes in reversed order."
10352 (cond
10353 ((not org-reverse-note-order) nil)
10354 ((eq t org-reverse-note-order) t)
10355 ((not (listp org-reverse-note-order)) nil)
10356 (t (catch 'exit
10357 (let ((all org-reverse-note-order)
10358 entry)
10359 (while (setq entry (pop all))
10360 (if (string-match (car entry) buffer-file-name)
10361 (throw 'exit (cdr entry))))
10362 nil)))))
10364 (defvar org-refile-target-table nil
10365 "The list of refile targets, created by `org-refile'.")
10367 (defvar org-agenda-new-buffers nil
10368 "Buffers created to visit agenda files.")
10370 (defvar org-refile-cache nil
10371 "Cache for refile targets.")
10373 (defvar org-refile-markers nil
10374 "All the markers used for caching refile locations.")
10376 (defun org-refile-marker (pos)
10377 "Get a new refile marker, but only if caching is in use."
10378 (if (not org-refile-use-cache)
10380 (let ((m (make-marker)))
10381 (move-marker m pos)
10382 (push m org-refile-markers)
10383 m)))
10385 (defun org-refile-cache-clear ()
10386 "Clear the refile cache and disable all the markers."
10387 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
10388 (setq org-refile-markers nil)
10389 (setq org-refile-cache nil)
10390 (message "Refile cache has been cleared"))
10392 (defun org-refile-cache-check-set (set)
10393 "Check if all the markers in the cache still have live buffers."
10394 (let (marker)
10395 (catch 'exit
10396 (while (and set (setq marker (nth 3 (pop set))))
10397 ;; if org-refile-use-outline-path is 'file, marker may be nil
10398 (when (and marker (null (marker-buffer marker)))
10399 (message "not found") (sit-for 3)
10400 (throw 'exit nil)))
10401 t)))
10403 (defun org-refile-cache-put (set &rest identifiers)
10404 "Push the refile targets SET into the cache, under IDENTIFIERS."
10405 (let* ((key (sha1 (prin1-to-string identifiers)))
10406 (entry (assoc key org-refile-cache)))
10407 (if entry
10408 (setcdr entry set)
10409 (push (cons key set) org-refile-cache))))
10411 (defun org-refile-cache-get (&rest identifiers)
10412 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10413 (cond
10414 ((not org-refile-cache) nil)
10415 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10417 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10418 org-refile-cache))))
10419 (and set (org-refile-cache-check-set set) set)))))
10421 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
10422 "Produce a table with refile targets."
10423 (let ((case-fold-search nil)
10424 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10425 (entries (or org-refile-targets '((nil . (:level . 1)))))
10426 targets tgs txt re files f desc descre fast-path-p level pos0)
10427 (message "Getting targets...")
10428 (with-current-buffer (or default-buffer (current-buffer))
10429 (while (setq entry (pop entries))
10430 (setq files (car entry) desc (cdr entry))
10431 (setq fast-path-p nil)
10432 (cond
10433 ((null files) (setq files (list (current-buffer))))
10434 ((eq files 'org-agenda-files)
10435 (setq files (org-agenda-files 'unrestricted)))
10436 ((and (symbolp files) (fboundp files))
10437 (setq files (funcall files)))
10438 ((and (symbolp files) (boundp files))
10439 (setq files (symbol-value files))))
10440 (if (stringp files) (setq files (list files)))
10441 (cond
10442 ((eq (car desc) :tag)
10443 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
10444 ((eq (car desc) :todo)
10445 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
10446 ((eq (car desc) :regexp)
10447 (setq descre (cdr desc)))
10448 ((eq (car desc) :level)
10449 (setq descre (concat "^\\*\\{" (number-to-string
10450 (if org-odd-levels-only
10451 (1- (* 2 (cdr desc)))
10452 (cdr desc)))
10453 "\\}[ \t]")))
10454 ((eq (car desc) :maxlevel)
10455 (setq fast-path-p t)
10456 (setq descre (concat "^\\*\\{1," (number-to-string
10457 (if org-odd-levels-only
10458 (1- (* 2 (cdr desc)))
10459 (cdr desc)))
10460 "\\}[ \t]")))
10461 (t (error "Bad refiling target description %s" desc)))
10462 (while (setq f (pop files))
10463 (with-current-buffer
10464 (if (bufferp f) f (org-get-agenda-file-buffer f))
10466 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
10467 (progn
10468 (if (bufferp f) (setq f (buffer-file-name
10469 (buffer-base-buffer f))))
10470 (setq f (and f (expand-file-name f)))
10471 (if (eq org-refile-use-outline-path 'file)
10472 (push (list (file-name-nondirectory f) f nil nil) tgs))
10473 (save-excursion
10474 (save-restriction
10475 (widen)
10476 (goto-char (point-min))
10477 (while (re-search-forward descre nil t)
10478 (goto-char (setq pos0 (point-at-bol)))
10479 (catch 'next
10480 (when org-refile-target-verify-function
10481 (save-match-data
10482 (or (funcall org-refile-target-verify-function)
10483 (throw 'next t))))
10484 (when (and (looking-at org-complex-heading-regexp)
10485 (not (member (match-string 4) excluded-entries))
10486 (match-string 4))
10487 (setq level (org-reduced-level
10488 (- (match-end 1) (match-beginning 1)))
10489 txt (org-link-display-format (match-string 4))
10490 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
10491 re (format org-complex-heading-regexp-format
10492 (regexp-quote (match-string 4))))
10493 (when org-refile-use-outline-path
10494 (setq txt (mapconcat
10495 'org-protect-slash
10496 (append
10497 (if (eq org-refile-use-outline-path
10498 'file)
10499 (list (file-name-nondirectory
10500 (buffer-file-name
10501 (buffer-base-buffer))))
10502 (if (eq org-refile-use-outline-path
10503 'full-file-path)
10504 (list (buffer-file-name
10505 (buffer-base-buffer)))))
10506 (org-get-outline-path fast-path-p
10507 level txt)
10508 (list txt))
10509 "/")))
10510 (push (list txt f re (org-refile-marker (point)))
10511 tgs)))
10512 (when (= (point) pos0)
10513 ;; verification function has not moved point
10514 (goto-char (point-at-eol))))))))
10515 (when org-refile-use-cache
10516 (org-refile-cache-put tgs (buffer-file-name) descre))
10517 (setq targets (append tgs targets))
10518 ))))
10519 (message "Getting targets...done")
10520 (nreverse targets)))
10522 (defun org-protect-slash (s)
10523 (while (string-match "/" s)
10524 (setq s (replace-match "\\" t t s)))
10527 (defvar org-olpa (make-vector 20 nil))
10529 (defun org-get-outline-path (&optional fastp level heading)
10530 "Return the outline path to the current entry, as a list.
10532 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
10533 routine which makes outline path derivations for an entire file,
10534 avoiding backtracing. Refile target collection makes use of that."
10535 (if fastp
10536 (progn
10537 (if (> level 19)
10538 (error "Outline path failure, more than 19 levels"))
10539 (loop for i from level upto 19 do
10540 (aset org-olpa i nil))
10541 (prog1
10542 (delq nil (append org-olpa nil))
10543 (aset org-olpa level heading)))
10544 (let (rtn case-fold-search)
10545 (save-excursion
10546 (save-restriction
10547 (widen)
10548 (while (org-up-heading-safe)
10549 (when (looking-at org-complex-heading-regexp)
10550 (push (org-match-string-no-properties 4) rtn)))
10551 rtn)))))
10553 (defun org-format-outline-path (path &optional width prefix)
10554 "Format the outline path PATH for display.
10555 Width is the maximum number of characters that is available.
10556 Prefix is a prefix to be included in the returned string,
10557 such as the file name."
10558 (setq width (or width 79))
10559 (if prefix (setq width (- width (length prefix))))
10560 (if (not path)
10561 (or prefix "")
10562 (let* ((nsteps (length path))
10563 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
10564 (maxwidth (if (<= total-width width)
10565 10000 ;; everything fits
10566 ;; we need to shorten the level headings
10567 (/ (- width nsteps) nsteps)))
10568 (org-odd-levels-only nil)
10569 (n 0)
10570 (total (1+ (length prefix))))
10571 (setq maxwidth (max maxwidth 10))
10572 (concat prefix
10573 (mapconcat
10574 (lambda (h)
10575 (setq n (1+ n))
10576 (if (and (= n nsteps) (< maxwidth 10000))
10577 (setq maxwidth (- total-width total)))
10578 (if (< (length h) maxwidth)
10579 (progn (setq total (+ total (length h) 1)) h)
10580 (setq h (substring h 0 (- maxwidth 2))
10581 total (+ total maxwidth 1))
10582 (if (string-match "[ \t]+\\'" h)
10583 (setq h (substring h 0 (match-beginning 0))))
10584 (setq h (concat h "..")))
10585 (org-add-props h nil 'face
10586 (nth (% (1- n) org-n-level-faces)
10587 org-level-faces))
10589 path "/")))))
10591 (defun org-display-outline-path (&optional file current)
10592 "Display the current outline path in the echo area."
10593 (interactive "P")
10594 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
10595 (case-fold-search nil)
10596 (path (and (eq major-mode 'org-mode) (org-get-outline-path))))
10597 (if current (setq path (append path
10598 (save-excursion
10599 (org-back-to-heading t)
10600 (if (looking-at org-complex-heading-regexp)
10601 (list (match-string 4)))))))
10602 (message "%s"
10603 (org-format-outline-path
10604 path
10605 (1- (frame-width))
10606 (and file bfn (concat (file-name-nondirectory bfn) "/"))))))
10608 (defvar org-refile-history nil
10609 "History for refiling operations.")
10611 (defvar org-after-refile-insert-hook nil
10612 "Hook run after `org-refile' has inserted its stuff at the new location.
10613 Note that this is still *before* the stuff will be removed from
10614 the *old* location.")
10616 (defvar org-capture-last-stored-marker)
10617 (defun org-refile (&optional goto default-buffer rfloc)
10618 "Move the entry or entries at point to another heading.
10619 The list of target headings is compiled using the information in
10620 `org-refile-targets', which see.
10622 At the target location, the entry is filed as a subitem of the target
10623 heading. Depending on `org-reverse-note-order', the new subitem will
10624 either be the first or the last subitem.
10626 If there is an active region, all entries in that region will be moved.
10627 However, the region must fulfill the requirement that the first heading
10628 is the first one sets the top-level of the moved text - at most siblings
10629 below it are allowed.
10631 With prefix arg GOTO, the command will only visit the target location
10632 and not actually move anything.
10634 With a double prefix arg \\[universal-argument] \\[universal-argument], \
10635 go to the location where the last refiling operation has put the subtree.
10636 With a prefix argument of `2', refile to the running clock.
10638 RFLOC can be a refile location obtained in a different way.
10640 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
10642 If you are using target caching (see `org-refile-use-cache'),
10643 You have to clear the target cache in order to find new targets.
10644 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
10645 prefix argument (`C-u C-u C-u C-c C-w')."
10647 (interactive "P")
10648 (if (member goto '(0 (64)))
10649 (org-refile-cache-clear)
10650 (let* ((cbuf (current-buffer))
10651 (regionp (org-region-active-p))
10652 (region-start (and regionp (region-beginning)))
10653 (region-end (and regionp (region-end)))
10654 (region-length (and regionp (- region-end region-start)))
10655 (filename (buffer-file-name (buffer-base-buffer cbuf)))
10656 pos it nbuf file re level reversed)
10657 (setq last-command nil)
10658 (when regionp
10659 (goto-char region-start)
10660 (or (bolp) (goto-char (point-at-bol)))
10661 (setq region-start (point))
10662 (unless (or (org-kill-is-subtree-p
10663 (buffer-substring region-start region-end))
10664 (prog1 org-refile-active-region-within-subtree
10665 (org-toggle-heading)))
10666 (error "The region is not a (sequence of) subtree(s)")))
10667 (if (equal goto '(16))
10668 (org-refile-goto-last-stored)
10669 (when (or
10670 (and (equal goto 2)
10671 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
10672 (prog1
10673 (setq it (list (or org-clock-heading "running clock")
10674 (buffer-file-name
10675 (marker-buffer org-clock-hd-marker))
10677 (marker-position org-clock-hd-marker)))
10678 (setq goto nil)))
10679 (setq it (or rfloc
10680 (let (heading-text)
10681 (save-excursion
10682 (unless goto
10683 (org-back-to-heading t)
10684 (setq heading-text
10685 (nth 4 (org-heading-components))))
10686 (org-refile-get-location
10687 (cond (goto "Goto")
10688 (regionp "Refile region to")
10689 (t (concat "Refile subtree \""
10690 heading-text "\" to")))
10691 default-buffer
10692 (and (not (equal '(4) goto))
10693 org-refile-allow-creating-parent-nodes)
10694 goto))))))
10695 (setq file (nth 1 it)
10696 re (nth 2 it)
10697 pos (nth 3 it))
10698 (if (and (not goto)
10700 (equal (buffer-file-name) file)
10701 (if regionp
10702 (and (>= pos region-start)
10703 (<= pos region-end))
10704 (and (>= pos (point))
10705 (< pos (save-excursion
10706 (org-end-of-subtree t t))))))
10707 (error "Cannot refile to position inside the tree or region"))
10709 (setq nbuf (or (find-buffer-visiting file)
10710 (find-file-noselect file)))
10711 (if goto
10712 (progn
10713 (org-pop-to-buffer-same-window nbuf)
10714 (goto-char pos)
10715 (org-show-context 'org-goto))
10716 (if regionp
10717 (progn
10718 (org-kill-new (buffer-substring region-start region-end))
10719 (org-save-markers-in-region region-start region-end))
10720 (org-copy-subtree 1 nil t))
10721 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
10722 (find-file-noselect file)))
10723 (setq reversed (org-notes-order-reversed-p))
10724 (save-excursion
10725 (save-restriction
10726 (widen)
10727 (if pos
10728 (progn
10729 (goto-char pos)
10730 (looking-at org-outline-regexp)
10731 (setq level (org-get-valid-level (funcall outline-level) 1))
10732 (goto-char
10733 (if reversed
10734 (or (outline-next-heading) (point-max))
10735 (or (save-excursion (org-get-next-sibling))
10736 (org-end-of-subtree t t)
10737 (point-max)))))
10738 (setq level 1)
10739 (if (not reversed)
10740 (goto-char (point-max))
10741 (goto-char (point-min))
10742 (or (outline-next-heading) (goto-char (point-max)))))
10743 (if (not (bolp)) (newline))
10744 (org-paste-subtree level)
10745 (when org-log-refile
10746 (org-add-log-setup 'refile nil nil 'findpos
10747 org-log-refile)
10748 (unless (eq org-log-refile 'note)
10749 (save-excursion (org-add-log-note))))
10750 (and org-auto-align-tags (org-set-tags nil t))
10751 (bookmark-set "org-refile-last-stored")
10752 ;; If we are refiling for capture, make sure that the
10753 ;; last-capture pointers point here
10754 (when (org-bound-and-true-p org-refile-for-capture)
10755 (bookmark-set "org-capture-last-stored-marker")
10756 (move-marker org-capture-last-stored-marker (point)))
10757 (if (fboundp 'deactivate-mark) (deactivate-mark))
10758 (run-hooks 'org-after-refile-insert-hook))))
10759 (if regionp
10760 (delete-region (point) (+ (point) region-length))
10761 (org-cut-subtree))
10762 (when (featurep 'org-inlinetask)
10763 (org-inlinetask-remove-END-maybe))
10764 (setq org-markers-to-move nil)
10765 (message "Refiled to \"%s\" in file %s" (car it) file)))))))
10767 (defun org-refile-goto-last-stored ()
10768 "Go to the location where the last refile was stored."
10769 (interactive)
10770 (bookmark-jump "org-refile-last-stored")
10771 (message "This is the location of the last refile"))
10773 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
10774 no-exclude)
10775 "Prompt the user for a refile location, using PROMPT.
10776 PROMPT should not be suffixed with a colon and a space, because
10777 this function appends the default value from
10778 `org-refile-history' automatically, if that is not empty.
10779 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
10780 this is used for the GOTO interface."
10781 (let ((org-refile-targets org-refile-targets)
10782 (org-refile-use-outline-path org-refile-use-outline-path)
10783 excluded-entries)
10784 (when (and (eq major-mode 'org-mode)
10785 (not org-refile-use-cache)
10786 (not no-exclude))
10787 (org-map-tree
10788 (lambda()
10789 (setq excluded-entries
10790 (append excluded-entries (list (org-get-heading t t)))))))
10791 (setq org-refile-target-table
10792 (org-refile-get-targets default-buffer excluded-entries)))
10793 (unless org-refile-target-table
10794 (error "No refile targets"))
10795 (let* ((prompt (concat prompt
10796 (and (car org-refile-history)
10797 (concat " (default " (car org-refile-history) ")"))
10798 ": "))
10799 (cbuf (current-buffer))
10800 (partial-completion-mode nil)
10801 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
10802 (cfunc (if (and org-refile-use-outline-path
10803 org-outline-path-complete-in-steps)
10804 'org-olpath-completing-read
10805 'org-icompleting-read))
10806 (extra (if org-refile-use-outline-path "/" ""))
10807 (filename (and cfn (expand-file-name cfn)))
10808 (tbl (mapcar
10809 (lambda (x)
10810 (if (and (not (member org-refile-use-outline-path
10811 '(file full-file-path)))
10812 (not (equal filename (nth 1 x))))
10813 (cons (concat (car x) extra " ("
10814 (file-name-nondirectory (nth 1 x)) ")")
10815 (cdr x))
10816 (cons (concat (car x) extra) (cdr x))))
10817 org-refile-target-table))
10818 (completion-ignore-case t)
10819 pa answ parent-target child parent old-hist)
10820 (setq old-hist org-refile-history)
10821 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
10822 nil 'org-refile-history (car org-refile-history)))
10823 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
10824 (org-refile-check-position pa)
10825 (if pa
10826 (progn
10827 (when (or (not org-refile-history)
10828 (not (eq old-hist org-refile-history))
10829 (not (equal (car pa) (car org-refile-history))))
10830 (setq org-refile-history
10831 (cons (car pa) (if (assoc (car org-refile-history) tbl)
10832 org-refile-history
10833 (cdr org-refile-history))))
10834 (if (equal (car org-refile-history) (nth 1 org-refile-history))
10835 (pop org-refile-history)))
10837 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
10838 (progn
10839 (setq parent (match-string 1 answ)
10840 child (match-string 2 answ))
10841 (setq parent-target (or (assoc parent tbl)
10842 (assoc (concat parent "/") tbl)))
10843 (when (and parent-target
10844 (or (eq new-nodes t)
10845 (and (eq new-nodes 'confirm)
10846 (y-or-n-p (format "Create new node \"%s\"? "
10847 child)))))
10848 (org-refile-new-child parent-target child)))
10849 (error "Invalid target location")))))
10851 (declare-function org-string-nw-p "org-macs.el" (s))
10852 (defun org-refile-check-position (refile-pointer)
10853 "Check if the refile pointer matches the readline to which it points."
10854 (let* ((file (nth 1 refile-pointer))
10855 (re (nth 2 refile-pointer))
10856 (pos (nth 3 refile-pointer))
10857 buffer)
10858 (when (org-string-nw-p re)
10859 (setq buffer (if (markerp pos)
10860 (marker-buffer pos)
10861 (or (find-buffer-visiting file)
10862 (find-file-noselect file))))
10863 (with-current-buffer buffer
10864 (save-excursion
10865 (save-restriction
10866 (widen)
10867 (goto-char pos)
10868 (beginning-of-line 1)
10869 (unless (org-looking-at-p re)
10870 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
10872 (defun org-refile-new-child (parent-target child)
10873 "Use refile target PARENT-TARGET to add new CHILD below it."
10874 (unless parent-target
10875 (error "Cannot find parent for new node"))
10876 (let ((file (nth 1 parent-target))
10877 (pos (nth 3 parent-target))
10878 level)
10879 (with-current-buffer (or (find-buffer-visiting file)
10880 (find-file-noselect file))
10881 (save-excursion
10882 (save-restriction
10883 (widen)
10884 (if pos
10885 (goto-char pos)
10886 (goto-char (point-max))
10887 (if (not (bolp)) (newline)))
10888 (when (looking-at org-outline-regexp)
10889 (setq level (funcall outline-level))
10890 (org-end-of-subtree t t))
10891 (org-back-over-empty-lines)
10892 (insert "\n" (make-string
10893 (if pos (org-get-valid-level level 1) 1) ?*)
10894 " " child "\n")
10895 (beginning-of-line 0)
10896 (list (concat (car parent-target) "/" child) file "" (point)))))))
10898 (defun org-olpath-completing-read (prompt collection &rest args)
10899 "Read an outline path like a file name."
10900 (let ((thetable collection)
10901 (org-completion-use-ido nil) ; does not work with ido.
10902 (org-completion-use-iswitchb nil)) ; or iswitchb
10903 (apply
10904 'org-icompleting-read prompt
10905 (lambda (string predicate &optional flag)
10906 (let (rtn r f (l (length string)))
10907 (cond
10908 ((eq flag nil)
10909 ;; try completion
10910 (try-completion string thetable))
10911 ((eq flag t)
10912 ;; all-completions
10913 (setq rtn (all-completions string thetable predicate))
10914 (mapcar
10915 (lambda (x)
10916 (setq r (substring x l))
10917 (if (string-match " ([^)]*)$" x)
10918 (setq f (match-string 0 x))
10919 (setq f ""))
10920 (if (string-match "/" r)
10921 (concat string (substring r 0 (match-end 0)) f)
10923 rtn))
10924 ((eq flag 'lambda)
10925 ;; exact match?
10926 (assoc string thetable)))
10928 args)))
10930 ;;;; Dynamic blocks
10932 (defun org-find-dblock (name)
10933 "Find the first dynamic block with name NAME in the buffer.
10934 If not found, stay at current position and return nil."
10935 (let (pos)
10936 (save-excursion
10937 (goto-char (point-min))
10938 (setq pos (and (re-search-forward (concat "^[ \t]*#\\+BEGIN:[ \t]+" name "\\>")
10939 nil t)
10940 (match-beginning 0))))
10941 (if pos (goto-char pos))
10942 pos))
10944 (defconst org-dblock-start-re
10945 "^[ \t]*#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
10946 "Matches the start line of a dynamic block, with parameters.")
10948 (defconst org-dblock-end-re "^[ \t]*#\\+END\\([: \t\r\n]\\|$\\)"
10949 "Matches the end of a dynamic block.")
10951 (defun org-create-dblock (plist)
10952 "Create a dynamic block section, with parameters taken from PLIST.
10953 PLIST must contain a :name entry which is used as name of the block."
10954 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
10955 (end-of-line 1)
10956 (newline))
10957 (let ((col (current-column))
10958 (name (plist-get plist :name)))
10959 (insert "#+BEGIN: " name)
10960 (while plist
10961 (if (eq (car plist) :name)
10962 (setq plist (cddr plist))
10963 (insert " " (prin1-to-string (pop plist)))))
10964 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
10965 (beginning-of-line -2)))
10967 (defun org-prepare-dblock ()
10968 "Prepare dynamic block for refresh.
10969 This empties the block, puts the cursor at the insert position and returns
10970 the property list including an extra property :name with the block name."
10971 (unless (looking-at org-dblock-start-re)
10972 (error "Not at a dynamic block"))
10973 (let* ((begdel (1+ (match-end 0)))
10974 (name (org-no-properties (match-string 1)))
10975 (params (append (list :name name)
10976 (read (concat "(" (match-string 3) ")")))))
10977 (save-excursion
10978 (beginning-of-line 1)
10979 (skip-chars-forward " \t")
10980 (setq params (plist-put params :indentation-column (current-column))))
10981 (unless (re-search-forward org-dblock-end-re nil t)
10982 (error "Dynamic block not terminated"))
10983 (setq params
10984 (append params
10985 (list :content (buffer-substring
10986 begdel (match-beginning 0)))))
10987 (delete-region begdel (match-beginning 0))
10988 (goto-char begdel)
10989 (open-line 1)
10990 params))
10992 (defun org-map-dblocks (&optional command)
10993 "Apply COMMAND to all dynamic blocks in the current buffer.
10994 If COMMAND is not given, use `org-update-dblock'."
10995 (let ((cmd (or command 'org-update-dblock)))
10996 (save-excursion
10997 (goto-char (point-min))
10998 (while (re-search-forward org-dblock-start-re nil t)
10999 (goto-char (match-beginning 0))
11000 (save-excursion
11001 (condition-case nil
11002 (funcall cmd)
11003 (error (message "Error during update of dynamic block"))))
11004 (unless (re-search-forward org-dblock-end-re nil t)
11005 (error "Dynamic block not terminated"))))))
11007 (defun org-dblock-update (&optional arg)
11008 "User command for updating dynamic blocks.
11009 Update the dynamic block at point. With prefix ARG, update all dynamic
11010 blocks in the buffer."
11011 (interactive "P")
11012 (if arg
11013 (org-update-all-dblocks)
11014 (or (looking-at org-dblock-start-re)
11015 (org-beginning-of-dblock))
11016 (org-update-dblock)))
11018 (defun org-update-dblock ()
11019 "Update the dynamic block at point.
11020 This means to empty the block, parse for parameters and then call
11021 the correct writing function."
11022 (interactive)
11023 (save-window-excursion
11024 (let* ((pos (point))
11025 (line (org-current-line))
11026 (params (org-prepare-dblock))
11027 (name (plist-get params :name))
11028 (indent (plist-get params :indentation-column))
11029 (cmd (intern (concat "org-dblock-write:" name))))
11030 (message "Updating dynamic block `%s' at line %d..." name line)
11031 (funcall cmd params)
11032 (message "Updating dynamic block `%s' at line %d...done" name line)
11033 (goto-char pos)
11034 (when (and indent (> indent 0))
11035 (setq indent (make-string indent ?\ ))
11036 (save-excursion
11037 (org-beginning-of-dblock)
11038 (forward-line 1)
11039 (while (not (looking-at org-dblock-end-re))
11040 (insert indent)
11041 (beginning-of-line 2))
11042 (when (looking-at org-dblock-end-re)
11043 (and (looking-at "[ \t]+")
11044 (replace-match ""))
11045 (insert indent)))))))
11047 (defun org-beginning-of-dblock ()
11048 "Find the beginning of the dynamic block at point.
11049 Error if there is no such block at point."
11050 (let ((pos (point))
11051 beg)
11052 (end-of-line 1)
11053 (if (and (re-search-backward org-dblock-start-re nil t)
11054 (setq beg (match-beginning 0))
11055 (re-search-forward org-dblock-end-re nil t)
11056 (> (match-end 0) pos))
11057 (goto-char beg)
11058 (goto-char pos)
11059 (error "Not in a dynamic block"))))
11061 ;;;###autoload
11062 (defun org-update-all-dblocks ()
11063 "Update all dynamic blocks in the buffer.
11064 This function can be used in a hook."
11065 (interactive)
11066 (when (eq major-mode 'org-mode)
11067 (org-map-dblocks 'org-update-dblock)))
11070 ;;;; Completion
11072 (defconst org-additional-option-like-keywords
11073 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML:"
11074 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook:"
11075 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"
11076 "LATEX_CLASS:" "LATEX_CLASS_OPTIONS:" "ATTR_LaTeX:"
11077 "BEGIN:" "END:"
11078 "ORGTBL" "TBLFM:" "TBLNAME:"
11079 "BEGIN_EXAMPLE" "END_EXAMPLE"
11080 "BEGIN_QUOTE" "END_QUOTE"
11081 "BEGIN_VERSE" "END_VERSE"
11082 "BEGIN_CENTER" "END_CENTER"
11083 "BEGIN_SRC" "END_SRC"
11084 "BEGIN_RESULT" "END_RESULT"
11085 "NAME:" "RESULTS:"
11086 "HEADER:" "HEADERS:"
11087 "CATEGORY:" "COLUMNS:" "PROPERTY:"
11088 "CAPTION:" "LABEL:"
11089 "SETUPFILE:"
11090 "INCLUDE:"
11091 "BIND:"
11092 "MACRO:"))
11094 (defcustom org-structure-template-alist
11096 ("s" "#+BEGIN_SRC ?\n\n#+END_SRC"
11097 "<src lang=\"?\">\n\n</src>")
11098 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE"
11099 "<example>\n?\n</example>")
11100 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE"
11101 "<quote>\n?\n</quote>")
11102 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE"
11103 "<verse>\n?\n</verse>")
11104 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER"
11105 "<center>\n?\n</center>")
11106 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11107 "<literal style=\"latex\">\n?\n</literal>")
11108 ("L" "#+LaTeX: "
11109 "<literal style=\"latex\">?</literal>")
11110 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
11111 "<literal style=\"html\">\n?\n</literal>")
11112 ("H" "#+HTML: "
11113 "<literal style=\"html\">?</literal>")
11114 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
11115 ("A" "#+ASCII: ")
11116 ("i" "#+INDEX: ?"
11117 "#+INDEX: ?")
11118 ("I" "#+INCLUDE %file ?"
11119 "<include file=%file markup=\"?\">")
11121 "Structure completion elements.
11122 This is a list of abbreviation keys and values. The value gets inserted
11123 if you type `<' followed by the key and then press the completion key,
11124 usually `M-TAB'. %file will be replaced by a file name after prompting
11125 for the file using completion. The cursor will be placed at the position
11126 of the `?` in the template.
11127 There are two templates for each key, the first uses the original Org syntax,
11128 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11129 the default when the /org-mtags.el/ module has been loaded. See also the
11130 variable `org-mtags-prefer-muse-templates'."
11131 :group 'org-completion
11132 :type '(repeat
11133 (string :tag "Key")
11134 (string :tag "Template")
11135 (string :tag "Muse Template")))
11137 (defun org-try-structure-completion ()
11138 "Try to complete a structure template before point.
11139 This looks for strings like \"<e\" on an otherwise empty line and
11140 expands them."
11141 (let ((l (buffer-substring (point-at-bol) (point)))
11143 (when (and (looking-at "[ \t]*$")
11144 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
11145 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
11146 (org-complete-expand-structure-template (+ -1 (point-at-bol)
11147 (match-beginning 1)) a)
11148 t)))
11150 (defun org-complete-expand-structure-template (start cell)
11151 "Expand a structure template."
11152 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
11153 (rpl (nth (if musep 2 1) cell))
11154 (ind ""))
11155 (delete-region start (point))
11156 (when (string-match "\\`#\\+" rpl)
11157 (cond
11158 ((bolp))
11159 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
11160 (setq ind (buffer-substring (point-at-bol) (point))))
11161 (t (newline))))
11162 (setq start (point))
11163 (if (string-match "%file" rpl)
11164 (setq rpl (replace-match
11165 (concat
11166 "\""
11167 (save-match-data
11168 (abbreviate-file-name (read-file-name "Include file: ")))
11169 "\"")
11170 t t rpl)))
11171 (setq rpl (mapconcat 'identity (split-string rpl "\n")
11172 (concat "\n" ind)))
11173 (insert rpl)
11174 (if (re-search-backward "\\?" start t) (delete-char 1))))
11176 ;;;; TODO, DEADLINE, Comments
11178 (defun org-toggle-comment ()
11179 "Change the COMMENT state of an entry."
11180 (interactive)
11181 (save-excursion
11182 (org-back-to-heading)
11183 (let (case-fold-search)
11184 (cond
11185 ((looking-at (format org-heading-keyword-regexp-format
11186 org-comment-string))
11187 (goto-char (match-end 1))
11188 (looking-at (concat " +" org-comment-string))
11189 (replace-match "" t t)
11190 (when (eolp) (insert " ")))
11191 ((looking-at org-outline-regexp)
11192 (goto-char (match-end 0))
11193 (insert org-comment-string " "))))))
11195 (defvar org-last-todo-state-is-todo nil
11196 "This is non-nil when the last TODO state change led to a TODO state.
11197 If the last change removed the TODO tag or switched to DONE, then
11198 this is nil.")
11200 (defvar org-setting-tags nil) ; dynamically skipped
11202 (defvar org-todo-setup-filter-hook nil
11203 "Hook for functions that pre-filter todo specs.
11204 Each function takes a todo spec and returns either nil or the spec
11205 transformed into canonical form." )
11207 (defvar org-todo-get-default-hook nil
11208 "Hook for functions that get a default item for todo.
11209 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11210 nil or a string to be used for the todo mark." )
11212 (defvar org-agenda-headline-snapshot-before-repeat)
11214 (defun org-current-effective-time ()
11215 "Return current time adjusted for `org-extend-today-until' variable"
11216 (let* ((ct (org-current-time))
11217 (dct (decode-time ct))
11218 (ct1
11219 (if (and org-use-effective-time
11220 (< (nth 2 dct) org-extend-today-until))
11221 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct))
11222 ct)))
11223 ct1))
11225 (defun org-todo-yesterday (&optional arg)
11226 "Like `org-todo' but the time of change will be 23:59 of yesterday."
11227 (interactive "P")
11228 (if (eq major-mode 'org-agenda-mode)
11229 (apply 'org-agenda-todo-yesterday arg)
11230 (let* ((hour (third (decode-time
11231 (org-current-time))))
11232 (org-extend-today-until (1+ hour)))
11233 (org-todo arg))))
11235 (defun org-todo (&optional arg)
11236 "Change the TODO state of an item.
11237 The state of an item is given by a keyword at the start of the heading,
11238 like
11239 *** TODO Write paper
11240 *** DONE Call mom
11242 The different keywords are specified in the variable `org-todo-keywords'.
11243 By default the available states are \"TODO\" and \"DONE\".
11244 So for this example: when the item starts with TODO, it is changed to DONE.
11245 When it starts with DONE, the DONE is removed. And when neither TODO nor
11246 DONE are present, add TODO at the beginning of the heading.
11248 With \\[universal-argument] prefix arg, use completion to determine the new \
11249 state.
11250 With numeric prefix arg, switch to that state.
11251 With a double \\[universal-argument] prefix, switch to the next set of TODO \
11252 keywords (nextset).
11253 With a triple \\[universal-argument] prefix, circumvent any state blocking.
11254 With a numeric prefix arg of 0, inhibit note taking for the change.
11256 For calling through lisp, arg is also interpreted in the following way:
11257 'none -> empty state
11258 \"\"(empty string) -> switch to empty state
11259 'done -> switch to DONE
11260 'nextset -> switch to the next set of keywords
11261 'previousset -> switch to the previous set of keywords
11262 \"WAITING\" -> switch to the specified keyword, but only if it
11263 really is a member of `org-todo-keywords'."
11264 (interactive "P")
11265 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11266 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
11267 'region-start-level 'region))
11268 org-loop-over-headlines-in-active-region)
11269 (org-map-entries
11270 `(org-todo ,arg)
11271 org-loop-over-headlines-in-active-region
11272 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
11273 (if (equal arg '(16)) (setq arg 'nextset))
11274 (let ((org-blocker-hook org-blocker-hook)
11275 (case-fold-search nil))
11276 (when (equal arg '(64))
11277 (setq arg nil org-blocker-hook nil))
11278 (when (and org-blocker-hook
11279 (or org-inhibit-blocking
11280 (org-entry-get nil "NOBLOCKING")))
11281 (setq org-blocker-hook nil))
11282 (save-excursion
11283 (catch 'exit
11284 (org-back-to-heading t)
11285 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
11286 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
11287 (looking-at "\\(?: *\\|[ \t]*$\\)"))
11288 (let* ((match-data (match-data))
11289 (startpos (point-at-bol))
11290 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
11291 (org-log-done org-log-done)
11292 (org-log-repeat org-log-repeat)
11293 (org-todo-log-states org-todo-log-states)
11294 (org-inhibit-logging
11295 (if (equal arg 0)
11296 (progn (setq arg nil) 'note) org-inhibit-logging))
11297 (this (match-string 1))
11298 (hl-pos (match-beginning 0))
11299 (head (org-get-todo-sequence-head this))
11300 (ass (assoc head org-todo-kwd-alist))
11301 (interpret (nth 1 ass))
11302 (done-word (nth 3 ass))
11303 (final-done-word (nth 4 ass))
11304 (org-last-state (or this ""))
11305 (completion-ignore-case t)
11306 (member (member this org-todo-keywords-1))
11307 (tail (cdr member))
11308 (org-state (cond
11309 ((and org-todo-key-trigger
11310 (or (and (equal arg '(4))
11311 (eq org-use-fast-todo-selection 'prefix))
11312 (and (not arg) org-use-fast-todo-selection
11313 (not (eq org-use-fast-todo-selection
11314 'prefix)))))
11315 ;; Use fast selection
11316 (org-fast-todo-selection))
11317 ((and (equal arg '(4))
11318 (or (not org-use-fast-todo-selection)
11319 (not org-todo-key-trigger)))
11320 ;; Read a state with completion
11321 (org-icompleting-read
11322 "State: " (mapcar (lambda(x) (list x))
11323 org-todo-keywords-1)
11324 nil t))
11325 ((eq arg 'right)
11326 (if this
11327 (if tail (car tail) nil)
11328 (car org-todo-keywords-1)))
11329 ((eq arg 'left)
11330 (if (equal member org-todo-keywords-1)
11332 (if this
11333 (nth (- (length org-todo-keywords-1)
11334 (length tail) 2)
11335 org-todo-keywords-1)
11336 (org-last org-todo-keywords-1))))
11337 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
11338 (setq arg nil))) ; hack to fall back to cycling
11339 (arg
11340 ;; user or caller requests a specific state
11341 (cond
11342 ((equal arg "") nil)
11343 ((eq arg 'none) nil)
11344 ((eq arg 'done) (or done-word (car org-done-keywords)))
11345 ((eq arg 'nextset)
11346 (or (car (cdr (member head org-todo-heads)))
11347 (car org-todo-heads)))
11348 ((eq arg 'previousset)
11349 (let ((org-todo-heads (reverse org-todo-heads)))
11350 (or (car (cdr (member head org-todo-heads)))
11351 (car org-todo-heads))))
11352 ((car (member arg org-todo-keywords-1)))
11353 ((stringp arg)
11354 (error "State `%s' not valid in this file" arg))
11355 ((nth (1- (prefix-numeric-value arg))
11356 org-todo-keywords-1))))
11357 ((null member) (or head (car org-todo-keywords-1)))
11358 ((equal this final-done-word) nil) ;; -> make empty
11359 ((null tail) nil) ;; -> first entry
11360 ((memq interpret '(type priority))
11361 (if (eq this-command last-command)
11362 (car tail)
11363 (if (> (length tail) 0)
11364 (or done-word (car org-done-keywords))
11365 nil)))
11367 (car tail))))
11368 (org-state (or
11369 (run-hook-with-args-until-success
11370 'org-todo-get-default-hook org-state org-last-state)
11371 org-state))
11372 (next (if org-state (concat " " org-state " ") " "))
11373 (change-plist (list :type 'todo-state-change :from this :to org-state
11374 :position startpos))
11375 dolog now-done-p)
11376 (when org-blocker-hook
11377 (setq org-last-todo-state-is-todo
11378 (not (member this org-done-keywords)))
11379 (unless (save-excursion
11380 (save-match-data
11381 (org-with-wide-buffer
11382 (run-hook-with-args-until-failure
11383 'org-blocker-hook change-plist))))
11384 (if (org-called-interactively-p 'interactive)
11385 (error "TODO state change from %s to %s blocked" this org-state)
11386 ;; fail silently
11387 (message "TODO state change from %s to %s blocked" this org-state)
11388 (throw 'exit nil))))
11389 (store-match-data match-data)
11390 (replace-match next t t)
11391 (unless (pos-visible-in-window-p hl-pos)
11392 (message "TODO state changed to %s" (org-trim next)))
11393 (unless head
11394 (setq head (org-get-todo-sequence-head org-state)
11395 ass (assoc head org-todo-kwd-alist)
11396 interpret (nth 1 ass)
11397 done-word (nth 3 ass)
11398 final-done-word (nth 4 ass)))
11399 (when (memq arg '(nextset previousset))
11400 (message "Keyword-Set %d/%d: %s"
11401 (- (length org-todo-sets) -1
11402 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
11403 (length org-todo-sets)
11404 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
11405 (setq org-last-todo-state-is-todo
11406 (not (member org-state org-done-keywords)))
11407 (setq now-done-p (and (member org-state org-done-keywords)
11408 (not (member this org-done-keywords))))
11409 (and logging (org-local-logging logging))
11410 (when (and (or org-todo-log-states org-log-done)
11411 (not (eq org-inhibit-logging t))
11412 (not (memq arg '(nextset previousset))))
11413 ;; we need to look at recording a time and note
11414 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
11415 (nth 2 (assoc this org-todo-log-states))))
11416 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
11417 (setq dolog 'time))
11418 (when (and org-state
11419 (member org-state org-not-done-keywords)
11420 (not (member this org-not-done-keywords)))
11421 ;; This is now a todo state and was not one before
11422 ;; If there was a CLOSED time stamp, get rid of it.
11423 (org-add-planning-info nil nil 'closed))
11424 (when (and now-done-p org-log-done)
11425 ;; It is now done, and it was not done before
11426 (org-add-planning-info 'closed (org-current-effective-time))
11427 (if (and (not dolog) (eq 'note org-log-done))
11428 (org-add-log-setup 'done org-state this 'findpos 'note)))
11429 (when (and org-state dolog)
11430 ;; This is a non-nil state, and we need to log it
11431 (org-add-log-setup 'state org-state this 'findpos dolog)))
11432 ;; Fixup tag positioning
11433 (org-todo-trigger-tag-changes org-state)
11434 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
11435 (when org-provide-todo-statistics
11436 (org-update-parent-todo-statistics))
11437 (run-hooks 'org-after-todo-state-change-hook)
11438 (if (and arg (not (member org-state org-done-keywords)))
11439 (setq head (org-get-todo-sequence-head org-state)))
11440 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
11441 ;; Do we need to trigger a repeat?
11442 (when now-done-p
11443 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
11444 ;; This is for the agenda, take a snapshot of the headline.
11445 (save-match-data
11446 (setq org-agenda-headline-snapshot-before-repeat
11447 (org-get-heading))))
11448 (org-auto-repeat-maybe org-state))
11449 ;; Fixup cursor location if close to the keyword
11450 (if (and (outline-on-heading-p)
11451 (not (bolp))
11452 (save-excursion (beginning-of-line 1)
11453 (looking-at org-todo-line-regexp))
11454 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
11455 (progn
11456 (goto-char (or (match-end 2) (match-end 1)))
11457 (and (looking-at " ") (just-one-space))))
11458 (when org-trigger-hook
11459 (save-excursion
11460 (run-hook-with-args 'org-trigger-hook change-plist)))))))))
11462 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
11463 "Block turning an entry into a TODO, using the hierarchy.
11464 This checks whether the current task should be blocked from state
11465 changes. Such blocking occurs when:
11467 1. The task has children which are not all in a completed state.
11469 2. A task has a parent with the property :ORDERED:, and there
11470 are siblings prior to the current task with incomplete
11471 status.
11473 3. The parent of the task is blocked because it has siblings that should
11474 be done first, or is child of a block grandparent TODO entry."
11476 (if (not org-enforce-todo-dependencies)
11477 t ; if locally turned off don't block
11478 (catch 'dont-block
11479 ;; If this is not a todo state change, or if this entry is already DONE,
11480 ;; do not block
11481 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11482 (member (plist-get change-plist :from)
11483 (cons 'done org-done-keywords))
11484 (member (plist-get change-plist :to)
11485 (cons 'todo org-not-done-keywords))
11486 (not (plist-get change-plist :to)))
11487 (throw 'dont-block t))
11488 ;; If this task has children, and any are undone, it's blocked
11489 (save-excursion
11490 (org-back-to-heading t)
11491 (let ((this-level (funcall outline-level)))
11492 (outline-next-heading)
11493 (let ((child-level (funcall outline-level)))
11494 (while (and (not (eobp))
11495 (> child-level this-level))
11496 ;; this todo has children, check whether they are all
11497 ;; completed
11498 (if (and (not (org-entry-is-done-p))
11499 (org-entry-is-todo-p))
11500 (throw 'dont-block nil))
11501 (outline-next-heading)
11502 (setq child-level (funcall outline-level))))))
11503 ;; Otherwise, if the task's parent has the :ORDERED: property, and
11504 ;; any previous siblings are undone, it's blocked
11505 (save-excursion
11506 (org-back-to-heading t)
11507 (let* ((pos (point))
11508 (parent-pos (and (org-up-heading-safe) (point))))
11509 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11510 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11511 (forward-line 1)
11512 (re-search-forward org-not-done-heading-regexp pos t))
11513 (throw 'dont-block nil)) ; block, there is an older sibling not done.
11514 ;; Search further up the hierarchy, to see if an ancestor is blocked
11515 (while t
11516 (goto-char parent-pos)
11517 (if (not (looking-at org-not-done-heading-regexp))
11518 (throw 'dont-block t)) ; do not block, parent is not a TODO
11519 (setq pos (point))
11520 (setq parent-pos (and (org-up-heading-safe) (point)))
11521 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11522 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11523 (forward-line 1)
11524 (re-search-forward org-not-done-heading-regexp pos t))
11525 (throw 'dont-block nil)))))))) ; block, older sibling not done.
11527 (defcustom org-track-ordered-property-with-tag nil
11528 "Should the ORDERED property also be shown as a tag?
11529 The ORDERED property decides if an entry should require subtasks to be
11530 completed in sequence. Since a property is not very visible, setting
11531 this option means that toggling the ORDERED property with the command
11532 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
11533 not relevant for the behavior, but it makes things more visible.
11535 Note that toggling the tag with tags commands will not change the property
11536 and therefore not influence behavior!
11538 This can be t, meaning the tag ORDERED should be used, It can also be a
11539 string to select a different tag for this task."
11540 :group 'org-todo
11541 :type '(choice
11542 (const :tag "No tracking" nil)
11543 (const :tag "Track with ORDERED tag" t)
11544 (string :tag "Use other tag")))
11546 (defun org-toggle-ordered-property ()
11547 "Toggle the ORDERED property of the current entry.
11548 For better visibility, you can track the value of this property with a tag.
11549 See variable `org-track-ordered-property-with-tag'."
11550 (interactive)
11551 (let* ((t1 org-track-ordered-property-with-tag)
11552 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
11553 (save-excursion
11554 (org-back-to-heading)
11555 (if (org-entry-get nil "ORDERED")
11556 (progn
11557 (org-delete-property "ORDERED")
11558 (and tag (org-toggle-tag tag 'off))
11559 (message "Subtasks can be completed in arbitrary order"))
11560 (org-entry-put nil "ORDERED" "t")
11561 (and tag (org-toggle-tag tag 'on))
11562 (message "Subtasks must be completed in sequence")))))
11564 (defvar org-blocked-by-checkboxes) ; dynamically scoped
11565 (defun org-block-todo-from-checkboxes (change-plist)
11566 "Block turning an entry into a TODO, using checkboxes.
11567 This checks whether the current task should be blocked from state
11568 changes because there are unchecked boxes in this entry."
11569 (if (not org-enforce-todo-checkbox-dependencies)
11570 t ; if locally turned off don't block
11571 (catch 'dont-block
11572 ;; If this is not a todo state change, or if this entry is already DONE,
11573 ;; do not block
11574 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11575 (member (plist-get change-plist :from)
11576 (cons 'done org-done-keywords))
11577 (member (plist-get change-plist :to)
11578 (cons 'todo org-not-done-keywords))
11579 (not (plist-get change-plist :to)))
11580 (throw 'dont-block t))
11581 ;; If this task has checkboxes that are not checked, it's blocked
11582 (save-excursion
11583 (org-back-to-heading t)
11584 (let ((beg (point)) end)
11585 (outline-next-heading)
11586 (setq end (point))
11587 (goto-char beg)
11588 (if (org-list-search-forward
11589 (concat (org-item-beginning-re)
11590 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
11591 "\\[[- ]\\]")
11592 end t)
11593 (progn
11594 (if (boundp 'org-blocked-by-checkboxes)
11595 (setq org-blocked-by-checkboxes t))
11596 (throw 'dont-block nil)))))
11597 t))) ; do not block
11599 (defun org-entry-blocked-p ()
11600 "Is the current entry blocked?"
11601 (if (org-entry-get nil "NOBLOCKING")
11602 nil ;; Never block this entry
11603 (not
11604 (run-hook-with-args-until-failure
11605 'org-blocker-hook
11606 (list :type 'todo-state-change
11607 :position (point)
11608 :from 'todo
11609 :to 'done)))))
11611 (defun org-update-statistics-cookies (all)
11612 "Update the statistics cookie, either from TODO or from checkboxes.
11613 This should be called with the cursor in a line with a statistics cookie."
11614 (interactive "P")
11615 (if all
11616 (progn
11617 (org-update-checkbox-count 'all)
11618 (org-map-entries 'org-update-parent-todo-statistics))
11619 (if (not (org-at-heading-p))
11620 (org-update-checkbox-count)
11621 (let ((pos (move-marker (make-marker) (point)))
11622 end l1 l2)
11623 (ignore-errors (org-back-to-heading t))
11624 (if (not (org-at-heading-p))
11625 (org-update-checkbox-count)
11626 (setq l1 (org-outline-level))
11627 (setq end (save-excursion
11628 (outline-next-heading)
11629 (if (org-at-heading-p) (setq l2 (org-outline-level)))
11630 (point)))
11631 (if (and (save-excursion
11632 (re-search-forward
11633 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
11634 (not (save-excursion (re-search-forward
11635 ":COOKIE_DATA:.*\\<todo\\>" end t))))
11636 (org-update-checkbox-count)
11637 (if (and l2 (> l2 l1))
11638 (progn
11639 (goto-char end)
11640 (org-update-parent-todo-statistics))
11641 (goto-char pos)
11642 (beginning-of-line 1)
11643 (while (re-search-forward
11644 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
11645 (point-at-eol) t)
11646 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
11647 (goto-char pos)
11648 (move-marker pos nil)))))
11650 (defvar org-entry-property-inherited-from) ;; defined below
11651 (defun org-update-parent-todo-statistics ()
11652 "Update any statistics cookie in the parent of the current headline.
11653 When `org-hierarchical-todo-statistics' is nil, statistics will cover
11654 the entire subtree and this will travel up the hierarchy and update
11655 statistics everywhere."
11656 (let* ((prop (save-excursion (org-up-heading-safe)
11657 (org-entry-get nil "COOKIE_DATA" 'inherit)))
11658 (recursive (or (not org-hierarchical-todo-statistics)
11659 (and prop (string-match "\\<recursive\\>" prop))))
11660 (lim (or (and prop (marker-position org-entry-property-inherited-from))
11662 (first t)
11663 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
11664 level ltoggle l1 new ndel
11665 (cnt-all 0) (cnt-done 0) is-percent kwd
11666 checkbox-beg ov ovs ove cookie-present)
11667 (catch 'exit
11668 (save-excursion
11669 (beginning-of-line 1)
11670 (setq ltoggle (funcall outline-level))
11671 ;; Three situations are to consider:
11673 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
11674 ;; to the top-level ancestor on the headline;
11676 ;; 2. If parent has "recursive" property, repeat up to the
11677 ;; headline setting that property, taking inheritance into
11678 ;; account;
11680 ;; 3. Else, move up to direct parent and proceed only once.
11681 (while (and (setq level (org-up-heading-safe))
11682 (or recursive first)
11683 (>= (point) lim))
11684 (setq first nil cookie-present nil)
11685 (unless (and level
11686 (not (string-match
11687 "\\<checkbox\\>"
11688 (downcase (or (org-entry-get nil "COOKIE_DATA")
11689 "")))))
11690 (throw 'exit nil))
11691 (while (re-search-forward box-re (point-at-eol) t)
11692 (setq cnt-all 0 cnt-done 0 cookie-present t)
11693 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
11694 (save-match-data
11695 (unless (outline-next-heading) (throw 'exit nil))
11696 (while (and (looking-at org-complex-heading-regexp)
11697 (> (setq l1 (length (match-string 1))) level))
11698 (setq kwd (and (or recursive (= l1 ltoggle))
11699 (match-string 2)))
11700 (if (or (eq org-provide-todo-statistics 'all-headlines)
11701 (and (listp org-provide-todo-statistics)
11702 (or (member kwd org-provide-todo-statistics)
11703 (member kwd org-done-keywords))))
11704 (setq cnt-all (1+ cnt-all))
11705 (if (eq org-provide-todo-statistics t)
11706 (and kwd (setq cnt-all (1+ cnt-all)))))
11707 (and (member kwd org-done-keywords)
11708 (setq cnt-done (1+ cnt-done)))
11709 (outline-next-heading)))
11710 (setq new
11711 (if is-percent
11712 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
11713 (format "[%d/%d]" cnt-done cnt-all))
11714 ndel (- (match-end 0) checkbox-beg))
11715 ;; handle overlays when updating cookie from column view
11716 (when (setq ov (car (overlays-at checkbox-beg)))
11717 (setq ovs (overlay-start ov) ove (overlay-end ov))
11718 (delete-overlay ov))
11719 (goto-char checkbox-beg)
11720 (insert new)
11721 (delete-region (point) (+ (point) ndel))
11722 (when org-auto-align-tags (org-fix-tags-on-the-fly))
11723 (when ov (move-overlay ov ovs ove)))
11724 (when cookie-present
11725 (run-hook-with-args 'org-after-todo-statistics-hook
11726 cnt-done (- cnt-all cnt-done))))))
11727 (run-hooks 'org-todo-statistics-hook)))
11729 (defvar org-after-todo-statistics-hook nil
11730 "Hook that is called after a TODO statistics cookie has been updated.
11731 Each function is called with two arguments: the number of not-done entries
11732 and the number of done entries.
11734 For example, the following function, when added to this hook, will switch
11735 an entry to DONE when all children are done, and back to TODO when new
11736 entries are set to a TODO status. Note that this hook is only called
11737 when there is a statistics cookie in the headline!
11739 (defun org-summary-todo (n-done n-not-done)
11740 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
11741 (let (org-log-done org-log-states) ; turn off logging
11742 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
11745 (defvar org-todo-statistics-hook nil
11746 "Hook that is run whenever Org thinks TODO statistics should be updated.
11747 This hook runs even if there is no statistics cookie present, in which case
11748 `org-after-todo-statistics-hook' would not run.")
11750 (defun org-todo-trigger-tag-changes (state)
11751 "Apply the changes defined in `org-todo-state-tags-triggers'."
11752 (let ((l org-todo-state-tags-triggers)
11753 changes)
11754 (when (or (not state) (equal state ""))
11755 (setq changes (append changes (cdr (assoc "" l)))))
11756 (when (and (stringp state) (> (length state) 0))
11757 (setq changes (append changes (cdr (assoc state l)))))
11758 (when (member state org-not-done-keywords)
11759 (setq changes (append changes (cdr (assoc 'todo l)))))
11760 (when (member state org-done-keywords)
11761 (setq changes (append changes (cdr (assoc 'done l)))))
11762 (dolist (c changes)
11763 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
11765 (defun org-local-logging (value)
11766 "Get logging settings from a property VALUE."
11767 (let* (words w a)
11768 ;; directly set the variables, they are already local.
11769 (setq org-log-done nil
11770 org-log-repeat nil
11771 org-todo-log-states nil)
11772 (setq words (org-split-string value))
11773 (while (setq w (pop words))
11774 (cond
11775 ((setq a (assoc w org-startup-options))
11776 (and (member (nth 1 a) '(org-log-done org-log-repeat))
11777 (set (nth 1 a) (nth 2 a))))
11778 ((setq a (org-extract-log-state-settings w))
11779 (and (member (car a) org-todo-keywords-1)
11780 (push a org-todo-log-states)))))))
11782 (defun org-get-todo-sequence-head (kwd)
11783 "Return the head of the TODO sequence to which KWD belongs.
11784 If KWD is not set, check if there is a text property remembering the
11785 right sequence."
11786 (let (p)
11787 (cond
11788 ((not kwd)
11789 (or (get-text-property (point-at-bol) 'org-todo-head)
11790 (progn
11791 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
11792 nil (point-at-eol)))
11793 (get-text-property p 'org-todo-head))))
11794 ((not (member kwd org-todo-keywords-1))
11795 (car org-todo-keywords-1))
11796 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
11798 (defun org-fast-todo-selection ()
11799 "Fast TODO keyword selection with single keys.
11800 Returns the new TODO keyword, or nil if no state change should occur."
11801 (let* ((fulltable org-todo-key-alist)
11802 (done-keywords org-done-keywords) ;; needed for the faces.
11803 (maxlen (apply 'max (mapcar
11804 (lambda (x)
11805 (if (stringp (car x)) (string-width (car x)) 0))
11806 fulltable)))
11807 (expert nil)
11808 (fwidth (+ maxlen 3 1 3))
11809 (ncol (/ (- (window-width) 4) fwidth))
11810 tg cnt e c tbl
11811 groups ingroup)
11812 (save-excursion
11813 (save-window-excursion
11814 (if expert
11815 (set-buffer (get-buffer-create " *Org todo*"))
11816 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
11817 (erase-buffer)
11818 (org-set-local 'org-done-keywords done-keywords)
11819 (setq tbl fulltable cnt 0)
11820 (while (setq e (pop tbl))
11821 (cond
11822 ((equal e '(:startgroup))
11823 (push '() groups) (setq ingroup t)
11824 (when (not (= cnt 0))
11825 (setq cnt 0)
11826 (insert "\n"))
11827 (insert "{ "))
11828 ((equal e '(:endgroup))
11829 (setq ingroup nil cnt 0)
11830 (insert "}\n"))
11831 ((equal e '(:newline))
11832 (when (not (= cnt 0))
11833 (setq cnt 0)
11834 (insert "\n")
11835 (setq e (car tbl))
11836 (while (equal (car tbl) '(:newline))
11837 (insert "\n")
11838 (setq tbl (cdr tbl)))))
11840 (setq tg (car e) c (cdr e))
11841 (if ingroup (push tg (car groups)))
11842 (setq tg (org-add-props tg nil 'face
11843 (org-get-todo-face tg)))
11844 (if (and (= cnt 0) (not ingroup)) (insert " "))
11845 (insert "[" c "] " tg (make-string
11846 (- fwidth 4 (length tg)) ?\ ))
11847 (when (= (setq cnt (1+ cnt)) ncol)
11848 (insert "\n")
11849 (if ingroup (insert " "))
11850 (setq cnt 0)))))
11851 (insert "\n")
11852 (goto-char (point-min))
11853 (if (not expert) (org-fit-window-to-buffer))
11854 (message "[a-z..]:Set [SPC]:clear")
11855 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
11856 (cond
11857 ((or (= c ?\C-g)
11858 (and (= c ?q) (not (rassoc c fulltable))))
11859 (setq quit-flag t))
11860 ((= c ?\ ) nil)
11861 ((setq e (rassoc c fulltable) tg (car e))
11863 (t (setq quit-flag t)))))))
11865 (defun org-entry-is-todo-p ()
11866 (member (org-get-todo-state) org-not-done-keywords))
11868 (defun org-entry-is-done-p ()
11869 (member (org-get-todo-state) org-done-keywords))
11871 (defun org-get-todo-state ()
11872 (save-excursion
11873 (org-back-to-heading t)
11874 (and (looking-at org-todo-line-regexp)
11875 (match-end 2)
11876 (match-string 2))))
11878 (defun org-at-date-range-p (&optional inactive-ok)
11879 "Is the cursor inside a date range?"
11880 (interactive)
11881 (save-excursion
11882 (catch 'exit
11883 (let ((pos (point)))
11884 (skip-chars-backward "^[<\r\n")
11885 (skip-chars-backward "<[")
11886 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
11887 (>= (match-end 0) pos)
11888 (throw 'exit t))
11889 (skip-chars-backward "^<[\r\n")
11890 (skip-chars-backward "<[")
11891 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
11892 (>= (match-end 0) pos)
11893 (throw 'exit t)))
11894 nil)))
11896 (defun org-get-repeat (&optional tagline)
11897 "Check if there is a deadline/schedule with repeater in this entry."
11898 (save-match-data
11899 (save-excursion
11900 (org-back-to-heading t)
11901 (and (re-search-forward (if tagline
11902 (concat tagline "\\s-*" org-repeat-re)
11903 org-repeat-re)
11904 (org-entry-end-position) t)
11905 (match-string-no-properties 1)))))
11907 (defvar org-last-changed-timestamp)
11908 (defvar org-last-inserted-timestamp)
11909 (defvar org-log-post-message)
11910 (defvar org-log-note-purpose)
11911 (defvar org-log-note-how)
11912 (defvar org-log-note-extra)
11913 (defun org-auto-repeat-maybe (done-word)
11914 "Check if the current headline contains a repeated deadline/schedule.
11915 If yes, set TODO state back to what it was and change the base date
11916 of repeating deadline/scheduled time stamps to new date.
11917 This function is run automatically after each state change to a DONE state."
11918 ;; last-state is dynamically scoped into this function
11919 (let* ((repeat (org-get-repeat))
11920 (aa (assoc org-last-state org-todo-kwd-alist))
11921 (interpret (nth 1 aa))
11922 (head (nth 2 aa))
11923 (whata '(("d" . day) ("m" . month) ("y" . year)))
11924 (msg "Entry repeats: ")
11925 (org-log-done nil)
11926 (org-todo-log-states nil)
11927 re type n what ts time to-state)
11928 (when repeat
11929 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
11930 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
11931 org-todo-repeat-to-state))
11932 (unless (and to-state (member to-state org-todo-keywords-1))
11933 (setq to-state (if (eq interpret 'type) org-last-state head)))
11934 (org-todo to-state)
11935 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
11936 (org-entry-put nil "LAST_REPEAT" (format-time-string
11937 (org-time-stamp-format t t))))
11938 (when org-log-repeat
11939 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
11940 (memq 'org-add-log-note post-command-hook))
11941 ;; OK, we are already setup for some record
11942 (if (eq org-log-repeat 'note)
11943 ;; make sure we take a note, not only a time stamp
11944 (setq org-log-note-how 'note))
11945 ;; Set up for taking a record
11946 (org-add-log-setup 'state (or done-word (car org-done-keywords))
11947 org-last-state
11948 'findpos org-log-repeat)))
11949 (org-back-to-heading t)
11950 (org-add-planning-info nil nil 'closed)
11951 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
11952 org-deadline-time-regexp "\\)\\|\\("
11953 org-ts-regexp "\\)"))
11954 (while (re-search-forward
11955 re (save-excursion (outline-next-heading) (point)) t)
11956 (setq type (if (match-end 1) org-scheduled-string
11957 (if (match-end 3) org-deadline-string "Plain:"))
11958 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
11959 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
11960 (setq n (string-to-number (match-string 2 ts))
11961 what (match-string 3 ts))
11962 (if (equal what "w") (setq n (* n 7) what "d"))
11963 ;; Preparation, see if we need to modify the start date for the change
11964 (when (match-end 1)
11965 (setq time (save-match-data (org-time-string-to-time ts)))
11966 (cond
11967 ((equal (match-string 1 ts) ".")
11968 ;; Shift starting date to today
11969 (org-timestamp-change
11970 (- (org-today) (time-to-days time))
11971 'day))
11972 ((equal (match-string 1 ts) "+")
11973 (let ((nshiftmax 10) (nshift 0))
11974 (while (or (= nshift 0)
11975 (<= (time-to-days time)
11976 (time-to-days (current-time))))
11977 (when (= (incf nshift) nshiftmax)
11978 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
11979 (error "Abort")))
11980 (org-timestamp-change n (cdr (assoc what whata)))
11981 (org-at-timestamp-p t)
11982 (setq ts (match-string 1))
11983 (setq time (save-match-data (org-time-string-to-time ts)))))
11984 (org-timestamp-change (- n) (cdr (assoc what whata)))
11985 ;; rematch, so that we have everything in place for the real shift
11986 (org-at-timestamp-p t)
11987 (setq ts (match-string 1))
11988 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
11989 (org-timestamp-change n (cdr (assoc what whata)))
11990 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
11991 (setq org-log-post-message msg)
11992 (message "%s" msg))))
11994 (defun org-show-todo-tree (arg)
11995 "Make a compact tree which shows all headlines marked with TODO.
11996 The tree will show the lines where the regexp matches, and all higher
11997 headlines above the match.
11998 With a \\[universal-argument] prefix, prompt for a regexp to match.
11999 With a numeric prefix N, construct a sparse tree for the Nth element
12000 of `org-todo-keywords-1'."
12001 (interactive "P")
12002 (let ((case-fold-search nil)
12003 (kwd-re
12004 (cond ((null arg) org-not-done-regexp)
12005 ((equal arg '(4))
12006 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12007 (mapcar 'list org-todo-keywords-1))))
12008 (concat "\\("
12009 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12010 "\\)\\>")))
12011 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12012 (regexp-quote (nth (1- (prefix-numeric-value arg))
12013 org-todo-keywords-1)))
12014 (t (error "Invalid prefix argument: %s" arg)))))
12015 (message "%d TODO entries found"
12016 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12018 (defun org-deadline (&optional remove time)
12019 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12020 With argument REMOVE, remove any deadline from the item.
12021 With argument TIME, set the deadline at the corresponding date. TIME
12022 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12023 (interactive "P")
12024 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12025 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12026 'region-start-level 'region))
12027 org-loop-over-headlines-in-active-region)
12028 (org-map-entries
12029 `(org-deadline ',remove ,time)
12030 org-loop-over-headlines-in-active-region
12031 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12032 (let* ((old-date (org-entry-get nil "DEADLINE"))
12033 (repeater (and old-date
12034 (string-match
12035 "\\([.+-]+[0-9]+[dwmy]\\(?:[/ ][-+]?[0-9]+[dwmy]\\)?\\) ?"
12036 old-date)
12037 (match-string 1 old-date))))
12038 (if remove
12039 (progn
12040 (when (and old-date org-log-redeadline)
12041 (org-add-log-setup 'deldeadline nil old-date 'findpos
12042 org-log-redeadline))
12043 (org-remove-timestamp-with-keyword org-deadline-string)
12044 (message "Item no longer has a deadline."))
12045 (org-add-planning-info 'deadline time 'closed)
12046 (when (and old-date org-log-redeadline
12047 (not (equal old-date
12048 (substring org-last-inserted-timestamp 1 -1))))
12049 (org-add-log-setup 'redeadline nil old-date 'findpos
12050 org-log-redeadline))
12051 (when repeater
12052 (save-excursion
12053 (org-back-to-heading t)
12054 (when (re-search-forward (concat org-deadline-string " "
12055 org-last-inserted-timestamp)
12056 (save-excursion
12057 (outline-next-heading) (point)) t)
12058 (goto-char (1- (match-end 0)))
12059 (insert " " repeater)
12060 (setq org-last-inserted-timestamp
12061 (concat (substring org-last-inserted-timestamp 0 -1)
12062 " " repeater
12063 (substring org-last-inserted-timestamp -1))))))
12064 (message "Deadline on %s" org-last-inserted-timestamp)))))
12066 (defun org-schedule (&optional remove time)
12067 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12068 With argument REMOVE, remove any scheduling date from the item.
12069 With argument TIME, scheduled at the corresponding date. TIME can
12070 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12071 (interactive "P")
12072 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12073 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12074 'region-start-level 'region))
12075 org-loop-over-headlines-in-active-region)
12076 (org-map-entries
12077 `(org-schedule ',remove ,time)
12078 org-loop-over-headlines-in-active-region
12079 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12080 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12081 (repeater (and old-date
12082 (string-match
12083 "\\([.+-]+[0-9]+[dwmy]\\(?:[/ ][-+]?[0-9]+[dwmy]\\)?\\) ?"
12084 old-date)
12085 (match-string 1 old-date))))
12086 (if remove
12087 (progn
12088 (when (and old-date org-log-reschedule)
12089 (org-add-log-setup 'delschedule nil old-date 'findpos
12090 org-log-reschedule))
12091 (org-remove-timestamp-with-keyword org-scheduled-string)
12092 (message "Item is no longer scheduled."))
12093 (org-add-planning-info 'scheduled time 'closed)
12094 (when (and old-date org-log-reschedule
12095 (not (equal old-date
12096 (substring org-last-inserted-timestamp 1 -1))))
12097 (org-add-log-setup 'reschedule nil old-date 'findpos
12098 org-log-reschedule))
12099 (when repeater
12100 (save-excursion
12101 (org-back-to-heading t)
12102 (when (re-search-forward (concat org-scheduled-string " "
12103 org-last-inserted-timestamp)
12104 (save-excursion
12105 (outline-next-heading) (point)) t)
12106 (goto-char (1- (match-end 0)))
12107 (insert " " repeater)
12108 (setq org-last-inserted-timestamp
12109 (concat (substring org-last-inserted-timestamp 0 -1)
12110 " " repeater
12111 (substring org-last-inserted-timestamp -1))))))
12112 (message "Scheduled to %s" org-last-inserted-timestamp)))))
12114 (defun org-get-scheduled-time (pom &optional inherit)
12115 "Get the scheduled time as a time tuple, of a format suitable
12116 for calling org-schedule with, or if there is no scheduling,
12117 returns nil."
12118 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12119 (when time
12120 (apply 'encode-time (org-parse-time-string time)))))
12122 (defun org-get-deadline-time (pom &optional inherit)
12123 "Get the deadline as a time tuple, of a format suitable for
12124 calling org-deadline with, or if there is no scheduling, returns
12125 nil."
12126 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12127 (when time
12128 (apply 'encode-time (org-parse-time-string time)))))
12130 (defun org-remove-timestamp-with-keyword (keyword)
12131 "Remove all time stamps with KEYWORD in the current entry."
12132 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12133 beg)
12134 (save-excursion
12135 (org-back-to-heading t)
12136 (setq beg (point))
12137 (outline-next-heading)
12138 (while (re-search-backward re beg t)
12139 (replace-match "")
12140 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12141 (equal (char-before) ?\ ))
12142 (backward-delete-char 1)
12143 (if (string-match "^[ \t]*$" (buffer-substring
12144 (point-at-bol) (point-at-eol)))
12145 (delete-region (point-at-bol)
12146 (min (point-max) (1+ (point-at-eol))))))))))
12148 (defun org-add-planning-info (what &optional time &rest remove)
12149 "Insert new timestamp with keyword in the line directly after the headline.
12150 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
12151 If non is given, the user is prompted for a date.
12152 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
12153 be removed."
12154 (interactive)
12155 (let (org-time-was-given org-end-time-was-given ts
12156 end default-time default-input)
12158 (catch 'exit
12159 (when (and (memq what '(scheduled deadline))
12160 (or (not time)
12161 (and (stringp time)
12162 (string-match "^[-+]+[0-9]" time))))
12163 ;; Try to get a default date/time from existing timestamp
12164 (save-excursion
12165 (org-back-to-heading t)
12166 (setq end (save-excursion (outline-next-heading) (point)))
12167 (when (re-search-forward (if (eq what 'scheduled)
12168 org-scheduled-time-regexp
12169 org-deadline-time-regexp)
12170 end t)
12171 (setq ts (match-string 1)
12172 default-time
12173 (apply 'encode-time (org-parse-time-string ts))
12174 default-input (and ts (org-get-compact-tod ts))))))
12175 (when what
12176 (setq time
12177 (if (stringp time)
12178 ;; This is a string (relative or absolute), set proper date
12179 (apply 'encode-time
12180 (org-read-date-analyze
12181 time default-time (decode-time default-time)))
12182 ;; If necessary, get the time from the user
12183 (or time (org-read-date nil 'to-time nil nil
12184 default-time default-input)))))
12186 (when (and org-insert-labeled-timestamps-at-point
12187 (member what '(scheduled deadline)))
12188 (insert
12189 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
12190 (org-insert-time-stamp time org-time-was-given
12191 nil nil nil (list org-end-time-was-given))
12192 (setq what nil))
12193 (save-excursion
12194 (save-restriction
12195 (let (col list elt ts buffer-invisibility-spec)
12196 (org-back-to-heading t)
12197 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
12198 (goto-char (match-end 1))
12199 (setq col (current-column))
12200 (goto-char (match-end 0))
12201 (if (eobp) (insert "\n") (forward-char 1))
12202 (when (and (not what)
12203 (not (looking-at
12204 (concat "[ \t]*"
12205 org-keyword-time-not-clock-regexp))))
12206 ;; Nothing to add, nothing to remove...... :-)
12207 (throw 'exit nil))
12208 (if (and (not (looking-at org-outline-regexp))
12209 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
12210 "[^\r\n]*"))
12211 (not (equal (match-string 1) org-clock-string)))
12212 (narrow-to-region (match-beginning 0) (match-end 0))
12213 (insert-before-markers "\n")
12214 (backward-char 1)
12215 (narrow-to-region (point) (point))
12216 (and org-adapt-indentation (org-indent-to-column col)))
12217 ;; Check if we have to remove something.
12218 (setq list (cons what remove))
12219 (while list
12220 (setq elt (pop list))
12221 (when (or (and (eq elt 'scheduled)
12222 (re-search-forward org-scheduled-time-regexp nil t))
12223 (and (eq elt 'deadline)
12224 (re-search-forward org-deadline-time-regexp nil t))
12225 (and (eq elt 'closed)
12226 (re-search-forward org-closed-time-regexp nil t)))
12227 (replace-match "")
12228 (if (looking-at "--+<[^>]+>") (replace-match ""))))
12229 (and (looking-at "[ \t]+") (replace-match ""))
12230 (and org-adapt-indentation (bolp) (org-indent-to-column col))
12231 (when what
12232 (insert
12233 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
12234 (cond ((eq what 'scheduled) org-scheduled-string)
12235 ((eq what 'deadline) org-deadline-string)
12236 ((eq what 'closed) org-closed-string))
12237 " ")
12238 (setq ts (org-insert-time-stamp
12239 time
12240 (or org-time-was-given
12241 (and (eq what 'closed) org-log-done-with-time))
12242 (eq what 'closed)
12243 nil nil (list org-end-time-was-given)))
12244 (insert
12245 (if (not (or (bolp) (eq (char-before) ?\ )
12246 (memq (char-after) '(32 10))
12247 (eobp))) " " ""))
12248 (end-of-line 1))
12249 (goto-char (point-min))
12250 (widen)
12251 (if (and (looking-at "[ \t]*\n")
12252 (equal (char-before) ?\n))
12253 (delete-region (1- (point)) (point-at-eol)))
12254 ts))))))
12256 (defvar org-log-note-marker (make-marker))
12257 (defvar org-log-note-purpose nil)
12258 (defvar org-log-note-state nil)
12259 (defvar org-log-note-previous-state nil)
12260 (defvar org-log-note-how nil)
12261 (defvar org-log-note-extra nil)
12262 (defvar org-log-note-window-configuration nil)
12263 (defvar org-log-note-return-to (make-marker))
12264 (defvar org-log-note-effective-time nil
12265 "Remembered current time so that dynamically scoped
12266 `org-extend-today-until' affects tha timestamps in state change
12267 log")
12269 (defvar org-log-post-message nil
12270 "Message to be displayed after a log note has been stored.
12271 The auto-repeater uses this.")
12273 (defun org-add-note ()
12274 "Add a note to the current entry.
12275 This is done in the same way as adding a state change note."
12276 (interactive)
12277 (org-add-log-setup 'note nil nil 'findpos nil))
12279 (defvar org-property-end-re)
12280 (defun org-add-log-setup (&optional purpose state prev-state
12281 findpos how extra)
12282 "Set up the post command hook to take a note.
12283 If this is about to TODO state change, the new state is expected in STATE.
12284 When FINDPOS is non-nil, find the correct position for the note in
12285 the current entry. If not, assume that it can be inserted at point.
12286 HOW is an indicator what kind of note should be created.
12287 EXTRA is additional text that will be inserted into the notes buffer."
12288 (let* ((org-log-into-drawer (org-log-into-drawer))
12289 (drawer (cond ((stringp org-log-into-drawer)
12290 org-log-into-drawer)
12291 (org-log-into-drawer "LOGBOOK")
12292 (t nil))))
12293 (save-restriction
12294 (save-excursion
12295 (when findpos
12296 (org-back-to-heading t)
12297 (narrow-to-region (point) (save-excursion
12298 (outline-next-heading) (point)))
12299 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
12300 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
12301 "[^\r\n]*\\)?"))
12302 (goto-char (match-end 0))
12303 (cond
12304 (drawer
12305 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
12306 nil t)
12307 (progn
12308 (goto-char (match-end 0))
12309 (or org-log-states-order-reversed
12310 (and (re-search-forward org-property-end-re nil t)
12311 (goto-char (1- (match-beginning 0))))))
12312 (insert "\n:" drawer ":\n:END:")
12313 (beginning-of-line 0)
12314 (org-indent-line-function)
12315 (beginning-of-line 2)
12316 (org-indent-line-function)
12317 (end-of-line 0)))
12318 ((and org-log-state-notes-insert-after-drawers
12319 (save-excursion
12320 (forward-line) (looking-at org-drawer-regexp)))
12321 (forward-line)
12322 (while (looking-at org-drawer-regexp)
12323 (goto-char (match-end 0))
12324 (re-search-forward org-property-end-re (point-max) t)
12325 (forward-line))
12326 (forward-line -1)))
12327 (unless org-log-states-order-reversed
12328 (and (= (char-after) ?\n) (forward-char 1))
12329 (org-skip-over-state-notes)
12330 (skip-chars-backward " \t\n\r")))
12331 (move-marker org-log-note-marker (point))
12332 (setq org-log-note-purpose purpose
12333 org-log-note-state state
12334 org-log-note-previous-state prev-state
12335 org-log-note-how how
12336 org-log-note-extra extra
12337 org-log-note-effective-time (org-current-effective-time))
12338 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
12340 (defun org-skip-over-state-notes ()
12341 "Skip past the list of State notes in an entry."
12342 (if (looking-at "\n[ \t]*- State") (forward-char 1))
12343 (when (ignore-errors (goto-char (org-in-item-p)))
12344 (let* ((struct (org-list-struct))
12345 (prevs (org-list-prevs-alist struct)))
12346 (while (looking-at "[ \t]*- State")
12347 (goto-char (or (org-list-get-next-item (point) struct prevs)
12348 (org-list-get-item-end (point) struct)))))))
12350 (defun org-add-log-note (&optional purpose)
12351 "Pop up a window for taking a note, and add this note later at point."
12352 (remove-hook 'post-command-hook 'org-add-log-note)
12353 (setq org-log-note-window-configuration (current-window-configuration))
12354 (delete-other-windows)
12355 (move-marker org-log-note-return-to (point))
12356 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
12357 (goto-char org-log-note-marker)
12358 (org-switch-to-buffer-other-window "*Org Note*")
12359 (erase-buffer)
12360 (if (memq org-log-note-how '(time state))
12361 (let (current-prefix-arg) (org-store-log-note))
12362 (let ((org-inhibit-startup t)) (org-mode))
12363 (insert (format "# Insert note for %s.
12364 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
12365 (cond
12366 ((eq org-log-note-purpose 'clock-out) "stopped clock")
12367 ((eq org-log-note-purpose 'done) "closed todo item")
12368 ((eq org-log-note-purpose 'state)
12369 (format "state change from \"%s\" to \"%s\""
12370 (or org-log-note-previous-state "")
12371 (or org-log-note-state "")))
12372 ((eq org-log-note-purpose 'reschedule)
12373 "rescheduling")
12374 ((eq org-log-note-purpose 'delschedule)
12375 "no longer scheduled")
12376 ((eq org-log-note-purpose 'redeadline)
12377 "changing deadline")
12378 ((eq org-log-note-purpose 'deldeadline)
12379 "removing deadline")
12380 ((eq org-log-note-purpose 'refile)
12381 "refiling")
12382 ((eq org-log-note-purpose 'note)
12383 "this entry")
12384 (t (error "This should not happen")))))
12385 (if org-log-note-extra (insert org-log-note-extra))
12386 (org-set-local 'org-finish-function 'org-store-log-note)
12387 (run-hooks 'org-log-buffer-setup-hook)))
12389 (defvar org-note-abort nil) ; dynamically scoped
12390 (defun org-store-log-note ()
12391 "Finish taking a log note, and insert it to where it belongs."
12392 (let ((txt (buffer-string))
12393 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
12394 lines ind bul)
12395 (kill-buffer (current-buffer))
12396 (while (string-match "\\`#.*\n[ \t\n]*" txt)
12397 (setq txt (replace-match "" t t txt)))
12398 (if (string-match "\\s-+\\'" txt)
12399 (setq txt (replace-match "" t t txt)))
12400 (setq lines (org-split-string txt "\n"))
12401 (when (and note (string-match "\\S-" note))
12402 (setq note
12403 (org-replace-escapes
12404 note
12405 (list (cons "%u" (user-login-name))
12406 (cons "%U" user-full-name)
12407 (cons "%t" (format-time-string
12408 (org-time-stamp-format 'long 'inactive)
12409 org-log-note-effective-time))
12410 (cons "%T" (format-time-string
12411 (org-time-stamp-format 'long nil)
12412 org-log-note-effective-time))
12413 (cons "%d" (format-time-string
12414 (org-time-stamp-format nil 'inactive)
12415 org-log-note-effective-time))
12416 (cons "%D" (format-time-string
12417 (org-time-stamp-format nil nil)
12418 org-log-note-effective-time))
12419 (cons "%s" (if org-log-note-state
12420 (concat "\"" org-log-note-state "\"")
12421 ""))
12422 (cons "%S" (if org-log-note-previous-state
12423 (concat "\"" org-log-note-previous-state "\"")
12424 "\"\"")))))
12425 (if lines (setq note (concat note " \\\\")))
12426 (push note lines))
12427 (when (or current-prefix-arg org-note-abort)
12428 (when org-log-into-drawer
12429 (org-remove-empty-drawer-at
12430 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
12431 org-log-note-marker))
12432 (setq lines nil))
12433 (when lines
12434 (with-current-buffer (marker-buffer org-log-note-marker)
12435 (save-excursion
12436 (goto-char org-log-note-marker)
12437 (move-marker org-log-note-marker nil)
12438 (end-of-line 1)
12439 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
12440 (setq ind (save-excursion
12441 (if (ignore-errors (goto-char (org-in-item-p)))
12442 (let ((struct (org-list-struct)))
12443 (org-list-get-ind
12444 (org-list-get-top-point struct) struct))
12445 (skip-chars-backward " \r\t\n")
12446 (cond
12447 ((and (org-at-heading-p)
12448 org-adapt-indentation)
12449 (1+ (org-current-level)))
12450 ((org-at-heading-p) 0)
12451 (t (org-get-indentation))))))
12452 (setq bul (org-list-bullet-string "-"))
12453 (org-indent-line-to ind)
12454 (insert bul (pop lines))
12455 (let ((ind-body (+ (length bul) ind)))
12456 (while lines
12457 (insert "\n")
12458 (org-indent-line-to ind-body)
12459 (insert (pop lines))))
12460 (message "Note stored")
12461 (org-back-to-heading t)
12462 (org-cycle-hide-drawers 'children)))))
12463 (set-window-configuration org-log-note-window-configuration)
12464 (with-current-buffer (marker-buffer org-log-note-return-to)
12465 (goto-char org-log-note-return-to))
12466 (move-marker org-log-note-return-to nil)
12467 (and org-log-post-message (message "%s" org-log-post-message)))
12469 (defun org-remove-empty-drawer-at (drawer pos)
12470 "Remove an empty drawer DRAWER at position POS.
12471 POS may also be a marker."
12472 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
12473 (save-excursion
12474 (save-restriction
12475 (widen)
12476 (goto-char pos)
12477 (if (org-in-regexp
12478 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
12479 (replace-match ""))))))
12481 (defun org-sparse-tree (&optional arg)
12482 "Create a sparse tree, prompt for the details.
12483 This command can create sparse trees. You first need to select the type
12484 of match used to create the tree:
12486 t Show all TODO entries.
12487 T Show entries with a specific TODO keyword.
12488 m Show entries selected by a tags/property match.
12489 p Enter a property name and its value (both with completion on existing
12490 names/values) and show entries with that property.
12491 r Show entries matching a regular expression (`/' can be used as well)
12492 d Show deadlines due within `org-deadline-warning-days'.
12493 b Show deadlines and scheduled items before a date.
12494 a Show deadlines and scheduled items after a date."
12495 (interactive "P")
12496 (let (ans kwd value)
12497 (message "Sparse tree: [r]egexp [/]regexp [t]odo [T]odo-kwd [m]atch [p]roperty\n [d]eadlines [b]efore-date [a]fter-date [D]ates range")
12498 (setq ans (read-char-exclusive))
12499 (cond
12500 ((equal ans ?d)
12501 (call-interactively 'org-check-deadlines))
12502 ((equal ans ?b)
12503 (call-interactively 'org-check-before-date))
12504 ((equal ans ?a)
12505 (call-interactively 'org-check-after-date))
12506 ((equal ans ?D)
12507 (call-interactively 'org-check-dates-range))
12508 ((equal ans ?t)
12509 (org-show-todo-tree nil))
12510 ((equal ans ?T)
12511 (org-show-todo-tree '(4)))
12512 ((member ans '(?T ?m))
12513 (call-interactively 'org-match-sparse-tree))
12514 ((member ans '(?p ?P))
12515 (setq kwd (org-icompleting-read "Property: "
12516 (mapcar 'list (org-buffer-property-keys))))
12517 (setq value (org-icompleting-read "Value: "
12518 (mapcar 'list (org-property-values kwd))))
12519 (unless (string-match "\\`{.*}\\'" value)
12520 (setq value (concat "\"" value "\"")))
12521 (org-match-sparse-tree arg (concat kwd "=" value)))
12522 ((member ans '(?r ?R ?/))
12523 (call-interactively 'org-occur))
12524 (t (error "No such sparse tree command \"%c\"" ans)))))
12526 (defvar org-occur-highlights nil
12527 "List of overlays used for occur matches.")
12528 (make-variable-buffer-local 'org-occur-highlights)
12529 (defvar org-occur-parameters nil
12530 "Parameters of the active org-occur calls.
12531 This is a list, each call to org-occur pushes as cons cell,
12532 containing the regular expression and the callback, onto the list.
12533 The list can contain several entries if `org-occur' has been called
12534 several time with the KEEP-PREVIOUS argument. Otherwise, this list
12535 will only contain one set of parameters. When the highlights are
12536 removed (for example with `C-c C-c', or with the next edit (depending
12537 on `org-remove-highlights-with-change'), this variable is emptied
12538 as well.")
12539 (make-variable-buffer-local 'org-occur-parameters)
12541 (defun org-occur (regexp &optional keep-previous callback)
12542 "Make a compact tree which shows all matches of REGEXP.
12543 The tree will show the lines where the regexp matches, and all higher
12544 headlines above the match. It will also show the heading after the match,
12545 to make sure editing the matching entry is easy.
12546 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
12547 call to `org-occur' will be kept, to allow stacking of calls to this
12548 command.
12549 If CALLBACK is non-nil, it is a function which is called to confirm
12550 that the match should indeed be shown."
12551 (interactive "sRegexp: \nP")
12552 (when (equal regexp "")
12553 (error "Regexp cannot be empty"))
12554 (unless keep-previous
12555 (org-remove-occur-highlights nil nil t))
12556 (push (cons regexp callback) org-occur-parameters)
12557 (let ((cnt 0))
12558 (save-excursion
12559 (goto-char (point-min))
12560 (if (or (not keep-previous) ; do not want to keep
12561 (not org-occur-highlights)) ; no previous matches
12562 ;; hide everything
12563 (org-overview))
12564 (while (re-search-forward regexp nil t)
12565 (when (or (not callback)
12566 (save-match-data (funcall callback)))
12567 (setq cnt (1+ cnt))
12568 (when org-highlight-sparse-tree-matches
12569 (org-highlight-new-match (match-beginning 0) (match-end 0)))
12570 (org-show-context 'occur-tree))))
12571 (when org-remove-highlights-with-change
12572 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
12573 nil 'local))
12574 (unless org-sparse-tree-open-archived-trees
12575 (org-hide-archived-subtrees (point-min) (point-max)))
12576 (run-hooks 'org-occur-hook)
12577 (if (org-called-interactively-p 'interactive)
12578 (message "%d match(es) for regexp %s" cnt regexp))
12579 cnt))
12581 (defun org-occur-next-match (&optional n reset)
12582 "Function for `next-error-function' to find sparse tree matches.
12583 N is the number of matches to move, when negative move backwards.
12584 RESET is entirely ignored - this function always goes back to the
12585 starting point when no match is found."
12586 (let* ((limit (if (< n 0) (point-min) (point-max)))
12587 (search-func (if (< n 0)
12588 'previous-single-char-property-change
12589 'next-single-char-property-change))
12590 (n (abs n))
12591 (pos (point))
12593 (catch 'exit
12594 (while (setq p1 (funcall search-func (point) 'org-type))
12595 (when (equal p1 limit)
12596 (goto-char pos)
12597 (error "No more matches"))
12598 (when (equal (get-char-property p1 'org-type) 'org-occur)
12599 (setq n (1- n))
12600 (when (= n 0)
12601 (goto-char p1)
12602 (throw 'exit (point))))
12603 (goto-char p1))
12604 (goto-char p1)
12605 (error "No more matches"))))
12607 (defun org-show-context (&optional key)
12608 "Make sure point and context are visible.
12609 How much context is shown depends upon the variables
12610 `org-show-hierarchy-above', `org-show-following-heading',
12611 `org-show-entry-below' and `org-show-siblings'."
12612 (let ((heading-p (org-at-heading-p t))
12613 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
12614 (following-p (org-get-alist-option org-show-following-heading key))
12615 (entry-p (org-get-alist-option org-show-entry-below key))
12616 (siblings-p (org-get-alist-option org-show-siblings key)))
12617 (catch 'exit
12618 ;; Show heading or entry text
12619 (if (and heading-p (not entry-p))
12620 (org-flag-heading nil) ; only show the heading
12621 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
12622 (org-show-hidden-entry))) ; show entire entry
12623 (when following-p
12624 ;; Show next sibling, or heading below text
12625 (save-excursion
12626 (and (if heading-p (org-goto-sibling) (outline-next-heading))
12627 (org-flag-heading nil))))
12628 (when siblings-p (org-show-siblings))
12629 (when hierarchy-p
12630 ;; show all higher headings, possibly with siblings
12631 (save-excursion
12632 (while (and (condition-case nil
12633 (progn (org-up-heading-all 1) t)
12634 (error nil))
12635 (not (bobp)))
12636 (org-flag-heading nil)
12637 (when siblings-p (org-show-siblings))))))))
12639 (defvar org-reveal-start-hook nil
12640 "Hook run before revealing a location.")
12642 (defun org-reveal (&optional siblings)
12643 "Show current entry, hierarchy above it, and the following headline.
12644 This can be used to show a consistent set of context around locations
12645 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
12646 not t for the search context.
12648 With optional argument SIBLINGS, on each level of the hierarchy all
12649 siblings are shown. This repairs the tree structure to what it would
12650 look like when opened with hierarchical calls to `org-cycle'.
12651 With double optional argument \\[universal-argument] \\[universal-argument], \
12652 go to the parent and show the
12653 entire tree."
12654 (interactive "P")
12655 (run-hooks 'org-reveal-start-hook)
12656 (let ((org-show-hierarchy-above t)
12657 (org-show-following-heading t)
12658 (org-show-siblings (if siblings t org-show-siblings)))
12659 (org-show-context nil))
12660 (when (equal siblings '(16))
12661 (save-excursion
12662 (when (org-up-heading-safe)
12663 (org-show-subtree)
12664 (run-hook-with-args 'org-cycle-hook 'subtree)))))
12666 (defun org-highlight-new-match (beg end)
12667 "Highlight from BEG to END and mark the highlight is an occur headline."
12668 (let ((ov (make-overlay beg end)))
12669 (overlay-put ov 'face 'secondary-selection)
12670 (overlay-put ov 'org-type 'org-occur)
12671 (push ov org-occur-highlights)))
12673 (defun org-remove-occur-highlights (&optional beg end noremove)
12674 "Remove the occur highlights from the buffer.
12675 BEG and END are ignored. If NOREMOVE is nil, remove this function
12676 from the `before-change-functions' in the current buffer."
12677 (interactive)
12678 (unless org-inhibit-highlight-removal
12679 (mapc 'delete-overlay org-occur-highlights)
12680 (setq org-occur-highlights nil)
12681 (setq org-occur-parameters nil)
12682 (unless noremove
12683 (remove-hook 'before-change-functions
12684 'org-remove-occur-highlights 'local))))
12686 ;;;; Priorities
12688 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
12689 "Regular expression matching the priority indicator.")
12691 (defvar org-remove-priority-next-time nil)
12693 (defun org-priority-up ()
12694 "Increase the priority of the current item."
12695 (interactive)
12696 (org-priority 'up))
12698 (defun org-priority-down ()
12699 "Decrease the priority of the current item."
12700 (interactive)
12701 (org-priority 'down))
12703 (defun org-priority (&optional action)
12704 "Change the priority of an item by ARG.
12705 ACTION can be `set', `up', `down', or a character."
12706 (interactive)
12707 (unless org-enable-priority-commands
12708 (error "Priority commands are disabled"))
12709 (setq action (or action 'set))
12710 (let (current new news have remove)
12711 (save-excursion
12712 (org-back-to-heading t)
12713 (if (looking-at org-priority-regexp)
12714 (setq current (string-to-char (match-string 2))
12715 have t))
12716 (cond
12717 ((eq action 'remove)
12718 (setq remove t new ?\ ))
12719 ((or (eq action 'set)
12720 (if (featurep 'xemacs) (characterp action) (integerp action)))
12721 (if (not (eq action 'set))
12722 (setq new action)
12723 (message "Priority %c-%c, SPC to remove: "
12724 org-highest-priority org-lowest-priority)
12725 (save-match-data
12726 (setq new (read-char-exclusive))))
12727 (if (and (= (upcase org-highest-priority) org-highest-priority)
12728 (= (upcase org-lowest-priority) org-lowest-priority))
12729 (setq new (upcase new)))
12730 (cond ((equal new ?\ ) (setq remove t))
12731 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
12732 (error "Priority must be between `%c' and `%c'"
12733 org-highest-priority org-lowest-priority))))
12734 ((eq action 'up)
12735 (setq new (if have
12736 (1- current) ; normal cycling
12737 ;; last priority was empty
12738 (if (eq last-command this-command)
12739 org-lowest-priority ; wrap around empty to lowest
12740 ;; default
12741 (if org-priority-start-cycle-with-default
12742 org-default-priority
12743 (1- org-default-priority))))))
12744 ((eq action 'down)
12745 (setq new (if have
12746 (1+ current) ; normal cycling
12747 ;; last priority was empty
12748 (if (eq last-command this-command)
12749 org-highest-priority ; wrap around empty to highest
12750 ;; default
12751 (if org-priority-start-cycle-with-default
12752 org-default-priority
12753 (1+ org-default-priority))))))
12754 (t (error "Invalid action")))
12755 (if (or (< (upcase new) org-highest-priority)
12756 (> (upcase new) org-lowest-priority))
12757 (if (and (memq action '(up down))
12758 (not have) (not (eq last-command this-command)))
12759 ;; `new' is from default priority
12760 (error
12761 "The default can not be set, see `org-default-priority' why")
12762 ;; normal cycling: `new' is beyond highest/lowest priority
12763 ;; and is wrapped around to the empty priority
12764 (setq remove t)))
12765 (setq news (format "%c" new))
12766 (if have
12767 (if remove
12768 (replace-match "" t t nil 1)
12769 (replace-match news t t nil 2))
12770 (if remove
12771 (error "No priority cookie found in line")
12772 (let ((case-fold-search nil))
12773 (looking-at org-todo-line-regexp))
12774 (if (match-end 2)
12775 (progn
12776 (goto-char (match-end 2))
12777 (insert " [#" news "]"))
12778 (goto-char (match-beginning 3))
12779 (insert "[#" news "] "))))
12780 (org-preserve-lc (org-set-tags nil 'align)))
12781 (if remove
12782 (message "Priority removed")
12783 (message "Priority of current item set to %s" news))))
12785 (defun org-get-priority (s)
12786 "Find priority cookie and return priority."
12787 (if (functionp org-get-priority-function)
12788 (funcall org-get-priority-function)
12789 (save-match-data
12790 (if (not (string-match org-priority-regexp s))
12791 (* 1000 (- org-lowest-priority org-default-priority))
12792 (* 1000 (- org-lowest-priority
12793 (string-to-char (match-string 2 s))))))))
12795 ;;;; Tags
12797 (defvar org-agenda-archives-mode)
12798 (defvar org-map-continue-from nil
12799 "Position from where mapping should continue.
12800 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
12802 (defvar org-scanner-tags nil
12803 "The current tag list while the tags scanner is running.")
12804 (defvar org-trust-scanner-tags nil
12805 "Should `org-get-tags-at' use the tags for the scanner.
12806 This is for internal dynamical scoping only.
12807 When this is non-nil, the function `org-get-tags-at' will return the value
12808 of `org-scanner-tags' instead of building the list by itself. This
12809 can lead to large speed-ups when the tags scanner is used in a file with
12810 many entries, and when the list of tags is retrieved, for example to
12811 obtain a list of properties. Building the tags list for each entry in such
12812 a file becomes an N^2 operation - but with this variable set, it scales
12813 as N.")
12815 (defun org-scan-tags (action matcher todo-only &optional start-level)
12816 "Scan headline tags with inheritance and produce output ACTION.
12818 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
12819 or `agenda' to produce an entry list for an agenda view. It can also be
12820 a Lisp form or a function that should be called at each matched headline, in
12821 this case the return value is a list of all return values from these calls.
12823 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
12824 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
12825 only lines with a not-done TODO keyword are included in the output.
12826 This should be the same variable that was scoped into
12827 and set by `org-make-tags-matcher' when it constructed MATCHER.
12829 START-LEVEL can be a string with asterisks, reducing the scope to
12830 headlines matching this string."
12831 (require 'org-agenda)
12832 (let* ((re (concat "^"
12833 (if start-level
12834 ;; Get the correct level to match
12835 (concat "\\*\\{" (number-to-string start-level) "\\} ")
12836 org-outline-regexp)
12837 " *\\(\\<\\("
12838 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
12839 (org-re
12840 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
12841 (props (list 'face 'default
12842 'done-face 'org-agenda-done
12843 'undone-face 'default
12844 'mouse-face 'highlight
12845 'org-not-done-regexp org-not-done-regexp
12846 'org-todo-regexp org-todo-regexp
12847 'org-complex-heading-regexp org-complex-heading-regexp
12848 'help-echo
12849 (format "mouse-2 or RET jump to org file %s"
12850 (abbreviate-file-name
12851 (or (buffer-file-name (buffer-base-buffer))
12852 (buffer-name (buffer-base-buffer)))))))
12853 (case-fold-search nil)
12854 (org-map-continue-from nil)
12855 lspos tags tags-list
12856 (tags-alist (list (cons 0 org-file-tags)))
12857 (llast 0) rtn rtn1 level category i txt
12858 todo marker entry priority)
12859 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
12860 (setq action (list 'lambda nil action)))
12861 (save-excursion
12862 (goto-char (point-min))
12863 (when (eq action 'sparse-tree)
12864 (org-overview)
12865 (org-remove-occur-highlights))
12866 (while (re-search-forward re nil t)
12867 (setq org-map-continue-from nil)
12868 (catch :skip
12869 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
12870 tags (if (match-end 4) (org-match-string-no-properties 4)))
12871 (goto-char (setq lspos (match-beginning 0)))
12872 (setq level (org-reduced-level (funcall outline-level))
12873 category (org-get-category))
12874 (setq i llast llast level)
12875 ;; remove tag lists from same and sublevels
12876 (while (>= i level)
12877 (when (setq entry (assoc i tags-alist))
12878 (setq tags-alist (delete entry tags-alist)))
12879 (setq i (1- i)))
12880 ;; add the next tags
12881 (when tags
12882 (setq tags (org-split-string tags ":")
12883 tags-alist
12884 (cons (cons level tags) tags-alist)))
12885 ;; compile tags for current headline
12886 (setq tags-list
12887 (if org-use-tag-inheritance
12888 (apply 'append (mapcar 'cdr (reverse tags-alist)))
12889 tags)
12890 org-scanner-tags tags-list)
12891 (when org-use-tag-inheritance
12892 (setcdr (car tags-alist)
12893 (mapcar (lambda (x)
12894 (setq x (copy-sequence x))
12895 (org-add-prop-inherited x))
12896 (cdar tags-alist))))
12897 (when (and tags org-use-tag-inheritance
12898 (or (not (eq t org-use-tag-inheritance))
12899 org-tags-exclude-from-inheritance))
12900 ;; selective inheritance, remove uninherited ones
12901 (setcdr (car tags-alist)
12902 (org-remove-uninherited-tags (cdar tags-alist))))
12903 (when (and
12905 ;; eval matcher only when the todo condition is OK
12906 (and (or (not todo-only) (member todo org-not-done-keywords))
12907 (let ((case-fold-search t) (org-trust-scanner-tags t))
12908 (eval matcher)))
12910 ;; Call the skipper, but return t if it does not skip,
12911 ;; so that the `and' form continues evaluating
12912 (progn
12913 (unless (eq action 'sparse-tree) (org-agenda-skip))
12916 ;; Check if timestamps are deselecting this entry
12917 (or (not todo-only)
12918 (and (member todo org-not-done-keywords)
12919 (or (not org-agenda-tags-todo-honor-ignore-options)
12920 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
12922 ;; Extra check for the archive tag
12923 ;; FIXME: Does the skipper already do this????
12925 (not (member org-archive-tag tags-list))
12926 ;; we have an archive tag, should we use this anyway?
12927 (or (not org-agenda-skip-archived-trees)
12928 (and (eq action 'agenda) org-agenda-archives-mode))))
12930 ;; select this headline
12932 (cond
12933 ((eq action 'sparse-tree)
12934 (and org-highlight-sparse-tree-matches
12935 (org-get-heading) (match-end 0)
12936 (org-highlight-new-match
12937 (match-beginning 1) (match-end 1)))
12938 (org-show-context 'tags-tree))
12939 ((eq action 'agenda)
12940 (setq txt (org-agenda-format-item
12942 (concat
12943 (if (eq org-tags-match-list-sublevels 'indented)
12944 (make-string (1- level) ?.) "")
12945 (org-get-heading))
12946 category
12947 tags-list)
12948 priority (org-get-priority txt))
12949 (goto-char lspos)
12950 (setq marker (org-agenda-new-marker))
12951 (org-add-props txt props
12952 'org-marker marker 'org-hd-marker marker 'org-category category
12953 'todo-state todo
12954 'priority priority 'type "tagsmatch")
12955 (push txt rtn))
12956 ((functionp action)
12957 (setq org-map-continue-from nil)
12958 (save-excursion
12959 (setq rtn1 (funcall action))
12960 (push rtn1 rtn)))
12961 (t (error "Invalid action")))
12963 ;; if we are to skip sublevels, jump to end of subtree
12964 (unless org-tags-match-list-sublevels
12965 (org-end-of-subtree t)
12966 (backward-char 1))))
12967 ;; Get the correct position from where to continue
12968 (if org-map-continue-from
12969 (goto-char org-map-continue-from)
12970 (and (= (point) lspos) (end-of-line 1)))))
12971 (when (and (eq action 'sparse-tree)
12972 (not org-sparse-tree-open-archived-trees))
12973 (org-hide-archived-subtrees (point-min) (point-max)))
12974 (nreverse rtn)))
12976 (defun org-remove-uninherited-tags (tags)
12977 "Remove all tags that are not inherited from the list TAGS."
12978 (cond
12979 ((eq org-use-tag-inheritance t)
12980 (if org-tags-exclude-from-inheritance
12981 (org-delete-all org-tags-exclude-from-inheritance tags)
12982 tags))
12983 ((not org-use-tag-inheritance) nil)
12984 ((stringp org-use-tag-inheritance)
12985 (delq nil (mapcar
12986 (lambda (x)
12987 (if (and (string-match org-use-tag-inheritance x)
12988 (not (member x org-tags-exclude-from-inheritance)))
12989 x nil))
12990 tags)))
12991 ((listp org-use-tag-inheritance)
12992 (delq nil (mapcar
12993 (lambda (x)
12994 (if (member x org-use-tag-inheritance) x nil))
12995 tags)))))
12997 (defun org-match-sparse-tree (&optional todo-only match)
12998 "Create a sparse tree according to tags string MATCH.
12999 MATCH can contain positive and negative selection of tags, like
13000 \"+WORK+URGENT-WITHBOSS\".
13001 If optional argument TODO-ONLY is non-nil, only select lines that are
13002 also TODO lines."
13003 (interactive "P")
13004 (org-prepare-agenda-buffers (list (current-buffer)))
13005 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13007 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13009 (defvar org-cached-props nil)
13010 (defun org-cached-entry-get (pom property)
13011 (if (or (eq t org-use-property-inheritance)
13012 (and (stringp org-use-property-inheritance)
13013 (string-match org-use-property-inheritance property))
13014 (and (listp org-use-property-inheritance)
13015 (member property org-use-property-inheritance)))
13016 ;; Caching is not possible, check it directly
13017 (org-entry-get pom property 'inherit)
13018 ;; Get all properties, so that we can do complicated checks easily
13019 (cdr (assoc property (or org-cached-props
13020 (setq org-cached-props
13021 (org-entry-properties pom)))))))
13023 (defun org-global-tags-completion-table (&optional files)
13024 "Return the list of all tags in all agenda buffer/files.
13025 Optional FILES argument is a list of files to which can be used
13026 instead of the agenda files."
13027 (save-excursion
13028 (org-uniquify
13029 (delq nil
13030 (apply 'append
13031 (mapcar
13032 (lambda (file)
13033 (set-buffer (find-file-noselect file))
13034 (append (org-get-buffer-tags)
13035 (mapcar (lambda (x) (if (stringp (car-safe x))
13036 (list (car-safe x)) nil))
13037 org-tag-alist)))
13038 (if (and files (car files))
13039 files
13040 (org-agenda-files))))))))
13042 (defun org-make-tags-matcher (match)
13043 "Create the TAGS/TODO matcher form for the selection string MATCH.
13045 The variable `todo-only' is scoped dynamically into this function; it will be
13046 set to t if the matcher restricts matching to TODO entries,
13047 otherwise will not be touched.
13049 Returns a cons of the selection string MATCH and the constructed
13050 lisp form implementing the matcher. The matcher is to be
13051 evaluated at an Org entry, with point on the headline,
13052 and returns t if the entry matches the
13053 selection string MATCH. The returned lisp form references
13054 two variables with information about the entry, which must be
13055 bound around the form's evaluation: todo, the TODO keyword at the
13056 entry (or nil of none); and tags-list, the list of all tags at the
13057 entry including inherited ones. Additionally, the category
13058 of the entry (if any) must be specified as the text property
13059 'org-category on the headline.
13061 See also `org-scan-tags'.
13063 (declare (special todo-only))
13064 (unless (boundp 'todo-only)
13065 (error "org-make-tags-matcher expects todo-only to be scoped in"))
13066 (unless match
13067 ;; Get a new match request, with completion
13068 (let ((org-last-tags-completion-table
13069 (org-global-tags-completion-table)))
13070 (setq match (org-completing-read-no-i
13071 "Match: " 'org-tags-completion-function nil nil nil
13072 'org-tags-history))))
13074 ;; Parse the string and create a lisp form
13075 (let ((match0 match)
13076 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
13077 minus tag mm
13078 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
13079 orterms term orlist re-p str-p level-p level-op time-p
13080 prop-p pn pv po gv rest)
13081 (if (string-match "/+" match)
13082 ;; match contains also a todo-matching request
13083 (progn
13084 (setq tagsmatch (substring match 0 (match-beginning 0))
13085 todomatch (substring match (match-end 0)))
13086 (if (string-match "^!" todomatch)
13087 (setq todo-only t todomatch (substring todomatch 1)))
13088 (if (string-match "^\\s-*$" todomatch)
13089 (setq todomatch nil)))
13090 ;; only matching tags
13091 (setq tagsmatch match todomatch nil))
13093 ;; Make the tags matcher
13094 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
13095 (setq tagsmatcher t)
13096 (setq orterms (org-split-string tagsmatch "|") orlist nil)
13097 (while (setq term (pop orterms))
13098 (while (and (equal (substring term -1) "\\") orterms)
13099 (setq term (concat term "|" (pop orterms)))) ; repair bad split
13100 (while (string-match re term)
13101 (setq rest (substring term (match-end 0))
13102 minus (and (match-end 1)
13103 (equal (match-string 1 term) "-"))
13104 tag (save-match-data (replace-regexp-in-string
13105 "\\\\-" "-"
13106 (match-string 2 term)))
13107 re-p (equal (string-to-char tag) ?{)
13108 level-p (match-end 4)
13109 prop-p (match-end 5)
13110 mm (cond
13111 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
13112 (level-p
13113 (setq level-op (org-op-to-function (match-string 3 term)))
13114 `(,level-op level ,(string-to-number
13115 (match-string 4 term))))
13116 (prop-p
13117 (setq pn (match-string 5 term)
13118 po (match-string 6 term)
13119 pv (match-string 7 term)
13120 re-p (equal (string-to-char pv) ?{)
13121 str-p (equal (string-to-char pv) ?\")
13122 time-p (save-match-data
13123 (string-match "^\"[[<].*[]>]\"$" pv))
13124 pv (if (or re-p str-p) (substring pv 1 -1) pv))
13125 (if time-p (setq pv (org-matcher-time pv)))
13126 (setq po (org-op-to-function po (if time-p 'time str-p)))
13127 (cond
13128 ((equal pn "CATEGORY")
13129 (setq gv '(get-text-property (point) 'org-category)))
13130 ((equal pn "TODO")
13131 (setq gv 'todo))
13133 (setq gv `(org-cached-entry-get nil ,pn))))
13134 (if re-p
13135 (if (eq po 'org<>)
13136 `(not (string-match ,pv (or ,gv "")))
13137 `(string-match ,pv (or ,gv "")))
13138 (if str-p
13139 `(,po (or ,gv "") ,pv)
13140 `(,po (string-to-number (or ,gv ""))
13141 ,(string-to-number pv) ))))
13142 (t `(member ,tag tags-list)))
13143 mm (if minus (list 'not mm) mm)
13144 term rest)
13145 (push mm tagsmatcher))
13146 (push (if (> (length tagsmatcher) 1)
13147 (cons 'and tagsmatcher)
13148 (car tagsmatcher))
13149 orlist)
13150 (setq tagsmatcher nil))
13151 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
13152 (setq tagsmatcher
13153 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
13154 ;; Make the todo matcher
13155 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
13156 (setq todomatcher t)
13157 (setq orterms (org-split-string todomatch "|") orlist nil)
13158 (while (setq term (pop orterms))
13159 (while (string-match re term)
13160 (setq minus (and (match-end 1)
13161 (equal (match-string 1 term) "-"))
13162 kwd (match-string 2 term)
13163 re-p (equal (string-to-char kwd) ?{)
13164 term (substring term (match-end 0))
13165 mm (if re-p
13166 `(string-match ,(substring kwd 1 -1) todo)
13167 (list 'equal 'todo kwd))
13168 mm (if minus (list 'not mm) mm))
13169 (push mm todomatcher))
13170 (push (if (> (length todomatcher) 1)
13171 (cons 'and todomatcher)
13172 (car todomatcher))
13173 orlist)
13174 (setq todomatcher nil))
13175 (setq todomatcher (if (> (length orlist) 1)
13176 (cons 'or orlist) (car orlist))))
13178 ;; Return the string and lisp forms of the matcher
13179 (setq matcher (if todomatcher
13180 (list 'and tagsmatcher todomatcher)
13181 tagsmatcher))
13182 (when todo-only
13183 (setq matcher (list 'and '(member todo org-not-done-keywords)
13184 matcher)))
13185 (cons match0 matcher)))
13187 (defun org-op-to-function (op &optional stringp)
13188 "Turn an operator into the appropriate function."
13189 (setq op
13190 (cond
13191 ((equal op "<" ) '(< string< org-time<))
13192 ((equal op ">" ) '(> org-string> org-time>))
13193 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
13194 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
13195 ((member op '("=" "==")) '(= string= org-time=))
13196 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
13197 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
13199 (defun org<> (a b) (not (= a b)))
13200 (defun org-string<= (a b) (or (string= a b) (string< a b)))
13201 (defun org-string>= (a b) (not (string< a b)))
13202 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
13203 (defun org-string<> (a b) (not (string= a b)))
13204 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
13205 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
13206 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
13207 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
13208 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
13209 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
13210 (defun org-2ft (s)
13211 "Convert S to a floating point time.
13212 If S is already a number, just return it. If it is a string, parse
13213 it as a time string and apply `float-time' to it. If S is nil, just return 0."
13214 (cond
13215 ((numberp s) s)
13216 ((stringp s)
13217 (condition-case nil
13218 (float-time (apply 'encode-time (org-parse-time-string s)))
13219 (error 0.)))
13220 (t 0.)))
13222 (defun org-time-today ()
13223 "Time in seconds today at 0:00.
13224 Returns the float number of seconds since the beginning of the
13225 epoch to the beginning of today (00:00)."
13226 (float-time (apply 'encode-time
13227 (append '(0 0 0) (nthcdr 3 (decode-time))))))
13229 (defun org-matcher-time (s)
13230 "Interpret a time comparison value."
13231 (save-match-data
13232 (cond
13233 ((string= s "<now>") (float-time))
13234 ((string= s "<today>") (org-time-today))
13235 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
13236 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
13237 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
13238 (+ (org-time-today)
13239 (* (string-to-number (match-string 1 s))
13240 (cdr (assoc (match-string 2 s)
13241 '(("d" . 86400.0) ("w" . 604800.0)
13242 ("m" . 2678400.0) ("y" . 31557600.0)))))))
13243 (t (org-2ft s)))))
13245 (defun org-match-any-p (re list)
13246 "Does re match any element of list?"
13247 (setq list (mapcar (lambda (x) (string-match re x)) list))
13248 (delq nil list))
13250 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
13251 (defvar org-tags-overlay (make-overlay 1 1))
13252 (org-detach-overlay org-tags-overlay)
13254 (defun org-get-local-tags-at (&optional pos)
13255 "Get a list of tags defined in the current headline."
13256 (org-get-tags-at pos 'local))
13258 (defun org-get-local-tags ()
13259 "Get a list of tags defined in the current headline."
13260 (org-get-tags-at nil 'local))
13262 (defun org-get-tags-at (&optional pos local)
13263 "Get a list of all headline tags applicable at POS.
13264 POS defaults to point. If tags are inherited, the list contains
13265 the targets in the same sequence as the headlines appear, i.e.
13266 the tags of the current headline come last.
13267 When LOCAL is non-nil, only return tags from the current headline,
13268 ignore inherited ones."
13269 (interactive)
13270 (if (and org-trust-scanner-tags
13271 (or (not pos) (equal pos (point)))
13272 (not local))
13273 org-scanner-tags
13274 (let (tags ltags lastpos parent)
13275 (save-excursion
13276 (save-restriction
13277 (widen)
13278 (goto-char (or pos (point)))
13279 (save-match-data
13280 (catch 'done
13281 (condition-case nil
13282 (progn
13283 (org-back-to-heading t)
13284 (while (not (equal lastpos (point)))
13285 (setq lastpos (point))
13286 (when (looking-at
13287 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
13288 (setq ltags (org-split-string
13289 (org-match-string-no-properties 1) ":"))
13290 (when parent
13291 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
13292 (setq tags (append
13293 (if parent
13294 (org-remove-uninherited-tags ltags)
13295 ltags)
13296 tags)))
13297 (or org-use-tag-inheritance (throw 'done t))
13298 (if local (throw 'done t))
13299 (or (org-up-heading-safe) (error nil))
13300 (setq parent t)))
13301 (error nil)))))
13302 (if local
13303 tags
13304 (append (org-remove-uninherited-tags org-file-tags) tags))))))
13306 (defun org-add-prop-inherited (s)
13307 (add-text-properties 0 (length s) '(inherited t) s)
13310 (defun org-toggle-tag (tag &optional onoff)
13311 "Toggle the tag TAG for the current line.
13312 If ONOFF is `on' or `off', don't toggle but set to this state."
13313 (let (res current)
13314 (save-excursion
13315 (org-back-to-heading t)
13316 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
13317 (point-at-eol) t)
13318 (progn
13319 (setq current (match-string 1))
13320 (replace-match ""))
13321 (setq current ""))
13322 (setq current (nreverse (org-split-string current ":")))
13323 (cond
13324 ((eq onoff 'on)
13325 (setq res t)
13326 (or (member tag current) (push tag current)))
13327 ((eq onoff 'off)
13328 (or (not (member tag current)) (setq current (delete tag current))))
13329 (t (if (member tag current)
13330 (setq current (delete tag current))
13331 (setq res t)
13332 (push tag current))))
13333 (end-of-line 1)
13334 (if current
13335 (progn
13336 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
13337 (org-set-tags nil t))
13338 (delete-horizontal-space))
13339 (run-hooks 'org-after-tags-change-hook))
13340 res))
13342 (defun org-align-tags-here (to-col)
13343 ;; Assumes that this is a headline
13344 (let ((pos (point)) (col (current-column)) ncol tags-l p)
13345 (beginning-of-line 1)
13346 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13347 (< pos (match-beginning 2)))
13348 (progn
13349 (setq tags-l (- (match-end 2) (match-beginning 2)))
13350 (goto-char (match-beginning 1))
13351 (insert " ")
13352 (delete-region (point) (1+ (match-beginning 2)))
13353 (setq ncol (max (current-column)
13354 (1+ col)
13355 (if (> to-col 0)
13356 to-col
13357 (- (abs to-col) tags-l))))
13358 (setq p (point))
13359 (insert (make-string (- ncol (current-column)) ?\ ))
13360 (setq ncol (current-column))
13361 (when indent-tabs-mode (tabify p (point-at-eol)))
13362 (org-move-to-column (min ncol col) t))
13363 (goto-char pos))))
13365 (defun org-set-tags-command (&optional arg just-align)
13366 "Call the set-tags command for the current entry."
13367 (interactive "P")
13368 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
13369 (org-set-tags arg just-align)
13370 (save-excursion
13371 (org-back-to-heading t)
13372 (org-set-tags arg just-align))))
13374 (defun org-set-tags-to (data)
13375 "Set the tags of the current entry to DATA, replacing the current tags.
13376 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
13377 If DATA is nil or the empty string, any tags will be removed."
13378 (interactive "sTags: ")
13379 (setq data
13380 (cond
13381 ((eq data nil) "")
13382 ((equal data "") "")
13383 ((stringp data)
13384 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
13385 ":"))
13386 ((listp data)
13387 (concat ":" (mapconcat 'identity data ":") ":"))
13388 (t nil)))
13389 (when data
13390 (save-excursion
13391 (org-back-to-heading t)
13392 (when (looking-at org-complex-heading-regexp)
13393 (if (match-end 5)
13394 (progn
13395 (goto-char (match-beginning 5))
13396 (insert data)
13397 (delete-region (point) (point-at-eol))
13398 (org-set-tags nil 'align))
13399 (goto-char (point-at-eol))
13400 (insert " " data)
13401 (org-set-tags nil 'align)))
13402 (beginning-of-line 1)
13403 (if (looking-at ".*?\\([ \t]+\\)$")
13404 (delete-region (match-beginning 1) (match-end 1))))))
13406 (defun org-align-all-tags ()
13407 "Align the tags i all headings."
13408 (interactive)
13409 (save-excursion
13410 (or (ignore-errors (org-back-to-heading t))
13411 (outline-next-heading))
13412 (if (org-at-heading-p)
13413 (org-set-tags t)
13414 (message "No headings"))))
13416 (defvar org-indent-indentation-per-level)
13417 (defun org-set-tags (&optional arg just-align)
13418 "Set the tags for the current headline.
13419 With prefix ARG, realign all tags in headings in the current buffer."
13420 (interactive "P")
13421 (let* ((re org-outline-regexp-bol)
13422 (current (unless arg (org-get-tags-string)))
13423 (col (current-column))
13424 (org-setting-tags t)
13425 table current-tags inherited-tags ; computed below when needed
13426 tags p0 c0 c1 rpl di tc level)
13427 (if arg
13428 (save-excursion
13429 (goto-char (point-min))
13430 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
13431 (while (re-search-forward re nil t)
13432 (org-set-tags nil t)
13433 (end-of-line 1)))
13434 (message "All tags realigned to column %d" org-tags-column))
13435 (if just-align
13436 (setq tags current)
13437 ;; Get a new set of tags from the user
13438 (save-excursion
13439 (setq table (append org-tag-persistent-alist
13440 (or org-tag-alist (org-get-buffer-tags))
13441 (and
13442 org-complete-tags-always-offer-all-agenda-tags
13443 (org-global-tags-completion-table
13444 (org-agenda-files))))
13445 org-last-tags-completion-table table
13446 current-tags (org-split-string current ":")
13447 inherited-tags (nreverse
13448 (nthcdr (length current-tags)
13449 (nreverse (org-get-tags-at))))
13450 tags
13451 (if (or (eq t org-use-fast-tag-selection)
13452 (and org-use-fast-tag-selection
13453 (delq nil (mapcar 'cdr table))))
13454 (org-fast-tag-selection
13455 current-tags inherited-tags table
13456 (if org-fast-tag-selection-include-todo
13457 org-todo-key-alist))
13458 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
13459 (org-trim
13460 (org-icompleting-read "Tags: "
13461 'org-tags-completion-function
13462 nil nil current 'org-tags-history))))))
13463 (while (string-match "[-+&]+" tags)
13464 ;; No boolean logic, just a list
13465 (setq tags (replace-match ":" t t tags))))
13467 (setq tags (replace-regexp-in-string "[,]" ":" tags))
13469 (if org-tags-sort-function
13470 (setq tags (mapconcat 'identity
13471 (sort (org-split-string
13472 tags (org-re "[^[:alnum:]_@#%]+"))
13473 org-tags-sort-function) ":")))
13475 (if (string-match "\\`[\t ]*\\'" tags)
13476 (setq tags "")
13477 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
13478 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
13480 ;; Insert new tags at the correct column
13481 (beginning-of-line 1)
13482 (setq level (or (and (looking-at org-outline-regexp)
13483 (- (match-end 0) (point) 1))
13485 (cond
13486 ((and (equal current "") (equal tags "")))
13487 ((re-search-forward
13488 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
13489 (point-at-eol) t)
13490 (if (equal tags "")
13491 (setq rpl "")
13492 (goto-char (match-beginning 0))
13493 (setq c0 (current-column)
13494 ;; compute offset for the case of org-indent-mode active
13495 di (if org-indent-mode
13496 (* (1- org-indent-indentation-per-level) (1- level))
13498 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
13499 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
13500 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
13501 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
13502 (replace-match rpl t t)
13503 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
13504 tags)
13505 (t (error "Tags alignment failed")))
13506 (org-move-to-column col)
13507 (unless just-align
13508 (run-hooks 'org-after-tags-change-hook)))))
13510 (defun org-change-tag-in-region (beg end tag off)
13511 "Add or remove TAG for each entry in the region.
13512 This works in the agenda, and also in an org-mode buffer."
13513 (interactive
13514 (list (region-beginning) (region-end)
13515 (let ((org-last-tags-completion-table
13516 (if (eq major-mode 'org-mode)
13517 (org-get-buffer-tags)
13518 (org-global-tags-completion-table))))
13519 (org-icompleting-read
13520 "Tag: " 'org-tags-completion-function nil nil nil
13521 'org-tags-history))
13522 (progn
13523 (message "[s]et or [r]emove? ")
13524 (equal (read-char-exclusive) ?r))))
13525 (if (fboundp 'deactivate-mark) (deactivate-mark))
13526 (let ((agendap (equal major-mode 'org-agenda-mode))
13527 l1 l2 m buf pos newhead (cnt 0))
13528 (goto-char end)
13529 (setq l2 (1- (org-current-line)))
13530 (goto-char beg)
13531 (setq l1 (org-current-line))
13532 (loop for l from l1 to l2 do
13533 (org-goto-line l)
13534 (setq m (get-text-property (point) 'org-hd-marker))
13535 (when (or (and (eq major-mode 'org-mode) (org-at-heading-p))
13536 (and agendap m))
13537 (setq buf (if agendap (marker-buffer m) (current-buffer))
13538 pos (if agendap m (point)))
13539 (with-current-buffer buf
13540 (save-excursion
13541 (save-restriction
13542 (goto-char pos)
13543 (setq cnt (1+ cnt))
13544 (org-toggle-tag tag (if off 'off 'on))
13545 (setq newhead (org-get-heading)))))
13546 (and agendap (org-agenda-change-all-lines newhead m))))
13547 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
13549 (defun org-tags-completion-function (string predicate &optional flag)
13550 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
13551 (confirm (lambda (x) (stringp (car x)))))
13552 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
13553 (setq s1 (match-string 1 string)
13554 s2 (match-string 2 string))
13555 (setq s1 "" s2 string))
13556 (cond
13557 ((eq flag nil)
13558 ;; try completion
13559 (setq rtn (try-completion s2 ctable confirm))
13560 (if (stringp rtn)
13561 (setq rtn
13562 (concat s1 s2 (substring rtn (length s2))
13563 (if (and org-add-colon-after-tag-completion
13564 (assoc rtn ctable))
13565 ":" ""))))
13566 rtn)
13567 ((eq flag t)
13568 ;; all-completions
13569 (all-completions s2 ctable confirm)
13571 ((eq flag 'lambda)
13572 ;; exact match?
13573 (assoc s2 ctable)))
13576 (defun org-fast-tag-insert (kwd tags face &optional end)
13577 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
13578 (insert (format "%-12s" (concat kwd ":"))
13579 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
13580 (or end "")))
13582 (defun org-fast-tag-show-exit (flag)
13583 (save-excursion
13584 (org-goto-line 3)
13585 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
13586 (replace-match ""))
13587 (when flag
13588 (end-of-line 1)
13589 (org-move-to-column (- (window-width) 19) t)
13590 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
13592 (defun org-set-current-tags-overlay (current prefix)
13593 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
13594 (if (featurep 'xemacs)
13595 (org-overlay-display org-tags-overlay (concat prefix s)
13596 'secondary-selection)
13597 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
13598 (org-overlay-display org-tags-overlay (concat prefix s)))))
13600 (defvar org-last-tag-selection-key nil)
13601 (defun org-fast-tag-selection (current inherited table &optional todo-table)
13602 "Fast tag selection with single keys.
13603 CURRENT is the current list of tags in the headline, INHERITED is the
13604 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
13605 possibly with grouping information. TODO-TABLE is a similar table with
13606 TODO keywords, should these have keys assigned to them.
13607 If the keys are nil, a-z are automatically assigned.
13608 Returns the new tags string, or nil to not change the current settings."
13609 (let* ((fulltable (append table todo-table))
13610 (maxlen (apply 'max (mapcar
13611 (lambda (x)
13612 (if (stringp (car x)) (string-width (car x)) 0))
13613 fulltable)))
13614 (buf (current-buffer))
13615 (expert (eq org-fast-tag-selection-single-key 'expert))
13616 (buffer-tags nil)
13617 (fwidth (+ maxlen 3 1 3))
13618 (ncol (/ (- (window-width) 4) fwidth))
13619 (i-face 'org-done)
13620 (c-face 'org-todo)
13621 tg cnt e c char c1 c2 ntable tbl rtn
13622 ov-start ov-end ov-prefix
13623 (exit-after-next org-fast-tag-selection-single-key)
13624 (done-keywords org-done-keywords)
13625 groups ingroup)
13626 (save-excursion
13627 (beginning-of-line 1)
13628 (if (looking-at
13629 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13630 (setq ov-start (match-beginning 1)
13631 ov-end (match-end 1)
13632 ov-prefix "")
13633 (setq ov-start (1- (point-at-eol))
13634 ov-end (1+ ov-start))
13635 (skip-chars-forward "^\n\r")
13636 (setq ov-prefix
13637 (concat
13638 (buffer-substring (1- (point)) (point))
13639 (if (> (current-column) org-tags-column)
13641 (make-string (- org-tags-column (current-column)) ?\ ))))))
13642 (move-overlay org-tags-overlay ov-start ov-end)
13643 (save-window-excursion
13644 (if expert
13645 (set-buffer (get-buffer-create " *Org tags*"))
13646 (delete-other-windows)
13647 (split-window-vertically)
13648 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
13649 (erase-buffer)
13650 (org-set-local 'org-done-keywords done-keywords)
13651 (org-fast-tag-insert "Inherited" inherited i-face "\n")
13652 (org-fast-tag-insert "Current" current c-face "\n\n")
13653 (org-fast-tag-show-exit exit-after-next)
13654 (org-set-current-tags-overlay current ov-prefix)
13655 (setq tbl fulltable char ?a cnt 0)
13656 (while (setq e (pop tbl))
13657 (cond
13658 ((equal (car e) :startgroup)
13659 (push '() groups) (setq ingroup t)
13660 (when (not (= cnt 0))
13661 (setq cnt 0)
13662 (insert "\n"))
13663 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
13664 ((equal (car e) :endgroup)
13665 (setq ingroup nil cnt 0)
13666 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
13667 ((equal e '(:newline))
13668 (when (not (= cnt 0))
13669 (setq cnt 0)
13670 (insert "\n")
13671 (setq e (car tbl))
13672 (while (equal (car tbl) '(:newline))
13673 (insert "\n")
13674 (setq tbl (cdr tbl)))))
13676 (setq tg (copy-sequence (car e)) c2 nil)
13677 (if (cdr e)
13678 (setq c (cdr e))
13679 ;; automatically assign a character.
13680 (setq c1 (string-to-char
13681 (downcase (substring
13682 tg (if (= (string-to-char tg) ?@) 1 0)))))
13683 (if (or (rassoc c1 ntable) (rassoc c1 table))
13684 (while (or (rassoc char ntable) (rassoc char table))
13685 (setq char (1+ char)))
13686 (setq c2 c1))
13687 (setq c (or c2 char)))
13688 (if ingroup (push tg (car groups)))
13689 (setq tg (org-add-props tg nil 'face
13690 (cond
13691 ((not (assoc tg table))
13692 (org-get-todo-face tg))
13693 ((member tg current) c-face)
13694 ((member tg inherited) i-face)
13695 (t nil))))
13696 (if (and (= cnt 0) (not ingroup)) (insert " "))
13697 (insert "[" c "] " tg (make-string
13698 (- fwidth 4 (length tg)) ?\ ))
13699 (push (cons tg c) ntable)
13700 (when (= (setq cnt (1+ cnt)) ncol)
13701 (insert "\n")
13702 (if ingroup (insert " "))
13703 (setq cnt 0)))))
13704 (setq ntable (nreverse ntable))
13705 (insert "\n")
13706 (goto-char (point-min))
13707 (if (not expert) (org-fit-window-to-buffer))
13708 (setq rtn
13709 (catch 'exit
13710 (while t
13711 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
13712 (if (not groups) "no " "")
13713 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
13714 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13715 (setq org-last-tag-selection-key c)
13716 (cond
13717 ((= c ?\r) (throw 'exit t))
13718 ((= c ?!)
13719 (setq groups (not groups))
13720 (goto-char (point-min))
13721 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
13722 ((= c ?\C-c)
13723 (if (not expert)
13724 (org-fast-tag-show-exit
13725 (setq exit-after-next (not exit-after-next)))
13726 (setq expert nil)
13727 (delete-other-windows)
13728 (set-window-buffer (split-window-vertically) " *Org tags*")
13729 (org-switch-to-buffer-other-window " *Org tags*")
13730 (org-fit-window-to-buffer)))
13731 ((or (= c ?\C-g)
13732 (and (= c ?q) (not (rassoc c ntable))))
13733 (org-detach-overlay org-tags-overlay)
13734 (setq quit-flag t))
13735 ((= c ?\ )
13736 (setq current nil)
13737 (if exit-after-next (setq exit-after-next 'now)))
13738 ((= c ?\t)
13739 (condition-case nil
13740 (setq tg (org-icompleting-read
13741 "Tag: "
13742 (or buffer-tags
13743 (with-current-buffer buf
13744 (org-get-buffer-tags)))))
13745 (quit (setq tg "")))
13746 (when (string-match "\\S-" tg)
13747 (add-to-list 'buffer-tags (list tg))
13748 (if (member tg current)
13749 (setq current (delete tg current))
13750 (push tg current)))
13751 (if exit-after-next (setq exit-after-next 'now)))
13752 ((setq e (rassoc c todo-table) tg (car e))
13753 (with-current-buffer buf
13754 (save-excursion (org-todo tg)))
13755 (if exit-after-next (setq exit-after-next 'now)))
13756 ((setq e (rassoc c ntable) tg (car e))
13757 (if (member tg current)
13758 (setq current (delete tg current))
13759 (loop for g in groups do
13760 (if (member tg g)
13761 (mapc (lambda (x)
13762 (setq current (delete x current)))
13763 g)))
13764 (push tg current))
13765 (if exit-after-next (setq exit-after-next 'now))))
13767 ;; Create a sorted list
13768 (setq current
13769 (sort current
13770 (lambda (a b)
13771 (assoc b (cdr (memq (assoc a ntable) ntable))))))
13772 (if (eq exit-after-next 'now) (throw 'exit t))
13773 (goto-char (point-min))
13774 (beginning-of-line 2)
13775 (delete-region (point) (point-at-eol))
13776 (org-fast-tag-insert "Current" current c-face)
13777 (org-set-current-tags-overlay current ov-prefix)
13778 (while (re-search-forward
13779 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
13780 (setq tg (match-string 1))
13781 (add-text-properties
13782 (match-beginning 1) (match-end 1)
13783 (list 'face
13784 (cond
13785 ((member tg current) c-face)
13786 ((member tg inherited) i-face)
13787 (t (get-text-property (match-beginning 1) 'face))))))
13788 (goto-char (point-min)))))
13789 (org-detach-overlay org-tags-overlay)
13790 (if rtn
13791 (mapconcat 'identity current ":")
13792 nil))))
13794 (defun org-get-tags-string ()
13795 "Get the TAGS string in the current headline."
13796 (unless (org-at-heading-p t)
13797 (error "Not on a heading"))
13798 (save-excursion
13799 (beginning-of-line 1)
13800 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13801 (org-match-string-no-properties 1)
13802 "")))
13804 (defun org-get-tags ()
13805 "Get the list of tags specified in the current headline."
13806 (org-split-string (org-get-tags-string) ":"))
13808 (defun org-get-buffer-tags ()
13809 "Get a table of all tags used in the buffer, for completion."
13810 (let (tags)
13811 (save-excursion
13812 (goto-char (point-min))
13813 (while (re-search-forward
13814 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
13815 (when (equal (char-after (point-at-bol 0)) ?*)
13816 (mapc (lambda (x) (add-to-list 'tags x))
13817 (org-split-string (org-match-string-no-properties 1) ":")))))
13818 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
13819 (mapcar 'list tags)))
13821 ;;;; The mapping API
13823 ;;;###autoload
13824 (defun org-map-entries (func &optional match scope &rest skip)
13825 "Call FUNC at each headline selected by MATCH in SCOPE.
13827 FUNC is a function or a lisp form. The function will be called without
13828 arguments, with the cursor positioned at the beginning of the headline.
13829 The return values of all calls to the function will be collected and
13830 returned as a list.
13832 The call to FUNC will be wrapped into a save-excursion form, so FUNC
13833 does not need to preserve point. After evaluation, the cursor will be
13834 moved to the end of the line (presumably of the headline of the
13835 processed entry) and search continues from there. Under some
13836 circumstances, this may not produce the wanted results. For example,
13837 if you have removed (e.g. archived) the current (sub)tree it could
13838 mean that the next entry will be skipped entirely. In such cases, you
13839 can specify the position from where search should continue by making
13840 FUNC set the variable `org-map-continue-from' to the desired buffer
13841 position.
13843 MATCH is a tags/property/todo match as it is used in the agenda tags view.
13844 Only headlines that are matched by this query will be considered during
13845 the iteration. When MATCH is nil or t, all headlines will be
13846 visited by the iteration.
13848 SCOPE determines the scope of this command. It can be any of:
13850 nil The current buffer, respecting the restriction if any
13851 tree The subtree started with the entry at point
13852 region The entries within the active region, if any
13853 region-start-level
13854 The entries within the active region, but only those at
13855 the same level than the first one.
13856 file The current buffer, without restriction
13857 file-with-archives
13858 The current buffer, and any archives associated with it
13859 agenda All agenda files
13860 agenda-with-archives
13861 All agenda files with any archive files associated with them
13862 \(file1 file2 ...)
13863 If this is a list, all files in the list will be scanned
13865 The remaining args are treated as settings for the skipping facilities of
13866 the scanner. The following items can be given here:
13868 archive skip trees with the archive tag.
13869 comment skip trees with the COMMENT keyword
13870 function or Emacs Lisp form:
13871 will be used as value for `org-agenda-skip-function', so whenever
13872 the function returns t, FUNC will not be called for that
13873 entry and search will continue from the point where the
13874 function leaves it.
13876 If your function needs to retrieve the tags including inherited tags
13877 at the *current* entry, you can use the value of the variable
13878 `org-scanner-tags' which will be much faster than getting the value
13879 with `org-get-tags-at'. If your function gets properties with
13880 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
13881 to t around the call to `org-entry-properties' to get the same speedup.
13882 Note that if your function moves around to retrieve tags and properties at
13883 a *different* entry, you cannot use these techniques."
13884 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
13885 (not (org-region-active-p)))
13886 (let* ((org-agenda-archives-mode nil) ; just to make sure
13887 (org-agenda-skip-archived-trees (memq 'archive skip))
13888 (org-agenda-skip-comment-trees (memq 'comment skip))
13889 (org-agenda-skip-function
13890 (car (org-delete-all '(comment archive) skip)))
13891 (org-tags-match-list-sublevels t)
13892 (start-level (eq scope 'region-start-level))
13893 matcher file res
13894 org-todo-keywords-for-agenda
13895 org-done-keywords-for-agenda
13896 org-todo-keyword-alist-for-agenda
13897 org-drawers-for-agenda
13898 org-tag-alist-for-agenda
13899 todo-only)
13901 (cond
13902 ((eq match t) (setq matcher t))
13903 ((eq match nil) (setq matcher t))
13904 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
13906 (save-excursion
13907 (save-restriction
13908 (cond ((eq scope 'tree)
13909 (org-back-to-heading t)
13910 (org-narrow-to-subtree)
13911 (setq scope nil))
13912 ((and (or (eq scope 'region) (eq scope 'region-start-level))
13913 (org-region-active-p))
13914 ;; If needed, set start-level to a string like "2"
13915 (when start-level
13916 (save-excursion
13917 (goto-char (region-beginning))
13918 (unless (org-at-heading-p) (outline-next-heading))
13919 (setq start-level (org-current-level))))
13920 (narrow-to-region (region-beginning)
13921 (save-excursion
13922 (goto-char (region-end))
13923 (unless (and (bolp) (org-at-heading-p))
13924 (outline-next-heading))
13925 (point)))
13926 (setq scope nil)))
13928 (if (not scope)
13929 (progn
13930 (org-prepare-agenda-buffers
13931 (list (buffer-file-name (current-buffer))))
13932 (setq res (org-scan-tags func matcher todo-only start-level)))
13933 ;; Get the right scope
13934 (cond
13935 ((and scope (listp scope) (symbolp (car scope)))
13936 (setq scope (eval scope)))
13937 ((eq scope 'agenda)
13938 (setq scope (org-agenda-files t)))
13939 ((eq scope 'agenda-with-archives)
13940 (setq scope (org-agenda-files t))
13941 (setq scope (org-add-archive-files scope)))
13942 ((eq scope 'file)
13943 (setq scope (list (buffer-file-name))))
13944 ((eq scope 'file-with-archives)
13945 (setq scope (org-add-archive-files (list (buffer-file-name))))))
13946 (org-prepare-agenda-buffers scope)
13947 (while (setq file (pop scope))
13948 (with-current-buffer (org-find-base-buffer-visiting file)
13949 (save-excursion
13950 (save-restriction
13951 (widen)
13952 (goto-char (point-min))
13953 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
13954 res)))
13956 ;;;; Properties
13958 ;;; Setting and retrieving properties
13960 (defconst org-special-properties
13961 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
13962 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM")
13963 "The special properties valid in Org-mode.
13965 These are properties that are not defined in the property drawer,
13966 but in some other way.")
13968 (defconst org-default-properties
13969 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
13970 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
13971 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
13972 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
13973 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
13974 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
13975 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
13976 "Some properties that are used by Org-mode for various purposes.
13977 Being in this list makes sure that they are offered for completion.")
13979 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
13980 "Regular expression matching the first line of a property drawer.")
13982 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
13983 "Regular expression matching the last line of a property drawer.")
13985 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
13986 "Regular expression matching the first line of a property drawer.")
13988 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
13989 "Regular expression matching the first line of a property drawer.")
13991 (defconst org-property-drawer-re
13992 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
13993 org-property-end-re "\\)\n?")
13994 "Matches an entire property drawer.")
13996 (defconst org-clock-drawer-re
13997 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
13998 org-property-end-re "\\)\n?")
13999 "Matches an entire clock drawer.")
14001 (defsubst org-re-property (property)
14002 "Return a regexp matching PROPERTY.
14003 Match group 1 will be set to the value "
14004 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
14006 (defun org-property-action ()
14007 "Do an action on properties."
14008 (interactive)
14009 (let (c)
14010 (org-at-property-p)
14011 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14012 (setq c (read-char-exclusive))
14013 (cond
14014 ((equal c ?s)
14015 (call-interactively 'org-set-property))
14016 ((equal c ?d)
14017 (call-interactively 'org-delete-property))
14018 ((equal c ?D)
14019 (call-interactively 'org-delete-property-globally))
14020 ((equal c ?c)
14021 (call-interactively 'org-compute-property-at-point))
14022 (t (error "No such property action %c" c)))))
14024 (defun org-set-effort (&optional value)
14025 "Set the effort property of the current entry.
14026 With numerical prefix arg, use the nth allowed value, 0 stands for the 10th
14027 allowed value."
14028 (interactive "P")
14029 (if (equal value 0) (setq value 10))
14030 (let* ((completion-ignore-case t)
14031 (prop org-effort-property)
14032 (cur (org-entry-get nil prop))
14033 (allowed (org-property-get-allowed-values nil prop 'table))
14034 (existing (mapcar 'list (org-property-values prop)))
14036 (val (cond
14037 ((stringp value) value)
14038 ((and allowed (integerp value))
14039 (or (car (nth (1- value) allowed))
14040 (car (org-last allowed))))
14041 (allowed
14042 (message "Select 1-9,0, [RET%s]: %s"
14043 (if cur (concat "=" cur) "")
14044 (mapconcat 'car allowed " "))
14045 (setq rpl (read-char-exclusive))
14046 (if (equal rpl ?\r)
14048 (setq rpl (- rpl ?0))
14049 (if (equal rpl 0) (setq rpl 10))
14050 (if (and (> rpl 0) (<= rpl (length allowed)))
14051 (car (nth (1- rpl) allowed))
14052 (org-completing-read "Effort: " allowed nil))))
14054 (let (org-completion-use-ido org-completion-use-iswitchb)
14055 (org-completing-read
14056 (concat "Effort " (if (and cur (string-match "\\S-" cur))
14057 (concat "[" cur "]") "")
14058 ": ")
14059 existing nil nil "" nil cur))))))
14060 (unless (equal (org-entry-get nil prop) val)
14061 (org-entry-put nil prop val))
14062 (message "%s is now %s" prop val)))
14064 (defun org-at-property-p ()
14065 "Is cursor inside a property drawer?"
14066 (save-excursion
14067 (beginning-of-line 1)
14068 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
14069 (save-match-data ;; Used by calling procedures
14070 (let ((p (point))
14071 (range (unless (org-before-first-heading-p)
14072 (org-get-property-block))))
14073 (and range (<= (car range) p) (< p (cdr range))))))))
14075 (defun org-get-property-block (&optional beg end force)
14076 "Return the (beg . end) range of the body of the property drawer.
14077 BEG and END can be beginning and end of subtree, if not given
14078 they will be found.
14079 If the drawer does not exist and FORCE is non-nil, create the drawer."
14080 (catch 'exit
14081 (save-excursion
14082 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
14083 (end (or end (progn (outline-next-heading) (point)))))
14084 (goto-char beg)
14085 (if (re-search-forward org-property-start-re end t)
14086 (setq beg (1+ (match-end 0)))
14087 (if force
14088 (save-excursion
14089 (org-insert-property-drawer)
14090 (setq end (progn (outline-next-heading) (point))))
14091 (throw 'exit nil))
14092 (goto-char beg)
14093 (if (re-search-forward org-property-start-re end t)
14094 (setq beg (1+ (match-end 0)))))
14095 (if (re-search-forward org-property-end-re end t)
14096 (setq end (match-beginning 0))
14097 (or force (throw 'exit nil))
14098 (goto-char beg)
14099 (setq end beg)
14100 (org-indent-line-function)
14101 (insert ":END:\n"))
14102 (cons beg end)))))
14104 (defun org-entry-properties (&optional pom which specific)
14105 "Get all properties of the entry at point-or-marker POM.
14106 This includes the TODO keyword, the tags, time strings for deadline,
14107 scheduled, and clocking, and any additional properties defined in the
14108 entry. The return value is an alist, keys may occur multiple times
14109 if the property key was used several times.
14110 POM may also be nil, in which case the current entry is used.
14111 If WHICH is nil or `all', get all properties. If WHICH is
14112 `special' or `standard', only get that subclass. If WHICH
14113 is a string only get exactly this property. SPECIFIC can be a string, the
14114 specific property we are interested in. Specifying it can speed
14115 things up because then unnecessary parsing is avoided."
14116 (setq which (or which 'all))
14117 (org-with-point-at pom
14118 (let ((clockstr (substring org-clock-string 0 -1))
14119 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
14120 (case-fold-search nil)
14121 beg end range props sum-props key key1 value string clocksum)
14122 (save-excursion
14123 (when (condition-case nil
14124 (and (eq major-mode 'org-mode) (org-back-to-heading t))
14125 (error nil))
14126 (setq beg (point))
14127 (setq sum-props (get-text-property (point) 'org-summaries))
14128 (setq clocksum (get-text-property (point) :org-clock-minutes))
14129 (outline-next-heading)
14130 (setq end (point))
14131 (when (memq which '(all special))
14132 ;; Get the special properties, like TODO and tags
14133 (goto-char beg)
14134 (when (and (or (not specific) (string= specific "TODO"))
14135 (looking-at org-todo-line-regexp) (match-end 2))
14136 (push (cons "TODO" (org-match-string-no-properties 2)) props))
14137 (when (and (or (not specific) (string= specific "PRIORITY"))
14138 (looking-at org-priority-regexp))
14139 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
14140 (when (or (not specific) (string= specific "FILE"))
14141 (push (cons "FILE" buffer-file-name) props))
14142 (when (and (or (not specific) (string= specific "TAGS"))
14143 (setq value (org-get-tags-string))
14144 (string-match "\\S-" value))
14145 (push (cons "TAGS" value) props))
14146 (when (and (or (not specific) (string= specific "ALLTAGS"))
14147 (setq value (org-get-tags-at)))
14148 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
14149 ":"))
14150 props))
14151 (when (or (not specific) (string= specific "BLOCKED"))
14152 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
14153 (when (or (not specific)
14154 (member specific
14155 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
14156 "TIMESTAMP" "TIMESTAMP_IA")))
14157 (catch 'match
14158 (while (re-search-forward org-maybe-keyword-time-regexp end t)
14159 (setq key (if (match-end 1)
14160 (substring (org-match-string-no-properties 1)
14161 0 -1))
14162 string (if (equal key clockstr)
14163 (org-no-properties
14164 (org-trim
14165 (buffer-substring
14166 (match-beginning 3) (goto-char
14167 (point-at-eol)))))
14168 (substring (org-match-string-no-properties 3)
14169 1 -1)))
14170 ;; Get the correct property name from the key. This is
14171 ;; necessary if the user has configured time keywords.
14172 (setq key1 (concat key ":"))
14173 (cond
14174 ((not key)
14175 (setq key
14176 (if (= (char-after (match-beginning 3)) ?\[)
14177 "TIMESTAMP_IA" "TIMESTAMP")))
14178 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
14179 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
14180 ((equal key1 org-closed-string) (setq key "CLOSED"))
14181 ((equal key1 org-clock-string) (setq key "CLOCK")))
14182 (if (and specific (equal key specific) (not (equal key "CLOCK")))
14183 (progn
14184 (push (cons key string) props)
14185 ;; no need to search further if match is found
14186 (throw 'match t))
14187 (when (or (equal key "CLOCK") (not (assoc key props)))
14188 (push (cons key string) props))))))
14191 (when (memq which '(all standard))
14192 ;; Get the standard properties, like :PROP: ...
14193 (setq range (org-get-property-block beg end))
14194 (when range
14195 (goto-char (car range))
14196 (while (re-search-forward
14197 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
14198 (cdr range) t)
14199 (setq key (org-match-string-no-properties 1)
14200 value (org-trim (or (org-match-string-no-properties 2) "")))
14201 (unless (member key excluded)
14202 (push (cons key (or value "")) props)))))
14203 (if clocksum
14204 (push (cons "CLOCKSUM"
14205 (org-columns-number-to-string (/ (float clocksum) 60.)
14206 'add_times))
14207 props))
14208 (unless (assoc "CATEGORY" props)
14209 (push (cons "CATEGORY" (org-get-category)) props))
14210 (append sum-props (nreverse props)))))))
14212 (defun org-entry-get (pom property &optional inherit literal-nil)
14213 "Get value of PROPERTY for entry at point-or-marker POM.
14214 If INHERIT is non-nil and the entry does not have the property,
14215 then also check higher levels of the hierarchy.
14216 If INHERIT is the symbol `selective', use inheritance only if the setting
14217 in `org-use-property-inheritance' selects PROPERTY for inheritance.
14218 If the property is present but empty, the return value is the empty string.
14219 If the property is not present at all, nil is returned.
14221 If LITERAL-NIL is set, return the string value \"nil\" as a string,
14222 do not interpret it as the list atom nil. This is used for inheritance
14223 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
14224 (org-with-point-at pom
14225 (if (and inherit (if (eq inherit 'selective)
14226 (org-property-inherit-p property)
14228 (org-entry-get-with-inheritance property literal-nil)
14229 (if (member property org-special-properties)
14230 ;; We need a special property. Use `org-entry-properties' to
14231 ;; retrieve it, but specify the wanted property
14232 (cdr (assoc property (org-entry-properties nil 'special property)))
14233 (let ((range (unless (org-before-first-heading-p)
14234 (org-get-property-block)))
14235 (props (list (or (assoc property org-file-properties)
14236 (assoc property org-global-properties)
14237 (assoc property org-global-properties-fixed))))
14238 val)
14239 (flet ((ap (key)
14240 (when (re-search-forward
14241 (org-re-property key) (cdr range) t)
14242 (setq props
14243 (org-update-property-plist
14245 (if (match-end 1)
14246 (org-match-string-no-properties 1) "")
14247 props)))))
14248 (when (and range (goto-char (car range)))
14249 (ap property)
14250 (goto-char (car range))
14251 (while (ap (concat property "+")))
14252 (setq val (cdr (assoc property props)))
14253 (when val (if literal-nil val (org-not-nil val))))))))))
14255 (defun org-property-or-variable-value (var &optional inherit)
14256 "Check if there is a property fixing the value of VAR.
14257 If yes, return this value. If not, return the current value of the variable."
14258 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14259 (if (and prop (stringp prop) (string-match "\\S-" prop))
14260 (read prop)
14261 (symbol-value var))))
14263 (defun org-entry-delete (pom property)
14264 "Delete the property PROPERTY from entry at point-or-marker POM."
14265 (org-with-point-at pom
14266 (if (member property org-special-properties)
14267 nil ; cannot delete these properties.
14268 (let ((range (org-get-property-block)))
14269 (if (and range
14270 (goto-char (car range))
14271 (re-search-forward
14272 (org-re-property property)
14273 (cdr range) t))
14274 (progn
14275 (delete-region (match-beginning 0) (1+ (point-at-eol)))
14277 nil)))))
14279 ;; Multi-values properties are properties that contain multiple values
14280 ;; These values are assumed to be single words, separated by whitespace.
14281 (defun org-entry-add-to-multivalued-property (pom property value)
14282 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
14283 (let* ((old (org-entry-get pom property))
14284 (values (and old (org-split-string old "[ \t]"))))
14285 (setq value (org-entry-protect-space value))
14286 (unless (member value values)
14287 (setq values (cons value values))
14288 (org-entry-put pom property
14289 (mapconcat 'identity values " ")))))
14291 (defun org-entry-remove-from-multivalued-property (pom property value)
14292 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
14293 (let* ((old (org-entry-get pom property))
14294 (values (and old (org-split-string old "[ \t]"))))
14295 (setq value (org-entry-protect-space value))
14296 (when (member value values)
14297 (setq values (delete value values))
14298 (org-entry-put pom property
14299 (mapconcat 'identity values " ")))))
14301 (defun org-entry-member-in-multivalued-property (pom property value)
14302 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
14303 (let* ((old (org-entry-get pom property))
14304 (values (and old (org-split-string old "[ \t]"))))
14305 (setq value (org-entry-protect-space value))
14306 (member value values)))
14308 (defun org-entry-get-multivalued-property (pom property)
14309 "Return a list of values in a multivalued property."
14310 (let* ((value (org-entry-get pom property))
14311 (values (and value (org-split-string value "[ \t]"))))
14312 (mapcar 'org-entry-restore-space values)))
14314 (defun org-entry-put-multivalued-property (pom property &rest values)
14315 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
14316 VALUES should be a list of strings. Spaces will be protected."
14317 (org-entry-put pom property
14318 (mapconcat 'org-entry-protect-space values " "))
14319 (let* ((value (org-entry-get pom property))
14320 (values (and value (org-split-string value "[ \t]"))))
14321 (mapcar 'org-entry-restore-space values)))
14323 (defun org-entry-protect-space (s)
14324 "Protect spaces and newline in string S."
14325 (while (string-match " " s)
14326 (setq s (replace-match "%20" t t s)))
14327 (while (string-match "\n" s)
14328 (setq s (replace-match "%0A" t t s)))
14331 (defun org-entry-restore-space (s)
14332 "Restore spaces and newline in string S."
14333 (while (string-match "%20" s)
14334 (setq s (replace-match " " t t s)))
14335 (while (string-match "%0A" s)
14336 (setq s (replace-match "\n" t t s)))
14339 (defvar org-entry-property-inherited-from (make-marker)
14340 "Marker pointing to the entry from where a property was inherited.
14341 Each call to `org-entry-get-with-inheritance' will set this marker to the
14342 location of the entry where the inheritance search matched. If there was
14343 no match, the marker will point nowhere.
14344 Note that also `org-entry-get' calls this function, if the INHERIT flag
14345 is set.")
14347 (defun org-entry-get-with-inheritance (property &optional literal-nil)
14348 "Get entry property, and search higher levels if not present.
14349 The search will stop at the first ancestor which has the property defined.
14350 If the value found is \"nil\", return nil to show that the property
14351 should be considered as undefined (this is the meaning of nil here).
14352 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
14353 (move-marker org-entry-property-inherited-from nil)
14354 (let (tmp)
14355 (unless (org-before-first-heading-p)
14356 (save-excursion
14357 (save-restriction
14358 (widen)
14359 (catch 'ex
14360 (while t
14361 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
14362 (org-back-to-heading t)
14363 (move-marker org-entry-property-inherited-from (point))
14364 (throw 'ex tmp))
14365 (or (org-up-heading-safe) (throw 'ex nil)))))))
14366 (setq tmp (or tmp
14367 (cdr (assoc property org-file-properties))
14368 (cdr (assoc property org-global-properties))
14369 (cdr (assoc property org-global-properties-fixed))))
14370 (if literal-nil tmp (org-not-nil tmp))))
14372 (defvar org-property-changed-functions nil
14373 "Hook called when the value of a property has changed.
14374 Each hook function should accept two arguments, the name of the property
14375 and the new value.")
14377 (defun org-entry-put (pom property value)
14378 "Set PROPERTY to VALUE for entry at point-or-marker POM."
14379 (org-with-point-at pom
14380 (org-back-to-heading t)
14381 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
14382 range)
14383 (cond
14384 ((equal property "TODO")
14385 (when (and (stringp value) (string-match "\\S-" value)
14386 (not (member value org-todo-keywords-1)))
14387 (error "\"%s\" is not a valid TODO state" value))
14388 (if (or (not value)
14389 (not (string-match "\\S-" value)))
14390 (setq value 'none))
14391 (org-todo value)
14392 (org-set-tags nil 'align))
14393 ((equal property "PRIORITY")
14394 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
14395 (string-to-char value) ?\ ))
14396 (org-set-tags nil 'align))
14397 ((equal property "SCHEDULED")
14398 (if (re-search-forward org-scheduled-time-regexp end t)
14399 (cond
14400 ((eq value 'earlier) (org-timestamp-change -1 'day))
14401 ((eq value 'later) (org-timestamp-change 1 'day))
14402 (t (call-interactively 'org-schedule)))
14403 (call-interactively 'org-schedule)))
14404 ((equal property "DEADLINE")
14405 (if (re-search-forward org-deadline-time-regexp end t)
14406 (cond
14407 ((eq value 'earlier) (org-timestamp-change -1 'day))
14408 ((eq value 'later) (org-timestamp-change 1 'day))
14409 (t (call-interactively 'org-deadline)))
14410 (call-interactively 'org-deadline)))
14411 ((member property org-special-properties)
14412 (error "The %s property can not yet be set with `org-entry-put'"
14413 property))
14414 (t ; a non-special property
14415 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
14416 (setq range (org-get-property-block beg end 'force))
14417 (goto-char (car range))
14418 (if (re-search-forward
14419 (org-re-property property) (cdr range) t)
14420 (progn
14421 (delete-region (match-beginning 0) (match-end 0))
14422 (goto-char (match-beginning 0)))
14423 (goto-char (cdr range))
14424 (insert "\n")
14425 (backward-char 1)
14426 (org-indent-line-function))
14427 (insert ":" property ":")
14428 (and value (insert " " value))
14429 (org-indent-line-function)))))
14430 (run-hook-with-args 'org-property-changed-functions property value)))
14432 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
14433 "Get all property keys in the current buffer.
14434 With INCLUDE-SPECIALS, also list the special properties that reflect things
14435 like tags and TODO state.
14436 With INCLUDE-DEFAULTS, also include properties that has special meaning
14437 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
14438 and others.
14439 With INCLUDE-COLUMNS, also include property names given in COLUMN
14440 formats in the current buffer."
14441 (let (rtn range cfmt s p)
14442 (save-excursion
14443 (save-restriction
14444 (widen)
14445 (goto-char (point-min))
14446 (while (re-search-forward org-property-start-re nil t)
14447 (setq range (org-get-property-block))
14448 (goto-char (car range))
14449 (while (re-search-forward
14450 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
14451 (cdr range) t)
14452 (add-to-list 'rtn (org-match-string-no-properties 1)))
14453 (outline-next-heading))))
14455 (when include-specials
14456 (setq rtn (append org-special-properties rtn)))
14458 (when include-defaults
14459 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
14460 (add-to-list 'rtn org-effort-property))
14462 (when include-columns
14463 (save-excursion
14464 (save-restriction
14465 (widen)
14466 (goto-char (point-min))
14467 (while (re-search-forward
14468 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
14469 nil t)
14470 (setq cfmt (match-string 2) s 0)
14471 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
14472 cfmt s)
14473 (setq s (match-end 0)
14474 p (match-string 1 cfmt))
14475 (unless (or (equal p "ITEM")
14476 (member p org-special-properties))
14477 (add-to-list 'rtn (match-string 1 cfmt))))))))
14479 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
14481 (defun org-property-values (key)
14482 "Return a list of all values of property KEY in the current buffer."
14483 (save-excursion
14484 (save-restriction
14485 (widen)
14486 (goto-char (point-min))
14487 (let ((re (org-re-property key))
14488 values)
14489 (while (re-search-forward re nil t)
14490 (add-to-list 'values (org-trim (match-string 1))))
14491 (delete "" values)))))
14493 (defun org-insert-property-drawer ()
14494 "Insert a property drawer into the current entry."
14495 (org-back-to-heading t)
14496 (looking-at org-outline-regexp)
14497 (let ((indent (if org-adapt-indentation
14498 (- (match-end 0) (match-beginning 0))
14500 (beg (point))
14501 (re (concat "^[ \t]*" org-keyword-time-regexp))
14502 end hiddenp)
14503 (outline-next-heading)
14504 (setq end (point))
14505 (goto-char beg)
14506 (while (re-search-forward re end t))
14507 (setq hiddenp (outline-invisible-p))
14508 (end-of-line 1)
14509 (and (equal (char-after) ?\n) (forward-char 1))
14510 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
14511 (if (member (match-string 1) '("CLOCK:" ":END:"))
14512 ;; just skip this line
14513 (beginning-of-line 2)
14514 ;; Drawer start, find the end
14515 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
14516 (beginning-of-line 1)))
14517 (org-skip-over-state-notes)
14518 (skip-chars-backward " \t\n\r")
14519 (if (eq (char-before) ?*) (forward-char 1))
14520 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
14521 (beginning-of-line 0)
14522 (org-indent-to-column indent)
14523 (beginning-of-line 2)
14524 (org-indent-to-column indent)
14525 (beginning-of-line 0)
14526 (if hiddenp
14527 (save-excursion
14528 (org-back-to-heading t)
14529 (hide-entry))
14530 (org-flag-drawer t))))
14532 (defun org-insert-drawer (&optional arg drawer)
14533 "Insert a drawer at point.
14535 Optional argument DRAWER, when non-nil, is a string representing
14536 drawer's name. Otherwise, the user is prompted for a name.
14538 If a region is active, insert the drawer around that region
14539 instead.
14541 Point is left between drawer's boundaries."
14542 (interactive "P")
14543 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
14544 "LOGBOOK"))
14545 ;; SYSTEM-DRAWERS is a list of drawer names that are used
14546 ;; internally by Org. They are meant to be inserted
14547 ;; automatically.
14548 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
14549 ;; Remove system drawers from list. Note: For some reason,
14550 ;; `org-completing-read' ignores the predicate while
14551 ;; `completing-read' handles it fine.
14552 (drawer (if arg "PROPERTIES"
14553 (or drawer
14554 (completing-read
14555 "Drawer: " org-drawers
14556 (lambda (d) (not (member d system-drawers))))))))
14557 (cond
14558 ;; With C-u, fall back on `org-insert-property-drawer'
14559 (arg (org-insert-property-drawer))
14560 ;; With an active region, insert a drawer at point.
14561 ((not (org-region-active-p))
14562 (progn
14563 (unless (bolp) (insert "\n"))
14564 (insert (format ":%s:\n\n:END:\n" drawer))
14565 (forward-line -2)))
14566 ;; Otherwise, insert the drawer at point
14568 (let ((rbeg (region-beginning))
14569 (rend (copy-marker (region-end))))
14570 (unwind-protect
14571 (progn
14572 (goto-char rbeg)
14573 (beginning-of-line)
14574 (when (save-excursion
14575 (re-search-forward org-outline-regexp-bol rend t))
14576 (error "Drawers cannot contain headlines"))
14577 ;; Position point at the beginning of the first
14578 ;; non-blank line in region. Insert drawer's opening
14579 ;; there, then indent it.
14580 (org-skip-whitespace)
14581 (beginning-of-line)
14582 (insert ":" drawer ":\n")
14583 (forward-line -1)
14584 (indent-for-tab-command)
14585 ;; Move point to the beginning of the first blank line
14586 ;; after the last non-blank line in region. Insert
14587 ;; drawer's closing, then indent it.
14588 (goto-char rend)
14589 (skip-chars-backward " \r\t\n")
14590 (insert "\n:END:")
14591 (indent-for-tab-command)
14592 (unless (eolp) (insert "\n")))
14593 ;; Clear marker, whatever the outcome of insertion is.
14594 (set-marker rend nil)))))))
14596 (defvar org-property-set-functions-alist nil
14597 "Property set function alist.
14598 Each entry should have the following format:
14600 (PROPERTY . READ-FUNCTION)
14602 The read function will be called with the same argument as
14603 `org-completing-read'.")
14605 (defun org-set-property-function (property)
14606 "Get the function that should be used to set PROPERTY.
14607 This is computed according to `org-property-set-functions-alist'."
14608 (or (cdr (assoc property org-property-set-functions-alist))
14609 'org-completing-read))
14611 (defun org-read-property-value (property)
14612 "Read PROPERTY value from user."
14613 (let* ((completion-ignore-case t)
14614 (allowed (org-property-get-allowed-values nil property 'table))
14615 (cur (org-entry-get nil property))
14616 (prompt (concat property " value"
14617 (if (and cur (string-match "\\S-" cur))
14618 (concat " [" cur "]") "") ": "))
14619 (set-function (org-set-property-function property))
14620 (val (if allowed
14621 (funcall set-function prompt allowed nil
14622 (not (get-text-property 0 'org-unrestricted
14623 (caar allowed))))
14624 (let (org-completion-use-ido org-completion-use-iswitchb)
14625 (funcall set-function prompt
14626 (mapcar 'list (org-property-values property))
14627 nil nil "" nil cur)))))
14628 (if (equal val "")
14630 val)))
14632 (defvar org-last-set-property nil)
14633 (defun org-read-property-name ()
14634 "Read a property name."
14635 (let* ((completion-ignore-case t)
14636 (keys (org-buffer-property-keys nil t t))
14637 (default-prop (or (save-excursion
14638 (save-match-data
14639 (beginning-of-line)
14640 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
14641 (null (string= (match-string 1) "END"))
14642 (match-string 1))))
14643 org-last-set-property))
14644 (property (org-icompleting-read
14645 (concat "Property"
14646 (if default-prop (concat " [" default-prop "]") "")
14647 ": ")
14648 (mapcar 'list keys)
14649 nil nil nil nil
14650 default-prop
14652 (if (member property keys)
14653 property
14654 (or (cdr (assoc (downcase property)
14655 (mapcar (lambda (x) (cons (downcase x) x))
14656 keys)))
14657 property))))
14659 (defun org-set-property (property value)
14660 "In the current entry, set PROPERTY to VALUE.
14661 When called interactively, this will prompt for a property name, offering
14662 completion on existing and default properties. And then it will prompt
14663 for a value, offering completion either on allowed values (via an inherited
14664 xxx_ALL property) or on existing values in other instances of this property
14665 in the current file."
14666 (interactive (list nil nil))
14667 (let* ((property (or property (org-read-property-name)))
14668 (value (or value (org-read-property-value property)))
14669 (fn (assoc property org-properties-postprocess-alist)))
14670 (setq org-last-set-property property)
14671 ;; Possibly postprocess the inserted value:
14672 (when fn (setq value (funcall (cadr fn) value)))
14673 (unless (equal (org-entry-get nil property) value)
14674 (org-entry-put nil property value))))
14676 (defun org-delete-property (property)
14677 "In the current entry, delete PROPERTY."
14678 (interactive
14679 (let* ((completion-ignore-case t)
14680 (prop (org-icompleting-read "Property: "
14681 (org-entry-properties nil 'standard))))
14682 (list prop)))
14683 (message "Property %s %s" property
14684 (if (org-entry-delete nil property)
14685 "deleted"
14686 "was not present in the entry")))
14688 (defun org-delete-property-globally (property)
14689 "Remove PROPERTY globally, from all entries."
14690 (interactive
14691 (let* ((completion-ignore-case t)
14692 (prop (org-icompleting-read
14693 "Globally remove property: "
14694 (mapcar 'list (org-buffer-property-keys)))))
14695 (list prop)))
14696 (save-excursion
14697 (save-restriction
14698 (widen)
14699 (goto-char (point-min))
14700 (let ((cnt 0))
14701 (while (re-search-forward
14702 (org-re-property property)
14703 nil t)
14704 (setq cnt (1+ cnt))
14705 (delete-region (match-beginning 0) (1+ (point-at-eol))))
14706 (message "Property \"%s\" removed from %d entries" property cnt)))))
14708 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
14710 (defun org-compute-property-at-point ()
14711 "Compute the property at point.
14712 This looks for an enclosing column format, extracts the operator and
14713 then applies it to the property in the column format's scope."
14714 (interactive)
14715 (unless (org-at-property-p)
14716 (error "Not at a property"))
14717 (let ((prop (org-match-string-no-properties 2)))
14718 (org-columns-get-format-and-top-level)
14719 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
14720 (error "No operator defined for property %s" prop))
14721 (org-columns-compute prop)))
14723 (defvar org-property-allowed-value-functions nil
14724 "Hook for functions supplying allowed values for a specific property.
14725 The functions must take a single argument, the name of the property, and
14726 return a flat list of allowed values. If \":ETC\" is one of
14727 the values, this means that these values are intended as defaults for
14728 completion, but that other values should be allowed too.
14729 The functions must return nil if they are not responsible for this
14730 property.")
14732 (defun org-property-get-allowed-values (pom property &optional table)
14733 "Get allowed values for the property PROPERTY.
14734 When TABLE is non-nil, return an alist that can directly be used for
14735 completion."
14736 (let (vals)
14737 (cond
14738 ((equal property "TODO")
14739 (setq vals (org-with-point-at pom
14740 (append org-todo-keywords-1 '("")))))
14741 ((equal property "PRIORITY")
14742 (let ((n org-lowest-priority))
14743 (while (>= n org-highest-priority)
14744 (push (char-to-string n) vals)
14745 (setq n (1- n)))))
14746 ((member property org-special-properties))
14747 ((setq vals (run-hook-with-args-until-success
14748 'org-property-allowed-value-functions property)))
14750 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
14751 (when (and vals (string-match "\\S-" vals))
14752 (setq vals (car (read-from-string (concat "(" vals ")"))))
14753 (setq vals (mapcar (lambda (x)
14754 (cond ((stringp x) x)
14755 ((numberp x) (number-to-string x))
14756 ((symbolp x) (symbol-name x))
14757 (t "???")))
14758 vals)))))
14759 (when (member ":ETC" vals)
14760 (setq vals (remove ":ETC" vals))
14761 (org-add-props (car vals) '(org-unrestricted t)))
14762 (if table (mapcar 'list vals) vals)))
14764 (defun org-property-previous-allowed-value (&optional previous)
14765 "Switch to the next allowed value for this property."
14766 (interactive)
14767 (org-property-next-allowed-value t))
14769 (defun org-property-next-allowed-value (&optional previous)
14770 "Switch to the next allowed value for this property."
14771 (interactive)
14772 (unless (org-at-property-p)
14773 (error "Not at a property"))
14774 (let* ((key (match-string 2))
14775 (value (match-string 3))
14776 (allowed (or (org-property-get-allowed-values (point) key)
14777 (and (member value '("[ ]" "[-]" "[X]"))
14778 '("[ ]" "[X]"))))
14779 nval)
14780 (unless allowed
14781 (error "Allowed values for this property have not been defined"))
14782 (if previous (setq allowed (reverse allowed)))
14783 (if (member value allowed)
14784 (setq nval (car (cdr (member value allowed)))))
14785 (setq nval (or nval (car allowed)))
14786 (if (equal nval value)
14787 (error "Only one allowed value for this property"))
14788 (org-at-property-p)
14789 (replace-match (concat " :" key ": " nval) t t)
14790 (org-indent-line-function)
14791 (beginning-of-line 1)
14792 (skip-chars-forward " \t")
14793 (run-hook-with-args 'org-property-changed-functions key nval)))
14795 (defun org-find-olp (path &optional this-buffer)
14796 "Return a marker pointing to the entry at outline path OLP.
14797 If anything goes wrong, throw an error.
14798 You can wrap this call to catch the error like this:
14800 (condition-case msg
14801 (org-mobile-locate-entry (match-string 4))
14802 (error (nth 1 msg)))
14804 The return value will then be either a string with the error message,
14805 or a marker if everything is OK.
14807 If THIS-BUFFER is set, the outline path does not contain a file,
14808 only headings."
14809 (let* ((file (if this-buffer buffer-file-name (pop path)))
14810 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
14811 (level 1)
14812 (lmin 1)
14813 (lmax 1)
14814 limit re end found pos heading cnt flevel)
14815 (unless buffer (error "File not found :%s" file))
14816 (with-current-buffer buffer
14817 (save-excursion
14818 (save-restriction
14819 (widen)
14820 (setq limit (point-max))
14821 (goto-char (point-min))
14822 (while (setq heading (pop path))
14823 (setq re (format org-complex-heading-regexp-format
14824 (regexp-quote heading)))
14825 (setq cnt 0 pos (point))
14826 (while (re-search-forward re end t)
14827 (setq level (- (match-end 1) (match-beginning 1)))
14828 (if (and (>= level lmin) (<= level lmax))
14829 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
14830 (when (= cnt 0) (error "Heading not found on level %d: %s"
14831 lmax heading))
14832 (when (> cnt 1) (error "Heading not unique on level %d: %s"
14833 lmax heading))
14834 (goto-char found)
14835 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
14836 (setq end (save-excursion (org-end-of-subtree t t))))
14837 (when (org-at-heading-p)
14838 (move-marker (make-marker) (point))))))))
14840 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
14841 "Find node HEADING in BUFFER.
14842 Return a marker to the heading if it was found, or nil if not.
14843 If POS-ONLY is set, return just the position instead of a marker.
14845 The heading text must match exact, but it may have a TODO keyword,
14846 a priority cookie and tags in the standard locations."
14847 (with-current-buffer (or buffer (current-buffer))
14848 (save-excursion
14849 (save-restriction
14850 (widen)
14851 (goto-char (point-min))
14852 (let (case-fold-search)
14853 (if (re-search-forward
14854 (format org-complex-heading-regexp-format
14855 (regexp-quote heading)) nil t)
14856 (if pos-only
14857 (match-beginning 0)
14858 (move-marker (make-marker) (match-beginning 0)))))))))
14860 (defun org-find-exact-heading-in-directory (heading &optional dir)
14861 "Find Org node headline HEADING in all .org files in directory DIR.
14862 When the target headline is found, return a marker to this location."
14863 (let ((files (directory-files (or dir default-directory)
14864 nil "\\`[^.#].*\\.org\\'"))
14865 file visiting m buffer)
14866 (catch 'found
14867 (while (setq file (pop files))
14868 (message "trying %s" file)
14869 (setq visiting (org-find-base-buffer-visiting file))
14870 (setq buffer (or visiting (find-file-noselect file)))
14871 (setq m (org-find-exact-headline-in-buffer
14872 heading buffer))
14873 (when (and (not m) (not visiting)) (kill-buffer buffer))
14874 (and m (throw 'found m))))))
14876 (defun org-find-entry-with-id (ident)
14877 "Locate the entry that contains the ID property with exact value IDENT.
14878 IDENT can be a string, a symbol or a number, this function will search for
14879 the string representation of it.
14880 Return the position where this entry starts, or nil if there is no such entry."
14881 (interactive "sID: ")
14882 (let ((id (cond
14883 ((stringp ident) ident)
14884 ((symbol-name ident) (symbol-name ident))
14885 ((numberp ident) (number-to-string ident))
14886 (t (error "IDENT %s must be a string, symbol or number" ident))))
14887 (case-fold-search nil))
14888 (save-excursion
14889 (save-restriction
14890 (widen)
14891 (goto-char (point-min))
14892 (when (re-search-forward
14893 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
14894 nil t)
14895 (org-back-to-heading t)
14896 (point))))))
14898 ;;;; Timestamps
14900 (defvar org-last-changed-timestamp nil)
14901 (defvar org-last-inserted-timestamp nil
14902 "The last time stamp inserted with `org-insert-time-stamp'.")
14903 (defvar org-time-was-given) ; dynamically scoped parameter
14904 (defvar org-end-time-was-given) ; dynamically scoped parameter
14905 (defvar org-ts-what) ; dynamically scoped parameter
14907 (defun org-time-stamp (arg &optional inactive)
14908 "Prompt for a date/time and insert a time stamp.
14909 If the user specifies a time like HH:MM, or if this command is called
14910 with a prefix argument, the time stamp will contain date and time.
14911 Otherwise, only the date will be included. All parts of a date not
14912 specified by the user will be filled in from the current date/time.
14913 So if you press just return without typing anything, the time stamp
14914 will represent the current date/time. If there is already a timestamp
14915 at the cursor, it will be modified."
14916 (interactive "P")
14917 (let* ((ts nil)
14918 (default-time
14919 ;; Default time is either today, or, when entering a range,
14920 ;; the range start.
14921 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
14922 (save-excursion
14923 (re-search-backward
14924 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
14925 (- (point) 20) t)))
14926 (apply 'encode-time (org-parse-time-string (match-string 1)))
14927 (current-time)))
14928 (default-input (and ts (org-get-compact-tod ts)))
14929 (repeater (save-excursion
14930 (save-match-data
14931 (beginning-of-line)
14932 (when (re-search-forward
14933 "\\([.+-]+[0-9]+[dwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[dwmy]\\)?\\) ?"
14934 (save-excursion (progn (end-of-line) (point))) t)
14935 (match-string 0)))))
14936 org-time-was-given org-end-time-was-given time)
14937 (cond
14938 ((and (org-at-timestamp-p t)
14939 (memq last-command '(org-time-stamp org-time-stamp-inactive))
14940 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
14941 (insert "--")
14942 (setq time (let ((this-command this-command))
14943 (org-read-date arg 'totime nil nil
14944 default-time default-input inactive)))
14945 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
14946 ((org-at-timestamp-p t)
14947 (setq time (let ((this-command this-command))
14948 (org-read-date arg 'totime nil nil default-time default-input inactive)))
14949 (when (org-at-timestamp-p t) ; just to get the match data
14950 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
14951 (replace-match "")
14952 (setq org-last-changed-timestamp
14953 (org-insert-time-stamp
14954 time (or org-time-was-given arg)
14955 inactive nil nil (list org-end-time-was-given)))
14956 (when repeater (goto-char (1- (point))) (insert " " repeater)
14957 (setq org-last-changed-timestamp
14958 (concat (substring org-last-inserted-timestamp 0 -1)
14959 " " repeater ">"))))
14960 (message "Timestamp updated"))
14962 (setq time (let ((this-command this-command))
14963 (org-read-date arg 'totime nil nil default-time default-input inactive)))
14964 (org-insert-time-stamp time (or org-time-was-given arg) inactive
14965 nil nil (list org-end-time-was-given))))))
14967 ;; FIXME: can we use this for something else, like computing time differences?
14968 (defun org-get-compact-tod (s)
14969 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
14970 (let* ((t1 (match-string 1 s))
14971 (h1 (string-to-number (match-string 2 s)))
14972 (m1 (string-to-number (match-string 3 s)))
14973 (t2 (and (match-end 4) (match-string 5 s)))
14974 (h2 (and t2 (string-to-number (match-string 6 s))))
14975 (m2 (and t2 (string-to-number (match-string 7 s))))
14976 dh dm)
14977 (if (not t2)
14979 (setq dh (- h2 h1) dm (- m2 m1))
14980 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
14981 (concat t1 "+" (number-to-string dh)
14982 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
14984 (defun org-time-stamp-inactive (&optional arg)
14985 "Insert an inactive time stamp.
14986 An inactive time stamp is enclosed in square brackets instead of angle
14987 brackets. It is inactive in the sense that it does not trigger agenda entries,
14988 does not link to the calendar and cannot be changed with the S-cursor keys.
14989 So these are more for recording a certain time/date."
14990 (interactive "P")
14991 (org-time-stamp arg 'inactive))
14993 (defvar org-date-ovl (make-overlay 1 1))
14994 (overlay-put org-date-ovl 'face 'org-date-selected)
14995 (org-detach-overlay org-date-ovl)
14997 (defvar org-ans1) ; dynamically scoped parameter
14998 (defvar org-ans2) ; dynamically scoped parameter
15000 (defvar org-plain-time-of-day-regexp) ; defined below
15002 (defvar org-overriding-default-time nil) ; dynamically scoped
15003 (defvar org-read-date-overlay nil)
15004 (defvar org-dcst nil) ; dynamically scoped
15005 (defvar org-read-date-history nil)
15006 (defvar org-read-date-final-answer nil)
15007 (defvar org-read-date-analyze-futurep nil)
15008 (defvar org-read-date-analyze-forced-year nil)
15009 (defvar org-read-date-inactive)
15011 (defun org-read-date (&optional org-with-time to-time from-string prompt
15012 default-time default-input inactive)
15013 "Read a date, possibly a time, and make things smooth for the user.
15014 The prompt will suggest to enter an ISO date, but you can also enter anything
15015 which will at least partially be understood by `parse-time-string'.
15016 Unrecognized parts of the date will default to the current day, month, year,
15017 hour and minute. If this command is called to replace a timestamp at point,
15018 or to enter the second timestamp of a range, the default time is taken
15019 from the existing stamp. Furthermore, the command prefers the future,
15020 so if you are giving a date where the year is not given, and the day-month
15021 combination is already past in the current year, it will assume you
15022 mean next year. For details, see the manual. A few examples:
15024 3-2-5 --> 2003-02-05
15025 feb 15 --> currentyear-02-15
15026 2/15 --> currentyear-02-15
15027 sep 12 9 --> 2009-09-12
15028 12:45 --> today 12:45
15029 22 sept 0:34 --> currentyear-09-22 0:34
15030 12 --> currentyear-currentmonth-12
15031 Fri --> nearest Friday (today or later)
15032 etc.
15034 Furthermore you can specify a relative date by giving, as the *first* thing
15035 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
15036 change in days weeks, months, years.
15037 With a single plus or minus, the date is relative to today. With a double
15038 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
15039 +4d --> four days from today
15040 +4 --> same as above
15041 +2w --> two weeks from today
15042 ++5 --> five days from default date
15044 The function understands only English month and weekday abbreviations.
15046 While prompting, a calendar is popped up - you can also select the
15047 date with the mouse (button 1). The calendar shows a period of three
15048 months. To scroll it to other months, use the keys `>' and `<'.
15049 If you don't like the calendar, turn it off with
15050 \(setq org-read-date-popup-calendar nil)
15052 With optional argument TO-TIME, the date will immediately be converted
15053 to an internal time.
15054 With an optional argument WITH-TIME, the prompt will suggest to also
15055 insert a time. Note that when WITH-TIME is not set, you can still
15056 enter a time, and this function will inform the calling routine about
15057 this change. The calling routine may then choose to change the format
15058 used to insert the time stamp into the buffer to include the time.
15059 With optional argument FROM-STRING, read from this string instead from
15060 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
15061 the time/date that is used for everything that is not specified by the
15062 user."
15063 (require 'parse-time)
15064 (let* ((org-time-stamp-rounding-minutes
15065 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
15066 (org-dcst org-display-custom-times)
15067 (ct (org-current-time))
15068 (org-def (or org-overriding-default-time default-time ct))
15069 (org-defdecode (decode-time org-def))
15070 (dummy (progn
15071 (when (< (nth 2 org-defdecode) org-extend-today-until)
15072 (setcar (nthcdr 2 org-defdecode) -1)
15073 (setcar (nthcdr 1 org-defdecode) 59)
15074 (setq org-def (apply 'encode-time org-defdecode)
15075 org-defdecode (decode-time org-def)))))
15076 (calendar-frame-setup nil)
15077 (calendar-setup nil)
15078 (calendar-move-hook nil)
15079 (calendar-view-diary-initially-flag nil)
15080 (calendar-view-holidays-initially-flag nil)
15081 (timestr (format-time-string
15082 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
15083 (prompt (concat (if prompt (concat prompt " ") "")
15084 (format "Date+time [%s]: " timestr)))
15085 ans (org-ans0 "") org-ans1 org-ans2 final)
15087 (cond
15088 (from-string (setq ans from-string))
15089 (org-read-date-popup-calendar
15090 (save-excursion
15091 (save-window-excursion
15092 (calendar)
15093 (unwind-protect
15094 (progn
15095 (calendar-forward-day (- (time-to-days org-def)
15096 (calendar-absolute-from-gregorian
15097 (calendar-current-date))))
15098 (org-eval-in-calendar nil t)
15099 (let* ((old-map (current-local-map))
15100 (map (copy-keymap calendar-mode-map))
15101 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
15102 (org-defkey map (kbd "RET") 'org-calendar-select)
15103 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
15104 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
15105 (org-defkey minibuffer-local-map [(meta shift left)]
15106 (lambda () (interactive)
15107 (org-eval-in-calendar '(calendar-backward-month 1))))
15108 (org-defkey minibuffer-local-map [(meta shift right)]
15109 (lambda () (interactive)
15110 (org-eval-in-calendar '(calendar-forward-month 1))))
15111 (org-defkey minibuffer-local-map [(meta shift up)]
15112 (lambda () (interactive)
15113 (org-eval-in-calendar '(calendar-backward-year 1))))
15114 (org-defkey minibuffer-local-map [(meta shift down)]
15115 (lambda () (interactive)
15116 (org-eval-in-calendar '(calendar-forward-year 1))))
15117 (org-defkey minibuffer-local-map [?\e (shift left)]
15118 (lambda () (interactive)
15119 (org-eval-in-calendar '(calendar-backward-month 1))))
15120 (org-defkey minibuffer-local-map [?\e (shift right)]
15121 (lambda () (interactive)
15122 (org-eval-in-calendar '(calendar-forward-month 1))))
15123 (org-defkey minibuffer-local-map [?\e (shift up)]
15124 (lambda () (interactive)
15125 (org-eval-in-calendar '(calendar-backward-year 1))))
15126 (org-defkey minibuffer-local-map [?\e (shift down)]
15127 (lambda () (interactive)
15128 (org-eval-in-calendar '(calendar-forward-year 1))))
15129 (org-defkey minibuffer-local-map [(shift up)]
15130 (lambda () (interactive)
15131 (org-eval-in-calendar '(calendar-backward-week 1))))
15132 (org-defkey minibuffer-local-map [(shift down)]
15133 (lambda () (interactive)
15134 (org-eval-in-calendar '(calendar-forward-week 1))))
15135 (org-defkey minibuffer-local-map [(shift left)]
15136 (lambda () (interactive)
15137 (org-eval-in-calendar '(calendar-backward-day 1))))
15138 (org-defkey minibuffer-local-map [(shift right)]
15139 (lambda () (interactive)
15140 (org-eval-in-calendar '(calendar-forward-day 1))))
15141 (org-defkey minibuffer-local-map ">"
15142 (lambda () (interactive)
15143 (org-eval-in-calendar '(scroll-calendar-left 1))))
15144 (org-defkey minibuffer-local-map "<"
15145 (lambda () (interactive)
15146 (org-eval-in-calendar '(scroll-calendar-right 1))))
15147 (org-defkey minibuffer-local-map "\C-v"
15148 (lambda () (interactive)
15149 (org-eval-in-calendar
15150 '(calendar-scroll-left-three-months 1))))
15151 (org-defkey minibuffer-local-map "\M-v"
15152 (lambda () (interactive)
15153 (org-eval-in-calendar
15154 '(calendar-scroll-right-three-months 1))))
15155 (run-hooks 'org-read-date-minibuffer-setup-hook)
15156 (unwind-protect
15157 (progn
15158 (use-local-map map)
15159 (setq org-read-date-inactive inactive)
15160 (add-hook 'post-command-hook 'org-read-date-display)
15161 (setq org-ans0 (read-string prompt default-input
15162 'org-read-date-history nil))
15163 ;; org-ans0: from prompt
15164 ;; org-ans1: from mouse click
15165 ;; org-ans2: from calendar motion
15166 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
15167 (remove-hook 'post-command-hook 'org-read-date-display)
15168 (use-local-map old-map)
15169 (when org-read-date-overlay
15170 (delete-overlay org-read-date-overlay)
15171 (setq org-read-date-overlay nil)))))
15172 (bury-buffer "*Calendar*")))))
15174 (t ; Naked prompt only
15175 (unwind-protect
15176 (setq ans (read-string prompt default-input
15177 'org-read-date-history timestr))
15178 (when org-read-date-overlay
15179 (delete-overlay org-read-date-overlay)
15180 (setq org-read-date-overlay nil)))))
15182 (setq final (org-read-date-analyze ans org-def org-defdecode))
15184 (when org-read-date-analyze-forced-year
15185 (message "Year was forced into %s"
15186 (if org-read-date-force-compatible-dates
15187 "compatible range (1970-2037)"
15188 "range representable on this machine"))
15189 (ding))
15191 ;; One round trip to get rid of 34th of August and stuff like that....
15192 (setq final (decode-time (apply 'encode-time final)))
15194 (setq org-read-date-final-answer ans)
15196 (if to-time
15197 (apply 'encode-time final)
15198 (if (and (boundp 'org-time-was-given) org-time-was-given)
15199 (format "%04d-%02d-%02d %02d:%02d"
15200 (nth 5 final) (nth 4 final) (nth 3 final)
15201 (nth 2 final) (nth 1 final))
15202 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
15204 (defvar org-def)
15205 (defvar org-defdecode)
15206 (defvar org-with-time)
15207 (defun org-read-date-display ()
15208 "Display the current date prompt interpretation in the minibuffer."
15209 (when org-read-date-display-live
15210 (when org-read-date-overlay
15211 (delete-overlay org-read-date-overlay))
15212 (when (minibufferp (current-buffer))
15213 (save-excursion
15214 (end-of-line 1)
15215 (while (not (equal (buffer-substring
15216 (max (point-min) (- (point) 4)) (point))
15217 " "))
15218 (insert " ")))
15219 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
15220 " " (or org-ans1 org-ans2)))
15221 (org-end-time-was-given nil)
15222 (f (org-read-date-analyze ans org-def org-defdecode))
15223 (fmts (if org-dcst
15224 org-time-stamp-custom-formats
15225 org-time-stamp-formats))
15226 (fmt (if (or org-with-time
15227 (and (boundp 'org-time-was-given) org-time-was-given))
15228 (cdr fmts)
15229 (car fmts)))
15230 (txt (format-time-string fmt (apply 'encode-time f)))
15231 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
15232 (txt (concat "=> " txt)))
15233 (when (and org-end-time-was-given
15234 (string-match org-plain-time-of-day-regexp txt))
15235 (setq txt (concat (substring txt 0 (match-end 0)) "-"
15236 org-end-time-was-given
15237 (substring txt (match-end 0)))))
15238 (when org-read-date-analyze-futurep
15239 (setq txt (concat txt " (=>F)")))
15240 (setq org-read-date-overlay
15241 (make-overlay (1- (point-at-eol)) (point-at-eol)))
15242 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
15244 (defun org-read-date-analyze (ans org-def org-defdecode)
15245 "Analyze the combined answer of the date prompt."
15246 ;; FIXME: cleanup and comment
15247 (let ((nowdecode (decode-time (current-time)))
15248 delta deltan deltaw deltadef year month day
15249 hour minute second wday pm h2 m2 tl wday1
15250 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
15251 (setq org-read-date-analyze-futurep nil
15252 org-read-date-analyze-forced-year nil)
15253 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
15254 (setq ans "+0"))
15256 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
15257 (setq ans (replace-match "" t t ans)
15258 deltan (car delta)
15259 deltaw (nth 1 delta)
15260 deltadef (nth 2 delta)))
15262 ;; Check if there is an iso week date in there
15263 ;; If yes, store the info and postpone interpreting it until the rest
15264 ;; of the parsing is done
15265 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
15266 (setq iso-year (if (match-end 1)
15267 (org-small-year-to-year
15268 (string-to-number (match-string 1 ans))))
15269 iso-weekday (if (match-end 3)
15270 (string-to-number (match-string 3 ans)))
15271 iso-week (string-to-number (match-string 2 ans)))
15272 (setq ans (replace-match "" t t ans)))
15274 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
15275 (when (string-match
15276 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
15277 (setq year (if (match-end 2)
15278 (string-to-number (match-string 2 ans))
15279 (progn (setq kill-year t)
15280 (string-to-number (format-time-string "%Y"))))
15281 month (string-to-number (match-string 3 ans))
15282 day (string-to-number (match-string 4 ans)))
15283 (if (< year 100) (setq year (+ 2000 year)))
15284 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15285 t nil ans)))
15287 ;; Help matching dotted european dates
15288 (when (string-match
15289 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\. ?\\([1-9][0-9][0-9][0-9]\\)?" ans)
15290 (setq year (if (match-end 3)
15291 (string-to-number (match-string 3 ans))
15292 (progn (setq kill-year t)
15293 (string-to-number (format-time-string "%Y"))))
15294 day (string-to-number (match-string 1 ans))
15295 month (string-to-number (match-string 2 ans))
15296 ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15297 t nil ans)))
15299 ;; Help matching american dates, like 5/30 or 5/30/7
15300 (when (string-match
15301 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
15302 (setq year (if (match-end 4)
15303 (string-to-number (match-string 4 ans))
15304 (progn (setq kill-year t)
15305 (string-to-number (format-time-string "%Y"))))
15306 month (string-to-number (match-string 1 ans))
15307 day (string-to-number (match-string 2 ans)))
15308 (if (< year 100) (setq year (+ 2000 year)))
15309 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15310 t nil ans)))
15311 ;; Help matching am/pm times, because `parse-time-string' does not do that.
15312 ;; If there is a time with am/pm, and *no* time without it, we convert
15313 ;; so that matching will be successful.
15314 (loop for i from 1 to 2 do ; twice, for end time as well
15315 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
15316 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
15317 (setq hour (string-to-number (match-string 1 ans))
15318 minute (if (match-end 3)
15319 (string-to-number (match-string 3 ans))
15321 pm (equal ?p
15322 (string-to-char (downcase (match-string 4 ans)))))
15323 (if (and (= hour 12) (not pm))
15324 (setq hour 0)
15325 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
15326 (setq ans (replace-match (format "%02d:%02d" hour minute)
15327 t t ans))))
15329 ;; Check if a time range is given as a duration
15330 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
15331 (setq hour (string-to-number (match-string 1 ans))
15332 h2 (+ hour (string-to-number (match-string 3 ans)))
15333 minute (string-to-number (match-string 2 ans))
15334 m2 (+ minute (if (match-end 5) (string-to-number
15335 (match-string 5 ans))0)))
15336 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
15337 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
15338 t t ans)))
15340 ;; Check if there is a time range
15341 (when (boundp 'org-end-time-was-given)
15342 (setq org-time-was-given nil)
15343 (when (and (string-match org-plain-time-of-day-regexp ans)
15344 (match-end 8))
15345 (setq org-end-time-was-given (match-string 8 ans))
15346 (setq ans (concat (substring ans 0 (match-beginning 7))
15347 (substring ans (match-end 7))))))
15349 (setq tl (parse-time-string ans)
15350 day (or (nth 3 tl) (nth 3 org-defdecode))
15351 month (or (nth 4 tl)
15352 (if (and org-read-date-prefer-future
15353 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
15354 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
15355 (nth 4 org-defdecode)))
15356 year (or (and (not kill-year) (nth 5 tl))
15357 (if (and org-read-date-prefer-future
15358 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
15359 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
15360 (nth 5 org-defdecode)))
15361 hour (or (nth 2 tl) (nth 2 org-defdecode))
15362 minute (or (nth 1 tl) (nth 1 org-defdecode))
15363 second (or (nth 0 tl) 0)
15364 wday (nth 6 tl))
15366 (when (and (eq org-read-date-prefer-future 'time)
15367 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
15368 (equal day (nth 3 nowdecode))
15369 (equal month (nth 4 nowdecode))
15370 (equal year (nth 5 nowdecode))
15371 (nth 2 tl)
15372 (or (< (nth 2 tl) (nth 2 nowdecode))
15373 (and (= (nth 2 tl) (nth 2 nowdecode))
15374 (nth 1 tl)
15375 (< (nth 1 tl) (nth 1 nowdecode)))))
15376 (setq day (1+ day)
15377 futurep t))
15379 ;; Special date definitions below
15380 (cond
15381 (iso-week
15382 ;; There was an iso week
15383 (require 'cal-iso)
15384 (setq futurep nil)
15385 (setq year (or iso-year year)
15386 day (or iso-weekday wday 1)
15387 wday nil ; to make sure that the trigger below does not match
15388 iso-date (calendar-gregorian-from-absolute
15389 (calendar-absolute-from-iso
15390 (list iso-week day year))))
15391 ; FIXME: Should we also push ISO weeks into the future?
15392 ; (when (and org-read-date-prefer-future
15393 ; (not iso-year)
15394 ; (< (calendar-absolute-from-gregorian iso-date)
15395 ; (time-to-days (current-time))))
15396 ; (setq year (1+ year)
15397 ; iso-date (calendar-gregorian-from-absolute
15398 ; (calendar-absolute-from-iso
15399 ; (list iso-week day year)))))
15400 (setq month (car iso-date)
15401 year (nth 2 iso-date)
15402 day (nth 1 iso-date)))
15403 (deltan
15404 (setq futurep nil)
15405 (unless deltadef
15406 (let ((now (decode-time (current-time))))
15407 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
15408 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
15409 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
15410 ((equal deltaw "m") (setq month (+ month deltan)))
15411 ((equal deltaw "y") (setq year (+ year deltan)))))
15412 ((and wday (not (nth 3 tl)))
15413 (setq futurep nil)
15414 ;; Weekday was given, but no day, so pick that day in the week
15415 ;; on or after the derived date.
15416 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
15417 (unless (equal wday wday1)
15418 (setq day (+ day (% (- wday wday1 -7) 7))))))
15419 (if (and (boundp 'org-time-was-given)
15420 (nth 2 tl))
15421 (setq org-time-was-given t))
15422 (if (< year 100) (setq year (+ 2000 year)))
15423 ;; Check of the date is representable
15424 (if org-read-date-force-compatible-dates
15425 (progn
15426 (if (< year 1970)
15427 (setq year 1970 org-read-date-analyze-forced-year t))
15428 (if (> year 2037)
15429 (setq year 2037 org-read-date-analyze-forced-year t)))
15430 (condition-case nil
15431 (ignore (encode-time second minute hour day month year))
15432 (error
15433 (setq year (nth 5 org-defdecode))
15434 (setq org-read-date-analyze-forced-year t))))
15435 (setq org-read-date-analyze-futurep futurep)
15436 (list second minute hour day month year)))
15438 (defvar parse-time-weekdays)
15439 (defun org-read-date-get-relative (s today default)
15440 "Check string S for special relative date string.
15441 TODAY and DEFAULT are internal times, for today and for a default.
15442 Return shift list (N what def-flag)
15443 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
15444 N is the number of WHATs to shift.
15445 DEF-FLAG is t when a double ++ or -- indicates shift relative to
15446 the DEFAULT date rather than TODAY."
15447 (require 'parse-time)
15448 (when (and
15449 (string-match
15450 (concat
15451 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
15452 "\\([0-9]+\\)?"
15453 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
15454 "\\([ \t]\\|$\\)") s)
15455 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
15456 (let* ((dir (if (> (match-end 1) (match-beginning 1))
15457 (string-to-char (substring (match-string 1 s) -1))
15458 ?+))
15459 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
15460 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
15461 (what (if (match-end 3) (match-string 3 s) "d"))
15462 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
15463 (date (if rel default today))
15464 (wday (nth 6 (decode-time date)))
15465 delta)
15466 (if wday1
15467 (progn
15468 (setq delta (mod (+ 7 (- wday1 wday)) 7))
15469 (if (= dir ?-) (setq delta (- delta 7)))
15470 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
15471 (list delta "d" rel))
15472 (list (* n (if (= dir ?-) -1 1)) what rel)))))
15474 (defun org-order-calendar-date-args (arg1 arg2 arg3)
15475 "Turn a user-specified date into the internal representation.
15476 The internal representation needed by the calendar is (month day year).
15477 This is a wrapper to handle the brain-dead convention in calendar that
15478 user function argument order change dependent on argument order."
15479 (if (boundp 'calendar-date-style)
15480 (cond
15481 ((eq calendar-date-style 'american)
15482 (list arg1 arg2 arg3))
15483 ((eq calendar-date-style 'european)
15484 (list arg2 arg1 arg3))
15485 ((eq calendar-date-style 'iso)
15486 (list arg2 arg3 arg1)))
15487 (with-no-warnings ;; european-calendar-style is obsolete as of version 23.1
15488 (if (org-bound-and-true-p european-calendar-style)
15489 (list arg2 arg1 arg3)
15490 (list arg1 arg2 arg3)))))
15492 (defun org-eval-in-calendar (form &optional keepdate)
15493 "Eval FORM in the calendar window and return to current window.
15494 Also, store the cursor date in variable org-ans2."
15495 (let ((sf (selected-frame))
15496 (sw (selected-window)))
15497 (select-window (get-buffer-window "*Calendar*" t))
15498 (eval form)
15499 (when (and (not keepdate) (calendar-cursor-to-date))
15500 (let* ((date (calendar-cursor-to-date))
15501 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15502 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
15503 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
15504 (select-window sw)
15505 (org-select-frame-set-input-focus sf)))
15507 (defun org-calendar-select ()
15508 "Return to `org-read-date' with the date currently selected.
15509 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15510 (interactive)
15511 (when (calendar-cursor-to-date)
15512 (let* ((date (calendar-cursor-to-date))
15513 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15514 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15515 (if (active-minibuffer-window) (exit-minibuffer))))
15517 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
15518 "Insert a date stamp for the date given by the internal TIME.
15519 WITH-HM means use the stamp format that includes the time of the day.
15520 INACTIVE means use square brackets instead of angular ones, so that the
15521 stamp will not contribute to the agenda.
15522 PRE and POST are optional strings to be inserted before and after the
15523 stamp.
15524 The command returns the inserted time stamp."
15525 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
15526 stamp)
15527 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
15528 (insert-before-markers (or pre ""))
15529 (when (listp extra)
15530 (setq extra (car extra))
15531 (if (and (stringp extra)
15532 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
15533 (setq extra (format "-%02d:%02d"
15534 (string-to-number (match-string 1 extra))
15535 (string-to-number (match-string 2 extra))))
15536 (setq extra nil)))
15537 (when extra
15538 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
15539 (insert-before-markers (setq stamp (format-time-string fmt time)))
15540 (insert-before-markers (or post ""))
15541 (setq org-last-inserted-timestamp stamp)))
15543 (defun org-toggle-time-stamp-overlays ()
15544 "Toggle the use of custom time stamp formats."
15545 (interactive)
15546 (setq org-display-custom-times (not org-display-custom-times))
15547 (unless org-display-custom-times
15548 (let ((p (point-min)) (bmp (buffer-modified-p)))
15549 (while (setq p (next-single-property-change p 'display))
15550 (if (and (get-text-property p 'display)
15551 (eq (get-text-property p 'face) 'org-date))
15552 (remove-text-properties
15553 p (setq p (next-single-property-change p 'display))
15554 '(display t))))
15555 (set-buffer-modified-p bmp)))
15556 (if (featurep 'xemacs)
15557 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
15558 (org-restart-font-lock)
15559 (setq org-table-may-need-update t)
15560 (if org-display-custom-times
15561 (message "Time stamps are overlaid with custom format")
15562 (message "Time stamp overlays removed")))
15564 (defun org-display-custom-time (beg end)
15565 "Overlay modified time stamp format over timestamp between BEG and END."
15566 (let* ((ts (buffer-substring beg end))
15567 t1 w1 with-hm tf time str w2 (off 0))
15568 (save-match-data
15569 (setq t1 (org-parse-time-string ts t))
15570 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)?\\'" ts)
15571 (setq off (- (match-end 0) (match-beginning 0)))))
15572 (setq end (- end off))
15573 (setq w1 (- end beg)
15574 with-hm (and (nth 1 t1) (nth 2 t1))
15575 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
15576 time (org-fix-decoded-time t1)
15577 str (org-add-props
15578 (format-time-string
15579 (substring tf 1 -1) (apply 'encode-time time))
15580 nil 'mouse-face 'highlight)
15581 w2 (length str))
15582 (if (not (= w2 w1))
15583 (add-text-properties (1+ beg) (+ 2 beg)
15584 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
15585 (if (featurep 'xemacs)
15586 (progn
15587 (put-text-property beg end 'invisible t)
15588 (put-text-property beg end 'end-glyph (make-glyph str)))
15589 (put-text-property beg end 'display str))))
15591 (defun org-translate-time (string)
15592 "Translate all timestamps in STRING to custom format.
15593 But do this only if the variable `org-display-custom-times' is set."
15594 (when org-display-custom-times
15595 (save-match-data
15596 (let* ((start 0)
15597 (re org-ts-regexp-both)
15598 t1 with-hm inactive tf time str beg end)
15599 (while (setq start (string-match re string start))
15600 (setq beg (match-beginning 0)
15601 end (match-end 0)
15602 t1 (save-match-data
15603 (org-parse-time-string (substring string beg end) t))
15604 with-hm (and (nth 1 t1) (nth 2 t1))
15605 inactive (equal (substring string beg (1+ beg)) "[")
15606 tf (funcall (if with-hm 'cdr 'car)
15607 org-time-stamp-custom-formats)
15608 time (org-fix-decoded-time t1)
15609 str (format-time-string
15610 (concat
15611 (if inactive "[" "<") (substring tf 1 -1)
15612 (if inactive "]" ">"))
15613 (apply 'encode-time time))
15614 string (replace-match str t t string)
15615 start (+ start (length str)))))))
15616 string)
15618 (defun org-fix-decoded-time (time)
15619 "Set 0 instead of nil for the first 6 elements of time.
15620 Don't touch the rest."
15621 (let ((n 0))
15622 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
15624 (defun org-days-to-time (timestamp-string)
15625 "Difference between TIMESTAMP-STRING and now in days."
15626 (- (time-to-days (org-time-string-to-time timestamp-string))
15627 (time-to-days (current-time))))
15629 (defun org-deadline-close (timestamp-string &optional ndays)
15630 "Is the time in TIMESTAMP-STRING close to the current date?"
15631 (setq ndays (or ndays (org-get-wdays timestamp-string)))
15632 (and (< (org-days-to-time timestamp-string) ndays)
15633 (not (org-entry-is-done-p))))
15635 (defun org-get-wdays (ts)
15636 "Get the deadline lead time appropriate for timestring TS."
15637 (cond
15638 ((<= org-deadline-warning-days 0)
15639 ;; 0 or negative, enforce this value no matter what
15640 (- org-deadline-warning-days))
15641 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\| \\)" ts)
15642 ;; lead time is specified.
15643 (floor (* (string-to-number (match-string 1 ts))
15644 (cdr (assoc (match-string 2 ts)
15645 '(("d" . 1) ("w" . 7)
15646 ("m" . 30.4) ("y" . 365.25)))))))
15647 ;; go for the default.
15648 (t org-deadline-warning-days)))
15650 (defun org-calendar-select-mouse (ev)
15651 "Return to `org-read-date' with the date currently selected.
15652 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15653 (interactive "e")
15654 (mouse-set-point ev)
15655 (when (calendar-cursor-to-date)
15656 (let* ((date (calendar-cursor-to-date))
15657 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15658 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15659 (if (active-minibuffer-window) (exit-minibuffer))))
15661 (defun org-check-deadlines (ndays)
15662 "Check if there are any deadlines due or past due.
15663 A deadline is considered due if it happens within `org-deadline-warning-days'
15664 days from today's date. If the deadline appears in an entry marked DONE,
15665 it is not shown. The prefix arg NDAYS can be used to test that many
15666 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
15667 (interactive "P")
15668 (let* ((org-warn-days
15669 (cond
15670 ((equal ndays '(4)) 100000)
15671 (ndays (prefix-numeric-value ndays))
15672 (t (abs org-deadline-warning-days))))
15673 (case-fold-search nil)
15674 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
15675 (callback
15676 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
15678 (message "%d deadlines past-due or due within %d days"
15679 (org-occur regexp nil callback)
15680 org-warn-days)))
15682 (defun org-check-before-date (date)
15683 "Check if there are deadlines or scheduled entries before DATE."
15684 (interactive (list (org-read-date)))
15685 (let ((case-fold-search nil)
15686 (regexp (concat "\\<\\(" org-deadline-string
15687 "\\|" org-scheduled-string
15688 "\\) *<\\([^>]+\\)>"))
15689 (callback
15690 (lambda () (time-less-p
15691 (org-time-string-to-time (match-string 2))
15692 (org-time-string-to-time date)))))
15693 (message "%d entries before %s"
15694 (org-occur regexp nil callback) date)))
15696 (defun org-check-after-date (date)
15697 "Check if there are deadlines or scheduled entries after DATE."
15698 (interactive (list (org-read-date)))
15699 (let ((case-fold-search nil)
15700 (regexp (concat "\\<\\(" org-deadline-string
15701 "\\|" org-scheduled-string
15702 "\\) *<\\([^>]+\\)>"))
15703 (callback
15704 (lambda () (not
15705 (time-less-p
15706 (org-time-string-to-time (match-string 2))
15707 (org-time-string-to-time date))))))
15708 (message "%d entries after %s"
15709 (org-occur regexp nil callback) date)))
15711 (defun org-check-dates-range (start-date end-date)
15712 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
15713 (interactive (list (org-read-date nil nil nil "Range starts")
15714 (org-read-date nil nil nil "Range end")))
15715 (let ((case-fold-search nil)
15716 (regexp (concat "\\<\\(" org-deadline-string
15717 "\\|" org-scheduled-string
15718 "\\) *<\\([^>]+\\)>"))
15719 (callback
15720 (lambda ()
15721 (let ((match (match-string 2)))
15722 (and
15723 (not (time-less-p
15724 (org-time-string-to-time match)
15725 (org-time-string-to-time start-date)))
15726 (time-less-p
15727 (org-time-string-to-time match)
15728 (org-time-string-to-time end-date)))))))
15729 (message "%d entries between %s and %s"
15730 (org-occur regexp nil callback) start-date end-date)))
15732 (defun org-evaluate-time-range (&optional to-buffer)
15733 "Evaluate a time range by computing the difference between start and end.
15734 Normally the result is just printed in the echo area, but with prefix arg
15735 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
15736 If the time range is actually in a table, the result is inserted into the
15737 next column.
15738 For time difference computation, a year is assumed to be exactly 365
15739 days in order to avoid rounding problems."
15740 (interactive "P")
15742 (org-clock-update-time-maybe)
15743 (save-excursion
15744 (unless (org-at-date-range-p t)
15745 (goto-char (point-at-bol))
15746 (re-search-forward org-tr-regexp-both (point-at-eol) t))
15747 (if (not (org-at-date-range-p t))
15748 (error "Not at a time-stamp range, and none found in current line")))
15749 (let* ((ts1 (match-string 1))
15750 (ts2 (match-string 2))
15751 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
15752 (match-end (match-end 0))
15753 (time1 (org-time-string-to-time ts1))
15754 (time2 (org-time-string-to-time ts2))
15755 (t1 (org-float-time time1))
15756 (t2 (org-float-time time2))
15757 (diff (abs (- t2 t1)))
15758 (negative (< (- t2 t1) 0))
15759 ;; (ys (floor (* 365 24 60 60)))
15760 (ds (* 24 60 60))
15761 (hs (* 60 60))
15762 (fy "%dy %dd %02d:%02d")
15763 (fy1 "%dy %dd")
15764 (fd "%dd %02d:%02d")
15765 (fd1 "%dd")
15766 (fh "%02d:%02d")
15767 y d h m align)
15768 (if havetime
15769 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
15771 d (floor (/ diff ds)) diff (mod diff ds)
15772 h (floor (/ diff hs)) diff (mod diff hs)
15773 m (floor (/ diff 60)))
15774 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
15776 d (floor (+ (/ diff ds) 0.5))
15777 h 0 m 0))
15778 (if (not to-buffer)
15779 (message "%s" (org-make-tdiff-string y d h m))
15780 (if (org-at-table-p)
15781 (progn
15782 (goto-char match-end)
15783 (setq align t)
15784 (and (looking-at " *|") (goto-char (match-end 0))))
15785 (goto-char match-end))
15786 (if (looking-at
15787 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
15788 (replace-match ""))
15789 (if negative (insert " -"))
15790 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
15791 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
15792 (insert " " (format fh h m))))
15793 (if align (org-table-align))
15794 (message "Time difference inserted")))))
15796 (defun org-make-tdiff-string (y d h m)
15797 (let ((fmt "")
15798 (l nil))
15799 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
15800 l (push y l)))
15801 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
15802 l (push d l)))
15803 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
15804 l (push h l)))
15805 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
15806 l (push m l)))
15807 (apply 'format fmt (nreverse l))))
15809 (defun org-time-string-to-time (s &optional buffer pos)
15810 (condition-case errdata
15811 (apply 'encode-time (org-parse-time-string s))
15812 (error (error "Bad timestamp `%s'%s\nError was: %s"
15813 s (if (not (and buffer pos))
15815 (format " at %d in buffer `%s'" pos buffer))
15816 (cdr errdata)))))
15818 (defun org-time-string-to-seconds (s)
15819 (org-float-time (org-time-string-to-time s)))
15821 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
15822 "Convert a time stamp to an absolute day number.
15823 If there is a specifier for a cyclic time stamp, get the closest date to
15824 DAYNR.
15825 PREFER and SHOW-ALL are passed through to `org-closest-date'.
15826 The variable date is bound by the calendar when this is called."
15827 (cond
15828 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
15829 (if (org-diary-sexp-entry (match-string 1 s) "" date)
15830 daynr
15831 (+ daynr 1000)))
15832 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
15833 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
15834 (time-to-days (current-time))) (match-string 0 s)
15835 prefer show-all))
15836 (t (time-to-days
15837 (condition-case errdata
15838 (apply 'encode-time (org-parse-time-string s))
15839 (error (error "Bad timestamp `%s'%s\nError was: %s"
15840 s (if (not (and buffer pos))
15842 (format " at %d in buffer `%s'" pos buffer))
15843 (cdr errdata))))))))
15845 (defun org-days-to-iso-week (days)
15846 "Return the iso week number."
15847 (require 'cal-iso)
15848 (car (calendar-iso-from-absolute days)))
15850 (defun org-small-year-to-year (year)
15851 "Convert 2-digit years into 4-digit years.
15852 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
15853 The year 2000 cannot be abbreviated. Any year larger than 99
15854 is returned unchanged."
15855 (if (< year 38)
15856 (setq year (+ 2000 year))
15857 (if (< year 100)
15858 (setq year (+ 1900 year))))
15859 year)
15861 (defun org-time-from-absolute (d)
15862 "Return the time corresponding to date D.
15863 D may be an absolute day number, or a calendar-type list (month day year)."
15864 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
15865 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
15867 (defun org-calendar-holiday ()
15868 "List of holidays, for Diary display in Org-mode."
15869 (require 'holidays)
15870 (let ((hl (funcall
15871 (if (fboundp 'calendar-check-holidays)
15872 'calendar-check-holidays 'check-calendar-holidays) date)))
15873 (if hl (mapconcat 'identity hl "; "))))
15875 (defun org-diary-sexp-entry (sexp entry date)
15876 "Process a SEXP diary ENTRY for DATE."
15877 (require 'diary-lib)
15878 (let ((result (if calendar-debug-sexp
15879 (let ((stack-trace-on-error t))
15880 (eval (car (read-from-string sexp))))
15881 (condition-case nil
15882 (eval (car (read-from-string sexp)))
15883 (error
15884 (beep)
15885 (message "Bad sexp at line %d in %s: %s"
15886 (org-current-line)
15887 (buffer-file-name) sexp)
15888 (sleep-for 2))))))
15889 (cond ((stringp result) (split-string result "; "))
15890 ((and (consp result)
15891 (not (consp (cdr result)))
15892 (stringp (cdr result))) (cdr result))
15893 ((and (consp result)
15894 (stringp (car result))) result)
15895 (result entry)
15896 (t nil))))
15898 (defun org-diary-to-ical-string (frombuf)
15899 "Get iCalendar entries from diary entries in buffer FROMBUF.
15900 This uses the icalendar.el library."
15901 (let* ((tmpdir (if (featurep 'xemacs)
15902 (temp-directory)
15903 temporary-file-directory))
15904 (tmpfile (make-temp-name
15905 (expand-file-name "orgics" tmpdir)))
15906 buf rtn b e)
15907 (with-current-buffer frombuf
15908 (icalendar-export-region (point-min) (point-max) tmpfile)
15909 (setq buf (find-buffer-visiting tmpfile))
15910 (set-buffer buf)
15911 (goto-char (point-min))
15912 (if (re-search-forward "^BEGIN:VEVENT" nil t)
15913 (setq b (match-beginning 0)))
15914 (goto-char (point-max))
15915 (if (re-search-backward "^END:VEVENT" nil t)
15916 (setq e (match-end 0)))
15917 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
15918 (kill-buffer buf)
15919 (delete-file tmpfile)
15920 rtn))
15922 (defun org-closest-date (start current change prefer show-all)
15923 "Find the date closest to CURRENT that is consistent with START and CHANGE.
15924 When PREFER is `past', return a date that is either CURRENT or past.
15925 When PREFER is `future', return a date that is either CURRENT or future.
15926 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
15927 ;; Make the proper lists from the dates
15928 (catch 'exit
15929 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
15930 dn dw sday cday n1 n2 n0
15931 d m y y1 y2 date1 date2 nmonths nm ny m2)
15933 (setq start (org-date-to-gregorian start)
15934 current (org-date-to-gregorian
15935 (if show-all
15936 current
15937 (time-to-days (current-time))))
15938 sday (calendar-absolute-from-gregorian start)
15939 cday (calendar-absolute-from-gregorian current))
15941 (if (<= cday sday) (throw 'exit sday))
15943 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
15944 (setq dn (string-to-number (match-string 1 change))
15945 dw (cdr (assoc (match-string 2 change) a1)))
15946 (error "Invalid change specifier: %s" change))
15947 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
15948 (cond
15949 ((eq dw 'day)
15950 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
15951 n2 (+ n1 dn)))
15952 ((eq dw 'year)
15953 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
15954 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
15955 (setq date1 (list m d y1)
15956 n1 (calendar-absolute-from-gregorian date1)
15957 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
15958 n2 (calendar-absolute-from-gregorian date2)))
15959 ((eq dw 'month)
15960 ;; approx number of month between the two dates
15961 (setq nmonths (floor (/ (- cday sday) 30.436875)))
15962 ;; How often does dn fit in there?
15963 (setq d (nth 1 start) m (car start) y (nth 2 start)
15964 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
15965 m (+ m nm)
15966 ny (floor (/ m 12))
15967 y (+ y ny)
15968 m (- m (* ny 12)))
15969 (while (> m 12) (setq m (- m 12) y (1+ y)))
15970 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
15971 (setq m2 (+ m dn) y2 y)
15972 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
15973 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
15974 (while (<= n2 cday)
15975 (setq n1 n2 m m2 y y2)
15976 (setq m2 (+ m dn) y2 y)
15977 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
15978 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
15979 ;; Make sure n1 is the earlier date
15980 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
15981 (if show-all
15982 (cond
15983 ((eq prefer 'past) (if (= cday n2) n2 n1))
15984 ((eq prefer 'future) (if (= cday n1) n1 n2))
15985 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
15986 (cond
15987 ((eq prefer 'past) (if (= cday n2) n2 n1))
15988 ((eq prefer 'future) (if (= cday n1) n1 n2))
15989 (t (if (= cday n1) n1 n2)))))))
15991 (defun org-date-to-gregorian (date)
15992 "Turn any specification of DATE into a Gregorian date for the calendar."
15993 (cond ((integerp date) (calendar-gregorian-from-absolute date))
15994 ((and (listp date) (= (length date) 3)) date)
15995 ((stringp date)
15996 (setq date (org-parse-time-string date))
15997 (list (nth 4 date) (nth 3 date) (nth 5 date)))
15998 ((listp date)
15999 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
16001 (defun org-parse-time-string (s &optional nodefault)
16002 "Parse the standard Org-mode time string.
16003 This should be a lot faster than the normal `parse-time-string'.
16004 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
16005 hour and minute fields will be nil if not given."
16006 (if (string-match org-ts-regexp0 s)
16007 (list 0
16008 (if (or (match-beginning 8) (not nodefault))
16009 (string-to-number (or (match-string 8 s) "0")))
16010 (if (or (match-beginning 7) (not nodefault))
16011 (string-to-number (or (match-string 7 s) "0")))
16012 (string-to-number (match-string 4 s))
16013 (string-to-number (match-string 3 s))
16014 (string-to-number (match-string 2 s))
16015 nil nil nil)
16016 (error "Not a standard Org-mode time string: %s" s)))
16018 (defun org-timestamp-up (&optional arg)
16019 "Increase the date item at the cursor by one.
16020 If the cursor is on the year, change the year. If it is on the month,
16021 the day or the time, change that.
16022 With prefix ARG, change by that many units."
16023 (interactive "p")
16024 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
16026 (defun org-timestamp-down (&optional arg)
16027 "Decrease the date item at the cursor by one.
16028 If the cursor is on the year, change the year. If it is on the month,
16029 the day or the time, change that.
16030 With prefix ARG, change by that many units."
16031 (interactive "p")
16032 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
16034 (defun org-timestamp-up-day (&optional arg)
16035 "Increase the date in the time stamp by one day.
16036 With prefix ARG, change that many days."
16037 (interactive "p")
16038 (if (and (not (org-at-timestamp-p t))
16039 (org-at-heading-p))
16040 (org-todo 'up)
16041 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
16043 (defun org-timestamp-down-day (&optional arg)
16044 "Decrease the date in the time stamp by one day.
16045 With prefix ARG, change that many days."
16046 (interactive "p")
16047 (if (and (not (org-at-timestamp-p t))
16048 (org-at-heading-p))
16049 (org-todo 'down)
16050 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
16052 (defun org-at-timestamp-p (&optional inactive-ok)
16053 "Determine if the cursor is in or at a timestamp."
16054 (interactive)
16055 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
16056 (pos (point))
16057 (ans (or (looking-at tsr)
16058 (save-excursion
16059 (skip-chars-backward "^[<\n\r\t")
16060 (if (> (point) (point-min)) (backward-char 1))
16061 (and (looking-at tsr)
16062 (> (- (match-end 0) pos) -1))))))
16063 (and ans
16064 (boundp 'org-ts-what)
16065 (setq org-ts-what
16066 (cond
16067 ((= pos (match-beginning 0)) 'bracket)
16068 ;; Point is considered to be "on the bracket" whether
16069 ;; it's really on it or right after it.
16070 ((or (= pos (1- (match-end 0)))
16071 (= pos (match-end 0))) 'bracket)
16072 ((org-pos-in-match-range pos 2) 'year)
16073 ((org-pos-in-match-range pos 3) 'month)
16074 ((org-pos-in-match-range pos 7) 'hour)
16075 ((org-pos-in-match-range pos 8) 'minute)
16076 ((or (org-pos-in-match-range pos 4)
16077 (org-pos-in-match-range pos 5)) 'day)
16078 ((and (> pos (or (match-end 8) (match-end 5)))
16079 (< pos (match-end 0)))
16080 (- pos (or (match-end 8) (match-end 5))))
16081 (t 'day))))
16082 ans))
16084 (defun org-toggle-timestamp-type ()
16085 "Toggle the type (<active> or [inactive]) of a time stamp."
16086 (interactive)
16087 (when (org-at-timestamp-p t)
16088 (let ((beg (match-beginning 0)) (end (match-end 0))
16089 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
16090 (save-excursion
16091 (goto-char beg)
16092 (while (re-search-forward "[][<>]" end t)
16093 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
16094 t t)))
16095 (message "Timestamp is now %sactive"
16096 (if (equal (char-after beg) ?<) "" "in")))))
16098 (defun org-timestamp-change (n &optional what updown)
16099 "Change the date in the time stamp at point.
16100 The date will be changed by N times WHAT. WHAT can be `day', `month',
16101 `year', `minute', `second'. If WHAT is not given, the cursor position
16102 in the timestamp determines what will be changed."
16103 (let ((origin (point)) origin-cat
16104 with-hm inactive
16105 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
16106 org-ts-what
16107 extra rem
16108 ts time time0)
16109 (if (not (org-at-timestamp-p t))
16110 (error "Not at a timestamp"))
16111 (if (and (not what) (eq org-ts-what 'bracket))
16112 (org-toggle-timestamp-type)
16113 ;; Point isn't on brackets. Remember the part of the time-stamp
16114 ;; the point was in. Indeed, size of time-stamps may change,
16115 ;; but point must be kept in the same category nonetheless.
16116 (setq origin-cat org-ts-what)
16117 (if (and (not what) (not (eq org-ts-what 'day))
16118 org-display-custom-times
16119 (get-text-property (point) 'display)
16120 (not (get-text-property (1- (point)) 'display)))
16121 (setq org-ts-what 'day))
16122 (setq org-ts-what (or what org-ts-what)
16123 inactive (= (char-after (match-beginning 0)) ?\[)
16124 ts (match-string 0))
16125 (replace-match "")
16126 (if (string-match
16127 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)*\\)[]>]"
16129 (setq extra (match-string 1 ts)))
16130 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
16131 (setq with-hm t))
16132 (setq time0 (org-parse-time-string ts))
16133 (when (and updown
16134 (eq org-ts-what 'minute)
16135 (not current-prefix-arg))
16136 ;; This looks like s-up and s-down. Change by one rounding step.
16137 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
16138 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
16139 (setcar (cdr time0) (+ (nth 1 time0)
16140 (if (> n 0) (- rem) (- dm rem))))))
16141 (setq time
16142 (encode-time (or (car time0) 0)
16143 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
16144 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
16145 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
16146 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
16147 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
16148 (nthcdr 6 time0)))
16149 (when (and (member org-ts-what '(hour minute))
16150 extra
16151 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
16152 (setq extra (org-modify-ts-extra
16153 extra
16154 (if (eq org-ts-what 'hour) 2 5)
16155 n dm)))
16156 (when (integerp org-ts-what)
16157 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
16158 (if (eq what 'calendar)
16159 (let ((cal-date (org-get-date-from-calendar)))
16160 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
16161 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
16162 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
16163 (setcar time0 (or (car time0) 0))
16164 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
16165 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
16166 (setq time (apply 'encode-time time0))))
16167 ;; Insert the new time-stamp, and ensure point stays in the same
16168 ;; category as before (i.e. not after the last position in that
16169 ;; category).
16170 (let ((pos (point)))
16171 ;; Stay before inserted string. `save-excursion' is of no use.
16172 (setq org-last-changed-timestamp
16173 (org-insert-time-stamp time with-hm inactive nil nil extra))
16174 (goto-char pos))
16175 (save-match-data
16176 (looking-at org-ts-regexp3)
16177 (goto-char (cond
16178 ;; `day' category ends before `hour' if any, or at
16179 ;; the end of the day name.
16180 ((eq origin-cat 'day)
16181 (min (or (match-beginning 7) (1- (match-end 5))) origin))
16182 ((eq origin-cat 'hour) (min (match-end 7) origin))
16183 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
16184 ((integerp origin-cat) (min (1- (match-end 0)) origin))
16185 ;; `year' and `month' have both fixed size: point
16186 ;; couldn't have moved into another part.
16187 (t origin))))
16188 ;; Update clock if on a CLOCK line.
16189 (org-clock-update-time-maybe)
16190 ;; Try to recenter the calendar window, if any.
16191 (if (and org-calendar-follow-timestamp-change
16192 (get-buffer-window "*Calendar*" t)
16193 (memq org-ts-what '(day month year)))
16194 (org-recenter-calendar (time-to-days time))))))
16196 (defun org-modify-ts-extra (s pos n dm)
16197 "Change the different parts of the lead-time and repeat fields in timestamp."
16198 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
16199 ng h m new rem)
16200 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
16201 (cond
16202 ((or (org-pos-in-match-range pos 2)
16203 (org-pos-in-match-range pos 3))
16204 (setq m (string-to-number (match-string 3 s))
16205 h (string-to-number (match-string 2 s)))
16206 (if (org-pos-in-match-range pos 2)
16207 (setq h (+ h n))
16208 (setq n (* dm (org-no-warnings (signum n))))
16209 (when (not (= 0 (setq rem (% m dm))))
16210 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
16211 (setq m (+ m n)))
16212 (if (< m 0) (setq m (+ m 60) h (1- h)))
16213 (if (> m 59) (setq m (- m 60) h (1+ h)))
16214 (setq h (min 24 (max 0 h)))
16215 (setq ng 1 new (format "-%02d:%02d" h m)))
16216 ((org-pos-in-match-range pos 6)
16217 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
16218 ((org-pos-in-match-range pos 5)
16219 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
16221 ((org-pos-in-match-range pos 9)
16222 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
16223 ((org-pos-in-match-range pos 8)
16224 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
16226 (when ng
16227 (setq s (concat
16228 (substring s 0 (match-beginning ng))
16230 (substring s (match-end ng))))))
16233 (defun org-recenter-calendar (date)
16234 "If the calendar is visible, recenter it to DATE."
16235 (let ((cwin (get-buffer-window "*Calendar*" t)))
16236 (when cwin
16237 (let ((calendar-move-hook nil))
16238 (with-selected-window cwin
16239 (calendar-goto-date (if (listp date) date
16240 (calendar-gregorian-from-absolute date))))))))
16242 (defun org-goto-calendar (&optional arg)
16243 "Go to the Emacs calendar at the current date.
16244 If there is a time stamp in the current line, go to that date.
16245 A prefix ARG can be used to force the current date."
16246 (interactive "P")
16247 (let ((tsr org-ts-regexp) diff
16248 (calendar-move-hook nil)
16249 (calendar-view-holidays-initially-flag nil)
16250 (calendar-view-diary-initially-flag nil))
16251 (if (or (org-at-timestamp-p)
16252 (save-excursion
16253 (beginning-of-line 1)
16254 (looking-at (concat ".*" tsr))))
16255 (let ((d1 (time-to-days (current-time)))
16256 (d2 (time-to-days
16257 (org-time-string-to-time (match-string 1)))))
16258 (setq diff (- d2 d1))))
16259 (calendar)
16260 (calendar-goto-today)
16261 (if (and diff (not arg)) (calendar-forward-day diff))))
16263 (defun org-get-date-from-calendar ()
16264 "Return a list (month day year) of date at point in calendar."
16265 (with-current-buffer "*Calendar*"
16266 (save-match-data
16267 (calendar-cursor-to-date))))
16269 (defun org-date-from-calendar ()
16270 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
16271 If there is already a time stamp at the cursor position, update it."
16272 (interactive)
16273 (if (org-at-timestamp-p t)
16274 (org-timestamp-change 0 'calendar)
16275 (let ((cal-date (org-get-date-from-calendar)))
16276 (org-insert-time-stamp
16277 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
16279 (defun org-minutes-to-hh:mm-string (m)
16280 "Compute H:MM from a number of minutes."
16281 (let ((h (/ m 60)))
16282 (setq m (- m (* 60 h)))
16283 (format org-time-clocksum-format h m)))
16285 (defun org-hh:mm-string-to-minutes (s)
16286 "Convert a string H:MM to a number of minutes.
16287 If the string is just a number, interpret it as minutes.
16288 In fact, the first hh:mm or number in the string will be taken,
16289 there can be extra stuff in the string.
16290 If no number is found, the return value is 0."
16291 (cond
16292 ((integerp s) s)
16293 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
16294 (+ (* (string-to-number (match-string 1 s)) 60)
16295 (string-to-number (match-string 2 s))))
16296 ((string-match "\\([0-9]+\\)" s)
16297 (string-to-number (match-string 1 s)))
16298 (t 0)))
16300 (defcustom org-effort-durations
16301 `(("h" . 60)
16302 ("d" . ,(* 60 8))
16303 ("w" . ,(* 60 8 5))
16304 ("m" . ,(* 60 8 5 4))
16305 ("y" . ,(* 60 8 5 40)))
16306 "Conversion factor to minutes for an effort modifier.
16308 Each entry has the form (MODIFIER . MINUTES).
16310 In an effort string, a number followed by MODIFIER is multiplied
16311 by the specified number of MINUTES to obtain an effort in
16312 minutes.
16314 For example, if the value of this variable is ((\"hours\" . 60)), then an
16315 effort string \"2hours\" is equivalent to 120 minutes."
16316 :group 'org-agenda
16317 :version "24.1"
16318 :type '(alist :key-type (string :tag "Modifier")
16319 :value-type (number :tag "Minutes")))
16321 (defun org-duration-string-to-minutes (s)
16322 "Convert a duration string S to minutes.
16324 A bare number is interpreted as minutes, modifiers can be set by
16325 customizing `org-effort-durations' (which see).
16327 Entries containing a colon are interpreted as H:MM by
16328 `org-hh:mm-string-to-minutes'."
16329 (let ((result 0)
16330 (re (concat "\\([0-9]+\\) *\\("
16331 (regexp-opt (mapcar 'car org-effort-durations))
16332 "\\)")))
16333 (while (string-match re s)
16334 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
16335 (string-to-number (match-string 1 s))))
16336 (setq s (replace-match "" nil t s)))
16337 (incf result (org-hh:mm-string-to-minutes s))
16338 result))
16340 ;;;; Files
16342 (defun org-save-all-org-buffers ()
16343 "Save all Org-mode buffers without user confirmation."
16344 (interactive)
16345 (message "Saving all Org-mode buffers...")
16346 (save-some-buffers t (lambda () (eq major-mode 'org-mode)))
16347 (when (featurep 'org-id) (org-id-locations-save))
16348 (message "Saving all Org-mode buffers... done"))
16350 (defun org-revert-all-org-buffers ()
16351 "Revert all Org-mode buffers.
16352 Prompt for confirmation when there are unsaved changes.
16353 Be sure you know what you are doing before letting this function
16354 overwrite your changes.
16356 This function is useful in a setup where one tracks org files
16357 with a version control system, to revert on one machine after pulling
16358 changes from another. I believe the procedure must be like this:
16360 1. M-x org-save-all-org-buffers
16361 2. Pull changes from the other machine, resolve conflicts
16362 3. M-x org-revert-all-org-buffers"
16363 (interactive)
16364 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
16365 (error "Abort"))
16366 (save-excursion
16367 (save-window-excursion
16368 (mapc
16369 (lambda (b)
16370 (when (and (with-current-buffer b (eq major-mode 'org-mode))
16371 (with-current-buffer b buffer-file-name))
16372 (org-pop-to-buffer-same-window b)
16373 (revert-buffer t 'no-confirm)))
16374 (buffer-list))
16375 (when (and (featurep 'org-id) org-id-track-globally)
16376 (org-id-locations-load)))))
16378 ;;;; Agenda files
16380 ;;;###autoload
16381 (defun org-switchb (&optional arg)
16382 "Switch between Org buffers.
16383 With one prefix argument, restrict available buffers to files.
16384 With two prefix arguments, restrict available buffers to agenda files.
16386 Defaults to `iswitchb' for buffer name completion.
16387 Set `org-completion-use-ido' to make it use ido instead."
16388 (interactive "P")
16389 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
16390 ((equal arg '(16)) (org-buffer-list 'agenda))
16391 (t (org-buffer-list))))
16392 (org-completion-use-iswitchb org-completion-use-iswitchb)
16393 (org-completion-use-ido org-completion-use-ido))
16394 (unless (or org-completion-use-ido org-completion-use-iswitchb)
16395 (setq org-completion-use-iswitchb t))
16396 (org-pop-to-buffer-same-window
16397 (org-icompleting-read "Org buffer: "
16398 (mapcar 'list (mapcar 'buffer-name blist))
16399 nil t))))
16401 ;;; Define some older names previously used for this functionality
16402 ;;;###autoload
16403 (defalias 'org-ido-switchb 'org-switchb)
16404 ;;;###autoload
16405 (defalias 'org-iswitchb 'org-switchb)
16407 (defun org-buffer-list (&optional predicate exclude-tmp)
16408 "Return a list of Org buffers.
16409 PREDICATE can be `export', `files' or `agenda'.
16411 export restrict the list to Export buffers.
16412 files restrict the list to buffers visiting Org files.
16413 agenda restrict the list to buffers visiting agenda files.
16415 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
16416 (let* ((bfn nil)
16417 (agenda-files (and (eq predicate 'agenda)
16418 (mapcar 'file-truename (org-agenda-files t))))
16419 (filter
16420 (cond
16421 ((eq predicate 'files)
16422 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
16423 ((eq predicate 'export)
16424 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
16425 ((eq predicate 'agenda)
16426 (lambda (b)
16427 (with-current-buffer b
16428 (and (eq major-mode 'org-mode)
16429 (setq bfn (buffer-file-name b))
16430 (member (file-truename bfn) agenda-files)))))
16431 (t (lambda (b) (with-current-buffer b
16432 (or (eq major-mode 'org-mode)
16433 (string-match "\*Org .*Export"
16434 (buffer-name b)))))))))
16435 (delq nil
16436 (mapcar
16437 (lambda(b)
16438 (if (and (funcall filter b)
16439 (or (not exclude-tmp)
16440 (not (string-match "tmp" (buffer-name b)))))
16442 nil))
16443 (buffer-list)))))
16445 (defun org-agenda-files (&optional unrestricted archives)
16446 "Get the list of agenda files.
16447 Optional UNRESTRICTED means return the full list even if a restriction
16448 is currently in place.
16449 When ARCHIVES is t, include all archive files that are really being
16450 used by the agenda files. If ARCHIVE is `ifmode', do this only if
16451 `org-agenda-archives-mode' is t."
16452 (let ((files
16453 (cond
16454 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
16455 ((stringp org-agenda-files) (org-read-agenda-file-list))
16456 ((listp org-agenda-files) org-agenda-files)
16457 (t (error "Invalid value of `org-agenda-files'")))))
16458 (setq files (apply 'append
16459 (mapcar (lambda (f)
16460 (if (file-directory-p f)
16461 (directory-files
16462 f t org-agenda-file-regexp)
16463 (list f)))
16464 files)))
16465 (when org-agenda-skip-unavailable-files
16466 (setq files (delq nil
16467 (mapcar (function
16468 (lambda (file)
16469 (and (file-readable-p file) file)))
16470 files))))
16471 (when (or (eq archives t)
16472 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
16473 (setq files (org-add-archive-files files)))
16474 files))
16476 (defun org-agenda-file-p (&optional file)
16477 "Return non-nil, if FILE is an agenda file.
16478 If FILE is omitted, use the file associated with the current
16479 buffer."
16480 (member (or file (buffer-file-name))
16481 (org-agenda-files t)))
16483 (defun org-edit-agenda-file-list ()
16484 "Edit the list of agenda files.
16485 Depending on setup, this either uses customize to edit the variable
16486 `org-agenda-files', or it visits the file that is holding the list. In the
16487 latter case, the buffer is set up in a way that saving it automatically kills
16488 the buffer and restores the previous window configuration."
16489 (interactive)
16490 (if (stringp org-agenda-files)
16491 (let ((cw (current-window-configuration)))
16492 (find-file org-agenda-files)
16493 (org-set-local 'org-window-configuration cw)
16494 (org-add-hook 'after-save-hook
16495 (lambda ()
16496 (set-window-configuration
16497 (prog1 org-window-configuration
16498 (kill-buffer (current-buffer))))
16499 (org-install-agenda-files-menu)
16500 (message "New agenda file list installed"))
16501 nil 'local)
16502 (message "%s" (substitute-command-keys
16503 "Edit list and finish with \\[save-buffer]")))
16504 (customize-variable 'org-agenda-files)))
16506 (defun org-store-new-agenda-file-list (list)
16507 "Set new value for the agenda file list and save it correctly."
16508 (if (stringp org-agenda-files)
16509 (let ((fe (org-read-agenda-file-list t)) b u)
16510 (while (setq b (find-buffer-visiting org-agenda-files))
16511 (kill-buffer b))
16512 (with-temp-file org-agenda-files
16513 (insert
16514 (mapconcat
16515 (lambda (f) ;; Keep un-expanded entries.
16516 (if (setq u (assoc f fe))
16517 (cdr u)
16519 list "\n")
16520 "\n")))
16521 (let ((org-mode-hook nil) (org-inhibit-startup t)
16522 (org-insert-mode-line-in-empty-file nil))
16523 (setq org-agenda-files list)
16524 (customize-save-variable 'org-agenda-files org-agenda-files))))
16526 (defun org-read-agenda-file-list (&optional pair-with-expansion)
16527 "Read the list of agenda files from a file.
16528 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
16529 filenames, used by `org-store-new-agenda-file-list' to write back
16530 un-expanded file names."
16531 (when (file-directory-p org-agenda-files)
16532 (error "`org-agenda-files' cannot be a single directory"))
16533 (when (stringp org-agenda-files)
16534 (with-temp-buffer
16535 (insert-file-contents org-agenda-files)
16536 (mapcar
16537 (lambda (f)
16538 (let ((e (expand-file-name (substitute-in-file-name f)
16539 org-directory)))
16540 (if pair-with-expansion
16541 (cons e f)
16542 e)))
16543 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
16545 ;;;###autoload
16546 (defun org-cycle-agenda-files ()
16547 "Cycle through the files in `org-agenda-files'.
16548 If the current buffer visits an agenda file, find the next one in the list.
16549 If the current buffer does not, find the first agenda file."
16550 (interactive)
16551 (let* ((fs (org-agenda-files t))
16552 (files (append fs (list (car fs))))
16553 (tcf (if buffer-file-name (file-truename buffer-file-name)))
16554 file)
16555 (unless files (error "No agenda files"))
16556 (catch 'exit
16557 (while (setq file (pop files))
16558 (if (equal (file-truename file) tcf)
16559 (when (car files)
16560 (find-file (car files))
16561 (throw 'exit t))))
16562 (find-file (car fs)))
16563 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
16565 (defun org-agenda-file-to-front (&optional to-end)
16566 "Move/add the current file to the top of the agenda file list.
16567 If the file is not present in the list, it is added to the front. If it is
16568 present, it is moved there. With optional argument TO-END, add/move to the
16569 end of the list."
16570 (interactive "P")
16571 (let ((org-agenda-skip-unavailable-files nil)
16572 (file-alist (mapcar (lambda (x)
16573 (cons (file-truename x) x))
16574 (org-agenda-files t)))
16575 (ctf (file-truename buffer-file-name))
16576 x had)
16577 (setq x (assoc ctf file-alist) had x)
16579 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
16580 (if to-end
16581 (setq file-alist (append (delq x file-alist) (list x)))
16582 (setq file-alist (cons x (delq x file-alist))))
16583 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
16584 (org-install-agenda-files-menu)
16585 (message "File %s to %s of agenda file list"
16586 (if had "moved" "added") (if to-end "end" "front"))))
16588 (defun org-remove-file (&optional file)
16589 "Remove current file from the list of files in variable `org-agenda-files'.
16590 These are the files which are being checked for agenda entries.
16591 Optional argument FILE means use this file instead of the current."
16592 (interactive)
16593 (let* ((org-agenda-skip-unavailable-files nil)
16594 (file (or file buffer-file-name))
16595 (true-file (file-truename file))
16596 (afile (abbreviate-file-name file))
16597 (files (delq nil (mapcar
16598 (lambda (x)
16599 (if (equal true-file
16600 (file-truename x))
16601 nil x))
16602 (org-agenda-files t)))))
16603 (if (not (= (length files) (length (org-agenda-files t))))
16604 (progn
16605 (org-store-new-agenda-file-list files)
16606 (org-install-agenda-files-menu)
16607 (message "Removed file: %s" afile))
16608 (message "File was not in list: %s (not removed)" afile))))
16610 (defun org-file-menu-entry (file)
16611 (vector file (list 'find-file file) t))
16613 (defun org-check-agenda-file (file)
16614 "Make sure FILE exists. If not, ask user what to do."
16615 (when (not (file-exists-p file))
16616 (message "non-existent agenda file %s. [R]emove from list or [A]bort?"
16617 (abbreviate-file-name file))
16618 (let ((r (downcase (read-char-exclusive))))
16619 (cond
16620 ((equal r ?r)
16621 (org-remove-file file)
16622 (throw 'nextfile t))
16623 (t (error "Abort"))))))
16625 (defun org-get-agenda-file-buffer (file)
16626 "Get a buffer visiting FILE. If the buffer needs to be created, add
16627 it to the list of buffers which might be released later."
16628 (let ((buf (org-find-base-buffer-visiting file)))
16629 (if buf
16630 buf ; just return it
16631 ;; Make a new buffer and remember it
16632 (setq buf (find-file-noselect file))
16633 (if buf (push buf org-agenda-new-buffers))
16634 buf)))
16636 (defun org-release-buffers (blist)
16637 "Release all buffers in list, asking the user for confirmation when needed.
16638 When a buffer is unmodified, it is just killed. When modified, it is saved
16639 \(if the user agrees) and then killed."
16640 (let (buf file)
16641 (while (setq buf (pop blist))
16642 (setq file (buffer-file-name buf))
16643 (when (and (buffer-modified-p buf)
16644 file
16645 (y-or-n-p (format "Save file %s? " file)))
16646 (with-current-buffer buf (save-buffer)))
16647 (kill-buffer buf))))
16649 (defun org-prepare-agenda-buffers (files)
16650 "Create buffers for all agenda files, protect archived trees and comments."
16651 (interactive)
16652 (let ((pa '(:org-archived t))
16653 (pc '(:org-comment t))
16654 (pall '(:org-archived t :org-comment t))
16655 (inhibit-read-only t)
16656 (rea (concat ":" org-archive-tag ":"))
16657 bmp file re)
16658 (save-excursion
16659 (save-restriction
16660 (while (setq file (pop files))
16661 (catch 'nextfile
16662 (if (bufferp file)
16663 (set-buffer file)
16664 (org-check-agenda-file file)
16665 (set-buffer (org-get-agenda-file-buffer file)))
16666 (widen)
16667 (setq bmp (buffer-modified-p))
16668 (org-refresh-category-properties)
16669 (setq org-todo-keywords-for-agenda
16670 (append org-todo-keywords-for-agenda org-todo-keywords-1))
16671 (setq org-done-keywords-for-agenda
16672 (append org-done-keywords-for-agenda org-done-keywords))
16673 (setq org-todo-keyword-alist-for-agenda
16674 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
16675 (setq org-drawers-for-agenda
16676 (append org-drawers-for-agenda org-drawers))
16677 (setq org-tag-alist-for-agenda
16678 (append org-tag-alist-for-agenda org-tag-alist))
16680 (save-excursion
16681 (remove-text-properties (point-min) (point-max) pall)
16682 (when org-agenda-skip-archived-trees
16683 (goto-char (point-min))
16684 (while (re-search-forward rea nil t)
16685 (if (org-at-heading-p t)
16686 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
16687 (goto-char (point-min))
16688 (setq re (format org-heading-keyword-regexp-format
16689 org-comment-string))
16690 (while (re-search-forward re nil t)
16691 (add-text-properties
16692 (match-beginning 0) (org-end-of-subtree t) pc)))
16693 (set-buffer-modified-p bmp)))))
16694 (setq org-todo-keywords-for-agenda
16695 (org-uniquify org-todo-keywords-for-agenda))
16696 (setq org-todo-keyword-alist-for-agenda
16697 (org-uniquify org-todo-keyword-alist-for-agenda)
16698 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
16700 ;;;; Embedded LaTeX
16702 (defvar org-cdlatex-mode-map (make-sparse-keymap)
16703 "Keymap for the minor `org-cdlatex-mode'.")
16705 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
16706 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
16707 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
16708 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
16709 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
16711 (defvar org-cdlatex-texmathp-advice-is-done nil
16712 "Flag remembering if we have applied the advice to texmathp already.")
16714 (define-minor-mode org-cdlatex-mode
16715 "Toggle the minor `org-cdlatex-mode'.
16716 This mode supports entering LaTeX environment and math in LaTeX fragments
16717 in Org-mode.
16718 \\{org-cdlatex-mode-map}"
16719 nil " OCDL" nil
16720 (when org-cdlatex-mode
16721 (require 'cdlatex)
16722 (run-hooks 'cdlatex-mode-hook)
16723 (cdlatex-compute-tables))
16724 (unless org-cdlatex-texmathp-advice-is-done
16725 (setq org-cdlatex-texmathp-advice-is-done t)
16726 (defadvice texmathp (around org-math-always-on activate)
16727 "Always return t in org-mode buffers.
16728 This is because we want to insert math symbols without dollars even outside
16729 the LaTeX math segments. If Orgmode thinks that point is actually inside
16730 an embedded LaTeX fragment, let texmathp do its job.
16731 \\[org-cdlatex-mode-map]"
16732 (interactive)
16733 (let (p)
16734 (cond
16735 ((not (eq major-mode 'org-mode)) ad-do-it)
16736 ((eq this-command 'cdlatex-math-symbol)
16737 (setq ad-return-value t
16738 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
16740 (let ((p (org-inside-LaTeX-fragment-p)))
16741 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
16742 (setq ad-return-value t
16743 texmathp-why '("Org-mode embedded math" . 0))
16744 (if p ad-do-it)))))))))
16746 (defun turn-on-org-cdlatex ()
16747 "Unconditionally turn on `org-cdlatex-mode'."
16748 (org-cdlatex-mode 1))
16750 (defun org-inside-LaTeX-fragment-p ()
16751 "Test if point is inside a LaTeX fragment.
16752 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
16753 sequence appearing also before point.
16754 Even though the matchers for math are configurable, this function assumes
16755 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
16756 delimiters are skipped when they have been removed by customization.
16757 The return value is nil, or a cons cell with the delimiter and the
16758 position of this delimiter.
16760 This function does a reasonably good job, but can locally be fooled by
16761 for example currency specifications. For example it will assume being in
16762 inline math after \"$22.34\". The LaTeX fragment formatter will only format
16763 fragments that are properly closed, but during editing, we have to live
16764 with the uncertainty caused by missing closing delimiters. This function
16765 looks only before point, not after."
16766 (catch 'exit
16767 (let ((pos (point))
16768 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
16769 (lim (progn
16770 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
16771 (point)))
16772 dd-on str (start 0) m re)
16773 (goto-char pos)
16774 (when dodollar
16775 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
16776 re (nth 1 (assoc "$" org-latex-regexps)))
16777 (while (string-match re str start)
16778 (cond
16779 ((= (match-end 0) (length str))
16780 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
16781 ((= (match-end 0) (- (length str) 5))
16782 (throw 'exit nil))
16783 (t (setq start (match-end 0))))))
16784 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
16785 (goto-char pos)
16786 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
16787 (and (match-beginning 2) (throw 'exit nil))
16788 ;; count $$
16789 (while (re-search-backward "\\$\\$" lim t)
16790 (setq dd-on (not dd-on)))
16791 (goto-char pos)
16792 (if dd-on (cons "$$" m))))))
16794 (defun org-inside-latex-macro-p ()
16795 "Is point inside a LaTeX macro or its arguments?"
16796 (save-match-data
16797 (org-in-regexp
16798 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
16800 (defun org-try-cdlatex-tab ()
16801 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
16802 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
16803 - inside a LaTeX fragment, or
16804 - after the first word in a line, where an abbreviation expansion could
16805 insert a LaTeX environment."
16806 (when org-cdlatex-mode
16807 (cond
16808 ;; Before any word on the line: No expansion possible.
16809 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
16810 ;; Just after first word on the line: Expand it. Make sure it
16811 ;; cannot happen on headlines, though.
16812 ((save-excursion
16813 (skip-chars-backward "a-zA-Z0-9*")
16814 (skip-chars-backward " \t")
16815 (and (bolp) (not (org-at-heading-p))))
16816 (cdlatex-tab) t)
16817 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
16819 (defun org-cdlatex-underscore-caret (&optional arg)
16820 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
16821 Revert to the normal definition outside of these fragments."
16822 (interactive "P")
16823 (if (org-inside-LaTeX-fragment-p)
16824 (call-interactively 'cdlatex-sub-superscript)
16825 (let (org-cdlatex-mode)
16826 (call-interactively (key-binding (vector last-input-event))))))
16828 (defun org-cdlatex-math-modify (&optional arg)
16829 "Execute `cdlatex-math-modify' in LaTeX fragments.
16830 Revert to the normal definition outside of these fragments."
16831 (interactive "P")
16832 (if (org-inside-LaTeX-fragment-p)
16833 (call-interactively 'cdlatex-math-modify)
16834 (let (org-cdlatex-mode)
16835 (call-interactively (key-binding (vector last-input-event))))))
16837 (defvar org-latex-fragment-image-overlays nil
16838 "List of overlays carrying the images of latex fragments.")
16839 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
16841 (defun org-remove-latex-fragment-image-overlays ()
16842 "Remove all overlays with LaTeX fragment images in current buffer."
16843 (mapc 'delete-overlay org-latex-fragment-image-overlays)
16844 (setq org-latex-fragment-image-overlays nil))
16846 (defun org-preview-latex-fragment (&optional subtree)
16847 "Preview the LaTeX fragment at point, or all locally or globally.
16848 If the cursor is in a LaTeX fragment, create the image and overlay
16849 it over the source code. If there is no fragment at point, display
16850 all fragments in the current text, from one headline to the next. With
16851 prefix SUBTREE, display all fragments in the current subtree. With a
16852 double prefix arg \\[universal-argument] \\[universal-argument], or when \
16853 the cursor is before the first headline,
16854 display all fragments in the buffer.
16855 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
16856 (interactive "P")
16857 (unless buffer-file-name
16858 (error "Can't preview LaTeX fragment in a non-file buffer"))
16859 (org-remove-latex-fragment-image-overlays)
16860 (save-excursion
16861 (save-restriction
16862 (let (beg end at msg)
16863 (cond
16864 ((or (equal subtree '(16))
16865 (not (save-excursion
16866 (re-search-backward org-outline-regexp-bol nil t))))
16867 (setq beg (point-min) end (point-max)
16868 msg "Creating images for buffer...%s"))
16869 ((equal subtree '(4))
16870 (org-back-to-heading)
16871 (setq beg (point) end (org-end-of-subtree t)
16872 msg "Creating images for subtree...%s"))
16874 (if (setq at (org-inside-LaTeX-fragment-p))
16875 (goto-char (max (point-min) (- (cdr at) 2)))
16876 (org-back-to-heading))
16877 (setq beg (point) end (progn (outline-next-heading) (point))
16878 msg (if at "Creating image...%s"
16879 "Creating images for entry...%s"))))
16880 (message msg "")
16881 (narrow-to-region beg end)
16882 (goto-char beg)
16883 (org-format-latex
16884 (concat "ltxpng/" (file-name-sans-extension
16885 (file-name-nondirectory
16886 buffer-file-name)))
16887 default-directory 'overlays msg at 'forbuffer 'dvipng)
16888 (message msg "done. Use `C-c C-c' to remove images.")))))
16890 (defvar org-latex-regexps
16891 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
16892 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
16893 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
16894 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
16895 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
16896 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
16897 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
16898 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
16899 "Regular expressions for matching embedded LaTeX.")
16901 (defvar org-export-have-math nil) ;; dynamic scoping
16902 (defun org-format-latex (prefix &optional dir overlays msg at
16903 forbuffer processing-type)
16904 "Replace LaTeX fragments with links to an image, and produce images.
16905 Some of the options can be changed using the variable
16906 `org-format-latex-options'."
16907 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
16908 (let* ((prefixnodir (file-name-nondirectory prefix))
16909 (absprefix (expand-file-name prefix dir))
16910 (todir (file-name-directory absprefix))
16911 (opt org-format-latex-options)
16912 (matchers (plist-get opt :matchers))
16913 (re-list org-latex-regexps)
16914 (org-format-latex-header-extra
16915 (plist-get (org-infile-export-plist) :latex-header-extra))
16916 (cnt 0) txt hash link beg end re e checkdir
16917 executables-checked string
16918 m n block-type block linkfile movefile ov)
16919 ;; Check the different regular expressions
16920 (while (setq e (pop re-list))
16921 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
16922 block (if block-type "\n\n" ""))
16923 (when (member m matchers)
16924 (goto-char (point-min))
16925 (while (re-search-forward re nil t)
16926 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
16927 (not (get-text-property (match-beginning n)
16928 'org-protected))
16929 (or (not overlays)
16930 (not (eq (get-char-property (match-beginning n)
16931 'org-overlay-type)
16932 'org-latex-overlay))))
16933 (setq org-export-have-math t)
16934 (cond
16935 ((eq processing-type 'verbatim)
16936 ;; Leave the text verbatim, just protect it
16937 (add-text-properties (match-beginning n) (match-end n)
16938 '(org-protected t)))
16939 ((eq processing-type 'mathjax)
16940 ;; Prepare for MathJax processing
16941 (setq string (match-string n))
16942 (if (member m '("$" "$1"))
16943 (save-excursion
16944 (delete-region (match-beginning n) (match-end n))
16945 (goto-char (match-beginning n))
16946 (insert (org-add-props (concat "\\(" (substring string 1 -1)
16947 "\\)")
16948 '(org-protected t))))
16949 (add-text-properties (match-beginning n) (match-end n)
16950 '(org-protected t))))
16951 ((eq processing-type 'dvipng)
16952 ;; Process to an image
16953 (setq txt (match-string n)
16954 beg (match-beginning n) end (match-end n)
16955 cnt (1+ cnt))
16956 (let (print-length print-level) ; make sure full list is printed
16957 (setq hash (sha1 (prin1-to-string
16958 (list org-format-latex-header
16959 org-format-latex-header-extra
16960 org-export-latex-default-packages-alist
16961 org-export-latex-packages-alist
16962 org-format-latex-options
16963 forbuffer txt)))
16964 linkfile (format "%s_%s.png" prefix hash)
16965 movefile (format "%s_%s.png" absprefix hash)))
16966 (setq link (concat block "[[file:" linkfile "]]" block))
16967 (if msg (message msg cnt))
16968 (goto-char beg)
16969 (unless checkdir ; make sure the directory exists
16970 (setq checkdir t)
16971 (or (file-directory-p todir) (make-directory todir t)))
16973 (unless executables-checked
16974 (org-check-external-command
16975 "latex" "needed to convert LaTeX fragments to images")
16976 (org-check-external-command
16977 "dvipng" "needed to convert LaTeX fragments to images")
16978 (setq executables-checked t))
16980 (unless (file-exists-p movefile)
16981 (org-create-formula-image
16982 txt movefile opt forbuffer))
16983 (if overlays
16984 (progn
16985 (mapc (lambda (o)
16986 (if (eq (overlay-get o 'org-overlay-type)
16987 'org-latex-overlay)
16988 (delete-overlay o)))
16989 (overlays-in beg end))
16990 (setq ov (make-overlay beg end))
16991 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
16992 (if (featurep 'xemacs)
16993 (progn
16994 (overlay-put ov 'invisible t)
16995 (overlay-put
16996 ov 'end-glyph
16997 (make-glyph (vector 'png :file movefile))))
16998 (overlay-put
16999 ov 'display
17000 (list 'image :type 'png :file movefile :ascent 'center)))
17001 (push ov org-latex-fragment-image-overlays)
17002 (goto-char end))
17003 (delete-region beg end)
17004 (insert (org-add-props link
17005 (list 'org-latex-src
17006 (replace-regexp-in-string
17007 "\"" "" txt)
17008 'org-latex-src-embed-type
17009 (if block-type 'paragraph 'character))))))
17010 ((eq processing-type 'mathml)
17011 ;; Process to MathML
17012 (unless executables-checked
17013 (unless (save-match-data (org-format-latex-mathml-available-p))
17014 (error "LaTeX to MathML converter not configured"))
17015 (setq executables-checked t))
17016 (setq txt (match-string n)
17017 beg (match-beginning n) end (match-end n)
17018 cnt (1+ cnt))
17019 (if msg (message msg cnt))
17020 (goto-char beg)
17021 (delete-region beg end)
17022 (insert (org-format-latex-as-mathml
17023 txt block-type prefix dir)))
17025 (error "Unknown conversion type %s for latex fragments"
17026 processing-type)))))))))
17028 (defun org-create-math-formula (latex-frag &optional mathml-file)
17029 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
17030 Use `org-latex-to-mathml-convert-command'. If the conversion is
17031 sucessful, return the portion between \"<math...> </math>\"
17032 elements otherwise return nil. When MATHML-FILE is specified,
17033 write the results in to that file. When invoked as an
17034 interactive command, prompt for LATEX-FRAG, with initial value
17035 set to the current active region and echo the results for user
17036 inspection."
17037 (interactive (list (let ((frag (when (region-active-p)
17038 (buffer-substring-no-properties
17039 (region-beginning) (region-end)))))
17040 (read-string "LaTeX Fragment: " frag nil frag))))
17041 (unless latex-frag (error "Invalid latex-frag"))
17042 (let* ((tmp-in-file (file-relative-name
17043 (make-temp-name (expand-file-name "ltxmathml-in"))))
17044 (ignore (write-region latex-frag nil tmp-in-file))
17045 (tmp-out-file (file-relative-name
17046 (make-temp-name (expand-file-name "ltxmathml-out"))))
17047 (cmd (format-spec
17048 org-latex-to-mathml-convert-command
17049 `((?j . ,(shell-quote-argument
17050 (expand-file-name org-latex-to-mathml-jar-file)))
17051 (?I . ,(shell-quote-argument tmp-in-file))
17052 (?o . ,(shell-quote-argument tmp-out-file)))))
17053 mathml shell-command-output)
17054 (when (org-called-interactively-p 'any)
17055 (unless (org-format-latex-mathml-available-p)
17056 (error "LaTeX to MathML converter not configured")))
17057 (message "Running %s" cmd)
17058 (setq shell-command-output (shell-command-to-string cmd))
17059 (setq mathml
17060 (when (file-readable-p tmp-out-file)
17061 (with-current-buffer (find-file-noselect tmp-out-file t)
17062 (goto-char (point-min))
17063 (when (re-search-forward
17064 (concat
17065 (regexp-quote
17066 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
17067 "\\(.\\|\n\\)*"
17068 (regexp-quote "</math>")) nil t)
17069 (prog1 (match-string 0) (kill-buffer))))))
17070 (cond
17071 (mathml
17072 (setq mathml
17073 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
17074 (when mathml-file
17075 (write-region mathml nil mathml-file))
17076 (when (org-called-interactively-p 'any)
17077 (message mathml)))
17078 ((message "LaTeX to MathML conversion failed")
17079 (message shell-command-output)))
17080 (delete-file tmp-in-file)
17081 (when (file-exists-p tmp-out-file)
17082 (delete-file tmp-out-file))
17083 mathml))
17085 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
17086 prefix &optional dir)
17087 "Use `org-create-math-formula' but check local cache first."
17088 (let* ((absprefix (expand-file-name prefix dir))
17089 (print-length nil) (print-level nil)
17090 (formula-id (concat
17091 "formula-"
17092 (sha1
17093 (prin1-to-string
17094 (list latex-frag
17095 org-latex-to-mathml-convert-command)))))
17096 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
17097 (formula-cache-dir (file-name-directory formula-cache)))
17099 (unless (file-directory-p formula-cache-dir)
17100 (make-directory formula-cache-dir t))
17102 (unless (file-exists-p formula-cache)
17103 (org-create-math-formula latex-frag formula-cache))
17105 (if (file-exists-p formula-cache)
17106 ;; Successful conversion. Return the link to MathML file.
17107 (org-add-props
17108 (format "[[file:%s]]" (file-relative-name formula-cache dir))
17109 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
17110 'org-latex-src-embed-type (if latex-frag-type
17111 'paragraph 'character)))
17112 ;; Failed conversion. Return the LaTeX fragment verbatim
17113 (add-text-properties
17114 0 (1- (length latex-frag)) '(org-protected t) latex-frag)
17115 latex-frag)))
17117 ;; This function borrows from Ganesh Swami's latex2png.el
17118 (defun org-create-formula-image (string tofile options buffer)
17119 "This calls dvipng."
17120 (require 'org-latex)
17121 (let* ((tmpdir (if (featurep 'xemacs)
17122 (temp-directory)
17123 temporary-file-directory))
17124 (texfilebase (make-temp-name
17125 (expand-file-name "orgtex" tmpdir)))
17126 (texfile (concat texfilebase ".tex"))
17127 (dvifile (concat texfilebase ".dvi"))
17128 (pngfile (concat texfilebase ".png"))
17129 (fnh (if (featurep 'xemacs)
17130 (font-height (face-font 'default))
17131 (face-attribute 'default :height nil)))
17132 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17133 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17134 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17135 "Black"))
17136 (bg (or (plist-get options (if buffer :background :html-background))
17137 "Transparent")))
17138 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
17139 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
17140 (with-temp-file texfile
17141 (insert (org-splice-latex-header
17142 org-format-latex-header
17143 org-export-latex-default-packages-alist
17144 org-export-latex-packages-alist t
17145 org-format-latex-header-extra))
17146 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")
17147 (require 'org-latex)
17148 (org-export-latex-fix-inputenc))
17149 (let ((dir default-directory))
17150 (condition-case nil
17151 (progn
17152 (cd tmpdir)
17153 (call-process "latex" nil nil nil texfile))
17154 (error nil))
17155 (cd dir))
17156 (if (not (file-exists-p dvifile))
17157 (progn (message "Failed to create dvi file from %s" texfile) nil)
17158 (condition-case nil
17159 (if (featurep 'xemacs)
17160 (call-process "dvipng" nil nil nil
17161 "-fg" fg "-bg" bg
17162 "-T" "tight"
17163 "-o" pngfile
17164 dvifile)
17165 (call-process "dvipng" nil nil nil
17166 "-fg" fg "-bg" bg
17167 "-D" dpi
17168 ;;"-x" scale "-y" scale
17169 "-T" "tight"
17170 "-o" pngfile
17171 dvifile))
17172 (error nil))
17173 (if (not (file-exists-p pngfile))
17174 (if org-format-latex-signal-error
17175 (error "Failed to create png file from %s" texfile)
17176 (message "Failed to create png file from %s" texfile)
17177 nil)
17178 ;; Use the requested file name and clean up
17179 (copy-file pngfile tofile 'replace)
17180 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
17181 (delete-file (concat texfilebase e)))
17182 pngfile))))
17184 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
17185 "Fill a LaTeX header template TPL.
17186 In the template, the following place holders will be recognized:
17188 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
17189 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
17190 [PACKAGES] \\usepackage statements for PKG
17191 [NO-PACKAGES] do not include PKG
17192 [EXTRA] the string EXTRA
17193 [NO-EXTRA] do not include EXTRA
17195 For backward compatibility, if both the positive and the negative place
17196 holder is missing, the positive one (without the \"NO-\") will be
17197 assumed to be present at the end of the template.
17198 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
17199 EXTRA is a string.
17200 SNIPPETS-P indicates if this is run to create snippet images for HTML."
17201 (let (rpl (end ""))
17202 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
17203 (setq rpl (if (or (match-end 1) (not def-pkg))
17204 "" (org-latex-packages-to-string def-pkg snippets-p t))
17205 tpl (replace-match rpl t t tpl))
17206 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
17208 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
17209 (setq rpl (if (or (match-end 1) (not pkg))
17210 "" (org-latex-packages-to-string pkg snippets-p t))
17211 tpl (replace-match rpl t t tpl))
17212 (if pkg (setq end
17213 (concat end "\n"
17214 (org-latex-packages-to-string pkg snippets-p)))))
17216 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
17217 (setq rpl (if (or (match-end 1) (not extra))
17218 "" (concat extra "\n"))
17219 tpl (replace-match rpl t t tpl))
17220 (if (and extra (string-match "\\S-" extra))
17221 (setq end (concat end "\n" extra))))
17223 (if (string-match "\\S-" end)
17224 (concat tpl "\n" end)
17225 tpl)))
17227 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
17228 "Turn an alist of packages into a string with the \\usepackage macros."
17229 (setq pkg (mapconcat (lambda(p)
17230 (cond
17231 ((stringp p) p)
17232 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
17233 (format "%% Package %s omitted" (cadr p)))
17234 ((equal "" (car p))
17235 (format "\\usepackage{%s}" (cadr p)))
17237 (format "\\usepackage[%s]{%s}"
17238 (car p) (cadr p)))))
17240 "\n"))
17241 (if newline (concat pkg "\n") pkg))
17243 (defun org-dvipng-color (attr)
17244 "Return an rgb color specification for dvipng."
17245 (apply 'format "rgb %s %s %s"
17246 (mapcar 'org-normalize-color
17247 (if (featurep 'xemacs)
17248 (color-rgb-components
17249 (face-property 'default
17250 (cond ((eq attr :foreground) 'foreground)
17251 ((eq attr :background) 'background))))
17252 (color-values (face-attribute 'default attr nil))))))
17254 (defun org-normalize-color (value)
17255 "Return string to be used as color value for an RGB component."
17256 (format "%g" (/ value 65535.0)))
17258 ;; Image display
17261 (defvar org-inline-image-overlays nil)
17262 (make-variable-buffer-local 'org-inline-image-overlays)
17264 (defun org-toggle-inline-images (&optional include-linked)
17265 "Toggle the display of inline images.
17266 INCLUDE-LINKED is passed to `org-display-inline-images'."
17267 (interactive "P")
17268 (if org-inline-image-overlays
17269 (progn
17270 (org-remove-inline-images)
17271 (message "Inline image display turned off"))
17272 (org-display-inline-images include-linked)
17273 (if org-inline-image-overlays
17274 (message "%d images displayed inline"
17275 (length org-inline-image-overlays))
17276 (message "No images to display inline"))))
17278 (defun org-display-inline-images (&optional include-linked refresh beg end)
17279 "Display inline images.
17280 Normally only links without a description part are inlined, because this
17281 is how it will work for export. When INCLUDE-LINKED is set, also links
17282 with a description part will be inlined. This can be nice for a quick
17283 look at those images, but it does not reflect what exported files will look
17284 like.
17285 When REFRESH is set, refresh existing images between BEG and END.
17286 This will create new image displays only if necessary.
17287 BEG and END default to the buffer boundaries."
17288 (interactive "P")
17289 (unless refresh
17290 (org-remove-inline-images)
17291 (if (fboundp 'clear-image-cache) (clear-image-cache)))
17292 (save-excursion
17293 (save-restriction
17294 (widen)
17295 (setq beg (or beg (point-min)) end (or end (point-max)))
17296 (goto-char beg)
17297 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
17298 (substring (org-image-file-name-regexp) 0 -2)
17299 "\\)\\]" (if include-linked "" "\\]")))
17300 old file ov img)
17301 (while (re-search-forward re end t)
17302 (setq old (get-char-property-and-overlay (match-beginning 1)
17303 'org-image-overlay))
17304 (setq file (expand-file-name
17305 (concat (or (match-string 3) "") (match-string 4))))
17306 (when (file-exists-p file)
17307 (if (and (car-safe old) refresh)
17308 (image-refresh (overlay-get (cdr old) 'display))
17309 (setq img (save-match-data (create-image file)))
17310 (when img
17311 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
17312 (overlay-put ov 'display img)
17313 (overlay-put ov 'face 'default)
17314 (overlay-put ov 'org-image-overlay t)
17315 (overlay-put ov 'modification-hooks
17316 (list 'org-display-inline-modification-hook))
17317 (push ov org-inline-image-overlays)))))))))
17319 (defun org-display-inline-modification-hook (ov after beg end &optional len)
17320 "Remove inline-display overlay if a corresponding region is modified."
17321 (let ((inhibit-modification-hooks t))
17322 (when (and ov after)
17323 (delete ov org-inline-image-overlays)
17324 (delete-overlay ov))))
17326 (defun org-remove-inline-images ()
17327 "Remove inline display of images."
17328 (interactive)
17329 (mapc 'delete-overlay org-inline-image-overlays)
17330 (setq org-inline-image-overlays nil))
17332 ;;;; Key bindings
17334 ;; Outline functions from `outline-mode-prefix-map'
17335 ;; that can be remapped in Org:
17336 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
17337 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
17338 (define-key org-mode-map [remap outline-forward-same-level]
17339 'org-forward-same-level)
17340 (define-key org-mode-map [remap outline-backward-same-level]
17341 'org-backward-same-level)
17342 (define-key org-mode-map [remap show-branches]
17343 'org-kill-note-or-show-branches)
17344 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
17345 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
17346 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
17348 ;; Outline functions from `outline-mode-prefix-map'
17349 ;; that can not be remapped in Org:
17350 ;; - the column "key binding" shows whether the Outline function is still
17351 ;; available in Org mode on the same key that it has been bound to in
17352 ;; Outline mode:
17353 ;; - "overridden": key used for a different functionality in Org mode
17354 ;; - else: key still bound to the same Outline function in Org mode
17355 ;; | Outline function | key binding | Org replacement |
17356 ;; |------------------------------------+-------------+-----------------------|
17357 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
17358 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
17359 ;; | `show-children' | `C-c C-i' | visibility cycling |
17360 ;; | `hide-subtree' | overridden | visibility cycling |
17361 ;; | `outline-up-heading' | `C-c C-u' | still same function |
17362 ;; | `hide-body' | overridden | no replacement |
17363 ;; | `show-all' | overridden | no replacement |
17364 ;; | `hide-entry' | overridden | visibility cycling |
17365 ;; | `show-entry' | overridden | no replacement |
17366 ;; | `hide-leaves' | overridden | no replacement |
17367 ;; | `hide-sublevels' | overridden | no replacement |
17368 ;; | `hide-other' | overridden | no replacement |
17369 ;; | `outline-move-subtree-up' | `C-c C-^' | better: org-shiftup |
17370 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
17372 ;; Make `C-c C-x' a prefix key
17373 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
17375 ;; TAB key with modifiers
17376 (org-defkey org-mode-map "\C-i" 'org-cycle)
17377 (org-defkey org-mode-map [(tab)] 'org-cycle)
17378 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
17379 (org-defkey org-mode-map "\M-\t" 'pcomplete)
17380 ;; The following line is necessary under Suse GNU/Linux
17381 (unless (featurep 'xemacs)
17382 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
17383 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
17384 (define-key org-mode-map [backtab] 'org-shifttab)
17386 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
17387 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
17388 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
17390 ;; Cursor keys with modifiers
17391 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
17392 (org-defkey org-mode-map [(meta right)] 'org-metaright)
17393 (org-defkey org-mode-map [(meta up)] 'org-metaup)
17394 (org-defkey org-mode-map [(meta down)] 'org-metadown)
17396 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
17397 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
17398 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
17399 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
17401 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
17402 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
17403 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
17404 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
17406 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
17407 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
17408 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
17409 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
17411 ;; Babel keys
17412 (define-key org-mode-map org-babel-key-prefix org-babel-map)
17413 (mapc (lambda (pair)
17414 (define-key org-babel-map (car pair) (cdr pair)))
17415 org-babel-key-bindings)
17417 ;;; Extra keys for tty access.
17418 ;; We only set them when really needed because otherwise the
17419 ;; menus don't show the simple keys
17421 (when (or org-use-extra-keys
17422 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
17423 (not window-system))
17424 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
17425 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
17426 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
17427 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
17428 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
17429 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
17430 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
17431 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
17432 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
17433 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
17434 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
17435 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
17436 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
17437 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
17438 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
17439 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
17440 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
17441 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
17442 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
17443 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
17444 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
17445 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
17446 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
17447 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
17448 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
17449 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
17450 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
17451 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
17453 ;; All the other keys
17455 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
17456 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
17457 (if (boundp 'narrow-map)
17458 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
17459 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
17460 (if (boundp 'narrow-map)
17461 (org-defkey narrow-map "b" 'org-narrow-to-block)
17462 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
17463 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-same-level)
17464 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-same-level)
17465 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
17466 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
17467 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
17468 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
17469 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
17470 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
17471 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
17472 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
17473 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
17474 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
17475 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
17476 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
17477 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
17478 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
17479 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
17480 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
17481 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
17482 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
17483 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
17484 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
17485 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
17486 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
17487 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
17488 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
17489 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
17490 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
17491 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
17492 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
17493 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
17494 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
17495 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
17496 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
17497 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
17498 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
17499 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
17500 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
17501 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
17502 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
17503 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
17504 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
17505 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
17506 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
17507 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
17508 (org-defkey org-mode-map "\C-c^" 'org-sort)
17509 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
17510 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
17511 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
17512 (org-defkey org-mode-map "\C-m" 'org-return)
17513 (org-defkey org-mode-map "\C-j" 'org-return-indent)
17514 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
17515 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
17516 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
17517 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
17518 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
17519 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
17520 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
17521 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
17522 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
17523 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
17524 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
17525 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
17526 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
17527 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
17528 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
17529 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
17530 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
17531 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
17532 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
17533 (org-defkey org-mode-map "\C-c\C-@" 'org-mark-list)
17534 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
17535 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
17537 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
17538 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
17539 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
17540 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
17542 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
17543 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
17544 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
17545 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
17546 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
17547 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
17548 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
17549 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
17550 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
17551 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
17552 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
17553 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
17554 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
17555 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
17556 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
17557 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
17558 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
17559 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
17561 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
17562 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
17563 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
17564 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
17565 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
17567 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
17569 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
17571 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
17572 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
17574 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
17577 (when (featurep 'xemacs)
17578 (org-defkey org-mode-map 'button3 'popup-mode-menu))
17581 (defconst org-speed-commands-default
17583 ("Outline Navigation")
17584 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
17585 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
17586 ("f" . (org-speed-move-safe 'org-forward-same-level))
17587 ("b" . (org-speed-move-safe 'org-backward-same-level))
17588 ("u" . (org-speed-move-safe 'outline-up-heading))
17589 ("j" . org-goto)
17590 ("g" . (org-refile t))
17591 ("Outline Visibility")
17592 ("c" . org-cycle)
17593 ("C" . org-shifttab)
17594 (" " . org-display-outline-path)
17595 ("Outline Structure Editing")
17596 ("U" . org-shiftmetaup)
17597 ("D" . org-shiftmetadown)
17598 ("r" . org-metaright)
17599 ("l" . org-metaleft)
17600 ("R" . org-shiftmetaright)
17601 ("L" . org-shiftmetaleft)
17602 ("i" . (progn (forward-char 1) (call-interactively
17603 'org-insert-heading-respect-content)))
17604 ("^" . org-sort)
17605 ("w" . org-refile)
17606 ("a" . org-archive-subtree-default-with-confirmation)
17607 ("." . org-mark-subtree)
17608 ("Clock Commands")
17609 ("I" . org-clock-in)
17610 ("O" . org-clock-out)
17611 ("Meta Data Editing")
17612 ("t" . org-todo)
17613 ("0" . (org-priority ?\ ))
17614 ("1" . (org-priority ?A))
17615 ("2" . (org-priority ?B))
17616 ("3" . (org-priority ?C))
17617 (";" . org-set-tags-command)
17618 ("e" . org-set-effort)
17619 ("Agenda Views etc")
17620 ("v" . org-agenda)
17621 ("/" . org-sparse-tree)
17622 ("Misc")
17623 ("o" . org-open-at-point)
17624 ("?" . org-speed-command-help)
17625 ("<" . (org-agenda-set-restriction-lock 'subtree))
17626 (">" . (org-agenda-remove-restriction-lock))
17628 "The default speed commands.")
17630 (defun org-print-speed-command (e)
17631 (if (> (length (car e)) 1)
17632 (progn
17633 (princ "\n")
17634 (princ (car e))
17635 (princ "\n")
17636 (princ (make-string (length (car e)) ?-))
17637 (princ "\n"))
17638 (princ (car e))
17639 (princ " ")
17640 (if (symbolp (cdr e))
17641 (princ (symbol-name (cdr e)))
17642 (prin1 (cdr e)))
17643 (princ "\n")))
17645 (defun org-speed-command-help ()
17646 "Show the available speed commands."
17647 (interactive)
17648 (if (not org-use-speed-commands)
17649 (error "Speed commands are not activated, customize `org-use-speed-commands'")
17650 (with-output-to-temp-buffer "*Help*"
17651 (princ "User-defined Speed commands\n===========================\n")
17652 (mapc 'org-print-speed-command org-speed-commands-user)
17653 (princ "\n")
17654 (princ "Built-in Speed commands\n=======================\n")
17655 (mapc 'org-print-speed-command org-speed-commands-default))
17656 (with-current-buffer "*Help*"
17657 (setq truncate-lines t))))
17659 (defun org-speed-move-safe (cmd)
17660 "Execute CMD, but make sure that the cursor always ends up in a headline.
17661 If not, return to the original position and throw an error."
17662 (interactive)
17663 (let ((pos (point)))
17664 (call-interactively cmd)
17665 (unless (and (bolp) (org-at-heading-p))
17666 (goto-char pos)
17667 (error "Boundary reached while executing %s" cmd))))
17669 (defvar org-self-insert-command-undo-counter 0)
17671 (defvar org-table-auto-blank-field) ; defined in org-table.el
17672 (defvar org-speed-command nil)
17674 (defun org-speed-command-default-hook (keys)
17675 "Hook for activating single-letter speed commands.
17676 `org-speed-commands-default' specifies a minimal command set.
17677 Use `org-speed-commands-user' for further customization."
17678 (when (or (and (bolp) (looking-at org-outline-regexp))
17679 (and (functionp org-use-speed-commands)
17680 (funcall org-use-speed-commands)))
17681 (cdr (assoc keys (append org-speed-commands-user
17682 org-speed-commands-default)))))
17684 (defun org-babel-speed-command-hook (keys)
17685 "Hook for activating single-letter code block commands."
17686 (when (and (bolp) (looking-at org-babel-src-block-regexp))
17687 (cdr (assoc keys org-babel-key-bindings))))
17689 (defcustom org-speed-command-hook
17690 '(org-speed-command-default-hook org-babel-speed-command-hook)
17691 "Hook for activating speed commands at strategic locations.
17692 Hook functions are called in sequence until a valid handler is
17693 found.
17695 Each hook takes a single argument, a user-pressed command key
17696 which is also a `self-insert-command' from the global map.
17698 Within the hook, examine the cursor position and the command key
17699 and return nil or a valid handler as appropriate. Handler could
17700 be one of an interactive command, a function, or a form.
17702 Set `org-use-speed-commands' to non-nil value to enable this
17703 hook. The default setting is `org-speed-command-default-hook'."
17704 :group 'org-structure
17705 :version "24.1"
17706 :type 'hook)
17708 (defun org-self-insert-command (N)
17709 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
17710 If the cursor is in a table looking at whitespace, the whitespace is
17711 overwritten, and the table is not marked as requiring realignment."
17712 (interactive "p")
17713 (org-check-before-invisible-edit 'insert)
17714 (cond
17715 ((and org-use-speed-commands
17716 (setq org-speed-command
17717 (run-hook-with-args-until-success
17718 'org-speed-command-hook (this-command-keys))))
17719 (cond
17720 ((commandp org-speed-command)
17721 (setq this-command org-speed-command)
17722 (call-interactively org-speed-command))
17723 ((functionp org-speed-command)
17724 (funcall org-speed-command))
17725 ((and org-speed-command (listp org-speed-command))
17726 (eval org-speed-command))
17727 (t (let (org-use-speed-commands)
17728 (call-interactively 'org-self-insert-command)))))
17729 ((and
17730 (org-table-p)
17731 (progn
17732 ;; check if we blank the field, and if that triggers align
17733 (and (featurep 'org-table) org-table-auto-blank-field
17734 (member last-command
17735 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
17736 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
17737 ;; got extra space, this field does not determine column width
17738 (let (org-table-may-need-update) (org-table-blank-field))
17739 ;; no extra space, this field may determine column width
17740 (org-table-blank-field)))
17742 (eq N 1)
17743 (looking-at "[^|\n]* |"))
17744 (let (org-table-may-need-update)
17745 (goto-char (1- (match-end 0)))
17746 (backward-delete-char 1)
17747 (goto-char (match-beginning 0))
17748 (self-insert-command N)))
17750 (setq org-table-may-need-update t)
17751 (self-insert-command N)
17752 (org-fix-tags-on-the-fly)
17753 (if org-self-insert-cluster-for-undo
17754 (if (not (eq last-command 'org-self-insert-command))
17755 (setq org-self-insert-command-undo-counter 1)
17756 (if (>= org-self-insert-command-undo-counter 20)
17757 (setq org-self-insert-command-undo-counter 1)
17758 (and (> org-self-insert-command-undo-counter 0)
17759 buffer-undo-list (listp buffer-undo-list)
17760 (not (cadr buffer-undo-list)) ; remove nil entry
17761 (setcdr buffer-undo-list (cddr buffer-undo-list)))
17762 (setq org-self-insert-command-undo-counter
17763 (1+ org-self-insert-command-undo-counter))))))))
17765 (defun org-check-before-invisible-edit (kind)
17766 "Check is editing if kind KIND would be dangerous with invisible text around.
17767 The detailed reaction depends on the user option `org-catch-invisible-edits'."
17768 ;; First, try to get out of here as quickly as possible, to reduce overhead
17769 (if (and org-catch-invisible-edits
17770 (or (not (boundp 'visible-mode)) (not visible-mode))
17771 (or (get-char-property (point) 'invisible)
17772 (get-char-property (max (point-min) (1- (point))) 'invisible)))
17773 ;; OK, we need to take a closer look
17774 (let* ((invisible-at-point (get-char-property (point) 'invisible))
17775 (invisible-before-point (if (bobp) nil (get-char-property
17776 (1- (point)) 'invisible)))
17777 (border-and-ok-direction
17779 ;; Check if we are acting predictably before invisible text
17780 (and invisible-at-point (not invisible-before-point)
17781 (memq kind '(insert delete-backward)))
17782 ;; Check if we are acting predictably after invisible text
17783 ;; This works not well, and I have turned it off. It seems
17784 ;; better to always show and stop after invisible text.
17785 ;; (and (not invisible-at-point) invisible-before-point
17786 ;; (memq kind '(insert delete)))
17789 (when (or (memq invisible-at-point '(outline org-hide-block))
17790 (memq invisible-before-point '(outline org-hide-block)))
17791 (if (eq org-catch-invisible-edits 'error)
17792 (error "Editing in invisible areas is prohibited - make visible first"))
17793 ;; Make the area visible
17794 (save-excursion
17795 (if invisible-before-point
17796 (goto-char (previous-single-char-property-change
17797 (point) 'invisible)))
17798 (org-cycle))
17799 (cond
17800 ((eq org-catch-invisible-edits 'show)
17801 ;; That's it, we do the edit after showing
17802 (message
17803 "Unfolding invisible region around point before editing")
17804 (sit-for 1))
17805 ((and (eq org-catch-invisible-edits 'smart)
17806 border-and-ok-direction)
17807 (message "Unfolding invisible region around point before editing"))
17809 ;; Don't do the edit, make the user repeat it in full visibility
17810 (error "Edit in invisible region aborted, repeat to confirm with text visible")))))))
17812 (defun org-fix-tags-on-the-fly ()
17813 (when (and (equal (char-after (point-at-bol)) ?*)
17814 (org-at-heading-p))
17815 (org-align-tags-here org-tags-column)))
17817 (defun org-delete-backward-char (N)
17818 "Like `delete-backward-char', insert whitespace at field end in tables.
17819 When deleting backwards, in tables this function will insert whitespace in
17820 front of the next \"|\" separator, to keep the table aligned. The table will
17821 still be marked for re-alignment if the field did fill the entire column,
17822 because, in this case the deletion might narrow the column."
17823 (interactive "p")
17824 (org-check-before-invisible-edit 'delete-backward)
17825 (if (and (org-table-p)
17826 (eq N 1)
17827 (string-match "|" (buffer-substring (point-at-bol) (point)))
17828 (looking-at ".*?|"))
17829 (let ((pos (point))
17830 (noalign (looking-at "[^|\n\r]* |"))
17831 (c org-table-may-need-update))
17832 (backward-delete-char N)
17833 (if (not overwrite-mode)
17834 (progn
17835 (skip-chars-forward "^|")
17836 (insert " ")
17837 (goto-char (1- pos))))
17838 ;; noalign: if there were two spaces at the end, this field
17839 ;; does not determine the width of the column.
17840 (if noalign (setq org-table-may-need-update c)))
17841 (backward-delete-char N)
17842 (org-fix-tags-on-the-fly)))
17844 (defun org-delete-char (N)
17845 "Like `delete-char', but insert whitespace at field end in tables.
17846 When deleting characters, in tables this function will insert whitespace in
17847 front of the next \"|\" separator, to keep the table aligned. The table will
17848 still be marked for re-alignment if the field did fill the entire column,
17849 because, in this case the deletion might narrow the column."
17850 (interactive "p")
17851 (org-check-before-invisible-edit 'delete)
17852 (if (and (org-table-p)
17853 (not (bolp))
17854 (not (= (char-after) ?|))
17855 (eq N 1))
17856 (if (looking-at ".*?|")
17857 (let ((pos (point))
17858 (noalign (looking-at "[^|\n\r]* |"))
17859 (c org-table-may-need-update))
17860 (replace-match (concat
17861 (substring (match-string 0) 1 -1)
17862 " |"))
17863 (goto-char pos)
17864 ;; noalign: if there were two spaces at the end, this field
17865 ;; does not determine the width of the column.
17866 (if noalign (setq org-table-may-need-update c)))
17867 (delete-char N))
17868 (delete-char N)
17869 (org-fix-tags-on-the-fly)))
17871 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
17872 (put 'org-self-insert-command 'delete-selection t)
17873 (put 'orgtbl-self-insert-command 'delete-selection t)
17874 (put 'org-delete-char 'delete-selection 'supersede)
17875 (put 'org-delete-backward-char 'delete-selection 'supersede)
17876 (put 'org-yank 'delete-selection 'yank)
17878 ;; Make `flyspell-mode' delay after some commands
17879 (put 'org-self-insert-command 'flyspell-delayed t)
17880 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
17881 (put 'org-delete-char 'flyspell-delayed t)
17882 (put 'org-delete-backward-char 'flyspell-delayed t)
17884 ;; Make pabbrev-mode expand after org-mode commands
17885 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
17886 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
17888 ;; How to do this: Measure non-white length of current string
17889 ;; If equal to column width, we should realign.
17891 (defun org-remap (map &rest commands)
17892 "In MAP, remap the functions given in COMMANDS.
17893 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
17894 (let (new old)
17895 (while commands
17896 (setq old (pop commands) new (pop commands))
17897 (if (fboundp 'command-remapping)
17898 (org-defkey map (vector 'remap old) new)
17899 (substitute-key-definition old new map global-map)))))
17901 (when (eq org-enable-table-editor 'optimized)
17902 ;; If the user wants maximum table support, we need to hijack
17903 ;; some standard editing functions
17904 (org-remap org-mode-map
17905 'self-insert-command 'org-self-insert-command
17906 'delete-char 'org-delete-char
17907 'delete-backward-char 'org-delete-backward-char)
17908 (org-defkey org-mode-map "|" 'org-force-self-insert))
17910 (defvar org-ctrl-c-ctrl-c-hook nil
17911 "Hook for functions attaching themselves to `C-c C-c'.
17913 This can be used to add additional functionality to the C-c C-c
17914 key which executes context-dependent commands. This hook is run
17915 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
17916 run after the last test.
17918 Each function will be called with no arguments. The function
17919 must check if the context is appropriate for it to act. If yes,
17920 it should do its thing and then return a non-nil value. If the
17921 context is wrong, just do nothing and return nil.")
17923 (defvar org-ctrl-c-ctrl-c-final-hook nil
17924 "Hook for functions attaching themselves to `C-c C-c'.
17926 This can be used to add additional functionality to the C-c C-c
17927 key which executes context-dependent commands. This hook is run
17928 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
17929 before the first test.
17931 Each function will be called with no arguments. The function
17932 must check if the context is appropriate for it to act. If yes,
17933 it should do its thing and then return a non-nil value. If the
17934 context is wrong, just do nothing and return nil.")
17936 (defvar org-tab-first-hook nil
17937 "Hook for functions to attach themselves to TAB.
17938 See `org-ctrl-c-ctrl-c-hook' for more information.
17939 This hook runs as the first action when TAB is pressed, even before
17940 `org-cycle' messes around with the `outline-regexp' to cater for
17941 inline tasks and plain list item folding.
17942 If any function in this hook returns t, any other actions that
17943 would have been caused by TAB (such as table field motion or visibility
17944 cycling) will not occur.")
17946 (defvar org-tab-after-check-for-table-hook nil
17947 "Hook for functions to attach themselves to TAB.
17948 See `org-ctrl-c-ctrl-c-hook' for more information.
17949 This hook runs after it has been established that the cursor is not in a
17950 table, but before checking if the cursor is in a headline or if global cycling
17951 should be done.
17952 If any function in this hook returns t, not other actions like visibility
17953 cycling will be done.")
17955 (defvar org-tab-after-check-for-cycling-hook nil
17956 "Hook for functions to attach themselves to TAB.
17957 See `org-ctrl-c-ctrl-c-hook' for more information.
17958 This hook runs after it has been established that not table field motion and
17959 not visibility should be done because of current context. This is probably
17960 the place where a package like yasnippets can hook in.")
17962 (defvar org-tab-before-tab-emulation-hook nil
17963 "Hook for functions to attach themselves to TAB.
17964 See `org-ctrl-c-ctrl-c-hook' for more information.
17965 This hook runs after every other options for TAB have been exhausted, but
17966 before indentation and \t insertion takes place.")
17968 (defvar org-metaleft-hook nil
17969 "Hook for functions attaching themselves to `M-left'.
17970 See `org-ctrl-c-ctrl-c-hook' for more information.")
17971 (defvar org-metaright-hook nil
17972 "Hook for functions attaching themselves to `M-right'.
17973 See `org-ctrl-c-ctrl-c-hook' for more information.")
17974 (defvar org-metaup-hook nil
17975 "Hook for functions attaching themselves to `M-up'.
17976 See `org-ctrl-c-ctrl-c-hook' for more information.")
17977 (defvar org-metadown-hook nil
17978 "Hook for functions attaching themselves to `M-down'.
17979 See `org-ctrl-c-ctrl-c-hook' for more information.")
17980 (defvar org-shiftmetaleft-hook nil
17981 "Hook for functions attaching themselves to `M-S-left'.
17982 See `org-ctrl-c-ctrl-c-hook' for more information.")
17983 (defvar org-shiftmetaright-hook nil
17984 "Hook for functions attaching themselves to `M-S-right'.
17985 See `org-ctrl-c-ctrl-c-hook' for more information.")
17986 (defvar org-shiftmetaup-hook nil
17987 "Hook for functions attaching themselves to `M-S-up'.
17988 See `org-ctrl-c-ctrl-c-hook' for more information.")
17989 (defvar org-shiftmetadown-hook nil
17990 "Hook for functions attaching themselves to `M-S-down'.
17991 See `org-ctrl-c-ctrl-c-hook' for more information.")
17992 (defvar org-metareturn-hook nil
17993 "Hook for functions attaching themselves to `M-RET'.
17994 See `org-ctrl-c-ctrl-c-hook' for more information.")
17995 (defvar org-shiftup-hook nil
17996 "Hook for functions attaching themselves to `S-up'.
17997 See `org-ctrl-c-ctrl-c-hook' for more information.")
17998 (defvar org-shiftup-final-hook nil
17999 "Hook for functions attaching themselves to `S-up'.
18000 This one runs after all other options except shift-select have been excluded.
18001 See `org-ctrl-c-ctrl-c-hook' for more information.")
18002 (defvar org-shiftdown-hook nil
18003 "Hook for functions attaching themselves to `S-down'.
18004 See `org-ctrl-c-ctrl-c-hook' for more information.")
18005 (defvar org-shiftdown-final-hook nil
18006 "Hook for functions attaching themselves to `S-down'.
18007 This one runs after all other options except shift-select have been excluded.
18008 See `org-ctrl-c-ctrl-c-hook' for more information.")
18009 (defvar org-shiftleft-hook nil
18010 "Hook for functions attaching themselves to `S-left'.
18011 See `org-ctrl-c-ctrl-c-hook' for more information.")
18012 (defvar org-shiftleft-final-hook nil
18013 "Hook for functions attaching themselves to `S-left'.
18014 This one runs after all other options except shift-select have been excluded.
18015 See `org-ctrl-c-ctrl-c-hook' for more information.")
18016 (defvar org-shiftright-hook nil
18017 "Hook for functions attaching themselves to `S-right'.
18018 See `org-ctrl-c-ctrl-c-hook' for more information.")
18019 (defvar org-shiftright-final-hook nil
18020 "Hook for functions attaching themselves to `S-right'.
18021 This one runs after all other options except shift-select have been excluded.
18022 See `org-ctrl-c-ctrl-c-hook' for more information.")
18024 (defun org-modifier-cursor-error ()
18025 "Throw an error, a modified cursor command was applied in wrong context."
18026 (error "This command is active in special context like tables, headlines or items"))
18028 (defun org-shiftselect-error ()
18029 "Throw an error because Shift-Cursor command was applied in wrong context."
18030 (if (and (boundp 'shift-select-mode) shift-select-mode)
18031 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
18032 (error "This command works only in special context like headlines or timestamps")))
18034 (defun org-call-for-shift-select (cmd)
18035 (let ((this-command-keys-shift-translated t))
18036 (call-interactively cmd)))
18038 (defun org-shifttab (&optional arg)
18039 "Global visibility cycling or move to previous table field.
18040 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
18041 on context.
18042 See the individual commands for more information."
18043 (interactive "P")
18044 (cond
18045 ((org-at-table-p) (call-interactively 'org-table-previous-field))
18046 ((integerp arg)
18047 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
18048 (message "Content view to level: %d" arg)
18049 (org-content (prefix-numeric-value arg2))
18050 (setq org-cycle-global-status 'overview)))
18051 (t (call-interactively 'org-global-cycle))))
18053 (defun org-shiftmetaleft ()
18054 "Promote subtree or delete table column.
18055 Calls `org-promote-subtree', `org-outdent-item-tree', or
18056 `org-table-delete-column', depending on context. See the
18057 individual commands for more information."
18058 (interactive)
18059 (cond
18060 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
18061 ((org-at-table-p) (call-interactively 'org-table-delete-column))
18062 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
18063 ((if (not (org-region-active-p)) (org-at-item-p)
18064 (save-excursion (goto-char (region-beginning))
18065 (org-at-item-p)))
18066 (call-interactively 'org-outdent-item-tree))
18067 (t (org-modifier-cursor-error))))
18069 (defun org-shiftmetaright ()
18070 "Demote subtree or insert table column.
18071 Calls `org-demote-subtree', `org-indent-item-tree', or
18072 `org-table-insert-column', depending on context. See the
18073 individual commands for more information."
18074 (interactive)
18075 (cond
18076 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
18077 ((org-at-table-p) (call-interactively 'org-table-insert-column))
18078 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
18079 ((if (not (org-region-active-p)) (org-at-item-p)
18080 (save-excursion (goto-char (region-beginning))
18081 (org-at-item-p)))
18082 (call-interactively 'org-indent-item-tree))
18083 (t (org-modifier-cursor-error))))
18085 (defun org-shiftmetaup (&optional arg)
18086 "Move subtree up or kill table row.
18087 Calls `org-move-subtree-up' or `org-table-kill-row' or
18088 `org-move-item-up' depending on context. See the individual commands
18089 for more information."
18090 (interactive "P")
18091 (cond
18092 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
18093 ((org-at-table-p) (call-interactively 'org-table-kill-row))
18094 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18095 ((org-at-item-p) (call-interactively 'org-move-item-up))
18096 (t (org-modifier-cursor-error))))
18098 (defun org-shiftmetadown (&optional arg)
18099 "Move subtree down or insert table row.
18100 Calls `org-move-subtree-down' or `org-table-insert-row' or
18101 `org-move-item-down', depending on context. See the individual
18102 commands for more information."
18103 (interactive "P")
18104 (cond
18105 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
18106 ((org-at-table-p) (call-interactively 'org-table-insert-row))
18107 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
18108 ((org-at-item-p) (call-interactively 'org-move-item-down))
18109 (t (org-modifier-cursor-error))))
18111 (defsubst org-hidden-tree-error ()
18112 (error
18113 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
18115 (defun org-metaleft (&optional arg)
18116 "Promote heading or move table column to left.
18117 Calls `org-do-promote' or `org-table-move-column', depending on context.
18118 With no specific context, calls the Emacs default `backward-word'.
18119 See the individual commands for more information."
18120 (interactive "P")
18121 (cond
18122 ((run-hook-with-args-until-success 'org-metaleft-hook))
18123 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
18124 ((org-with-limited-levels
18125 (or (org-at-heading-p)
18126 (and (org-region-active-p)
18127 (save-excursion
18128 (goto-char (region-beginning))
18129 (org-at-heading-p)))))
18130 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18131 (call-interactively 'org-do-promote))
18132 ;; At an inline task.
18133 ((org-at-heading-p)
18134 (call-interactively 'org-inlinetask-promote))
18135 ((or (org-at-item-p)
18136 (and (org-region-active-p)
18137 (save-excursion
18138 (goto-char (region-beginning))
18139 (org-at-item-p))))
18140 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
18141 (call-interactively 'org-outdent-item))
18142 (t (call-interactively 'backward-word))))
18144 (defun org-metaright (&optional arg)
18145 "Demote a subtree, a list item or move table column to right.
18146 In front of a drawer or a block keyword, indent it correctly.
18147 With no specific context, calls the Emacs default `forward-word'.
18148 See the individual commands for more information."
18149 (interactive "P")
18150 (cond
18151 ((run-hook-with-args-until-success 'org-metaright-hook))
18152 ((org-at-table-p) (call-interactively 'org-table-move-column))
18153 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
18154 ((org-at-block-p) (call-interactively 'org-indent-block))
18155 ((org-with-limited-levels
18156 (or (org-at-heading-p)
18157 (and (org-region-active-p)
18158 (save-excursion
18159 (goto-char (region-beginning))
18160 (org-at-heading-p)))))
18161 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18162 (call-interactively 'org-do-demote))
18163 ;; At an inline task.
18164 ((org-at-heading-p)
18165 (call-interactively 'org-inlinetask-demote))
18166 ((or (org-at-item-p)
18167 (and (org-region-active-p)
18168 (save-excursion
18169 (goto-char (region-beginning))
18170 (org-at-item-p))))
18171 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
18172 (call-interactively 'org-indent-item))
18173 (t (call-interactively 'forward-word))))
18175 (defun org-check-for-hidden (what)
18176 "Check if there are hidden headlines/items in the current visual line.
18177 WHAT can be either `headlines' or `items'. If the current line is
18178 an outline or item heading and it has a folded subtree below it,
18179 this function returns t, nil otherwise."
18180 (let ((re (cond
18181 ((eq what 'headlines) org-outline-regexp-bol)
18182 ((eq what 'items) (org-item-beginning-re))
18183 (t (error "This should not happen"))))
18184 beg end)
18185 (save-excursion
18186 (catch 'exit
18187 (unless (org-region-active-p)
18188 (setq beg (point-at-bol))
18189 (beginning-of-line 2)
18190 (while (and (not (eobp)) ;; this is like `next-line'
18191 (get-char-property (1- (point)) 'invisible))
18192 (beginning-of-line 2))
18193 (setq end (point))
18194 (goto-char beg)
18195 (goto-char (point-at-eol))
18196 (setq end (max end (point)))
18197 (while (re-search-forward re end t)
18198 (if (get-char-property (match-beginning 0) 'invisible)
18199 (throw 'exit t))))
18200 nil))))
18202 (defun org-metaup (&optional arg)
18203 "Move subtree up or move table row up.
18204 Calls `org-move-subtree-up' or `org-table-move-row' or
18205 `org-move-item-up', depending on context. See the individual commands
18206 for more information."
18207 (interactive "P")
18208 (cond
18209 ((run-hook-with-args-until-success 'org-metaup-hook))
18210 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
18211 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18212 ((org-at-item-p) (call-interactively 'org-move-item-up))
18213 (t (transpose-lines 1) (beginning-of-line -1))))
18215 (defun org-metadown (&optional arg)
18216 "Move subtree down or move table row down.
18217 Calls `org-move-subtree-down' or `org-table-move-row' or
18218 `org-move-item-down', depending on context. See the individual
18219 commands for more information."
18220 (interactive "P")
18221 (cond
18222 ((run-hook-with-args-until-success 'org-metadown-hook))
18223 ((org-at-table-p) (call-interactively 'org-table-move-row))
18224 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
18225 ((org-at-item-p) (call-interactively 'org-move-item-down))
18226 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
18228 (defun org-shiftup (&optional arg)
18229 "Increase item in timestamp or increase priority of current headline.
18230 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
18231 depending on context. See the individual commands for more information."
18232 (interactive "P")
18233 (cond
18234 ((run-hook-with-args-until-success 'org-shiftup-hook))
18235 ((and org-support-shift-select (org-region-active-p))
18236 (org-call-for-shift-select 'previous-line))
18237 ((org-at-timestamp-p t)
18238 (call-interactively (if org-edit-timestamp-down-means-later
18239 'org-timestamp-down 'org-timestamp-up)))
18240 ((and (not (eq org-support-shift-select 'always))
18241 org-enable-priority-commands
18242 (org-at-heading-p))
18243 (call-interactively 'org-priority-up))
18244 ((and (not org-support-shift-select) (org-at-item-p))
18245 (call-interactively 'org-previous-item))
18246 ((org-clocktable-try-shift 'up arg))
18247 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
18248 (org-support-shift-select
18249 (org-call-for-shift-select 'previous-line))
18250 (t (org-shiftselect-error))))
18252 (defun org-shiftdown (&optional arg)
18253 "Decrease item in timestamp or decrease priority of current headline.
18254 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
18255 depending on context. See the individual commands for more information."
18256 (interactive "P")
18257 (cond
18258 ((run-hook-with-args-until-success 'org-shiftdown-hook))
18259 ((and org-support-shift-select (org-region-active-p))
18260 (org-call-for-shift-select 'next-line))
18261 ((org-at-timestamp-p t)
18262 (call-interactively (if org-edit-timestamp-down-means-later
18263 'org-timestamp-up 'org-timestamp-down)))
18264 ((and (not (eq org-support-shift-select 'always))
18265 org-enable-priority-commands
18266 (org-at-heading-p))
18267 (call-interactively 'org-priority-down))
18268 ((and (not org-support-shift-select) (org-at-item-p))
18269 (call-interactively 'org-next-item))
18270 ((org-clocktable-try-shift 'down arg))
18271 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
18272 (org-support-shift-select
18273 (org-call-for-shift-select 'next-line))
18274 (t (org-shiftselect-error))))
18276 (defun org-shiftright (&optional arg)
18277 "Cycle the thing at point or in the current line, depending on context.
18278 Depending on context, this does one of the following:
18280 - switch a timestamp at point one day into the future
18281 - on a headline, switch to the next TODO keyword.
18282 - on an item, switch entire list to the next bullet type
18283 - on a property line, switch to the next allowed value
18284 - on a clocktable definition line, move time block into the future"
18285 (interactive "P")
18286 (cond
18287 ((run-hook-with-args-until-success 'org-shiftright-hook))
18288 ((and org-support-shift-select (org-region-active-p))
18289 (org-call-for-shift-select 'forward-char))
18290 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
18291 ((and (not (eq org-support-shift-select 'always))
18292 (org-at-heading-p))
18293 (let ((org-inhibit-logging
18294 (not org-treat-S-cursor-todo-selection-as-state-change))
18295 (org-inhibit-blocking
18296 (not org-treat-S-cursor-todo-selection-as-state-change)))
18297 (org-call-with-arg 'org-todo 'right)))
18298 ((or (and org-support-shift-select
18299 (not (eq org-support-shift-select 'always))
18300 (org-at-item-bullet-p))
18301 (and (not org-support-shift-select) (org-at-item-p)))
18302 (org-call-with-arg 'org-cycle-list-bullet nil))
18303 ((and (not (eq org-support-shift-select 'always))
18304 (org-at-property-p))
18305 (call-interactively 'org-property-next-allowed-value))
18306 ((org-clocktable-try-shift 'right arg))
18307 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
18308 (org-support-shift-select
18309 (org-call-for-shift-select 'forward-char))
18310 (t (org-shiftselect-error))))
18312 (defun org-shiftleft (&optional arg)
18313 "Cycle the thing at point or in the current line, depending on context.
18314 Depending on context, this does one of the following:
18316 - switch a timestamp at point one day into the past
18317 - on a headline, switch to the previous TODO keyword.
18318 - on an item, switch entire list to the previous bullet type
18319 - on a property line, switch to the previous allowed value
18320 - on a clocktable definition line, move time block into the past"
18321 (interactive "P")
18322 (cond
18323 ((run-hook-with-args-until-success 'org-shiftleft-hook))
18324 ((and org-support-shift-select (org-region-active-p))
18325 (org-call-for-shift-select 'backward-char))
18326 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
18327 ((and (not (eq org-support-shift-select 'always))
18328 (org-at-heading-p))
18329 (let ((org-inhibit-logging
18330 (not org-treat-S-cursor-todo-selection-as-state-change))
18331 (org-inhibit-blocking
18332 (not org-treat-S-cursor-todo-selection-as-state-change)))
18333 (org-call-with-arg 'org-todo 'left)))
18334 ((or (and org-support-shift-select
18335 (not (eq org-support-shift-select 'always))
18336 (org-at-item-bullet-p))
18337 (and (not org-support-shift-select) (org-at-item-p)))
18338 (org-call-with-arg 'org-cycle-list-bullet 'previous))
18339 ((and (not (eq org-support-shift-select 'always))
18340 (org-at-property-p))
18341 (call-interactively 'org-property-previous-allowed-value))
18342 ((org-clocktable-try-shift 'left arg))
18343 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
18344 (org-support-shift-select
18345 (org-call-for-shift-select 'backward-char))
18346 (t (org-shiftselect-error))))
18348 (defun org-shiftcontrolright ()
18349 "Switch to next TODO set."
18350 (interactive)
18351 (cond
18352 ((and org-support-shift-select (org-region-active-p))
18353 (org-call-for-shift-select 'forward-word))
18354 ((and (not (eq org-support-shift-select 'always))
18355 (org-at-heading-p))
18356 (org-call-with-arg 'org-todo 'nextset))
18357 (org-support-shift-select
18358 (org-call-for-shift-select 'forward-word))
18359 (t (org-shiftselect-error))))
18361 (defun org-shiftcontrolleft ()
18362 "Switch to previous TODO set."
18363 (interactive)
18364 (cond
18365 ((and org-support-shift-select (org-region-active-p))
18366 (org-call-for-shift-select 'backward-word))
18367 ((and (not (eq org-support-shift-select 'always))
18368 (org-at-heading-p))
18369 (org-call-with-arg 'org-todo 'previousset))
18370 (org-support-shift-select
18371 (org-call-for-shift-select 'backward-word))
18372 (t (org-shiftselect-error))))
18374 (defun org-shiftcontrolup ()
18375 "Change timestamps synchronously up in CLOCK log lines."
18376 (interactive)
18377 (cond ((and (not org-support-shift-select)
18378 (org-at-clock-log-p)
18379 (org-at-timestamp-p t))
18380 (org-clock-timestamps-up))
18381 (t (org-shiftselect-error))))
18383 (defun org-shiftcontroldown ()
18384 "Change timestamps synchronously down in CLOCK log lines."
18385 (interactive)
18386 (cond ((and (not org-support-shift-select)
18387 (org-at-clock-log-p)
18388 (org-at-timestamp-p t))
18389 (org-clock-timestamps-down))
18390 (t (org-shiftselect-error))))
18392 (defun org-ctrl-c-ret ()
18393 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
18394 (interactive)
18395 (cond
18396 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
18397 (t (call-interactively 'org-insert-heading))))
18399 (defun org-find-visible ()
18400 (let ((s (point)))
18401 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
18402 (get-char-property s 'invisible)))
18404 (defun org-find-invisible ()
18405 (let ((s (point)))
18406 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
18407 (not (get-char-property s 'invisible))))
18410 (defun org-copy-visible (beg end)
18411 "Copy the visible parts of the region."
18412 (interactive "r")
18413 (let (snippets s)
18414 (save-excursion
18415 (save-restriction
18416 (narrow-to-region beg end)
18417 (setq s (goto-char (point-min)))
18418 (while (not (= (point) (point-max)))
18419 (goto-char (org-find-invisible))
18420 (push (buffer-substring s (point)) snippets)
18421 (setq s (goto-char (org-find-visible))))))
18422 (kill-new (apply 'concat (nreverse snippets)))))
18424 (defun org-copy-special ()
18425 "Copy region in table or copy current subtree.
18426 Calls `org-table-copy' or `org-copy-subtree', depending on context.
18427 See the individual commands for more information."
18428 (interactive)
18429 (call-interactively
18430 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
18432 (defun org-cut-special ()
18433 "Cut region in table or cut current subtree.
18434 Calls `org-table-copy' or `org-cut-subtree', depending on context.
18435 See the individual commands for more information."
18436 (interactive)
18437 (call-interactively
18438 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
18440 (defun org-paste-special (arg)
18441 "Paste rectangular region into table, or past subtree relative to level.
18442 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
18443 See the individual commands for more information."
18444 (interactive "P")
18445 (if (org-at-table-p)
18446 (org-table-paste-rectangle)
18447 (org-paste-subtree arg)))
18449 (defun org-edit-special (&optional arg)
18450 "Call a special editor for the stuff at point.
18451 When at a table, call the formula editor with `org-table-edit-formulas'.
18452 When at the first line of an src example, call `org-edit-src-code'.
18453 When in an #+include line, visit the include file. Otherwise call
18454 `ffap' to visit the file at point."
18455 (interactive)
18456 ;; possibly prep session before editing source
18457 (when arg
18458 (let* ((info (org-babel-get-src-block-info))
18459 (lang (nth 0 info))
18460 (params (nth 2 info))
18461 (session (cdr (assoc :session params))))
18462 (when (and info session) ;; we are in a source-code block with a session
18463 (funcall
18464 (intern (concat "org-babel-prep-session:" lang)) session params))))
18465 (cond ;; proceed with `org-edit-special'
18466 ((save-excursion
18467 (beginning-of-line 1)
18468 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
18469 (find-file (org-trim (match-string 1))))
18470 ((org-edit-src-code))
18471 ((org-edit-fixed-width-region))
18472 ((org-at-table.el-p)
18473 (org-edit-src-code))
18474 ((or (org-at-table-p)
18475 (save-excursion
18476 (beginning-of-line 1)
18477 (looking-at "[ \t]*#\\+TBLFM:")))
18478 (call-interactively 'org-table-edit-formulas))
18479 (t (call-interactively 'ffap))))
18481 (defvar org-table-coordinate-overlays) ; defined in org-table.el
18482 (defun org-ctrl-c-ctrl-c (&optional arg)
18483 "Set tags in headline, or update according to changed information at point.
18485 This command does many different things, depending on context:
18487 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
18488 this is what we do.
18490 - If the cursor is on a statistics cookie, update it.
18492 - If the cursor is in a headline, prompt for tags and insert them
18493 into the current line, aligned to `org-tags-column'. When called
18494 with prefix arg, realign all tags in the current buffer.
18496 - If the cursor is in one of the special #+KEYWORD lines, this
18497 triggers scanning the buffer for these lines and updating the
18498 information.
18500 - If the cursor is inside a table, realign the table. This command
18501 works even if the automatic table editor has been turned off.
18503 - If the cursor is on a #+TBLFM line, re-apply the formulas to
18504 the entire table.
18506 - If the cursor is at a footnote reference or definition, jump to
18507 the corresponding definition or references, respectively.
18509 - If the cursor is a the beginning of a dynamic block, update it.
18511 - If the current buffer is a capture buffer, close note and file it.
18513 - If the cursor is on a <<<target>>>, update radio targets and
18514 corresponding links in this buffer.
18516 - If the cursor is on a numbered item in a plain list, renumber the
18517 ordered list.
18519 - If the cursor is on a checkbox, toggle it.
18521 - If the cursor is on a code block, evaluate it. The variable
18522 `org-confirm-babel-evaluate' can be used to control prompting
18523 before code block evaluation, by default every code block
18524 evaluation requires confirmation. Code block evaluation can be
18525 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
18526 (interactive "P")
18527 (let ((org-enable-table-editor t))
18528 (cond
18529 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
18530 org-occur-highlights
18531 org-latex-fragment-image-overlays)
18532 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
18533 (org-remove-occur-highlights)
18534 (org-remove-latex-fragment-image-overlays)
18535 (message "Temporary highlights/overlays removed from current buffer"))
18536 ((and (local-variable-p 'org-finish-function (current-buffer))
18537 (fboundp org-finish-function))
18538 (funcall org-finish-function))
18539 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
18540 ((org-in-regexp org-ts-regexp-both)
18541 (org-timestamp-change 0 'day))
18542 ((or (looking-at org-property-start-re)
18543 (org-at-property-p))
18544 (call-interactively 'org-property-action))
18545 ((org-at-target-p) (call-interactively 'org-update-radio-target-regexp))
18546 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
18547 (or (org-at-heading-p) (org-at-item-p)))
18548 (call-interactively 'org-update-statistics-cookies))
18549 ((org-at-heading-p) (call-interactively 'org-set-tags))
18550 ((org-at-table.el-p)
18551 (message "Use C-c ' to edit table.el tables"))
18552 ((org-at-table-p)
18553 (org-table-maybe-eval-formula)
18554 (if arg
18555 (call-interactively 'org-table-recalculate)
18556 (org-table-maybe-recalculate-line))
18557 (call-interactively 'org-table-align)
18558 (orgtbl-send-table 'maybe))
18559 ((or (org-footnote-at-reference-p)
18560 (org-footnote-at-definition-p))
18561 (call-interactively 'org-footnote-action))
18562 ((org-at-item-checkbox-p)
18563 ;; Cursor at a checkbox: repair list and update checkboxes. Send
18564 ;; list only if at top item.
18565 (let* ((cbox (match-string 1))
18566 (struct (org-list-struct))
18567 (old-struct (copy-tree struct))
18568 (parents (org-list-parents-alist struct))
18569 (orderedp (org-entry-get nil "ORDERED"))
18570 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
18571 block-item)
18572 ;; Use a light version of `org-toggle-checkbox' to avoid
18573 ;; computing list structure twice.
18574 (let ((new-box (cond
18575 ((equal arg '(16)) "[-]")
18576 ((equal arg '(4)) nil)
18577 ((equal "[X]" cbox) "[ ]")
18578 (t "[X]"))))
18579 (if (and firstp arg)
18580 ;; If at first item of sub-list, remove check-box from
18581 ;; every item at the same level.
18582 (mapc
18583 (lambda (pos) (org-list-set-checkbox pos struct new-box))
18584 (org-list-get-all-items
18585 (point-at-bol) struct (org-list-prevs-alist struct)))
18586 (org-list-set-checkbox (point-at-bol) struct new-box)))
18587 ;; Replicate `org-list-write-struct', while grabbing a return
18588 ;; value from `org-list-struct-fix-box'.
18589 (org-list-struct-fix-ind struct parents 2)
18590 (org-list-struct-fix-item-end struct)
18591 (let ((prevs (org-list-prevs-alist struct)))
18592 (org-list-struct-fix-bul struct prevs)
18593 (org-list-struct-fix-ind struct parents)
18594 (setq block-item
18595 (org-list-struct-fix-box struct parents prevs orderedp)))
18596 (org-list-struct-apply-struct struct old-struct)
18597 (org-update-checkbox-count-maybe)
18598 (when block-item
18599 (message
18600 "Checkboxes were removed due to unchecked box at line %d"
18601 (org-current-line block-item)))
18602 (when firstp (org-list-send-list 'maybe))))
18603 ((org-at-item-p)
18604 ;; Cursor at an item: repair list. Do checkbox related actions
18605 ;; only if function was called with an argument. Send list only
18606 ;; if at top item.
18607 (let* ((struct (org-list-struct))
18608 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
18609 old-struct)
18610 (when arg
18611 (setq old-struct (copy-tree struct))
18612 (if firstp
18613 ;; If at first item of sub-list, add check-box to every
18614 ;; item at the same level.
18615 (mapc
18616 (lambda (pos)
18617 (unless (org-list-get-checkbox pos struct)
18618 (org-list-set-checkbox pos struct "[ ]")))
18619 (org-list-get-all-items
18620 (point-at-bol) struct (org-list-prevs-alist struct)))
18621 (org-list-set-checkbox (point-at-bol) struct "[ ]")))
18622 (org-list-write-struct
18623 struct (org-list-parents-alist struct) old-struct)
18624 (when arg (org-update-checkbox-count-maybe))
18625 (when firstp (org-list-send-list 'maybe))))
18626 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
18627 ;; Dynamic block
18628 (beginning-of-line 1)
18629 (save-excursion (org-update-dblock)))
18630 ((save-excursion
18631 (beginning-of-line 1)
18632 (looking-at "[ \t]*#\\+\\([A-Z]+\\)"))
18633 (cond
18634 ((equal (match-string 1) "TBLFM")
18635 ;; Recalculate the table before this line
18636 (save-excursion
18637 (beginning-of-line 1)
18638 (skip-chars-backward " \r\n\t")
18639 (if (org-at-table-p)
18640 (org-call-with-arg 'org-table-recalculate (or arg t)))))
18642 (let ((org-inhibit-startup-visibility-stuff t)
18643 (org-startup-align-all-tables nil))
18644 (when (boundp 'org-table-coordinate-overlays)
18645 (mapc 'delete-overlay org-table-coordinate-overlays)
18646 (setq org-table-coordinate-overlays nil))
18647 (org-save-outline-visibility 'use-markers (org-mode-restart)))
18648 (message "Local setup has been refreshed"))))
18649 ((org-clock-update-time-maybe))
18651 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
18652 (error "C-c C-c can do nothing useful at this location"))))))
18654 (defun org-mode-restart ()
18655 "Restart Org-mode, to scan again for special lines.
18656 Also updates the keyword regular expressions."
18657 (interactive)
18658 (org-mode)
18659 (message "Org-mode restarted"))
18661 (defun org-kill-note-or-show-branches ()
18662 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
18663 (interactive)
18664 (if (not org-finish-function)
18665 (progn
18666 (hide-subtree)
18667 (call-interactively 'show-branches))
18668 (let ((org-note-abort t))
18669 (funcall org-finish-function))))
18671 (defun org-return (&optional indent)
18672 "Goto next table row or insert a newline.
18673 Calls `org-table-next-row' or `newline', depending on context.
18674 See the individual commands for more information."
18675 (interactive)
18676 (cond
18677 ((or (bobp) (org-in-src-block-p))
18678 (if indent (newline-and-indent) (newline)))
18679 ((org-at-table-p)
18680 (org-table-justify-field-maybe)
18681 (call-interactively 'org-table-next-row))
18682 ;; when `newline-and-indent' is called within a list, make sure
18683 ;; text moved stays inside the item.
18684 ((and (org-in-item-p) indent)
18685 (if (and (org-at-item-p) (>= (point) (match-end 0)))
18686 (progn
18687 (save-match-data (newline))
18688 (org-indent-line-to (length (match-string 0))))
18689 (let ((ind (org-get-indentation)))
18690 (newline)
18691 (if (org-looking-back org-list-end-re)
18692 (org-indent-line-function)
18693 (org-indent-line-to ind)))))
18694 ((and org-return-follows-link
18695 (let ((tprop (get-text-property (point) 'face)))
18696 (or (eq tprop 'org-link)
18697 (and (listp tprop) (memq 'org-link tprop)))))
18698 (call-interactively 'org-open-at-point))
18699 ((and (org-at-heading-p)
18700 (looking-at
18701 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
18702 (org-show-entry)
18703 (end-of-line 1)
18704 (newline))
18705 (t (if indent (newline-and-indent) (newline)))))
18707 (defun org-return-indent ()
18708 "Goto next table row or insert a newline and indent.
18709 Calls `org-table-next-row' or `newline-and-indent', depending on
18710 context. See the individual commands for more information."
18711 (interactive)
18712 (org-return t))
18714 (defun org-ctrl-c-star ()
18715 "Compute table, or change heading status of lines.
18716 Calls `org-table-recalculate' or `org-toggle-heading',
18717 depending on context."
18718 (interactive)
18719 (cond
18720 ((org-at-table-p)
18721 (call-interactively 'org-table-recalculate))
18723 ;; Convert all lines in region to list items
18724 (call-interactively 'org-toggle-heading))))
18726 (defun org-ctrl-c-minus ()
18727 "Insert separator line in table or modify bullet status of line.
18728 Also turns a plain line or a region of lines into list items.
18729 Calls `org-table-insert-hline', `org-toggle-item', or
18730 `org-cycle-list-bullet', depending on context."
18731 (interactive)
18732 (cond
18733 ((org-at-table-p)
18734 (call-interactively 'org-table-insert-hline))
18735 ((org-region-active-p)
18736 (call-interactively 'org-toggle-item))
18737 ((org-in-item-p)
18738 (call-interactively 'org-cycle-list-bullet))
18740 (call-interactively 'org-toggle-item))))
18742 (defun org-toggle-item (arg)
18743 "Convert headings or normal lines to items, items to normal lines.
18744 If there is no active region, only the current line is considered.
18746 If the first non blank line in the region is an headline, convert
18747 all headlines to items, shifting text accordingly.
18749 If it is an item, convert all items to normal lines.
18751 If it is normal text, change region into an item. With a prefix
18752 argument ARG, change each line in region into an item."
18753 (interactive "P")
18754 (let ((shift-text
18755 (function
18756 ;; Shift text in current section to IND, from point to END.
18757 ;; The function leaves point to END line.
18758 (lambda (ind end)
18759 (let ((min-i 1000) (end (copy-marker end)))
18760 ;; First determine the minimum indentation (MIN-I) of
18761 ;; the text.
18762 (save-excursion
18763 (catch 'exit
18764 (while (< (point) end)
18765 (let ((i (org-get-indentation)))
18766 (cond
18767 ;; Skip blank lines and inline tasks.
18768 ((looking-at "^[ \t]*$"))
18769 ((looking-at org-outline-regexp-bol))
18770 ;; We can't find less than 0 indentation.
18771 ((zerop i) (throw 'exit (setq min-i 0)))
18772 ((< i min-i) (setq min-i i))))
18773 (forward-line))))
18774 ;; Then indent each line so that a line indented to
18775 ;; MIN-I becomes indented to IND. Ignore blank lines
18776 ;; and inline tasks in the process.
18777 (let ((delta (- ind min-i)))
18778 (while (< (point) end)
18779 (unless (or (looking-at "^[ \t]*$")
18780 (looking-at org-outline-regexp-bol))
18781 (org-indent-line-to (+ (org-get-indentation) delta)))
18782 (forward-line)))))))
18783 (skip-blanks
18784 (function
18785 ;; Return beginning of first non-blank line, starting from
18786 ;; line at POS.
18787 (lambda (pos)
18788 (save-excursion
18789 (goto-char pos)
18790 (skip-chars-forward " \r\t\n")
18791 (point-at-bol)))))
18792 beg end)
18793 ;; Determine boundaries of changes.
18794 (if (org-region-active-p)
18795 (setq beg (funcall skip-blanks (region-beginning))
18796 end (copy-marker (region-end)))
18797 (setq beg (funcall skip-blanks (point-at-bol))
18798 end (copy-marker (point-at-eol))))
18799 ;; Depending on the starting line, choose an action on the text
18800 ;; between BEG and END.
18801 (org-with-limited-levels
18802 (save-excursion
18803 (goto-char beg)
18804 (cond
18805 ;; Case 1. Start at an item: de-itemize. Note that it only
18806 ;; happens when a region is active: `org-ctrl-c-minus'
18807 ;; would call `org-cycle-list-bullet' otherwise.
18808 ((org-at-item-p)
18809 (while (< (point) end)
18810 (when (org-at-item-p)
18811 (skip-chars-forward " \t")
18812 (delete-region (point) (match-end 0)))
18813 (forward-line)))
18814 ;; Case 2. Start at an heading: convert to items.
18815 ((org-at-heading-p)
18816 (let* ((bul (org-list-bullet-string "-"))
18817 (bul-len (length bul))
18818 ;; Indentation of the first heading. It should be
18819 ;; relative to the indentation of its parent, if any.
18820 (start-ind (save-excursion
18821 (cond
18822 ((not org-adapt-indentation) 0)
18823 ((not (outline-previous-heading)) 0)
18824 (t (length (match-string 0))))))
18825 ;; Level of first heading. Further headings will be
18826 ;; compared to it to determine hierarchy in the list.
18827 (ref-level (org-reduced-level (org-outline-level))))
18828 (while (< (point) end)
18829 (let* ((level (org-reduced-level (org-outline-level)))
18830 (delta (max 0 (- level ref-level))))
18831 ;; If current headline is less indented than the first
18832 ;; one, set it as reference, in order to preserve
18833 ;; subtrees.
18834 (when (< level ref-level) (setq ref-level level))
18835 (replace-match bul t t)
18836 (org-indent-line-to (+ start-ind (* delta bul-len)))
18837 ;; Ensure all text down to END (or SECTION-END) belongs
18838 ;; to the newly created item.
18839 (let ((section-end (save-excursion
18840 (or (outline-next-heading) (point)))))
18841 (forward-line)
18842 (funcall shift-text
18843 (+ start-ind (* (1+ delta) bul-len))
18844 (min end section-end)))))))
18845 ;; Case 3. Normal line with ARG: turn each non-item line into
18846 ;; an item.
18847 (arg
18848 (while (< (point) end)
18849 (unless (or (org-at-heading-p) (org-at-item-p))
18850 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
18851 (replace-match
18852 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
18853 (forward-line)))
18854 ;; Case 4. Normal line without ARG: make the first line of
18855 ;; region an item, and shift indentation of others
18856 ;; lines to set them as item's body.
18857 (t (let* ((bul (org-list-bullet-string "-"))
18858 (bul-len (length bul))
18859 (ref-ind (org-get-indentation)))
18860 (skip-chars-forward " \t")
18861 (insert bul)
18862 (forward-line)
18863 (while (< (point) end)
18864 ;; Ensure that lines less indented than first one
18865 ;; still get included in item body.
18866 (funcall shift-text
18867 (+ ref-ind bul-len)
18868 (min end (save-excursion (or (outline-next-heading)
18869 (point)))))
18870 (forward-line)))))))))
18872 (defun org-toggle-heading (&optional nstars)
18873 "Convert headings to normal text, or items or text to headings.
18874 If there is no active region, only the current line is considered.
18876 If the first non blank line is an headline, remove the stars from
18877 all headlines in the region.
18879 If it is a plain list item, turn all plain list items into headings.
18881 If it is a normal line, turn each and every normal line (i.e. not
18882 an heading or an item) in the region into a heading.
18884 When converting a line into a heading, the number of stars is chosen
18885 such that the lines become children of the current entry. However,
18886 when a prefix argument is given, its value determines the number of
18887 stars to add."
18888 (interactive "P")
18889 (let ((skip-blanks
18890 (function
18891 ;; Return beginning of first non-blank line, starting from
18892 ;; line at POS.
18893 (lambda (pos)
18894 (save-excursion
18895 (goto-char pos)
18896 (skip-chars-forward " \r\t\n")
18897 (point-at-bol)))))
18898 beg end)
18899 ;; Determine boundaries of changes. If region ends at a bol, do
18900 ;; not consider the last line to be in the region.
18901 (if (org-region-active-p)
18902 (setq beg (funcall skip-blanks (region-beginning))
18903 end (copy-marker (save-excursion
18904 (goto-char (region-end))
18905 (if (bolp) (point) (point-at-eol)))))
18906 (setq beg (funcall skip-blanks (point-at-bol))
18907 end (copy-marker (point-at-eol))))
18908 ;; Ensure inline tasks don't count as headings.
18909 (org-with-limited-levels
18910 (save-excursion
18911 (goto-char beg)
18912 (cond
18913 ;; Case 1. Started at an heading: de-star headings.
18914 ((org-at-heading-p)
18915 (while (< (point) end)
18916 (when (org-at-heading-p t)
18917 (looking-at org-outline-regexp) (replace-match ""))
18918 (forward-line)))
18919 ;; Case 2. Started at an item: change items into headlines.
18920 ;; One star will be added by `org-list-to-subtree'.
18921 ((org-at-item-p)
18922 (let* ((stars (make-string
18923 (if nstars
18924 ;; subtract the star that will be added again by
18925 ;; `org-list-to-subtree'
18926 (1- (prefix-numeric-value current-prefix-arg))
18927 (or (org-current-level) 0))
18928 ?*))
18929 (add-stars
18930 (cond (nstars "") ; stars from prefix only
18931 ((equal stars "") "") ; before first heading
18932 (org-odd-levels-only "*") ; inside heading, odd
18933 (t "")))) ; inside heading, oddeven
18934 (while (< (point) end)
18935 (when (org-at-item-p)
18936 ;; Pay attention to cases when region ends before list.
18937 (let* ((struct (org-list-struct))
18938 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
18939 (save-restriction
18940 (narrow-to-region (point) list-end)
18941 (insert
18942 (org-list-to-subtree
18943 (org-list-parse-list t)
18944 '(:istart (concat stars add-stars (funcall get-stars depth))
18945 :icount (concat stars add-stars (funcall get-stars depth))))))))
18946 (forward-line))))
18947 ;; Case 3. Started at normal text: make every line an heading,
18948 ;; skipping headlines and items.
18949 (t (let* ((stars (make-string
18950 (if nstars
18951 (prefix-numeric-value current-prefix-arg)
18952 (or (org-current-level) 0))
18953 ?*))
18954 (add-stars
18955 (cond (nstars "") ; stars from prefix only
18956 ((equal stars "") "*") ; before first heading
18957 (org-odd-levels-only "**") ; inside heading, odd
18958 (t "*"))) ; inside heading, oddeven
18959 (rpl (concat stars add-stars " ")))
18960 (while (< (point) end)
18961 (when (and (not (org-at-heading-p)) (not (org-at-item-p))
18962 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
18963 (replace-match (concat rpl (match-string 2))))
18964 (forward-line)))))))))
18966 (defun org-meta-return (&optional arg)
18967 "Insert a new heading or wrap a region in a table.
18968 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
18969 See the individual commands for more information."
18970 (interactive "P")
18971 (cond
18972 ((run-hook-with-args-until-success 'org-metareturn-hook))
18973 ((or (org-at-drawer-p) (org-at-property-p))
18974 (newline-and-indent))
18975 ((org-at-table-p)
18976 (call-interactively 'org-table-wrap-region))
18977 (t (call-interactively 'org-insert-heading))))
18979 ;;; Menu entries
18981 ;; Define the Org-mode menus
18982 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
18983 '("Tbl"
18984 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
18985 ["Next Field" org-cycle (org-at-table-p)]
18986 ["Previous Field" org-shifttab (org-at-table-p)]
18987 ["Next Row" org-return (org-at-table-p)]
18988 "--"
18989 ["Blank Field" org-table-blank-field (org-at-table-p)]
18990 ["Edit Field" org-table-edit-field (org-at-table-p)]
18991 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
18992 "--"
18993 ("Column"
18994 ["Move Column Left" org-metaleft (org-at-table-p)]
18995 ["Move Column Right" org-metaright (org-at-table-p)]
18996 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
18997 ["Insert Column" org-shiftmetaright (org-at-table-p)])
18998 ("Row"
18999 ["Move Row Up" org-metaup (org-at-table-p)]
19000 ["Move Row Down" org-metadown (org-at-table-p)]
19001 ["Delete Row" org-shiftmetaup (org-at-table-p)]
19002 ["Insert Row" org-shiftmetadown (org-at-table-p)]
19003 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
19004 "--"
19005 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
19006 ("Rectangle"
19007 ["Copy Rectangle" org-copy-special (org-at-table-p)]
19008 ["Cut Rectangle" org-cut-special (org-at-table-p)]
19009 ["Paste Rectangle" org-paste-special (org-at-table-p)]
19010 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
19011 "--"
19012 ("Calculate"
19013 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
19014 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
19015 ["Edit Formulas" org-edit-special (org-at-table-p)]
19016 "--"
19017 ["Recalculate line" org-table-recalculate (org-at-table-p)]
19018 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
19019 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
19020 "--"
19021 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
19022 "--"
19023 ["Sum Column/Rectangle" org-table-sum
19024 (or (org-at-table-p) (org-region-active-p))]
19025 ["Which Column?" org-table-current-column (org-at-table-p)])
19026 ["Debug Formulas"
19027 org-table-toggle-formula-debugger
19028 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
19029 ["Show Col/Row Numbers"
19030 org-table-toggle-coordinate-overlays
19031 :style toggle
19032 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
19033 "--"
19034 ["Create" org-table-create (and (not (org-at-table-p))
19035 org-enable-table-editor)]
19036 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
19037 ["Import from File" org-table-import (not (org-at-table-p))]
19038 ["Export to File" org-table-export (org-at-table-p)]
19039 "--"
19040 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
19042 (easy-menu-define org-org-menu org-mode-map "Org menu"
19043 '("Org"
19044 ("Show/Hide"
19045 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
19046 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
19047 ["Sparse Tree..." org-sparse-tree t]
19048 ["Reveal Context" org-reveal t]
19049 ["Show All" show-all t]
19050 "--"
19051 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
19052 "--"
19053 ["New Heading" org-insert-heading t]
19054 ("Navigate Headings"
19055 ["Up" outline-up-heading t]
19056 ["Next" outline-next-visible-heading t]
19057 ["Previous" outline-previous-visible-heading t]
19058 ["Next Same Level" outline-forward-same-level t]
19059 ["Previous Same Level" outline-backward-same-level t]
19060 "--"
19061 ["Jump" org-goto t])
19062 ("Edit Structure"
19063 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
19064 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
19065 "--"
19066 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
19067 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
19068 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
19069 "--"
19070 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
19071 "--"
19072 ["Copy visible text" org-copy-visible t]
19073 "--"
19074 ["Promote Heading" org-metaleft (not (org-at-table-p))]
19075 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
19076 ["Demote Heading" org-metaright (not (org-at-table-p))]
19077 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
19078 "--"
19079 ["Sort Region/Children" org-sort (not (org-at-table-p))]
19080 "--"
19081 ["Convert to odd levels" org-convert-to-odd-levels t]
19082 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
19083 ("Editing"
19084 ["Emphasis..." org-emphasize t]
19085 ["Edit Source Example" org-edit-special t]
19086 "--"
19087 ["Footnote new/jump" org-footnote-action t]
19088 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
19089 ("Archive"
19090 ["Archive (default method)" org-archive-subtree-default t]
19091 "--"
19092 ["Move Subtree to Archive file" org-advertized-archive-subtree t]
19093 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
19094 ["Move subtree to Archive sibling" org-archive-to-archive-sibling t]
19096 "--"
19097 ("Hyperlinks"
19098 ["Store Link (Global)" org-store-link t]
19099 ["Find existing link to here" org-occur-link-in-agenda-files t]
19100 ["Insert Link" org-insert-link t]
19101 ["Follow Link" org-open-at-point t]
19102 "--"
19103 ["Next link" org-next-link t]
19104 ["Previous link" org-previous-link t]
19105 "--"
19106 ["Descriptive Links"
19107 org-toggle-link-display
19108 :style radio
19109 :selected org-descriptive-links
19111 ["Literal Links"
19112 org-toggle-link-display
19113 :style radio
19114 :selected (not org-descriptive-links)])
19115 "--"
19116 ("TODO Lists"
19117 ["TODO/DONE/-" org-todo t]
19118 ("Select keyword"
19119 ["Next keyword" org-shiftright (org-at-heading-p)]
19120 ["Previous keyword" org-shiftleft (org-at-heading-p)]
19121 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
19122 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
19123 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
19124 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
19125 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
19126 "--"
19127 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
19128 :selected org-enforce-todo-dependencies :style toggle :active t]
19129 "Settings for tree at point"
19130 ["Do Children sequentially" org-toggle-ordered-property :style radio
19131 :selected (org-entry-get nil "ORDERED")
19132 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
19133 ["Do Children parallel" org-toggle-ordered-property :style radio
19134 :selected (not (org-entry-get nil "ORDERED"))
19135 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
19136 "--"
19137 ["Set Priority" org-priority t]
19138 ["Priority Up" org-shiftup t]
19139 ["Priority Down" org-shiftdown t]
19140 "--"
19141 ["Get news from all feeds" org-feed-update-all t]
19142 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
19143 ["Customize feeds" (customize-variable 'org-feed-alist) t])
19144 ("TAGS and Properties"
19145 ["Set Tags" org-set-tags-command t]
19146 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
19147 "--"
19148 ["Set property" org-set-property t]
19149 ["Column view of properties" org-columns t]
19150 ["Insert Column View DBlock" org-insert-columns-dblock t])
19151 ("Dates and Scheduling"
19152 ["Timestamp" org-time-stamp t]
19153 ["Timestamp (inactive)" org-time-stamp-inactive t]
19154 ("Change Date"
19155 ["1 Day Later" org-shiftright t]
19156 ["1 Day Earlier" org-shiftleft t]
19157 ["1 ... Later" org-shiftup t]
19158 ["1 ... Earlier" org-shiftdown t])
19159 ["Compute Time Range" org-evaluate-time-range t]
19160 ["Schedule Item" org-schedule t]
19161 ["Deadline" org-deadline t]
19162 "--"
19163 ["Custom time format" org-toggle-time-stamp-overlays
19164 :style radio :selected org-display-custom-times]
19165 "--"
19166 ["Goto Calendar" org-goto-calendar t]
19167 ["Date from Calendar" org-date-from-calendar t]
19168 "--"
19169 ["Start/Restart Timer" org-timer-start t]
19170 ["Pause/Continue Timer" org-timer-pause-or-continue t]
19171 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
19172 ["Insert Timer String" org-timer t]
19173 ["Insert Timer Item" org-timer-item t])
19174 ("Logging work"
19175 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
19176 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
19177 ["Clock out" org-clock-out t]
19178 ["Clock cancel" org-clock-cancel t]
19179 "--"
19180 ["Mark as default task" org-clock-mark-default-task t]
19181 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
19182 ["Goto running clock" org-clock-goto t]
19183 "--"
19184 ["Display times" org-clock-display t]
19185 ["Create clock table" org-clock-report t]
19186 "--"
19187 ["Record DONE time"
19188 (progn (setq org-log-done (not org-log-done))
19189 (message "Switching to %s will %s record a timestamp"
19190 (car org-done-keywords)
19191 (if org-log-done "automatically" "not")))
19192 :style toggle :selected org-log-done])
19193 "--"
19194 ["Agenda Command..." org-agenda t]
19195 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
19196 ("File List for Agenda")
19197 ("Special views current file"
19198 ["TODO Tree" org-show-todo-tree t]
19199 ["Check Deadlines" org-check-deadlines t]
19200 ["Timeline" org-timeline t]
19201 ["Tags/Property tree" org-match-sparse-tree t])
19202 "--"
19203 ["Export/Publish..." org-export t]
19204 ("LaTeX"
19205 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
19206 :selected org-cdlatex-mode]
19207 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
19208 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
19209 ["Modify math symbol" org-cdlatex-math-modify
19210 (org-inside-LaTeX-fragment-p)]
19211 ["Insert citation" org-reftex-citation t]
19212 "--"
19213 ["Template for BEAMER" (progn (require 'org-beamer)
19214 (org-insert-beamer-options-template)) t])
19215 "--"
19216 ("MobileOrg"
19217 ["Push Files and Views" org-mobile-push t]
19218 ["Get Captured and Flagged" org-mobile-pull t]
19219 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
19220 "--"
19221 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
19222 "--"
19223 ("Documentation"
19224 ["Show Version" org-version t]
19225 ["Info Documentation" org-info t])
19226 ("Customize"
19227 ["Browse Org Group" org-customize t]
19228 "--"
19229 ["Expand This Menu" org-create-customize-menu
19230 (fboundp 'customize-menu-create)])
19231 ["Send bug report" org-submit-bug-report t]
19232 "--"
19233 ("Refresh/Reload"
19234 ["Refresh setup current buffer" org-mode-restart t]
19235 ["Reload Org (after update)" org-reload t]
19236 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
19239 (defun org-info (&optional node)
19240 "Read documentation for Org-mode in the info system.
19241 With optional NODE, go directly to that node."
19242 (interactive)
19243 (info (format "(org)%s" (or node ""))))
19245 ;;;###autoload
19246 (defun org-submit-bug-report ()
19247 "Submit a bug report on Org-mode via mail.
19249 Don't hesitate to report any problems or inaccurate documentation.
19251 If you don't have setup sending mail from (X)Emacs, please copy the
19252 output buffer into your mail program, as it gives us important
19253 information about your Org-mode version and configuration."
19254 (interactive)
19255 (require 'reporter)
19256 (org-load-modules-maybe)
19257 (org-require-autoloaded-modules)
19258 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
19259 (reporter-submit-bug-report
19260 "emacs-orgmode@gnu.org"
19261 (org-version)
19262 (let (list)
19263 (save-window-excursion
19264 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
19265 (delete-other-windows)
19266 (erase-buffer)
19267 (insert "You are about to submit a bug report to the Org-mode mailing list.
19269 We would like to add your full Org-mode and Outline configuration to the
19270 bug report. This greatly simplifies the work of the maintainer and
19271 other experts on the mailing list.
19273 HOWEVER, some variables you have customized may contain private
19274 information. The names of customers, colleagues, or friends, might
19275 appear in the form of file names, tags, todo states, or search strings.
19276 If you answer yes to the prompt, you might want to check and remove
19277 such private information before sending the email.")
19278 (add-text-properties (point-min) (point-max) '(face org-warning))
19279 (when (yes-or-no-p "Include your Org-mode configuration ")
19280 (mapatoms
19281 (lambda (v)
19282 (and (boundp v)
19283 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
19284 (or (and (symbol-value v)
19285 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
19286 (and
19287 (get v 'custom-type) (get v 'standard-value)
19288 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
19289 (push v list)))))
19290 (kill-buffer (get-buffer "*Warn about privacy*"))
19291 list))
19292 nil nil
19293 "Remember to cover the basics, that is, what you expected to happen and
19294 what in fact did happen. You don't know how to make a good report? See
19296 http://orgmode.org/manual/Feedback.html#Feedback
19298 Your bug report will be posted to the Org-mode mailing list.
19299 ------------------------------------------------------------------------")
19300 (save-excursion
19301 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
19302 (replace-match "\\1Bug: \\3 [\\2]")))))
19305 (defun org-install-agenda-files-menu ()
19306 (let ((bl (buffer-list)))
19307 (save-excursion
19308 (while bl
19309 (set-buffer (pop bl))
19310 (if (eq major-mode 'org-mode) (setq bl nil)))
19311 (when (eq major-mode 'org-mode)
19312 (easy-menu-change
19313 '("Org") "File List for Agenda"
19314 (append
19315 (list
19316 ["Edit File List" (org-edit-agenda-file-list) t]
19317 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
19318 ["Remove Current File from List" org-remove-file t]
19319 ["Cycle through agenda files" org-cycle-agenda-files t]
19320 ["Occur in all agenda files" org-occur-in-agenda-files t]
19321 "--")
19322 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
19324 ;;;; Documentation
19326 ;;;###autoload
19327 (defun org-require-autoloaded-modules ()
19328 (interactive)
19329 (mapc 'require
19330 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
19331 org-docbook org-exp org-html org-icalendar
19332 org-id org-latex
19333 org-publish org-remember org-table
19334 org-timer org-xoxo)))
19336 ;;;###autoload
19337 (defun org-reload (&optional uncompiled)
19338 "Reload all org lisp files.
19339 With prefix arg UNCOMPILED, load the uncompiled versions."
19340 (interactive "P")
19341 (require 'find-func)
19342 (let* ((file-re "^\\(org\\|orgtbl\\)\\(\\.el\\|-.*\\.el\\)")
19343 (dir-org (file-name-directory (org-find-library-name "org")))
19344 (dir-org-contrib (ignore-errors
19345 (file-name-directory
19346 (org-find-library-name "org-contribdir"))))
19347 (babel-files
19348 (mapcar (lambda (el) (concat "ob" (when el (format "-%s" el)) ".el"))
19349 (append (list nil "comint" "eval" "exp" "keys"
19350 "lob" "ref" "table" "tangle")
19351 (delq nil
19352 (mapcar
19353 (lambda (lang)
19354 (when (cdr lang) (symbol-name (car lang))))
19355 org-babel-load-languages)))))
19356 (files
19357 (append (directory-files dir-org t file-re)
19358 babel-files
19359 (and dir-org-contrib
19360 (directory-files dir-org-contrib t file-re))))
19361 (remove-re (concat (if (featurep 'xemacs)
19362 "org-colview" "org-colview-xemacs")
19363 "\\'")))
19364 (setq files (mapcar 'file-name-sans-extension files))
19365 (setq files (mapcar
19366 (lambda (x) (if (string-match remove-re x) nil x))
19367 files))
19368 (setq files (delq nil files))
19369 (mapc
19370 (lambda (f)
19371 (when (featurep (intern (file-name-nondirectory f)))
19372 (if (and (not uncompiled)
19373 (file-exists-p (concat f ".elc")))
19374 (load (concat f ".elc") nil nil t)
19375 (load (concat f ".el") nil nil t))))
19376 files))
19377 (org-version))
19379 ;;;###autoload
19380 (defun org-customize ()
19381 "Call the customize function with org as argument."
19382 (interactive)
19383 (org-load-modules-maybe)
19384 (org-require-autoloaded-modules)
19385 (customize-browse 'org))
19387 (defun org-create-customize-menu ()
19388 "Create a full customization menu for Org-mode, insert it into the menu."
19389 (interactive)
19390 (org-load-modules-maybe)
19391 (org-require-autoloaded-modules)
19392 (if (fboundp 'customize-menu-create)
19393 (progn
19394 (easy-menu-change
19395 '("Org") "Customize"
19396 `(["Browse Org group" org-customize t]
19397 "--"
19398 ,(customize-menu-create 'org)
19399 ["Set" Custom-set t]
19400 ["Save" Custom-save t]
19401 ["Reset to Current" Custom-reset-current t]
19402 ["Reset to Saved" Custom-reset-saved t]
19403 ["Reset to Standard Settings" Custom-reset-standard t]))
19404 (message "\"Org\"-menu now contains full customization menu"))
19405 (error "Cannot expand menu (outdated version of cus-edit.el)")))
19407 ;;;; Miscellaneous stuff
19409 ;;; Generally useful functions
19411 (defun org-get-at-bol (property)
19412 "Get text property PROPERTY at beginning of line."
19413 (get-text-property (point-at-bol) property))
19415 (defun org-find-text-property-in-string (prop s)
19416 "Return the first non-nil value of property PROP in string S."
19417 (or (get-text-property 0 prop s)
19418 (get-text-property (or (next-single-property-change 0 prop s) 0)
19419 prop s)))
19421 (defun org-display-warning (message) ;; Copied from Emacs-Muse
19422 "Display the given MESSAGE as a warning."
19423 (if (fboundp 'display-warning)
19424 (display-warning 'org message
19425 (if (featurep 'xemacs) 'warning :warning))
19426 (let ((buf (get-buffer-create "*Org warnings*")))
19427 (with-current-buffer buf
19428 (goto-char (point-max))
19429 (insert "Warning (Org): " message)
19430 (unless (bolp)
19431 (newline)))
19432 (display-buffer buf)
19433 (sit-for 0))))
19435 (defun org-eval (form)
19436 "Eval FORM and return result."
19437 (condition-case error
19438 (eval form)
19439 (error (format "%%![Error: %s]" error))))
19441 (defun org-in-clocktable-p ()
19442 "Check if the cursor is in a clocktable."
19443 (let ((pos (point)) start)
19444 (save-excursion
19445 (end-of-line 1)
19446 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
19447 (setq start (match-beginning 0))
19448 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
19449 (>= (match-end 0) pos)
19450 start))))
19452 (defun org-in-commented-line ()
19453 "Is point in a line starting with `#'?"
19454 (equal (char-after (point-at-bol)) ?#))
19456 (defun org-in-indented-comment-line ()
19457 "Is point in a line starting with `#' after some white space?"
19458 (save-excursion
19459 (save-match-data
19460 (goto-char (point-at-bol))
19461 (looking-at "[ \t]*#"))))
19463 (defun org-in-verbatim-emphasis ()
19464 (save-match-data
19465 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
19467 (defun org-goto-marker-or-bmk (marker &optional bookmark)
19468 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
19469 (if (and marker (marker-buffer marker)
19470 (buffer-live-p (marker-buffer marker)))
19471 (progn
19472 (org-pop-to-buffer-same-window (marker-buffer marker))
19473 (if (or (> marker (point-max)) (< marker (point-min)))
19474 (widen))
19475 (goto-char marker)
19476 (org-show-context 'org-goto))
19477 (if bookmark
19478 (bookmark-jump bookmark)
19479 (error "Cannot find location"))))
19481 (defun org-quote-csv-field (s)
19482 "Quote field for inclusion in CSV material."
19483 (if (string-match "[\",]" s)
19484 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
19487 (defun org-force-self-insert (N)
19488 "Needed to enforce self-insert under remapping."
19489 (interactive "p")
19490 (self-insert-command N))
19492 (defun org-string-width (s)
19493 "Compute width of string, ignoring invisible characters.
19494 This ignores character with invisibility property `org-link', and also
19495 characters with property `org-cwidth', because these will become invisible
19496 upon the next fontification round."
19497 (let (b l)
19498 (when (or (eq t buffer-invisibility-spec)
19499 (assq 'org-link buffer-invisibility-spec))
19500 (while (setq b (text-property-any 0 (length s)
19501 'invisible 'org-link s))
19502 (setq s (concat (substring s 0 b)
19503 (substring s (or (next-single-property-change
19504 b 'invisible s) (length s)))))))
19505 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
19506 (setq s (concat (substring s 0 b)
19507 (substring s (or (next-single-property-change
19508 b 'org-cwidth s) (length s))))))
19509 (setq l (string-width s) b -1)
19510 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
19511 (setq l (- l (get-text-property b 'org-dwidth-n s))))
19514 (defun org-shorten-string (s maxlength)
19515 "Shorten string S so tht it is no longer than MAXLENGTH characters.
19516 If the string is shorter or has length MAXLENGTH, just return the
19517 original string. If it is longer, the functions finds a space in the
19518 string, breaks this string off at that locations and adds three dots
19519 as ellipsis. Including the ellipsis, the string will not be longer
19520 than MAXLENGTH. If finding a good breaking point in the string does
19521 not work, the string is just chopped off in the middle of a word
19522 if necessary."
19523 (if (<= (length s) maxlength)
19525 (let* ((n (max (- maxlength 4) 1))
19526 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
19527 (if (string-match re s)
19528 (concat (match-string 1 s) "...")
19529 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
19531 (defun org-get-indentation (&optional line)
19532 "Get the indentation of the current line, interpreting tabs.
19533 When LINE is given, assume it represents a line and compute its indentation."
19534 (if line
19535 (if (string-match "^ *" (org-remove-tabs line))
19536 (match-end 0))
19537 (save-excursion
19538 (beginning-of-line 1)
19539 (skip-chars-forward " \t")
19540 (current-column))))
19542 (defun org-get-string-indentation (s)
19543 "What indentation has S due to SPACE and TAB at the beginning of the string?"
19544 (let ((n -1) (i 0) (w tab-width) c)
19545 (catch 'exit
19546 (while (< (setq n (1+ n)) (length s))
19547 (setq c (aref s n))
19548 (cond ((= c ?\ ) (setq i (1+ i)))
19549 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
19550 (t (throw 'exit t)))))
19553 (defun org-remove-tabs (s &optional width)
19554 "Replace tabulators in S with spaces.
19555 Assumes that s is a single line, starting in column 0."
19556 (setq width (or width tab-width))
19557 (while (string-match "\t" s)
19558 (setq s (replace-match
19559 (make-string
19560 (- (* width (/ (+ (match-beginning 0) width) width))
19561 (match-beginning 0)) ?\ )
19562 t t s)))
19565 (defun org-fix-indentation (line ind)
19566 "Fix indentation in LINE.
19567 IND is a cons cell with target and minimum indentation.
19568 If the current indentation in LINE is smaller than the minimum,
19569 leave it alone. If it is larger than ind, set it to the target."
19570 (let* ((l (org-remove-tabs line))
19571 (i (org-get-indentation l))
19572 (i1 (car ind)) (i2 (cdr ind)))
19573 (if (>= i i2) (setq l (substring line i2)))
19574 (if (> i1 0)
19575 (concat (make-string i1 ?\ ) l)
19576 l)))
19578 (defun org-remove-indentation (code &optional n)
19579 "Remove the maximum common indentation from the lines in CODE.
19580 N may optionally be the number of spaces to remove."
19581 (with-temp-buffer
19582 (insert code)
19583 (org-do-remove-indentation n)
19584 (buffer-string)))
19586 (defun org-do-remove-indentation (&optional n)
19587 "Remove the maximum common indentation from the buffer."
19588 (untabify (point-min) (point-max))
19589 (let ((min 10000) re)
19590 (if n
19591 (setq min n)
19592 (goto-char (point-min))
19593 (while (re-search-forward "^ *[^ \n]" nil t)
19594 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
19595 (unless (or (= min 0) (= min 10000))
19596 (setq re (format "^ \\{%d\\}" min))
19597 (goto-char (point-min))
19598 (while (re-search-forward re nil t)
19599 (replace-match "")
19600 (end-of-line 1))
19601 min)))
19603 (defun org-fill-template (template alist)
19604 "Find each %key of ALIST in TEMPLATE and replace it."
19605 (let ((case-fold-search nil)
19606 entry key value)
19607 (setq alist (sort (copy-sequence alist)
19608 (lambda (a b) (< (length (car a)) (length (car b))))))
19609 (while (setq entry (pop alist))
19610 (setq template
19611 (replace-regexp-in-string
19612 (concat "%" (regexp-quote (car entry)))
19613 (cdr entry) template t t)))
19614 template))
19616 (defun org-base-buffer (buffer)
19617 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
19618 (if (not buffer)
19619 buffer
19620 (or (buffer-base-buffer buffer)
19621 buffer)))
19623 (defun org-trim (s)
19624 "Remove whitespace at beginning and end of string."
19625 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
19626 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
19629 (defun org-wrap (string &optional width lines)
19630 "Wrap string to either a number of lines, or a width in characters.
19631 If WIDTH is non-nil, the string is wrapped to that width, however many lines
19632 that costs. If there is a word longer than WIDTH, the text is actually
19633 wrapped to the length of that word.
19634 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
19635 many lines, whatever width that takes.
19636 The return value is a list of lines, without newlines at the end."
19637 (let* ((words (org-split-string string "[ \t\n]+"))
19638 (maxword (apply 'max (mapcar 'org-string-width words)))
19639 w ll)
19640 (cond (width
19641 (org-do-wrap words (max maxword width)))
19642 (lines
19643 (setq w maxword)
19644 (setq ll (org-do-wrap words maxword))
19645 (if (<= (length ll) lines)
19647 (setq ll words)
19648 (while (> (length ll) lines)
19649 (setq w (1+ w))
19650 (setq ll (org-do-wrap words w)))
19651 ll))
19652 (t (error "Cannot wrap this")))))
19654 (defun org-do-wrap (words width)
19655 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
19656 (let (lines line)
19657 (while words
19658 (setq line (pop words))
19659 (while (and words (< (+ (length line) (length (car words))) width))
19660 (setq line (concat line " " (pop words))))
19661 (setq lines (push line lines)))
19662 (nreverse lines)))
19664 (defun org-split-string (string &optional separators)
19665 "Splits STRING into substrings at SEPARATORS.
19666 No empty strings are returned if there are matches at the beginning
19667 and end of string."
19668 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
19669 (start 0)
19670 notfirst
19671 (list nil))
19672 (while (and (string-match rexp string
19673 (if (and notfirst
19674 (= start (match-beginning 0))
19675 (< start (length string)))
19676 (1+ start) start))
19677 (< (match-beginning 0) (length string)))
19678 (setq notfirst t)
19679 (or (eq (match-beginning 0) 0)
19680 (and (eq (match-beginning 0) (match-end 0))
19681 (eq (match-beginning 0) start))
19682 (setq list
19683 (cons (substring string start (match-beginning 0))
19684 list)))
19685 (setq start (match-end 0)))
19686 (or (eq start (length string))
19687 (setq list
19688 (cons (substring string start)
19689 list)))
19690 (nreverse list)))
19692 (defun org-quote-vert (s)
19693 "Replace \"|\" with \"\\vert\"."
19694 (while (string-match "|" s)
19695 (setq s (replace-match "\\vert" t t s)))
19698 (defun org-uuidgen-p (s)
19699 "Is S an ID created by UUIDGEN?"
19700 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
19702 (defun org-in-src-block-p nil
19703 "Whether point is in a code source block."
19704 (let (ov)
19705 (when (setq ov (overlays-at (point)))
19706 (memq 'org-block-background
19707 (overlay-properties
19708 (car ov))))))
19710 (defun org-context ()
19711 "Return a list of contexts of the current cursor position.
19712 If several contexts apply, all are returned.
19713 Each context entry is a list with a symbol naming the context, and
19714 two positions indicating start and end of the context. Possible
19715 contexts are:
19717 :headline anywhere in a headline
19718 :headline-stars on the leading stars in a headline
19719 :todo-keyword on a TODO keyword (including DONE) in a headline
19720 :tags on the TAGS in a headline
19721 :priority on the priority cookie in a headline
19722 :item on the first line of a plain list item
19723 :item-bullet on the bullet/number of a plain list item
19724 :checkbox on the checkbox in a plain list item
19725 :table in an org-mode table
19726 :table-special on a special filed in a table
19727 :table-table in a table.el table
19728 :clocktable in a clocktable
19729 :src-block in a source block
19730 :link on a hyperlink
19731 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
19732 :target on a <<target>>
19733 :radio-target on a <<<radio-target>>>
19734 :latex-fragment on a LaTeX fragment
19735 :latex-preview on a LaTeX fragment with overlaid preview image
19737 This function expects the position to be visible because it uses font-lock
19738 faces as a help to recognize the following contexts: :table-special, :link,
19739 and :keyword."
19740 (let* ((f (get-text-property (point) 'face))
19741 (faces (if (listp f) f (list f)))
19742 (case-fold-search t)
19743 (p (point)) clist o)
19744 ;; First the large context
19745 (cond
19746 ((org-at-heading-p t)
19747 (push (list :headline (point-at-bol) (point-at-eol)) clist)
19748 (when (progn
19749 (beginning-of-line 1)
19750 (looking-at org-todo-line-tags-regexp))
19751 (push (org-point-in-group p 1 :headline-stars) clist)
19752 (push (org-point-in-group p 2 :todo-keyword) clist)
19753 (push (org-point-in-group p 4 :tags) clist))
19754 (goto-char p)
19755 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
19756 (if (looking-at "\\[#[A-Z0-9]\\]")
19757 (push (org-point-in-group p 0 :priority) clist)))
19759 ((org-at-item-p)
19760 (push (org-point-in-group p 2 :item-bullet) clist)
19761 (push (list :item (point-at-bol)
19762 (save-excursion (org-end-of-item) (point)))
19763 clist)
19764 (and (org-at-item-checkbox-p)
19765 (push (org-point-in-group p 0 :checkbox) clist)))
19767 ((org-at-table-p)
19768 (push (list :table (org-table-begin) (org-table-end)) clist)
19769 (if (memq 'org-formula faces)
19770 (push (list :table-special
19771 (previous-single-property-change p 'face)
19772 (next-single-property-change p 'face)) clist)))
19773 ((org-at-table-p 'any)
19774 (push (list :table-table) clist)))
19775 (goto-char p)
19777 ;; New the "medium" contexts: clocktables, source blocks
19778 (cond ((org-in-clocktable-p)
19779 (push (list :clocktable
19780 (and (or (looking-at "#\\+BEGIN: clocktable")
19781 (search-backward "#+BEGIN: clocktable" nil t))
19782 (match-beginning 0))
19783 (and (re-search-forward "#\\+END:?" nil t)
19784 (match-end 0))) clist))
19785 ((org-in-src-block-p)
19786 (push (list :src-block
19787 (and (or (looking-at "#\\+BEGIN_SRC")
19788 (search-backward "#+BEGIN_SRC" nil t))
19789 (match-beginning 0))
19790 (and (search-forward "#+END_SRC" nil t)
19791 (match-beginning 0))) clist)))
19792 (goto-char p)
19794 ;; Now the small context
19795 (cond
19796 ((org-at-timestamp-p)
19797 (push (org-point-in-group p 0 :timestamp) clist))
19798 ((memq 'org-link faces)
19799 (push (list :link
19800 (previous-single-property-change p 'face)
19801 (next-single-property-change p 'face)) clist))
19802 ((memq 'org-special-keyword faces)
19803 (push (list :keyword
19804 (previous-single-property-change p 'face)
19805 (next-single-property-change p 'face)) clist))
19806 ((org-at-target-p)
19807 (push (org-point-in-group p 0 :target) clist)
19808 (goto-char (1- (match-beginning 0)))
19809 (if (looking-at org-radio-target-regexp)
19810 (push (org-point-in-group p 0 :radio-target) clist))
19811 (goto-char p))
19812 ((setq o (car (delq nil
19813 (mapcar
19814 (lambda (x)
19815 (if (memq x org-latex-fragment-image-overlays) x))
19816 (overlays-at (point))))))
19817 (push (list :latex-fragment
19818 (overlay-start o) (overlay-end o)) clist)
19819 (push (list :latex-preview
19820 (overlay-start o) (overlay-end o)) clist))
19821 ((org-inside-LaTeX-fragment-p)
19822 ;; FIXME: positions wrong.
19823 (push (list :latex-fragment (point) (point)) clist)))
19825 (setq clist (nreverse (delq nil clist)))
19826 clist))
19828 ;; FIXME: Compare with at-regexp-p Do we need both?
19829 (defun org-in-regexp (re &optional nlines visually)
19830 "Check if point is inside a match of regexp.
19831 Normally only the current line is checked, but you can include NLINES extra
19832 lines both before and after point into the search.
19833 If VISUALLY is set, require that the cursor is not after the match but
19834 really on, so that the block visually is on the match."
19835 (catch 'exit
19836 (let ((pos (point))
19837 (eol (point-at-eol (+ 1 (or nlines 0))))
19838 (inc (if visually 1 0)))
19839 (save-excursion
19840 (beginning-of-line (- 1 (or nlines 0)))
19841 (while (re-search-forward re eol t)
19842 (if (and (<= (match-beginning 0) pos)
19843 (>= (+ inc (match-end 0)) pos))
19844 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
19846 (defun org-at-regexp-p (regexp)
19847 "Is point inside a match of REGEXP in the current line?"
19848 (catch 'exit
19849 (save-excursion
19850 (let ((pos (point)) (end (point-at-eol)))
19851 (beginning-of-line 1)
19852 (while (re-search-forward regexp end t)
19853 (if (and (<= (match-beginning 0) pos)
19854 (>= (match-end 0) pos))
19855 (throw 'exit t)))
19856 nil))))
19858 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
19859 "Non-nil when point is between matches of START-RE and END-RE.
19861 Also return a non-nil value when point is on one of the matches.
19863 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
19864 buffer positions. Default values are the positions of headlines
19865 surrounding the point.
19867 The functions returns a cons cell whose car (resp. cdr) is the
19868 position before START-RE (resp. after END-RE)."
19869 (save-match-data
19870 (let ((pos (point))
19871 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
19872 (limit-down (or lim-down (save-excursion (outline-next-heading))))
19873 beg end)
19874 (save-excursion
19875 ;; Point is on a block when on START-RE or if START-RE can be
19876 ;; found before it...
19877 (and (or (org-at-regexp-p start-re)
19878 (re-search-backward start-re limit-up t))
19879 (setq beg (match-beginning 0))
19880 ;; ... and END-RE after it...
19881 (goto-char (match-end 0))
19882 (re-search-forward end-re limit-down t)
19883 (> (setq end (match-end 0)) pos)
19884 ;; ... without another START-RE in-between.
19885 (goto-char (match-beginning 0))
19886 (not (re-search-backward start-re (1+ beg) t))
19887 ;; Return value.
19888 (cons beg end))))))
19890 (defun org-in-block-p (names)
19891 "Non-nil when point belongs to a block whose name belongs to NAMES.
19893 NAMES is a list of strings containing names of blocks.
19895 Return first block name matched, or nil. Beware that in case of
19896 nested blocks, the returned name may not belong to the closest
19897 block from point."
19898 (save-match-data
19899 (catch 'exit
19900 (let ((case-fold-search t)
19901 (lim-up (save-excursion (outline-previous-heading)))
19902 (lim-down (save-excursion (outline-next-heading))))
19903 (mapc (lambda (name)
19904 (let ((n (regexp-quote name)))
19905 (when (org-between-regexps-p
19906 (concat "^[ \t]*#\\+begin_" n)
19907 (concat "^[ \t]*#\\+end_" n)
19908 lim-up lim-down)
19909 (throw 'exit n))))
19910 names))
19911 nil)))
19913 (defun org-occur-in-agenda-files (regexp &optional nlines)
19914 "Call `multi-occur' with buffers for all agenda files."
19915 (interactive "sOrg-files matching: \np")
19916 (let* ((files (org-agenda-files))
19917 (tnames (mapcar 'file-truename files))
19918 (extra org-agenda-text-search-extra-files)
19920 (when (eq (car extra) 'agenda-archives)
19921 (setq extra (cdr extra))
19922 (setq files (org-add-archive-files files)))
19923 (while (setq f (pop extra))
19924 (unless (member (file-truename f) tnames)
19925 (add-to-list 'files f 'append)
19926 (add-to-list 'tnames (file-truename f) 'append)))
19927 (multi-occur
19928 (mapcar (lambda (x)
19929 (with-current-buffer
19930 (or (get-file-buffer x) (find-file-noselect x))
19931 (widen)
19932 (current-buffer)))
19933 files)
19934 regexp)))
19936 (if (boundp 'occur-mode-find-occurrence-hook)
19937 ;; Emacs 23
19938 (add-hook 'occur-mode-find-occurrence-hook
19939 (lambda ()
19940 (when (eq major-mode 'org-mode)
19941 (org-reveal))))
19942 ;; Emacs 22
19943 (defadvice occur-mode-goto-occurrence
19944 (after org-occur-reveal activate)
19945 (and (eq major-mode 'org-mode) (org-reveal)))
19946 (defadvice occur-mode-goto-occurrence-other-window
19947 (after org-occur-reveal activate)
19948 (and (eq major-mode 'org-mode) (org-reveal)))
19949 (defadvice occur-mode-display-occurrence
19950 (after org-occur-reveal activate)
19951 (when (eq major-mode 'org-mode)
19952 (let ((pos (occur-mode-find-occurrence)))
19953 (with-current-buffer (marker-buffer pos)
19954 (save-excursion
19955 (goto-char pos)
19956 (org-reveal)))))))
19958 (defun org-occur-link-in-agenda-files ()
19959 "Create a link and search for it in the agendas.
19960 The link is not stored in `org-stored-links', it is just created
19961 for the search purpose."
19962 (interactive)
19963 (let ((link (condition-case nil
19964 (org-store-link nil)
19965 (error "Unable to create a link to here"))))
19966 (org-occur-in-agenda-files (regexp-quote link))))
19968 (defun org-uniquify (list)
19969 "Remove duplicate elements from LIST."
19970 (let (res)
19971 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
19972 res))
19974 (defun org-delete-all (elts list)
19975 "Remove all elements in ELTS from LIST."
19976 (while elts
19977 (setq list (delete (pop elts) list)))
19978 list)
19980 (defun org-count (cl-item cl-seq)
19981 "Count the number of occurrences of ITEM in SEQ.
19982 Taken from `count' in cl-seq.el with all keyword arguments removed."
19983 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
19984 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
19985 (while (< cl-start cl-end)
19986 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
19987 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
19988 (setq cl-start (1+ cl-start)))
19989 cl-count))
19991 (defun org-remove-if (predicate seq)
19992 "Remove everything from SEQ that fulfills PREDICATE."
19993 (let (res e)
19994 (while seq
19995 (setq e (pop seq))
19996 (if (not (funcall predicate e)) (push e res)))
19997 (nreverse res)))
19999 (defun org-remove-if-not (predicate seq)
20000 "Remove everything from SEQ that does not fulfill PREDICATE."
20001 (let (res e)
20002 (while seq
20003 (setq e (pop seq))
20004 (if (funcall predicate e) (push e res)))
20005 (nreverse res)))
20007 (defun org-reduce (cl-func cl-seq &rest cl-keys)
20008 "Reduce two-argument FUNCTION across SEQ.
20009 Taken from `reduce' in cl-seq.el with all keyword arguments but
20010 \":initial-value\" removed."
20011 (let ((cl-accum (cond ((memq :initial-value cl-keys)
20012 (cadr (memq :initial-value cl-keys)))
20013 (cl-seq (pop cl-seq))
20014 (t (funcall cl-func)))))
20015 (while cl-seq
20016 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
20017 cl-accum))
20019 (defun org-back-over-empty-lines ()
20020 "Move backwards over whitespace, to the beginning of the first empty line.
20021 Returns the number of empty lines passed."
20022 (let ((pos (point)))
20023 (if (cdr (assoc 'heading org-blank-before-new-entry))
20024 (skip-chars-backward " \t\n\r")
20025 (unless (eobp)
20026 (forward-line -1)))
20027 (beginning-of-line 2)
20028 (goto-char (min (point) pos))
20029 (count-lines (point) pos)))
20031 (defun org-skip-whitespace ()
20032 (skip-chars-forward " \t\n\r"))
20034 (defun org-point-in-group (point group &optional context)
20035 "Check if POINT is in match-group GROUP.
20036 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
20037 match. If the match group does not exist or point is not inside it,
20038 return nil."
20039 (and (match-beginning group)
20040 (>= point (match-beginning group))
20041 (<= point (match-end group))
20042 (if context
20043 (list context (match-beginning group) (match-end group))
20044 t)))
20046 (defun org-switch-to-buffer-other-window (&rest args)
20047 "Switch to buffer in a second window on the current frame.
20048 In particular, do not allow pop-up frames.
20049 Returns the newly created buffer."
20050 (let (pop-up-frames special-display-buffer-names special-display-regexps
20051 special-display-function)
20052 (apply 'switch-to-buffer-other-window args)))
20054 (defun org-combine-plists (&rest plists)
20055 "Create a single property list from all plists in PLISTS.
20056 The process starts by copying the first list, and then setting properties
20057 from the other lists. Settings in the last list are the most significant
20058 ones and overrule settings in the other lists."
20059 (let ((rtn (copy-sequence (pop plists)))
20060 p v ls)
20061 (while plists
20062 (setq ls (pop plists))
20063 (while ls
20064 (setq p (pop ls) v (pop ls))
20065 (setq rtn (plist-put rtn p v))))
20066 rtn))
20068 (defun org-move-line-down (arg)
20069 "Move the current line down. With prefix argument, move it past ARG lines."
20070 (interactive "p")
20071 (let ((col (current-column))
20072 beg end pos)
20073 (beginning-of-line 1) (setq beg (point))
20074 (beginning-of-line 2) (setq end (point))
20075 (beginning-of-line (+ 1 arg))
20076 (setq pos (move-marker (make-marker) (point)))
20077 (insert (delete-and-extract-region beg end))
20078 (goto-char pos)
20079 (org-move-to-column col)))
20081 (defun org-move-line-up (arg)
20082 "Move the current line up. With prefix argument, move it past ARG lines."
20083 (interactive "p")
20084 (let ((col (current-column))
20085 beg end pos)
20086 (beginning-of-line 1) (setq beg (point))
20087 (beginning-of-line 2) (setq end (point))
20088 (beginning-of-line (- arg))
20089 (setq pos (move-marker (make-marker) (point)))
20090 (insert (delete-and-extract-region beg end))
20091 (goto-char pos)
20092 (org-move-to-column col)))
20094 (defun org-replace-escapes (string table)
20095 "Replace %-escapes in STRING with values in TABLE.
20096 TABLE is an association list with keys like \"%a\" and string values.
20097 The sequences in STRING may contain normal field width and padding information,
20098 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
20099 so values can contain further %-escapes if they are define later in TABLE."
20100 (let ((tbl (copy-alist table))
20101 (case-fold-search nil)
20102 (pchg 0)
20103 e re rpl)
20104 (while (setq e (pop tbl))
20105 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
20106 (when (and (cdr e) (string-match re (cdr e)))
20107 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
20108 (safe "SREF"))
20109 (add-text-properties 0 3 (list 'sref sref) safe)
20110 (setcdr e (replace-match safe t t (cdr e)))))
20111 (while (string-match re string)
20112 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
20113 (cdr e)))
20114 (setq string (replace-match rpl t t string))))
20115 (while (setq pchg (next-property-change pchg string))
20116 (let ((sref (get-text-property pchg 'sref string)))
20117 (when (and sref (string-match "SREF" string pchg))
20118 (setq string (replace-match sref t t string)))))
20119 string))
20121 (defun org-sublist (list start end)
20122 "Return a section of LIST, from START to END.
20123 Counting starts at 1."
20124 (let (rtn (c start))
20125 (setq list (nthcdr (1- start) list))
20126 (while (and list (<= c end))
20127 (push (pop list) rtn)
20128 (setq c (1+ c)))
20129 (nreverse rtn)))
20131 (defun org-find-base-buffer-visiting (file)
20132 "Like `find-buffer-visiting' but always return the base buffer and
20133 not an indirect buffer."
20134 (let ((buf (or (get-file-buffer file)
20135 (find-buffer-visiting file))))
20136 (if buf
20137 (or (buffer-base-buffer buf) buf)
20138 nil)))
20140 (defun org-image-file-name-regexp (&optional extensions)
20141 "Return regexp matching the file names of images.
20142 If EXTENSIONS is given, only match these."
20143 (if (and (not extensions) (fboundp 'image-file-name-regexp))
20144 (image-file-name-regexp)
20145 (let ((image-file-name-extensions
20146 (or extensions
20147 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
20148 "xbm" "xpm" "pbm" "pgm" "ppm"))))
20149 (concat "\\."
20150 (regexp-opt (nconc (mapcar 'upcase
20151 image-file-name-extensions)
20152 image-file-name-extensions)
20154 "\\'"))))
20156 (defun org-file-image-p (file &optional extensions)
20157 "Return non-nil if FILE is an image."
20158 (save-match-data
20159 (string-match (org-image-file-name-regexp extensions) file)))
20161 (defun org-get-cursor-date ()
20162 "Return the date at cursor in as a time.
20163 This works in the calendar and in the agenda, anywhere else it just
20164 returns the current time."
20165 (let (date day defd)
20166 (cond
20167 ((eq major-mode 'calendar-mode)
20168 (setq date (calendar-cursor-to-date)
20169 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
20170 ((eq major-mode 'org-agenda-mode)
20171 (setq day (get-text-property (point) 'day))
20172 (if day
20173 (setq date (calendar-gregorian-from-absolute day)
20174 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
20175 (nth 2 date))))))
20176 (or defd (current-time))))
20178 (defvar org-agenda-action-marker (make-marker)
20179 "Marker pointing to the entry for the next agenda action.")
20181 (defun org-mark-entry-for-agenda-action ()
20182 "Mark the current entry as target of an agenda action.
20183 Agenda actions are actions executed from the agenda with the key `k',
20184 which make use of the date at the cursor."
20185 (interactive)
20186 (move-marker org-agenda-action-marker
20187 (save-excursion (org-back-to-heading t) (point))
20188 (current-buffer))
20189 (message
20190 "Entry marked for action; press `k' at desired date in agenda or calendar"))
20192 (defun org-mark-subtree ()
20193 "Mark the current subtree.
20194 This puts point at the start of the current subtree, and mark at the end.
20196 If point is in an inline task, mark that task instead."
20197 (interactive)
20198 (let ((inline-task-p
20199 (and (featurep 'org-inlinetask)
20200 (org-inlinetask-in-task-p)))
20201 (beg))
20202 ;; Get beginning of subtree
20203 (cond
20204 (inline-task-p (org-inlinetask-goto-beginning))
20205 ((org-at-heading-p) (beginning-of-line))
20206 (t (org-with-limited-levels (outline-previous-visible-heading 1))))
20207 (setq beg (point))
20208 ;; Get end of it
20209 (if inline-task-p
20210 (org-inlinetask-goto-end)
20211 (org-end-of-subtree))
20212 ;; Mark zone
20213 (push-mark (point) nil t)
20214 (goto-char beg)))
20216 ;;; Paragraph filling stuff.
20217 ;; We want this to be just right, so use the full arsenal.
20219 (defun org-indent-line-function ()
20220 "Indent line depending on context."
20221 (interactive)
20222 (let* ((pos (point))
20223 (itemp (org-at-item-p))
20224 (case-fold-search t)
20225 (org-drawer-regexp (or org-drawer-regexp "\000"))
20226 (inline-task-p (and (featurep 'org-inlinetask)
20227 (org-inlinetask-in-task-p)))
20228 (inline-re (and inline-task-p
20229 (org-inlinetask-outline-regexp)))
20230 column)
20231 (beginning-of-line 1)
20232 (cond
20233 ;; Comments
20234 ((looking-at "# ") (setq column 0))
20235 ;; Headings
20236 ((looking-at org-outline-regexp) (setq column 0))
20237 ;; Included files
20238 ((looking-at "#\\+include:") (setq column 0))
20239 ;; Footnote definition
20240 ((looking-at org-footnote-definition-re) (setq column 0))
20241 ;; Literal examples
20242 ((looking-at "[ \t]*:\\( \\|$\\)")
20243 (setq column (org-get-indentation))) ; do nothing
20244 ;; Lists
20245 ((ignore-errors (goto-char (org-in-item-p)))
20246 (setq column (if itemp
20247 (org-get-indentation)
20248 (org-list-item-body-column (point))))
20249 (goto-char pos))
20250 ;; Drawers
20251 ((and (looking-at "[ \t]*:END:")
20252 (save-excursion (re-search-backward org-drawer-regexp nil t)))
20253 (save-excursion
20254 (goto-char (1- (match-beginning 1)))
20255 (setq column (current-column))))
20256 ;; Special blocks
20257 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
20258 (save-excursion
20259 (re-search-backward
20260 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
20261 (setq column (org-get-indentation (match-string 0))))
20262 ((and (not (looking-at "[ \t]*#\\+begin_"))
20263 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
20264 (save-excursion
20265 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
20266 (setq column
20267 (cond ((equal (downcase (match-string 1)) "src")
20268 ;; src blocks: let `org-edit-src-exit' handle them
20269 (org-get-indentation))
20270 ((equal (downcase (match-string 1)) "example")
20271 (max (org-get-indentation)
20272 (org-get-indentation (match-string 0))))
20274 (org-get-indentation (match-string 0))))))
20275 ;; This line has nothing special, look at the previous relevant
20276 ;; line to compute indentation
20278 (beginning-of-line 0)
20279 (while (and (not (bobp))
20280 (not (looking-at org-drawer-regexp))
20281 ;; When point started in an inline task, do not move
20282 ;; above task starting line.
20283 (not (and inline-task-p (looking-at inline-re)))
20284 ;; Skip drawers, blocks, empty lines, verbatim,
20285 ;; comments, tables, footnotes definitions, lists,
20286 ;; inline tasks.
20287 (or (and (looking-at "[ \t]*:END:")
20288 (re-search-backward org-drawer-regexp nil t))
20289 (and (looking-at "[ \t]*#\\+end_")
20290 (re-search-backward "[ \t]*#\\+begin_"nil t))
20291 (looking-at "[ \t]*[\n:#|]")
20292 (looking-at org-footnote-definition-re)
20293 (and (ignore-errors (goto-char (org-in-item-p)))
20294 (goto-char
20295 (org-list-get-top-point (org-list-struct))))
20296 (and (not inline-task-p)
20297 (featurep 'org-inlinetask)
20298 (org-inlinetask-in-task-p)
20299 (or (org-inlinetask-goto-beginning) t))))
20300 (beginning-of-line 0))
20301 (cond
20302 ;; There was an heading above.
20303 ((looking-at "\\*+[ \t]+")
20304 (if (not org-adapt-indentation)
20305 (setq column 0)
20306 (goto-char (match-end 0))
20307 (setq column (current-column))))
20308 ;; A drawer had started and is unfinished
20309 ((looking-at org-drawer-regexp)
20310 (goto-char (1- (match-beginning 1)))
20311 (setq column (current-column)))
20312 ;; Else, nothing noticeable found: get indentation and go on.
20313 (t (setq column (org-get-indentation))))))
20314 ;; Now apply indentation and move cursor accordingly
20315 (goto-char pos)
20316 (if (<= (current-column) (current-indentation))
20317 (org-indent-line-to column)
20318 (save-excursion (org-indent-line-to column)))
20319 ;; Special polishing for properties, see `org-property-format'
20320 (setq column (current-column))
20321 (beginning-of-line 1)
20322 (if (looking-at
20323 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
20324 (replace-match (concat (match-string 1)
20325 (format org-property-format
20326 (match-string 2) (match-string 3)))
20327 t t))
20328 (org-move-to-column column)))
20330 (defun org-indent-drawer ()
20331 "Indent the drawer at point."
20332 (interactive)
20333 (let ((p (point))
20334 (e (and (save-excursion (re-search-forward ":END:" nil t))
20335 (match-end 0)))
20336 (folded
20337 (save-excursion
20338 (end-of-line)
20339 (when (overlays-at (point))
20340 (member 'invisible (overlay-properties
20341 (car (overlays-at (point)))))))))
20342 (when folded (org-cycle))
20343 (indent-for-tab-command)
20344 (while (and (move-beginning-of-line 2) (< (point) e))
20345 (indent-for-tab-command))
20346 (goto-char p)
20347 (when folded (org-cycle)))
20348 (message "Drawer at point indented"))
20350 (defun org-indent-block ()
20351 "Indent the block at point."
20352 (interactive)
20353 (let ((p (point))
20354 (case-fold-search t)
20355 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
20356 (match-end 0)))
20357 (folded
20358 (save-excursion
20359 (end-of-line)
20360 (when (overlays-at (point))
20361 (member 'invisible (overlay-properties
20362 (car (overlays-at (point)))))))))
20363 (when folded (org-cycle))
20364 (indent-for-tab-command)
20365 (while (and (move-beginning-of-line 2) (< (point) e))
20366 (indent-for-tab-command))
20367 (goto-char p)
20368 (when folded (org-cycle)))
20369 (message "Block at point indented"))
20371 (defvar org-adaptive-fill-regexp-backup adaptive-fill-regexp
20372 "Variable to store copy of `adaptive-fill-regexp'.
20373 Since `adaptive-fill-regexp' is set to never match, we need to
20374 store a backup of its value before entering `org-mode' so that
20375 the functionality can be provided as a fall-back.")
20377 (defun org-set-autofill-regexps ()
20378 (interactive)
20379 ;; In the paragraph separator we include headlines, because filling
20380 ;; text in a line directly attached to a headline would otherwise
20381 ;; fill the headline as well.
20382 (org-set-local 'comment-start-skip "^#+[ \t]*")
20383 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|#]")
20384 ;; The paragraph starter includes hand-formatted lists.
20385 (org-set-local
20386 'paragraph-start
20387 (concat
20388 "\f" "\\|"
20389 "[ ]*$" "\\|"
20390 org-outline-regexp "\\|"
20391 "[ \t]*#" "\\|"
20392 (org-item-re) "\\|"
20393 "[ \t]*[:|]" "\\|"
20394 "\\$\\$" "\\|"
20395 "\\\\\\(begin\\|end\\|[][]\\)"))
20396 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
20397 ;; But only if the user has not turned off tables or fixed-width regions
20398 (org-set-local
20399 'auto-fill-inhibit-regexp
20400 (concat org-outline-regexp
20401 "\\|#\\+"
20402 "\\|[ \t]*" org-keyword-time-regexp
20403 (if (or org-enable-table-editor org-enable-fixed-width-editor)
20404 (concat
20405 "\\|[ \t]*["
20406 (if org-enable-table-editor "|" "")
20407 (if org-enable-fixed-width-editor ":" "")
20408 "]"))))
20409 ;; We use our own fill-paragraph function, to make sure that tables
20410 ;; and fixed-width regions are not wrapped. That function will pass
20411 ;; through to `fill-paragraph' when appropriate.
20412 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
20413 ;; Prevent auto-fill from inserting unwanted new items.
20414 (if (boundp 'fill-nobreak-predicate)
20415 (org-set-local
20416 'fill-nobreak-predicate
20417 (org-uniquify
20418 (append fill-nobreak-predicate
20419 '(org-fill-item-nobreak-p org-fill-line-break-nobreak-p)))))
20420 ;; Adaptive filling: To get full control, first make sure that
20421 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
20422 (unless (local-variable-p 'adaptive-fill-regexp (current-buffer))
20423 (org-set-local 'org-adaptive-fill-regexp-backup
20424 adaptive-fill-regexp))
20425 (org-set-local 'adaptive-fill-regexp "\000")
20426 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
20427 (org-set-local 'adaptive-fill-function
20428 'org-adaptive-fill-function)
20429 (org-set-local
20430 'align-mode-rules-list
20431 '((org-in-buffer-settings
20432 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
20433 (modes . '(org-mode))))))
20435 (defun org-fill-item-nobreak-p ()
20436 "Non-nil when a line break at point would insert a new item."
20437 (and (looking-at (org-item-re)) (org-list-in-valid-context-p)))
20439 (defun org-fill-line-break-nobreak-p ()
20440 "Non-nil when a line break at point would create an Org line break."
20441 (save-excursion
20442 (skip-chars-backward "[ \t]")
20443 (skip-chars-backward "\\\\")
20444 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
20446 (defun org-fill-paragraph (&optional justify)
20447 "Re-align a table, pass through to fill-paragraph if no table."
20448 (let ((table-p (org-at-table-p))
20449 (table.el-p (org-at-table.el-p))
20450 (itemp (org-in-item-p)))
20451 (cond ((and (equal (char-after (point-at-bol)) ?*)
20452 (save-excursion (goto-char (point-at-bol))
20453 (looking-at org-outline-regexp)))
20454 t) ; skip headlines
20455 (table.el-p t) ; skip table.el tables
20456 (table-p (org-table-align) t) ; align Org tables
20457 (itemp ; align text in items
20458 (let* ((struct (save-excursion (goto-char itemp)
20459 (org-list-struct)))
20460 (parents (org-list-parents-alist struct))
20461 (children (org-list-get-children itemp struct parents))
20462 beg end prev next prefix)
20463 ;; Determine in which part of item point is: before
20464 ;; first child, after last child, between two
20465 ;; sub-lists, or simply in item if there's no child.
20466 (cond
20467 ((not children)
20468 (setq prefix (make-string (org-list-item-body-column itemp) ?\ )
20469 beg itemp
20470 end (org-list-get-item-end itemp struct)))
20471 ((< (point) (setq next (car children)))
20472 (setq prefix (make-string (org-list-item-body-column itemp) ?\ )
20473 beg itemp
20474 end next))
20475 ((> (point) (setq prev (car (last children))))
20476 (setq beg (org-list-get-item-end prev struct)
20477 end (org-list-get-item-end itemp struct)
20478 prefix (save-excursion
20479 (goto-char beg)
20480 (skip-chars-forward " \t")
20481 (make-string (current-column) ?\ ))))
20482 (t (catch 'exit
20483 (while (setq next (pop children))
20484 (if (> (point) next)
20485 (setq prev next)
20486 (setq beg (org-list-get-item-end prev struct)
20487 end next
20488 prefix (save-excursion
20489 (goto-char beg)
20490 (skip-chars-forward " \t")
20491 (make-string (current-column) ?\ )))
20492 (throw 'exit nil))))))
20493 ;; Use `fill-paragraph' with buffer narrowed to item
20494 ;; without any child, and with our computed PREFIX.
20495 (flet ((fill-context-prefix (from to &optional flr) prefix))
20496 (save-restriction
20497 (narrow-to-region beg end)
20498 (save-excursion (fill-paragraph justify)))) t))
20499 ;; Special case where point is not in a list but is on
20500 ;; a paragraph adjacent to a list: make sure this paragraph
20501 ;; doesn't get merged with the end of the list by narrowing
20502 ;; buffer first.
20503 ((save-excursion (forward-paragraph -1)
20504 (setq itemp (org-in-item-p)))
20505 (let ((struct (save-excursion (goto-char itemp)
20506 (org-list-struct))))
20507 (save-restriction
20508 (narrow-to-region (org-list-get-bottom-point struct)
20509 (save-excursion (forward-paragraph 1)
20510 (point)))
20511 (fill-paragraph justify) t)))
20512 ;; Don't fill schedule/deadline line before a paragraph
20513 ((save-excursion (forward-paragraph -1)
20514 (or (looking-at (concat "^[^\n]*" org-scheduled-regexp ".*$"))
20515 (looking-at (concat "^[^\n]*" org-deadline-regexp ".*$"))))
20516 (save-restriction
20517 (narrow-to-region (1+ (match-end 0))
20518 (save-excursion (forward-paragraph 1) (point)))
20519 (fill-paragraph justify) t))
20520 ;; Else simply call `fill-paragraph'.
20521 (t nil))))
20523 ;; For reference, this is the default value of adaptive-fill-regexp
20524 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
20526 (defun org-adaptive-fill-function ()
20527 "Return a fill prefix for org-mode files."
20528 (let (itemp)
20529 (save-excursion
20530 (cond
20531 ;; Comment line
20532 ((looking-at "#[ \t]+")
20533 (match-string-no-properties 0))
20534 ;; Plain list item
20535 ((org-at-item-p)
20536 (make-string (org-list-item-body-column (point-at-bol)) ?\ ))
20537 ;; Point is in a list after `backward-paragraph': original
20538 ;; point wasn't in the list, or filling would have been taken
20539 ;; care of by `org-auto-fill-function', but the list and the
20540 ;; real paragraph are not separated by a blank line. Thus, move
20541 ;; point after the list to go back to real paragraph and
20542 ;; determine fill-prefix.
20543 ((setq itemp (org-in-item-p))
20544 (goto-char itemp)
20545 (let* ((struct (org-list-struct))
20546 (bottom (org-list-get-bottom-point struct)))
20547 (goto-char bottom)
20548 (make-string (org-get-indentation) ?\ )))
20549 ;; Other text
20550 ((looking-at org-adaptive-fill-regexp-backup)
20551 (match-string-no-properties 0))))))
20553 (defun org-auto-fill-function ()
20554 "Auto-fill function."
20555 (let (itemp prefix)
20556 ;; When in a list, compute an appropriate fill-prefix and make
20557 ;; sure it will be used by `do-auto-fill'.
20558 (if (setq itemp (org-in-item-p))
20559 (progn
20560 (setq prefix (make-string (org-list-item-body-column itemp) ?\ ))
20561 (flet ((fill-context-prefix (from to &optional flr) prefix))
20562 (do-auto-fill)))
20563 ;; Else just use `do-auto-fill'.
20564 (do-auto-fill))))
20566 ;;; Other stuff.
20568 (defun org-toggle-fixed-width-section (arg)
20569 "Toggle the fixed-width export.
20570 If there is no active region, the QUOTE keyword at the current headline is
20571 inserted or removed. When present, it causes the text between this headline
20572 and the next to be exported as fixed-width text, and unmodified.
20573 If there is an active region, this command adds or removes a colon as the
20574 first character of this line. If the first character of a line is a colon,
20575 this line is also exported in fixed-width font."
20576 (interactive "P")
20577 (let* ((cc 0)
20578 (regionp (org-region-active-p))
20579 (beg (if regionp (region-beginning) (point)))
20580 (end (if regionp (region-end)))
20581 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
20582 (case-fold-search nil)
20583 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
20584 off)
20585 (if regionp
20586 (save-excursion
20587 (goto-char beg)
20588 (setq cc (current-column))
20589 (beginning-of-line 1)
20590 (setq off (looking-at re))
20591 (while (> nlines 0)
20592 (setq nlines (1- nlines))
20593 (beginning-of-line 1)
20594 (cond
20595 (arg
20596 (org-move-to-column cc t)
20597 (insert ": \n")
20598 (forward-line -1))
20599 ((and off (looking-at re))
20600 (replace-match "" t t nil 1))
20601 ((not off) (org-move-to-column cc t) (insert ": ")))
20602 (forward-line 1)))
20603 (save-excursion
20604 (org-back-to-heading)
20605 (cond
20606 ((looking-at (format org-heading-keyword-regexp-format
20607 org-quote-string))
20608 (goto-char (match-end 1))
20609 (looking-at (concat " +" org-quote-string))
20610 (replace-match "" t t)
20611 (when (eolp) (insert " ")))
20612 ((looking-at org-outline-regexp)
20613 (goto-char (match-end 0))
20614 (insert org-quote-string " ")))))))
20616 (defun org-reftex-citation ()
20617 "Use reftex-citation to insert a citation into the buffer.
20618 This looks for a line like
20620 #+BIBLIOGRAPHY: foo plain option:-d
20622 and derives from it that foo.bib is the bibliography file relevant
20623 for this document. It then installs the necessary environment for RefTeX
20624 to work in this buffer and calls `reftex-citation' to insert a citation
20625 into the buffer.
20627 Export of such citations to both LaTeX and HTML is handled by the contributed
20628 package org-exp-bibtex by Taru Karttunen."
20629 (interactive)
20630 (let ((reftex-docstruct-symbol 'rds)
20631 (reftex-cite-format "\\cite{%l}")
20632 rds bib)
20633 (save-excursion
20634 (save-restriction
20635 (widen)
20636 (let ((case-fold-search t)
20637 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
20638 (if (not (save-excursion
20639 (or (re-search-forward re nil t)
20640 (re-search-backward re nil t))))
20641 (error "No bibliography defined in file")
20642 (setq bib (concat (match-string 1) ".bib")
20643 rds (list (list 'bib bib)))))))
20644 (call-interactively 'reftex-citation)))
20646 ;;;; Functions extending outline functionality
20648 (defun org-beginning-of-line (&optional arg)
20649 "Go to the beginning of the current line. If that is invisible, continue
20650 to a visible line beginning. This makes the function of C-a more intuitive.
20651 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
20652 first attempt, and only move to after the tags when the cursor is already
20653 beyond the end of the headline."
20654 (interactive "P")
20655 (let ((pos (point))
20656 (special (if (consp org-special-ctrl-a/e)
20657 (car org-special-ctrl-a/e)
20658 org-special-ctrl-a/e))
20659 refpos)
20660 (if (org-bound-and-true-p line-move-visual)
20661 (beginning-of-visual-line 1)
20662 (beginning-of-line 1))
20663 (if (and arg (fboundp 'move-beginning-of-line))
20664 (call-interactively 'move-beginning-of-line)
20665 (if (bobp)
20667 (backward-char 1)
20668 (if (org-truely-invisible-p)
20669 (while (and (not (bobp)) (org-truely-invisible-p))
20670 (backward-char 1)
20671 (beginning-of-line 1))
20672 (forward-char 1))))
20673 (when special
20674 (cond
20675 ((and (looking-at org-complex-heading-regexp)
20676 (= (char-after (match-end 1)) ?\ ))
20677 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
20678 (point-at-eol)))
20679 (goto-char
20680 (if (eq special t)
20681 (cond ((> pos refpos) refpos)
20682 ((= pos (point)) refpos)
20683 (t (point)))
20684 (cond ((> pos (point)) (point))
20685 ((not (eq last-command this-command)) (point))
20686 (t refpos)))))
20687 ((org-at-item-p)
20688 ;; Being at an item and not looking at an the item means point
20689 ;; was previously moved to beginning of a visual line, which
20690 ;; doesn't contain the item. Therefore, do nothing special,
20691 ;; just stay here.
20692 (when (looking-at org-list-full-item-re)
20693 ;; Set special position at first white space character after
20694 ;; bullet, and check-box, if any.
20695 (let ((after-bullet
20696 (let ((box (match-end 3)))
20697 (if (not box) (match-end 1)
20698 (let ((after (char-after box)))
20699 (if (and after (= after ? )) (1+ box) box))))))
20700 ;; Special case: Move point to special position when
20701 ;; currently after it or at beginning of line.
20702 (if (eq special t)
20703 (when (or (> pos after-bullet) (= (point) pos))
20704 (goto-char after-bullet))
20705 ;; Reversed case: Move point to special position when
20706 ;; point was already at beginning of line and command is
20707 ;; repeated.
20708 (when (and (= (point) pos) (eq last-command this-command))
20709 (goto-char after-bullet))))))))
20710 (org-no-warnings
20711 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
20713 (defun org-end-of-line (&optional arg)
20714 "Go to the end of the line.
20715 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
20716 first attempt, and only move to after the tags when the cursor is already
20717 beyond the end of the headline."
20718 (interactive "P")
20719 (let ((special (if (consp org-special-ctrl-a/e)
20720 (cdr org-special-ctrl-a/e)
20721 org-special-ctrl-a/e)))
20722 (cond
20723 ((or (not special) arg
20724 (not (or (org-at-heading-p) (org-at-item-p) (org-at-drawer-p))))
20725 (call-interactively
20726 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
20727 ((fboundp 'move-end-of-line) 'move-end-of-line)
20728 (t 'end-of-line))))
20729 ((org-at-heading-p)
20730 (let ((pos (point)))
20731 (beginning-of-line 1)
20732 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
20733 (if (eq special t)
20734 (if (or (< pos (match-beginning 1))
20735 (= pos (match-end 0)))
20736 (goto-char (match-beginning 1))
20737 (goto-char (match-end 0)))
20738 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
20739 (goto-char (match-end 0))
20740 (goto-char (match-beginning 1))))
20741 (call-interactively (if (fboundp 'move-end-of-line)
20742 'move-end-of-line
20743 'end-of-line)))))
20744 ((org-at-drawer-p)
20745 (move-end-of-line 1)
20746 (when (overlays-at (1- (point))) (backward-char 1)))
20747 ;; At an item: Move before any hidden text.
20748 (t (call-interactively
20749 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
20750 ((fboundp 'move-end-of-line) 'move-end-of-line)
20751 (t 'end-of-line)))))
20752 (org-no-warnings
20753 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
20755 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
20756 (define-key org-mode-map "\C-e" 'org-end-of-line)
20758 (defun org-backward-sentence (&optional arg)
20759 "Go to beginning of sentence, or beginning of table field.
20760 This will call `backward-sentence' or `org-table-beginning-of-field',
20761 depending on context."
20762 (interactive "P")
20763 (cond
20764 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
20765 (t (call-interactively 'backward-sentence))))
20767 (defun org-forward-sentence (&optional arg)
20768 "Go to end of sentence, or end of table field.
20769 This will call `forward-sentence' or `org-table-end-of-field',
20770 depending on context."
20771 (interactive "P")
20772 (cond
20773 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
20774 (t (call-interactively 'forward-sentence))))
20776 (define-key org-mode-map "\M-a" 'org-backward-sentence)
20777 (define-key org-mode-map "\M-e" 'org-forward-sentence)
20779 (defun org-kill-line (&optional arg)
20780 "Kill line, to tags or end of line."
20781 (interactive "P")
20782 (cond
20783 ((or (not org-special-ctrl-k)
20784 (bolp)
20785 (not (org-at-heading-p)))
20786 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
20787 org-ctrl-k-protect-subtree)
20788 (if (or (eq org-ctrl-k-protect-subtree 'error)
20789 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
20790 (error "C-k aborted - would kill hidden subtree")))
20791 (call-interactively
20792 (if (and (boundp 'visual-line-mode) visual-line-mode) 'kill-visual-line 'kill-line)))
20793 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
20794 (kill-region (point) (match-beginning 1))
20795 (org-set-tags nil t))
20796 (t (kill-region (point) (point-at-eol)))))
20798 (define-key org-mode-map "\C-k" 'org-kill-line)
20800 (defun org-yank (&optional arg)
20801 "Yank. If the kill is a subtree, treat it specially.
20802 This command will look at the current kill and check if is a single
20803 subtree, or a series of subtrees[1]. If it passes the test, and if the
20804 cursor is at the beginning of a line or after the stars of a currently
20805 empty headline, then the yank is handled specially. How exactly depends
20806 on the value of the following variables, both set by default.
20808 org-yank-folded-subtrees
20809 When set, the subtree(s) will be folded after insertion, but only
20810 if doing so would now swallow text after the yanked text.
20812 org-yank-adjusted-subtrees
20813 When set, the subtree will be promoted or demoted in order to
20814 fit into the local outline tree structure, which means that the level
20815 will be adjusted so that it becomes the smaller one of the two
20816 *visible* surrounding headings.
20818 Any prefix to this command will cause `yank' to be called directly with
20819 no special treatment. In particular, a simple \\[universal-argument] prefix \
20820 will just
20821 plainly yank the text as it is.
20823 \[1] The test checks if the first non-white line is a heading
20824 and if there are no other headings with fewer stars."
20825 (interactive "P")
20826 (org-yank-generic 'yank arg))
20828 (defun org-yank-generic (command arg)
20829 "Perform some yank-like command.
20831 This function implements the behavior described in the `org-yank'
20832 documentation. However, it has been generalized to work for any
20833 interactive command with similar behavior."
20835 ;; pretend to be command COMMAND
20836 (setq this-command command)
20838 (if arg
20839 (call-interactively command)
20841 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
20842 (and (org-kill-is-subtree-p)
20843 (or (bolp)
20844 (and (looking-at "[ \t]*$")
20845 (string-match
20846 "\\`\\*+\\'"
20847 (buffer-substring (point-at-bol) (point)))))))
20848 swallowp)
20849 (cond
20850 ((and subtreep org-yank-folded-subtrees)
20851 (let ((beg (point))
20852 end)
20853 (if (and subtreep org-yank-adjusted-subtrees)
20854 (org-paste-subtree nil nil 'for-yank)
20855 (call-interactively command))
20857 (setq end (point))
20858 (goto-char beg)
20859 (when (and (bolp) subtreep
20860 (not (setq swallowp
20861 (org-yank-folding-would-swallow-text beg end))))
20862 (org-with-limited-levels
20863 (or (looking-at org-outline-regexp)
20864 (re-search-forward org-outline-regexp-bol end t))
20865 (while (and (< (point) end) (looking-at org-outline-regexp))
20866 (hide-subtree)
20867 (org-cycle-show-empty-lines 'folded)
20868 (condition-case nil
20869 (outline-forward-same-level 1)
20870 (error (goto-char end))))))
20871 (when swallowp
20872 (message
20873 "Inserted text not folded because that would swallow text"))
20875 (goto-char end)
20876 (skip-chars-forward " \t\n\r")
20877 (beginning-of-line 1)
20878 (push-mark beg 'nomsg)))
20879 ((and subtreep org-yank-adjusted-subtrees)
20880 (let ((beg (point-at-bol)))
20881 (org-paste-subtree nil nil 'for-yank)
20882 (push-mark beg 'nomsg)))
20884 (call-interactively command))))))
20886 (defun org-yank-folding-would-swallow-text (beg end)
20887 "Would hide-subtree at BEG swallow any text after END?"
20888 (let (level)
20889 (org-with-limited-levels
20890 (save-excursion
20891 (goto-char beg)
20892 (when (or (looking-at org-outline-regexp)
20893 (re-search-forward org-outline-regexp-bol end t))
20894 (setq level (org-outline-level)))
20895 (goto-char end)
20896 (skip-chars-forward " \t\r\n\v\f")
20897 (if (or (eobp)
20898 (and (bolp) (looking-at org-outline-regexp)
20899 (<= (org-outline-level) level)))
20900 nil ; Nothing would be swallowed
20901 t))))) ; something would swallow
20903 (define-key org-mode-map "\C-y" 'org-yank)
20905 (defun org-truely-invisible-p ()
20906 "Check if point is at a character currently not visible.
20907 This version does not only check the character property, but also
20908 `visible-mode'."
20909 ;; Early versions of noutline don't have `outline-invisible-p'.
20910 (if (org-bound-and-true-p visible-mode)
20912 (outline-invisible-p)))
20914 (defun org-invisible-p2 ()
20915 "Check if point is at a character currently not visible."
20916 (save-excursion
20917 (if (and (eolp) (not (bobp))) (backward-char 1))
20918 ;; Early versions of noutline don't have `outline-invisible-p'.
20919 (outline-invisible-p)))
20921 (defun org-back-to-heading (&optional invisible-ok)
20922 "Call `outline-back-to-heading', but provide a better error message."
20923 (condition-case nil
20924 (outline-back-to-heading invisible-ok)
20925 (error (error "Before first headline at position %d in buffer %s"
20926 (point) (current-buffer)))))
20928 (defun org-beginning-of-defun ()
20929 "Go to the beginning of the subtree, i.e. back to the heading."
20930 (org-back-to-heading))
20931 (defun org-end-of-defun ()
20932 "Go to the end of the subtree."
20933 (org-end-of-subtree nil t))
20935 (defun org-before-first-heading-p ()
20936 "Before first heading?"
20937 (save-excursion
20938 (end-of-line)
20939 (null (re-search-backward org-outline-regexp-bol nil t))))
20941 (defun org-at-heading-p (&optional ignored)
20942 (outline-on-heading-p t))
20943 ;; Compatibility alias with Org versions < 7.8.03
20944 (defalias 'org-on-heading-p 'org-at-heading-p)
20946 (defun org-at-drawer-p nil
20947 "Is cursor at a drawer keyword?"
20948 (save-excursion
20949 (move-beginning-of-line 1)
20950 (looking-at org-drawer-regexp)))
20952 (defun org-at-block-p nil
20953 "Is cursor at a block keyword?"
20954 (save-excursion
20955 (move-beginning-of-line 1)
20956 (looking-at org-block-regexp)))
20958 (defun org-point-at-end-of-empty-headline ()
20959 "If point is at the end of an empty headline, return t, else nil.
20960 If the heading only contains a TODO keyword, it is still still considered
20961 empty."
20962 (and (looking-at "[ \t]*$")
20963 (when org-todo-line-regexp
20964 (save-excursion
20965 (beginning-of-line 1)
20966 (let ((case-fold-search nil))
20967 (looking-at org-todo-line-regexp)
20968 (string= (match-string 3) ""))))))
20970 (defun org-at-heading-or-item-p ()
20971 (or (org-at-heading-p) (org-at-item-p)))
20973 (defun org-at-target-p ()
20974 (or (org-in-regexp org-radio-target-regexp)
20975 (org-in-regexp org-target-regexp)))
20976 ;; Compatibility alias with Org versions < 7.8.03
20977 (defalias 'org-on-target-p 'org-at-target-p)
20979 (defun org-up-heading-all (arg)
20980 "Move to the heading line of which the present line is a subheading.
20981 This function considers both visible and invisible heading lines.
20982 With argument, move up ARG levels."
20983 (if (fboundp 'outline-up-heading-all)
20984 (outline-up-heading-all arg) ; emacs 21 version of outline.el
20985 (outline-up-heading arg t))) ; emacs 22 version of outline.el
20987 (defun org-up-heading-safe ()
20988 "Move to the heading line of which the present line is a subheading.
20989 This version will not throw an error. It will return the level of the
20990 headline found, or nil if no higher level is found.
20992 Also, this function will be a lot faster than `outline-up-heading',
20993 because it relies on stars being the outline starters. This can really
20994 make a significant difference in outlines with very many siblings."
20995 (let (start-level re)
20996 (org-back-to-heading t)
20997 (setq start-level (funcall outline-level))
20998 (if (equal start-level 1)
21000 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
21001 (if (re-search-backward re nil t)
21002 (funcall outline-level)))))
21004 (defun org-first-sibling-p ()
21005 "Is this heading the first child of its parents?"
21006 (interactive)
21007 (let ((re org-outline-regexp-bol)
21008 level l)
21009 (unless (org-at-heading-p t)
21010 (error "Not at a heading"))
21011 (setq level (funcall outline-level))
21012 (save-excursion
21013 (if (not (re-search-backward re nil t))
21015 (setq l (funcall outline-level))
21016 (< l level)))))
21018 (defun org-goto-sibling (&optional previous)
21019 "Goto the next sibling, even if it is invisible.
21020 When PREVIOUS is set, go to the previous sibling instead. Returns t
21021 when a sibling was found. When none is found, return nil and don't
21022 move point."
21023 (let ((fun (if previous 're-search-backward 're-search-forward))
21024 (pos (point))
21025 (re org-outline-regexp-bol)
21026 level l)
21027 (when (condition-case nil (org-back-to-heading t) (error nil))
21028 (setq level (funcall outline-level))
21029 (catch 'exit
21030 (or previous (forward-char 1))
21031 (while (funcall fun re nil t)
21032 (setq l (funcall outline-level))
21033 (when (< l level) (goto-char pos) (throw 'exit nil))
21034 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
21035 (goto-char pos)
21036 nil))))
21038 (defun org-show-siblings ()
21039 "Show all siblings of the current headline."
21040 (save-excursion
21041 (while (org-goto-sibling) (org-flag-heading nil)))
21042 (save-excursion
21043 (while (org-goto-sibling 'previous)
21044 (org-flag-heading nil))))
21046 (defun org-goto-first-child ()
21047 "Goto the first child, even if it is invisible.
21048 Return t when a child was found. Otherwise don't move point and
21049 return nil."
21050 (let (level (pos (point)) (re org-outline-regexp-bol))
21051 (when (condition-case nil (org-back-to-heading t) (error nil))
21052 (setq level (outline-level))
21053 (forward-char 1)
21054 (if (and (re-search-forward re nil t) (> (outline-level) level))
21055 (progn (goto-char (match-beginning 0)) t)
21056 (goto-char pos) nil))))
21058 (defun org-show-hidden-entry ()
21059 "Show an entry where even the heading is hidden."
21060 (save-excursion
21061 (org-show-entry)))
21063 (defun org-flag-heading (flag &optional entry)
21064 "Flag the current heading. FLAG non-nil means make invisible.
21065 When ENTRY is non-nil, show the entire entry."
21066 (save-excursion
21067 (org-back-to-heading t)
21068 ;; Check if we should show the entire entry
21069 (if entry
21070 (progn
21071 (org-show-entry)
21072 (save-excursion
21073 (and (outline-next-heading)
21074 (org-flag-heading nil))))
21075 (outline-flag-region (max (point-min) (1- (point)))
21076 (save-excursion (outline-end-of-heading) (point))
21077 flag))))
21079 (defun org-get-next-sibling ()
21080 "Move to next heading of the same level, and return point.
21081 If there is no such heading, return nil.
21082 This is like outline-next-sibling, but invisible headings are ok."
21083 (let ((level (funcall outline-level)))
21084 (outline-next-heading)
21085 (while (and (not (eobp)) (> (funcall outline-level) level))
21086 (outline-next-heading))
21087 (if (or (eobp) (< (funcall outline-level) level))
21089 (point))))
21091 (defun org-get-last-sibling ()
21092 "Move to previous heading of the same level, and return point.
21093 If there is no such heading, return nil."
21094 (let ((opoint (point))
21095 (level (funcall outline-level)))
21096 (outline-previous-heading)
21097 (when (and (/= (point) opoint) (outline-on-heading-p t))
21098 (while (and (> (funcall outline-level) level)
21099 (not (bobp)))
21100 (outline-previous-heading))
21101 (if (< (funcall outline-level) level)
21103 (point)))))
21105 (defun org-end-of-subtree (&optional invisible-OK to-heading)
21106 ;; This contains an exact copy of the original function, but it uses
21107 ;; `org-back-to-heading', to make it work also in invisible
21108 ;; trees. And is uses an invisible-OK argument.
21109 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
21110 ;; Furthermore, when used inside Org, finding the end of a large subtree
21111 ;; with many children and grandchildren etc, this can be much faster
21112 ;; than the outline version.
21113 (org-back-to-heading invisible-OK)
21114 (let ((first t)
21115 (level (funcall outline-level)))
21116 (if (and (eq major-mode 'org-mode) (< level 1000))
21117 ;; A true heading (not a plain list item), in Org-mode
21118 ;; This means we can easily find the end by looking
21119 ;; only for the right number of stars. Using a regexp to do
21120 ;; this is so much faster than using a Lisp loop.
21121 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
21122 (forward-char 1)
21123 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
21124 ;; something else, do it the slow way
21125 (while (and (not (eobp))
21126 (or first (> (funcall outline-level) level)))
21127 (setq first nil)
21128 (outline-next-heading)))
21129 (unless to-heading
21130 (if (memq (preceding-char) '(?\n ?\^M))
21131 (progn
21132 ;; Go to end of line before heading
21133 (forward-char -1)
21134 (if (memq (preceding-char) '(?\n ?\^M))
21135 ;; leave blank line before heading
21136 (forward-char -1))))))
21137 (point))
21139 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
21140 "Use Org version in org-mode, for dramatic speed-up."
21141 (if (eq major-mode 'org-mode)
21142 (progn
21143 (org-end-of-subtree nil t)
21144 (unless (eobp) (backward-char 1)))
21145 ad-do-it))
21147 (defun org-end-of-meta-data-and-drawers ()
21148 "Jump to the first text after meta data and drawers in the current entry.
21149 This will move over empty lines, lines with planning time stamps,
21150 clocking lines, and drawers."
21151 (org-back-to-heading t)
21152 (let ((end (save-excursion (outline-next-heading) (point)))
21153 (re (concat "\\(" org-drawer-regexp "\\)"
21154 "\\|" "[ \t]*" org-keyword-time-regexp)))
21155 (forward-line 1)
21156 (while (re-search-forward re end t)
21157 (if (not (match-end 1))
21158 ;; empty or planning line
21159 (forward-line 1)
21160 ;; a drawer, find the end
21161 (re-search-forward "^[ \t]*:END:" end 'move)
21162 (forward-line 1)))
21163 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
21164 (point)))
21166 (defun org-forward-same-level (arg &optional invisible-ok)
21167 "Move forward to the arg'th subheading at same level as this one.
21168 Stop at the first and last subheadings of a superior heading.
21169 Normally this only looks at visible headings, but when INVISIBLE-OK is non-nil
21170 it wil also look at invisible ones."
21171 (interactive "p")
21172 (org-back-to-heading invisible-ok)
21173 (org-at-heading-p)
21174 (let* ((level (- (match-end 0) (match-beginning 0) 1))
21175 (re (format "^\\*\\{1,%d\\} " level))
21177 (forward-char 1)
21178 (while (> arg 0)
21179 (while (and (re-search-forward re nil 'move)
21180 (setq l (- (match-end 0) (match-beginning 0) 1))
21181 (= l level)
21182 (not invisible-ok)
21183 (progn (backward-char 1) (outline-invisible-p)))
21184 (if (< l level) (setq arg 1)))
21185 (setq arg (1- arg)))
21186 (beginning-of-line 1)))
21188 (defun org-backward-same-level (arg &optional invisible-ok)
21189 "Move backward to the arg'th subheading at same level as this one.
21190 Stop at the first and last subheadings of a superior heading."
21191 (interactive "p")
21192 (org-back-to-heading)
21193 (org-at-heading-p)
21194 (let* ((level (- (match-end 0) (match-beginning 0) 1))
21195 (re (format "^\\*\\{1,%d\\} " level))
21197 (while (> arg 0)
21198 (while (and (re-search-backward re nil 'move)
21199 (setq l (- (match-end 0) (match-beginning 0) 1))
21200 (= l level)
21201 (not invisible-ok)
21202 (outline-invisible-p))
21203 (if (< l level) (setq arg 1)))
21204 (setq arg (1- arg)))))
21206 (defun org-show-subtree ()
21207 "Show everything after this heading at deeper levels."
21208 (interactive)
21209 (outline-flag-region
21210 (point)
21211 (save-excursion
21212 (org-end-of-subtree t t))
21213 nil))
21215 (defun org-show-entry ()
21216 "Show the body directly following this heading.
21217 Show the heading too, if it is currently invisible."
21218 (interactive)
21219 (save-excursion
21220 (condition-case nil
21221 (progn
21222 (org-back-to-heading t)
21223 (outline-flag-region
21224 (max (point-min) (1- (point)))
21225 (save-excursion
21226 (if (re-search-forward
21227 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
21228 (match-beginning 1)
21229 (point-max)))
21230 nil)
21231 (org-cycle-hide-drawers 'children))
21232 (error nil))))
21234 (defun org-make-options-regexp (kwds &optional extra)
21235 "Make a regular expression for keyword lines."
21236 (concat
21238 "#?[ \t]*\\+\\("
21239 (mapconcat 'regexp-quote kwds "\\|")
21240 (if extra (concat "\\|" extra))
21241 "\\):[ \t]*"
21242 "\\(.*\\)"))
21244 ;; Make isearch reveal the necessary context
21245 (defun org-isearch-end ()
21246 "Reveal context after isearch exits."
21247 (when isearch-success ; only if search was successful
21248 (if (featurep 'xemacs)
21249 ;; Under XEmacs, the hook is run in the correct place,
21250 ;; we directly show the context.
21251 (org-show-context 'isearch)
21252 ;; In Emacs the hook runs *before* restoring the overlays.
21253 ;; So we have to use a one-time post-command-hook to do this.
21254 ;; (Emacs 22 has a special variable, see function `org-mode')
21255 (unless (and (boundp 'isearch-mode-end-hook-quit)
21256 isearch-mode-end-hook-quit)
21257 ;; Only when the isearch was not quitted.
21258 (org-add-hook 'post-command-hook 'org-isearch-post-command
21259 'append 'local)))))
21261 (defun org-isearch-post-command ()
21262 "Remove self from hook, and show context."
21263 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
21264 (org-show-context 'isearch))
21267 ;;;; Integration with and fixes for other packages
21269 ;;; Imenu support
21271 (defvar org-imenu-markers nil
21272 "All markers currently used by Imenu.")
21273 (make-variable-buffer-local 'org-imenu-markers)
21275 (defun org-imenu-new-marker (&optional pos)
21276 "Return a new marker for use by Imenu, and remember the marker."
21277 (let ((m (make-marker)))
21278 (move-marker m (or pos (point)))
21279 (push m org-imenu-markers)
21282 (defun org-imenu-get-tree ()
21283 "Produce the index for Imenu."
21284 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
21285 (setq org-imenu-markers nil)
21286 (let* ((n org-imenu-depth)
21287 (re (concat "^" (org-get-limited-outline-regexp)))
21288 (subs (make-vector (1+ n) nil))
21289 (last-level 0)
21290 m level head)
21291 (save-excursion
21292 (save-restriction
21293 (widen)
21294 (goto-char (point-max))
21295 (while (re-search-backward re nil t)
21296 (setq level (org-reduced-level (funcall outline-level)))
21297 (when (and (<= level n)
21298 (looking-at org-complex-heading-regexp))
21299 (setq head (org-link-display-format
21300 (org-match-string-no-properties 4))
21301 m (org-imenu-new-marker))
21302 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
21303 (if (>= level last-level)
21304 (push (cons head m) (aref subs level))
21305 (push (cons head (aref subs (1+ level))) (aref subs level))
21306 (loop for i from (1+ level) to n do (aset subs i nil)))
21307 (setq last-level level)))))
21308 (aref subs 1)))
21310 (eval-after-load "imenu"
21311 '(progn
21312 (add-hook 'imenu-after-jump-hook
21313 (lambda ()
21314 (if (eq major-mode 'org-mode)
21315 (org-show-context 'org-goto))))))
21317 (defun org-link-display-format (link)
21318 "Replace a link with either the description, or the link target
21319 if no description is present"
21320 (save-match-data
21321 (if (string-match org-bracket-link-analytic-regexp link)
21322 (replace-match (if (match-end 5)
21323 (match-string 5 link)
21324 (concat (match-string 1 link)
21325 (match-string 3 link)))
21326 nil t link)
21327 link)))
21329 (defun org-toggle-link-display ()
21330 "Toggle the literal or descriptive display of links."
21331 (interactive)
21332 (if org-descriptive-links
21333 (progn (org-remove-from-invisibility-spec '(org-link))
21334 (org-restart-font-lock)
21335 (setq org-descriptive-links nil))
21336 (progn (add-to-invisibility-spec '(org-link))
21337 (org-restart-font-lock)
21338 (setq org-descriptive-links t))))
21340 ;; Speedbar support
21342 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
21343 "Overlay marking the agenda restriction line in speedbar.")
21344 (overlay-put org-speedbar-restriction-lock-overlay
21345 'face 'org-agenda-restriction-lock)
21346 (overlay-put org-speedbar-restriction-lock-overlay
21347 'help-echo "Agendas are currently limited to this item.")
21348 (org-detach-overlay org-speedbar-restriction-lock-overlay)
21350 (defun org-speedbar-set-agenda-restriction ()
21351 "Restrict future agenda commands to the location at point in speedbar.
21352 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
21353 (interactive)
21354 (require 'org-agenda)
21355 (let (p m tp np dir txt)
21356 (cond
21357 ((setq p (text-property-any (point-at-bol) (point-at-eol)
21358 'org-imenu t))
21359 (setq m (get-text-property p 'org-imenu-marker))
21360 (with-current-buffer (marker-buffer m)
21361 (goto-char m)
21362 (org-agenda-set-restriction-lock 'subtree)))
21363 ((setq p (text-property-any (point-at-bol) (point-at-eol)
21364 'speedbar-function 'speedbar-find-file))
21365 (setq tp (previous-single-property-change
21366 (1+ p) 'speedbar-function)
21367 np (next-single-property-change
21368 tp 'speedbar-function)
21369 dir (speedbar-line-directory)
21370 txt (buffer-substring-no-properties (or tp (point-min))
21371 (or np (point-max))))
21372 (with-current-buffer (find-file-noselect
21373 (let ((default-directory dir))
21374 (expand-file-name txt)))
21375 (unless (eq major-mode 'org-mode)
21376 (error "Cannot restrict to non-Org-mode file"))
21377 (org-agenda-set-restriction-lock 'file)))
21378 (t (error "Don't know how to restrict Org-mode's agenda")))
21379 (move-overlay org-speedbar-restriction-lock-overlay
21380 (point-at-bol) (point-at-eol))
21381 (setq current-prefix-arg nil)
21382 (org-agenda-maybe-redo)))
21384 (eval-after-load "speedbar"
21385 '(progn
21386 (speedbar-add-supported-extension ".org")
21387 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
21388 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
21389 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
21390 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
21391 (add-hook 'speedbar-visiting-tag-hook
21392 (lambda () (and (eq major-mode 'org-mode) (org-show-context 'org-goto))))))
21394 ;;; Fixes and Hacks for problems with other packages
21396 ;; Make flyspell not check words in links, to not mess up our keymap
21397 (defun org-mode-flyspell-verify ()
21398 "Don't let flyspell put overlays at active buttons, or on
21399 {todo,all-time,additional-option-like}-keywords."
21400 (let ((pos (max (1- (point)) (point-min)))
21401 (word (thing-at-point 'word)))
21402 (and (not (get-text-property pos 'keymap))
21403 (not (get-text-property pos 'org-no-flyspell))
21404 (not (member word org-todo-keywords-1))
21405 (not (member word org-all-time-keywords))
21406 (not (member word org-additional-option-like-keywords)))))
21408 (defun org-remove-flyspell-overlays-in (beg end)
21409 "Remove flyspell overlays in region."
21410 (and (org-bound-and-true-p flyspell-mode)
21411 (fboundp 'flyspell-delete-region-overlays)
21412 (flyspell-delete-region-overlays beg end))
21413 (add-text-properties beg end '(org-no-flyspell t)))
21415 ;; Make `bookmark-jump' shows the jump location if it was hidden.
21416 (eval-after-load "bookmark"
21417 '(if (boundp 'bookmark-after-jump-hook)
21418 ;; We can use the hook
21419 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
21420 ;; Hook not available, use advice
21421 (defadvice bookmark-jump (after org-make-visible activate)
21422 "Make the position visible."
21423 (org-bookmark-jump-unhide))))
21425 ;; Make sure saveplace shows the location if it was hidden
21426 (eval-after-load "saveplace"
21427 '(defadvice save-place-find-file-hook (after org-make-visible activate)
21428 "Make the position visible."
21429 (org-bookmark-jump-unhide)))
21431 ;; Make sure ecb shows the location if it was hidden
21432 (eval-after-load "ecb"
21433 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
21434 "Make hierarchy visible when jumping into location from ECB tree buffer."
21435 (if (eq major-mode 'org-mode)
21436 (org-show-context))))
21438 (defun org-bookmark-jump-unhide ()
21439 "Unhide the current position, to show the bookmark location."
21440 (and (eq major-mode 'org-mode)
21441 (or (outline-invisible-p)
21442 (save-excursion (goto-char (max (point-min) (1- (point))))
21443 (outline-invisible-p)))
21444 (org-show-context 'bookmark-jump)))
21446 ;; Make session.el ignore our circular variable
21447 (eval-after-load "session"
21448 '(add-to-list 'session-globals-exclude 'org-mark-ring))
21450 ;;;; Experimental code
21452 (defun org-closed-in-range ()
21453 "Sparse tree of items closed in a certain time range.
21454 Still experimental, may disappear in the future."
21455 (interactive)
21456 ;; Get the time interval from the user.
21457 (let* ((time1 (org-float-time
21458 (org-read-date nil 'to-time nil "Starting date: ")))
21459 (time2 (org-float-time
21460 (org-read-date nil 'to-time nil "End date:")))
21461 ;; callback function
21462 (callback (lambda ()
21463 (let ((time
21464 (org-float-time
21465 (apply 'encode-time
21466 (org-parse-time-string
21467 (match-string 1))))))
21468 ;; check if time in interval
21469 (and (>= time time1) (<= time time2))))))
21470 ;; make tree, check each match with the callback
21471 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
21473 ;;;; Finish up
21475 (provide 'org)
21477 (run-hooks 'org-load-hook)
21479 ;;; org.el ends here