org-element: code clean-up and some optimizations
[org-mode/org-mode-NeilSmithlineMods.git] / lisp / org.el
blobf54026c2e863268e7a7e5b14b2c01b383634c981
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 'find-func)
79 (require 'format-spec)
81 ;; Emacs 22 calendar compatibility: Make sure the new variables are available
82 (when (fboundp 'defvaralias)
83 (unless (boundp 'calendar-view-holidays-initially-flag)
84 (defvaralias 'calendar-view-holidays-initially-flag
85 'view-calendar-holidays-initially))
86 (unless (boundp 'calendar-view-diary-initially-flag)
87 (defvaralias 'calendar-view-diary-initially-flag
88 'view-diary-entries-initially))
89 (unless (boundp 'diary-fancy-buffer)
90 (defvaralias 'diary-fancy-buffer 'fancy-diary-buffer)))
92 (require 'outline) (require 'noutline)
93 ;; Other stuff we need.
94 (require 'time-date)
95 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
96 (require 'easymenu)
97 (require 'overlay)
99 (require 'org-macs)
100 (require 'org-entities)
101 (require 'org-compat)
102 (require 'org-faces)
103 (require 'org-list)
104 (require 'org-pcomplete)
105 (require 'org-src)
106 (require 'org-footnote)
108 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
109 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
110 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
111 (declare-function org-pop-to-buffer-same-window "org-compat" (&optional buffer-or-name norecord label))
112 (declare-function org-at-clock-log-p "org-clock" ())
113 (declare-function org-clock-timestamps-up "org-clock" ())
114 (declare-function org-clock-timestamps-down "org-clock" ())
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 (defvaralias 'org-version 'org-release)
213 ;;;###autoload
214 (defun org-version (&optional here)
215 "Show the org-mode version in the echo area.
216 With prefix arg HERE, insert it at point."
217 (interactive "P")
218 (let* ((origin default-directory)
219 (version (if (boundp 'org-release) org-release "N/A"))
220 (git-version (if (boundp 'org-git-version) org-git-version "N/A"))
221 (org-install (ignore-errors (find-library-name "org-install")))
222 (version_ (format "Org-mode version %s (%s @ %s)"
223 version
224 git-version
225 (if org-install org-install "org-install.el can not be found!"))))
226 (if (org-called-interactively-p 'interactive)
227 (if here (insert version_)
228 (message version_))
229 version)))
231 ;;; Compatibility constants
233 ;;; The custom variables
235 (defgroup org nil
236 "Outline-based notes management and organizer."
237 :tag "Org"
238 :group 'outlines
239 :group 'calendar)
241 (defcustom org-mode-hook nil
242 "Mode hook for Org-mode, run after the mode was turned on."
243 :group 'org
244 :type 'hook)
246 (defcustom org-load-hook nil
247 "Hook that is run after org.el has been loaded."
248 :group 'org
249 :type 'hook)
251 (defcustom org-log-buffer-setup-hook nil
252 "Hook that is run after an Org log buffer is created."
253 :group 'org
254 :version "24.1"
255 :type 'hook)
257 (defvar org-modules) ; defined below
258 (defvar org-modules-loaded nil
259 "Have the modules been loaded already?")
261 (defun org-load-modules-maybe (&optional force)
262 "Load all extensions listed in `org-modules'."
263 (when (or force (not org-modules-loaded))
264 (mapc (lambda (ext)
265 (condition-case nil (require ext)
266 (error (message "Problems while trying to load feature `%s'" ext))))
267 org-modules)
268 (setq org-modules-loaded t)))
270 (defun org-set-modules (var value)
271 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
272 (set var value)
273 (when (featurep 'org)
274 (org-load-modules-maybe 'force)))
276 (when (org-bound-and-true-p org-modules)
277 (let ((a (member 'org-infojs org-modules)))
278 (and a (setcar a 'org-jsinfo))))
280 (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)
281 "Modules that should always be loaded together with org.el.
282 If a description starts with <C>, the file is not part of Emacs
283 and loading it will require that you have downloaded and properly installed
284 the org-mode distribution.
286 You can also use this system to load external packages (i.e. neither Org
287 core modules, nor modules from the CONTRIB directory). Just add symbols
288 to the end of the list. If the package is called org-xyz.el, then you need
289 to add the symbol `xyz', and the package must have a call to
291 (provide 'org-xyz)"
292 :group 'org
293 :set 'org-set-modules
294 :type
295 '(set :greedy t
296 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
297 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
298 (const :tag " crypt: Encryption of subtrees" org-crypt)
299 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
300 (const :tag " docview: Links to doc-view buffers" org-docview)
301 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
302 (const :tag " id: Global IDs for identifying entries" org-id)
303 (const :tag " info: Links to Info nodes" org-info)
304 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
305 (const :tag " habit: Track your consistency with habits" org-habit)
306 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
307 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
308 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
309 (const :tag " mew Links to Mew folders/messages" org-mew)
310 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
311 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
312 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
313 (const :tag " special-blocks: Turn blocks into LaTeX envs and HTML divs" org-special-blocks)
314 (const :tag " vm: Links to VM folders/messages" org-vm)
315 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
316 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
317 (const :tag " mouse: Additional mouse support" org-mouse)
318 (const :tag " TaskJuggler: Export tasks to a TaskJuggler project" org-taskjuggler)
320 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
321 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
322 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
323 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
324 (const :tag "C collector: Collect properties into tables" org-collector)
325 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
326 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
327 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
328 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
329 (const :tag "C eval: Include command output as text" org-eval)
330 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
331 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
332 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
333 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
334 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
336 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
338 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
339 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
340 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
341 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
342 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
343 (const :tag "C mac-link-grabber Grab links and URLs from various Mac applications" org-mac-link-grabber)
344 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
345 (const :tag "C mtags: Support for muse-like tags" org-mtags)
346 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
347 (const :tag "C registry: A registry for Org-mode links" org-registry)
348 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
349 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
350 (const :tag "C secretary: Team management with org-mode" org-secretary)
351 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
352 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
353 (const :tag "C track: Keep up with Org-mode development" org-track)
354 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
355 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
356 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
358 (defcustom org-support-shift-select nil
359 "Non-nil means make shift-cursor commands select text when possible.
361 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
362 start selecting a region, or enlarge regions started in this way.
363 In Org-mode, in special contexts, these same keys are used for
364 other purposes, important enough to compete with shift selection.
365 Org tries to balance these needs by supporting `shift-select-mode'
366 outside these special contexts, under control of this variable.
368 The default of this variable is nil, to avoid confusing behavior. Shifted
369 cursor keys will then execute Org commands in the following contexts:
370 - on a headline, changing TODO state (left/right) and priority (up/down)
371 - on a time stamp, changing the time
372 - in a plain list item, changing the bullet type
373 - in a property definition line, switching between allowed values
374 - in the BEGIN line of a clock table (changing the time block).
375 Outside these contexts, the commands will throw an error.
377 When this variable is t and the cursor is not in a special
378 context, Org-mode will support shift-selection for making and
379 enlarging regions. To make this more effective, the bullet
380 cycling will no longer happen anywhere in an item line, but only
381 if the cursor is exactly on the bullet.
383 If you set this variable to the symbol `always', then the keys
384 will not be special in headlines, property lines, and item lines,
385 to make shift selection work there as well. If this is what you
386 want, you can use the following alternative commands: `C-c C-t'
387 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
388 can be used to switch TODO sets, `C-c -' to cycle item bullet
389 types, and properties can be edited by hand or in column view.
391 However, when the cursor is on a timestamp, shift-cursor commands
392 will still edit the time stamp - this is just too good to give up.
394 XEmacs user should have this variable set to nil, because
395 `shift-select-mode' is in Emacs 23 or later only."
396 :group 'org
397 :type '(choice
398 (const :tag "Never" nil)
399 (const :tag "When outside special context" t)
400 (const :tag "Everywhere except timestamps" always)))
402 (defcustom org-loop-over-headlines-in-active-region nil
403 "Shall some commands act upon headlines in the active region?
405 When set to `t', some commands will be performed in all headlines
406 within the active region.
408 When set to `start-level', some commands will be performed in all
409 headlines within the active region, provided that these headlines
410 are of the same level than the first one.
412 When set to a string, those commands will be performed on the
413 matching headlines within the active region. Such string must be
414 a tags/property/todo match as it is used in the agenda tags view.
416 The list of commands is: `org-schedule', `org-deadline',
417 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
418 `org-archive-to-archive-sibling'. The archiving commands skip
419 already archived entries."
420 :type '(choice (const :tag "Don't loop" nil)
421 (const :tag "All headlines in active region" t)
422 (const :tag "In active region, headlines at the same level than the first one" 'start-level)
423 (string :tag "Tags/Property/Todo matcher"))
424 :version "24.1"
425 :group 'org-todo
426 :group 'org-archive)
428 (defgroup org-startup nil
429 "Options concerning startup of Org-mode."
430 :tag "Org Startup"
431 :group 'org)
433 (defcustom org-startup-folded t
434 "Non-nil means entering Org-mode will switch to OVERVIEW.
435 This can also be configured on a per-file basis by adding one of
436 the following lines anywhere in the buffer:
438 #+STARTUP: fold (or `overview', this is equivalent)
439 #+STARTUP: nofold (or `showall', this is equivalent)
440 #+STARTUP: content
441 #+STARTUP: showeverything"
442 :group 'org-startup
443 :type '(choice
444 (const :tag "nofold: show all" nil)
445 (const :tag "fold: overview" t)
446 (const :tag "content: all headlines" content)
447 (const :tag "show everything, even drawers" showeverything)))
449 (defcustom org-startup-truncated t
450 "Non-nil means entering Org-mode will set `truncate-lines'.
451 This is useful since some lines containing links can be very long and
452 uninteresting. Also tables look terrible when wrapped."
453 :group 'org-startup
454 :type 'boolean)
456 (defcustom org-startup-indented nil
457 "Non-nil means turn on `org-indent-mode' on startup.
458 This can also be configured on a per-file basis by adding one of
459 the following lines anywhere in the buffer:
461 #+STARTUP: indent
462 #+STARTUP: noindent"
463 :group 'org-structure
464 :type '(choice
465 (const :tag "Not" nil)
466 (const :tag "Globally (slow on startup in large files)" t)))
468 (defcustom org-use-sub-superscripts t
469 "Non-nil means interpret \"_\" and \"^\" for export.
470 When this option is turned on, you can use TeX-like syntax for sub- and
471 superscripts. Several characters after \"_\" or \"^\" will be
472 considered as a single item - so grouping with {} is normally not
473 needed. For example, the following things will be parsed as single
474 sub- or superscripts.
476 10^24 or 10^tau several digits will be considered 1 item.
477 10^-12 or 10^-tau a leading sign with digits or a word
478 x^2-y^3 will be read as x^2 - y^3, because items are
479 terminated by almost any nonword/nondigit char.
480 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
482 Still, ambiguity is possible - so when in doubt use {} to enclose the
483 sub/superscript. If you set this variable to the symbol `{}',
484 the braces are *required* in order to trigger interpretations as
485 sub/superscript. This can be helpful in documents that need \"_\"
486 frequently in plain text.
488 Not all export backends support this, but HTML does.
490 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
491 :group 'org-startup
492 :group 'org-export-translation
493 :version "24.1"
494 :type '(choice
495 (const :tag "Always interpret" t)
496 (const :tag "Only with braces" {})
497 (const :tag "Never interpret" nil)))
499 (if (fboundp 'defvaralias)
500 (defvaralias 'org-export-with-sub-superscripts 'org-use-sub-superscripts))
503 (defcustom org-startup-with-beamer-mode nil
504 "Non-nil means turn on `org-beamer-mode' on startup.
505 This can also be configured on a per-file basis by adding one of
506 the following lines anywhere in the buffer:
508 #+STARTUP: beamer"
509 :group 'org-startup
510 :version "24.1"
511 :type 'boolean)
513 (defcustom org-startup-align-all-tables nil
514 "Non-nil means align all tables when visiting a file.
515 This is useful when the column width in tables is forced with <N> cookies
516 in table fields. Such tables will look correct only after the first re-align.
517 This can also be configured on a per-file basis by adding one of
518 the following lines anywhere in the buffer:
519 #+STARTUP: align
520 #+STARTUP: noalign"
521 :group 'org-startup
522 :type 'boolean)
524 (defcustom org-startup-with-inline-images nil
525 "Non-nil means show inline images when loading a new Org file.
526 This can also be configured on a per-file basis by adding one of
527 the following lines anywhere in the buffer:
528 #+STARTUP: inlineimages
529 #+STARTUP: noinlineimages"
530 :group 'org-startup
531 :version "24.1"
532 :type 'boolean)
534 (defcustom org-insert-mode-line-in-empty-file nil
535 "Non-nil means insert the first line setting Org-mode in empty files.
536 When the function `org-mode' is called interactively in an empty file, this
537 normally means that the file name does not automatically trigger Org-mode.
538 To ensure that the file will always be in Org-mode in the future, a
539 line enforcing Org-mode will be inserted into the buffer, if this option
540 has been set."
541 :group 'org-startup
542 :type 'boolean)
544 (defcustom org-replace-disputed-keys nil
545 "Non-nil means use alternative key bindings for some keys.
546 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
547 These keys are also used by other packages like shift-selection-mode'
548 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
549 If you want to use Org-mode together with one of these other modes,
550 or more generally if you would like to move some Org-mode commands to
551 other keys, set this variable and configure the keys with the variable
552 `org-disputed-keys'.
554 This option is only relevant at load-time of Org-mode, and must be set
555 *before* org.el is loaded. Changing it requires a restart of Emacs to
556 become effective."
557 :group 'org-startup
558 :type 'boolean)
560 (defcustom org-use-extra-keys nil
561 "Non-nil means use extra key sequence definitions for certain commands.
562 This happens automatically if you run XEmacs or if `window-system'
563 is nil. This variable lets you do the same manually. You must
564 set it before loading org.
566 Example: on Carbon Emacs 22 running graphically, with an external
567 keyboard on a Powerbook, the default way of setting M-left might
568 not work for either Alt or ESC. Setting this variable will make
569 it work for ESC."
570 :group 'org-startup
571 :type 'boolean)
573 (if (fboundp 'defvaralias)
574 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
576 (defcustom org-disputed-keys
577 '(([(shift up)] . [(meta p)])
578 ([(shift down)] . [(meta n)])
579 ([(shift left)] . [(meta -)])
580 ([(shift right)] . [(meta +)])
581 ([(control shift right)] . [(meta shift +)])
582 ([(control shift left)] . [(meta shift -)]))
583 "Keys for which Org-mode and other modes compete.
584 This is an alist, cars are the default keys, second element specifies
585 the alternative to use when `org-replace-disputed-keys' is t.
587 Keys can be specified in any syntax supported by `define-key'.
588 The value of this option takes effect only at Org-mode's startup,
589 therefore you'll have to restart Emacs to apply it after changing."
590 :group 'org-startup
591 :type 'alist)
593 (defun org-key (key)
594 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
595 Or return the original if not disputed.
596 Also apply the translations defined in `org-xemacs-key-equivalents'."
597 (when org-replace-disputed-keys
598 (let* ((nkey (key-description key))
599 (x (org-find-if (lambda (x)
600 (equal (key-description (car x)) nkey))
601 org-disputed-keys)))
602 (setq key (if x (cdr x) key))))
603 (when (featurep 'xemacs)
604 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
605 key)
607 (defun org-find-if (predicate seq)
608 (catch 'exit
609 (while seq
610 (if (funcall predicate (car seq))
611 (throw 'exit (car seq))
612 (pop seq)))))
614 (defun org-defkey (keymap key def)
615 "Define a key, possibly translated, as returned by `org-key'."
616 (define-key keymap (org-key key) def))
618 (defcustom org-ellipsis nil
619 "The ellipsis to use in the Org-mode outline.
620 When nil, just use the standard three dots. When a string, use that instead,
621 When a face, use the standard 3 dots, but with the specified face.
622 The change affects only Org-mode (which will then use its own display table).
623 Changing this requires executing `M-x org-mode' in a buffer to become
624 effective."
625 :group 'org-startup
626 :type '(choice (const :tag "Default" nil)
627 (face :tag "Face" :value org-warning)
628 (string :tag "String" :value "...#")))
630 (defvar org-display-table nil
631 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
633 (defgroup org-keywords nil
634 "Keywords in Org-mode."
635 :tag "Org Keywords"
636 :group 'org)
638 (defcustom org-deadline-string "DEADLINE:"
639 "String to mark deadline entries.
640 A deadline is this string, followed by a time stamp. Should be a word,
641 terminated by a colon. You can insert a schedule keyword and
642 a timestamp with \\[org-deadline].
643 Changes become only effective after restarting Emacs."
644 :group 'org-keywords
645 :type 'string)
647 (defcustom org-scheduled-string "SCHEDULED:"
648 "String to mark scheduled TODO entries.
649 A schedule is this string, followed by a time stamp. Should be a word,
650 terminated by a colon. You can insert a schedule keyword and
651 a timestamp with \\[org-schedule].
652 Changes become only effective after restarting Emacs."
653 :group 'org-keywords
654 :type 'string)
656 (defcustom org-closed-string "CLOSED:"
657 "String used as the prefix for timestamps logging closing a TODO entry."
658 :group 'org-keywords
659 :type 'string)
661 (defcustom org-clock-string "CLOCK:"
662 "String used as prefix for timestamps clocking work hours on an item."
663 :group 'org-keywords
664 :type 'string)
666 (defcustom org-comment-string "COMMENT"
667 "Entries starting with this keyword will never be exported.
668 An entry can be toggled between COMMENT and normal with
669 \\[org-toggle-comment].
670 Changes become only effective after restarting Emacs."
671 :group 'org-keywords
672 :type 'string)
674 (defcustom org-quote-string "QUOTE"
675 "Entries starting with this keyword will be exported in fixed-width font.
676 Quoting applies only to the text in the entry following the headline, and does
677 not extend beyond the next headline, even if that is lower level.
678 An entry can be toggled between QUOTE and normal with
679 \\[org-toggle-fixed-width-section]."
680 :group 'org-keywords
681 :type 'string)
683 (defconst org-repeat-re
684 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
685 "Regular expression for specifying repeated events.
686 After a match, group 1 contains the repeat expression.")
688 (defgroup org-structure nil
689 "Options concerning the general structure of Org-mode files."
690 :tag "Org Structure"
691 :group 'org)
693 (defgroup org-reveal-location nil
694 "Options about how to make context of a location visible."
695 :tag "Org Reveal Location"
696 :group 'org-structure)
698 (defconst org-context-choice
699 '(choice
700 (const :tag "Always" t)
701 (const :tag "Never" nil)
702 (repeat :greedy t :tag "Individual contexts"
703 (cons
704 (choice :tag "Context"
705 (const agenda)
706 (const org-goto)
707 (const occur-tree)
708 (const tags-tree)
709 (const link-search)
710 (const mark-goto)
711 (const bookmark-jump)
712 (const isearch)
713 (const default))
714 (boolean))))
715 "Contexts for the reveal options.")
717 (defcustom org-show-hierarchy-above '((default . t))
718 "Non-nil means show full hierarchy when revealing a location.
719 Org-mode often shows locations in an org-mode file which might have
720 been invisible before. When this is set, the hierarchy of headings
721 above the exposed location is shown.
722 Turning this off for example for sparse trees makes them very compact.
723 Instead of t, this can also be an alist specifying this option for different
724 contexts. Valid contexts are
725 agenda when exposing an entry from the agenda
726 org-goto when using the command `org-goto' on key C-c C-j
727 occur-tree when using the command `org-occur' on key C-c /
728 tags-tree when constructing a sparse tree based on tags matches
729 link-search when exposing search matches associated with a link
730 mark-goto when exposing the jump goal of a mark
731 bookmark-jump when exposing a bookmark location
732 isearch when exiting from an incremental search
733 default default for all contexts not set explicitly"
734 :group 'org-reveal-location
735 :type org-context-choice)
737 (defcustom org-show-following-heading '((default . nil))
738 "Non-nil means show following heading when revealing a location.
739 Org-mode often shows locations in an org-mode file which might have
740 been invisible before. When this is set, the heading following the
741 match is shown.
742 Turning this off for example for sparse trees makes them very compact,
743 but makes it harder to edit the location of the match. In such a case,
744 use the command \\[org-reveal] to show more context.
745 Instead of t, this can also be an alist specifying this option for different
746 contexts. See `org-show-hierarchy-above' for valid contexts."
747 :group 'org-reveal-location
748 :type org-context-choice)
750 (defcustom org-show-siblings '((default . nil) (isearch t))
751 "Non-nil means show all sibling heading when revealing a location.
752 Org-mode often shows locations in an org-mode file which might have
753 been invisible before. When this is set, the sibling of the current entry
754 heading are all made visible. If `org-show-hierarchy-above' is t,
755 the same happens on each level of the hierarchy above the current entry.
757 By default this is on for the isearch context, off for all other contexts.
758 Turning this off for example for sparse trees makes them very compact,
759 but makes it harder to edit the location of the match. In such a case,
760 use the command \\[org-reveal] to show more context.
761 Instead of t, this can also be an alist specifying this option for different
762 contexts. See `org-show-hierarchy-above' for valid contexts."
763 :group 'org-reveal-location
764 :type org-context-choice)
766 (defcustom org-show-entry-below '((default . nil))
767 "Non-nil means show the entry below a headline when revealing a location.
768 Org-mode often shows locations in an org-mode file which might have
769 been invisible before. When this is set, the text below the headline that is
770 exposed is also shown.
772 By default this is off for all contexts.
773 Instead of t, this can also be an alist specifying this option for different
774 contexts. See `org-show-hierarchy-above' for valid contexts."
775 :group 'org-reveal-location
776 :type org-context-choice)
778 (defcustom org-indirect-buffer-display 'other-window
779 "How should indirect tree buffers be displayed?
780 This applies to indirect buffers created with the commands
781 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
782 Valid values are:
783 current-window Display in the current window
784 other-window Just display in another window.
785 dedicated-frame Create one new frame, and re-use it each time.
786 new-frame Make a new frame each time. Note that in this case
787 previously-made indirect buffers are kept, and you need to
788 kill these buffers yourself."
789 :group 'org-structure
790 :group 'org-agenda-windows
791 :type '(choice
792 (const :tag "In current window" current-window)
793 (const :tag "In current frame, other window" other-window)
794 (const :tag "Each time a new frame" new-frame)
795 (const :tag "One dedicated frame" dedicated-frame)))
797 (defcustom org-use-speed-commands nil
798 "Non-nil means activate single letter commands at beginning of a headline.
799 This may also be a function to test for appropriate locations where speed
800 commands should be active."
801 :group 'org-structure
802 :type '(choice
803 (const :tag "Never" nil)
804 (const :tag "At beginning of headline stars" t)
805 (function)))
807 (defcustom org-speed-commands-user nil
808 "Alist of additional speed commands.
809 This list will be checked before `org-speed-commands-default'
810 when the variable `org-use-speed-commands' is non-nil
811 and when the cursor is at the beginning of a headline.
812 The car if each entry is a string with a single letter, which must
813 be assigned to `self-insert-command' in the global map.
814 The cdr is either a command to be called interactively, a function
815 to be called, or a form to be evaluated.
816 An entry that is just a list with a single string will be interpreted
817 as a descriptive headline that will be added when listing the speed
818 commands in the Help buffer using the `?' speed command."
819 :group 'org-structure
820 :type '(repeat :value ("k" . ignore)
821 (choice :value ("k" . ignore)
822 (list :tag "Descriptive Headline" (string :tag "Headline"))
823 (cons :tag "Letter and Command"
824 (string :tag "Command letter")
825 (choice
826 (function)
827 (sexp))))))
829 (defgroup org-cycle nil
830 "Options concerning visibility cycling in Org-mode."
831 :tag "Org Cycle"
832 :group 'org-structure)
834 (defcustom org-cycle-skip-children-state-if-no-children t
835 "Non-nil means skip CHILDREN state in entries that don't have any."
836 :group 'org-cycle
837 :type 'boolean)
839 (defcustom org-cycle-max-level nil
840 "Maximum level which should still be subject to visibility cycling.
841 Levels higher than this will, for cycling, be treated as text, not a headline.
842 When `org-odd-levels-only' is set, a value of N in this variable actually
843 means 2N-1 stars as the limiting headline.
844 When nil, cycle all levels.
845 Note that the limiting level of cycling is also influenced by
846 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
847 `org-inlinetask-min-level' is, cycling will be limited to levels one less
848 than its value."
849 :group 'org-cycle
850 :type '(choice
851 (const :tag "No limit" nil)
852 (integer :tag "Maximum level")))
854 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK" "RESULTS")
855 "Names of drawers. Drawers are not opened by cycling on the headline above.
856 Drawers only open with a TAB on the drawer line itself. A drawer looks like
857 this:
858 :DRAWERNAME:
859 .....
860 :END:
861 The drawer \"PROPERTIES\" is special for capturing properties through
862 the property API.
864 Drawers can be defined on the per-file basis with a line like:
866 #+DRAWERS: HIDDEN STATE PROPERTIES"
867 :group 'org-structure
868 :group 'org-cycle
869 :type '(repeat (string :tag "Drawer Name")))
871 (defcustom org-hide-block-startup nil
872 "Non-nil means entering Org-mode will fold all blocks.
873 This can also be set in on a per-file basis with
875 #+STARTUP: hideblocks
876 #+STARTUP: showblocks"
877 :group 'org-startup
878 :group 'org-cycle
879 :type 'boolean)
881 (defcustom org-cycle-global-at-bob nil
882 "Cycle globally if cursor is at beginning of buffer and not at a headline.
883 This makes it possible to do global cycling without having to use S-TAB or
884 \\[universal-argument] TAB. For this special case to work, the first line \
885 of the buffer
886 must not be a headline - it may be empty or some other text. When used in
887 this way, `org-cycle-hook' is disables temporarily, to make sure the
888 cursor stays at the beginning of the buffer.
889 When this option is nil, don't do anything special at the beginning
890 of the buffer."
891 :group 'org-cycle
892 :type 'boolean)
894 (defcustom org-cycle-level-after-item/entry-creation t
895 "Non-nil means cycle entry level or item indentation in new empty entries.
897 When the cursor is at the end of an empty headline, i.e with only stars
898 and maybe a TODO keyword, TAB will then switch the entry to become a child,
899 and then all possible ancestor states, before returning to the original state.
900 This makes data entry extremely fast: M-RET to create a new headline,
901 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
903 When the cursor is at the end of an empty plain list item, one TAB will
904 make it a subitem, two or more tabs will back up to make this an item
905 higher up in the item hierarchy."
906 :group 'org-cycle
907 :type 'boolean)
909 (defcustom org-cycle-emulate-tab t
910 "Where should `org-cycle' emulate TAB.
911 nil Never
912 white Only in completely white lines
913 whitestart Only at the beginning of lines, before the first non-white char
914 t Everywhere except in headlines
915 exc-hl-bol Everywhere except at the start of a headline
916 If TAB is used in a place where it does not emulate TAB, the current subtree
917 visibility is cycled."
918 :group 'org-cycle
919 :type '(choice (const :tag "Never" nil)
920 (const :tag "Only in completely white lines" white)
921 (const :tag "Before first char in a line" whitestart)
922 (const :tag "Everywhere except in headlines" t)
923 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
926 (defcustom org-cycle-separator-lines 2
927 "Number of empty lines needed to keep an empty line between collapsed trees.
928 If you leave an empty line between the end of a subtree and the following
929 headline, this empty line is hidden when the subtree is folded.
930 Org-mode will leave (exactly) one empty line visible if the number of
931 empty lines is equal or larger to the number given in this variable.
932 So the default 2 means at least 2 empty lines after the end of a subtree
933 are needed to produce free space between a collapsed subtree and the
934 following headline.
936 If the number is negative, and the number of empty lines is at least -N,
937 all empty lines are shown.
939 Special case: when 0, never leave empty lines in collapsed view."
940 :group 'org-cycle
941 :type 'integer)
942 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
944 (defcustom org-pre-cycle-hook nil
945 "Hook that is run before visibility cycling is happening.
946 The function(s) in this hook must accept a single argument which indicates
947 the new state that will be set right after running this hook. The
948 argument is a symbol. Before a global state change, it can have the values
949 `overview', `content', or `all'. Before a local state change, it can have
950 the values `folded', `children', or `subtree'."
951 :group 'org-cycle
952 :type 'hook)
954 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
955 org-cycle-hide-drawers
956 org-cycle-show-empty-lines
957 org-optimize-window-after-visibility-change)
958 "Hook that is run after `org-cycle' has changed the buffer visibility.
959 The function(s) in this hook must accept a single argument which indicates
960 the new state that was set by the most recent `org-cycle' command. The
961 argument is a symbol. After a global state change, it can have the values
962 `overview', `content', or `all'. After a local state change, it can have
963 the values `folded', `children', or `subtree'."
964 :group 'org-cycle
965 :type 'hook)
967 (defgroup org-edit-structure nil
968 "Options concerning structure editing in Org-mode."
969 :tag "Org Edit Structure"
970 :group 'org-structure)
972 (defcustom org-odd-levels-only nil
973 "Non-nil means skip even levels and only use odd levels for the outline.
974 This has the effect that two stars are being added/taken away in
975 promotion/demotion commands. It also influences how levels are
976 handled by the exporters.
977 Changing it requires restart of `font-lock-mode' to become effective
978 for fontification also in regions already fontified.
979 You may also set this on a per-file basis by adding one of the following
980 lines to the buffer:
982 #+STARTUP: odd
983 #+STARTUP: oddeven"
984 :group 'org-edit-structure
985 :group 'org-appearance
986 :type 'boolean)
988 (defcustom org-adapt-indentation t
989 "Non-nil means adapt indentation to outline node level.
991 When this variable is set, Org assumes that you write outlines by
992 indenting text in each node to align with the headline (after the stars).
993 The following issues are influenced by this variable:
995 - When this is set and the *entire* text in an entry is indented, the
996 indentation is increased by one space in a demotion command, and
997 decreased by one in a promotion command. If any line in the entry
998 body starts with text at column 0, indentation is not changed at all.
1000 - Property drawers and planning information is inserted indented when
1001 this variable s set. When nil, they will not be indented.
1003 - TAB indents a line relative to context. The lines below a headline
1004 will be indented when this variable is set.
1006 Note that this is all about true indentation, by adding and removing
1007 space characters. See also `org-indent.el' which does level-dependent
1008 indentation in a virtual way, i.e. at display time in Emacs."
1009 :group 'org-edit-structure
1010 :type 'boolean)
1012 (defcustom org-special-ctrl-a/e nil
1013 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1015 When t, `C-a' will bring back the cursor to the beginning of the
1016 headline text, i.e. after the stars and after a possible TODO
1017 keyword. In an item, this will be the position after bullet and
1018 check-box, if any. When the cursor is already at that position,
1019 another `C-a' will bring it to the beginning of the line.
1021 `C-e' will jump to the end of the headline, ignoring the presence
1022 of tags in the headline. A second `C-e' will then jump to the
1023 true end of the line, after any tags. This also means that, when
1024 this variable is non-nil, `C-e' also will never jump beyond the
1025 end of the heading of a folded section, i.e. not after the
1026 ellipses.
1028 When set to the symbol `reversed', the first `C-a' or `C-e' works
1029 normally, going to the true line boundary first. Only a directly
1030 following, identical keypress will bring the cursor to the
1031 special positions.
1033 This may also be a cons cell where the behavior for `C-a' and
1034 `C-e' is set separately."
1035 :group 'org-edit-structure
1036 :type '(choice
1037 (const :tag "off" nil)
1038 (const :tag "on: after stars/bullet and before tags first" t)
1039 (const :tag "reversed: true line boundary first" reversed)
1040 (cons :tag "Set C-a and C-e separately"
1041 (choice :tag "Special C-a"
1042 (const :tag "off" nil)
1043 (const :tag "on: after stars/bullet first" t)
1044 (const :tag "reversed: before stars/bullet first" reversed))
1045 (choice :tag "Special C-e"
1046 (const :tag "off" nil)
1047 (const :tag "on: before tags first" t)
1048 (const :tag "reversed: after tags first" reversed)))))
1049 (if (fboundp 'defvaralias)
1050 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
1052 (defcustom org-special-ctrl-k nil
1053 "Non-nil means `C-k' will behave specially in headlines.
1054 When nil, `C-k' will call the default `kill-line' command.
1055 When t, the following will happen while the cursor is in the headline:
1057 - When the cursor is at the beginning of a headline, kill the entire
1058 line and possible the folded subtree below the line.
1059 - When in the middle of the headline text, kill the headline up to the tags.
1060 - When after the headline text, kill the tags."
1061 :group 'org-edit-structure
1062 :type 'boolean)
1064 (defcustom org-ctrl-k-protect-subtree nil
1065 "Non-nil means, do not delete a hidden subtree with C-k.
1066 When set to the symbol `error', simply throw an error when C-k is
1067 used to kill (part-of) a headline that has hidden text behind it.
1068 Any other non-nil value will result in a query to the user, if it is
1069 OK to kill that hidden subtree. When nil, kill without remorse."
1070 :group 'org-edit-structure
1071 :version "24.1"
1072 :type '(choice
1073 (const :tag "Do not protect hidden subtrees" nil)
1074 (const :tag "Protect hidden subtrees with a security query" t)
1075 (const :tag "Never kill a hidden subtree with C-k" error)))
1077 (defcustom org-catch-invisible-edits nil
1078 "Check if in invisible region before inserting or deleting a character.
1079 Valid values are:
1081 nil Do not check, so just do invisible edits.
1082 error Throw an error and do nothing.
1083 show Make point visible, and do the requested edit.
1084 show-and-error Make point visible, then throw an error and abort the edit.
1085 smart Make point visible, and do insertion/deletion if it is
1086 adjacent to visible text and the change feels predictable.
1087 Never delete a previously invisible character or add in the
1088 middle or right after an invisible region. Basically, this
1089 allows insertion and backward-delete right before ellipses.
1090 FIXME: maybe in this case we should not even show?"
1091 :group 'org-edit-structure
1092 :version "24.1"
1093 :type '(choice
1094 (const :tag "Do not check" nil)
1095 (const :tag "Throw error when trying to edit" error)
1096 (const :tag "Unhide, but do not do the edit" show-and-error)
1097 (const :tag "Show invisible part and do the edit" show)
1098 (const :tag "Be smart and do the right thing" smart)))
1100 (defcustom org-yank-folded-subtrees t
1101 "Non-nil means when yanking subtrees, fold them.
1102 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1103 it starts with a heading and all other headings in it are either children
1104 or siblings, then fold all the subtrees. However, do this only if no
1105 text after the yank would be swallowed into a folded tree by this action."
1106 :group 'org-edit-structure
1107 :type 'boolean)
1109 (defcustom org-yank-adjusted-subtrees nil
1110 "Non-nil means when yanking subtrees, adjust the level.
1111 With this setting, `org-paste-subtree' is used to insert the subtree, see
1112 this function for details."
1113 :group 'org-edit-structure
1114 :type 'boolean)
1116 (defcustom org-M-RET-may-split-line '((default . t))
1117 "Non-nil means M-RET will split the line at the cursor position.
1118 When nil, it will go to the end of the line before making a
1119 new line.
1120 You may also set this option in a different way for different
1121 contexts. Valid contexts are:
1123 headline when creating a new headline
1124 item when creating a new item
1125 table in a table field
1126 default the value to be used for all contexts not explicitly
1127 customized"
1128 :group 'org-structure
1129 :group 'org-table
1130 :type '(choice
1131 (const :tag "Always" t)
1132 (const :tag "Never" nil)
1133 (repeat :greedy t :tag "Individual contexts"
1134 (cons
1135 (choice :tag "Context"
1136 (const headline)
1137 (const item)
1138 (const table)
1139 (const default))
1140 (boolean)))))
1143 (defcustom org-insert-heading-respect-content nil
1144 "Non-nil means insert new headings after the current subtree.
1145 When nil, the new heading is created directly after the current line.
1146 The commands \\[org-insert-heading-respect-content] and
1147 \\[org-insert-todo-heading-respect-content] turn this variable on
1148 for the duration of the command."
1149 :group 'org-structure
1150 :type 'boolean)
1152 (defcustom org-blank-before-new-entry '((heading . auto)
1153 (plain-list-item . auto))
1154 "Should `org-insert-heading' leave a blank line before new heading/item?
1155 The value is an alist, with `heading' and `plain-list-item' as CAR,
1156 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1157 which case Org will look at the surrounding headings/items and try to
1158 make an intelligent decision whether to insert a blank line or not.
1160 For plain lists, if the variable `org-empty-line-terminates-plain-lists' is
1161 set, the setting here is ignored and no empty line is inserted, to avoid
1162 breaking the list structure."
1163 :group 'org-edit-structure
1164 :type '(list
1165 (cons (const heading)
1166 (choice (const :tag "Never" nil)
1167 (const :tag "Always" t)
1168 (const :tag "Auto" auto)))
1169 (cons (const plain-list-item)
1170 (choice (const :tag "Never" nil)
1171 (const :tag "Always" t)
1172 (const :tag "Auto" auto)))))
1174 (defcustom org-insert-heading-hook nil
1175 "Hook being run after inserting a new heading."
1176 :group 'org-edit-structure
1177 :type 'hook)
1179 (defcustom org-enable-fixed-width-editor t
1180 "Non-nil means lines starting with \":\" are treated as fixed-width.
1181 This currently only means they are never auto-wrapped.
1182 When nil, such lines will be treated like ordinary lines.
1183 See also the QUOTE keyword."
1184 :group 'org-edit-structure
1185 :type 'boolean)
1187 (defcustom org-goto-auto-isearch t
1188 "Non-nil means typing characters in `org-goto' starts incremental search."
1189 :group 'org-edit-structure
1190 :type 'boolean)
1192 (defgroup org-sparse-trees nil
1193 "Options concerning sparse trees in Org-mode."
1194 :tag "Org Sparse Trees"
1195 :group 'org-structure)
1197 (defcustom org-highlight-sparse-tree-matches t
1198 "Non-nil means highlight all matches that define a sparse tree.
1199 The highlights will automatically disappear the next time the buffer is
1200 changed by an edit command."
1201 :group 'org-sparse-trees
1202 :type 'boolean)
1204 (defcustom org-remove-highlights-with-change t
1205 "Non-nil means any change to the buffer will remove temporary highlights.
1206 Such highlights are created by `org-occur' and `org-clock-display'.
1207 When nil, `C-c C-c needs to be used to get rid of the highlights.
1208 The highlights created by `org-preview-latex-fragment' always need
1209 `C-c C-c' to be removed."
1210 :group 'org-sparse-trees
1211 :group 'org-time
1212 :type 'boolean)
1215 (defcustom org-occur-hook '(org-first-headline-recenter)
1216 "Hook that is run after `org-occur' has constructed a sparse tree.
1217 This can be used to recenter the window to show as much of the structure
1218 as possible."
1219 :group 'org-sparse-trees
1220 :type 'hook)
1222 (defgroup org-imenu-and-speedbar nil
1223 "Options concerning imenu and speedbar in Org-mode."
1224 :tag "Org Imenu and Speedbar"
1225 :group 'org-structure)
1227 (defcustom org-imenu-depth 2
1228 "The maximum level for Imenu access to Org-mode headlines.
1229 This also applied for speedbar access."
1230 :group 'org-imenu-and-speedbar
1231 :type 'integer)
1233 (defgroup org-table nil
1234 "Options concerning tables in Org-mode."
1235 :tag "Org Table"
1236 :group 'org)
1238 (defcustom org-enable-table-editor 'optimized
1239 "Non-nil means lines starting with \"|\" are handled by the table editor.
1240 When nil, such lines will be treated like ordinary lines.
1242 When equal to the symbol `optimized', the table editor will be optimized to
1243 do the following:
1244 - Automatic overwrite mode in front of whitespace in table fields.
1245 This makes the structure of the table stay in tact as long as the edited
1246 field does not exceed the column width.
1247 - Minimize the number of realigns. Normally, the table is aligned each time
1248 TAB or RET are pressed to move to another field. With optimization this
1249 happens only if changes to a field might have changed the column width.
1250 Optimization requires replacing the functions `self-insert-command',
1251 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1252 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1253 very good at guessing when a re-align will be necessary, but you can always
1254 force one with \\[org-ctrl-c-ctrl-c].
1256 If you would like to use the optimized version in Org-mode, but the
1257 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1259 This variable can be used to turn on and off the table editor during a session,
1260 but in order to toggle optimization, a restart is required.
1262 See also the variable `org-table-auto-blank-field'."
1263 :group 'org-table
1264 :type '(choice
1265 (const :tag "off" nil)
1266 (const :tag "on" t)
1267 (const :tag "on, optimized" optimized)))
1269 (defcustom org-self-insert-cluster-for-undo t
1270 "Non-nil means cluster self-insert commands for undo when possible.
1271 If this is set, then, like in the Emacs command loop, 20 consecutive
1272 characters will be undone together.
1273 This is configurable, because there is some impact on typing performance."
1274 :group 'org-table
1275 :type 'boolean)
1277 (defcustom org-table-tab-recognizes-table.el t
1278 "Non-nil means TAB will automatically notice a table.el table.
1279 When it sees such a table, it moves point into it and - if necessary -
1280 calls `table-recognize-table'."
1281 :group 'org-table-editing
1282 :type 'boolean)
1284 (defgroup org-link nil
1285 "Options concerning links in Org-mode."
1286 :tag "Org Link"
1287 :group 'org)
1289 (defvar org-link-abbrev-alist-local nil
1290 "Buffer-local version of `org-link-abbrev-alist', which see.
1291 The value of this is taken from the #+LINK lines.")
1292 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1294 (defcustom org-link-abbrev-alist nil
1295 "Alist of link abbreviations.
1296 The car of each element is a string, to be replaced at the start of a link.
1297 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1298 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1300 [[linkkey:tag][description]]
1302 The 'linkkey' must be a word word, starting with a letter, followed
1303 by letters, numbers, '-' or '_'.
1305 If REPLACE is a string, the tag will simply be appended to create the link.
1306 If the string contains \"%s\", the tag will be inserted there. Alternatively,
1307 the placeholder \"%h\" will cause a url-encoded version of the tag to
1308 be inserted at that point (see the function `url-hexify-string').
1310 REPLACE may also be a function that will be called with the tag as the
1311 only argument to create the link, which should be returned as a string.
1313 See the manual for examples."
1314 :group 'org-link
1315 :type '(repeat
1316 (cons
1317 (string :tag "Protocol")
1318 (choice
1319 (string :tag "Format")
1320 (function)))))
1322 (defcustom org-descriptive-links t
1323 "Non-nil means Org will display descriptive links.
1324 E.g. [[http://orgmode.org][Org website]] will be displayed as
1325 \"Org Website\", hiding the link itself and just displaying its
1326 description. When set to `nil', Org will display the full links
1327 literally.
1329 You can interactively set the value of this variable by calling
1330 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1331 :group 'org-link
1332 :type 'boolean)
1334 (defcustom org-link-file-path-type 'adaptive
1335 "How the path name in file links should be stored.
1336 Valid values are:
1338 relative Relative to the current directory, i.e. the directory of the file
1339 into which the link is being inserted.
1340 absolute Absolute path, if possible with ~ for home directory.
1341 noabbrev Absolute path, no abbreviation of home directory.
1342 adaptive Use relative path for files in the current directory and sub-
1343 directories of it. For other files, use an absolute path."
1344 :group 'org-link
1345 :type '(choice
1346 (const relative)
1347 (const absolute)
1348 (const noabbrev)
1349 (const adaptive)))
1351 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1352 "Types of links that should be activated in Org-mode files.
1353 This is a list of symbols, each leading to the activation of a certain link
1354 type. In principle, it does not hurt to turn on most link types - there may
1355 be a small gain when turning off unused link types. The types are:
1357 bracket The recommended [[link][description]] or [[link]] links with hiding.
1358 angle Links in angular brackets that may contain whitespace like
1359 <bbdb:Carsten Dominik>.
1360 plain Plain links in normal text, no whitespace, like http://google.com.
1361 radio Text that is matched by a radio target, see manual for details.
1362 tag Tag settings in a headline (link to tag search).
1363 date Time stamps (link to calendar).
1364 footnote Footnote labels.
1366 Changing this variable requires a restart of Emacs to become effective."
1367 :group 'org-link
1368 :type '(set :greedy t
1369 (const :tag "Double bracket links" bracket)
1370 (const :tag "Angular bracket links" angle)
1371 (const :tag "Plain text links" plain)
1372 (const :tag "Radio target matches" radio)
1373 (const :tag "Tags" tag)
1374 (const :tag "Timestamps" date)
1375 (const :tag "Footnotes" footnote)))
1377 (defcustom org-make-link-description-function nil
1378 "Function to use to generate link descriptions from links.
1379 If nil the link location will be used. This function must take
1380 two parameters; the first is the link and the second the
1381 description `org-insert-link' has generated, and should return the
1382 description to use."
1383 :group 'org-link
1384 :type 'function)
1386 (defgroup org-link-store nil
1387 "Options concerning storing links in Org-mode."
1388 :tag "Org Store Link"
1389 :group 'org-link)
1391 (defcustom org-email-link-description-format "Email %c: %.30s"
1392 "Format of the description part of a link to an email or usenet message.
1393 The following %-escapes will be replaced by corresponding information:
1395 %F full \"From\" field
1396 %f name, taken from \"From\" field, address if no name
1397 %T full \"To\" field
1398 %t first name in \"To\" field, address if no name
1399 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1400 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1401 %s subject
1402 %d date
1403 %m message-id.
1405 You may use normal field width specification between the % and the letter.
1406 This is for example useful to limit the length of the subject.
1408 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1409 :group 'org-link-store
1410 :type 'string)
1412 (defcustom org-from-is-user-regexp
1413 (let (r1 r2)
1414 (when (and user-mail-address (not (string= user-mail-address "")))
1415 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1416 (when (and user-full-name (not (string= user-full-name "")))
1417 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1418 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1419 "Regexp matched against the \"From:\" header of an email or usenet message.
1420 It should match if the message is from the user him/herself."
1421 :group 'org-link-store
1422 :type 'regexp)
1424 (defcustom org-link-to-org-use-id 'create-if-interactive-and-no-custom-id
1425 "Non-nil means storing a link to an Org file will use entry IDs.
1427 Note that before this variable is even considered, org-id must be loaded,
1428 so please customize `org-modules' and turn it on.
1430 The variable can have the following values:
1432 t Create an ID if needed to make a link to the current entry.
1434 create-if-interactive
1435 If `org-store-link' is called directly (interactively, as a user
1436 command), do create an ID to support the link. But when doing the
1437 job for remember, only use the ID if it already exists. The
1438 purpose of this setting is to avoid proliferation of unwanted
1439 IDs, just because you happen to be in an Org file when you
1440 call `org-remember' that automatically and preemptively
1441 creates a link. If you do want to get an ID link in a remember
1442 template to an entry not having an ID, create it first by
1443 explicitly creating a link to it, using `C-c C-l' first.
1445 create-if-interactive-and-no-custom-id
1446 Like create-if-interactive, but do not create an ID if there is
1447 a CUSTOM_ID property defined in the entry. This is the default.
1449 use-existing
1450 Use existing ID, do not create one.
1452 nil Never use an ID to make a link, instead link using a text search for
1453 the headline text."
1454 :group 'org-link-store
1455 :type '(choice
1456 (const :tag "Create ID to make link" t)
1457 (const :tag "Create if storing link interactively"
1458 create-if-interactive)
1459 (const :tag "Create if storing link interactively and no CUSTOM_ID is present"
1460 create-if-interactive-and-no-custom-id)
1461 (const :tag "Only use existing" use-existing)
1462 (const :tag "Do not use ID to create link" nil)))
1464 (defcustom org-context-in-file-links t
1465 "Non-nil means file links from `org-store-link' contain context.
1466 A search string will be added to the file name with :: as separator and
1467 used to find the context when the link is activated by the command
1468 `org-open-at-point'. When this option is t, the entire active region
1469 will be placed in the search string of the file link. If set to a
1470 positive integer, only the first n lines of context will be stored.
1472 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1473 negates this setting for the duration of the command."
1474 :group 'org-link-store
1475 :type '(choice boolean integer))
1477 (defcustom org-keep-stored-link-after-insertion nil
1478 "Non-nil means keep link in list for entire session.
1480 The command `org-store-link' adds a link pointing to the current
1481 location to an internal list. These links accumulate during a session.
1482 The command `org-insert-link' can be used to insert links into any
1483 Org-mode file (offering completion for all stored links). When this
1484 option is nil, every link which has been inserted once using \\[org-insert-link]
1485 will be removed from the list, to make completing the unused links
1486 more efficient."
1487 :group 'org-link-store
1488 :type 'boolean)
1490 (defgroup org-link-follow nil
1491 "Options concerning following links in Org-mode."
1492 :tag "Org Follow Link"
1493 :group 'org-link)
1495 (defcustom org-link-translation-function nil
1496 "Function to translate links with different syntax to Org syntax.
1497 This can be used to translate links created for example by the Planner
1498 or emacs-wiki packages to Org syntax.
1499 The function must accept two parameters, a TYPE containing the link
1500 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1501 which is everything after the link protocol. It should return a cons
1502 with possibly modified values of type and path.
1503 Org contains a function for this, so if you set this variable to
1504 `org-translate-link-from-planner', you should be able follow many
1505 links created by planner."
1506 :group 'org-link-follow
1507 :type 'function)
1509 (defcustom org-follow-link-hook nil
1510 "Hook that is run after a link has been followed."
1511 :group 'org-link-follow
1512 :type 'hook)
1514 (defcustom org-tab-follows-link nil
1515 "Non-nil means on links TAB will follow the link.
1516 Needs to be set before org.el is loaded.
1517 This really should not be used, it does not make sense, and the
1518 implementation is bad."
1519 :group 'org-link-follow
1520 :type 'boolean)
1522 (defcustom org-return-follows-link nil
1523 "Non-nil means on links RET will follow the link."
1524 :group 'org-link-follow
1525 :type 'boolean)
1527 (defcustom org-mouse-1-follows-link
1528 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1529 "Non-nil means mouse-1 on a link will follow the link.
1530 A longer mouse click will still set point. Does not work on XEmacs.
1531 Needs to be set before org.el is loaded."
1532 :group 'org-link-follow
1533 :type 'boolean)
1535 (defcustom org-mark-ring-length 4
1536 "Number of different positions to be recorded in the ring.
1537 Changing this requires a restart of Emacs to work correctly."
1538 :group 'org-link-follow
1539 :type 'integer)
1541 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1542 "Non-nil means internal links in Org files must exactly match a headline.
1543 When nil, the link search tries to match a phrase with all words
1544 in the search text."
1545 :group 'org-link-follow
1546 :version "24.1"
1547 :type '(choice
1548 (const :tag "Use fuzzy text search" nil)
1549 (const :tag "Match only exact headline" t)
1550 (const :tag "Match exact headline or query to create it"
1551 query-to-create)))
1553 (defcustom org-link-frame-setup
1554 '((vm . vm-visit-folder-other-frame)
1555 (vm-imap . vm-visit-imap-folder-other-frame)
1556 (gnus . org-gnus-no-new-news)
1557 (file . find-file-other-window)
1558 (wl . wl-other-frame))
1559 "Setup the frame configuration for following links.
1560 When following a link with Emacs, it may often be useful to display
1561 this link in another window or frame. This variable can be used to
1562 set this up for the different types of links.
1563 For VM, use any of
1564 `vm-visit-folder'
1565 `vm-visit-folder-other-window'
1566 `vm-visit-folder-other-frame'
1567 For Gnus, use any of
1568 `gnus'
1569 `gnus-other-frame'
1570 `org-gnus-no-new-news'
1571 For FILE, use any of
1572 `find-file'
1573 `find-file-other-window'
1574 `find-file-other-frame'
1575 For Wanderlust use any of
1576 `wl'
1577 `wl-other-frame'
1578 For the calendar, use the variable `calendar-setup'.
1579 For BBDB, it is currently only possible to display the matches in
1580 another window."
1581 :group 'org-link-follow
1582 :type '(list
1583 (cons (const vm)
1584 (choice
1585 (const vm-visit-folder)
1586 (const vm-visit-folder-other-window)
1587 (const vm-visit-folder-other-frame)))
1588 (cons (const gnus)
1589 (choice
1590 (const gnus)
1591 (const gnus-other-frame)
1592 (const org-gnus-no-new-news)))
1593 (cons (const file)
1594 (choice
1595 (const find-file)
1596 (const find-file-other-window)
1597 (const find-file-other-frame)))
1598 (cons (const wl)
1599 (choice
1600 (const wl)
1601 (const wl-other-frame)))))
1603 (defcustom org-display-internal-link-with-indirect-buffer nil
1604 "Non-nil means use indirect buffer to display infile links.
1605 Activating internal links (from one location in a file to another location
1606 in the same file) normally just jumps to the location. When the link is
1607 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1608 is displayed in
1609 another window. When this option is set, the other window actually displays
1610 an indirect buffer clone of the current buffer, to avoid any visibility
1611 changes to the current buffer."
1612 :group 'org-link-follow
1613 :type 'boolean)
1615 (defcustom org-open-non-existing-files nil
1616 "Non-nil means `org-open-file' will open non-existing files.
1617 When nil, an error will be generated.
1618 This variable applies only to external applications because they
1619 might choke on non-existing files. If the link is to a file that
1620 will be opened in Emacs, the variable is ignored."
1621 :group 'org-link-follow
1622 :type 'boolean)
1624 (defcustom org-open-directory-means-index-dot-org nil
1625 "Non-nil means a link to a directory really means to index.org.
1626 When nil, following a directory link will run dired or open a finder/explorer
1627 window on that directory."
1628 :group 'org-link-follow
1629 :type 'boolean)
1631 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1632 "Function and arguments to call for following mailto links.
1633 This is a list with the first element being a Lisp function, and the
1634 remaining elements being arguments to the function. In string arguments,
1635 %a will be replaced by the address, and %s will be replaced by the subject
1636 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1637 :group 'org-link-follow
1638 :type '(choice
1639 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1640 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1641 (const :tag "message-mail" (message-mail "%a" "%s"))
1642 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1644 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1645 "Non-nil means ask for confirmation before executing shell links.
1646 Shell links can be dangerous: just think about a link
1648 [[shell:rm -rf ~/*][Google Search]]
1650 This link would show up in your Org-mode document as \"Google Search\",
1651 but really it would remove your entire home directory.
1652 Therefore we advise against setting this variable to nil.
1653 Just change it to `y-or-n-p' if you want to confirm with a
1654 single keystroke rather than having to type \"yes\"."
1655 :group 'org-link-follow
1656 :type '(choice
1657 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1658 (const :tag "with y-or-n (faster)" y-or-n-p)
1659 (const :tag "no confirmation (dangerous)" nil)))
1660 (put 'org-confirm-shell-link-function
1661 'safe-local-variable
1662 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1664 (defcustom org-confirm-shell-link-not-regexp ""
1665 "A regexp to skip confirmation for shell links."
1666 :group 'org-link-follow
1667 :version "24.1"
1668 :type 'regexp)
1670 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1671 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1672 Elisp links can be dangerous: just think about a link
1674 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1676 This link would show up in your Org-mode document as \"Google Search\",
1677 but really it would remove your entire home directory.
1678 Therefore we advise against setting this variable to nil.
1679 Just change it to `y-or-n-p' if you want to confirm with a
1680 single keystroke rather than having to type \"yes\"."
1681 :group 'org-link-follow
1682 :type '(choice
1683 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1684 (const :tag "with y-or-n (faster)" y-or-n-p)
1685 (const :tag "no confirmation (dangerous)" nil)))
1686 (put 'org-confirm-shell-link-function
1687 'safe-local-variable
1688 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1690 (defcustom org-confirm-elisp-link-not-regexp ""
1691 "A regexp to skip confirmation for Elisp links."
1692 :group 'org-link-follow
1693 :version "24.1"
1694 :type 'regexp)
1696 (defconst org-file-apps-defaults-gnu
1697 '((remote . emacs)
1698 (system . mailcap)
1699 (t . mailcap))
1700 "Default file applications on a UNIX or GNU/Linux system.
1701 See `org-file-apps'.")
1703 (defconst org-file-apps-defaults-macosx
1704 '((remote . emacs)
1705 (t . "open %s")
1706 (system . "open %s")
1707 ("ps.gz" . "gv %s")
1708 ("eps.gz" . "gv %s")
1709 ("dvi" . "xdvi %s")
1710 ("fig" . "xfig %s"))
1711 "Default file applications on a MacOS X system.
1712 The system \"open\" is known as a default, but we use X11 applications
1713 for some files for which the OS does not have a good default.
1714 See `org-file-apps'.")
1716 (defconst org-file-apps-defaults-windowsnt
1717 (list
1718 '(remote . emacs)
1719 (cons t
1720 (list (if (featurep 'xemacs)
1721 'mswindows-shell-execute
1722 'w32-shell-execute)
1723 "open" 'file))
1724 (cons 'system
1725 (list (if (featurep 'xemacs)
1726 'mswindows-shell-execute
1727 'w32-shell-execute)
1728 "open" 'file)))
1729 "Default file applications on a Windows NT system.
1730 The system \"open\" is used for most files.
1731 See `org-file-apps'.")
1733 (defcustom org-file-apps
1735 (auto-mode . emacs)
1736 ("\\.mm\\'" . default)
1737 ("\\.x?html?\\'" . default)
1738 ("\\.pdf\\'" . default)
1740 "External applications for opening `file:path' items in a document.
1741 Org-mode uses system defaults for different file types, but
1742 you can use this variable to set the application for a given file
1743 extension. The entries in this list are cons cells where the car identifies
1744 files and the cdr the corresponding command. Possible values for the
1745 file identifier are
1746 \"string\" A string as a file identifier can be interpreted in different
1747 ways, depending on its contents:
1749 - Alphanumeric characters only:
1750 Match links with this file extension.
1751 Example: (\"pdf\" . \"evince %s\")
1752 to open PDFs with evince.
1754 - Regular expression: Match links where the
1755 filename matches the regexp. If you want to
1756 use groups here, use shy groups.
1758 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1759 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1760 to open *.html and *.xhtml with firefox.
1762 - Regular expression which contains (non-shy) groups:
1763 Match links where the whole link, including \"::\", and
1764 anything after that, matches the regexp.
1765 In a custom command string, %1, %2, etc. are replaced with
1766 the parts of the link that were matched by the groups.
1767 For backwards compatibility, if a command string is given
1768 that does not use any of the group matches, this case is
1769 handled identically to the second one (i.e. match against
1770 file name only).
1771 In a custom lisp form, you can access the group matches with
1772 (match-string n link).
1774 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1775 to open [[file:document.pdf::5]] with evince at page 5.
1777 `directory' Matches a directory
1778 `remote' Matches a remote file, accessible through tramp or efs.
1779 Remote files most likely should be visited through Emacs
1780 because external applications cannot handle such paths.
1781 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1782 so all files Emacs knows how to handle. Using this with
1783 command `emacs' will open most files in Emacs. Beware that this
1784 will also open html files inside Emacs, unless you add
1785 (\"html\" . default) to the list as well.
1786 t Default for files not matched by any of the other options.
1787 `system' The system command to open files, like `open' on Windows
1788 and Mac OS X, and mailcap under GNU/Linux. This is the command
1789 that will be selected if you call `C-c C-o' with a double
1790 \\[universal-argument] \\[universal-argument] prefix.
1792 Possible values for the command are:
1793 `emacs' The file will be visited by the current Emacs process.
1794 `default' Use the default application for this file type, which is the
1795 association for t in the list, most likely in the system-specific
1796 part.
1797 This can be used to overrule an unwanted setting in the
1798 system-specific variable.
1799 `system' Use the system command for opening files, like \"open\".
1800 This command is specified by the entry whose car is `system'.
1801 Most likely, the system-specific version of this variable
1802 does define this command, but you can overrule/replace it
1803 here.
1804 string A command to be executed by a shell; %s will be replaced
1805 by the path to the file.
1806 sexp A Lisp form which will be evaluated. The file path will
1807 be available in the Lisp variable `file'.
1808 For more examples, see the system specific constants
1809 `org-file-apps-defaults-macosx'
1810 `org-file-apps-defaults-windowsnt'
1811 `org-file-apps-defaults-gnu'."
1812 :group 'org-link-follow
1813 :type '(repeat
1814 (cons (choice :value ""
1815 (string :tag "Extension")
1816 (const :tag "System command to open files" system)
1817 (const :tag "Default for unrecognized files" t)
1818 (const :tag "Remote file" remote)
1819 (const :tag "Links to a directory" directory)
1820 (const :tag "Any files that have Emacs modes"
1821 auto-mode))
1822 (choice :value ""
1823 (const :tag "Visit with Emacs" emacs)
1824 (const :tag "Use default" default)
1825 (const :tag "Use the system command" system)
1826 (string :tag "Command")
1827 (sexp :tag "Lisp form")))))
1831 (defgroup org-refile nil
1832 "Options concerning refiling entries in Org-mode."
1833 :tag "Org Refile"
1834 :group 'org)
1836 (defcustom org-directory "~/org"
1837 "Directory with org files.
1838 This is just a default location to look for Org files. There is no need
1839 at all to put your files into this directory. It is only used in the
1840 following situations:
1842 1. When a remember template specifies a target file that is not an
1843 absolute path. The path will then be interpreted relative to
1844 `org-directory'
1845 2. When a remember note is filed away in an interactive way (when exiting the
1846 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1847 with `org-directory' as the default path."
1848 :group 'org-refile
1849 :group 'org-remember
1850 :type 'directory)
1852 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1853 "Default target for storing notes.
1854 Used as a fall back file for org-remember.el and org-capture.el, for
1855 templates that do not specify a target file."
1856 :group 'org-refile
1857 :group 'org-remember
1858 :type '(choice
1859 (const :tag "Default from remember-data-file" nil)
1860 file))
1862 (defcustom org-goto-interface 'outline
1863 "The default interface to be used for `org-goto'.
1864 Allowed values are:
1865 outline The interface shows an outline of the relevant file
1866 and the correct heading is found by moving through
1867 the outline or by searching with incremental search.
1868 outline-path-completion Headlines in the current buffer are offered via
1869 completion. This is the interface also used by
1870 the refile command."
1871 :group 'org-refile
1872 :type '(choice
1873 (const :tag "Outline" outline)
1874 (const :tag "Outline-path-completion" outline-path-completion)))
1876 (defcustom org-goto-max-level 5
1877 "Maximum target level when running `org-goto' with refile interface."
1878 :group 'org-refile
1879 :type 'integer)
1881 (defcustom org-reverse-note-order nil
1882 "Non-nil means store new notes at the beginning of a file or entry.
1883 When nil, new notes will be filed to the end of a file or entry.
1884 This can also be a list with cons cells of regular expressions that
1885 are matched against file names, and values."
1886 :group 'org-remember
1887 :group 'org-refile
1888 :type '(choice
1889 (const :tag "Reverse always" t)
1890 (const :tag "Reverse never" nil)
1891 (repeat :tag "By file name regexp"
1892 (cons regexp boolean))))
1894 (defcustom org-log-refile nil
1895 "Information to record when a task is refiled.
1897 Possible values are:
1899 nil Don't add anything
1900 time Add a time stamp to the task
1901 note Prompt for a note and add it with template `org-log-note-headings'
1903 This option can also be set with on a per-file-basis with
1905 #+STARTUP: nologrefile
1906 #+STARTUP: logrefile
1907 #+STARTUP: lognoterefile
1909 You can have local logging settings for a subtree by setting the LOGGING
1910 property to one or more of these keywords.
1912 When bulk-refiling from the agenda, the value `note' is forbidden and
1913 will temporarily be changed to `time'."
1914 :group 'org-refile
1915 :group 'org-progress
1916 :version "24.1"
1917 :type '(choice
1918 (const :tag "No logging" nil)
1919 (const :tag "Record timestamp" time)
1920 (const :tag "Record timestamp with note." note)))
1922 (defcustom org-refile-targets nil
1923 "Targets for refiling entries with \\[org-refile].
1924 This is a list of cons cells. Each cell contains:
1925 - a specification of the files to be considered, either a list of files,
1926 or a symbol whose function or variable value will be used to retrieve
1927 a file name or a list of file names. If you use `org-agenda-files' for
1928 that, all agenda files will be scanned for targets. Nil means consider
1929 headings in the current buffer.
1930 - A specification of how to find candidate refile targets. This may be
1931 any of:
1932 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1933 This tag has to be present in all target headlines, inheritance will
1934 not be considered.
1935 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1936 todo keyword.
1937 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1938 headlines that are refiling targets.
1939 - a cons cell (:level . N). Any headline of level N is considered 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.
1942 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1943 Note that, when `org-odd-levels-only' is set, level corresponds to
1944 order in hierarchy, not to the number of stars.
1946 Each element of this list generates a set of possible targets.
1947 The union of these sets is presented (with completion) to
1948 the user by `org-refile'.
1950 You can set the variable `org-refile-target-verify-function' to a function
1951 to verify each headline found by the simple criteria above.
1953 When this variable is nil, all top-level headlines in the current buffer
1954 are used, equivalent to the value `((nil . (:level . 1))'."
1955 :group 'org-refile
1956 :type '(repeat
1957 (cons
1958 (choice :value org-agenda-files
1959 (const :tag "All agenda files" org-agenda-files)
1960 (const :tag "Current buffer" nil)
1961 (function) (variable) (file))
1962 (choice :tag "Identify target headline by"
1963 (cons :tag "Specific tag" (const :value :tag) (string))
1964 (cons :tag "TODO keyword" (const :value :todo) (string))
1965 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1966 (cons :tag "Level number" (const :value :level) (integer))
1967 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1969 (defcustom org-refile-target-verify-function nil
1970 "Function to verify if the headline at point should be a refile target.
1971 The function will be called without arguments, with point at the
1972 beginning of the headline. It should return t and leave point
1973 where it is if the headline is a valid target for refiling.
1975 If the target should not be selected, the function must return nil.
1976 In addition to this, it may move point to a place from where the search
1977 should be continued. For example, the function may decide that the entire
1978 subtree of the current entry should be excluded and move point to the end
1979 of the subtree."
1980 :group 'org-refile
1981 :type 'function)
1983 (defcustom org-refile-use-cache nil
1984 "Non-nil means cache refile targets to speed up the process.
1985 The cache for a particular file will be updated automatically when
1986 the buffer has been killed, or when any of the marker used for flagging
1987 refile targets no longer points at a live buffer.
1988 If you have added new entries to a buffer that might themselves be targets,
1989 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
1990 find that easier, `C-u C-u C-u C-c C-w'."
1991 :group 'org-refile
1992 :version "24.1"
1993 :type 'boolean)
1995 (defcustom org-refile-use-outline-path nil
1996 "Non-nil means provide refile targets as paths.
1997 So a level 3 headline will be available as level1/level2/level3.
1999 When the value is `file', also include the file name (without directory)
2000 into the path. In this case, you can also stop the completion after
2001 the file name, to get entries inserted as top level in the file.
2003 When `full-file-path', include the full file path."
2004 :group 'org-refile
2005 :type '(choice
2006 (const :tag "Not" nil)
2007 (const :tag "Yes" t)
2008 (const :tag "Start with file name" file)
2009 (const :tag "Start with full file path" full-file-path)))
2011 (defcustom org-outline-path-complete-in-steps t
2012 "Non-nil means complete the outline path in hierarchical steps.
2013 When Org-mode uses the refile interface to select an outline path
2014 \(see variable `org-refile-use-outline-path'), the completion of
2015 the path can be done is a single go, or if can be done in steps down
2016 the headline hierarchy. Going in steps is probably the best if you
2017 do not use a special completion package like `ido' or `icicles'.
2018 However, when using these packages, going in one step can be very
2019 fast, while still showing the whole path to the entry."
2020 :group 'org-refile
2021 :type 'boolean)
2023 (defcustom org-refile-allow-creating-parent-nodes nil
2024 "Non-nil means allow to create new nodes as refile targets.
2025 New nodes are then created by adding \"/new node name\" to the completion
2026 of an existing node. When the value of this variable is `confirm',
2027 new node creation must be confirmed by the user (recommended)
2028 When nil, the completion must match an existing entry.
2030 Note that, if the new heading is not seen by the criteria
2031 listed in `org-refile-targets', multiple instances of the same
2032 heading would be created by trying again to file under the new
2033 heading."
2034 :group 'org-refile
2035 :type '(choice
2036 (const :tag "Never" nil)
2037 (const :tag "Always" t)
2038 (const :tag "Prompt for confirmation" confirm)))
2040 (defcustom org-refile-active-region-within-subtree nil
2041 "Non-nil means also refile active region within a subtree.
2043 By default `org-refile' doesn't allow refiling regions if they
2044 don't contain a set of subtrees, but it might be convenient to
2045 do so sometimes: in that case, the first line of the region is
2046 converted to a headline before refiling."
2047 :group 'org-refile
2048 :version "24.1"
2049 :type 'boolean)
2051 (defgroup org-todo nil
2052 "Options concerning TODO items in Org-mode."
2053 :tag "Org TODO"
2054 :group 'org)
2056 (defgroup org-progress nil
2057 "Options concerning Progress logging in Org-mode."
2058 :tag "Org Progress"
2059 :group 'org-time)
2061 (defvar org-todo-interpretation-widgets
2062 '((:tag "Sequence (cycling hits every state)" sequence)
2063 (:tag "Type (cycling directly to DONE)" type))
2064 "The available interpretation symbols for customizing `org-todo-keywords'.
2065 Interested libraries should add to this list.")
2067 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2068 "List of TODO entry keyword sequences and their interpretation.
2069 \\<org-mode-map>This is a list of sequences.
2071 Each sequence starts with a symbol, either `sequence' or `type',
2072 indicating if the keywords should be interpreted as a sequence of
2073 action steps, or as different types of TODO items. The first
2074 keywords are states requiring action - these states will select a headline
2075 for inclusion into the global TODO list Org-mode produces. If one of
2076 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2077 signify that no further action is necessary. If \"|\" is not found,
2078 the last keyword is treated as the only DONE state of the sequence.
2080 The command \\[org-todo] cycles an entry through these states, and one
2081 additional state where no keyword is present. For details about this
2082 cycling, see the manual.
2084 TODO keywords and interpretation can also be set on a per-file basis with
2085 the special #+SEQ_TODO and #+TYP_TODO lines.
2087 Each keyword can optionally specify a character for fast state selection
2088 \(in combination with the variable `org-use-fast-todo-selection')
2089 and specifiers for state change logging, using the same syntax
2090 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
2091 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2092 indicates to record a time stamp each time this state is selected.
2094 Each keyword may also specify if a timestamp or a note should be
2095 recorded when entering or leaving the state, by adding additional
2096 characters in the parenthesis after the keyword. This looks like this:
2097 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2098 record only the time of the state change. With X and Y being either
2099 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2100 Y when leaving the state if and only if the *target* state does not
2101 define X. You may omit any of the fast-selection key or X or /Y,
2102 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2104 For backward compatibility, this variable may also be just a list
2105 of keywords - in this case the interpretation (sequence or type) will be
2106 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2107 :group 'org-todo
2108 :group 'org-keywords
2109 :type '(choice
2110 (repeat :tag "Old syntax, just keywords"
2111 (string :tag "Keyword"))
2112 (repeat :tag "New syntax"
2113 (cons
2114 (choice
2115 :tag "Interpretation"
2116 ;;Quick and dirty way to see
2117 ;;`org-todo-interpretations'. This takes the
2118 ;;place of item arguments
2119 :convert-widget
2120 (lambda (widget)
2121 (widget-put widget
2122 :args (mapcar
2123 #'(lambda (x)
2124 (widget-convert
2125 (cons 'const x)))
2126 org-todo-interpretation-widgets))
2127 widget))
2128 (repeat
2129 (string :tag "Keyword"))))))
2131 (defvar org-todo-keywords-1 nil
2132 "All TODO and DONE keywords active in a buffer.")
2133 (make-variable-buffer-local 'org-todo-keywords-1)
2134 (defvar org-todo-keywords-for-agenda nil)
2135 (defvar org-done-keywords-for-agenda nil)
2136 (defvar org-drawers-for-agenda nil)
2137 (defvar org-todo-keyword-alist-for-agenda nil)
2138 (defvar org-tag-alist-for-agenda nil)
2139 (defvar org-agenda-contributing-files nil)
2140 (defvar org-not-done-keywords nil)
2141 (make-variable-buffer-local 'org-not-done-keywords)
2142 (defvar org-done-keywords nil)
2143 (make-variable-buffer-local 'org-done-keywords)
2144 (defvar org-todo-heads nil)
2145 (make-variable-buffer-local 'org-todo-heads)
2146 (defvar org-todo-sets nil)
2147 (make-variable-buffer-local 'org-todo-sets)
2148 (defvar org-todo-log-states nil)
2149 (make-variable-buffer-local 'org-todo-log-states)
2150 (defvar org-todo-kwd-alist nil)
2151 (make-variable-buffer-local 'org-todo-kwd-alist)
2152 (defvar org-todo-key-alist nil)
2153 (make-variable-buffer-local 'org-todo-key-alist)
2154 (defvar org-todo-key-trigger nil)
2155 (make-variable-buffer-local 'org-todo-key-trigger)
2157 (defcustom org-todo-interpretation 'sequence
2158 "Controls how TODO keywords are interpreted.
2159 This variable is in principle obsolete and is only used for
2160 backward compatibility, if the interpretation of todo keywords is
2161 not given already in `org-todo-keywords'. See that variable for
2162 more information."
2163 :group 'org-todo
2164 :group 'org-keywords
2165 :type '(choice (const sequence)
2166 (const type)))
2168 (defcustom org-use-fast-todo-selection t
2169 "Non-nil means use the fast todo selection scheme with C-c C-t.
2170 This variable describes if and under what circumstances the cycling
2171 mechanism for TODO keywords will be replaced by a single-key, direct
2172 selection scheme.
2174 When nil, fast selection is never used.
2176 When the symbol `prefix', it will be used when `org-todo' is called with
2177 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
2178 in an agenda buffer.
2180 When t, fast selection is used by default. In this case, the prefix
2181 argument forces cycling instead.
2183 In all cases, the special interface is only used if access keys have actually
2184 been assigned by the user, i.e. if keywords in the configuration are followed
2185 by a letter in parenthesis, like TODO(t)."
2186 :group 'org-todo
2187 :type '(choice
2188 (const :tag "Never" nil)
2189 (const :tag "By default" t)
2190 (const :tag "Only with C-u C-c C-t" prefix)))
2192 (defcustom org-provide-todo-statistics t
2193 "Non-nil means update todo statistics after insert and toggle.
2194 ALL-HEADLINES means update todo statistics by including headlines
2195 with no TODO keyword as well, counting them as not done.
2196 A list of TODO keywords means the same, but skip keywords that are
2197 not in this list.
2199 When this is set, todo statistics is updated in the parent of the
2200 current entry each time a todo state is changed."
2201 :group 'org-todo
2202 :type '(choice
2203 (const :tag "Yes, only for TODO entries" t)
2204 (const :tag "Yes, including all entries" 'all-headlines)
2205 (repeat :tag "Yes, for TODOs in this list"
2206 (string :tag "TODO keyword"))
2207 (other :tag "No TODO statistics" nil)))
2209 (defcustom org-hierarchical-todo-statistics t
2210 "Non-nil means TODO statistics covers just direct children.
2211 When nil, all entries in the subtree are considered.
2212 This has only an effect if `org-provide-todo-statistics' is set.
2213 To set this to nil for only a single subtree, use a COOKIE_DATA
2214 property and include the word \"recursive\" into the value."
2215 :group 'org-todo
2216 :type 'boolean)
2218 (defcustom org-after-todo-state-change-hook nil
2219 "Hook which is run after the state of a TODO item was changed.
2220 The new state (a string with a TODO keyword, or nil) is available in the
2221 Lisp variable `org-state'."
2222 :group 'org-todo
2223 :type 'hook)
2225 (defvar org-blocker-hook nil
2226 "Hook for functions that are allowed to block a state change.
2228 Each function gets as its single argument a property list, see
2229 `org-trigger-hook' for more information about this list.
2231 If any of the functions in this hook returns nil, the state change
2232 is blocked.")
2234 (defvar org-trigger-hook nil
2235 "Hook for functions that are triggered by a state change.
2237 Each function gets as its single argument a property list with at least
2238 the following elements:
2240 (:type type-of-change :position pos-at-entry-start
2241 :from old-state :to new-state)
2243 Depending on the type, more properties may be present.
2245 This mechanism is currently implemented for:
2247 TODO state changes
2248 ------------------
2249 :type todo-state-change
2250 :from previous state (keyword as a string), or nil, or a symbol
2251 'todo' or 'done', to indicate the general type of state.
2252 :to new state, like in :from")
2254 (defcustom org-enforce-todo-dependencies nil
2255 "Non-nil means undone TODO entries will block switching the parent to DONE.
2256 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2257 be blocked if any prior sibling is not yet done.
2258 Finally, if the parent is blocked because of ordered siblings of its own,
2259 the child will also be blocked."
2260 :set (lambda (var val)
2261 (set var val)
2262 (if val
2263 (add-hook 'org-blocker-hook
2264 'org-block-todo-from-children-or-siblings-or-parent)
2265 (remove-hook 'org-blocker-hook
2266 'org-block-todo-from-children-or-siblings-or-parent)))
2267 :group 'org-todo
2268 :type 'boolean)
2270 (defcustom org-enforce-todo-checkbox-dependencies nil
2271 "Non-nil means unchecked boxes will block switching the parent to DONE.
2272 When this is nil, checkboxes have no influence on switching TODO states.
2273 When non-nil, you first need to check off all check boxes before the TODO
2274 entry can be switched to DONE.
2275 This variable needs to be set before org.el is loaded, and you need to
2276 restart Emacs after a change to make the change effective. The only way
2277 to change is while Emacs is running is through the customize interface."
2278 :set (lambda (var val)
2279 (set var val)
2280 (if val
2281 (add-hook 'org-blocker-hook
2282 'org-block-todo-from-checkboxes)
2283 (remove-hook 'org-blocker-hook
2284 'org-block-todo-from-checkboxes)))
2285 :group 'org-todo
2286 :type 'boolean)
2288 (defcustom org-treat-insert-todo-heading-as-state-change nil
2289 "Non-nil means inserting a TODO heading is treated as state change.
2290 So when the command \\[org-insert-todo-heading] is used, state change
2291 logging will apply if appropriate. When nil, the new TODO item will
2292 be inserted directly, and no logging will take place."
2293 :group 'org-todo
2294 :type 'boolean)
2296 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2297 "Non-nil means switching TODO states with S-cursor counts as state change.
2298 This is the default behavior. However, setting this to nil allows a
2299 convenient way to select a TODO state and bypass any logging associated
2300 with that."
2301 :group 'org-todo
2302 :type 'boolean)
2304 (defcustom org-todo-state-tags-triggers nil
2305 "Tag changes that should be triggered by TODO state changes.
2306 This is a list. Each entry is
2308 (state-change (tag . flag) .......)
2310 State-change can be a string with a state, and empty string to indicate the
2311 state that has no TODO keyword, or it can be one of the symbols `todo'
2312 or `done', meaning any not-done or done state, respectively."
2313 :group 'org-todo
2314 :group 'org-tags
2315 :type '(repeat
2316 (cons (choice :tag "When changing to"
2317 (const :tag "Not-done state" todo)
2318 (const :tag "Done state" done)
2319 (string :tag "State"))
2320 (repeat
2321 (cons :tag "Tag action"
2322 (string :tag "Tag")
2323 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2325 (defcustom org-log-done nil
2326 "Information to record when a task moves to the DONE state.
2328 Possible values are:
2330 nil Don't add anything, just change the keyword
2331 time Add a time stamp to the task
2332 note Prompt for a note and add it with template `org-log-note-headings'
2334 This option can also be set with on a per-file-basis with
2336 #+STARTUP: nologdone
2337 #+STARTUP: logdone
2338 #+STARTUP: lognotedone
2340 You can have local logging settings for a subtree by setting the LOGGING
2341 property to one or more of these keywords."
2342 :group 'org-todo
2343 :group 'org-progress
2344 :type '(choice
2345 (const :tag "No logging" nil)
2346 (const :tag "Record CLOSED timestamp" time)
2347 (const :tag "Record CLOSED timestamp with note." note)))
2349 ;; Normalize old uses of org-log-done.
2350 (cond
2351 ((eq org-log-done t) (setq org-log-done 'time))
2352 ((and (listp org-log-done) (memq 'done org-log-done))
2353 (setq org-log-done 'note)))
2355 (defcustom org-log-reschedule nil
2356 "Information to record when the scheduling date of a tasks is modified.
2358 Possible values are:
2360 nil Don't add anything, just change the date
2361 time Add a time stamp to the task
2362 note Prompt for a note and add it with template `org-log-note-headings'
2364 This option can also be set with on a per-file-basis with
2366 #+STARTUP: nologreschedule
2367 #+STARTUP: logreschedule
2368 #+STARTUP: lognotereschedule"
2369 :group 'org-todo
2370 :group 'org-progress
2371 :type '(choice
2372 (const :tag "No logging" nil)
2373 (const :tag "Record timestamp" time)
2374 (const :tag "Record timestamp with note." note)))
2376 (defcustom org-log-redeadline nil
2377 "Information to record when the deadline date of a tasks is modified.
2379 Possible values are:
2381 nil Don't add anything, just change the date
2382 time Add a time stamp to the task
2383 note Prompt for a note and add it with template `org-log-note-headings'
2385 This option can also be set with on a per-file-basis with
2387 #+STARTUP: nologredeadline
2388 #+STARTUP: logredeadline
2389 #+STARTUP: lognoteredeadline
2391 You can have local logging settings for a subtree by setting the LOGGING
2392 property to one or more of these keywords."
2393 :group 'org-todo
2394 :group 'org-progress
2395 :type '(choice
2396 (const :tag "No logging" nil)
2397 (const :tag "Record timestamp" time)
2398 (const :tag "Record timestamp with note." note)))
2400 (defcustom org-log-note-clock-out nil
2401 "Non-nil means record a note when clocking out of an item.
2402 This can also be configured on a per-file basis by adding one of
2403 the following lines anywhere in the buffer:
2405 #+STARTUP: lognoteclock-out
2406 #+STARTUP: nolognoteclock-out"
2407 :group 'org-todo
2408 :group 'org-progress
2409 :type 'boolean)
2411 (defcustom org-log-done-with-time t
2412 "Non-nil means the CLOSED time stamp will contain date and time.
2413 When nil, only the date will be recorded."
2414 :group 'org-progress
2415 :type 'boolean)
2417 (defcustom org-log-note-headings
2418 '((done . "CLOSING NOTE %t")
2419 (state . "State %-12s from %-12S %t")
2420 (note . "Note taken on %t")
2421 (reschedule . "Rescheduled from %S on %t")
2422 (delschedule . "Not scheduled, was %S on %t")
2423 (redeadline . "New deadline from %S on %t")
2424 (deldeadline . "Removed deadline, was %S on %t")
2425 (refile . "Refiled on %t")
2426 (clock-out . ""))
2427 "Headings for notes added to entries.
2428 The value is an alist, with the car being a symbol indicating the note
2429 context, and the cdr is the heading to be used. The heading may also be the
2430 empty string.
2431 %t in the heading will be replaced by a time stamp.
2432 %T will be an active time stamp instead the default inactive one
2433 %d will be replaced by a short-format time stamp.
2434 %D will be replaced by an active short-format time stamp.
2435 %s will be replaced by the new TODO state, in double quotes.
2436 %S will be replaced by the old TODO state, in double quotes.
2437 %u will be replaced by the user name.
2438 %U will be replaced by the full user name.
2440 In fact, it is not a good idea to change the `state' entry, because
2441 agenda log mode depends on the format of these entries."
2442 :group 'org-todo
2443 :group 'org-progress
2444 :type '(list :greedy t
2445 (cons (const :tag "Heading when closing an item" done) string)
2446 (cons (const :tag
2447 "Heading when changing todo state (todo sequence only)"
2448 state) string)
2449 (cons (const :tag "Heading when just taking a note" note) string)
2450 (cons (const :tag "Heading when clocking out" clock-out) string)
2451 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2452 (cons (const :tag "Heading when rescheduling" reschedule) string)
2453 (cons (const :tag "Heading when changing deadline" redeadline) string)
2454 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2455 (cons (const :tag "Heading when refiling" refile) string)))
2457 (unless (assq 'note org-log-note-headings)
2458 (push '(note . "%t") org-log-note-headings))
2460 (defcustom org-log-into-drawer nil
2461 "Non-nil means insert state change notes and time stamps into a drawer.
2462 When nil, state changes notes will be inserted after the headline and
2463 any scheduling and clock lines, but not inside a drawer.
2465 The value of this variable should be the name of the drawer to use.
2466 LOGBOOK is proposed as the default drawer for this purpose, you can
2467 also set this to a string to define the drawer of your choice.
2469 A value of t is also allowed, representing \"LOGBOOK\".
2471 If this variable is set, `org-log-state-notes-insert-after-drawers'
2472 will be ignored.
2474 You can set the property LOG_INTO_DRAWER to overrule this setting for
2475 a subtree."
2476 :group 'org-todo
2477 :group 'org-progress
2478 :type '(choice
2479 (const :tag "Not into a drawer" nil)
2480 (const :tag "LOGBOOK" t)
2481 (string :tag "Other")))
2483 (if (fboundp 'defvaralias)
2484 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2486 (defun org-log-into-drawer ()
2487 "Return the value of `org-log-into-drawer', but let properties overrule.
2488 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2489 used instead of the default value."
2490 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit)))
2491 (cond
2492 ((or (not p) (equal p "nil")) org-log-into-drawer)
2493 ((equal p "t") "LOGBOOK")
2494 (t p))))
2496 (defcustom org-log-state-notes-insert-after-drawers nil
2497 "Non-nil means insert state change notes after any drawers in entry.
2498 Only the drawers that *immediately* follow the headline and the
2499 deadline/scheduled line are skipped.
2500 When nil, insert notes right after the heading and perhaps the line
2501 with deadline/scheduling if present.
2503 This variable will have no effect if `org-log-into-drawer' is
2504 set."
2505 :group 'org-todo
2506 :group 'org-progress
2507 :type 'boolean)
2509 (defcustom org-log-states-order-reversed t
2510 "Non-nil means the latest state note will be directly after heading.
2511 When nil, the state change notes will be ordered according to time."
2512 :group 'org-todo
2513 :group 'org-progress
2514 :type 'boolean)
2516 (defcustom org-todo-repeat-to-state nil
2517 "The TODO state to which a repeater should return the repeating task.
2518 By default this is the first task in a TODO sequence, or the previous state
2519 in a TODO_TYP set. But you can specify another task here.
2520 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2521 :group 'org-todo
2522 :version "24.1"
2523 :type '(choice (const :tag "Head of sequence" nil)
2524 (string :tag "Specific state")))
2526 (defcustom org-log-repeat 'time
2527 "Non-nil means record moving through the DONE state when triggering repeat.
2528 An auto-repeating task is immediately switched back to TODO when
2529 marked DONE. If you are not logging state changes (by adding \"@\"
2530 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2531 record a closing note, there will be no record of the task moving
2532 through DONE. This variable forces taking a note anyway.
2534 nil Don't force a record
2535 time Record a time stamp
2536 note Record a note
2538 This option can also be set with on a per-file-basis with
2540 #+STARTUP: logrepeat
2541 #+STARTUP: lognoterepeat
2542 #+STARTUP: nologrepeat
2544 You can have local logging settings for a subtree by setting the LOGGING
2545 property to one or more of these keywords."
2546 :group 'org-todo
2547 :group 'org-progress
2548 :type '(choice
2549 (const :tag "Don't force a record" nil)
2550 (const :tag "Force recording the DONE state" time)
2551 (const :tag "Force recording a note with the DONE state" note)))
2554 (defgroup org-priorities nil
2555 "Priorities in Org-mode."
2556 :tag "Org Priorities"
2557 :group 'org-todo)
2559 (defcustom org-enable-priority-commands t
2560 "Non-nil means priority commands are active.
2561 When nil, these commands will be disabled, so that you never accidentally
2562 set a priority."
2563 :group 'org-priorities
2564 :type 'boolean)
2566 (defcustom org-highest-priority ?A
2567 "The highest priority of TODO items. A character like ?A, ?B etc.
2568 Must have a smaller ASCII number than `org-lowest-priority'."
2569 :group 'org-priorities
2570 :type 'character)
2572 (defcustom org-lowest-priority ?C
2573 "The lowest priority of TODO items. A character like ?A, ?B etc.
2574 Must have a larger ASCII number than `org-highest-priority'."
2575 :group 'org-priorities
2576 :type 'character)
2578 (defcustom org-default-priority ?B
2579 "The default priority of TODO items.
2580 This is the priority an item gets if no explicit priority is given.
2581 When starting to cycle on an empty priority the first step in the cycle
2582 depends on `org-priority-start-cycle-with-default'. The resulting first
2583 step priority must not exceed the range from `org-highest-priority' to
2584 `org-lowest-priority' which means that `org-default-priority' has to be
2585 in this range exclusive or inclusive the range boundaries. Else the
2586 first step refuses to set the default and the second will fall back
2587 to (depending on the command used) the highest or lowest priority."
2588 :group 'org-priorities
2589 :type 'character)
2591 (defcustom org-priority-start-cycle-with-default t
2592 "Non-nil means start with default priority when starting to cycle.
2593 When this is nil, the first step in the cycle will be (depending on the
2594 command used) one higher or lower than the default priority.
2595 See also `org-default-priority'."
2596 :group 'org-priorities
2597 :type 'boolean)
2599 (defcustom org-get-priority-function nil
2600 "Function to extract the priority from a string.
2601 The string is normally the headline. If this is nil Org computes the
2602 priority from the priority cookie like [#A] in the headline. It returns
2603 an integer, increasing by 1000 for each priority level.
2604 The user can set a different function here, which should take a string
2605 as an argument and return the numeric priority."
2606 :group 'org-priorities
2607 :version "24.1"
2608 :type 'function)
2610 (defgroup org-time nil
2611 "Options concerning time stamps and deadlines in Org-mode."
2612 :tag "Org Time"
2613 :group 'org)
2615 (defcustom org-insert-labeled-timestamps-at-point nil
2616 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2617 When nil, these labeled time stamps are forces into the second line of an
2618 entry, just after the headline. When scheduling from the global TODO list,
2619 the time stamp will always be forced into the second line."
2620 :group 'org-time
2621 :type 'boolean)
2623 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2624 "Formats for `format-time-string' which are used for time stamps.
2625 It is not recommended to change this constant.")
2627 (defcustom org-time-stamp-rounding-minutes '(0 5)
2628 "Number of minutes to round time stamps to.
2629 These are two values, the first applies when first creating a time stamp.
2630 The second applies when changing it with the commands `S-up' and `S-down'.
2631 When changing the time stamp, this means that it will change in steps
2632 of N minutes, as given by the second value.
2634 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2635 numbers should be factors of 60, so for example 5, 10, 15.
2637 When this is larger than 1, you can still force an exact time stamp by using
2638 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2639 and by using a prefix arg to `S-up/down' to specify the exact number
2640 of minutes to shift."
2641 :group 'org-time
2642 :get #'(lambda (var) ; Make sure both elements are there
2643 (if (integerp (default-value var))
2644 (list (default-value var) 5)
2645 (default-value var)))
2646 :type '(list
2647 (integer :tag "when inserting times")
2648 (integer :tag "when modifying times")))
2650 ;; Normalize old customizations of this variable.
2651 (when (integerp org-time-stamp-rounding-minutes)
2652 (setq org-time-stamp-rounding-minutes
2653 (list org-time-stamp-rounding-minutes
2654 org-time-stamp-rounding-minutes)))
2656 (defcustom org-display-custom-times nil
2657 "Non-nil means overlay custom formats over all time stamps.
2658 The formats are defined through the variable `org-time-stamp-custom-formats'.
2659 To turn this on on a per-file basis, insert anywhere in the file:
2660 #+STARTUP: customtime"
2661 :group 'org-time
2662 :set 'set-default
2663 :type 'sexp)
2664 (make-variable-buffer-local 'org-display-custom-times)
2666 (defcustom org-time-stamp-custom-formats
2667 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2668 "Custom formats for time stamps. See `format-time-string' for the syntax.
2669 These are overlaid over the default ISO format if the variable
2670 `org-display-custom-times' is set. Time like %H:%M should be at the
2671 end of the second format. The custom formats are also honored by export
2672 commands, if custom time display is turned on at the time of export."
2673 :group 'org-time
2674 :type 'sexp)
2676 (defun org-time-stamp-format (&optional long inactive)
2677 "Get the right format for a time string."
2678 (let ((f (if long (cdr org-time-stamp-formats)
2679 (car org-time-stamp-formats))))
2680 (if inactive
2681 (concat "[" (substring f 1 -1) "]")
2682 f)))
2684 (defcustom org-time-clocksum-format "%d:%02d"
2685 "The format string used when creating CLOCKSUM lines.
2686 This is also used when org-mode generates a time duration."
2687 :group 'org-time
2688 :type 'string)
2690 (defcustom org-time-clocksum-use-fractional nil
2691 "If non-nil, \\[org-clock-display] uses fractional times.
2692 org-mode generates a time duration."
2693 :group 'org-time
2694 :type 'boolean)
2696 (defcustom org-time-clocksum-fractional-format "%.2f"
2697 "The format string used when creating CLOCKSUM lines, or when
2698 org-mode generates a time duration."
2699 :group 'org-time
2700 :type 'string)
2702 (defcustom org-deadline-warning-days 14
2703 "No. of days before expiration during which a deadline becomes active.
2704 This variable governs the display in sparse trees and in the agenda.
2705 When 0 or negative, it means use this number (the absolute value of it)
2706 even if a deadline has a different individual lead time specified.
2708 Custom commands can set this variable in the options section."
2709 :group 'org-time
2710 :group 'org-agenda-daily/weekly
2711 :type 'integer)
2713 (defcustom org-read-date-prefer-future t
2714 "Non-nil means assume future for incomplete date input from user.
2715 This affects the following situations:
2716 1. The user gives a month but not a year.
2717 For example, if it is April and you enter \"feb 2\", this will be read
2718 as Feb 2, *next* year. \"May 5\", however, will be this year.
2719 2. The user gives a day, but no month.
2720 For example, if today is the 15th, and you enter \"3\", Org-mode will
2721 read this as the third of *next* month. However, if you enter \"17\",
2722 it will be considered as *this* month.
2724 If you set this variable to the symbol `time', then also the following
2725 will work:
2727 3. If the user gives a time, but no day. If the time is before now,
2728 to will be interpreted as tomorrow.
2730 Currently none of this works for ISO week specifications.
2732 When this option is nil, the current day, month and year will always be
2733 used as defaults.
2735 See also `org-agenda-jump-prefer-future'."
2736 :group 'org-time
2737 :type '(choice
2738 (const :tag "Never" nil)
2739 (const :tag "Check month and day" t)
2740 (const :tag "Check month, day, and time" time)))
2742 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
2743 "Should the agenda jump command prefer the future for incomplete dates?
2744 The default is to do the same as configured in `org-read-date-prefer-future'.
2745 But you can also set a deviating value here.
2746 This may t or nil, or the symbol `org-read-date-prefer-future'."
2747 :group 'org-agenda
2748 :group 'org-time
2749 :version "24.1"
2750 :type '(choice
2751 (const :tag "Use org-read-date-prefer-future"
2752 org-read-date-prefer-future)
2753 (const :tag "Never" nil)
2754 (const :tag "Always" t)))
2756 (defcustom org-read-date-force-compatible-dates t
2757 "Should date/time prompt force dates that are guaranteed to work in Emacs?
2759 Depending on the system Emacs is running on, certain dates cannot
2760 be represented with the type used internally to represent time.
2761 Dates between 1970-1-1 and 2038-1-1 can always be represented
2762 correctly. Some systems allow for earlier dates, some for later,
2763 some for both. One way to find out it to insert any date into an
2764 Org buffer, putting the cursor on the year and hitting S-up and
2765 S-down to test the range.
2767 When this variable is set to t, the date/time prompt will not let
2768 you specify dates outside the 1970-2037 range, so it is certain that
2769 these dates will work in whatever version of Emacs you are
2770 running, and also that you can move a file from one Emacs implementation
2771 to another. WHenever Org is forcing the year for you, it will display
2772 a message and beep.
2774 When this variable is nil, Org will check if the date is
2775 representable in the specific Emacs implementation you are using.
2776 If not, it will force a year, usually the current year, and beep
2777 to remind you. Currently this setting is not recommended because
2778 the likelihood that you will open your Org files in an Emacs that
2779 has limited date range is not negligible.
2781 A workaround for this problem is to use diary sexp dates for time
2782 stamps outside of this range."
2783 :group 'org-time
2784 :version "24.1"
2785 :type 'boolean)
2787 (defcustom org-read-date-display-live t
2788 "Non-nil means display current interpretation of date prompt live.
2789 This display will be in an overlay, in the minibuffer."
2790 :group 'org-time
2791 :type 'boolean)
2793 (defcustom org-read-date-popup-calendar t
2794 "Non-nil means pop up a calendar when prompting for a date.
2795 In the calendar, the date can be selected with mouse-1. However, the
2796 minibuffer will also be active, and you can simply enter the date as well.
2797 When nil, only the minibuffer will be available."
2798 :group 'org-time
2799 :type 'boolean)
2800 (if (fboundp 'defvaralias)
2801 (defvaralias 'org-popup-calendar-for-date-prompt
2802 'org-read-date-popup-calendar))
2804 (defcustom org-read-date-minibuffer-setup-hook nil
2805 "Hook to be used to set up keys for the date/time interface.
2806 Add key definitions to `minibuffer-local-map', which will be a temporary
2807 copy."
2808 :group 'org-time
2809 :type 'hook)
2811 (defcustom org-extend-today-until 0
2812 "The hour when your day really ends. Must be an integer.
2813 This has influence for the following applications:
2814 - When switching the agenda to \"today\". It it is still earlier than
2815 the time given here, the day recognized as TODAY is actually yesterday.
2816 - When a date is read from the user and it is still before the time given
2817 here, the current date and time will be assumed to be yesterday, 23:59.
2818 Also, timestamps inserted in remember templates follow this rule.
2820 IMPORTANT: This is a feature whose implementation is and likely will
2821 remain incomplete. Really, it is only here because past midnight seems to
2822 be the favorite working time of John Wiegley :-)"
2823 :group 'org-time
2824 :type 'integer)
2826 (defcustom org-use-effective-time nil
2827 "If non-nil, consider `org-extend-today-until' when creating timestamps.
2828 For example, if `org-extend-today-until' is 8, and it's 4am, then the
2829 \"effective time\" of any timestamps between midnight and 8am will be
2830 23:59 of the previous day."
2831 :group 'org-time
2832 :version "24.1"
2833 :type 'boolean)
2835 (defcustom org-edit-timestamp-down-means-later nil
2836 "Non-nil means S-down will increase the time in a time stamp.
2837 When nil, S-up will increase."
2838 :group 'org-time
2839 :type 'boolean)
2841 (defcustom org-calendar-follow-timestamp-change t
2842 "Non-nil means make the calendar window follow timestamp changes.
2843 When a timestamp is modified and the calendar window is visible, it will be
2844 moved to the new date."
2845 :group 'org-time
2846 :type 'boolean)
2848 (defgroup org-tags nil
2849 "Options concerning tags in Org-mode."
2850 :tag "Org Tags"
2851 :group 'org)
2853 (defcustom org-tag-alist nil
2854 "List of tags allowed in Org-mode files.
2855 When this list is nil, Org-mode will base TAG input on what is already in the
2856 buffer.
2857 The value of this variable is an alist, the car of each entry must be a
2858 keyword as a string, the cdr may be a character that is used to select
2859 that tag through the fast-tag-selection interface.
2860 See the manual for details."
2861 :group 'org-tags
2862 :type '(repeat
2863 (choice
2864 (cons (string :tag "Tag name")
2865 (character :tag "Access char"))
2866 (list :tag "Start radio group"
2867 (const :startgroup)
2868 (option (string :tag "Group description")))
2869 (list :tag "End radio group"
2870 (const :endgroup)
2871 (option (string :tag "Group description")))
2872 (const :tag "New line" (:newline)))))
2874 (defcustom org-tag-persistent-alist nil
2875 "List of tags that will always appear in all Org-mode files.
2876 This is in addition to any in buffer settings or customizations
2877 of `org-tag-alist'.
2878 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2879 The value of this variable is an alist, the car of each entry must be a
2880 keyword as a string, the cdr may be a character that is used to select
2881 that tag through the fast-tag-selection interface.
2882 See the manual for details.
2883 To disable these tags on a per-file basis, insert anywhere in the file:
2884 #+STARTUP: noptag"
2885 :group 'org-tags
2886 :type '(repeat
2887 (choice
2888 (cons (string :tag "Tag name")
2889 (character :tag "Access char"))
2890 (const :tag "Start radio group" (:startgroup))
2891 (const :tag "End radio group" (:endgroup))
2892 (const :tag "New line" (:newline)))))
2894 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
2895 "If non-nil, always offer completion for all tags of all agenda files.
2896 Instead of customizing this variable directly, you might want to
2897 set it locally for capture buffers, because there no list of
2898 tags in that file can be created dynamically (there are none).
2900 (add-hook 'org-capture-mode-hook
2901 (lambda ()
2902 (set (make-local-variable
2903 'org-complete-tags-always-offer-all-agenda-tags)
2904 t)))"
2905 :group 'org-tags
2906 :version "24.1"
2907 :type 'boolean)
2909 (defvar org-file-tags nil
2910 "List of tags that can be inherited by all entries in the file.
2911 The tags will be inherited if the variable `org-use-tag-inheritance'
2912 says they should be.
2913 This variable is populated from #+FILETAGS lines.")
2915 (defcustom org-use-fast-tag-selection 'auto
2916 "Non-nil means use fast tag selection scheme.
2917 This is a special interface to select and deselect tags with single keys.
2918 When nil, fast selection is never used.
2919 When the symbol `auto', fast selection is used if and only if selection
2920 characters for tags have been configured, either through the variable
2921 `org-tag-alist' or through a #+TAGS line in the buffer.
2922 When t, fast selection is always used and selection keys are assigned
2923 automatically if necessary."
2924 :group 'org-tags
2925 :type '(choice
2926 (const :tag "Always" t)
2927 (const :tag "Never" nil)
2928 (const :tag "When selection characters are configured" 'auto)))
2930 (defcustom org-fast-tag-selection-single-key nil
2931 "Non-nil means fast tag selection exits after first change.
2932 When nil, you have to press RET to exit it.
2933 During fast tag selection, you can toggle this flag with `C-c'.
2934 This variable can also have the value `expert'. In this case, the window
2935 displaying the tags menu is not even shown, until you press C-c again."
2936 :group 'org-tags
2937 :type '(choice
2938 (const :tag "No" nil)
2939 (const :tag "Yes" t)
2940 (const :tag "Expert" expert)))
2942 (defvar org-fast-tag-selection-include-todo nil
2943 "Non-nil means fast tags selection interface will also offer TODO states.
2944 This is an undocumented feature, you should not rely on it.")
2946 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2947 "The column to which tags should be indented in a headline.
2948 If this number is positive, it specifies the column. If it is negative,
2949 it means that the tags should be flushright to that column. For example,
2950 -80 works well for a normal 80 character screen.
2951 When 0, place tags directly after headline text, with only one space in
2952 between."
2953 :group 'org-tags
2954 :type 'integer)
2956 (defcustom org-auto-align-tags t
2957 "Non-nil keeps tags aligned when modifying headlines.
2958 Some operations (i.e. demoting) change the length of a headline and
2959 therefore shift the tags around. With this option turned on, after
2960 each such operation the tags are again aligned to `org-tags-column'."
2961 :group 'org-tags
2962 :type 'boolean)
2964 (defcustom org-use-tag-inheritance t
2965 "Non-nil means tags in levels apply also for sublevels.
2966 When nil, only the tags directly given in a specific line apply there.
2967 This may also be a list of tags that should be inherited, or a regexp that
2968 matches tags that should be inherited. Additional control is possible
2969 with the variable `org-tags-exclude-from-inheritance' which gives an
2970 explicit list of tags to be excluded from inheritance., even if the value of
2971 `org-use-tag-inheritance' would select it for inheritance.
2973 If this option is t, a match early-on in a tree can lead to a large
2974 number of matches in the subtree when constructing the agenda or creating
2975 a sparse tree. If you only want to see the first match in a tree during
2976 a search, check out the variable `org-tags-match-list-sublevels'."
2977 :group 'org-tags
2978 :type '(choice
2979 (const :tag "Not" nil)
2980 (const :tag "Always" t)
2981 (repeat :tag "Specific tags" (string :tag "Tag"))
2982 (regexp :tag "Tags matched by regexp")))
2984 (defcustom org-tags-exclude-from-inheritance nil
2985 "List of tags that should never be inherited.
2986 This is a way to exclude a few tags from inheritance. For way to do
2987 the opposite, to actively allow inheritance for selected tags,
2988 see the variable `org-use-tag-inheritance'."
2989 :group 'org-tags
2990 :type '(repeat (string :tag "Tag")))
2992 (defun org-tag-inherit-p (tag)
2993 "Check if TAG is one that should be inherited."
2994 (cond
2995 ((member tag org-tags-exclude-from-inheritance) nil)
2996 ((eq org-use-tag-inheritance t) t)
2997 ((not org-use-tag-inheritance) nil)
2998 ((stringp org-use-tag-inheritance)
2999 (string-match org-use-tag-inheritance tag))
3000 ((listp org-use-tag-inheritance)
3001 (member tag org-use-tag-inheritance))
3002 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3004 (defcustom org-tags-match-list-sublevels t
3005 "Non-nil means list also sublevels of headlines matching a search.
3006 This variable applies to tags/property searches, and also to stuck
3007 projects because this search is based on a tags match as well.
3009 When set to the symbol `indented', sublevels are indented with
3010 leading dots.
3012 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3013 the sublevels of a headline matching a tag search often also match
3014 the same search. Listing all of them can create very long lists.
3015 Setting this variable to nil causes subtrees of a match to be skipped.
3017 This variable is semi-obsolete and probably should always be true. It
3018 is better to limit inheritance to certain tags using the variables
3019 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3020 :group 'org-tags
3021 :type '(choice
3022 (const :tag "No, don't list them" nil)
3023 (const :tag "Yes, do list them" t)
3024 (const :tag "List them, indented with leading dots" indented)))
3026 (defcustom org-tags-sort-function nil
3027 "When set, tags are sorted using this function as a comparator."
3028 :group 'org-tags
3029 :type '(choice
3030 (const :tag "No sorting" nil)
3031 (const :tag "Alphabetical" string<)
3032 (const :tag "Reverse alphabetical" string>)
3033 (function :tag "Custom function" nil)))
3035 (defvar org-tags-history nil
3036 "History of minibuffer reads for tags.")
3037 (defvar org-last-tags-completion-table nil
3038 "The last used completion table for tags.")
3039 (defvar org-after-tags-change-hook nil
3040 "Hook that is run after the tags in a line have changed.")
3042 (defgroup org-properties nil
3043 "Options concerning properties in Org-mode."
3044 :tag "Org Properties"
3045 :group 'org)
3047 (defcustom org-property-format "%-10s %s"
3048 "How property key/value pairs should be formatted by `indent-line'.
3049 When `indent-line' hits a property definition, it will format the line
3050 according to this format, mainly to make sure that the values are
3051 lined-up with respect to each other."
3052 :group 'org-properties
3053 :type 'string)
3055 (defcustom org-properties-postprocess-alist nil
3056 "Alist of properties and functions to adjust inserted values.
3057 Elements of this alist must be of the form
3059 ([string] [function])
3061 where [string] must be a property name and [function] must be a
3062 lambda expression: this lambda expression must take one argument,
3063 the value to adjust, and return the new value as a string.
3065 For example, this element will allow the property \"Remaining\"
3066 to be updated wrt the relation between the \"Effort\" property
3067 and the clock summary:
3069 ((\"Remaining\" (lambda(value)
3070 (let ((clocksum (org-clock-sum-current-item))
3071 (effort (org-duration-string-to-minutes
3072 (org-entry-get (point) \"Effort\"))))
3073 (org-minutes-to-hh:mm-string (- effort clocksum))))))"
3074 :group 'org-properties
3075 :version "24.1"
3076 :type 'alist)
3078 (defcustom org-use-property-inheritance nil
3079 "Non-nil means properties apply also for sublevels.
3081 This setting is chiefly used during property searches. Turning it on can
3082 cause significant overhead when doing a search, which is why it is not
3083 on by default.
3085 When nil, only the properties directly given in the current entry count.
3086 When t, every property is inherited. The value may also be a list of
3087 properties that should have inheritance, or a regular expression matching
3088 properties that should be inherited.
3090 However, note that some special properties use inheritance under special
3091 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3092 and the properties ending in \"_ALL\" when they are used as descriptor
3093 for valid values of a property.
3095 Note for programmers:
3096 When querying an entry with `org-entry-get', you can control if inheritance
3097 should be used. By default, `org-entry-get' looks only at the local
3098 properties. You can request inheritance by setting the inherit argument
3099 to t (to force inheritance) or to `selective' (to respect the setting
3100 in this variable)."
3101 :group 'org-properties
3102 :type '(choice
3103 (const :tag "Not" nil)
3104 (const :tag "Always" t)
3105 (repeat :tag "Specific properties" (string :tag "Property"))
3106 (regexp :tag "Properties matched by regexp")))
3108 (defun org-property-inherit-p (property)
3109 "Check if PROPERTY is one that should be inherited."
3110 (cond
3111 ((eq org-use-property-inheritance t) t)
3112 ((not org-use-property-inheritance) nil)
3113 ((stringp org-use-property-inheritance)
3114 (string-match org-use-property-inheritance property))
3115 ((listp org-use-property-inheritance)
3116 (member property org-use-property-inheritance))
3117 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3119 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3120 "The default column format, if no other format has been defined.
3121 This variable can be set on the per-file basis by inserting a line
3123 #+COLUMNS: %25ITEM ....."
3124 :group 'org-properties
3125 :type 'string)
3127 (defcustom org-columns-ellipses ".."
3128 "The ellipses to be used when a field in column view is truncated.
3129 When this is the empty string, as many characters as possible are shown,
3130 but then there will be no visual indication that the field has been truncated.
3131 When this is a string of length N, the last N characters of a truncated
3132 field are replaced by this string. If the column is narrower than the
3133 ellipses string, only part of the ellipses string will be shown."
3134 :group 'org-properties
3135 :type 'string)
3137 (defcustom org-columns-modify-value-for-display-function nil
3138 "Function that modifies values for display in column view.
3139 For example, it can be used to cut out a certain part from a time stamp.
3140 The function must take 2 arguments:
3142 column-title The title of the column (*not* the property name)
3143 value The value that should be modified.
3145 The function should return the value that should be displayed,
3146 or nil if the normal value should be used."
3147 :group 'org-properties
3148 :type 'function)
3150 (defcustom org-effort-property "Effort"
3151 "The property that is being used to keep track of effort estimates.
3152 Effort estimates given in this property need to have the format H:MM."
3153 :group 'org-properties
3154 :group 'org-progress
3155 :type '(string :tag "Property"))
3157 (defconst org-global-properties-fixed
3158 '(("VISIBILITY_ALL" . "folded children content all")
3159 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3160 "List of property/value pairs that can be inherited by any entry.
3162 These are fixed values, for the preset properties. The user variable
3163 that can be used to add to this list is `org-global-properties'.
3165 The entries in this list are cons cells where the car is a property
3166 name and cdr is a string with the value. If the value represents
3167 multiple items like an \"_ALL\" property, separate the items by
3168 spaces.")
3170 (defcustom org-global-properties nil
3171 "List of property/value pairs that can be inherited by any entry.
3173 This list will be combined with the constant `org-global-properties-fixed'.
3175 The entries in this list are cons cells where the car is a property
3176 name and cdr is a string with the value.
3178 You can set buffer-local values for the same purpose in the variable
3179 `org-file-properties' this by adding lines like
3181 #+PROPERTY: NAME VALUE"
3182 :group 'org-properties
3183 :type '(repeat
3184 (cons (string :tag "Property")
3185 (string :tag "Value"))))
3187 (defvar org-file-properties nil
3188 "List of property/value pairs that can be inherited by any entry.
3189 Valid for the current buffer.
3190 This variable is populated from #+PROPERTY lines.")
3191 (make-variable-buffer-local 'org-file-properties)
3193 (defgroup org-agenda nil
3194 "Options concerning agenda views in Org-mode."
3195 :tag "Org Agenda"
3196 :group 'org)
3198 (defvar org-category nil
3199 "Variable used by org files to set a category for agenda display.
3200 Such files should use a file variable to set it, for example
3202 # -*- mode: org; org-category: \"ELisp\"
3204 or contain a special line
3206 #+CATEGORY: ELisp
3208 If the file does not specify a category, then file's base name
3209 is used instead.")
3210 (make-variable-buffer-local 'org-category)
3211 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3213 (defcustom org-agenda-files nil
3214 "The files to be used for agenda display.
3215 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3216 \\[org-remove-file]. You can also use customize to edit the list.
3218 If an entry is a directory, all files in that directory that are matched by
3219 `org-agenda-file-regexp' will be part of the file list.
3221 If the value of the variable is not a list but a single file name, then
3222 the list of agenda files is actually stored and maintained in that file, one
3223 agenda file per line. In this file paths can be given relative to
3224 `org-directory'. Tilde expansion and environment variable substitution
3225 are also made."
3226 :group 'org-agenda
3227 :type '(choice
3228 (repeat :tag "List of files and directories" file)
3229 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3231 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3232 "Regular expression to match files for `org-agenda-files'.
3233 If any element in the list in that variable contains a directory instead
3234 of a normal file, all files in that directory that are matched by this
3235 regular expression will be included."
3236 :group 'org-agenda
3237 :type 'regexp)
3239 (defcustom org-agenda-text-search-extra-files nil
3240 "List of extra files to be searched by text search commands.
3241 These files will be search in addition to the agenda files by the
3242 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3243 Note that these files will only be searched for text search commands,
3244 not for the other agenda views like todo lists, tag searches or the weekly
3245 agenda. This variable is intended to list notes and possibly archive files
3246 that should also be searched by these two commands.
3247 In fact, if the first element in the list is the symbol `agenda-archives',
3248 than all archive files of all agenda files will be added to the search
3249 scope."
3250 :group 'org-agenda
3251 :type '(set :greedy t
3252 (const :tag "Agenda Archives" agenda-archives)
3253 (repeat :inline t (file))))
3255 (if (fboundp 'defvaralias)
3256 (defvaralias 'org-agenda-multi-occur-extra-files
3257 'org-agenda-text-search-extra-files))
3259 (defcustom org-agenda-skip-unavailable-files nil
3260 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3261 A nil value means to remove them, after a query, from the list."
3262 :group 'org-agenda
3263 :type 'boolean)
3265 (defcustom org-calendar-to-agenda-key [?c]
3266 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3267 The command `org-calendar-goto-agenda' will be bound to this key. The
3268 default is the character `c' because then `c' can be used to switch back and
3269 forth between agenda and calendar."
3270 :group 'org-agenda
3271 :type 'sexp)
3273 (defcustom org-calendar-agenda-action-key [?k]
3274 "The key to be installed in `calendar-mode-map' for agenda-action.
3275 The command `org-agenda-action' will be bound to this key. The
3276 default is the character `k' because we use the same key in the agenda."
3277 :group 'org-agenda
3278 :type 'sexp)
3280 (defcustom org-calendar-insert-diary-entry-key [?i]
3281 "The key to be installed in `calendar-mode-map' for adding diary entries.
3282 This option is irrelevant until `org-agenda-diary-file' has been configured
3283 to point to an Org-mode file. When that is the case, the command
3284 `org-agenda-diary-entry' will be bound to the key given here, by default
3285 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3286 if you want to continue doing this, you need to change this to a different
3287 key."
3288 :group 'org-agenda
3289 :type 'sexp)
3291 (defcustom org-agenda-diary-file 'diary-file
3292 "File to which to add new entries with the `i' key in agenda and calendar.
3293 When this is the symbol `diary-file', the functionality in the Emacs
3294 calendar will be used to add entries to the `diary-file'. But when this
3295 points to a file, `org-agenda-diary-entry' will be used instead."
3296 :group 'org-agenda
3297 :type '(choice
3298 (const :tag "The standard Emacs diary file" diary-file)
3299 (file :tag "Special Org file diary entries")))
3301 (eval-after-load "calendar"
3302 '(progn
3303 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3304 'org-calendar-goto-agenda)
3305 (org-defkey calendar-mode-map org-calendar-agenda-action-key
3306 'org-agenda-action)
3307 (add-hook 'calendar-mode-hook
3308 (lambda ()
3309 (unless (eq org-agenda-diary-file 'diary-file)
3310 (define-key calendar-mode-map
3311 org-calendar-insert-diary-entry-key
3312 'org-agenda-diary-entry))))))
3314 (defgroup org-latex nil
3315 "Options for embedding LaTeX code into Org-mode."
3316 :tag "Org LaTeX"
3317 :group 'org)
3319 (defcustom org-format-latex-options
3320 '(:foreground default :background default :scale 1.0
3321 :html-foreground "Black" :html-background "Transparent"
3322 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3323 "Options for creating images from LaTeX fragments.
3324 This is a property list with the following properties:
3325 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3326 `default' means use the foreground of the default face.
3327 :background the background color, or \"Transparent\".
3328 `default' means use the background of the default face.
3329 :scale a scaling factor for the size of the images, to get more pixels
3330 :html-foreground, :html-background, :html-scale
3331 the same numbers for HTML export.
3332 :matchers a list indicating which matchers should be used to
3333 find LaTeX fragments. Valid members of this list are:
3334 \"begin\" find environments
3335 \"$1\" find single characters surrounded by $.$
3336 \"$\" find math expressions surrounded by $...$
3337 \"$$\" find math expressions surrounded by $$....$$
3338 \"\\(\" find math expressions surrounded by \\(...\\)
3339 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3340 :group 'org-latex
3341 :type 'plist)
3343 (defcustom org-format-latex-signal-error t
3344 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3345 When nil, just push out a message."
3346 :group 'org-latex
3347 :version "24.1"
3348 :type 'boolean)
3350 (defcustom org-latex-to-mathml-jar-file nil
3351 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3352 Use this to specify additional executable file say a jar file.
3354 When using MathToWeb as the converter, specify the full-path to
3355 your mathtoweb.jar file."
3356 :group 'org-latex
3357 :version "24.1"
3358 :type '(choice
3359 (const :tag "None" nil)
3360 (file :tag "JAR file" :must-match t)))
3362 (defcustom org-latex-to-mathml-convert-command nil
3363 "Command to convert LaTeX fragments to MathML.
3364 Replace format-specifiers in the command as noted below and use
3365 `shell-command' to convert LaTeX to MathML.
3366 %j: Executable file in fully expanded form as specified by
3367 `org-latex-to-mathml-jar-file'.
3368 %I: Input LaTeX file in fully expanded form
3369 %o: Output MathML file
3370 This command is used by `org-create-math-formula'.
3372 When using MathToWeb as the converter, set this to
3373 \"java -jar %j -unicode -force -df %o %I\"."
3374 :group 'org-latex
3375 :version "24.1"
3376 :type '(choice
3377 (const :tag "None" nil)
3378 (string :tag "\nShell command")))
3380 (defcustom org-latex-create-formula-image-program 'dvipng
3381 "Program to convert LaTeX fragments with.
3383 dvipng Process the LaTeX fragments to dvi file, then convert
3384 dvi files to png files using dvipng.
3385 This will also include processing of non-math environments.
3386 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3387 to convert pdf files to png files"
3388 :group 'org-latex
3389 :version "24.1"
3390 :type '(choice
3391 (const :tag "dvipng" dvipng)
3392 (const :tag "imagemagick" imagemagick)))
3394 (defun org-format-latex-mathml-available-p ()
3395 "Return t if `org-latex-to-mathml-convert-command' is usable."
3396 (save-match-data
3397 (when (and (boundp 'org-latex-to-mathml-convert-command)
3398 org-latex-to-mathml-convert-command)
3399 (let ((executable (car (split-string
3400 org-latex-to-mathml-convert-command))))
3401 (when (executable-find executable)
3402 (if (string-match
3403 "%j" org-latex-to-mathml-convert-command)
3404 (file-readable-p org-latex-to-mathml-jar-file)
3405 t))))))
3407 (defcustom org-format-latex-header "\\documentclass{article}
3408 \\usepackage[usenames]{color}
3409 \\usepackage{amsmath}
3410 \\usepackage[mathscr]{eucal}
3411 \\pagestyle{empty} % do not remove
3412 \[PACKAGES]
3413 \[DEFAULT-PACKAGES]
3414 % The settings below are copied from fullpage.sty
3415 \\setlength{\\textwidth}{\\paperwidth}
3416 \\addtolength{\\textwidth}{-3cm}
3417 \\setlength{\\oddsidemargin}{1.5cm}
3418 \\addtolength{\\oddsidemargin}{-2.54cm}
3419 \\setlength{\\evensidemargin}{\\oddsidemargin}
3420 \\setlength{\\textheight}{\\paperheight}
3421 \\addtolength{\\textheight}{-\\headheight}
3422 \\addtolength{\\textheight}{-\\headsep}
3423 \\addtolength{\\textheight}{-\\footskip}
3424 \\addtolength{\\textheight}{-3cm}
3425 \\setlength{\\topmargin}{1.5cm}
3426 \\addtolength{\\topmargin}{-2.54cm}"
3427 "The document header used for processing LaTeX fragments.
3428 It is imperative that this header make sure that no page number
3429 appears on the page. The package defined in the variables
3430 `org-export-latex-default-packages-alist' and `org-export-latex-packages-alist'
3431 will either replace the placeholder \"[PACKAGES]\" in this header, or they
3432 will be appended."
3433 :group 'org-latex
3434 :type 'string)
3436 (defvar org-format-latex-header-extra nil)
3438 (defun org-set-packages-alist (var val)
3439 "Set the packages alist and make sure it has 3 elements per entry."
3440 (set var (mapcar (lambda (x)
3441 (if (and (consp x) (= (length x) 2))
3442 (list (car x) (nth 1 x) t)
3444 val)))
3446 (defun org-get-packages-alist (var)
3448 "Get the packages alist and make sure it has 3 elements per entry."
3449 (mapcar (lambda (x)
3450 (if (and (consp x) (= (length x) 2))
3451 (list (car x) (nth 1 x) t)
3453 (default-value var)))
3455 ;; The following variables are defined here because is it also used
3456 ;; when formatting latex fragments. Originally it was part of the
3457 ;; LaTeX exporter, which is why the name includes "export".
3458 (defcustom org-export-latex-default-packages-alist
3459 '(("AUTO" "inputenc" t)
3460 ("T1" "fontenc" t)
3461 ("" "fixltx2e" nil)
3462 ("" "graphicx" t)
3463 ("" "longtable" nil)
3464 ("" "float" nil)
3465 ("" "wrapfig" nil)
3466 ("" "soul" t)
3467 ("" "textcomp" t)
3468 ("" "marvosym" t)
3469 ("" "wasysym" t)
3470 ("" "latexsym" t)
3471 ("" "amssymb" t)
3472 ("" "hyperref" nil)
3473 "\\tolerance=1000"
3475 "Alist of default packages to be inserted in the header.
3476 Change this only if one of the packages here causes an incompatibility
3477 with another package you are using.
3478 The packages in this list are needed by one part or another of Org-mode
3479 to function properly.
3481 - inputenc, fontenc: for basic font and character selection
3482 - textcomp, marvosymb, wasysym, latexsym, amssym: for various symbols used
3483 for interpreting the entities in `org-entities'. You can skip some of these
3484 packages if you don't use any of the symbols in it.
3485 - graphicx: for including images
3486 - float, wrapfig: for figure placement
3487 - longtable: for long tables
3488 - hyperref: for cross references
3490 Therefore you should not modify this variable unless you know what you
3491 are doing. The one reason to change it anyway is that you might be loading
3492 some other package that conflicts with one of the default packages.
3493 Each cell is of the format \( \"options\" \"package\" snippet-flag\).
3494 If SNIPPET-FLAG is t, the package also needs to be included when
3495 compiling LaTeX snippets into images for inclusion into HTML."
3496 :group 'org-export-latex
3497 :set 'org-set-packages-alist
3498 :get 'org-get-packages-alist
3499 :version "24.1"
3500 :type '(repeat
3501 (choice
3502 (list :tag "options/package pair"
3503 (string :tag "options")
3504 (string :tag "package")
3505 (boolean :tag "Snippet"))
3506 (string :tag "A line of LaTeX"))))
3508 (defcustom org-export-latex-packages-alist nil
3509 "Alist of packages to be inserted in every LaTeX header.
3510 These will be inserted after `org-export-latex-default-packages-alist'.
3511 Each cell is of the format \( \"options\" \"package\" snippet-flag \).
3512 SNIPPET-FLAG, when t, indicates that this package is also needed when
3513 turning LaTeX snippets into images for inclusion into HTML.
3514 Make sure that you only list packages here which:
3515 - you want in every file
3516 - do not conflict with the default packages in
3517 `org-export-latex-default-packages-alist'
3518 - do not conflict with the setup in `org-format-latex-header'."
3519 :group 'org-export-latex
3520 :set 'org-set-packages-alist
3521 :get 'org-get-packages-alist
3522 :type '(repeat
3523 (choice
3524 (list :tag "options/package pair"
3525 (string :tag "options")
3526 (string :tag "package")
3527 (boolean :tag "Snippet"))
3528 (string :tag "A line of LaTeX"))))
3531 (defgroup org-appearance nil
3532 "Settings for Org-mode appearance."
3533 :tag "Org Appearance"
3534 :group 'org)
3536 (defcustom org-level-color-stars-only nil
3537 "Non-nil means fontify only the stars in each headline.
3538 When nil, the entire headline is fontified.
3539 Changing it requires restart of `font-lock-mode' to become effective
3540 also in regions already fontified."
3541 :group 'org-appearance
3542 :type 'boolean)
3544 (defcustom org-hide-leading-stars nil
3545 "Non-nil means hide the first N-1 stars in a headline.
3546 This works by using the face `org-hide' for these stars. This
3547 face is white for a light background, and black for a dark
3548 background. You may have to customize the face `org-hide' to
3549 make this work.
3550 Changing it requires restart of `font-lock-mode' to become effective
3551 also in regions already fontified.
3552 You may also set this on a per-file basis by adding one of the following
3553 lines to the buffer:
3555 #+STARTUP: hidestars
3556 #+STARTUP: showstars"
3557 :group 'org-appearance
3558 :type 'boolean)
3560 (defcustom org-hidden-keywords nil
3561 "List of symbols corresponding to keywords to be hidden the org buffer.
3562 For example, a value '(title) for this list will make the document's title
3563 appear in the buffer without the initial #+TITLE: keyword."
3564 :group 'org-appearance
3565 :version "24.1"
3566 :type '(set (const :tag "#+AUTHOR" author)
3567 (const :tag "#+DATE" date)
3568 (const :tag "#+EMAIL" email)
3569 (const :tag "#+TITLE" title)))
3571 (defcustom org-fontify-done-headline nil
3572 "Non-nil means change the face of a headline if it is marked DONE.
3573 Normally, only the TODO/DONE keyword indicates the state of a headline.
3574 When this is non-nil, the headline after the keyword is set to the
3575 `org-headline-done' as an additional indication."
3576 :group 'org-appearance
3577 :type 'boolean)
3579 (defcustom org-fontify-emphasized-text t
3580 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3581 Changing this variable requires a restart of Emacs to take effect."
3582 :group 'org-appearance
3583 :type 'boolean)
3585 (defcustom org-fontify-whole-heading-line nil
3586 "Non-nil means fontify the whole line for headings.
3587 This is useful when setting a background color for the
3588 org-level-* faces."
3589 :group 'org-appearance
3590 :type 'boolean)
3592 (defcustom org-highlight-latex-fragments-and-specials nil
3593 "Non-nil means fontify what is treated specially by the exporters."
3594 :group 'org-appearance
3595 :type 'boolean)
3597 (defcustom org-hide-emphasis-markers nil
3598 "Non-nil mean font-lock should hide the emphasis marker characters."
3599 :group 'org-appearance
3600 :type 'boolean)
3602 (defcustom org-pretty-entities nil
3603 "Non-nil means show entities as UTF8 characters.
3604 When nil, the \\name form remains in the buffer."
3605 :group 'org-appearance
3606 :version "24.1"
3607 :type 'boolean)
3609 (defcustom org-pretty-entities-include-sub-superscripts t
3610 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3611 :group 'org-appearance
3612 :version "24.1"
3613 :type 'boolean)
3615 (defvar org-emph-re nil
3616 "Regular expression for matching emphasis.
3617 After a match, the match groups contain these elements:
3618 0 The match of the full regular expression, including the characters
3619 before and after the proper match
3620 1 The character before the proper match, or empty at beginning of line
3621 2 The proper match, including the leading and trailing markers
3622 3 The leading marker like * or /, indicating the type of highlighting
3623 4 The text between the emphasis markers, not including the markers
3624 5 The character after the match, empty at the end of a line")
3625 (defvar org-verbatim-re nil
3626 "Regular expression for matching verbatim text.")
3627 (defvar org-emphasis-regexp-components) ; defined just below
3628 (defvar org-emphasis-alist) ; defined just below
3629 (defun org-set-emph-re (var val)
3630 "Set variable and compute the emphasis regular expression."
3631 (set var val)
3632 (when (and (boundp 'org-emphasis-alist)
3633 (boundp 'org-emphasis-regexp-components)
3634 org-emphasis-alist org-emphasis-regexp-components)
3635 (let* ((e org-emphasis-regexp-components)
3636 (pre (car e))
3637 (post (nth 1 e))
3638 (border (nth 2 e))
3639 (body (nth 3 e))
3640 (nl (nth 4 e))
3641 (body1 (concat body "*?"))
3642 (markers (mapconcat 'car org-emphasis-alist ""))
3643 (vmarkers (mapconcat
3644 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3645 org-emphasis-alist "")))
3646 ;; make sure special characters appear at the right position in the class
3647 (if (string-match "\\^" markers)
3648 (setq markers (concat (replace-match "" t t markers) "^")))
3649 (if (string-match "-" markers)
3650 (setq markers (concat (replace-match "" t t markers) "-")))
3651 (if (string-match "\\^" vmarkers)
3652 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3653 (if (string-match "-" vmarkers)
3654 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3655 (if (> nl 0)
3656 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3657 (int-to-string nl) "\\}")))
3658 ;; Make the regexp
3659 (setq org-emph-re
3660 (concat "\\([" pre "]\\|^\\)"
3661 "\\("
3662 "\\([" markers "]\\)"
3663 "\\("
3664 "[^" border "]\\|"
3665 "[^" border "]"
3666 body1
3667 "[^" border "]"
3668 "\\)"
3669 "\\3\\)"
3670 "\\([" post "]\\|$\\)"))
3671 (setq org-verbatim-re
3672 (concat "\\([" pre "]\\|^\\)"
3673 "\\("
3674 "\\([" vmarkers "]\\)"
3675 "\\("
3676 "[^" border "]\\|"
3677 "[^" border "]"
3678 body1
3679 "[^" border "]"
3680 "\\)"
3681 "\\3\\)"
3682 "\\([" post "]\\|$\\)")))))
3684 (defcustom org-emphasis-regexp-components
3685 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
3686 "Components used to build the regular expression for emphasis.
3687 This is a list with five entries. Terminology: In an emphasis string
3688 like \" *strong word* \", we call the initial space PREMATCH, the final
3689 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3690 and \"trong wor\" is the body. The different components in this variable
3691 specify what is allowed/forbidden in each part:
3693 pre Chars allowed as prematch. Beginning of line will be allowed too.
3694 post Chars allowed as postmatch. End of line will be allowed too.
3695 border The chars *forbidden* as border characters.
3696 body-regexp A regexp like \".\" to match a body character. Don't use
3697 non-shy groups here, and don't allow newline here.
3698 newline The maximum number of newlines allowed in an emphasis exp.
3700 Use customize to modify this, or restart Emacs after changing it."
3701 :group 'org-appearance
3702 :set 'org-set-emph-re
3703 :type '(list
3704 (sexp :tag "Allowed chars in pre ")
3705 (sexp :tag "Allowed chars in post ")
3706 (sexp :tag "Forbidden chars in border ")
3707 (sexp :tag "Regexp for body ")
3708 (integer :tag "number of newlines allowed")
3709 (option (boolean :tag "Please ignore this button"))))
3711 (defcustom org-emphasis-alist
3712 `(("*" bold "<b>" "</b>")
3713 ("/" italic "<i>" "</i>")
3714 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
3715 ("=" org-code "<code>" "</code>" verbatim)
3716 ("~" org-verbatim "<code>" "</code>" verbatim)
3717 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
3718 "<del>" "</del>")
3720 "Special syntax for emphasized text.
3721 Text starting and ending with a special character will be emphasized, for
3722 example *bold*, _underlined_ and /italic/. This variable sets the marker
3723 characters, the face to be used by font-lock for highlighting in Org-mode
3724 Emacs buffers, and the HTML tags to be used for this.
3725 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
3726 For DocBook export, see the variable `org-export-docbook-emphasis-alist'.
3727 Use customize to modify this, or restart Emacs after changing it."
3728 :group 'org-appearance
3729 :set 'org-set-emph-re
3730 :type '(repeat
3731 (list
3732 (string :tag "Marker character")
3733 (choice
3734 (face :tag "Font-lock-face")
3735 (plist :tag "Face property list"))
3736 (string :tag "HTML start tag")
3737 (string :tag "HTML end tag")
3738 (option (const verbatim)))))
3740 (defvar org-protecting-blocks
3741 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
3742 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
3743 This is needed for font-lock setup.")
3745 ;;; Miscellaneous options
3747 (defgroup org-completion nil
3748 "Completion in Org-mode."
3749 :tag "Org Completion"
3750 :group 'org)
3752 (defcustom org-completion-use-ido nil
3753 "Non-nil means use ido completion wherever possible.
3754 Note that `ido-mode' must be active for this variable to be relevant.
3755 If you decide to turn this variable on, you might well want to turn off
3756 `org-outline-path-complete-in-steps'.
3757 See also `org-completion-use-iswitchb'."
3758 :group 'org-completion
3759 :type 'boolean)
3761 (defcustom org-completion-use-iswitchb nil
3762 "Non-nil means use iswitchb completion wherever possible.
3763 Note that `iswitchb-mode' must be active for this variable to be relevant.
3764 If you decide to turn this variable on, you might well want to turn off
3765 `org-outline-path-complete-in-steps'.
3766 Note that this variable has only an effect if `org-completion-use-ido' is nil."
3767 :group 'org-completion
3768 :type 'boolean)
3770 (defcustom org-completion-fallback-command 'hippie-expand
3771 "The expansion command called by \\[pcomplete] in normal context.
3772 Normal means, no org-mode-specific context."
3773 :group 'org-completion
3774 :type 'function)
3776 ;;; Functions and variables from their packages
3777 ;; Declared here to avoid compiler warnings
3779 ;; XEmacs only
3780 (defvar outline-mode-menu-heading)
3781 (defvar outline-mode-menu-show)
3782 (defvar outline-mode-menu-hide)
3783 (defvar zmacs-regions) ; XEmacs regions
3785 ;; Emacs only
3786 (defvar mark-active)
3788 ;; Various packages
3789 (declare-function calendar-absolute-from-iso "cal-iso" (date))
3790 (declare-function calendar-forward-day "cal-move" (arg))
3791 (declare-function calendar-goto-date "cal-move" (date))
3792 (declare-function calendar-goto-today "cal-move" ())
3793 (declare-function calendar-iso-from-absolute "cal-iso" (date))
3794 (defvar calc-embedded-close-formula)
3795 (defvar calc-embedded-open-formula)
3796 (declare-function cdlatex-tab "ext:cdlatex" ())
3797 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
3798 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3799 (defvar font-lock-unfontify-region-function)
3800 (declare-function iswitchb-read-buffer "iswitchb"
3801 (prompt &optional default require-match start matches-set))
3802 (defvar iswitchb-temp-buflist)
3803 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
3804 (defvar org-agenda-tags-todo-honor-ignore-options)
3805 (declare-function org-agenda-skip "org-agenda" ())
3806 (declare-function
3807 org-agenda-format-item "org-agenda"
3808 (extra txt &optional category tags dotime noprefix remove-re habitp))
3809 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
3810 (declare-function org-agenda-change-all-lines "org-agenda"
3811 (newhead hdmarker &optional fixface just-this))
3812 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
3813 (declare-function org-agenda-maybe-redo "org-agenda" ())
3814 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
3815 (beg end))
3816 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
3817 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
3818 "org-agenda" (&optional end))
3819 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
3820 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
3821 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
3822 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
3823 (declare-function org-indent-mode "org-indent" (&optional arg))
3824 (declare-function parse-time-string "parse-time" (string))
3825 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
3826 (declare-function org-export-latex-fix-inputenc "org-latex" ())
3827 (declare-function orgtbl-send-table "org-table" (&optional maybe))
3828 (defvar remember-data-file)
3829 (defvar texmathp-why)
3830 (declare-function speedbar-line-directory "speedbar" (&optional depth))
3831 (declare-function table--at-cell-p "table" (position &optional object at-column))
3833 (defvar w3m-current-url)
3834 (defvar w3m-current-title)
3836 (defvar org-latex-regexps)
3838 ;;; Autoload and prepare some org modules
3840 ;; Some table stuff that needs to be defined here, because it is used
3841 ;; by the functions setting up org-mode or checking for table context.
3843 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
3844 "Detect an org-type or table-type table.")
3845 (defconst org-table-line-regexp "^[ \t]*|"
3846 "Detect an org-type table line.")
3847 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
3848 "Detect an org-type table line.")
3849 (defconst org-table-hline-regexp "^[ \t]*|-"
3850 "Detect an org-type table hline.")
3851 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
3852 "Detect a table-type table hline.")
3853 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
3854 "Detect the first line outside a table when searching from within it.
3855 This works for both table types.")
3857 ;; Autoload the functions in org-table.el that are needed by functions here.
3859 (eval-and-compile
3860 (org-autoload "org-table"
3861 '(org-table-align org-table-begin org-table-blank-field
3862 org-table-convert org-table-convert-region org-table-copy-down
3863 org-table-copy-region org-table-create
3864 org-table-create-or-convert-from-region
3865 org-table-create-with-table.el org-table-current-dline
3866 org-table-cut-region org-table-delete-column org-table-edit-field
3867 org-table-edit-formulas org-table-end org-table-eval-formula
3868 org-table-export org-table-field-info
3869 org-table-get-stored-formulas org-table-goto-column
3870 org-table-hline-and-move org-table-import org-table-insert-column
3871 org-table-insert-hline org-table-insert-row org-table-iterate
3872 org-table-justify-field-maybe org-table-kill-row
3873 org-table-maybe-eval-formula org-table-maybe-recalculate-line
3874 org-table-move-column org-table-move-column-left
3875 org-table-move-column-right org-table-move-row
3876 org-table-move-row-down org-table-move-row-up
3877 org-table-next-field org-table-next-row org-table-paste-rectangle
3878 org-table-previous-field org-table-recalculate
3879 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
3880 org-table-toggle-coordinate-overlays
3881 org-table-toggle-formula-debugger org-table-wrap-region
3882 orgtbl-mode turn-on-orgtbl org-table-to-lisp
3883 orgtbl-to-generic orgtbl-to-tsv orgtbl-to-csv orgtbl-to-latex
3884 orgtbl-to-orgtbl orgtbl-to-html orgtbl-to-texinfo)))
3886 (defun org-at-table-p (&optional table-type)
3887 "Return t if the cursor is inside an org-type table.
3888 If TABLE-TYPE is non-nil, also check for table.el-type tables."
3889 (if org-enable-table-editor
3890 (save-excursion
3891 (beginning-of-line 1)
3892 (looking-at (if table-type org-table-any-line-regexp
3893 org-table-line-regexp)))
3894 nil))
3895 (defsubst org-table-p () (org-at-table-p))
3897 (defun org-at-table.el-p ()
3898 "Return t if and only if we are at a table.el table."
3899 (and (org-at-table-p 'any)
3900 (save-excursion
3901 (goto-char (org-table-begin 'any))
3902 (looking-at org-table1-hline-regexp))))
3903 (defun org-table-recognize-table.el ()
3904 "If there is a table.el table nearby, recognize it and move into it."
3905 (if org-table-tab-recognizes-table.el
3906 (if (org-at-table.el-p)
3907 (progn
3908 (beginning-of-line 1)
3909 (if (looking-at org-table-dataline-regexp)
3911 (if (looking-at org-table1-hline-regexp)
3912 (progn
3913 (beginning-of-line 2)
3914 (if (looking-at org-table-any-border-regexp)
3915 (beginning-of-line -1)))))
3916 (if (re-search-forward "|" (org-table-end t) t)
3917 (progn
3918 (require 'table)
3919 (if (table--at-cell-p (point))
3921 (message "recognizing table.el table...")
3922 (table-recognize-table)
3923 (message "recognizing table.el table...done")))
3924 (error "This should not happen"))
3926 nil)
3927 nil))
3929 (defun org-at-table-hline-p ()
3930 "Return t if the cursor is inside a hline in a table."
3931 (if org-enable-table-editor
3932 (save-excursion
3933 (beginning-of-line 1)
3934 (looking-at org-table-hline-regexp))
3935 nil))
3937 (defvar org-table-clean-did-remove-column nil)
3939 (defun org-table-map-tables (function &optional quietly)
3940 "Apply FUNCTION to the start of all tables in the buffer."
3941 (save-excursion
3942 (save-restriction
3943 (widen)
3944 (goto-char (point-min))
3945 (while (re-search-forward org-table-any-line-regexp nil t)
3946 (unless quietly
3947 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
3948 (beginning-of-line 1)
3949 (when (and (looking-at org-table-line-regexp)
3950 ;; Exclude tables in src/example/verbatim/clocktable blocks
3951 (not (org-in-block-p '("src" "example"))))
3952 (save-excursion (funcall function))
3953 (or (looking-at org-table-line-regexp)
3954 (forward-char 1)))
3955 (re-search-forward org-table-any-border-regexp nil 1))))
3956 (unless quietly (message "Mapping tables: done")))
3958 ;; Declare and autoload functions from org-exp.el & Co
3960 (declare-function org-default-export-plist "org-exp")
3961 (declare-function org-infile-export-plist "org-exp")
3962 (declare-function org-get-current-options "org-exp")
3963 (eval-and-compile
3964 (org-autoload "org-exp"
3965 '(org-export org-export-visible
3966 org-insert-export-options-template
3967 org-table-clean-before-export))
3968 (org-autoload "org-ascii"
3969 '(org-export-as-ascii org-export-ascii-preprocess
3970 org-export-as-ascii-to-buffer org-replace-region-by-ascii
3971 org-export-region-as-ascii))
3972 (org-autoload "org-latex"
3973 '(org-export-as-latex-batch org-export-as-latex-to-buffer
3974 org-replace-region-by-latex org-export-region-as-latex
3975 org-export-as-latex org-export-as-pdf
3976 org-export-as-pdf-and-open))
3977 (org-autoload "org-html"
3978 '(org-export-as-html-and-open
3979 org-export-as-html-batch org-export-as-html-to-buffer
3980 org-replace-region-by-html org-export-region-as-html
3981 org-export-as-html))
3982 (org-autoload "org-docbook"
3983 '(org-export-as-docbook-batch org-export-as-docbook-to-buffer
3984 org-replace-region-by-docbook org-export-region-as-docbook
3985 org-export-as-docbook-pdf org-export-as-docbook-pdf-and-open
3986 org-export-as-docbook))
3987 (org-autoload "org-icalendar"
3988 '(org-export-icalendar-this-file
3989 org-export-icalendar-all-agenda-files
3990 org-export-icalendar-combine-agenda-files))
3991 (org-autoload "org-xoxo" '(org-export-as-xoxo))
3992 (org-autoload "org-beamer" '(org-beamer-mode org-beamer-sectioning)))
3994 ;; Declare and autoload functions from org-agenda.el
3996 (eval-and-compile
3997 (org-autoload "org-agenda"
3998 '(org-agenda org-agenda-list org-search-view
3999 org-todo-list org-tags-view org-agenda-list-stuck-projects
4000 org-diary org-agenda-to-appt
4001 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
4003 ;; Autoload org-remember
4005 (eval-and-compile
4006 (org-autoload "org-remember"
4007 '(org-remember-insinuate org-remember-annotation
4008 org-remember-apply-template org-remember org-remember-handler)))
4010 (eval-and-compile
4011 (org-autoload "org-capture"
4012 '(org-capture org-capture-insert-template-here
4013 org-capture-import-remember-templates)))
4015 ;; Autoload org-clock.el
4017 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
4018 (beg end))
4019 (declare-function org-clock-update-mode-line "org-clock" ())
4020 (declare-function org-resolve-clocks "org-clock"
4021 (&optional also-non-dangling-p prompt last-valid))
4022 (defvar org-clock-start-time)
4023 (defvar org-clock-marker (make-marker)
4024 "Marker recording the last clock-in.")
4025 (defvar org-clock-hd-marker (make-marker)
4026 "Marker recording the last clock-in, but the headline position.")
4027 (defvar org-clock-heading ""
4028 "The heading of the current clock entry.")
4029 (defun org-clock-is-active ()
4030 "Return non-nil if clock is currently running.
4031 The return value is actually the clock marker."
4032 (marker-buffer org-clock-marker))
4034 (eval-and-compile
4035 (org-autoload
4036 "org-clock"
4037 '(org-clock-in org-clock-out org-clock-cancel
4038 org-clock-goto org-clock-sum org-clock-display
4039 org-clock-remove-overlays org-clock-report
4040 org-clocktable-shift org-dblock-write:clocktable
4041 org-get-clocktable org-resolve-clocks)))
4043 (defun org-clock-update-time-maybe ()
4044 "If this is a CLOCK line, update it and return t.
4045 Otherwise, return nil."
4046 (interactive)
4047 (save-excursion
4048 (beginning-of-line 1)
4049 (skip-chars-forward " \t")
4050 (when (looking-at org-clock-string)
4051 (let ((re (concat "[ \t]*" org-clock-string
4052 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
4053 "\\([ \t]*=>.*\\)?\\)?"))
4054 ts te h m s neg)
4055 (cond
4056 ((not (looking-at re))
4057 nil)
4058 ((not (match-end 2))
4059 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4060 (> org-clock-marker (point))
4061 (<= org-clock-marker (point-at-eol)))
4062 ;; The clock is running here
4063 (setq org-clock-start-time
4064 (apply 'encode-time
4065 (org-parse-time-string (match-string 1))))
4066 (org-clock-update-mode-line)))
4068 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
4069 (end-of-line 1)
4070 (setq ts (match-string 1)
4071 te (match-string 3))
4072 (setq s (- (org-float-time
4073 (apply 'encode-time (org-parse-time-string te)))
4074 (org-float-time
4075 (apply 'encode-time (org-parse-time-string ts))))
4076 neg (< s 0)
4077 s (abs s)
4078 h (floor (/ s 3600))
4079 s (- s (* 3600 h))
4080 m (floor (/ s 60))
4081 s (- s (* 60 s)))
4082 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
4083 t))))))
4085 (defun org-check-running-clock ()
4086 "Check if the current buffer contains the running clock.
4087 If yes, offer to stop it and to save the buffer with the changes."
4088 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4089 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4090 (buffer-name))))
4091 (org-clock-out)
4092 (when (y-or-n-p "Save changed buffer?")
4093 (save-buffer))))
4095 (defun org-clocktable-try-shift (dir n)
4096 "Check if this line starts a clock table, if yes, shift the time block."
4097 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4098 (org-clocktable-shift dir n)))
4100 ;; Autoload org-timer.el
4102 (eval-and-compile
4103 (org-autoload
4104 "org-timer"
4105 '(org-timer-start org-timer org-timer-item
4106 org-timer-change-times-in-region
4107 org-timer-set-timer
4108 org-timer-reset-timers
4109 org-timer-show-remaining-time)))
4111 ;; Autoload org-feed.el
4113 (eval-and-compile
4114 (org-autoload
4115 "org-feed"
4116 '(org-feed-update org-feed-update-all org-feed-goto-inbox)))
4119 ;; Autoload org-indent.el
4121 ;; Define the variable already here, to make sure we have it.
4122 (defvar org-indent-mode nil
4123 "Non-nil if Org-Indent mode is enabled.
4124 Use the command `org-indent-mode' to change this variable.")
4126 (eval-and-compile
4127 (org-autoload
4128 "org-indent"
4129 '(org-indent-mode)))
4131 ;; Autoload org-mobile.el
4133 (eval-and-compile
4134 (org-autoload
4135 "org-mobile"
4136 '(org-mobile-push org-mobile-pull org-mobile-create-sumo-agenda)))
4138 ;; Autoload archiving code
4139 ;; The stuff that is needed for cycling and tags has to be defined here.
4141 (defgroup org-archive nil
4142 "Options concerning archiving in Org-mode."
4143 :tag "Org Archive"
4144 :group 'org-structure)
4146 (defcustom org-archive-location "%s_archive::"
4147 "The location where subtrees should be archived.
4149 The value of this variable is a string, consisting of two parts,
4150 separated by a double-colon. The first part is a filename and
4151 the second part is a headline.
4153 When the filename is omitted, archiving happens in the same file.
4154 %s in the filename will be replaced by the current file
4155 name (without the directory part). Archiving to a different file
4156 is useful to keep archived entries from contributing to the
4157 Org-mode Agenda.
4159 The archived entries will be filed as subtrees of the specified
4160 headline. When the headline is omitted, the subtrees are simply
4161 filed away at the end of the file, as top-level entries. Also in
4162 the heading you can use %s to represent the file name, this can be
4163 useful when using the same archive for a number of different files.
4165 Here are a few examples:
4166 \"%s_archive::\"
4167 If the current file is Projects.org, archive in file
4168 Projects.org_archive, as top-level trees. This is the default.
4170 \"::* Archived Tasks\"
4171 Archive in the current file, under the top-level headline
4172 \"* Archived Tasks\".
4174 \"~/org/archive.org::\"
4175 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4177 \"~/org/archive.org::* From %s\"
4178 Archive in file ~/org/archive.org (absolute path), under headlines
4179 \"From FILENAME\" where file name is the current file name.
4181 \"~/org/datetree.org::datetree/* Finished Tasks\"
4182 The \"datetree/\" string is special, signifying to archive
4183 items to the datetree. Items are placed in either the CLOSED
4184 date of the item, or the current date if there is no CLOSED date.
4185 The heading will be a subentry to the current date. There doesn't
4186 need to be a heading, but there always needs to be a slash after
4187 datetree. For example, to store archived items directly in the
4188 datetree, use \"~/org/datetree.org::datetree/\".
4190 \"basement::** Finished Tasks\"
4191 Archive in file ./basement (relative path), as level 3 trees
4192 below the level 2 heading \"** Finished Tasks\".
4194 You may set this option on a per-file basis by adding to the buffer a
4195 line like
4197 #+ARCHIVE: basement::** Finished Tasks
4199 You may also define it locally for a subtree by setting an ARCHIVE property
4200 in the entry. If such a property is found in an entry, or anywhere up
4201 the hierarchy, it will be used."
4202 :group 'org-archive
4203 :type 'string)
4205 (defcustom org-archive-tag "ARCHIVE"
4206 "The tag that marks a subtree as archived.
4207 An archived subtree does not open during visibility cycling, and does
4208 not contribute to the agenda listings.
4209 After changing this, font-lock must be restarted in the relevant buffers to
4210 get the proper fontification."
4211 :group 'org-archive
4212 :group 'org-keywords
4213 :type 'string)
4215 (defcustom org-agenda-skip-archived-trees t
4216 "Non-nil means the agenda will skip any items located in archived trees.
4217 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4218 variable is no longer recommended, you should leave it at the value t.
4219 Instead, use the key `v' to cycle the archives-mode in the agenda."
4220 :group 'org-archive
4221 :group 'org-agenda-skip
4222 :type 'boolean)
4224 (defcustom org-columns-skip-archived-trees t
4225 "Non-nil means ignore archived trees when creating column view."
4226 :group 'org-archive
4227 :group 'org-properties
4228 :type 'boolean)
4230 (defcustom org-cycle-open-archived-trees nil
4231 "Non-nil means `org-cycle' will open archived trees.
4232 An archived tree is a tree marked with the tag ARCHIVE.
4233 When nil, archived trees will stay folded. You can still open them with
4234 normal outline commands like `show-all', but not with the cycling commands."
4235 :group 'org-archive
4236 :group 'org-cycle
4237 :type 'boolean)
4239 (defcustom org-sparse-tree-open-archived-trees nil
4240 "Non-nil means sparse tree construction shows matches in archived trees.
4241 When nil, matches in these trees are highlighted, but the trees are kept in
4242 collapsed state."
4243 :group 'org-archive
4244 :group 'org-sparse-trees
4245 :type 'boolean)
4247 (defun org-cycle-hide-archived-subtrees (state)
4248 "Re-hide all archived subtrees after a visibility state change."
4249 (when (and (not org-cycle-open-archived-trees)
4250 (not (memq state '(overview folded))))
4251 (save-excursion
4252 (let* ((globalp (memq state '(contents all)))
4253 (beg (if globalp (point-min) (point)))
4254 (end (if globalp (point-max) (org-end-of-subtree t))))
4255 (org-hide-archived-subtrees beg end)
4256 (goto-char beg)
4257 (if (looking-at (concat ".*:" org-archive-tag ":"))
4258 (message "%s" (substitute-command-keys
4259 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4261 (defun org-force-cycle-archived ()
4262 "Cycle subtree even if it is archived."
4263 (interactive)
4264 (setq this-command 'org-cycle)
4265 (let ((org-cycle-open-archived-trees t))
4266 (call-interactively 'org-cycle)))
4268 (defun org-hide-archived-subtrees (beg end)
4269 "Re-hide all archived subtrees after a visibility state change."
4270 (save-excursion
4271 (let* ((re (concat ":" org-archive-tag ":")))
4272 (goto-char beg)
4273 (while (re-search-forward re end t)
4274 (when (org-at-heading-p)
4275 (org-flag-subtree t)
4276 (org-end-of-subtree t))))))
4278 (defun org-flag-subtree (flag)
4279 (save-excursion
4280 (org-back-to-heading t)
4281 (outline-end-of-heading)
4282 (outline-flag-region (point)
4283 (progn (org-end-of-subtree t) (point))
4284 flag)))
4286 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4288 (eval-and-compile
4289 (org-autoload "org-archive"
4290 '(org-add-archive-files org-archive-subtree
4291 org-archive-to-archive-sibling org-toggle-archive-tag
4292 org-archive-subtree-default
4293 org-archive-subtree-default-with-confirmation)))
4295 ;; Autoload Column View Code
4297 (declare-function org-columns-number-to-string "org-colview")
4298 (declare-function org-columns-get-format-and-top-level "org-colview")
4299 (declare-function org-columns-compute "org-colview")
4301 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4302 '(org-columns-number-to-string org-columns-get-format-and-top-level
4303 org-columns-compute org-agenda-columns org-columns-remove-overlays
4304 org-columns org-insert-columns-dblock org-dblock-write:columnview))
4306 ;; Autoload ID code
4308 (declare-function org-id-store-link "org-id")
4309 (declare-function org-id-locations-load "org-id")
4310 (declare-function org-id-locations-save "org-id")
4311 (defvar org-id-track-globally)
4312 (org-autoload "org-id"
4313 '(org-id-get-create org-id-new org-id-copy org-id-get
4314 org-id-get-with-outline-path-completion
4315 org-id-get-with-outline-drilling org-id-store-link
4316 org-id-goto org-id-find org-id-store-link))
4318 ;; Autoload Plotting Code
4320 (org-autoload "org-plot"
4321 '(org-plot/gnuplot))
4323 ;;; Variables for pre-computed regular expressions, all buffer local
4325 (defvar org-drawer-regexp nil
4326 "Matches first line of a hidden block.")
4327 (make-variable-buffer-local 'org-drawer-regexp)
4328 (defvar org-todo-regexp nil
4329 "Matches any of the TODO state keywords.")
4330 (make-variable-buffer-local 'org-todo-regexp)
4331 (defvar org-not-done-regexp nil
4332 "Matches any of the TODO state keywords except the last one.")
4333 (make-variable-buffer-local 'org-not-done-regexp)
4334 (defvar org-not-done-heading-regexp nil
4335 "Matches a TODO headline that is not done.")
4336 (make-variable-buffer-local 'org-not-done-regexp)
4337 (defvar org-todo-line-regexp nil
4338 "Matches a headline and puts TODO state into group 2 if present.")
4339 (make-variable-buffer-local 'org-todo-line-regexp)
4340 (defvar org-complex-heading-regexp nil
4341 "Matches a headline and puts everything into groups:
4342 group 1: the stars
4343 group 2: The todo keyword, maybe
4344 group 3: Priority cookie
4345 group 4: True headline
4346 group 5: Tags")
4347 (make-variable-buffer-local 'org-complex-heading-regexp)
4348 (defvar org-complex-heading-regexp-format nil
4349 "Printf format to make regexp to match an exact headline.
4350 This regexp will match the headline of any node which has the
4351 exact headline text that is put into the format, but may have any
4352 TODO state, priority and tags.")
4353 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4354 (defvar org-todo-line-tags-regexp nil
4355 "Matches a headline and puts TODO state into group 2 if present.
4356 Also put tags into group 4 if tags are present.")
4357 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4358 (defvar org-ds-keyword-length 12
4359 "Maximum length of the Deadline and SCHEDULED keywords.")
4360 (make-variable-buffer-local 'org-ds-keyword-length)
4361 (defvar org-deadline-regexp nil
4362 "Matches the DEADLINE keyword.")
4363 (make-variable-buffer-local 'org-deadline-regexp)
4364 (defvar org-deadline-time-regexp nil
4365 "Matches the DEADLINE keyword together with a time stamp.")
4366 (make-variable-buffer-local 'org-deadline-time-regexp)
4367 (defvar org-deadline-line-regexp nil
4368 "Matches the DEADLINE keyword and the rest of the line.")
4369 (make-variable-buffer-local 'org-deadline-line-regexp)
4370 (defvar org-scheduled-regexp nil
4371 "Matches the SCHEDULED keyword.")
4372 (make-variable-buffer-local 'org-scheduled-regexp)
4373 (defvar org-scheduled-time-regexp nil
4374 "Matches the SCHEDULED keyword together with a time stamp.")
4375 (make-variable-buffer-local 'org-scheduled-time-regexp)
4376 (defvar org-closed-time-regexp nil
4377 "Matches the CLOSED keyword together with a time stamp.")
4378 (make-variable-buffer-local 'org-closed-time-regexp)
4380 (defvar org-keyword-time-regexp nil
4381 "Matches any of the 4 keywords, together with the time stamp.")
4382 (make-variable-buffer-local 'org-keyword-time-regexp)
4383 (defvar org-keyword-time-not-clock-regexp nil
4384 "Matches any of the 3 keywords, together with the time stamp.")
4385 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4386 (defvar org-maybe-keyword-time-regexp nil
4387 "Matches a timestamp, possibly preceded by a keyword.")
4388 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4389 (defvar org-planning-or-clock-line-re nil
4390 "Matches a line with planning or clock info.")
4391 (make-variable-buffer-local 'org-planning-or-clock-line-re)
4392 (defvar org-all-time-keywords nil
4393 "List of time keywords.")
4394 (make-variable-buffer-local 'org-all-time-keywords)
4396 (defconst org-plain-time-of-day-regexp
4397 (concat
4398 "\\(\\<[012]?[0-9]"
4399 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4400 "\\(--?"
4401 "\\(\\<[012]?[0-9]"
4402 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4403 "\\)?")
4404 "Regular expression to match a plain time or time range.
4405 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4406 groups carry important information:
4407 0 the full match
4408 1 the first time, range or not
4409 8 the second time, if it is a range.")
4411 (defconst org-plain-time-extension-regexp
4412 (concat
4413 "\\(\\<[012]?[0-9]"
4414 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4415 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4416 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4417 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4418 groups carry important information:
4419 0 the full match
4420 7 hours of duration
4421 9 minutes of duration")
4423 (defconst org-stamp-time-of-day-regexp
4424 (concat
4425 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4426 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4427 "\\(--?"
4428 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4429 "Regular expression to match a timestamp time or time range.
4430 After a match, the following groups carry important information:
4431 0 the full match
4432 1 date plus weekday, for back referencing to make sure both times are on the same day
4433 2 the first time, range or not
4434 4 the second time, if it is a range.")
4436 (defconst org-startup-options
4437 '(("fold" org-startup-folded t)
4438 ("overview" org-startup-folded t)
4439 ("nofold" org-startup-folded nil)
4440 ("showall" org-startup-folded nil)
4441 ("showeverything" org-startup-folded showeverything)
4442 ("content" org-startup-folded content)
4443 ("indent" org-startup-indented t)
4444 ("noindent" org-startup-indented nil)
4445 ("hidestars" org-hide-leading-stars t)
4446 ("showstars" org-hide-leading-stars nil)
4447 ("odd" org-odd-levels-only t)
4448 ("oddeven" org-odd-levels-only nil)
4449 ("align" org-startup-align-all-tables t)
4450 ("noalign" org-startup-align-all-tables nil)
4451 ("inlineimages" org-startup-with-inline-images t)
4452 ("noinlineimages" org-startup-with-inline-images nil)
4453 ("customtime" org-display-custom-times t)
4454 ("logdone" org-log-done time)
4455 ("lognotedone" org-log-done note)
4456 ("nologdone" org-log-done nil)
4457 ("lognoteclock-out" org-log-note-clock-out t)
4458 ("nolognoteclock-out" org-log-note-clock-out nil)
4459 ("logrepeat" org-log-repeat state)
4460 ("lognoterepeat" org-log-repeat note)
4461 ("nologrepeat" org-log-repeat nil)
4462 ("logreschedule" org-log-reschedule time)
4463 ("lognotereschedule" org-log-reschedule note)
4464 ("nologreschedule" org-log-reschedule nil)
4465 ("logredeadline" org-log-redeadline time)
4466 ("lognoteredeadline" org-log-redeadline note)
4467 ("nologredeadline" org-log-redeadline nil)
4468 ("logrefile" org-log-refile time)
4469 ("lognoterefile" org-log-refile note)
4470 ("nologrefile" org-log-refile nil)
4471 ("fninline" org-footnote-define-inline t)
4472 ("nofninline" org-footnote-define-inline nil)
4473 ("fnlocal" org-footnote-section nil)
4474 ("fnauto" org-footnote-auto-label t)
4475 ("fnprompt" org-footnote-auto-label nil)
4476 ("fnconfirm" org-footnote-auto-label confirm)
4477 ("fnplain" org-footnote-auto-label plain)
4478 ("fnadjust" org-footnote-auto-adjust t)
4479 ("nofnadjust" org-footnote-auto-adjust nil)
4480 ("constcgs" constants-unit-system cgs)
4481 ("constSI" constants-unit-system SI)
4482 ("noptag" org-tag-persistent-alist nil)
4483 ("hideblocks" org-hide-block-startup t)
4484 ("nohideblocks" org-hide-block-startup nil)
4485 ("beamer" org-startup-with-beamer-mode t)
4486 ("entitiespretty" org-pretty-entities t)
4487 ("entitiesplain" org-pretty-entities nil))
4488 "Variable associated with STARTUP options for org-mode.
4489 Each element is a list of three items: The startup options as written
4490 in the #+STARTUP line, the corresponding variable, and the value to
4491 set this variable to if the option is found. An optional forth element PUSH
4492 means to push this value onto the list in the variable.")
4494 (defun org-update-property-plist (key val props)
4495 "Update PROPS with KEY and VAL."
4496 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4497 (key (if appending (substring key 0 (- (length key) 1)) key))
4498 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4499 (previous (cdr (assoc key props))))
4500 (if appending
4501 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4502 (cons (cons key val) remainder))))
4504 (defconst org-block-regexp
4505 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4506 "Regular expression for hiding blocks.")
4507 (defconst org-heading-keyword-regexp-format
4508 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4509 "Printf format for a regexp matching an headline with some keyword.
4510 This regexp will match the headline of any node which has the
4511 exact keyword that is put into the format. The keyword isn't in
4512 any group by default, but the stars and the body are.")
4513 (defconst org-heading-keyword-maybe-regexp-format
4514 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4515 "Printf format for a regexp matching an headline, possibly with some keyword.
4516 This regexp can match any headline with the specified keyword, or
4517 without a keyword. The keyword isn't in any group by default,
4518 but the stars and the body are.")
4520 (defun org-set-regexps-and-options ()
4521 "Precompute regular expressions for current buffer."
4522 (when (derived-mode-p 'org-mode)
4523 (org-set-local 'org-todo-kwd-alist nil)
4524 (org-set-local 'org-todo-key-alist nil)
4525 (org-set-local 'org-todo-key-trigger nil)
4526 (org-set-local 'org-todo-keywords-1 nil)
4527 (org-set-local 'org-done-keywords nil)
4528 (org-set-local 'org-todo-heads nil)
4529 (org-set-local 'org-todo-sets nil)
4530 (org-set-local 'org-todo-log-states nil)
4531 (org-set-local 'org-file-properties nil)
4532 (org-set-local 'org-file-tags nil)
4533 (let ((re (org-make-options-regexp
4534 '("CATEGORY" "TODO" "COLUMNS"
4535 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
4536 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE" "LATEX_CLASS"
4537 "OPTIONS")
4538 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4539 (splitre "[ \t]+")
4540 (scripts org-use-sub-superscripts)
4541 kwds kws0 kwsa key log value cat arch tags const links hw dws
4542 tail sep kws1 prio props ftags drawers beamer-p
4543 ext-setup-or-nil setup-contents (start 0))
4544 (save-excursion
4545 (save-restriction
4546 (widen)
4547 (goto-char (point-min))
4548 (while (or (and ext-setup-or-nil
4549 (string-match re ext-setup-or-nil start)
4550 (setq start (match-end 0)))
4551 (and (setq ext-setup-or-nil nil start 0)
4552 (re-search-forward re nil t)))
4553 (setq key (upcase (match-string 1 ext-setup-or-nil))
4554 value (org-match-string-no-properties 2 ext-setup-or-nil))
4555 (if (stringp value) (setq value (org-trim value)))
4556 (cond
4557 ((equal key "CATEGORY")
4558 (setq cat value))
4559 ((member key '("SEQ_TODO" "TODO"))
4560 (push (cons 'sequence (org-split-string value splitre)) kwds))
4561 ((equal key "TYP_TODO")
4562 (push (cons 'type (org-split-string value splitre)) kwds))
4563 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4564 ;; general TODO-like setup
4565 (push (cons (intern (downcase (match-string 1 key)))
4566 (org-split-string value splitre)) kwds))
4567 ((equal key "TAGS")
4568 (setq tags (append tags (if tags '("\\n") nil)
4569 (org-split-string value splitre))))
4570 ((equal key "COLUMNS")
4571 (org-set-local 'org-columns-default-format value))
4572 ((equal key "LINK")
4573 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4574 (push (cons (match-string 1 value)
4575 (org-trim (match-string 2 value)))
4576 links)))
4577 ((equal key "PRIORITIES")
4578 (setq prio (org-split-string value " +")))
4579 ((equal key "PROPERTY")
4580 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4581 (setq props (org-update-property-plist (match-string 1 value)
4582 (match-string 2 value)
4583 props))))
4584 ((equal key "FILETAGS")
4585 (when (string-match "\\S-" value)
4586 (setq ftags
4587 (append
4588 ftags
4589 (apply 'append
4590 (mapcar (lambda (x) (org-split-string x ":"))
4591 (org-split-string value)))))))
4592 ((equal key "DRAWERS")
4593 (setq drawers (delete-dups (append org-drawers (org-split-string value splitre)))))
4594 ((equal key "CONSTANTS")
4595 (setq const (append const (org-split-string value splitre))))
4596 ((equal key "STARTUP")
4597 (let ((opts (org-split-string value splitre))
4598 l var val)
4599 (while (setq l (pop opts))
4600 (when (setq l (assoc l org-startup-options))
4601 (setq var (nth 1 l) val (nth 2 l))
4602 (if (not (nth 3 l))
4603 (set (make-local-variable var) val)
4604 (if (not (listp (symbol-value var)))
4605 (set (make-local-variable var) nil))
4606 (set (make-local-variable var) (symbol-value var))
4607 (add-to-list var val))))))
4608 ((equal key "ARCHIVE")
4609 (setq arch value)
4610 (remove-text-properties 0 (length arch)
4611 '(face t fontified t) arch))
4612 ((equal key "LATEX_CLASS")
4613 (setq beamer-p (equal value "beamer")))
4614 ((equal key "OPTIONS")
4615 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4616 (setq scripts (read (match-string 2 value)))))
4617 ((equal key "SETUPFILE")
4618 (setq setup-contents (org-file-contents
4619 (expand-file-name
4620 (org-remove-double-quotes value))
4621 'noerror))
4622 (if (not ext-setup-or-nil)
4623 (setq ext-setup-or-nil setup-contents start 0)
4624 (setq ext-setup-or-nil
4625 (concat (substring ext-setup-or-nil 0 start)
4626 "\n" setup-contents "\n"
4627 (substring ext-setup-or-nil start)))))))
4628 ;; search for property blocks
4629 (goto-char (point-min))
4630 (while (re-search-forward org-block-regexp nil t)
4631 (when (equal "PROPERTY" (upcase (match-string 1)))
4632 (setq value (replace-regexp-in-string
4633 "[\n\r]" " " (match-string 4)))
4634 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4635 (setq props (org-update-property-plist (match-string 1 value)
4636 (match-string 2 value)
4637 props)))))))
4638 (org-set-local 'org-use-sub-superscripts scripts)
4639 (when cat
4640 (org-set-local 'org-category (intern cat))
4641 (push (cons "CATEGORY" cat) props))
4642 (when prio
4643 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4644 (setq prio (mapcar 'string-to-char prio))
4645 (org-set-local 'org-highest-priority (nth 0 prio))
4646 (org-set-local 'org-lowest-priority (nth 1 prio))
4647 (org-set-local 'org-default-priority (nth 2 prio)))
4648 (and props (org-set-local 'org-file-properties (nreverse props)))
4649 (and ftags (org-set-local 'org-file-tags
4650 (mapcar 'org-add-prop-inherited ftags)))
4651 (and drawers (org-set-local 'org-drawers drawers))
4652 (and arch (org-set-local 'org-archive-location arch))
4653 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4654 ;; Process the TODO keywords
4655 (unless kwds
4656 ;; Use the global values as if they had been given locally.
4657 (setq kwds (default-value 'org-todo-keywords))
4658 (if (stringp (car kwds))
4659 (setq kwds (list (cons org-todo-interpretation
4660 (default-value 'org-todo-keywords)))))
4661 (setq kwds (reverse kwds)))
4662 (setq kwds (nreverse kwds))
4663 (let (inter kws kw)
4664 (while (setq kws (pop kwds))
4665 (let ((kws (or
4666 (run-hook-with-args-until-success
4667 'org-todo-setup-filter-hook kws)
4668 kws)))
4669 (setq inter (pop kws) sep (member "|" kws)
4670 kws0 (delete "|" (copy-sequence kws))
4671 kwsa nil
4672 kws1 (mapcar
4673 (lambda (x)
4674 ;; 1 2
4675 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4676 (progn
4677 (setq kw (match-string 1 x)
4678 key (and (match-end 2) (match-string 2 x))
4679 log (org-extract-log-state-settings x))
4680 (push (cons kw (and key (string-to-char key))) kwsa)
4681 (and log (push log org-todo-log-states))
4683 (error "Invalid TODO keyword %s" x)))
4684 kws0)
4685 kwsa (if kwsa (append '((:startgroup))
4686 (nreverse kwsa)
4687 '((:endgroup))))
4688 hw (car kws1)
4689 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4690 tail (list inter hw (car dws) (org-last dws))))
4691 (add-to-list 'org-todo-heads hw 'append)
4692 (push kws1 org-todo-sets)
4693 (setq org-done-keywords (append org-done-keywords dws nil))
4694 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4695 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4696 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4697 (setq org-todo-sets (nreverse org-todo-sets)
4698 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4699 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4700 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4701 ;; Process the constants
4702 (when const
4703 (let (e cst)
4704 (while (setq e (pop const))
4705 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4706 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4707 (setq org-table-formula-constants-local cst)))
4709 ;; Process the tags.
4710 (when tags
4711 (let (e tgs)
4712 (while (setq e (pop tags))
4713 (cond
4714 ((equal e "{") (push '(:startgroup) tgs))
4715 ((equal e "}") (push '(:endgroup) tgs))
4716 ((equal e "\\n") (push '(:newline) tgs))
4717 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4718 (push (cons (match-string 1 e)
4719 (string-to-char (match-string 2 e)))
4720 tgs))
4721 (t (push (list e) tgs))))
4722 (org-set-local 'org-tag-alist nil)
4723 (while (setq e (pop tgs))
4724 (or (and (stringp (car e))
4725 (assoc (car e) org-tag-alist))
4726 (push e org-tag-alist)))))
4728 ;; Compute the regular expressions and other local variables.
4729 ;; Using `org-outline-regexp-bol' would complicate them much,
4730 ;; because of the fixed white space at the end of that string.
4731 (if (not org-done-keywords)
4732 (setq org-done-keywords (and org-todo-keywords-1
4733 (list (org-last org-todo-keywords-1)))))
4734 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4735 (length org-scheduled-string)
4736 (length org-clock-string)
4737 (length org-closed-string)))
4738 org-drawer-regexp
4739 (concat "^[ \t]*:\\("
4740 (mapconcat 'regexp-quote org-drawers "\\|")
4741 "\\):[ \t]*$")
4742 org-not-done-keywords
4743 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4744 org-todo-regexp
4745 (concat "\\("
4746 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4747 "\\)")
4748 org-not-done-regexp
4749 (concat "\\("
4750 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4751 "\\)")
4752 org-not-done-heading-regexp
4753 (format org-heading-keyword-regexp-format org-not-done-regexp)
4754 org-todo-line-regexp
4755 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
4756 org-complex-heading-regexp
4757 (concat "^\\(\\*+\\)"
4758 "\\(?: +" org-todo-regexp "\\)?"
4759 "\\(?: +\\(\\[#.\\]\\)\\)?"
4760 "\\(?: +\\(.*?\\)\\)?"
4761 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
4762 "[ \t]*$")
4763 org-complex-heading-regexp-format
4764 (concat "^\\(\\*+\\)"
4765 "\\(?: +" org-todo-regexp "\\)?"
4766 "\\(?: +\\(\\[#.\\]\\)\\)?"
4767 "\\(?: +"
4768 ;; Stats cookies can be stuck to body.
4769 "\\(?:\\[[0-9%%/]+\\] *\\)?"
4770 "\\(%s\\)"
4771 "\\(?: *\\[[0-9%%/]+\\]\\)?"
4772 "\\)"
4773 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
4774 "[ \t]*$")
4775 org-todo-line-tags-regexp
4776 (concat "^\\(\\*+\\)"
4777 "\\(?: +" org-todo-regexp "\\)?"
4778 "\\(?: +\\(.*?\\)\\)?"
4779 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
4780 "[ \t]*$")
4781 org-deadline-regexp (concat "\\<" org-deadline-string)
4782 org-deadline-time-regexp
4783 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4784 org-deadline-line-regexp
4785 (concat "\\<\\(" org-deadline-string "\\).*")
4786 org-scheduled-regexp
4787 (concat "\\<" org-scheduled-string)
4788 org-scheduled-time-regexp
4789 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4790 org-closed-time-regexp
4791 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4792 org-keyword-time-regexp
4793 (concat "\\<\\(" org-scheduled-string
4794 "\\|" org-deadline-string
4795 "\\|" org-closed-string
4796 "\\|" org-clock-string "\\)"
4797 " *[[<]\\([^]>]+\\)[]>]")
4798 org-keyword-time-not-clock-regexp
4799 (concat "\\<\\(" org-scheduled-string
4800 "\\|" org-deadline-string
4801 "\\|" org-closed-string
4802 "\\)"
4803 " *[[<]\\([^]>]+\\)[]>]")
4804 org-maybe-keyword-time-regexp
4805 (concat "\\(\\<\\(" org-scheduled-string
4806 "\\|" org-deadline-string
4807 "\\|" org-closed-string
4808 "\\|" org-clock-string "\\)\\)?"
4809 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4810 org-planning-or-clock-line-re
4811 (concat "^[ \t]*\\("
4812 org-scheduled-string "\\|"
4813 org-deadline-string "\\|"
4814 org-closed-string "\\|"
4815 org-clock-string "\\)")
4816 org-all-time-keywords
4817 (mapcar (lambda (w) (substring w 0 -1))
4818 (list org-scheduled-string org-deadline-string
4819 org-clock-string org-closed-string))
4821 (org-compute-latex-and-specials-regexp)
4822 (org-set-font-lock-defaults))))
4824 (defun org-file-contents (file &optional noerror)
4825 "Return the contents of FILE, as a string."
4826 (if (or (not file)
4827 (not (file-readable-p file)))
4828 (if noerror
4829 (progn
4830 (message "Cannot read file \"%s\"" file)
4831 (ding) (sit-for 2)
4833 (error "Cannot read file \"%s\"" file))
4834 (with-temp-buffer
4835 (insert-file-contents file)
4836 (buffer-string))))
4838 (defun org-extract-log-state-settings (x)
4839 "Extract the log state setting from a TODO keyword string.
4840 This will extract info from a string like \"WAIT(w@/!)\"."
4841 (let (kw key log1 log2)
4842 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4843 (setq kw (match-string 1 x)
4844 key (and (match-end 2) (match-string 2 x))
4845 log1 (and (match-end 3) (match-string 3 x))
4846 log2 (and (match-end 4) (match-string 4 x)))
4847 (and (or log1 log2)
4848 (list kw
4849 (and log1 (if (equal log1 "!") 'time 'note))
4850 (and log2 (if (equal log2 "!") 'time 'note)))))))
4852 (defun org-remove-keyword-keys (list)
4853 "Remove a pair of parenthesis at the end of each string in LIST."
4854 (mapcar (lambda (x)
4855 (if (string-match "(.*)$" x)
4856 (substring x 0 (match-beginning 0))
4858 list))
4860 (defun org-assign-fast-keys (alist)
4861 "Assign fast keys to a keyword-key alist.
4862 Respect keys that are already there."
4863 (let (new e (alt ?0))
4864 (while (setq e (pop alist))
4865 (if (or (memq (car e) '(:newline :endgroup :startgroup))
4866 (cdr e)) ;; Key already assigned.
4867 (push e new)
4868 (let ((clist (string-to-list (downcase (car e))))
4869 (used (append new alist)))
4870 (when (= (car clist) ?@)
4871 (pop clist))
4872 (while (and clist (rassoc (car clist) used))
4873 (pop clist))
4874 (unless clist
4875 (while (rassoc alt used)
4876 (incf alt)))
4877 (push (cons (car e) (or (car clist) alt)) new))))
4878 (nreverse new)))
4880 ;;; Some variables used in various places
4882 (defvar org-window-configuration nil
4883 "Used in various places to store a window configuration.")
4884 (defvar org-selected-window nil
4885 "Used in various places to store a window configuration.")
4886 (defvar org-finish-function nil
4887 "Function to be called when `C-c C-c' is used.
4888 This is for getting out of special buffers like remember.")
4891 ;; FIXME: Occasionally check by commenting these, to make sure
4892 ;; no other functions uses these, forgetting to let-bind them.
4893 (defvar entry)
4894 (defvar org-last-state)
4895 (defvar date)
4897 ;; Defined somewhere in this file, but used before definition.
4898 (defvar org-entities) ;; defined in org-entities.el
4899 (defvar org-struct-menu)
4900 (defvar org-org-menu)
4901 (defvar org-tbl-menu)
4903 ;;;; Define the Org-mode
4905 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4906 (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"))
4909 ;; We use a before-change function to check if a table might need
4910 ;; an update.
4911 (defvar org-table-may-need-update t
4912 "Indicates that a table might need an update.
4913 This variable is set by `org-before-change-function'.
4914 `org-table-align' sets it back to nil.")
4915 (defun org-before-change-function (beg end)
4916 "Every change indicates that a table might need an update."
4917 (setq org-table-may-need-update t))
4918 (defvar org-mode-map)
4919 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4920 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
4921 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4922 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
4923 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
4924 (defvar org-table-buffer-is-an nil)
4926 ;; `org-outline-regexp' ought to be a defconst but is let-binding in
4927 ;; some places -- e.g. see the macro org-with-limited-levels.
4929 ;; In Org buffers, the value of `outline-regexp' is that of
4930 ;; `org-outline-regexp'. The only function still directly relying on
4931 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
4932 ;; job when `orgstruct-mode' is active.
4933 (defvar org-outline-regexp "\\*+ "
4934 "Regexp to match Org headlines.")
4935 (defconst org-outline-regexp-bol "^\\*+ "
4936 "Regexp to match Org headlines.
4937 This is similar to `org-outline-regexp' but additionally makes
4938 sure that we are at the beginning of the line.")
4940 (defconst org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4941 "Matches an headline, putting stars and text into groups.
4942 Stars are put in group 1 and the trimmed body in group 2.")
4944 (defvar bidi-paragraph-direction)
4945 (defvar buffer-face-mode-face)
4946 (defvar org-auto-fill-fallback-function nil)
4947 (defvar org-indent-line-fallback-function nil)
4948 (defvar org-fill-paragraph-fallback-function nil)
4949 (make-variable-buffer-local 'org-auto-fill-fallback-function)
4950 (make-variable-buffer-local 'org-indent-line-fallback-function)
4951 (make-variable-buffer-local 'org-fill-paragraph-fallback-function)
4953 ;;;###autoload
4954 (define-derived-mode org-mode outline-mode "Org"
4955 "Outline-based notes management and organizer, alias
4956 \"Carsten's outline-mode for keeping track of everything.\"
4958 Org-mode develops organizational tasks around a NOTES file which
4959 contains information about projects as plain text. Org-mode is
4960 implemented on top of outline-mode, which is ideal to keep the content
4961 of large files well structured. It supports ToDo items, deadlines and
4962 time stamps, which magically appear in the diary listing of the Emacs
4963 calendar. Tables are easily created with a built-in table editor.
4964 Plain text URL-like links connect to websites, emails (VM), Usenet
4965 messages (Gnus), BBDB entries, and any files related to the project.
4966 For printing and sharing of notes, an Org-mode file (or a part of it)
4967 can be exported as a structured ASCII or HTML file.
4969 The following commands are available:
4971 \\{org-mode-map}"
4973 ;; Get rid of Outline menus, they are not needed
4974 ;; Need to do this here because define-derived-mode sets up
4975 ;; the keymap so late. Still, it is a waste to call this each time
4976 ;; we switch another buffer into org-mode.
4977 (if (featurep 'xemacs)
4978 (when (boundp 'outline-mode-menu-heading)
4979 ;; Assume this is Greg's port, it uses easymenu
4980 (easy-menu-remove outline-mode-menu-heading)
4981 (easy-menu-remove outline-mode-menu-show)
4982 (easy-menu-remove outline-mode-menu-hide))
4983 (define-key org-mode-map [menu-bar headings] 'undefined)
4984 (define-key org-mode-map [menu-bar hide] 'undefined)
4985 (define-key org-mode-map [menu-bar show] 'undefined))
4987 (org-load-modules-maybe)
4988 (easy-menu-add org-org-menu)
4989 (easy-menu-add org-tbl-menu)
4990 (org-install-agenda-files-menu)
4991 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
4992 (add-to-invisibility-spec '(org-cwidth))
4993 (add-to-invisibility-spec '(org-hide-block . t))
4994 (when (featurep 'xemacs)
4995 (org-set-local 'line-move-ignore-invisible t))
4996 (org-set-local 'outline-regexp org-outline-regexp)
4997 (org-set-local 'outline-level 'org-outline-level)
4998 (setq bidi-paragraph-direction 'left-to-right)
4999 (when (and org-ellipsis
5000 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5001 (fboundp 'make-glyph-code))
5002 (unless org-display-table
5003 (setq org-display-table (make-display-table)))
5004 (set-display-table-slot
5005 org-display-table 4
5006 (vconcat (mapcar
5007 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5008 org-ellipsis)))
5009 (if (stringp org-ellipsis) org-ellipsis "..."))))
5010 (setq buffer-display-table org-display-table))
5011 (org-set-regexps-and-options)
5012 (when (and org-tag-faces (not org-tags-special-faces-re))
5013 ;; tag faces set outside customize.... force initialization.
5014 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5015 ;; Calc embedded
5016 (org-set-local 'calc-embedded-open-mode "# ")
5017 (modify-syntax-entry ?@ "w")
5018 (if org-startup-truncated (setq truncate-lines t))
5019 (org-set-local 'font-lock-unfontify-region-function
5020 'org-unfontify-region)
5021 ;; Activate before-change-function
5022 (org-set-local 'org-table-may-need-update t)
5023 (org-add-hook 'before-change-functions 'org-before-change-function nil
5024 'local)
5025 ;; Check for running clock before killing a buffer
5026 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5027 ;; Paragraphs and auto-filling
5028 (org-set-autofill-regexps)
5029 (setq indent-line-function 'org-indent-line-function)
5030 (org-update-radio-target-regexp)
5031 ;; Beginning/end of defun
5032 (org-set-local 'beginning-of-defun-function 'org-beginning-of-defun)
5033 (org-set-local 'end-of-defun-function 'org-end-of-defun)
5034 ;; Next error for sparse trees
5035 (org-set-local 'next-error-function 'org-occur-next-match)
5036 ;; Make sure dependence stuff works reliably, even for users who set it
5037 ;; too late :-(
5038 (if org-enforce-todo-dependencies
5039 (add-hook 'org-blocker-hook
5040 'org-block-todo-from-children-or-siblings-or-parent)
5041 (remove-hook 'org-blocker-hook
5042 'org-block-todo-from-children-or-siblings-or-parent))
5043 (if org-enforce-todo-checkbox-dependencies
5044 (add-hook 'org-blocker-hook
5045 'org-block-todo-from-checkboxes)
5046 (remove-hook 'org-blocker-hook
5047 'org-block-todo-from-checkboxes))
5049 ;; Comment characters
5050 (org-set-local 'comment-start "#")
5051 (org-set-local 'comment-padding " ")
5053 ;; Align options lines
5054 (org-set-local
5055 'align-mode-rules-list
5056 '((org-in-buffer-settings
5057 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5058 (modes . '(org-mode)))))
5060 ;; Imenu
5061 (org-set-local 'imenu-create-index-function
5062 'org-imenu-get-tree)
5064 ;; Make isearch reveal context
5065 (if (or (featurep 'xemacs)
5066 (not (boundp 'outline-isearch-open-invisible-function)))
5067 ;; Emacs 21 and XEmacs make use of the hook
5068 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5069 ;; Emacs 22 deals with this through a special variable
5070 (org-set-local 'outline-isearch-open-invisible-function
5071 (lambda (&rest ignore) (org-show-context 'isearch))))
5073 ;; Turn on org-beamer-mode?
5074 (and org-startup-with-beamer-mode (org-beamer-mode 1))
5076 ;; Setup the pcomplete hooks
5077 (set (make-local-variable 'pcomplete-command-completion-function)
5078 'org-pcomplete-initial)
5079 (set (make-local-variable 'pcomplete-command-name-function)
5080 'org-command-at-point)
5081 (set (make-local-variable 'pcomplete-default-completion-function)
5082 'ignore)
5083 (set (make-local-variable 'pcomplete-parse-arguments-function)
5084 'org-parse-arguments)
5085 (set (make-local-variable 'pcomplete-termination-string) "")
5086 (when (>= emacs-major-version 23)
5087 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5089 ;; If empty file that did not turn on org-mode automatically, make it to.
5090 (if (and org-insert-mode-line-in-empty-file
5091 (org-called-interactively-p 'any)
5092 (= (point-min) (point-max)))
5093 (insert "# -*- mode: org -*-\n\n"))
5094 (unless org-inhibit-startup
5095 (when org-startup-align-all-tables
5096 (let ((bmp (buffer-modified-p)))
5097 (org-table-map-tables 'org-table-align 'quietly)
5098 (set-buffer-modified-p bmp)))
5099 (when org-startup-with-inline-images
5100 (org-display-inline-images))
5101 (when org-startup-indented
5102 (require 'org-indent)
5103 (org-indent-mode 1))
5104 (unless org-inhibit-startup-visibility-stuff
5105 (org-set-startup-visibility))))
5107 (when (fboundp 'abbrev-table-put)
5108 (abbrev-table-put org-mode-abbrev-table
5109 :parents (list text-mode-abbrev-table)))
5111 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5113 (defun org-current-time ()
5114 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
5115 (if (> (car org-time-stamp-rounding-minutes) 1)
5116 (let ((r (car org-time-stamp-rounding-minutes))
5117 (time (decode-time)))
5118 (apply 'encode-time
5119 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5120 (nthcdr 2 time))))
5121 (current-time)))
5123 (defun org-today ()
5124 "Return today date, considering `org-extend-today-until'."
5125 (time-to-days
5126 (time-subtract (current-time)
5127 (list 0 (* 3600 org-extend-today-until) 0))))
5129 ;;;; Font-Lock stuff, including the activators
5131 (defvar org-mouse-map (make-sparse-keymap))
5132 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5133 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5134 (when org-mouse-1-follows-link
5135 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5136 (when org-tab-follows-link
5137 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5138 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5140 (require 'font-lock)
5142 (defconst org-non-link-chars "]\t\n\r<>")
5143 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5144 "shell" "elisp" "doi" "message"))
5145 (defvar org-link-types-re nil
5146 "Matches a link that has a url-like prefix like \"http:\"")
5147 (defvar org-link-re-with-space nil
5148 "Matches a link with spaces, optional angular brackets around it.")
5149 (defvar org-link-re-with-space2 nil
5150 "Matches a link with spaces, optional angular brackets around it.")
5151 (defvar org-link-re-with-space3 nil
5152 "Matches a link with spaces, only for internal part in bracket links.")
5153 (defvar org-angle-link-re nil
5154 "Matches link with angular brackets, spaces are allowed.")
5155 (defvar org-plain-link-re nil
5156 "Matches plain link, without spaces.")
5157 (defvar org-bracket-link-regexp nil
5158 "Matches a link in double brackets.")
5159 (defvar org-bracket-link-analytic-regexp nil
5160 "Regular expression used to analyze links.
5161 Here is what the match groups contain after a match:
5162 1: http:
5163 2: http
5164 3: path
5165 4: [desc]
5166 5: desc")
5167 (defvar org-bracket-link-analytic-regexp++ nil
5168 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5169 (defvar org-any-link-re nil
5170 "Regular expression matching any link.")
5172 (defcustom org-match-sexp-depth 3
5173 "Number of stacked braces for sub/superscript matching.
5174 This has to be set before loading org.el to be effective."
5175 :group 'org-export-translation ; ??????????????????????????/
5176 :type 'integer)
5178 (defun org-create-multibrace-regexp (left right n)
5179 "Create a regular expression which will match a balanced sexp.
5180 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5181 as single character strings.
5182 The regexp returned will match the entire expression including the
5183 delimiters. It will also define a single group which contains the
5184 match except for the outermost delimiters. The maximum depth of
5185 stacked delimiters is N. Escaping delimiters is not possible."
5186 (let* ((nothing (concat "[^" left right "]*?"))
5187 (or "\\|")
5188 (re nothing)
5189 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5190 (while (> n 1)
5191 (setq n (1- n)
5192 re (concat re or next)
5193 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5194 (concat left "\\(" re "\\)" right)))
5196 (defvar org-match-substring-regexp
5197 (concat
5198 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5199 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5200 "\\|"
5201 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5202 "\\|"
5203 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5204 "The regular expression matching a sub- or superscript.")
5206 (defvar org-match-substring-with-braces-regexp
5207 (concat
5208 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5209 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5210 "\\)")
5211 "The regular expression matching a sub- or superscript, forcing braces.")
5213 (defun org-make-link-regexps ()
5214 "Update the link regular expressions.
5215 This should be called after the variable `org-link-types' has changed."
5216 (setq org-link-types-re
5217 (concat
5218 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5219 org-link-re-with-space
5220 (concat
5221 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5222 "\\([^" org-non-link-chars " ]"
5223 "[^" org-non-link-chars "]*"
5224 "[^" org-non-link-chars " ]\\)>?")
5225 org-link-re-with-space2
5226 (concat
5227 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5228 "\\([^" org-non-link-chars " ]"
5229 "[^\t\n\r]*"
5230 "[^" org-non-link-chars " ]\\)>?")
5231 org-link-re-with-space3
5232 (concat
5233 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5234 "\\([^" org-non-link-chars " ]"
5235 "[^\t\n\r]*\\)")
5236 org-angle-link-re
5237 (concat
5238 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5239 "\\([^" org-non-link-chars " ]"
5240 "[^" org-non-link-chars "]*"
5241 "\\)>")
5242 org-plain-link-re
5243 (concat
5244 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5245 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5246 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5247 org-bracket-link-regexp
5248 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5249 org-bracket-link-analytic-regexp
5250 (concat
5251 "\\[\\["
5252 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5253 "\\([^]]+\\)"
5254 "\\]"
5255 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5256 "\\]")
5257 org-bracket-link-analytic-regexp++
5258 (concat
5259 "\\[\\["
5260 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5261 "\\([^]]+\\)"
5262 "\\]"
5263 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5264 "\\]")
5265 org-any-link-re
5266 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5267 org-angle-link-re "\\)\\|\\("
5268 org-plain-link-re "\\)")))
5270 (org-make-link-regexps)
5272 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5273 "Regular expression for fast time stamp matching.")
5274 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5275 "Regular expression for fast time stamp matching.")
5276 (defconst org-ts-regexp0
5277 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5278 "Regular expression matching time strings for analysis.
5279 This one does not require the space after the date, so it can be used
5280 on a string that terminates immediately after the date.")
5281 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5282 "Regular expression matching time strings for analysis.")
5283 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5284 "Regular expression matching time stamps, with groups.")
5285 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5286 "Regular expression matching time stamps (also [..]), with groups.")
5287 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5288 "Regular expression matching a time stamp range.")
5289 (defconst org-tr-regexp-both
5290 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5291 "Regular expression matching a time stamp range.")
5292 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5293 org-ts-regexp "\\)?")
5294 "Regular expression matching a time stamp or time stamp range.")
5295 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5296 org-ts-regexp-both "\\)?")
5297 "Regular expression matching a time stamp or time stamp range.
5298 The time stamps may be either active or inactive.")
5300 (defvar org-emph-face nil)
5302 (defun org-do-emphasis-faces (limit)
5303 "Run through the buffer and add overlays to emphasized strings."
5304 (let (rtn a)
5305 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5306 (if (not (= (char-after (match-beginning 3))
5307 (char-after (match-beginning 4))))
5308 (progn
5309 (setq rtn t)
5310 (setq a (assoc (match-string 3) org-emphasis-alist))
5311 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5312 'face
5313 (nth 1 a))
5314 (and (nth 4 a)
5315 (org-remove-flyspell-overlays-in
5316 (match-beginning 0) (match-end 0)))
5317 (add-text-properties (match-beginning 2) (match-end 2)
5318 '(font-lock-multiline t org-emphasis t))
5319 (when org-hide-emphasis-markers
5320 (add-text-properties (match-end 4) (match-beginning 5)
5321 '(invisible org-link))
5322 (add-text-properties (match-beginning 3) (match-end 3)
5323 '(invisible org-link)))))
5324 (backward-char 1))
5325 rtn))
5327 (defun org-emphasize (&optional char)
5328 "Insert or change an emphasis, i.e. a font like bold or italic.
5329 If there is an active region, change that region to a new emphasis.
5330 If there is no region, just insert the marker characters and position
5331 the cursor between them.
5332 CHAR should be either the marker character, or the first character of the
5333 HTML tag associated with that emphasis. If CHAR is a space, the means
5334 to remove the emphasis of the selected region.
5335 If char is not given (for example in an interactive call) it
5336 will be prompted for."
5337 (interactive)
5338 (let ((eal org-emphasis-alist) e det
5339 (erc org-emphasis-regexp-components)
5340 (prompt "")
5341 (string "") beg end move tag c s)
5342 (if (org-region-active-p)
5343 (setq beg (region-beginning) end (region-end)
5344 string (buffer-substring beg end))
5345 (setq move t))
5347 (while (setq e (pop eal))
5348 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5349 c (aref tag 0))
5350 (push (cons c (string-to-char (car e))) det)
5351 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5352 (substring tag 1)))))
5353 (setq det (nreverse det))
5354 (unless char
5355 (message "%s" (concat "Emphasis marker or tag:" prompt))
5356 (setq char (read-char-exclusive)))
5357 (setq char (or (cdr (assoc char det)) char))
5358 (if (equal char ?\ )
5359 (setq s "" move nil)
5360 (unless (assoc (char-to-string char) org-emphasis-alist)
5361 (error "No such emphasis marker: \"%c\"" char))
5362 (setq s (char-to-string char)))
5363 (while (and (> (length string) 1)
5364 (equal (substring string 0 1) (substring string -1))
5365 (assoc (substring string 0 1) org-emphasis-alist))
5366 (setq string (substring string 1 -1)))
5367 (setq string (concat s string s))
5368 (if beg (delete-region beg end))
5369 (unless (or (bolp)
5370 (string-match (concat "[" (nth 0 erc) "\n]")
5371 (char-to-string (char-before (point)))))
5372 (insert " "))
5373 (unless (or (eobp)
5374 (string-match (concat "[" (nth 1 erc) "\n]")
5375 (char-to-string (char-after (point)))))
5376 (insert " ") (backward-char 1))
5377 (insert string)
5378 (and move (backward-char 1))))
5380 (defconst org-nonsticky-props
5381 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
5383 (defsubst org-rear-nonsticky-at (pos)
5384 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5386 (defun org-activate-plain-links (limit)
5387 "Run through the buffer and add overlays to links."
5388 (catch 'exit
5389 (let (f)
5390 (if (re-search-forward org-plain-link-re limit t)
5391 (progn
5392 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5393 (setq f (get-text-property (match-beginning 0) 'face))
5394 (if (or (eq f 'org-tag)
5395 (and (listp f) (memq 'org-tag f)))
5397 (add-text-properties (match-beginning 0) (match-end 0)
5398 (list 'mouse-face 'highlight
5399 'face 'org-link
5400 'keymap org-mouse-map))
5401 (org-rear-nonsticky-at (match-end 0)))
5402 t)))))
5404 (defun org-activate-code (limit)
5405 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5406 (progn
5407 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5408 (remove-text-properties (match-beginning 0) (match-end 0)
5409 '(display t invisible t intangible t))
5410 t)))
5412 (defcustom org-src-fontify-natively nil
5413 "When non-nil, fontify code in code blocks."
5414 :type 'boolean
5415 :version "24.1"
5416 :group 'org-appearance
5417 :group 'org-babel)
5419 (defun org-fontify-meta-lines-and-blocks (limit)
5420 (condition-case nil
5421 (org-fontify-meta-lines-and-blocks-1 limit)
5422 (error (message "org-mode fontification error"))))
5424 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5425 "Fontify #+ lines and blocks, in the correct ways."
5426 (let ((case-fold-search t))
5427 (if (re-search-forward
5428 "^\\([ \t]*#\\+\\(\\([a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5429 limit t)
5430 (let ((beg (match-beginning 0))
5431 (block-start (match-end 0))
5432 (block-end nil)
5433 (lang (match-string 7))
5434 (beg1 (line-beginning-position 2))
5435 (dc1 (downcase (match-string 2)))
5436 (dc3 (downcase (match-string 3)))
5437 end end1 quoting block-type ovl)
5438 (cond
5439 ((member dc1 '("html:" "ascii:" "latex:" "docbook:"))
5440 ;; a single line of backend-specific content
5441 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5442 (remove-text-properties (match-beginning 0) (match-end 0)
5443 '(display t invisible t intangible t))
5444 (add-text-properties (match-beginning 1) (match-end 3)
5445 '(font-lock-fontified t face org-meta-line))
5446 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5447 '(font-lock-fontified t face org-block))
5448 ; for backend-specific code
5450 ((and (match-end 4) (equal dc3 "begin"))
5451 ;; Truly a block
5452 (setq block-type (downcase (match-string 5))
5453 quoting (member block-type org-protecting-blocks))
5454 (when (re-search-forward
5455 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5456 nil t) ;; on purpose, we look further than LIMIT
5457 (setq end (min (point-max) (match-end 0))
5458 end1 (min (point-max) (1- (match-beginning 0))))
5459 (setq block-end (match-beginning 0))
5460 (when quoting
5461 (remove-text-properties beg end
5462 '(display t invisible t intangible t)))
5463 (add-text-properties
5464 beg end
5465 '(font-lock-fontified t font-lock-multiline t))
5466 (add-text-properties beg beg1 '(face org-meta-line))
5467 (add-text-properties end1 (min (point-max) (1+ end))
5468 '(face org-meta-line)) ; for end_src
5469 (cond
5470 ((and lang (not (string= lang "")) org-src-fontify-natively)
5471 (org-src-font-lock-fontify-block lang block-start block-end)
5472 ;; remove old background overlays
5473 (mapc (lambda (ov)
5474 (if (eq (overlay-get ov 'face) 'org-block-background)
5475 (delete-overlay ov)))
5476 (overlays-at (/ (+ beg1 block-end) 2)))
5477 ;; add a background overlay
5478 (setq ovl (make-overlay beg1 block-end))
5479 (overlay-put ovl 'face 'org-block-background)
5480 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5481 (quoting
5482 (add-text-properties beg1 (min (point-max) (1+ end1))
5483 '(face org-block))) ; end of source block
5484 ((not org-fontify-quote-and-verse-blocks))
5485 ((string= block-type "quote")
5486 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5487 ((string= block-type "verse")
5488 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5489 (add-text-properties beg beg1 '(face org-block-begin-line))
5490 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5491 '(face org-block-end-line))
5493 ((member dc1 '("title:" "author:" "email:" "date:"))
5494 (add-text-properties
5495 beg (match-end 3)
5496 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5497 '(font-lock-fontified t invisible t)
5498 '(font-lock-fontified t face org-document-info-keyword)))
5499 (add-text-properties
5500 (match-beginning 6) (match-end 6)
5501 (if (string-equal dc1 "title:")
5502 '(font-lock-fontified t face org-document-title)
5503 '(font-lock-fontified t face org-document-info))))
5504 ((not (member (char-after beg) '(?\ ?\t)))
5505 ;; just any other in-buffer setting, but not indented
5506 (add-text-properties
5507 beg (match-end 0)
5508 '(font-lock-fontified t face org-meta-line))
5510 ((or (member dc1 '("begin:" "end:" "caption:" "label:"
5511 "orgtbl:" "tblfm:" "tblname:" "results:"
5512 "call:" "header:" "headers:" "name:"))
5513 (and (match-end 4) (equal dc3 "attr")))
5514 (add-text-properties
5515 beg (match-end 0)
5516 '(font-lock-fontified t face org-meta-line))
5518 ((member dc3 '(" " ""))
5519 (add-text-properties
5520 beg (match-end 0)
5521 '(font-lock-fontified t face font-lock-comment-face)))
5522 (t nil))))))
5524 (defun org-strip-protective-commas (beg end)
5525 "Strip protective commas between BEG and END in the current buffer."
5526 (interactive "r")
5527 (save-excursion
5528 (save-match-data
5529 (goto-char beg)
5530 (let ((front-line (save-excursion
5531 (re-search-forward
5532 "[^[:space:]]" end t)
5533 (goto-char (match-beginning 0))
5534 (current-column))))
5535 (while (re-search-forward "^[ \t]*\\(,\\)\\([*]\\|#\\+\\)" end t)
5536 (goto-char (match-beginning 1))
5537 (when (= (current-column) front-line)
5538 (replace-match "" nil nil nil 1)))))))
5540 (defun org-activate-angle-links (limit)
5541 "Run through the buffer and add overlays to links."
5542 (if (re-search-forward org-angle-link-re limit t)
5543 (progn
5544 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5545 (add-text-properties (match-beginning 0) (match-end 0)
5546 (list 'mouse-face 'highlight
5547 'keymap org-mouse-map))
5548 (org-rear-nonsticky-at (match-end 0))
5549 t)))
5551 (defun org-activate-footnote-links (limit)
5552 "Run through the buffer and add overlays to footnotes."
5553 (let ((fn (org-footnote-next-reference-or-definition limit)))
5554 (when fn
5555 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5556 (org-remove-flyspell-overlays-in beg end)
5557 (add-text-properties beg end
5558 (list 'mouse-face 'highlight
5559 'keymap org-mouse-map
5560 'help-echo
5561 (if (= (point-at-bol) beg)
5562 "Footnote definition"
5563 "Footnote reference")
5564 'font-lock-fontified t
5565 'font-lock-multiline t
5566 'face 'org-footnote))))))
5568 (defun org-activate-bracket-links (limit)
5569 "Run through the buffer and add overlays to bracketed links."
5570 (if (re-search-forward org-bracket-link-regexp limit t)
5571 (let* ((help (concat "LINK: "
5572 (org-match-string-no-properties 1)))
5573 ;; FIXME: above we should remove the escapes.
5574 ;; but that requires another match, protecting match data,
5575 ;; a lot of overhead for font-lock.
5576 (ip (org-maybe-intangible
5577 (list 'invisible 'org-link
5578 'keymap org-mouse-map 'mouse-face 'highlight
5579 'font-lock-multiline t 'help-echo help)))
5580 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5581 'font-lock-multiline t 'help-echo help)))
5582 ;; We need to remove the invisible property here. Table narrowing
5583 ;; may have made some of this invisible.
5584 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5585 (remove-text-properties (match-beginning 0) (match-end 0)
5586 '(invisible nil))
5587 (if (match-end 3)
5588 (progn
5589 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5590 (org-rear-nonsticky-at (match-beginning 3))
5591 (add-text-properties (match-beginning 3) (match-end 3) vp)
5592 (org-rear-nonsticky-at (match-end 3))
5593 (add-text-properties (match-end 3) (match-end 0) ip)
5594 (org-rear-nonsticky-at (match-end 0)))
5595 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5596 (org-rear-nonsticky-at (match-beginning 1))
5597 (add-text-properties (match-beginning 1) (match-end 1) vp)
5598 (org-rear-nonsticky-at (match-end 1))
5599 (add-text-properties (match-end 1) (match-end 0) ip)
5600 (org-rear-nonsticky-at (match-end 0)))
5601 t)))
5603 (defun org-activate-dates (limit)
5604 "Run through the buffer and add overlays to dates."
5605 (if (re-search-forward org-tsr-regexp-both limit t)
5606 (progn
5607 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5608 (add-text-properties (match-beginning 0) (match-end 0)
5609 (list 'mouse-face 'highlight
5610 'keymap org-mouse-map))
5611 (org-rear-nonsticky-at (match-end 0))
5612 (when org-display-custom-times
5613 (if (match-end 3)
5614 (org-display-custom-time (match-beginning 3) (match-end 3)))
5615 (org-display-custom-time (match-beginning 1) (match-end 1)))
5616 t)))
5618 (defvar org-target-link-regexp nil
5619 "Regular expression matching radio targets in plain text.")
5620 (make-variable-buffer-local 'org-target-link-regexp)
5621 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5622 "Regular expression matching a link target.")
5623 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5624 "Regular expression matching a radio target.")
5625 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5626 "Regular expression matching any target.")
5628 (defun org-activate-target-links (limit)
5629 "Run through the buffer and add overlays to target matches."
5630 (when org-target-link-regexp
5631 (let ((case-fold-search t))
5632 (if (re-search-forward org-target-link-regexp limit t)
5633 (progn
5634 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5635 (add-text-properties (match-beginning 0) (match-end 0)
5636 (list 'mouse-face 'highlight
5637 'keymap org-mouse-map
5638 'help-echo "Radio target link"
5639 'org-linked-text t))
5640 (org-rear-nonsticky-at (match-end 0))
5641 t)))))
5643 (defun org-update-radio-target-regexp ()
5644 "Find all radio targets in this file and update the regular expression."
5645 (interactive)
5646 (when (memq 'radio org-activate-links)
5647 (setq org-target-link-regexp
5648 (org-make-target-link-regexp (org-all-targets 'radio)))
5649 (org-restart-font-lock)))
5651 (defun org-hide-wide-columns (limit)
5652 (let (s e)
5653 (setq s (text-property-any (point) (or limit (point-max))
5654 'org-cwidth t))
5655 (when s
5656 (setq e (next-single-property-change s 'org-cwidth))
5657 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5658 (goto-char e)
5659 t)))
5661 (defvar org-latex-and-specials-regexp nil
5662 "Regular expression for highlighting export special stuff.")
5663 (defvar org-match-substring-regexp)
5664 (defvar org-match-substring-with-braces-regexp)
5666 ;; This should be with the exporter code, but we also use if for font-locking
5667 (defconst org-export-html-special-string-regexps
5668 '(("\\\\-" . "&shy;")
5669 ("---\\([^-]\\)" . "&mdash;\\1")
5670 ("--\\([^-]\\)" . "&ndash;\\1")
5671 ("\\.\\.\\." . "&hellip;"))
5672 "Regular expressions for special string conversion.")
5675 (defun org-compute-latex-and-specials-regexp ()
5676 "Compute regular expression for stuff treated specially by exporters."
5677 (if (not org-highlight-latex-fragments-and-specials)
5678 (org-set-local 'org-latex-and-specials-regexp nil)
5679 (require 'org-exp)
5680 (let*
5681 ((matchers (plist-get org-format-latex-options :matchers))
5682 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5683 org-latex-regexps)))
5684 (org-export-allow-BIND nil)
5685 (options (org-combine-plists (org-default-export-plist)
5686 (org-infile-export-plist)))
5687 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5688 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5689 (org-export-with-TeX-macros (plist-get options :TeX-macros))
5690 (org-export-html-expand (plist-get options :expand-quoted-html))
5691 (org-export-with-special-strings (plist-get options :special-strings))
5692 (re-sub
5693 (cond
5694 ((equal org-export-with-sub-superscripts '{})
5695 (list org-match-substring-with-braces-regexp))
5696 (org-export-with-sub-superscripts
5697 (list org-match-substring-regexp))
5698 (t nil)))
5699 (re-latex
5700 (if org-export-with-LaTeX-fragments
5701 (mapcar (lambda (x) (nth 1 x)) latexs)))
5702 (re-macros
5703 (if org-export-with-TeX-macros
5704 (list (concat "\\\\"
5705 (regexp-opt
5706 (append
5708 (delq nil
5709 (mapcar 'car-safe
5710 (append org-entities-user
5711 org-entities)))
5712 (if (boundp 'org-latex-entities)
5713 (mapcar (lambda (x)
5714 (or (car-safe x) x))
5715 org-latex-entities)
5716 nil))
5717 'words))) ; FIXME
5719 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5720 (re-special (if org-export-with-special-strings
5721 (mapcar (lambda (x) (car x))
5722 org-export-html-special-string-regexps)))
5723 (re-rest
5724 (delq nil
5725 (list
5726 (if org-export-html-expand "@<[^>\n]+>")
5727 ))))
5728 (org-set-local
5729 'org-latex-and-specials-regexp
5730 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5731 re-rest) "\\|")))))
5733 (defun org-do-latex-and-special-faces (limit)
5734 "Run through the buffer and add overlays to links."
5735 (when org-latex-and-specials-regexp
5736 (let (rtn d)
5737 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5738 limit t))
5739 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5740 'face))
5741 '(org-code org-verbatim underline)))
5742 (progn
5743 (setq rtn t
5744 d (cond ((member (char-after (1+ (match-beginning 0)))
5745 '(?_ ?^)) 1)
5746 (t 0)))
5747 (font-lock-prepend-text-property
5748 (+ d (match-beginning 0)) (match-end 0)
5749 'face 'org-latex-and-export-specials)
5750 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5751 '(font-lock-multiline t)))))
5752 rtn)))
5754 (defun org-restart-font-lock ()
5755 "Restart `font-lock-mode', to force refontification."
5756 (when (and (boundp 'font-lock-mode) font-lock-mode)
5757 (font-lock-mode -1)
5758 (font-lock-mode 1)))
5760 (defun org-all-targets (&optional radio)
5761 "Return a list of all targets in this file.
5762 With optional argument RADIO, only find radio targets."
5763 (let ((re (if radio org-radio-target-regexp org-target-regexp))
5764 rtn)
5765 (save-excursion
5766 (goto-char (point-min))
5767 (while (re-search-forward re nil t)
5768 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
5769 rtn)))
5771 (defun org-make-target-link-regexp (targets)
5772 "Make regular expression matching all strings in TARGETS.
5773 The regular expression finds the targets also if there is a line break
5774 between words."
5775 (and targets
5776 (concat
5777 "\\<\\("
5778 (mapconcat
5779 (lambda (x)
5780 (setq x (regexp-quote x))
5781 (while (string-match " +" x)
5782 (setq x (replace-match "\\s-+" t t x)))
5784 targets
5785 "\\|")
5786 "\\)\\>")))
5788 (defun org-activate-tags (limit)
5789 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
5790 (progn
5791 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5792 (add-text-properties (match-beginning 1) (match-end 1)
5793 (list 'mouse-face 'highlight
5794 'keymap org-mouse-map))
5795 (org-rear-nonsticky-at (match-end 1))
5796 t)))
5798 (defun org-outline-level ()
5799 "Compute the outline level of the heading at point.
5800 This function assumes that the cursor is at the beginning of a line matched
5801 by `outline-regexp'. Otherwise it returns garbage.
5802 If this is called at a normal headline, the level is the number of stars.
5803 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
5804 (save-excursion
5805 (looking-at org-outline-regexp)
5806 (1- (- (match-end 0) (match-beginning 0)))))
5808 (defvar org-font-lock-keywords nil)
5810 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\+?\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
5811 "Regular expression matching a property line.")
5813 (defvar org-font-lock-hook nil
5814 "Functions to be called for special font lock stuff.")
5816 (defvar org-font-lock-set-keywords-hook nil
5817 "Functions that can manipulate `org-font-lock-extra-keywords'.
5818 This is called after `org-font-lock-extra-keywords' is defined, but before
5819 it is installed to be used by font lock. This can be useful if something
5820 needs to be inserted at a specific position in the font-lock sequence.")
5822 (defun org-font-lock-hook (limit)
5823 (run-hook-with-args 'org-font-lock-hook limit))
5825 (defun org-set-font-lock-defaults ()
5826 (let* ((em org-fontify-emphasized-text)
5827 (lk org-activate-links)
5828 (org-font-lock-extra-keywords
5829 (list
5830 ;; Call the hook
5831 '(org-font-lock-hook)
5832 ;; Headlines
5833 `(,(if org-fontify-whole-heading-line
5834 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
5835 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
5836 (1 (org-get-level-face 1))
5837 (2 (org-get-level-face 2))
5838 (3 (org-get-level-face 3)))
5839 ;; Table lines
5840 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5841 (1 'org-table t))
5842 ;; Table internals
5843 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5844 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5845 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5846 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
5847 ;; Drawers
5848 (list org-drawer-regexp '(0 'org-special-keyword t))
5849 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5850 ;; Properties
5851 (list org-property-re
5852 '(1 'org-special-keyword t)
5853 '(3 'org-property-value t))
5854 ;; Links
5855 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5856 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5857 (if (memq 'plain lk) '(org-activate-plain-links))
5858 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5859 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5860 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5861 (if (memq 'footnote lk) '(org-activate-footnote-links))
5862 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5863 '(org-hide-wide-columns (0 nil append))
5864 ;; TODO keyword
5865 (list (format org-heading-keyword-regexp-format
5866 org-todo-regexp)
5867 '(2 (org-get-todo-face 2) t))
5868 ;; DONE
5869 (if org-fontify-done-headline
5870 (list (format org-heading-keyword-regexp-format
5871 (concat
5872 "\\(?:"
5873 (mapconcat 'regexp-quote org-done-keywords "\\|")
5874 "\\)"))
5875 '(2 'org-headline-done t))
5876 nil)
5877 ;; Priorities
5878 '(org-font-lock-add-priority-faces)
5879 ;; Tags
5880 '(org-font-lock-add-tag-faces)
5881 ;; Special keywords
5882 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5883 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5884 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5885 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5886 ;; Emphasis
5887 (if em
5888 (if (featurep 'xemacs)
5889 '(org-do-emphasis-faces (0 nil append))
5890 '(org-do-emphasis-faces)))
5891 ;; Checkboxes
5892 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
5893 1 'org-checkbox prepend)
5894 (if (cdr (assq 'checkbox org-list-automatic-rules))
5895 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5896 (0 (org-get-checkbox-statistics-face) t)))
5897 ;; Description list items
5898 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
5899 1 'org-list-dt prepend)
5900 ;; ARCHIVEd headings
5901 (list (concat
5902 org-outline-regexp-bol
5903 "\\(.*:" org-archive-tag ":.*\\)")
5904 '(1 'org-archived prepend))
5905 ;; Specials
5906 '(org-do-latex-and-special-faces)
5907 '(org-fontify-entities)
5908 '(org-raise-scripts)
5909 ;; Code
5910 '(org-activate-code (1 'org-code t))
5911 ;; COMMENT
5912 (list (format org-heading-keyword-regexp-format
5913 (concat "\\("
5914 org-comment-string "\\|" org-quote-string
5915 "\\)"))
5916 '(2 'org-special-keyword t))
5917 '("^#.*" (0 'font-lock-comment-face t))
5918 ;; Blocks and meta lines
5919 '(org-fontify-meta-lines-and-blocks)
5921 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5922 (run-hooks 'org-font-lock-set-keywords-hook)
5923 ;; Now set the full font-lock-keywords
5924 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5925 (org-set-local 'font-lock-defaults
5926 '(org-font-lock-keywords t nil nil backward-paragraph))
5927 (kill-local-variable 'font-lock-keywords) nil))
5929 (defun org-toggle-pretty-entities ()
5930 "Toggle the composition display of entities as UTF8 characters."
5931 (interactive)
5932 (org-set-local 'org-pretty-entities (not org-pretty-entities))
5933 (org-restart-font-lock)
5934 (if org-pretty-entities
5935 (message "Entities are displayed as UTF8 characters")
5936 (save-restriction
5937 (widen)
5938 (org-decompose-region (point-min) (point-max))
5939 (message "Entities are displayed plain"))))
5941 (defun org-fontify-entities (limit)
5942 "Find an entity to fontify."
5943 (let (ee)
5944 (when org-pretty-entities
5945 (catch 'match
5946 (while (re-search-forward
5947 "\\\\\\(frac[13][24]\\|[a-zA-Z]+\\)\\($\\|[^[:alpha:]\n]\\)"
5948 limit t)
5949 (if (and (not (org-in-indented-comment-line))
5950 (setq ee (org-entity-get (match-string 1)))
5951 (= (length (nth 6 ee)) 1))
5952 (progn
5953 (add-text-properties
5954 (match-beginning 0) (match-end 1)
5955 (list 'font-lock-fontified t))
5956 (compose-region (match-beginning 0) (match-end 1)
5957 (nth 6 ee) nil)
5958 (backward-char 1)
5959 (throw 'match t))))
5960 nil))))
5962 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
5963 "Fontify string S like in Org-mode."
5964 (with-temp-buffer
5965 (insert s)
5966 (let ((org-odd-levels-only odd-levels))
5967 (org-mode)
5968 (font-lock-fontify-buffer)
5969 (buffer-string))))
5971 (defvar org-m nil)
5972 (defvar org-l nil)
5973 (defvar org-f nil)
5974 (defun org-get-level-face (n)
5975 "Get the right face for match N in font-lock matching of headlines."
5976 (setq org-l (- (match-end 2) (match-beginning 1) 1))
5977 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
5978 (if org-cycle-level-faces
5979 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
5980 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
5981 (cond
5982 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
5983 ((eq n 2) org-f)
5984 (t (if org-level-color-stars-only nil org-f))))
5987 (defun org-get-todo-face (kwd)
5988 "Get the right face for a TODO keyword KWD.
5989 If KWD is a number, get the corresponding match group."
5990 (if (numberp kwd) (setq kwd (match-string kwd)))
5991 (or (org-face-from-face-or-color
5992 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
5993 (and (member kwd org-done-keywords) 'org-done)
5994 'org-todo))
5996 (defun org-face-from-face-or-color (context inherit face-or-color)
5997 "Create a face list that inherits INHERIT, but sets the foreground color.
5998 When FACE-OR-COLOR is not a string, just return it."
5999 (if (stringp face-or-color)
6000 (list :inherit inherit
6001 (cdr (assoc context org-faces-easy-properties))
6002 face-or-color)
6003 face-or-color))
6005 (defun org-font-lock-add-tag-faces (limit)
6006 "Add the special tag faces."
6007 (when (and org-tag-faces org-tags-special-faces-re)
6008 (while (re-search-forward org-tags-special-faces-re limit t)
6009 (add-text-properties (match-beginning 1) (match-end 1)
6010 (list 'face (org-get-tag-face 1)
6011 'font-lock-fontified t))
6012 (backward-char 1))))
6014 (defun org-font-lock-add-priority-faces (limit)
6015 "Add the special priority faces."
6016 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6017 (add-text-properties
6018 (match-beginning 0) (match-end 0)
6019 (list 'face (or (org-face-from-face-or-color
6020 'priority 'org-special-keyword
6021 (cdr (assoc (char-after (match-beginning 1))
6022 org-priority-faces)))
6023 'org-special-keyword)
6024 'font-lock-fontified t))))
6026 (defun org-get-tag-face (kwd)
6027 "Get the right face for a TODO keyword KWD.
6028 If KWD is a number, get the corresponding match group."
6029 (if (numberp kwd) (setq kwd (match-string kwd)))
6030 (or (org-face-from-face-or-color
6031 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6032 'org-tag))
6034 (defun org-unfontify-region (beg end &optional maybe_loudly)
6035 "Remove fontification and activation overlays from links."
6036 (font-lock-default-unfontify-region beg end)
6037 (let* ((buffer-undo-list t)
6038 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6039 (inhibit-modification-hooks t)
6040 deactivate-mark buffer-file-name buffer-file-truename)
6041 (org-decompose-region beg end)
6042 (remove-text-properties beg end
6043 '(mouse-face t keymap t org-linked-text t
6044 invisible t intangible t
6045 org-no-flyspell t org-emphasis t))
6046 (org-remove-font-lock-display-properties beg end)))
6048 (defconst org-script-display '(((raise -0.3) (height 0.7))
6049 ((raise 0.3) (height 0.7))
6050 ((raise -0.5))
6051 ((raise 0.5)))
6052 "Display properties for showing superscripts and subscripts.")
6054 (defun org-remove-font-lock-display-properties (beg end)
6055 "Remove specific display properties that have been added by font lock.
6056 The will remove the raise properties that are used to show superscripts
6057 and subscripts."
6058 (let (next prop)
6059 (while (< beg end)
6060 (setq next (next-single-property-change beg 'display nil end)
6061 prop (get-text-property beg 'display))
6062 (if (member prop org-script-display)
6063 (put-text-property beg next 'display nil))
6064 (setq beg next))))
6066 (defun org-raise-scripts (limit)
6067 "Add raise properties to sub/superscripts."
6068 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6069 (if (re-search-forward
6070 (if (eq org-use-sub-superscripts t)
6071 org-match-substring-regexp
6072 org-match-substring-with-braces-regexp)
6073 limit t)
6074 (let* ((pos (point)) table-p comment-p
6075 (mpos (match-beginning 3))
6076 (emph-p (get-text-property mpos 'org-emphasis))
6077 (link-p (get-text-property mpos 'mouse-face))
6078 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6079 (goto-char (point-at-bol))
6080 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6081 comment-p (org-looking-at-p "[ \t]*#"))
6082 (goto-char pos)
6083 ;; FIXME: Should we go back one character here, for a_b^c
6084 ;; (goto-char (1- pos)) ;????????????????????
6085 (if (or comment-p emph-p link-p keyw-p)
6087 (put-text-property (match-beginning 3) (match-end 0)
6088 'display
6089 (if (equal (char-after (match-beginning 2)) ?^)
6090 (nth (if table-p 3 1) org-script-display)
6091 (nth (if table-p 2 0) org-script-display)))
6092 (add-text-properties (match-beginning 2) (match-end 2)
6093 (list 'invisible t
6094 'org-dwidth t 'org-dwidth-n 1))
6095 (if (and (eq (char-after (match-beginning 3)) ?{)
6096 (eq (char-before (match-end 3)) ?}))
6097 (progn
6098 (add-text-properties
6099 (match-beginning 3) (1+ (match-beginning 3))
6100 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6101 (add-text-properties
6102 (1- (match-end 3)) (match-end 3)
6103 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6104 t)))))
6106 ;;;; Visibility cycling, including org-goto and indirect buffer
6108 ;;; Cycling
6110 (defvar org-cycle-global-status nil)
6111 (make-variable-buffer-local 'org-cycle-global-status)
6112 (defvar org-cycle-subtree-status nil)
6113 (make-variable-buffer-local 'org-cycle-subtree-status)
6115 ;;;###autoload
6117 (defvar org-inlinetask-min-level)
6119 (defun org-cycle (&optional arg)
6120 "TAB-action and visibility cycling for Org-mode.
6122 This is the command invoked in Org-mode by the TAB key. Its main purpose
6123 is outline visibility cycling, but it also invokes other actions
6124 in special contexts.
6126 - When this function is called with a prefix argument, rotate the entire
6127 buffer through 3 states (global cycling)
6128 1. OVERVIEW: Show only top-level headlines.
6129 2. CONTENTS: Show all headlines of all levels, but no body text.
6130 3. SHOW ALL: Show everything.
6131 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6132 determined by the variable `org-startup-folded', and by any VISIBILITY
6133 properties in the buffer.
6134 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6135 including any drawers.
6137 - When inside a table, re-align the table and move to the next field.
6139 - When point is at the beginning of a headline, rotate the subtree started
6140 by this line through 3 different states (local cycling)
6141 1. FOLDED: Only the main headline is shown.
6142 2. CHILDREN: The main headline and the direct children are shown.
6143 From this state, you can move to one of the children
6144 and zoom in further.
6145 3. SUBTREE: Show the entire subtree, including body text.
6146 If there is no subtree, switch directly from CHILDREN to FOLDED.
6148 - When point is at the beginning of an empty headline and the variable
6149 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6150 of the headline by demoting and promoting it to likely levels. This
6151 speeds up creation document structure by pressing TAB once or several
6152 times right after creating a new headline.
6154 - When there is a numeric prefix, go up to a heading with level ARG, do
6155 a `show-subtree' and return to the previous cursor position. If ARG
6156 is negative, go up that many levels.
6158 - When point is not at the beginning of a headline, execute the global
6159 binding for TAB, which is re-indenting the line. See the option
6160 `org-cycle-emulate-tab' for details.
6162 - Special case: if point is at the beginning of the buffer and there is
6163 no headline in line 1, this function will act as if called with prefix arg
6164 (C-u TAB, same as S-TAB) also when called without prefix arg.
6165 But only if also the variable `org-cycle-global-at-bob' is t."
6166 (interactive "P")
6167 (org-load-modules-maybe)
6168 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6169 (and org-cycle-level-after-item/entry-creation
6170 (or (org-cycle-level)
6171 (org-cycle-item-indentation))))
6172 (let* ((limit-level
6173 (or org-cycle-max-level
6174 (and (boundp 'org-inlinetask-min-level)
6175 org-inlinetask-min-level
6176 (1- org-inlinetask-min-level))))
6177 (nstars (and limit-level
6178 (if org-odd-levels-only
6179 (and limit-level (1- (* limit-level 2)))
6180 limit-level)))
6181 (org-outline-regexp
6182 (if (not (derived-mode-p 'org-mode))
6183 outline-regexp
6184 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6185 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6186 (not (looking-at org-outline-regexp))))
6187 (org-cycle-hook
6188 (if bob-special
6189 (delq 'org-optimize-window-after-visibility-change
6190 (copy-sequence org-cycle-hook))
6191 org-cycle-hook))
6192 (pos (point)))
6194 (if (or bob-special (equal arg '(4)))
6195 ;; special case: use global cycling
6196 (setq arg t))
6198 (cond
6200 ((equal arg '(16))
6201 (setq last-command 'dummy)
6202 (org-set-startup-visibility)
6203 (message "Startup visibility, plus VISIBILITY properties"))
6205 ((equal arg '(64))
6206 (show-all)
6207 (message "Entire buffer visible, including drawers"))
6209 ;; Table: enter it or move to the next field.
6210 ((org-at-table-p 'any)
6211 (if (org-at-table.el-p)
6212 (message "Use C-c ' to edit table.el tables")
6213 (if arg (org-table-edit-field t)
6214 (org-table-justify-field-maybe)
6215 (call-interactively 'org-table-next-field))))
6217 ((run-hook-with-args-until-success
6218 'org-tab-after-check-for-table-hook))
6220 ;; Global cycling: delegate to `org-cycle-internal-global'.
6221 ((eq arg t) (org-cycle-internal-global))
6223 ;; Drawers: delegate to `org-flag-drawer'.
6224 ((and org-drawers org-drawer-regexp
6225 (save-excursion
6226 (beginning-of-line 1)
6227 (looking-at org-drawer-regexp)))
6228 (org-flag-drawer ; toggle block visibility
6229 (not (get-char-property (match-end 0) 'invisible))))
6231 ;; Show-subtree, ARG levels up from here.
6232 ((integerp arg)
6233 (save-excursion
6234 (org-back-to-heading)
6235 (outline-up-heading (if (< arg 0) (- arg)
6236 (- (funcall outline-level) arg)))
6237 (org-show-subtree)))
6239 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6240 ((and (featurep 'org-inlinetask)
6241 (org-inlinetask-at-task-p)
6242 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6243 (org-inlinetask-toggle-visibility))
6245 ((org-try-cdlatex-tab))
6247 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6248 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6249 (save-excursion (beginning-of-line 1)
6250 (looking-at org-outline-regexp)))
6251 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6252 (org-cycle-internal-local))
6254 ;; From there: TAB emulation and template completion.
6255 (buffer-read-only (org-back-to-heading))
6257 ((run-hook-with-args-until-success
6258 'org-tab-after-check-for-cycling-hook))
6260 ((org-try-structure-completion))
6262 ((run-hook-with-args-until-success
6263 'org-tab-before-tab-emulation-hook))
6265 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6266 (or (not (bolp))
6267 (not (looking-at org-outline-regexp))))
6268 (call-interactively (global-key-binding "\t")))
6270 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6271 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6272 (or (and (eq org-cycle-emulate-tab 'white)
6273 (= (match-end 0) (point-at-eol)))
6274 (and (eq org-cycle-emulate-tab 'whitestart)
6275 (>= (match-end 0) pos))))
6277 (eq org-cycle-emulate-tab t))
6278 (call-interactively (global-key-binding "\t")))
6280 (t (save-excursion
6281 (org-back-to-heading)
6282 (org-cycle)))))))
6284 (defun org-cycle-internal-global ()
6285 "Do the global cycling action."
6286 ;; Hack to avoid display of messages for .org attachments in Gnus
6287 (let ((ga (string-match "\\*fontification" (buffer-name))))
6288 (cond
6289 ((and (eq last-command this-command)
6290 (eq org-cycle-global-status 'overview))
6291 ;; We just created the overview - now do table of contents
6292 ;; This can be slow in very large buffers, so indicate action
6293 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6294 (unless ga (message "CONTENTS..."))
6295 (org-content)
6296 (unless ga (message "CONTENTS...done"))
6297 (setq org-cycle-global-status 'contents)
6298 (run-hook-with-args 'org-cycle-hook 'contents))
6300 ((and (eq last-command this-command)
6301 (eq org-cycle-global-status 'contents))
6302 ;; We just showed the table of contents - now show everything
6303 (run-hook-with-args 'org-pre-cycle-hook 'all)
6304 (show-all)
6305 (unless ga (message "SHOW ALL"))
6306 (setq org-cycle-global-status 'all)
6307 (run-hook-with-args 'org-cycle-hook 'all))
6310 ;; Default action: go to overview
6311 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6312 (org-overview)
6313 (unless ga (message "OVERVIEW"))
6314 (setq org-cycle-global-status 'overview)
6315 (run-hook-with-args 'org-cycle-hook 'overview)))))
6317 (defun org-cycle-internal-local ()
6318 "Do the local cycling action."
6319 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6320 ;; First, determine end of headline (EOH), end of subtree or item
6321 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6322 (save-excursion
6323 (if (org-at-item-p)
6324 (progn
6325 (beginning-of-line)
6326 (setq struct (org-list-struct))
6327 (setq eoh (point-at-eol))
6328 (setq eos (org-list-get-item-end-before-blank (point) struct))
6329 (setq has-children (org-list-has-child-p (point) struct)))
6330 (org-back-to-heading)
6331 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6332 (setq eos (save-excursion
6333 (org-end-of-subtree t)
6334 (unless (eobp)
6335 (skip-chars-forward " \t\n"))
6336 (if (eobp) (point) (1- (point)))))
6337 (setq has-children
6338 (or (save-excursion
6339 (let ((level (funcall outline-level)))
6340 (outline-next-heading)
6341 (and (org-at-heading-p t)
6342 (> (funcall outline-level) level))))
6343 (save-excursion
6344 (org-list-search-forward (org-item-beginning-re) eos t)))))
6345 ;; Determine end invisible part of buffer (EOL)
6346 (beginning-of-line 2)
6347 ;; XEmacs doesn't have `next-single-char-property-change'
6348 (if (featurep 'xemacs)
6349 (while (and (not (eobp)) ;; this is like `next-line'
6350 (get-char-property (1- (point)) 'invisible))
6351 (beginning-of-line 2))
6352 (while (and (not (eobp)) ;; this is like `next-line'
6353 (get-char-property (1- (point)) 'invisible))
6354 (goto-char (next-single-char-property-change (point) 'invisible))
6355 (and (eolp) (beginning-of-line 2))))
6356 (setq eol (point)))
6357 ;; Find out what to do next and set `this-command'
6358 (cond
6359 ((= eos eoh)
6360 ;; Nothing is hidden behind this heading
6361 (run-hook-with-args 'org-pre-cycle-hook 'empty)
6362 (message "EMPTY ENTRY")
6363 (setq org-cycle-subtree-status nil)
6364 (save-excursion
6365 (goto-char eos)
6366 (outline-next-heading)
6367 (if (outline-invisible-p) (org-flag-heading nil))))
6368 ((and (or (>= eol eos)
6369 (not (string-match "\\S-" (buffer-substring eol eos))))
6370 (or has-children
6371 (not (setq children-skipped
6372 org-cycle-skip-children-state-if-no-children))))
6373 ;; Entire subtree is hidden in one line: children view
6374 (run-hook-with-args 'org-pre-cycle-hook 'children)
6375 (if (org-at-item-p)
6376 (org-list-set-item-visibility (point-at-bol) struct 'children)
6377 (org-show-entry)
6378 (org-with-limited-levels (show-children))
6379 ;; FIXME: This slows down the func way too much.
6380 ;; How keep drawers hidden in subtree anyway?
6381 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6382 ;; (org-cycle-hide-drawers 'subtree))
6384 ;; Fold every list in subtree to top-level items.
6385 (when (eq org-cycle-include-plain-lists 'integrate)
6386 (save-excursion
6387 (org-back-to-heading)
6388 (while (org-list-search-forward (org-item-beginning-re) eos t)
6389 (beginning-of-line 1)
6390 (let* ((struct (org-list-struct))
6391 (prevs (org-list-prevs-alist struct))
6392 (end (org-list-get-bottom-point struct)))
6393 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6394 (org-list-get-all-items (point) struct prevs))
6395 (goto-char end))))))
6396 (message "CHILDREN")
6397 (save-excursion
6398 (goto-char eos)
6399 (outline-next-heading)
6400 (if (outline-invisible-p) (org-flag-heading nil)))
6401 (setq org-cycle-subtree-status 'children)
6402 (run-hook-with-args 'org-cycle-hook 'children))
6403 ((or children-skipped
6404 (and (eq last-command this-command)
6405 (eq org-cycle-subtree-status 'children)))
6406 ;; We just showed the children, or no children are there,
6407 ;; now show everything.
6408 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
6409 (outline-flag-region eoh eos nil)
6410 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6411 (setq org-cycle-subtree-status 'subtree)
6412 (run-hook-with-args 'org-cycle-hook 'subtree))
6414 ;; Default action: hide the subtree.
6415 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6416 (outline-flag-region eoh eos t)
6417 (message "FOLDED")
6418 (setq org-cycle-subtree-status 'folded)
6419 (run-hook-with-args 'org-cycle-hook 'folded)))))
6421 ;;;###autoload
6422 (defun org-global-cycle (&optional arg)
6423 "Cycle the global visibility. For details see `org-cycle'.
6424 With \\[universal-argument] prefix arg, switch to startup visibility.
6425 With a numeric prefix, show all headlines up to that level."
6426 (interactive "P")
6427 (let ((org-cycle-include-plain-lists
6428 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6429 (cond
6430 ((integerp arg)
6431 (show-all)
6432 (hide-sublevels arg)
6433 (setq org-cycle-global-status 'contents))
6434 ((equal arg '(4))
6435 (org-set-startup-visibility)
6436 (message "Startup visibility, plus VISIBILITY properties."))
6438 (org-cycle '(4))))))
6440 (defun org-set-startup-visibility ()
6441 "Set the visibility required by startup options and properties."
6442 (cond
6443 ((eq org-startup-folded t)
6444 (org-cycle '(4)))
6445 ((eq org-startup-folded 'content)
6446 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6447 (org-cycle '(4)) (org-cycle '(4)))))
6448 (unless (eq org-startup-folded 'showeverything)
6449 (if org-hide-block-startup (org-hide-block-all))
6450 (org-set-visibility-according-to-property 'no-cleanup)
6451 (org-cycle-hide-archived-subtrees 'all)
6452 (org-cycle-hide-drawers 'all)
6453 (org-cycle-show-empty-lines t)))
6455 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6456 "Switch subtree visibilities according to :VISIBILITY: property."
6457 (interactive)
6458 (let (org-show-entry-below state)
6459 (save-excursion
6460 (goto-char (point-min))
6461 (while (re-search-forward
6462 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6463 nil t)
6464 (setq state (match-string 1))
6465 (save-excursion
6466 (org-back-to-heading t)
6467 (hide-subtree)
6468 (org-reveal)
6469 (cond
6470 ((equal state '("fold" "folded"))
6471 (hide-subtree))
6472 ((equal state "children")
6473 (org-show-hidden-entry)
6474 (show-children))
6475 ((equal state "content")
6476 (save-excursion
6477 (save-restriction
6478 (org-narrow-to-subtree)
6479 (org-content))))
6480 ((member state '("all" "showall"))
6481 (show-subtree)))))
6482 (unless no-cleanup
6483 (org-cycle-hide-archived-subtrees 'all)
6484 (org-cycle-hide-drawers 'all)
6485 (org-cycle-show-empty-lines 'all)))))
6487 ;; This function uses outline-regexp instead of the more fundamental
6488 ;; org-outline-regexp so that org-cycle-global works outside of Org
6489 ;; buffers, where outline-regexp is needed.
6490 (defun org-overview ()
6491 "Switch to overview mode, showing only top-level headlines.
6492 Really, this shows all headlines with level equal or greater than the level
6493 of the first headline in the buffer. This is important, because if the
6494 first headline is not level one, then (hide-sublevels 1) gives confusing
6495 results."
6496 (interactive)
6497 (let ((level (save-excursion
6498 (goto-char (point-min))
6499 (if (re-search-forward (concat "^" outline-regexp) nil t)
6500 (progn
6501 (goto-char (match-beginning 0))
6502 (funcall outline-level))))))
6503 (and level (hide-sublevels level))))
6505 (defun org-content (&optional arg)
6506 "Show all headlines in the buffer, like a table of contents.
6507 With numerical argument N, show content up to level N."
6508 (interactive "P")
6509 (save-excursion
6510 ;; Visit all headings and show their offspring
6511 (and (integerp arg) (org-overview))
6512 (goto-char (point-max))
6513 (catch 'exit
6514 (while (and (progn (condition-case nil
6515 (outline-previous-visible-heading 1)
6516 (error (goto-char (point-min))))
6518 (looking-at org-outline-regexp))
6519 (if (integerp arg)
6520 (show-children (1- arg))
6521 (show-branches))
6522 (if (bobp) (throw 'exit nil))))))
6525 (defun org-optimize-window-after-visibility-change (state)
6526 "Adjust the window after a change in outline visibility.
6527 This function is the default value of the hook `org-cycle-hook'."
6528 (when (get-buffer-window (current-buffer))
6529 (cond
6530 ((eq state 'content) nil)
6531 ((eq state 'all) nil)
6532 ((eq state 'folded) nil)
6533 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6534 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6536 (defun org-remove-empty-overlays-at (pos)
6537 "Remove outline overlays that do not contain non-white stuff."
6538 (mapc
6539 (lambda (o)
6540 (and (eq 'outline (overlay-get o 'invisible))
6541 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6542 (overlay-end o))))
6543 (delete-overlay o)))
6544 (overlays-at pos)))
6546 (defun org-clean-visibility-after-subtree-move ()
6547 "Fix visibility issues after moving a subtree."
6548 ;; First, find a reasonable region to look at:
6549 ;; Start two siblings above, end three below
6550 (let* ((beg (save-excursion
6551 (and (org-get-last-sibling)
6552 (org-get-last-sibling))
6553 (point)))
6554 (end (save-excursion
6555 (and (org-get-next-sibling)
6556 (org-get-next-sibling)
6557 (org-get-next-sibling))
6558 (if (org-at-heading-p)
6559 (point-at-eol)
6560 (point))))
6561 (level (looking-at "\\*+"))
6562 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6563 (save-excursion
6564 (save-restriction
6565 (narrow-to-region beg end)
6566 (when re
6567 ;; Properly fold already folded siblings
6568 (goto-char (point-min))
6569 (while (re-search-forward re nil t)
6570 (if (and (not (outline-invisible-p))
6571 (save-excursion
6572 (goto-char (point-at-eol)) (outline-invisible-p)))
6573 (hide-entry))))
6574 (org-cycle-show-empty-lines 'overview)
6575 (org-cycle-hide-drawers 'overview)))))
6577 (defun org-cycle-show-empty-lines (state)
6578 "Show empty lines above all visible headlines.
6579 The region to be covered depends on STATE when called through
6580 `org-cycle-hook'. Lisp program can use t for STATE to get the
6581 entire buffer covered. Note that an empty line is only shown if there
6582 are at least `org-cycle-separator-lines' empty lines before the headline."
6583 (when (not (= org-cycle-separator-lines 0))
6584 (save-excursion
6585 (let* ((n (abs org-cycle-separator-lines))
6586 (re (cond
6587 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6588 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6589 (t (let ((ns (number-to-string (- n 2))))
6590 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6591 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6592 beg end b e)
6593 (cond
6594 ((memq state '(overview contents t))
6595 (setq beg (point-min) end (point-max)))
6596 ((memq state '(children folded))
6597 (setq beg (point) end (progn (org-end-of-subtree t t)
6598 (beginning-of-line 2)
6599 (point)))))
6600 (when beg
6601 (goto-char beg)
6602 (while (re-search-forward re end t)
6603 (unless (get-char-property (match-end 1) 'invisible)
6604 (setq e (match-end 1))
6605 (if (< org-cycle-separator-lines 0)
6606 (setq b (save-excursion
6607 (goto-char (match-beginning 0))
6608 (org-back-over-empty-lines)
6609 (if (save-excursion
6610 (goto-char (max (point-min) (1- (point))))
6611 (org-at-heading-p))
6612 (1- (point))
6613 (point))))
6614 (setq b (match-beginning 1)))
6615 (outline-flag-region b e nil)))))))
6616 ;; Never hide empty lines at the end of the file.
6617 (save-excursion
6618 (goto-char (point-max))
6619 (outline-previous-heading)
6620 (outline-end-of-heading)
6621 (if (and (looking-at "[ \t\n]+")
6622 (= (match-end 0) (point-max)))
6623 (outline-flag-region (point) (match-end 0) nil))))
6625 (defun org-show-empty-lines-in-parent ()
6626 "Move to the parent and re-show empty lines before visible headlines."
6627 (save-excursion
6628 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6629 (org-cycle-show-empty-lines context))))
6631 (defun org-files-list ()
6632 "Return `org-agenda-files' list, plus all open org-mode files.
6633 This is useful for operations that need to scan all of a user's
6634 open and agenda-wise Org files."
6635 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6636 (dolist (buf (buffer-list))
6637 (with-current-buffer buf
6638 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
6639 (let ((file (expand-file-name (buffer-file-name))))
6640 (unless (member file files)
6641 (push file files))))))
6642 files))
6644 (defsubst org-entry-beginning-position ()
6645 "Return the beginning position of the current entry."
6646 (save-excursion (outline-back-to-heading t) (point)))
6648 (defsubst org-entry-end-position ()
6649 "Return the end position of the current entry."
6650 (save-excursion (outline-next-heading) (point)))
6652 (defun org-cycle-hide-drawers (state)
6653 "Re-hide all drawers after a visibility state change."
6654 (when (and (derived-mode-p 'org-mode)
6655 (not (memq state '(overview folded contents))))
6656 (save-excursion
6657 (let* ((globalp (memq state '(contents all)))
6658 (beg (if globalp (point-min) (point)))
6659 (end (if globalp (point-max)
6660 (if (eq state 'children)
6661 (save-excursion (outline-next-heading) (point))
6662 (org-end-of-subtree t)))))
6663 (goto-char beg)
6664 (while (re-search-forward org-drawer-regexp end t)
6665 (org-flag-drawer t))))))
6667 (defun org-flag-drawer (flag)
6668 (save-excursion
6669 (beginning-of-line 1)
6670 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6671 (let ((b (match-end 0)))
6672 (if (re-search-forward
6673 "^[ \t]*:END:"
6674 (save-excursion (outline-next-heading) (point)) t)
6675 (outline-flag-region b (point-at-eol) flag)
6676 (error ":END: line missing at position %s" b))))))
6678 (defun org-subtree-end-visible-p ()
6679 "Is the end of the current subtree visible?"
6680 (pos-visible-in-window-p
6681 (save-excursion (org-end-of-subtree t) (point))))
6683 (defun org-first-headline-recenter (&optional N)
6684 "Move cursor to the first headline and recenter the headline.
6685 Optional argument N means put the headline into the Nth line of the window."
6686 (goto-char (point-min))
6687 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
6688 (beginning-of-line)
6689 (recenter (prefix-numeric-value N))))
6691 ;;; Saving and restoring visibility
6693 (defun org-outline-overlay-data (&optional use-markers)
6694 "Return a list of the locations of all outline overlays.
6695 These are overlays with the `invisible' property value `outline'.
6696 The return value is a list of cons cells, with start and stop
6697 positions for each overlay.
6698 If USE-MARKERS is set, return the positions as markers."
6699 (let (beg end)
6700 (save-excursion
6701 (save-restriction
6702 (widen)
6703 (delq nil
6704 (mapcar (lambda (o)
6705 (when (eq (overlay-get o 'invisible) 'outline)
6706 (setq beg (overlay-start o)
6707 end (overlay-end o))
6708 (and beg end (> end beg)
6709 (if use-markers
6710 (cons (move-marker (make-marker) beg)
6711 (move-marker (make-marker) end))
6712 (cons beg end)))))
6713 (overlays-in (point-min) (point-max))))))))
6715 (defun org-set-outline-overlay-data (data)
6716 "Create visibility overlays for all positions in DATA.
6717 DATA should have been made by `org-outline-overlay-data'."
6718 (let (o)
6719 (save-excursion
6720 (save-restriction
6721 (widen)
6722 (show-all)
6723 (mapc (lambda (c)
6724 (outline-flag-region (car c) (cdr c) t))
6725 data)))))
6727 ;;; Folding of blocks
6729 (defvar org-hide-block-overlays nil
6730 "Overlays hiding blocks.")
6731 (make-variable-buffer-local 'org-hide-block-overlays)
6733 (defun org-block-map (function &optional start end)
6734 "Call FUNCTION at the head of all source blocks in the current buffer.
6735 Optional arguments START and END can be used to limit the range."
6736 (let ((start (or start (point-min)))
6737 (end (or end (point-max))))
6738 (save-excursion
6739 (goto-char start)
6740 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
6741 (save-excursion
6742 (save-match-data
6743 (goto-char (match-beginning 0))
6744 (funcall function)))))))
6746 (defun org-hide-block-toggle-all ()
6747 "Toggle the visibility of all blocks in the current buffer."
6748 (org-block-map #'org-hide-block-toggle))
6750 (defun org-hide-block-all ()
6751 "Fold all blocks in the current buffer."
6752 (interactive)
6753 (org-show-block-all)
6754 (org-block-map #'org-hide-block-toggle-maybe))
6756 (defun org-show-block-all ()
6757 "Unfold all blocks in the current buffer."
6758 (interactive)
6759 (mapc 'delete-overlay org-hide-block-overlays)
6760 (setq org-hide-block-overlays nil))
6762 (defun org-hide-block-toggle-maybe ()
6763 "Toggle visibility of block at point."
6764 (interactive)
6765 (let ((case-fold-search t))
6766 (if (save-excursion
6767 (beginning-of-line 1)
6768 (looking-at org-block-regexp))
6769 (progn (org-hide-block-toggle)
6770 t) ;; to signal that we took action
6771 nil))) ;; to signal that we did not
6773 (defun org-hide-block-toggle (&optional force)
6774 "Toggle the visibility of the current block."
6775 (interactive)
6776 (save-excursion
6777 (beginning-of-line)
6778 (if (re-search-forward org-block-regexp nil t)
6779 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
6780 (end (match-end 0)) ;; end of entire body
6782 (if (memq t (mapcar (lambda (overlay)
6783 (eq (overlay-get overlay 'invisible)
6784 'org-hide-block))
6785 (overlays-at start)))
6786 (if (or (not force) (eq force 'off))
6787 (mapc (lambda (ov)
6788 (when (member ov org-hide-block-overlays)
6789 (setq org-hide-block-overlays
6790 (delq ov org-hide-block-overlays)))
6791 (when (eq (overlay-get ov 'invisible)
6792 'org-hide-block)
6793 (delete-overlay ov)))
6794 (overlays-at start)))
6795 (setq ov (make-overlay start end))
6796 (overlay-put ov 'invisible 'org-hide-block)
6797 ;; make the block accessible to isearch
6798 (overlay-put
6799 ov 'isearch-open-invisible
6800 (lambda (ov)
6801 (when (member ov org-hide-block-overlays)
6802 (setq org-hide-block-overlays
6803 (delq ov org-hide-block-overlays)))
6804 (when (eq (overlay-get ov 'invisible)
6805 'org-hide-block)
6806 (delete-overlay ov))))
6807 (push ov org-hide-block-overlays)))
6808 (error "Not looking at a source block"))))
6810 ;; org-tab-after-check-for-cycling-hook
6811 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
6812 ;; Remove overlays when changing major mode
6813 (add-hook 'org-mode-hook
6814 (lambda () (org-add-hook 'change-major-mode-hook
6815 'org-show-block-all 'append 'local)))
6817 ;;; Org-goto
6819 (defvar org-goto-window-configuration nil)
6820 (defvar org-goto-marker nil)
6821 (defvar org-goto-map
6822 (let ((map (make-sparse-keymap)))
6823 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
6824 (while (setq cmd (pop cmds))
6825 (substitute-key-definition cmd cmd map global-map)))
6826 (suppress-keymap map)
6827 (org-defkey map "\C-m" 'org-goto-ret)
6828 (org-defkey map [(return)] 'org-goto-ret)
6829 (org-defkey map [(left)] 'org-goto-left)
6830 (org-defkey map [(right)] 'org-goto-right)
6831 (org-defkey map [(control ?g)] 'org-goto-quit)
6832 (org-defkey map "\C-i" 'org-cycle)
6833 (org-defkey map [(tab)] 'org-cycle)
6834 (org-defkey map [(down)] 'outline-next-visible-heading)
6835 (org-defkey map [(up)] 'outline-previous-visible-heading)
6836 (if org-goto-auto-isearch
6837 (if (fboundp 'define-key-after)
6838 (define-key-after map [t] 'org-goto-local-auto-isearch)
6839 nil)
6840 (org-defkey map "q" 'org-goto-quit)
6841 (org-defkey map "n" 'outline-next-visible-heading)
6842 (org-defkey map "p" 'outline-previous-visible-heading)
6843 (org-defkey map "f" 'outline-forward-same-level)
6844 (org-defkey map "b" 'outline-backward-same-level)
6845 (org-defkey map "u" 'outline-up-heading))
6846 (org-defkey map "/" 'org-occur)
6847 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
6848 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
6849 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
6850 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
6851 (org-defkey map "\C-c\C-u" 'outline-up-heading)
6852 map))
6854 (defconst org-goto-help
6855 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
6856 RET=jump to location [Q]uit and return to previous location
6857 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
6859 (defvar org-goto-start-pos) ; dynamically scoped parameter
6861 ;; FIXME: Docstring does not mention both interfaces
6862 (defun org-goto (&optional alternative-interface)
6863 "Look up a different location in the current file, keeping current visibility.
6865 When you want look-up or go to a different location in a
6866 document, the fastest way is often to fold the entire buffer and
6867 then dive into the tree. This method has the disadvantage, that
6868 the previous location will be folded, which may not be what you
6869 want.
6871 This command works around this by showing a copy of the current
6872 buffer in an indirect buffer, in overview mode. You can dive
6873 into the tree in that copy, use org-occur and incremental search
6874 to find a location. When pressing RET or `Q', the command
6875 returns to the original buffer in which the visibility is still
6876 unchanged. After RET it will also jump to the location selected
6877 in the indirect buffer and expose the headline hierarchy above.
6879 With a prefix argument, use the alternative interface: e.g. if
6880 `org-goto-interface' is 'outline use 'outline-path-completion."
6881 (interactive "P")
6882 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
6883 (org-refile-use-outline-path t)
6884 (org-refile-target-verify-function nil)
6885 (interface
6886 (if (not alternative-interface)
6887 org-goto-interface
6888 (if (eq org-goto-interface 'outline)
6889 'outline-path-completion
6890 'outline)))
6891 (org-goto-start-pos (point))
6892 (selected-point
6893 (if (eq interface 'outline)
6894 (car (org-get-location (current-buffer) org-goto-help))
6895 (let ((pa (org-refile-get-location "Goto" nil nil t)))
6896 (org-refile-check-position pa)
6897 (nth 3 pa)))))
6898 (if selected-point
6899 (progn
6900 (org-mark-ring-push org-goto-start-pos)
6901 (goto-char selected-point)
6902 (if (or (outline-invisible-p) (org-invisible-p2))
6903 (org-show-context 'org-goto)))
6904 (message "Quit"))))
6906 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
6907 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
6908 (defvar org-goto-local-auto-isearch-map) ; defined below
6910 (defun org-get-location (buf help)
6911 "Let the user select a location in the Org-mode buffer BUF.
6912 This function uses a recursive edit. It returns the selected position
6913 or nil."
6914 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
6915 (isearch-hide-immediately nil)
6916 (isearch-search-fun-function
6917 (lambda () 'org-goto-local-search-headings))
6918 (org-goto-selected-point org-goto-exit-command)
6919 (pop-up-frames nil)
6920 (special-display-buffer-names nil)
6921 (special-display-regexps nil)
6922 (special-display-function nil))
6923 (save-excursion
6924 (save-window-excursion
6925 (delete-other-windows)
6926 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
6927 (org-pop-to-buffer-same-window
6928 (condition-case nil
6929 (make-indirect-buffer (current-buffer) "*org-goto*")
6930 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
6931 (with-output-to-temp-buffer "*Help*"
6932 (princ help))
6933 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
6934 (setq buffer-read-only nil)
6935 (let ((org-startup-truncated t)
6936 (org-startup-folded nil)
6937 (org-startup-align-all-tables nil))
6938 (org-mode)
6939 (org-overview))
6940 (setq buffer-read-only t)
6941 (if (and (boundp 'org-goto-start-pos)
6942 (integer-or-marker-p org-goto-start-pos))
6943 (let ((org-show-hierarchy-above t)
6944 (org-show-siblings t)
6945 (org-show-following-heading t))
6946 (goto-char org-goto-start-pos)
6947 (and (outline-invisible-p) (org-show-context)))
6948 (goto-char (point-min)))
6949 (let (org-special-ctrl-a/e) (org-beginning-of-line))
6950 (message "Select location and press RET")
6951 (use-local-map org-goto-map)
6952 (recursive-edit)
6954 (kill-buffer "*org-goto*")
6955 (cons org-goto-selected-point org-goto-exit-command)))
6957 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
6958 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
6959 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
6960 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
6962 (defun org-goto-local-search-headings (string bound noerror)
6963 "Search and make sure that any matches are in headlines."
6964 (catch 'return
6965 (while (if isearch-forward
6966 (search-forward string bound noerror)
6967 (search-backward string bound noerror))
6968 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
6969 (and (member :headline context)
6970 (not (member :tags context))))
6971 (throw 'return (point))))))
6973 (defun org-goto-local-auto-isearch ()
6974 "Start isearch."
6975 (interactive)
6976 (goto-char (point-min))
6977 (let ((keys (this-command-keys)))
6978 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
6979 (isearch-mode t)
6980 (isearch-process-search-char (string-to-char keys)))))
6982 (defun org-goto-ret (&optional arg)
6983 "Finish `org-goto' by going to the new location."
6984 (interactive "P")
6985 (setq org-goto-selected-point (point)
6986 org-goto-exit-command 'return)
6987 (throw 'exit nil))
6989 (defun org-goto-left ()
6990 "Finish `org-goto' by going to the new location."
6991 (interactive)
6992 (if (org-at-heading-p)
6993 (progn
6994 (beginning-of-line 1)
6995 (setq org-goto-selected-point (point)
6996 org-goto-exit-command 'left)
6997 (throw 'exit nil))
6998 (error "Not on a heading")))
7000 (defun org-goto-right ()
7001 "Finish `org-goto' by going to the new location."
7002 (interactive)
7003 (if (org-at-heading-p)
7004 (progn
7005 (setq org-goto-selected-point (point)
7006 org-goto-exit-command 'right)
7007 (throw 'exit nil))
7008 (error "Not on a heading")))
7010 (defun org-goto-quit ()
7011 "Finish `org-goto' without cursor motion."
7012 (interactive)
7013 (setq org-goto-selected-point nil)
7014 (setq org-goto-exit-command 'quit)
7015 (throw 'exit nil))
7017 ;;; Indirect buffer display of subtrees
7019 (defvar org-indirect-dedicated-frame nil
7020 "This is the frame being used for indirect tree display.")
7021 (defvar org-last-indirect-buffer nil)
7023 (defun org-tree-to-indirect-buffer (&optional arg)
7024 "Create indirect buffer and narrow it to current subtree.
7025 With numerical prefix ARG, go up to this level and then take that tree.
7026 If ARG is negative, go up that many levels.
7027 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7028 indirect buffer previously made with this command, to avoid proliferation of
7029 indirect buffers. However, when you call the command with a \
7030 \\[universal-argument] prefix, or
7031 when `org-indirect-buffer-display' is `new-frame', the last buffer
7032 is kept so that you can work with several indirect buffers at the same time.
7033 If `org-indirect-buffer-display' is `dedicated-frame', the \
7034 \\[universal-argument] prefix also
7035 requests that a new frame be made for the new buffer, so that the dedicated
7036 frame is not changed."
7037 (interactive "P")
7038 (let ((cbuf (current-buffer))
7039 (cwin (selected-window))
7040 (pos (point))
7041 beg end level heading ibuf)
7042 (save-excursion
7043 (org-back-to-heading t)
7044 (when (numberp arg)
7045 (setq level (org-outline-level))
7046 (if (< arg 0) (setq arg (+ level arg)))
7047 (while (> (setq level (org-outline-level)) arg)
7048 (outline-up-heading 1 t)))
7049 (setq beg (point)
7050 heading (org-get-heading))
7051 (org-end-of-subtree t t)
7052 (if (org-at-heading-p) (backward-char 1))
7053 (setq end (point)))
7054 (if (and (buffer-live-p org-last-indirect-buffer)
7055 (not (eq org-indirect-buffer-display 'new-frame))
7056 (not arg))
7057 (kill-buffer org-last-indirect-buffer))
7058 (setq ibuf (org-get-indirect-buffer cbuf)
7059 org-last-indirect-buffer ibuf)
7060 (cond
7061 ((or (eq org-indirect-buffer-display 'new-frame)
7062 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7063 (select-frame (make-frame))
7064 (delete-other-windows)
7065 (org-pop-to-buffer-same-window ibuf)
7066 (org-set-frame-title heading))
7067 ((eq org-indirect-buffer-display 'dedicated-frame)
7068 (raise-frame
7069 (select-frame (or (and org-indirect-dedicated-frame
7070 (frame-live-p org-indirect-dedicated-frame)
7071 org-indirect-dedicated-frame)
7072 (setq org-indirect-dedicated-frame (make-frame)))))
7073 (delete-other-windows)
7074 (org-pop-to-buffer-same-window ibuf)
7075 (org-set-frame-title (concat "Indirect: " heading)))
7076 ((eq org-indirect-buffer-display 'current-window)
7077 (org-pop-to-buffer-same-window ibuf))
7078 ((eq org-indirect-buffer-display 'other-window)
7079 (pop-to-buffer ibuf))
7080 (t (error "Invalid value")))
7081 (if (featurep 'xemacs)
7082 (save-excursion (org-mode) (turn-on-font-lock)))
7083 (narrow-to-region beg end)
7084 (show-all)
7085 (goto-char pos)
7086 (run-hook-with-args 'org-cycle-hook 'all)
7087 (and (window-live-p cwin) (select-window cwin))))
7089 (defun org-get-indirect-buffer (&optional buffer)
7090 (setq buffer (or buffer (current-buffer)))
7091 (let ((n 1) (base (buffer-name buffer)) bname)
7092 (while (buffer-live-p
7093 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7094 (setq n (1+ n)))
7095 (condition-case nil
7096 (make-indirect-buffer buffer bname 'clone)
7097 (error (make-indirect-buffer buffer bname)))))
7099 (defun org-set-frame-title (title)
7100 "Set the title of the current frame to the string TITLE."
7101 ;; FIXME: how to name a single frame in XEmacs???
7102 (unless (featurep 'xemacs)
7103 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7105 ;;;; Structure editing
7107 ;;; Inserting headlines
7109 (defun org-previous-line-empty-p ()
7110 (save-excursion
7111 (and (not (bobp))
7112 (or (beginning-of-line 0) t)
7113 (save-match-data
7114 (looking-at "[ \t]*$")))))
7116 (defun org-insert-heading (&optional force-heading invisible-ok)
7117 "Insert a new heading or item with same depth at point.
7118 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
7119 If point is at the beginning of a headline, insert a sibling before the
7120 current headline. If point is not at the beginning, split the line,
7121 create the new headline with the text in the current line after point
7122 \(but see also the variable `org-M-RET-may-split-line').
7124 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7125 This is important for non-interactive uses of the command."
7126 (interactive "P")
7127 (if (or (= (buffer-size) 0)
7128 (and (not (save-excursion
7129 (and (ignore-errors (org-back-to-heading invisible-ok))
7130 (org-at-heading-p))))
7131 (or force-heading (not (org-in-item-p)))))
7132 (progn
7133 (insert "\n* ")
7134 (run-hooks 'org-insert-heading-hook))
7135 (when (or force-heading (not (org-insert-item)))
7136 (let* ((empty-line-p nil)
7137 (level nil)
7138 (on-heading (org-at-heading-p))
7139 (head (save-excursion
7140 (condition-case nil
7141 (progn
7142 (org-back-to-heading invisible-ok)
7143 (when (and (not on-heading)
7144 (featurep 'org-inlinetask)
7145 (integerp org-inlinetask-min-level)
7146 (>= (length (match-string 0))
7147 org-inlinetask-min-level))
7148 ;; Find a heading level before the inline task
7149 (while (and (setq level (org-up-heading-safe))
7150 (>= level org-inlinetask-min-level)))
7151 (if (org-at-heading-p)
7152 (org-back-to-heading invisible-ok)
7153 (error "This should not happen")))
7154 (setq empty-line-p (org-previous-line-empty-p))
7155 (match-string 0))
7156 (error "*"))))
7157 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7158 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7159 pos hide-previous previous-pos)
7160 (cond
7161 ((and (org-at-heading-p) (bolp)
7162 (or (bobp)
7163 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
7164 ;; insert before the current line
7165 (open-line (if blank 2 1)))
7166 ((and (bolp)
7167 (not org-insert-heading-respect-content)
7168 (or (bobp)
7169 (save-excursion
7170 (backward-char 1) (not (outline-invisible-p)))))
7171 ;; insert right here
7172 nil)
7174 ;; somewhere in the line
7175 (save-excursion
7176 (setq previous-pos (point-at-bol))
7177 (end-of-line)
7178 (setq hide-previous (outline-invisible-p)))
7179 (and org-insert-heading-respect-content (org-show-subtree))
7180 (let ((split
7181 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
7182 (save-excursion
7183 (let ((p (point)))
7184 (goto-char (point-at-bol))
7185 (and (looking-at org-complex-heading-regexp)
7186 (match-beginning 4)
7187 (> p (match-beginning 4)))))))
7188 tags pos)
7189 (cond
7190 (org-insert-heading-respect-content
7191 (org-end-of-subtree nil t)
7192 (when (featurep 'org-inlinetask)
7193 (while (and (not (eobp))
7194 (looking-at "\\(\\*+\\)[ \t]+")
7195 (>= (length (match-string 1))
7196 org-inlinetask-min-level))
7197 (org-end-of-subtree nil t)))
7198 (or (bolp) (newline))
7199 (or (org-previous-line-empty-p)
7200 (and blank (newline)))
7201 (open-line 1))
7202 ((org-at-heading-p)
7203 (when hide-previous
7204 (show-children)
7205 (org-show-entry))
7206 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7207 (setq tags (and (match-end 2) (match-string 2)))
7208 (and (match-end 1)
7209 (delete-region (match-beginning 1) (match-end 1)))
7210 (setq pos (point-at-bol))
7211 (or split (end-of-line 1))
7212 (delete-horizontal-space)
7213 (if (string-match "\\`\\*+\\'"
7214 (buffer-substring (point-at-bol) (point)))
7215 (insert " "))
7216 (newline (if blank 2 1))
7217 (when tags
7218 (save-excursion
7219 (goto-char pos)
7220 (end-of-line 1)
7221 (insert " " tags)
7222 (org-set-tags nil 'align))))
7224 (or split (end-of-line 1))
7225 (newline (if blank 2 1)))))))
7226 (insert head) (just-one-space)
7227 (setq pos (point))
7228 (end-of-line 1)
7229 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7230 (when (and org-insert-heading-respect-content hide-previous)
7231 (save-excursion
7232 (goto-char previous-pos)
7233 (hide-subtree)))
7234 (run-hooks 'org-insert-heading-hook)))))
7236 (defun org-get-heading (&optional no-tags no-todo)
7237 "Return the heading of the current entry, without the stars.
7238 When NO-TAGS is non-nil, don't include tags.
7239 When NO-TODO is non-nil, don't include TODO keywords."
7240 (save-excursion
7241 (org-back-to-heading t)
7242 (cond
7243 ((and no-tags no-todo)
7244 (looking-at org-complex-heading-regexp)
7245 (match-string 4))
7246 (no-tags
7247 (looking-at (concat org-outline-regexp
7248 "\\(.*?\\)"
7249 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7250 (match-string 1))
7251 (no-todo
7252 (looking-at org-todo-line-regexp)
7253 (match-string 3))
7254 (t (looking-at org-heading-regexp)
7255 (match-string 2)))))
7257 (defun org-heading-components ()
7258 "Return the components of the current heading.
7259 This is a list with the following elements:
7260 - the level as an integer
7261 - the reduced level, different if `org-odd-levels-only' is set.
7262 - the TODO keyword, or nil
7263 - the priority character, like ?A, or nil if no priority is given
7264 - the headline text itself, or the tags string if no headline text
7265 - the tags string, or nil."
7266 (save-excursion
7267 (org-back-to-heading t)
7268 (if (let (case-fold-search) (looking-at org-complex-heading-regexp))
7269 (list (length (match-string 1))
7270 (org-reduced-level (length (match-string 1)))
7271 (org-match-string-no-properties 2)
7272 (and (match-end 3) (aref (match-string 3) 2))
7273 (org-match-string-no-properties 4)
7274 (org-match-string-no-properties 5)))))
7276 (defun org-get-entry ()
7277 "Get the entry text, after heading, entire subtree."
7278 (save-excursion
7279 (org-back-to-heading t)
7280 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7282 (defun org-insert-heading-after-current ()
7283 "Insert a new heading with same level as current, after current subtree."
7284 (interactive)
7285 (org-back-to-heading)
7286 (org-insert-heading)
7287 (org-move-subtree-down)
7288 (end-of-line 1))
7290 (defun org-insert-heading-respect-content ()
7291 (interactive)
7292 (let ((org-insert-heading-respect-content t))
7293 (org-insert-heading t)))
7295 (defun org-insert-todo-heading-respect-content (&optional force-state)
7296 (interactive "P")
7297 (let ((org-insert-heading-respect-content t))
7298 (org-insert-todo-heading force-state t)))
7300 (defun org-insert-todo-heading (arg &optional force-heading)
7301 "Insert a new heading with the same level and TODO state as current heading.
7302 If the heading has no TODO state, or if the state is DONE, use the first
7303 state (TODO by default). Also with prefix arg, force first state."
7304 (interactive "P")
7305 (when (or force-heading (not (org-insert-item 'checkbox)))
7306 (org-insert-heading force-heading)
7307 (save-excursion
7308 (org-back-to-heading)
7309 (outline-previous-heading)
7310 (looking-at org-todo-line-regexp))
7311 (let*
7312 ((new-mark-x
7313 (if (or arg
7314 (not (match-beginning 2))
7315 (member (match-string 2) org-done-keywords))
7316 (car org-todo-keywords-1)
7317 (match-string 2)))
7318 (new-mark
7320 (run-hook-with-args-until-success
7321 'org-todo-get-default-hook new-mark-x nil)
7322 new-mark-x)))
7323 (beginning-of-line 1)
7324 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7325 (if org-treat-insert-todo-heading-as-state-change
7326 (org-todo new-mark)
7327 (insert new-mark " "))))
7328 (when org-provide-todo-statistics
7329 (org-update-parent-todo-statistics))))
7331 (defun org-insert-subheading (arg)
7332 "Insert a new subheading and demote it.
7333 Works for outline headings and for plain lists alike."
7334 (interactive "P")
7335 (org-insert-heading arg)
7336 (cond
7337 ((org-at-heading-p) (org-do-demote))
7338 ((org-at-item-p) (org-indent-item))))
7340 (defun org-insert-todo-subheading (arg)
7341 "Insert a new subheading with TODO keyword or checkbox and demote it.
7342 Works for outline headings and for plain lists alike."
7343 (interactive "P")
7344 (org-insert-todo-heading arg)
7345 (cond
7346 ((org-at-heading-p) (org-do-demote))
7347 ((org-at-item-p) (org-indent-item))))
7349 ;;; Promotion and Demotion
7351 (defvar org-after-demote-entry-hook nil
7352 "Hook run after an entry has been demoted.
7353 The cursor will be at the beginning of the entry.
7354 When a subtree is being demoted, the hook will be called for each node.")
7356 (defvar org-after-promote-entry-hook nil
7357 "Hook run after an entry has been promoted.
7358 The cursor will be at the beginning of the entry.
7359 When a subtree is being promoted, the hook will be called for each node.")
7361 (defun org-promote-subtree ()
7362 "Promote the entire subtree.
7363 See also `org-promote'."
7364 (interactive)
7365 (save-excursion
7366 (org-with-limited-levels (org-map-tree 'org-promote)))
7367 (org-fix-position-after-promote))
7369 (defun org-demote-subtree ()
7370 "Demote the entire subtree. See `org-demote'.
7371 See also `org-promote'."
7372 (interactive)
7373 (save-excursion
7374 (org-with-limited-levels (org-map-tree 'org-demote)))
7375 (org-fix-position-after-promote))
7378 (defun org-do-promote ()
7379 "Promote the current heading higher up the tree.
7380 If the region is active in `transient-mark-mode', promote all headings
7381 in the region."
7382 (interactive)
7383 (save-excursion
7384 (if (org-region-active-p)
7385 (org-map-region 'org-promote (region-beginning) (region-end))
7386 (org-promote)))
7387 (org-fix-position-after-promote))
7389 (defun org-do-demote ()
7390 "Demote the current heading lower down the tree.
7391 If the region is active in `transient-mark-mode', demote all headings
7392 in the region."
7393 (interactive)
7394 (save-excursion
7395 (if (org-region-active-p)
7396 (org-map-region 'org-demote (region-beginning) (region-end))
7397 (org-demote)))
7398 (org-fix-position-after-promote))
7400 (defun org-fix-position-after-promote ()
7401 "Make sure that after pro/demotion cursor position is right."
7402 (let ((pos (point)))
7403 (when (save-excursion
7404 (beginning-of-line 1)
7405 (looking-at org-todo-line-regexp)
7406 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7407 (cond ((eobp) (insert " "))
7408 ((eolp) (insert " "))
7409 ((equal (char-after) ?\ ) (forward-char 1))))))
7411 (defun org-current-level ()
7412 "Return the level of the current entry, or nil if before the first headline.
7413 The level is the number of stars at the beginning of the headline."
7414 (save-excursion
7415 (org-with-limited-levels
7416 (if (ignore-errors (org-back-to-heading t))
7417 (funcall outline-level)))))
7419 (defun org-get-previous-line-level ()
7420 "Return the outline depth of the last headline before the current line.
7421 Returns 0 for the first headline in the buffer, and nil if before the
7422 first headline."
7423 (let ((current-level (org-current-level))
7424 (prev-level (when (> (line-number-at-pos) 1)
7425 (save-excursion
7426 (beginning-of-line 0)
7427 (org-current-level)))))
7428 (cond ((null current-level) nil) ; Before first headline
7429 ((null prev-level) 0) ; At first headline
7430 (prev-level))))
7432 (defun org-reduced-level (l)
7433 "Compute the effective level of a heading.
7434 This takes into account the setting of `org-odd-levels-only'."
7435 (cond
7436 ((zerop l) 0)
7437 (org-odd-levels-only (1+ (floor (/ l 2))))
7438 (t l)))
7440 (defun org-level-increment ()
7441 "Return the number of stars that will be added or removed at a
7442 time to headlines when structure editing, based on the value of
7443 `org-odd-levels-only'."
7444 (if org-odd-levels-only 2 1))
7446 (defun org-get-valid-level (level &optional change)
7447 "Rectify a level change under the influence of `org-odd-levels-only'
7448 LEVEL is a current level, CHANGE is by how much the level should be
7449 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7450 even level numbers will become the next higher odd number."
7451 (if org-odd-levels-only
7452 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7453 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7454 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7455 (max 1 (+ level (or change 0)))))
7457 (if (boundp 'define-obsolete-function-alias)
7458 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7459 (define-obsolete-function-alias 'org-get-legal-level
7460 'org-get-valid-level)
7461 (define-obsolete-function-alias 'org-get-legal-level
7462 'org-get-valid-level "23.1")))
7464 (defun org-promote ()
7465 "Promote the current heading higher up the tree.
7466 If the region is active in `transient-mark-mode', promote all headings
7467 in the region."
7468 (org-back-to-heading t)
7469 (let* ((level (save-match-data (funcall outline-level)))
7470 (after-change-functions (remove 'flyspell-after-change-function
7471 after-change-functions))
7472 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7473 (diff (abs (- level (length up-head) -1))))
7474 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
7475 (replace-match up-head nil t)
7476 ;; Fixup tag positioning
7477 (and org-auto-align-tags (org-set-tags nil t))
7478 (if org-adapt-indentation (org-fixup-indentation (- diff)))
7479 (run-hooks 'org-after-promote-entry-hook)))
7481 (defun org-demote ()
7482 "Demote the current heading lower down the tree.
7483 If the region is active in `transient-mark-mode', demote all headings
7484 in the region."
7485 (org-back-to-heading t)
7486 (let* ((level (save-match-data (funcall outline-level)))
7487 (after-change-functions (remove 'flyspell-after-change-function
7488 after-change-functions))
7489 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7490 (diff (abs (- level (length down-head) -1))))
7491 (replace-match down-head nil t)
7492 ;; Fixup tag positioning
7493 (and org-auto-align-tags (org-set-tags nil t))
7494 (if org-adapt-indentation (org-fixup-indentation diff))
7495 (run-hooks 'org-after-demote-entry-hook)))
7497 (defun org-cycle-level ()
7498 "Cycle the level of an empty headline through possible states.
7499 This goes first to child, then to parent, level, then up the hierarchy.
7500 After top level, it switches back to sibling level."
7501 (interactive)
7502 (let ((org-adapt-indentation nil))
7503 (when (org-point-at-end-of-empty-headline)
7504 (setq this-command 'org-cycle-level) ; Only needed for caching
7505 (let ((cur-level (org-current-level))
7506 (prev-level (org-get-previous-line-level)))
7507 (cond
7508 ;; If first headline in file, promote to top-level.
7509 ((= prev-level 0)
7510 (loop repeat (/ (- cur-level 1) (org-level-increment))
7511 do (org-do-promote)))
7512 ;; If same level as prev, demote one.
7513 ((= prev-level cur-level)
7514 (org-do-demote))
7515 ;; If parent is top-level, promote to top level if not already.
7516 ((= prev-level 1)
7517 (loop repeat (/ (- cur-level 1) (org-level-increment))
7518 do (org-do-promote)))
7519 ;; If top-level, return to prev-level.
7520 ((= cur-level 1)
7521 (loop repeat (/ (- prev-level 1) (org-level-increment))
7522 do (org-do-demote)))
7523 ;; If less than prev-level, promote one.
7524 ((< cur-level prev-level)
7525 (org-do-promote))
7526 ;; If deeper than prev-level, promote until higher than
7527 ;; prev-level.
7528 ((> cur-level prev-level)
7529 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7530 do (org-do-promote))))
7531 t))))
7533 (defun org-map-tree (fun)
7534 "Call FUN for every heading underneath the current one."
7535 (org-back-to-heading)
7536 (let ((level (funcall outline-level)))
7537 (save-excursion
7538 (funcall fun)
7539 (while (and (progn
7540 (outline-next-heading)
7541 (> (funcall outline-level) level))
7542 (not (eobp)))
7543 (funcall fun)))))
7545 (defun org-map-region (fun beg end)
7546 "Call FUN for every heading between BEG and END."
7547 (let ((org-ignore-region t))
7548 (save-excursion
7549 (setq end (copy-marker end))
7550 (goto-char beg)
7551 (if (and (re-search-forward org-outline-regexp-bol nil t)
7552 (< (point) end))
7553 (funcall fun))
7554 (while (and (progn
7555 (outline-next-heading)
7556 (< (point) end))
7557 (not (eobp)))
7558 (funcall fun)))))
7560 (defvar org-property-end-re) ; silence byte-compiler
7561 (defun org-fixup-indentation (diff)
7562 "Change the indentation in the current entry by DIFF.
7563 However, if any line in the current entry has no indentation, or if it
7564 would end up with no indentation after the change, nothing at all is done."
7565 (save-excursion
7566 (let ((end (save-excursion (outline-next-heading)
7567 (point-marker)))
7568 (prohibit (if (> diff 0)
7569 "^\\S-"
7570 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7571 col)
7572 (unless (save-excursion (end-of-line 1)
7573 (re-search-forward prohibit end t))
7574 (while (and (< (point) end)
7575 (re-search-forward "^[ \t]+" end t))
7576 (goto-char (match-end 0))
7577 (setq col (current-column))
7578 (if (< diff 0) (replace-match ""))
7579 (org-indent-to-column (+ diff col))))
7580 (move-marker end nil))))
7582 (defun org-convert-to-odd-levels ()
7583 "Convert an org-mode file with all levels allowed to one with odd levels.
7584 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7585 level 5 etc."
7586 (interactive)
7587 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7588 (let ((outline-level 'org-outline-level)
7589 (org-odd-levels-only nil) n)
7590 (save-excursion
7591 (goto-char (point-min))
7592 (while (re-search-forward "^\\*\\*+ " nil t)
7593 (setq n (- (length (match-string 0)) 2))
7594 (while (>= (setq n (1- n)) 0)
7595 (org-demote))
7596 (end-of-line 1))))))
7598 (defun org-convert-to-oddeven-levels ()
7599 "Convert an org-mode file with only odd levels to one with odd/even levels.
7600 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7601 file contains a section with an even level, conversion would
7602 destroy the structure of the file. An error is signaled in this
7603 case."
7604 (interactive)
7605 (goto-char (point-min))
7606 ;; First check if there are no even levels
7607 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7608 (org-show-context t)
7609 (error "Not all levels are odd in this file. Conversion not possible"))
7610 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
7611 (let ((outline-regexp org-outline-regexp)
7612 (outline-level 'org-outline-level)
7613 (org-odd-levels-only nil) n)
7614 (save-excursion
7615 (goto-char (point-min))
7616 (while (re-search-forward "^\\*\\*+ " nil t)
7617 (setq n (/ (1- (length (match-string 0))) 2))
7618 (while (>= (setq n (1- n)) 0)
7619 (org-promote))
7620 (end-of-line 1))))))
7622 (defun org-tr-level (n)
7623 "Make N odd if required."
7624 (if org-odd-levels-only (1+ (/ n 2)) n))
7626 ;;; Vertical tree motion, cutting and pasting of subtrees
7628 (defun org-move-subtree-up (&optional arg)
7629 "Move the current subtree up past ARG headlines of the same level."
7630 (interactive "p")
7631 (org-move-subtree-down (- (prefix-numeric-value arg))))
7633 (defun org-move-subtree-down (&optional arg)
7634 "Move the current subtree down past ARG headlines of the same level."
7635 (interactive "p")
7636 (setq arg (prefix-numeric-value arg))
7637 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
7638 'org-get-last-sibling))
7639 (ins-point (make-marker))
7640 (cnt (abs arg))
7641 (col (current-column))
7642 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
7643 ;; Select the tree
7644 (org-back-to-heading)
7645 (setq beg0 (point))
7646 (save-excursion
7647 (setq ne-beg (org-back-over-empty-lines))
7648 (setq beg (point)))
7649 (save-match-data
7650 (save-excursion (outline-end-of-heading)
7651 (setq folded (outline-invisible-p)))
7652 (outline-end-of-subtree))
7653 (outline-next-heading)
7654 (setq ne-end (org-back-over-empty-lines))
7655 (setq end (point))
7656 (goto-char beg0)
7657 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
7658 ;; include less whitespace
7659 (save-excursion
7660 (goto-char beg)
7661 (forward-line (- ne-beg ne-end))
7662 (setq beg (point))))
7663 ;; Find insertion point, with error handling
7664 (while (> cnt 0)
7665 (or (and (funcall movfunc) (looking-at org-outline-regexp))
7666 (progn (goto-char beg0)
7667 (error "Cannot move past superior level or buffer limit")))
7668 (setq cnt (1- cnt)))
7669 (if (> arg 0)
7670 ;; Moving forward - still need to move over subtree
7671 (progn (org-end-of-subtree t t)
7672 (save-excursion
7673 (org-back-over-empty-lines)
7674 (or (bolp) (newline)))))
7675 (setq ne-ins (org-back-over-empty-lines))
7676 (move-marker ins-point (point))
7677 (setq txt (buffer-substring beg end))
7678 (org-save-markers-in-region beg end)
7679 (delete-region beg end)
7680 (org-remove-empty-overlays-at beg)
7681 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
7682 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
7683 (and (not (bolp)) (looking-at "\n") (forward-char 1))
7684 (let ((bbb (point)))
7685 (insert-before-markers txt)
7686 (org-reinstall-markers-in-region bbb)
7687 (move-marker ins-point bbb))
7688 (or (bolp) (insert "\n"))
7689 (setq ins-end (point))
7690 (goto-char ins-point)
7691 (org-skip-whitespace)
7692 (when (and (< arg 0)
7693 (org-first-sibling-p)
7694 (> ne-ins ne-beg))
7695 ;; Move whitespace back to beginning
7696 (save-excursion
7697 (goto-char ins-end)
7698 (let ((kill-whole-line t))
7699 (kill-line (- ne-ins ne-beg)) (point)))
7700 (insert (make-string (- ne-ins ne-beg) ?\n)))
7701 (move-marker ins-point nil)
7702 (if folded
7703 (hide-subtree)
7704 (org-show-entry)
7705 (show-children)
7706 (org-cycle-hide-drawers 'children))
7707 (org-clean-visibility-after-subtree-move)
7708 ;; move back to the initial column we were at
7709 (move-to-column col)))
7711 (defvar org-subtree-clip ""
7712 "Clipboard for cut and paste of subtrees.
7713 This is actually only a copy of the kill, because we use the normal kill
7714 ring. We need it to check if the kill was created by `org-copy-subtree'.")
7716 (defvar org-subtree-clip-folded nil
7717 "Was the last copied subtree folded?
7718 This is used to fold the tree back after pasting.")
7720 (defun org-cut-subtree (&optional n)
7721 "Cut the current subtree into the clipboard.
7722 With prefix arg N, cut this many sequential subtrees.
7723 This is a short-hand for marking the subtree and then cutting it."
7724 (interactive "p")
7725 (org-copy-subtree n 'cut))
7727 (defun org-copy-subtree (&optional n cut force-store-markers)
7728 "Cut the current subtree into the clipboard.
7729 With prefix arg N, cut this many sequential subtrees.
7730 This is a short-hand for marking the subtree and then copying it.
7731 If CUT is non-nil, actually cut the subtree.
7732 If FORCE-STORE-MARKERS is non-nil, store the relative locations
7733 of some markers in the region, even if CUT is non-nil. This is
7734 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
7735 (interactive "p")
7736 (let (beg end folded (beg0 (point)))
7737 (if (org-called-interactively-p 'any)
7738 (org-back-to-heading nil) ; take what looks like a subtree
7739 (org-back-to-heading t)) ; take what is really there
7740 (org-back-over-empty-lines)
7741 (setq beg (point))
7742 (skip-chars-forward " \t\r\n")
7743 (save-match-data
7744 (save-excursion (outline-end-of-heading)
7745 (setq folded (outline-invisible-p)))
7746 (condition-case nil
7747 (org-forward-same-level (1- n) t)
7748 (error nil))
7749 (org-end-of-subtree t t))
7750 (org-back-over-empty-lines)
7751 (setq end (point))
7752 (goto-char beg0)
7753 (when (> end beg)
7754 (setq org-subtree-clip-folded folded)
7755 (when (or cut force-store-markers)
7756 (org-save-markers-in-region beg end))
7757 (if cut (kill-region beg end) (copy-region-as-kill beg end))
7758 (setq org-subtree-clip (current-kill 0))
7759 (message "%s: Subtree(s) with %d characters"
7760 (if cut "Cut" "Copied")
7761 (length org-subtree-clip)))))
7763 (defun org-paste-subtree (&optional level tree for-yank)
7764 "Paste the clipboard as a subtree, with modification of headline level.
7765 The entire subtree is promoted or demoted in order to match a new headline
7766 level.
7768 If the cursor is at the beginning of a headline, the same level as
7769 that headline is used to paste the tree
7771 If not, the new level is derived from the *visible* headings
7772 before and after the insertion point, and taken to be the inferior headline
7773 level of the two. So if the previous visible heading is level 3 and the
7774 next is level 4 (or vice versa), level 4 will be used for insertion.
7775 This makes sure that the subtree remains an independent subtree and does
7776 not swallow low level entries.
7778 You can also force a different level, either by using a numeric prefix
7779 argument, or by inserting the heading marker by hand. For example, if the
7780 cursor is after \"*****\", then the tree will be shifted to level 5.
7782 If optional TREE is given, use this text instead of the kill ring.
7784 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
7785 move back over whitespace before inserting, and move point to the end of
7786 the inserted text when done."
7787 (interactive "P")
7788 (setq tree (or tree (and kill-ring (current-kill 0))))
7789 (unless (org-kill-is-subtree-p tree)
7790 (error "%s"
7791 (substitute-command-keys
7792 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
7793 (org-with-limited-levels
7794 (let* ((visp (not (outline-invisible-p)))
7795 (txt tree)
7796 (^re_ "\\(\\*+\\)[ \t]*")
7797 (old-level (if (string-match org-outline-regexp-bol txt)
7798 (- (match-end 0) (match-beginning 0) 1)
7799 -1))
7800 (force-level (cond (level (prefix-numeric-value level))
7801 ((and (looking-at "[ \t]*$")
7802 (string-match
7803 "^\\*+$" (buffer-substring
7804 (point-at-bol) (point))))
7805 (- (match-end 1) (match-beginning 1)))
7806 ((and (bolp)
7807 (looking-at org-outline-regexp))
7808 (- (match-end 0) (point) 1))
7809 (t nil)))
7810 (previous-level (save-excursion
7811 (condition-case nil
7812 (progn
7813 (outline-previous-visible-heading 1)
7814 (if (looking-at ^re_)
7815 (- (match-end 0) (match-beginning 0) 1)
7817 (error 1))))
7818 (next-level (save-excursion
7819 (condition-case nil
7820 (progn
7821 (or (looking-at org-outline-regexp)
7822 (outline-next-visible-heading 1))
7823 (if (looking-at ^re_)
7824 (- (match-end 0) (match-beginning 0) 1)
7826 (error 1))))
7827 (new-level (or force-level (max previous-level next-level)))
7828 (shift (if (or (= old-level -1)
7829 (= new-level -1)
7830 (= old-level new-level))
7832 (- new-level old-level)))
7833 (delta (if (> shift 0) -1 1))
7834 (func (if (> shift 0) 'org-demote 'org-promote))
7835 (org-odd-levels-only nil)
7836 beg end newend)
7837 ;; Remove the forced level indicator
7838 (if force-level
7839 (delete-region (point-at-bol) (point)))
7840 ;; Paste
7841 (beginning-of-line (if (bolp) 1 2))
7842 (unless for-yank (org-back-over-empty-lines))
7843 (setq beg (point))
7844 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
7845 (insert-before-markers txt)
7846 (unless (string-match "\n\\'" txt) (insert "\n"))
7847 (setq newend (point))
7848 (org-reinstall-markers-in-region beg)
7849 (setq end (point))
7850 (goto-char beg)
7851 (skip-chars-forward " \t\n\r")
7852 (setq beg (point))
7853 (if (and (outline-invisible-p) visp)
7854 (save-excursion (outline-show-heading)))
7855 ;; Shift if necessary
7856 (unless (= shift 0)
7857 (save-restriction
7858 (narrow-to-region beg end)
7859 (while (not (= shift 0))
7860 (org-map-region func (point-min) (point-max))
7861 (setq shift (+ delta shift)))
7862 (goto-char (point-min))
7863 (setq newend (point-max))))
7864 (when (or (org-called-interactively-p 'interactive) for-yank)
7865 (message "Clipboard pasted as level %d subtree" new-level))
7866 (if (and (not for-yank) ; in this case, org-yank will decide about folding
7867 kill-ring
7868 (eq org-subtree-clip (current-kill 0))
7869 org-subtree-clip-folded)
7870 ;; The tree was folded before it was killed/copied
7871 (hide-subtree))
7872 (and for-yank (goto-char newend)))))
7874 (defun org-kill-is-subtree-p (&optional txt)
7875 "Check if the current kill is an outline subtree, or a set of trees.
7876 Returns nil if kill does not start with a headline, or if the first
7877 headline level is not the largest headline level in the tree.
7878 So this will actually accept several entries of equal levels as well,
7879 which is OK for `org-paste-subtree'.
7880 If optional TXT is given, check this string instead of the current kill."
7881 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
7882 (re (org-get-limited-outline-regexp))
7883 (^re (concat "^" re))
7884 (start-level (and kill
7885 (string-match
7886 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
7887 kill)
7888 (- (match-end 2) (match-beginning 2) 1)))
7889 (start (1+ (or (match-beginning 2) -1))))
7890 (if (not start-level)
7891 (progn
7892 nil) ;; does not even start with a heading
7893 (catch 'exit
7894 (while (setq start (string-match ^re kill (1+ start)))
7895 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
7896 (throw 'exit nil)))
7897 t))))
7899 (defvar org-markers-to-move nil
7900 "Markers that should be moved with a cut-and-paste operation.
7901 Those markers are stored together with their positions relative to
7902 the start of the region.")
7904 (defun org-save-markers-in-region (beg end)
7905 "Check markers in region.
7906 If these markers are between BEG and END, record their position relative
7907 to BEG, so that after moving the block of text, we can put the markers back
7908 into place.
7909 This function gets called just before an entry or tree gets cut from the
7910 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
7911 called immediately, to move the markers with the entries."
7912 (setq org-markers-to-move nil)
7913 (when (featurep 'org-clock)
7914 (org-clock-save-markers-for-cut-and-paste beg end))
7915 (when (featurep 'org-agenda)
7916 (org-agenda-save-markers-for-cut-and-paste beg end)))
7918 (defun org-check-and-save-marker (marker beg end)
7919 "Check if MARKER is between BEG and END.
7920 If yes, remember the marker and the distance to BEG."
7921 (when (and (marker-buffer marker)
7922 (equal (marker-buffer marker) (current-buffer)))
7923 (if (and (>= marker beg) (< marker end))
7924 (push (cons marker (- marker beg)) org-markers-to-move))))
7926 (defun org-reinstall-markers-in-region (beg)
7927 "Move all remembered markers to their position relative to BEG."
7928 (mapc (lambda (x)
7929 (move-marker (car x) (+ beg (cdr x))))
7930 org-markers-to-move)
7931 (setq org-markers-to-move nil))
7933 (defun org-narrow-to-subtree ()
7934 "Narrow buffer to the current subtree."
7935 (interactive)
7936 (save-excursion
7937 (save-match-data
7938 (org-with-limited-levels
7939 (narrow-to-region
7940 (progn (org-back-to-heading t) (point))
7941 (progn (org-end-of-subtree t t)
7942 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
7943 (point)))))))
7945 (defun org-narrow-to-block ()
7946 "Narrow buffer to the current block."
7947 (interactive)
7948 (let* ((case-fold-search t)
7949 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
7950 "^[ \t]*#\\+end_.*")))
7951 (if blockp
7952 (narrow-to-region (car blockp) (cdr blockp))
7953 (error "Not in a block"))))
7955 (eval-when-compile
7956 (defvar org-property-drawer-re))
7958 (defvar org-property-start-re) ;; defined below
7959 (defun org-clone-subtree-with-time-shift (n &optional shift)
7960 "Clone the task (subtree) at point N times.
7961 The clones will be inserted as siblings.
7963 In interactive use, the user will be prompted for the number of
7964 clones to be produced, and for a time SHIFT, which may be a
7965 repeater as used in time stamps, for example `+3d'.
7967 When a valid repeater is given and the entry contains any time
7968 stamps, the clones will become a sequence in time, with time
7969 stamps in the subtree shifted for each clone produced. If SHIFT
7970 is nil or the empty string, time stamps will be left alone. The
7971 ID property of the original subtree is removed.
7973 If the original subtree did contain time stamps with a repeater,
7974 the following will happen:
7975 - the repeater will be removed in each clone
7976 - an additional clone will be produced, with the current, unshifted
7977 date(s) in the entry.
7978 - the original entry will be placed *after* all the clones, with
7979 repeater intact.
7980 - the start days in the repeater in the original entry will be shifted
7981 to past the last clone.
7982 In this way you can spell out a number of instances of a repeating task,
7983 and still retain the repeater to cover future instances of the task."
7984 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
7985 (let (beg end template task idprop
7986 shift-n shift-what doshift nmin nmax (n-no-remove -1)
7987 (drawer-re org-drawer-regexp))
7988 (if (not (and (integerp n) (> n 0)))
7989 (error "Invalid number of replications %s" n))
7990 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
7991 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
7992 shift)))
7993 (error "Invalid shift specification %s" shift))
7994 (when doshift
7995 (setq shift-n (string-to-number (match-string 1 shift))
7996 shift-what (cdr (assoc (match-string 2 shift)
7997 '(("d" . day) ("w" . week)
7998 ("m" . month) ("y" . year))))))
7999 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8000 (setq nmin 1 nmax n)
8001 (org-back-to-heading t)
8002 (setq beg (point))
8003 (setq idprop (org-entry-get nil "ID"))
8004 (org-end-of-subtree t t)
8005 (or (bolp) (insert "\n"))
8006 (setq end (point))
8007 (setq template (buffer-substring beg end))
8008 (when (and doshift
8009 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8010 (delete-region beg end)
8011 (setq end beg)
8012 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8013 (goto-char end)
8014 (loop for n from nmin to nmax do
8015 ;; prepare clone
8016 (with-temp-buffer
8017 (insert template)
8018 (org-mode)
8019 (goto-char (point-min))
8020 (org-show-subtree)
8021 (and idprop (if org-clone-delete-id
8022 (org-entry-delete nil "ID")
8023 (org-id-get-create t)))
8024 (unless (= n 0)
8025 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8026 (kill-whole-line))
8027 (goto-char (point-min))
8028 (while (re-search-forward drawer-re nil t)
8029 (mapc (lambda (d)
8030 (org-remove-empty-drawer-at d (point))) org-drawers)))
8031 (goto-char (point-min))
8032 (when doshift
8033 (while (re-search-forward org-ts-regexp-both nil t)
8034 (org-timestamp-change (* n shift-n) shift-what))
8035 (unless (= n n-no-remove)
8036 (goto-char (point-min))
8037 (while (re-search-forward org-ts-regexp nil t)
8038 (save-excursion
8039 (goto-char (match-beginning 0))
8040 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8041 (delete-region (match-beginning 1) (match-end 1)))))))
8042 (setq task (buffer-string)))
8043 (insert task))
8044 (goto-char beg)))
8046 ;;; Outline Sorting
8048 (defun org-sort (with-case)
8049 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8050 Optional argument WITH-CASE means sort case-sensitively."
8051 (interactive "P")
8052 (cond
8053 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8054 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8056 (org-call-with-arg 'org-sort-entries with-case))))
8058 (defun org-sort-remove-invisible (s)
8059 (remove-text-properties 0 (length s) org-rm-props s)
8060 (while (string-match org-bracket-link-regexp s)
8061 (setq s (replace-match (if (match-end 2)
8062 (match-string 3 s)
8063 (match-string 1 s)) t t s)))
8066 (defvar org-priority-regexp) ; defined later in the file
8068 (defvar org-after-sorting-entries-or-items-hook nil
8069 "Hook that is run after a bunch of entries or items have been sorted.
8070 When children are sorted, the cursor is in the parent line when this
8071 hook gets called. When a region or a plain list is sorted, the cursor
8072 will be in the first entry of the sorted region/list.")
8074 (defun org-sort-entries
8075 (&optional with-case sorting-type getkey-func compare-func property)
8076 "Sort entries on a certain level of an outline tree.
8077 If there is an active region, the entries in the region are sorted.
8078 Else, if the cursor is before the first entry, sort the top-level items.
8079 Else, the children of the entry at point are sorted.
8081 Sorting can be alphabetically, numerically, by date/time as given by
8082 a time stamp, by a property or by priority.
8084 The command prompts for the sorting type unless it has been given to the
8085 function through the SORTING-TYPE argument, which needs to be a character,
8086 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F). Here is the
8087 precise meaning of each character:
8089 n Numerically, by converting the beginning of the entry/item to a number.
8090 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8091 t By date/time, either the first active time stamp in the entry, or, if
8092 none exist, by the first inactive one.
8093 s By the scheduled date/time.
8094 d By deadline date/time.
8095 c By creation time, which is assumed to be the first inactive time stamp
8096 at the beginning of a line.
8097 p By priority according to the cookie.
8098 r By the value of a property.
8100 Capital letters will reverse the sort order.
8102 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8103 called with point at the beginning of the record. It must return either
8104 a string or a number that should serve as the sorting key for that record.
8106 Comparing entries ignores case by default. However, with an optional argument
8107 WITH-CASE, the sorting considers case as well."
8108 (interactive "P")
8109 (let ((case-func (if with-case 'identity 'downcase))
8110 start beg end stars re re2
8111 txt what tmp)
8112 ;; Find beginning and end of region to sort
8113 (cond
8114 ((org-region-active-p)
8115 ;; we will sort the region
8116 (setq end (region-end)
8117 what "region")
8118 (goto-char (region-beginning))
8119 (if (not (org-at-heading-p)) (outline-next-heading))
8120 (setq start (point)))
8121 ((or (org-at-heading-p)
8122 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8123 ;; we will sort the children of the current headline
8124 (org-back-to-heading)
8125 (setq start (point)
8126 end (progn (org-end-of-subtree t t)
8127 (or (bolp) (insert "\n"))
8128 (org-back-over-empty-lines)
8129 (point))
8130 what "children")
8131 (goto-char start)
8132 (show-subtree)
8133 (outline-next-heading))
8135 ;; we will sort the top-level entries in this file
8136 (goto-char (point-min))
8137 (or (org-at-heading-p) (outline-next-heading))
8138 (setq start (point))
8139 (goto-char (point-max))
8140 (beginning-of-line 1)
8141 (when (looking-at ".*?\\S-")
8142 ;; File ends in a non-white line
8143 (end-of-line 1)
8144 (insert "\n"))
8145 (setq end (point-max))
8146 (setq what "top-level")
8147 (goto-char start)
8148 (show-all)))
8150 (setq beg (point))
8151 (if (>= beg end) (error "Nothing to sort"))
8153 (looking-at "\\(\\*+\\)")
8154 (setq stars (match-string 1)
8155 re (concat "^" (regexp-quote stars) " +")
8156 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8157 txt (buffer-substring beg end))
8158 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8159 (if (and (not (equal stars "*")) (string-match re2 txt))
8160 (error "Region to sort contains a level above the first entry"))
8162 (unless sorting-type
8163 (message
8164 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8165 [t]ime [s]cheduled [d]eadline [c]reated
8166 A/N/T/S/D/C/P/O/F means reversed:"
8167 what)
8168 (setq sorting-type (read-char-exclusive))
8170 (and (= (downcase sorting-type) ?f)
8171 (setq getkey-func
8172 (org-icompleting-read "Sort using function: "
8173 obarray 'fboundp t nil nil))
8174 (setq getkey-func (intern getkey-func)))
8176 (and (= (downcase sorting-type) ?r)
8177 (setq property
8178 (org-icompleting-read "Property: "
8179 (mapcar 'list (org-buffer-property-keys t))
8180 nil t))))
8182 (message "Sorting entries...")
8184 (save-restriction
8185 (narrow-to-region start end)
8186 (let ((dcst (downcase sorting-type))
8187 (case-fold-search nil)
8188 (now (current-time)))
8189 (sort-subr
8190 (/= dcst sorting-type)
8191 ;; This function moves to the beginning character of the "record" to
8192 ;; be sorted.
8193 (lambda nil
8194 (if (re-search-forward re nil t)
8195 (goto-char (match-beginning 0))
8196 (goto-char (point-max))))
8197 ;; This function moves to the last character of the "record" being
8198 ;; sorted.
8199 (lambda nil
8200 (save-match-data
8201 (condition-case nil
8202 (outline-forward-same-level 1)
8203 (error
8204 (goto-char (point-max))))))
8205 ;; This function returns the value that gets sorted against.
8206 (lambda nil
8207 (cond
8208 ((= dcst ?n)
8209 (if (looking-at org-complex-heading-regexp)
8210 (string-to-number (match-string 4))
8211 nil))
8212 ((= dcst ?a)
8213 (if (looking-at org-complex-heading-regexp)
8214 (funcall case-func (match-string 4))
8215 nil))
8216 ((= dcst ?t)
8217 (let ((end (save-excursion (outline-next-heading) (point))))
8218 (if (or (re-search-forward org-ts-regexp end t)
8219 (re-search-forward org-ts-regexp-both end t))
8220 (org-time-string-to-seconds (match-string 0))
8221 (org-float-time now))))
8222 ((= dcst ?c)
8223 (let ((end (save-excursion (outline-next-heading) (point))))
8224 (if (re-search-forward
8225 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8226 end t)
8227 (org-time-string-to-seconds (match-string 0))
8228 (org-float-time now))))
8229 ((= dcst ?s)
8230 (let ((end (save-excursion (outline-next-heading) (point))))
8231 (if (re-search-forward org-scheduled-time-regexp end t)
8232 (org-time-string-to-seconds (match-string 1))
8233 (org-float-time now))))
8234 ((= dcst ?d)
8235 (let ((end (save-excursion (outline-next-heading) (point))))
8236 (if (re-search-forward org-deadline-time-regexp end t)
8237 (org-time-string-to-seconds (match-string 1))
8238 (org-float-time now))))
8239 ((= dcst ?p)
8240 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8241 (string-to-char (match-string 2))
8242 org-default-priority))
8243 ((= dcst ?r)
8244 (or (org-entry-get nil property) ""))
8245 ((= dcst ?o)
8246 (if (looking-at org-complex-heading-regexp)
8247 (- 9999 (length (member (match-string 2)
8248 org-todo-keywords-1)))))
8249 ((= dcst ?f)
8250 (if getkey-func
8251 (progn
8252 (setq tmp (funcall getkey-func))
8253 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8254 tmp)
8255 (error "Invalid key function `%s'" getkey-func)))
8256 (t (error "Invalid sorting type `%c'" sorting-type))))
8258 (cond
8259 ((= dcst ?a) 'string<)
8260 ((= dcst ?f) compare-func)
8261 ((member dcst '(?p ?t ?s ?d ?c)) '<)
8262 (t nil)))))
8263 (run-hooks 'org-after-sorting-entries-or-items-hook)
8264 (message "Sorting entries...done")))
8266 (defun org-do-sort (table what &optional with-case sorting-type)
8267 "Sort TABLE of WHAT according to SORTING-TYPE.
8268 The user will be prompted for the SORTING-TYPE if the call to this
8269 function does not specify it. WHAT is only for the prompt, to indicate
8270 what is being sorted. The sorting key will be extracted from
8271 the car of the elements of the table.
8272 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8273 (unless sorting-type
8274 (message
8275 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
8276 what)
8277 (setq sorting-type (read-char-exclusive)))
8278 (let ((dcst (downcase sorting-type))
8279 extractfun comparefun)
8280 ;; Define the appropriate functions
8281 (cond
8282 ((= dcst ?n)
8283 (setq extractfun 'string-to-number
8284 comparefun (if (= dcst sorting-type) '< '>)))
8285 ((= dcst ?a)
8286 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8287 (lambda(x) (downcase (org-sort-remove-invisible x))))
8288 comparefun (if (= dcst sorting-type)
8289 'string<
8290 (lambda (a b) (and (not (string< a b))
8291 (not (string= a b)))))))
8292 ((= dcst ?t)
8293 (setq extractfun
8294 (lambda (x)
8295 (if (or (string-match org-ts-regexp x)
8296 (string-match org-ts-regexp-both x))
8297 (org-float-time
8298 (org-time-string-to-time (match-string 0 x)))
8300 comparefun (if (= dcst sorting-type) '< '>)))
8301 (t (error "Invalid sorting type `%c'" sorting-type)))
8303 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8304 table)
8305 (lambda (a b) (funcall comparefun (car a) (car b))))))
8308 ;;; The orgstruct minor mode
8310 ;; Define a minor mode which can be used in other modes in order to
8311 ;; integrate the org-mode structure editing commands.
8313 ;; This is really a hack, because the org-mode structure commands use
8314 ;; keys which normally belong to the major mode. Here is how it
8315 ;; works: The minor mode defines all the keys necessary to operate the
8316 ;; structure commands, but wraps the commands into a function which
8317 ;; tests if the cursor is currently at a headline or a plain list
8318 ;; item. If that is the case, the structure command is used,
8319 ;; temporarily setting many Org-mode variables like regular
8320 ;; expressions for filling etc. However, when any of those keys is
8321 ;; used at a different location, function uses `key-binding' to look
8322 ;; up if the key has an associated command in another currently active
8323 ;; keymap (minor modes, major mode, global), and executes that
8324 ;; command. There might be problems if any of the keys is otherwise
8325 ;; used as a prefix key.
8327 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
8328 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
8329 ;; addresses this by checking explicitly for both bindings.
8331 (defvar orgstruct-mode-map (make-sparse-keymap)
8332 "Keymap for the minor `orgstruct-mode'.")
8334 (defvar org-local-vars nil
8335 "List of local variables, for use by `orgstruct-mode'.")
8337 ;;;###autoload
8338 (define-minor-mode orgstruct-mode
8339 "Toggle the minor mode `orgstruct-mode'.
8340 This mode is for using Org-mode structure commands in other
8341 modes. The following keys behave as if Org-mode were active, if
8342 the cursor is on a headline, or on a plain list item (both as
8343 defined by Org-mode).
8345 M-up Move entry/item up
8346 M-down Move entry/item down
8347 M-left Promote
8348 M-right Demote
8349 M-S-up Move entry/item up
8350 M-S-down Move entry/item down
8351 M-S-left Promote subtree
8352 M-S-right Demote subtree
8353 M-q Fill paragraph and items like in Org-mode
8354 C-c ^ Sort entries
8355 C-c - Cycle list bullet
8356 TAB Cycle item visibility
8357 M-RET Insert new heading/item
8358 S-M-RET Insert new TODO heading / Checkbox item
8359 C-c C-c Set tags / toggle checkbox"
8360 nil " OrgStruct" nil
8361 (org-load-modules-maybe)
8362 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
8364 ;;;###autoload
8365 (defun turn-on-orgstruct ()
8366 "Unconditionally turn on `orgstruct-mode'."
8367 (orgstruct-mode 1))
8369 (defun orgstruct++-mode (&optional arg)
8370 "Toggle `orgstruct-mode', the enhanced version of it.
8371 In addition to setting orgstruct-mode, this also exports all indentation
8372 and autofilling variables from org-mode into the buffer. It will also
8373 recognize item context in multiline items.
8374 Note that turning off orgstruct-mode will *not* remove the
8375 indentation/paragraph settings. This can only be done by refreshing the
8376 major mode, for example with \\[normal-mode]."
8377 (interactive "P")
8378 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1)))
8379 ;; Set fallback functions
8380 org-auto-fill-fallback-function auto-fill-function
8381 org-indent-line-fallback-function indent-line-function
8382 org-fill-paragraph-fallback-function fill-paragraph-function)
8383 (if (< arg 1)
8384 (orgstruct-mode -1)
8385 (orgstruct-mode 1)
8386 (let (var val)
8387 (mapc
8388 (lambda (x)
8389 (when (string-match
8390 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
8391 (symbol-name (car x)))
8392 (setq var (car x) val (nth 1 x))
8393 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8394 org-local-vars)
8395 (org-set-local 'orgstruct-is-++ t))))
8397 (defvar orgstruct-is-++ nil
8398 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8399 (make-variable-buffer-local 'orgstruct-is-++)
8401 ;;;###autoload
8402 (defun turn-on-orgstruct++ ()
8403 "Unconditionally turn on `orgstruct++-mode'."
8404 (orgstruct++-mode 1))
8406 (defun orgstruct-error ()
8407 "Error when there is no default binding for a structure key."
8408 (interactive)
8409 (error "This key has no function outside structure elements"))
8411 (defun orgstruct-setup ()
8412 "Setup orgstruct keymaps."
8413 (let ((nfunc 0)
8414 (bindings
8415 (list
8416 '([(meta up)] org-metaup)
8417 '([(meta down)] org-metadown)
8418 '([(meta left)] org-metaleft)
8419 '([(meta right)] org-metaright)
8420 '([(meta shift up)] org-shiftmetaup)
8421 '([(meta shift down)] org-shiftmetadown)
8422 '([(meta shift left)] org-shiftmetaleft)
8423 '([(meta shift right)] org-shiftmetaright)
8424 '([?\e (up)] org-metaup)
8425 '([?\e (down)] org-metadown)
8426 '([?\e (left)] org-metaleft)
8427 '([?\e (right)] org-metaright)
8428 '([?\e (shift up)] org-shiftmetaup)
8429 '([?\e (shift down)] org-shiftmetadown)
8430 '([?\e (shift left)] org-shiftmetaleft)
8431 '([?\e (shift right)] org-shiftmetaright)
8432 '([(shift up)] org-shiftup)
8433 '([(shift down)] org-shiftdown)
8434 '([(shift left)] org-shiftleft)
8435 '([(shift right)] org-shiftright)
8436 '("\C-c\C-c" org-ctrl-c-ctrl-c)
8437 '("\M-q" fill-paragraph)
8438 '("\C-c^" org-sort)
8439 '("\C-c-" org-cycle-list-bullet)))
8440 elt key fun cmd)
8441 (while (setq elt (pop bindings))
8442 (setq nfunc (1+ nfunc))
8443 (setq key (org-key (car elt))
8444 fun (nth 1 elt)
8445 cmd (orgstruct-make-binding fun nfunc key))
8446 (org-defkey orgstruct-mode-map key cmd))
8448 ;; Special treatment needed for TAB and RET
8449 (org-defkey orgstruct-mode-map [(tab)]
8450 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
8451 (org-defkey orgstruct-mode-map "\C-i"
8452 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
8454 (org-defkey orgstruct-mode-map "\M-\C-m"
8455 (orgstruct-make-binding 'org-insert-heading 105
8456 "\M-\C-m" [(meta return)]))
8457 (org-defkey orgstruct-mode-map [(meta return)]
8458 (orgstruct-make-binding 'org-insert-heading 106
8459 [(meta return)] "\M-\C-m"))
8461 (org-defkey orgstruct-mode-map [(shift meta return)]
8462 (orgstruct-make-binding 'org-insert-todo-heading 107
8463 [(meta return)] "\M-\C-m"))
8465 (org-defkey orgstruct-mode-map "\e\C-m"
8466 (orgstruct-make-binding 'org-insert-heading 108
8467 "\e\C-m" [?\e (return)]))
8468 (org-defkey orgstruct-mode-map [?\e (return)]
8469 (orgstruct-make-binding 'org-insert-heading 109
8470 [?\e (return)] "\e\C-m"))
8471 (org-defkey orgstruct-mode-map [?\e (shift return)]
8472 (orgstruct-make-binding 'org-insert-todo-heading 110
8473 [?\e (return)] "\e\C-m"))
8475 (unless org-local-vars
8476 (setq org-local-vars (org-get-local-variables)))
8480 (defun orgstruct-make-binding (fun n &rest keys)
8481 "Create a function for binding in the structure minor mode.
8482 FUN is the command to call inside a table. N is used to create a unique
8483 command name. KEYS are keys that should be checked in for a command
8484 to execute outside of tables."
8485 (eval
8486 (list 'defun
8487 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
8488 '(arg)
8489 (concat "In Structure, run `" (symbol-name fun) "'.\n"
8490 "Outside of structure, run the binding of `"
8491 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
8492 "'.")
8493 '(interactive "p")
8494 (list 'if
8495 `(org-context-p 'headline 'item
8496 (and orgstruct-is-++
8497 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
8498 'item-body))
8499 (list 'org-run-like-in-org-mode (list 'quote fun))
8500 (list 'let '(orgstruct-mode)
8501 (list 'call-interactively
8502 (append '(or)
8503 (mapcar (lambda (k)
8504 (list 'key-binding k))
8505 keys)
8506 '('orgstruct-error))))))))
8508 (defun org-context-p (&rest contexts)
8509 "Check if local context is any of CONTEXTS.
8510 Possible values in the list of contexts are `table', `headline', and `item'."
8511 (let ((pos (point)))
8512 (goto-char (point-at-bol))
8513 (prog1 (or (and (memq 'table contexts)
8514 (looking-at "[ \t]*|"))
8515 (and (memq 'headline contexts)
8516 (looking-at org-outline-regexp))
8517 (and (memq 'item contexts)
8518 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
8519 (and (memq 'item-body contexts)
8520 (org-in-item-p)))
8521 (goto-char pos))))
8523 (defun org-get-local-variables ()
8524 "Return a list of all local variables in an org-mode buffer."
8525 (let (varlist)
8526 (with-current-buffer (get-buffer-create "*Org tmp*")
8527 (erase-buffer)
8528 (org-mode)
8529 (setq varlist (buffer-local-variables)))
8530 (kill-buffer "*Org tmp*")
8531 (delq nil
8532 (mapcar
8533 (lambda (x)
8534 (setq x
8535 (if (symbolp x)
8536 (list x)
8537 (list (car x) (list 'quote (cdr x)))))
8538 (if (string-match
8539 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
8540 (symbol-name (car x)))
8541 x nil))
8542 varlist))))
8544 (defun org-clone-local-variables (from-buffer &optional regexp)
8545 "Clone local variables from FROM-BUFFER.
8546 Optional argument REGEXP selects variables to clone."
8547 (mapc
8548 (lambda (pair)
8549 (and (symbolp (car pair))
8550 (or (null regexp)
8551 (string-match regexp (symbol-name (car pair))))
8552 (set (make-local-variable (car pair))
8553 (cdr pair))))
8554 (buffer-local-variables from-buffer)))
8556 ;;;###autoload
8557 (defun org-run-like-in-org-mode (cmd)
8558 "Run a command, pretending that the current buffer is in Org-mode.
8559 This will temporarily bind local variables that are typically bound in
8560 Org-mode to the values they have in Org-mode, and then interactively
8561 call CMD."
8562 (org-load-modules-maybe)
8563 (unless org-local-vars
8564 (setq org-local-vars (org-get-local-variables)))
8565 (eval (list 'let org-local-vars
8566 (list 'call-interactively (list 'quote cmd)))))
8568 ;;;; Archiving
8570 (defun org-get-category (&optional pos force-refresh)
8571 "Get the category applying to position POS."
8572 (save-match-data
8573 (if force-refresh (org-refresh-category-properties))
8574 (let ((pos (or pos (point))))
8575 (or (get-text-property pos 'org-category)
8576 (progn (org-refresh-category-properties)
8577 (get-text-property pos 'org-category))))))
8579 (defun org-refresh-category-properties ()
8580 "Refresh category text properties in the buffer."
8581 (let ((inhibit-read-only t)
8582 (def-cat (cond
8583 ((null org-category)
8584 (if buffer-file-name
8585 (file-name-sans-extension
8586 (file-name-nondirectory buffer-file-name))
8587 "???"))
8588 ((symbolp org-category) (symbol-name org-category))
8589 (t org-category)))
8590 beg end cat pos optionp)
8591 (org-unmodified
8592 (save-excursion
8593 (save-restriction
8594 (widen)
8595 (goto-char (point-min))
8596 (put-text-property (point) (point-max) 'org-category def-cat)
8597 (while (re-search-forward
8598 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8599 (setq pos (match-end 0)
8600 optionp (equal (char-after (match-beginning 0)) ?#)
8601 cat (org-trim (match-string 2)))
8602 (if optionp
8603 (setq beg (point-at-bol) end (point-max))
8604 (org-back-to-heading t)
8605 (setq beg (point) end (org-end-of-subtree t t)))
8606 (put-text-property beg end 'org-category cat)
8607 (put-text-property beg end 'org-category-position beg)
8608 (goto-char pos)))))))
8611 ;;;; Link Stuff
8613 ;;; Link abbreviations
8615 (defun org-link-expand-abbrev (link)
8616 "Apply replacements as defined in `org-link-abbrev-alist."
8617 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
8618 (let* ((key (match-string 1 link))
8619 (as (or (assoc key org-link-abbrev-alist-local)
8620 (assoc key org-link-abbrev-alist)))
8621 (tag (and (match-end 2) (match-string 3 link)))
8622 rpl)
8623 (if (not as)
8624 link
8625 (setq rpl (cdr as))
8626 (cond
8627 ((symbolp rpl) (funcall rpl tag))
8628 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
8629 ((string-match "%h" rpl)
8630 (replace-match (url-hexify-string (or tag "")) t t rpl))
8631 (t (concat rpl tag)))))
8632 link))
8634 ;;; Storing and inserting links
8636 (defvar org-insert-link-history nil
8637 "Minibuffer history for links inserted with `org-insert-link'.")
8639 (defvar org-stored-links nil
8640 "Contains the links stored with `org-store-link'.")
8642 (defvar org-store-link-plist nil
8643 "Plist with info about the most recently link created with `org-store-link'.")
8645 (defvar org-link-protocols nil
8646 "Link protocols added to Org-mode using `org-add-link-type'.")
8648 (defvar org-store-link-functions nil
8649 "List of functions that are called to create and store a link.
8650 Each function will be called in turn until one returns a non-nil
8651 value. Each function should check if it is responsible for creating
8652 this link (for example by looking at the major mode).
8653 If not, it must exit and return nil.
8654 If yes, it should return a non-nil value after a calling
8655 `org-store-link-props' with a list of properties and values.
8656 Special properties are:
8658 :type The link prefix, like \"http\". This must be given.
8659 :link The link, like \"http://www.astro.uva.nl/~dominik\".
8660 This is obligatory as well.
8661 :description Optional default description for the second pair
8662 of brackets in an Org-mode link. The user can still change
8663 this when inserting this link into an Org-mode buffer.
8665 In addition to these, any additional properties can be specified
8666 and then used in remember templates.")
8668 (defun org-add-link-type (type &optional follow export)
8669 "Add TYPE to the list of `org-link-types'.
8670 Re-compute all regular expressions depending on `org-link-types'
8672 FOLLOW and EXPORT are two functions.
8674 FOLLOW should take the link path as the single argument and do whatever
8675 is necessary to follow the link, for example find a file or display
8676 a mail message.
8678 EXPORT should format the link path for export to one of the export formats.
8679 It should be a function accepting three arguments:
8681 path the path of the link, the text after the prefix (like \"http:\")
8682 desc the description of the link, if any, or a description added by
8683 org-export-normalize-links if there is none
8684 format the export format, a symbol like `html' or `latex' or `ascii'..
8686 The function may use the FORMAT information to return different values
8687 depending on the format. The return value will be put literally into
8688 the exported file. If the return value is nil, this means Org should
8689 do what it normally does with links which do not have EXPORT defined.
8691 Org-mode has a built-in default for exporting links. If you are happy with
8692 this default, there is no need to define an export function for the link
8693 type. For a simple example of an export function, see `org-bbdb.el'."
8694 (add-to-list 'org-link-types type t)
8695 (org-make-link-regexps)
8696 (if (assoc type org-link-protocols)
8697 (setcdr (assoc type org-link-protocols) (list follow export))
8698 (push (list type follow export) org-link-protocols)))
8700 (defvar org-agenda-buffer-name)
8702 ;;;###autoload
8703 (defun org-store-link (arg)
8704 "\\<org-mode-map>Store an org-link to the current location.
8705 This link is added to `org-stored-links' and can later be inserted
8706 into an org-buffer with \\[org-insert-link].
8708 For some link types, a prefix arg is interpreted:
8709 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
8710 For file links, arg negates `org-context-in-file-links'."
8711 (interactive "P")
8712 (org-load-modules-maybe)
8713 (setq org-store-link-plist nil) ; reset
8714 (org-with-limited-levels
8715 (let (link cpltxt desc description search txt custom-id agenda-link)
8716 (cond
8718 ((run-hook-with-args-until-success 'org-store-link-functions)
8719 (setq link (plist-get org-store-link-plist :link)
8720 desc (or (plist-get org-store-link-plist :description) link)))
8722 ((org-src-edit-buffer-p)
8723 (let (label gc)
8724 (while (or (not label)
8725 (save-excursion
8726 (save-restriction
8727 (widen)
8728 (goto-char (point-min))
8729 (re-search-forward
8730 (regexp-quote (format org-coderef-label-format label))
8731 nil t))))
8732 (when label (message "Label exists already") (sit-for 2))
8733 (setq label (read-string "Code line label: " label)))
8734 (end-of-line 1)
8735 (setq link (format org-coderef-label-format label))
8736 (setq gc (- 79 (length link)))
8737 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
8738 (insert link)
8739 (setq link (concat "(" label ")") desc nil)))
8741 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
8742 ;; We are in the agenda, link to referenced location
8743 (let ((m (or (get-text-property (point) 'org-hd-marker)
8744 (get-text-property (point) 'org-marker))))
8745 (when m
8746 (org-with-point-at m
8747 (setq agenda-link
8748 (if (org-called-interactively-p 'any)
8749 (call-interactively 'org-store-link)
8750 (org-store-link nil)))))))
8752 ((eq major-mode 'calendar-mode)
8753 (let ((cd (calendar-cursor-to-date)))
8754 (setq link
8755 (format-time-string
8756 (car org-time-stamp-formats)
8757 (apply 'encode-time
8758 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
8759 nil nil nil))))
8760 (org-store-link-props :type "calendar" :date cd)))
8762 ((eq major-mode 'w3-mode)
8763 (setq cpltxt (if (and (buffer-name)
8764 (not (string-match "Untitled" (buffer-name))))
8765 (buffer-name)
8766 (url-view-url t))
8767 link (org-make-link (url-view-url t)))
8768 (org-store-link-props :type "w3" :url (url-view-url t)))
8770 ((eq major-mode 'w3m-mode)
8771 (setq cpltxt (or w3m-current-title w3m-current-url)
8772 link (org-make-link w3m-current-url))
8773 (org-store-link-props :type "w3m" :url (url-view-url t)))
8775 ((setq search (run-hook-with-args-until-success
8776 'org-create-file-search-functions))
8777 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
8778 "::" search))
8779 (setq cpltxt (or description link)))
8781 ((eq major-mode 'image-mode)
8782 (setq cpltxt (concat "file:"
8783 (abbreviate-file-name buffer-file-name))
8784 link (org-make-link cpltxt))
8785 (org-store-link-props :type "image" :file buffer-file-name))
8787 ((eq major-mode 'dired-mode)
8788 ;; link to the file in the current line
8789 (let ((file (dired-get-filename nil t)))
8790 (setq file (if file
8791 (abbreviate-file-name
8792 (expand-file-name (dired-get-filename nil t)))
8793 ;; otherwise, no file so use current directory.
8794 default-directory))
8795 (setq cpltxt (concat "file:" file)
8796 link (org-make-link cpltxt))))
8798 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
8799 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
8800 (cond
8801 ((org-in-regexp "<<\\(.*?\\)>>")
8802 (setq cpltxt
8803 (concat "file:"
8804 (abbreviate-file-name
8805 (buffer-file-name (buffer-base-buffer)))
8806 "::" (match-string 1))
8807 link (org-make-link cpltxt)))
8808 ((and (featurep 'org-id)
8809 (or (eq org-link-to-org-use-id t)
8810 (and (eq org-link-to-org-use-id 'create-if-interactive)
8811 (org-called-interactively-p 'any))
8812 (and (eq org-link-to-org-use-id
8813 'create-if-interactive-and-no-custom-id)
8814 (org-called-interactively-p 'any)
8815 (not custom-id))
8816 (and org-link-to-org-use-id
8817 (org-entry-get nil "ID"))))
8818 ;; We can make a link using the ID.
8819 (setq link (condition-case nil
8820 (prog1 (org-id-store-link)
8821 (setq desc (plist-get org-store-link-plist
8822 :description)))
8823 (error
8824 ;; probably before first headline, link to file only
8825 (concat "file:"
8826 (abbreviate-file-name
8827 (buffer-file-name (buffer-base-buffer))))))))
8829 ;; Just link to current headline
8830 (setq cpltxt (concat "file:"
8831 (abbreviate-file-name
8832 (buffer-file-name (buffer-base-buffer)))))
8833 ;; Add a context search string
8834 (when (org-xor org-context-in-file-links arg)
8835 (setq txt (cond
8836 ((org-at-heading-p) nil)
8837 ((org-region-active-p)
8838 (buffer-substring (region-beginning) (region-end)))
8839 (t nil)))
8840 (when (or (null txt) (string-match "\\S-" txt))
8841 (setq cpltxt
8842 (concat cpltxt "::"
8843 (condition-case nil
8844 (org-make-org-heading-search-string txt)
8845 (error "")))
8846 desc (or (nth 4 (ignore-errors
8847 (org-heading-components))) "NONE"))))
8848 (if (string-match "::\\'" cpltxt)
8849 (setq cpltxt (substring cpltxt 0 -2)))
8850 (setq link (org-make-link cpltxt)))))
8852 ((buffer-file-name (buffer-base-buffer))
8853 ;; Just link to this file here.
8854 (setq cpltxt (concat "file:"
8855 (abbreviate-file-name
8856 (buffer-file-name (buffer-base-buffer)))))
8857 ;; Add a context string
8858 (when (org-xor org-context-in-file-links arg)
8859 (setq txt (if (org-region-active-p)
8860 (buffer-substring (region-beginning) (region-end))
8861 (buffer-substring (point-at-bol) (point-at-eol))))
8862 ;; Only use search option if there is some text.
8863 (when (string-match "\\S-" txt)
8864 (setq cpltxt
8865 (concat cpltxt "::" (org-make-org-heading-search-string txt))
8866 desc "NONE")))
8867 (setq link (org-make-link cpltxt)))
8869 ((org-called-interactively-p 'interactive)
8870 (error "Cannot link to a buffer which is not visiting a file"))
8872 (t (setq link nil)))
8874 (if (consp link) (setq cpltxt (car link) link (cdr link)))
8875 (setq link (or link cpltxt)
8876 desc (or desc cpltxt))
8877 (if (equal desc "NONE") (setq desc nil))
8879 (if (and (or (org-called-interactively-p 'any) executing-kbd-macro) link)
8880 (progn
8881 (setq org-stored-links
8882 (cons (list link desc) org-stored-links))
8883 (message "Stored: %s" (or desc link))
8884 (when custom-id
8885 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
8886 "::#" custom-id))
8887 (setq org-stored-links
8888 (cons (list link desc) org-stored-links))))
8889 (or agenda-link (and link (org-make-link-string link desc)))))))
8891 (defun org-store-link-props (&rest plist)
8892 "Store link properties, extract names and addresses."
8893 (let (x adr)
8894 (when (setq x (plist-get plist :from))
8895 (setq adr (mail-extract-address-components x))
8896 (setq plist (plist-put plist :fromname (car adr)))
8897 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
8898 (when (setq x (plist-get plist :to))
8899 (setq adr (mail-extract-address-components x))
8900 (setq plist (plist-put plist :toname (car adr)))
8901 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
8902 (let ((from (plist-get plist :from))
8903 (to (plist-get plist :to)))
8904 (when (and from to org-from-is-user-regexp)
8905 (setq plist
8906 (plist-put plist :fromto
8907 (if (string-match org-from-is-user-regexp from)
8908 (concat "to %t")
8909 (concat "from %f"))))))
8910 (setq org-store-link-plist plist))
8912 (defun org-add-link-props (&rest plist)
8913 "Add these properties to the link property list."
8914 (let (key value)
8915 (while plist
8916 (setq key (pop plist) value (pop plist))
8917 (setq org-store-link-plist
8918 (plist-put org-store-link-plist key value)))))
8920 (defun org-email-link-description (&optional fmt)
8921 "Return the description part of an email link.
8922 This takes information from `org-store-link-plist' and formats it
8923 according to FMT (default from `org-email-link-description-format')."
8924 (setq fmt (or fmt org-email-link-description-format))
8925 (let* ((p org-store-link-plist)
8926 (to (plist-get p :toaddress))
8927 (from (plist-get p :fromaddress))
8928 (table
8929 (list
8930 (cons "%c" (plist-get p :fromto))
8931 (cons "%F" (plist-get p :from))
8932 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
8933 (cons "%T" (plist-get p :to))
8934 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
8935 (cons "%s" (plist-get p :subject))
8936 (cons "%d" (plist-get p :date))
8937 (cons "%m" (plist-get p :message-id)))))
8938 (when (string-match "%c" fmt)
8939 ;; Check if the user wrote this message
8940 (if (and org-from-is-user-regexp from to
8941 (save-match-data (string-match org-from-is-user-regexp from)))
8942 (setq fmt (replace-match "to %t" t t fmt))
8943 (setq fmt (replace-match "from %f" t t fmt))))
8944 (org-replace-escapes fmt table)))
8946 (defun org-make-org-heading-search-string (&optional string heading)
8947 "Make search string for STRING or current headline."
8948 (interactive)
8949 (let ((s (or string (org-get-heading)))
8950 (lines org-context-in-file-links))
8951 (unless (and string (not heading))
8952 ;; We are using a headline, clean up garbage in there.
8953 (if (string-match org-todo-regexp s)
8954 (setq s (replace-match "" t t s)))
8955 (if (string-match (org-re ":[[:alnum:]_@#%:]+:[ \t]*$") s)
8956 (setq s (replace-match "" t t s)))
8957 (setq s (org-trim s))
8958 (if (string-match (concat "^\\(" org-quote-string "\\|"
8959 org-comment-string "\\)") s)
8960 (setq s (replace-match "" t t s)))
8961 (while (string-match org-ts-regexp s)
8962 (setq s (replace-match "" t t s))))
8963 (or string (setq s (concat "*" s))) ; Add * for headlines
8964 (when (and string (integerp lines) (> lines 0))
8965 (let ((slines (org-split-string s "\n")))
8966 (when (< lines (length slines))
8967 (setq s (mapconcat
8968 'identity
8969 (reverse (nthcdr (- (length slines) lines)
8970 (reverse slines))) "\n")))))
8971 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
8973 (defun org-make-link (&rest strings)
8974 "Concatenate STRINGS."
8975 (apply 'concat strings))
8977 (defun org-make-link-string (link &optional description)
8978 "Make a link with brackets, consisting of LINK and DESCRIPTION."
8979 (unless (string-match "\\S-" link)
8980 (error "Empty link"))
8981 (when (and description
8982 (stringp description)
8983 (not (string-match "\\S-" description)))
8984 (setq description nil))
8985 (when (stringp description)
8986 ;; Remove brackets from the description, they are fatal.
8987 (while (string-match "\\[" description)
8988 (setq description (replace-match "{" t t description)))
8989 (while (string-match "\\]" description)
8990 (setq description (replace-match "}" t t description))))
8991 (when (equal link description)
8992 ;; No description needed, it is identical
8993 (setq description nil))
8994 (when (and (not description)
8995 (not (string-match (org-image-file-name-regexp) link))
8996 (not (equal link (org-link-escape link))))
8997 (setq description (org-extract-attributes link)))
8998 (setq link
8999 (cond ((string-match (org-image-file-name-regexp) link) link)
9000 ((string-match org-link-types-re link)
9001 (concat (match-string 1 link)
9002 (org-link-escape (substring link (match-end 1)))))
9003 (t (org-link-escape link))))
9004 (concat "[[" link "]"
9005 (if description (concat "[" description "]") "")
9006 "]"))
9008 (defconst org-link-escape-chars
9009 '(?\ ?\[ ?\] ?\; ?\= ?\+)
9010 "List of characters that should be escaped in link.
9011 This is the list that is used for internal purposes.")
9013 (defvar org-url-encoding-use-url-hexify nil)
9015 (defconst org-link-escape-chars-browser
9016 '(?\ )
9017 "List of escapes for characters that are problematic in links.
9018 This is the list that is used before handing over to the browser.")
9020 (defun org-link-escape (text &optional table merge)
9021 "Return percent escaped representation of TEXT.
9022 TEXT is a string with the text to escape.
9023 Optional argument TABLE is a list with characters that should be
9024 escaped. When nil, `org-link-escape-chars' is used.
9025 If optional argument MERGE is set, merge TABLE into
9026 `org-link-escape-chars'."
9027 (if (and org-url-encoding-use-url-hexify (not table))
9028 (url-hexify-string text)
9029 (cond
9030 ((and table merge)
9031 (mapc (lambda (defchr)
9032 (unless (member defchr table)
9033 (setq table (cons defchr table)))) org-link-escape-chars))
9034 ((null table)
9035 (setq table org-link-escape-chars)))
9036 (mapconcat
9037 (lambda (char)
9038 (if (or (member char table)
9039 (< char 32) (= char 37) (> char 126))
9040 (mapconcat (lambda (sequence-element)
9041 (format "%%%.2X" sequence-element))
9042 (or (encode-coding-char char 'utf-8)
9043 (error "Unable to percent escape character: %s"
9044 (char-to-string char))) "")
9045 (char-to-string char))) text "")))
9047 (defun org-link-unescape (str)
9048 "Unhex hexified Unicode strings as returned from the JavaScript function
9049 encodeURIComponent. E.g. `%C3%B6' is the german Umlaut `ö'."
9050 (unless (and (null str) (string= "" str))
9051 (let ((pos 0) (case-fold-search t) unhexed)
9052 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9053 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9054 (setq str (replace-match unhexed t t str))
9055 (setq pos (+ pos (length unhexed))))))
9056 str)
9058 (defun org-link-unescape-compound (hex)
9059 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German Umlaut `ö'.
9060 Note: this function also decodes single byte encodings like
9061 `%E1' (\"á\") if not followed by another `%[A-F0-9]{2}' group."
9062 (save-match-data
9063 (let* ((bytes (cdr (split-string hex "%")))
9064 (ret "")
9065 (eat 0)
9066 (sum 0))
9067 (while bytes
9068 (let* ((val (string-to-number (pop bytes) 16))
9069 (shift-xor
9070 (if (= 0 eat)
9071 (cond
9072 ((>= val 252) (cons 6 252))
9073 ((>= val 248) (cons 5 248))
9074 ((>= val 240) (cons 4 240))
9075 ((>= val 224) (cons 3 224))
9076 ((>= val 192) (cons 2 192))
9077 (t (cons 0 0)))
9078 (cons 6 128))))
9079 (if (>= val 192) (setq eat (car shift-xor)))
9080 (setq val (logxor val (cdr shift-xor)))
9081 (setq sum (+ (lsh sum (car shift-xor)) val))
9082 (if (> eat 0) (setq eat (- eat 1)))
9083 (cond
9084 ((= 0 eat) ;multi byte
9085 (setq ret (concat ret (org-char-to-string sum)))
9086 (setq sum 0))
9087 ((not bytes) ; single byte(s)
9088 (setq ret (org-link-unescape-single-byte-sequence hex))))
9089 )) ;; end (while bytes
9090 ret )))
9092 (defun org-link-unescape-single-byte-sequence (hex)
9093 "Unhexify hex-encoded single byte character sequences."
9094 (mapconcat (lambda (byte)
9095 (char-to-string (string-to-number byte 16)))
9096 (cdr (split-string hex "%")) ""))
9098 (defun org-xor (a b)
9099 "Exclusive or."
9100 (if a (not b) b))
9102 (defun org-fixup-message-id-for-http (s)
9103 "Replace special characters in a message id, so it can be used in an http query."
9104 (when (string-match "%" s)
9105 (setq s (mapconcat (lambda (c)
9106 (if (eq c ?%)
9107 "%25"
9108 (char-to-string c)))
9109 s "")))
9110 (while (string-match "<" s)
9111 (setq s (replace-match "%3C" t t s)))
9112 (while (string-match ">" s)
9113 (setq s (replace-match "%3E" t t s)))
9114 (while (string-match "@" s)
9115 (setq s (replace-match "%40" t t s)))
9118 (defun org-link-prettify (link)
9119 "Return a human-readable representation of LINK.
9120 The car of LINK must be a raw link the cdr of LINK must be either
9121 a link description or nil."
9122 (let ((desc (or (cadr link) "<no description>")))
9123 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9124 "[[" (car link) "]]")))
9126 ;;;###autoload
9127 (defun org-insert-link-global ()
9128 "Insert a link like Org-mode does.
9129 This command can be called in any mode to insert a link in Org-mode syntax."
9130 (interactive)
9131 (org-load-modules-maybe)
9132 (org-run-like-in-org-mode 'org-insert-link))
9134 (defun org-insert-link (&optional complete-file link-location default-description)
9135 "Insert a link. At the prompt, enter the link.
9137 Completion can be used to insert any of the link protocol prefixes like
9138 http or ftp in use.
9140 The history can be used to select a link previously stored with
9141 `org-store-link'. When the empty string is entered (i.e. if you just
9142 press RET at the prompt), the link defaults to the most recently
9143 stored link. As SPC triggers completion in the minibuffer, you need to
9144 use M-SPC or C-q SPC to force the insertion of a space character.
9146 You will also be prompted for a description, and if one is given, it will
9147 be displayed in the buffer instead of the link.
9149 If there is already a link at point, this command will allow you to edit link
9150 and description parts.
9152 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9153 be selected using completion. The path to the file will be relative to the
9154 current directory if the file is in the current directory or a subdirectory.
9155 Otherwise, the link will be the absolute path as completed in the minibuffer
9156 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9157 option `org-link-file-path-type'.
9159 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9160 the current directory or below.
9162 With three \\[universal-argument] prefixes, negate the meaning of
9163 `org-keep-stored-link-after-insertion'.
9165 If `org-make-link-description-function' is non-nil, this function will be
9166 called with the link target, and the result will be the default
9167 link description.
9169 If the LINK-LOCATION parameter is non-nil, this value will be
9170 used as the link location instead of reading one interactively.
9172 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9173 be used as the default description."
9174 (interactive "P")
9175 (let* ((wcf (current-window-configuration))
9176 (region (if (org-region-active-p)
9177 (buffer-substring (region-beginning) (region-end))))
9178 (remove (and region (list (region-beginning) (region-end))))
9179 (desc region)
9180 tmphist ; byte-compile incorrectly complains about this
9181 (link link-location)
9182 entry file all-prefixes)
9183 (cond
9184 (link-location) ; specified by arg, just use it.
9185 ((org-in-regexp org-bracket-link-regexp 1)
9186 ;; We do have a link at point, and we are going to edit it.
9187 (setq remove (list (match-beginning 0) (match-end 0)))
9188 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9189 (setq link (read-string "Link: "
9190 (org-link-unescape
9191 (org-match-string-no-properties 1)))))
9192 ((or (org-in-regexp org-angle-link-re)
9193 (org-in-regexp org-plain-link-re))
9194 ;; Convert to bracket link
9195 (setq remove (list (match-beginning 0) (match-end 0))
9196 link (read-string "Link: "
9197 (org-remove-angle-brackets (match-string 0)))))
9198 ((member complete-file '((4) (16)))
9199 ;; Completing read for file names.
9200 (setq link (org-file-complete-link complete-file)))
9202 ;; Read link, with completion for stored links.
9203 (with-output-to-temp-buffer "*Org Links*"
9204 (princ "Insert a link.
9205 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9206 (when org-stored-links
9207 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9208 (princ (mapconcat 'org-link-prettify
9209 (reverse org-stored-links) "\n"))))
9210 (let ((cw (selected-window)))
9211 (select-window (get-buffer-window "*Org Links*" 'visible))
9212 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9213 (unless (pos-visible-in-window-p (point-max))
9214 (org-fit-window-to-buffer))
9215 (and (window-live-p cw) (select-window cw)))
9216 ;; Fake a link history, containing the stored links.
9217 (setq tmphist (append (mapcar 'car org-stored-links)
9218 org-insert-link-history))
9219 (setq all-prefixes (append (mapcar 'car org-link-abbrev-alist-local)
9220 (mapcar 'car org-link-abbrev-alist)
9221 org-link-types))
9222 (unwind-protect
9223 (progn
9224 (setq link
9225 (let ((org-completion-use-ido nil)
9226 (org-completion-use-iswitchb nil))
9227 (org-completing-read
9228 "Link: "
9229 (append
9230 (mapcar (lambda (x) (list (concat x ":")))
9231 all-prefixes)
9232 (mapcar 'car org-stored-links))
9233 nil nil nil
9234 'tmphist
9235 (car (car org-stored-links)))))
9236 (if (not (string-match "\\S-" link))
9237 (error "No link selected"))
9238 (if (or (member link all-prefixes)
9239 (and (equal ":" (substring link -1))
9240 (member (substring link 0 -1) all-prefixes)
9241 (setq link (substring link 0 -1))))
9242 (setq link (org-link-try-special-completion link))))
9243 (set-window-configuration wcf)
9244 (kill-buffer "*Org Links*"))
9245 (setq entry (assoc link org-stored-links))
9246 (or entry (push link org-insert-link-history))
9247 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9248 (not org-keep-stored-link-after-insertion))
9249 (setq org-stored-links (delq (assoc link org-stored-links)
9250 org-stored-links)))
9251 (setq desc (or desc (nth 1 entry)))))
9253 (if (string-match org-plain-link-re link)
9254 ;; URL-like link, normalize the use of angular brackets.
9255 (setq link (org-make-link (org-remove-angle-brackets link))))
9257 ;; Check if we are linking to the current file with a search option
9258 ;; If yes, simplify the link by using only the search option.
9259 (when (and buffer-file-name
9260 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
9261 (let* ((path (match-string 1 link))
9262 (case-fold-search nil)
9263 (search (match-string 2 link)))
9264 (save-match-data
9265 (if (equal (file-truename buffer-file-name) (file-truename path))
9266 ;; We are linking to this same file, with a search option
9267 (setq link search)))))
9269 ;; Check if we can/should use a relative path. If yes, simplify the link
9270 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
9271 (let* ((type (match-string 1 link))
9272 (path (match-string 2 link))
9273 (origpath path)
9274 (case-fold-search nil))
9275 (cond
9276 ((or (eq org-link-file-path-type 'absolute)
9277 (equal complete-file '(16)))
9278 (setq path (abbreviate-file-name (expand-file-name path))))
9279 ((eq org-link-file-path-type 'noabbrev)
9280 (setq path (expand-file-name path)))
9281 ((eq org-link-file-path-type 'relative)
9282 (setq path (file-relative-name path)))
9284 (save-match-data
9285 (if (string-match (concat "^" (regexp-quote
9286 (expand-file-name
9287 (file-name-as-directory
9288 default-directory))))
9289 (expand-file-name path))
9290 ;; We are linking a file with relative path name.
9291 (setq path (substring (expand-file-name path)
9292 (match-end 0)))
9293 (setq path (abbreviate-file-name (expand-file-name path)))))))
9294 (setq link (concat type path))
9295 (if (equal desc origpath)
9296 (setq desc path))))
9298 (if org-make-link-description-function
9299 (setq desc (funcall org-make-link-description-function link desc))
9300 (if default-description (setq desc default-description)))
9302 (setq desc (read-string "Description: " desc))
9303 (unless (string-match "\\S-" desc) (setq desc nil))
9304 (if remove (apply 'delete-region remove))
9305 (insert (org-make-link-string link desc))))
9307 (defun org-link-try-special-completion (type)
9308 "If there is completion support for link type TYPE, offer it."
9309 (let ((fun (intern (concat "org-" type "-complete-link"))))
9310 (if (functionp fun)
9311 (funcall fun)
9312 (read-string "Link (no completion support): " (concat type ":")))))
9314 (defun org-file-complete-link (&optional arg)
9315 "Create a file link using completion."
9316 (let (file link)
9317 (setq file (read-file-name "File: "))
9318 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9319 (pwd1 (file-name-as-directory (abbreviate-file-name
9320 (expand-file-name ".")))))
9321 (cond
9322 ((equal arg '(16))
9323 (setq link (org-make-link
9324 "file:"
9325 (abbreviate-file-name (expand-file-name file)))))
9326 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9327 (setq link (org-make-link "file:" (match-string 1 file))))
9328 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9329 (expand-file-name file))
9330 (setq link (org-make-link
9331 "file:" (match-string 1 (expand-file-name file)))))
9332 (t (setq link (org-make-link "file:" file)))))
9333 link))
9335 (defun org-completing-read (&rest args)
9336 "Completing-read with SPACE being a normal character."
9337 (let ((enable-recursive-minibuffers t)
9338 (minibuffer-local-completion-map
9339 (copy-keymap minibuffer-local-completion-map)))
9340 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
9341 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
9342 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
9343 (apply 'org-icompleting-read args)))
9345 (defun org-completing-read-no-i (&rest args)
9346 (let (org-completion-use-ido org-completion-use-iswitchb)
9347 (apply 'org-completing-read args)))
9349 (defun org-iswitchb-completing-read (prompt choices &rest args)
9350 "Use iswitch as a completing-read replacement to choose from choices.
9351 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
9352 from."
9353 (let* ((iswitchb-use-virtual-buffers nil)
9354 (iswitchb-make-buflist-hook
9355 (lambda ()
9356 (setq iswitchb-temp-buflist choices))))
9357 (iswitchb-read-buffer prompt)))
9359 (defun org-icompleting-read (&rest args)
9360 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
9361 (org-without-partial-completion
9362 (if (and org-completion-use-ido
9363 (fboundp 'ido-completing-read)
9364 (boundp 'ido-mode) ido-mode
9365 (listp (second args)))
9366 (let ((ido-enter-matching-directory nil))
9367 (apply 'ido-completing-read (concat (car args))
9368 (if (consp (car (nth 1 args)))
9369 (mapcar 'car (nth 1 args))
9370 (nth 1 args))
9371 (cddr args)))
9372 (if (and org-completion-use-iswitchb
9373 (boundp 'iswitchb-mode) iswitchb-mode
9374 (listp (second args)))
9375 (apply 'org-iswitchb-completing-read (concat (car args))
9376 (if (consp (car (nth 1 args)))
9377 (mapcar 'car (nth 1 args))
9378 (nth 1 args))
9379 (cddr args))
9380 (apply 'completing-read args)))))
9382 (defun org-extract-attributes (s)
9383 "Extract the attributes cookie from a string and set as text property."
9384 (let (a attr (start 0) key value)
9385 (save-match-data
9386 (when (string-match "{{\\([^}]+\\)}}$" s)
9387 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
9388 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
9389 (setq key (match-string 1 a) value (match-string 2 a)
9390 start (match-end 0)
9391 attr (plist-put attr (intern key) value))))
9392 (org-add-props s nil 'org-attr attr))
9395 (defun org-extract-attributes-from-string (tag)
9396 (let (key value attr)
9397 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
9398 (setq key (match-string 1 tag) value (match-string 2 tag)
9399 tag (replace-match "" t t tag)
9400 attr (plist-put attr (intern key) value)))
9401 (cons tag attr)))
9403 (defun org-attributes-to-string (plist)
9404 "Format a property list into an HTML attribute list."
9405 (let ((s "") key value)
9406 (while plist
9407 (setq key (pop plist) value (pop plist))
9408 (and value
9409 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
9412 ;;; Opening/following a link
9414 (defvar org-link-search-failed nil)
9416 (defvar org-open-link-functions nil
9417 "Hook for functions finding a plain text link.
9418 These functions must take a single argument, the link content.
9419 They will be called for links that look like [[link text][description]]
9420 when LINK TEXT does not have a protocol like \"http:\" and does not look
9421 like a filename (e.g. \"./blue.png\").
9423 These functions will be called *before* Org attempts to resolve the
9424 link by doing text searches in the current buffer - so if you want a
9425 link \"[[target]]\" to still find \"<<target>>\", your function should
9426 handle this as a special case.
9428 When the function does handle the link, it must return a non-nil value.
9429 If it decides that it is not responsible for this link, it must return
9430 nil to indicate that that Org-mode can continue with other options
9431 like exact and fuzzy text search.")
9433 (defun org-next-link ()
9434 "Move forward to the next link.
9435 If the link is in hidden text, expose it."
9436 (interactive)
9437 (when (and org-link-search-failed (eq this-command last-command))
9438 (goto-char (point-min))
9439 (message "Link search wrapped back to beginning of buffer"))
9440 (setq org-link-search-failed nil)
9441 (let* ((pos (point))
9442 (ct (org-context))
9443 (a (assoc :link ct)))
9444 (if a (goto-char (nth 2 a)))
9445 (if (re-search-forward org-any-link-re nil t)
9446 (progn
9447 (goto-char (match-beginning 0))
9448 (if (outline-invisible-p) (org-show-context)))
9449 (goto-char pos)
9450 (setq org-link-search-failed t)
9451 (error "No further link found"))))
9453 (defun org-previous-link ()
9454 "Move backward to the previous link.
9455 If the link is in hidden text, expose it."
9456 (interactive)
9457 (when (and org-link-search-failed (eq this-command last-command))
9458 (goto-char (point-max))
9459 (message "Link search wrapped back to end of buffer"))
9460 (setq org-link-search-failed nil)
9461 (let* ((pos (point))
9462 (ct (org-context))
9463 (a (assoc :link ct)))
9464 (if a (goto-char (nth 1 a)))
9465 (if (re-search-backward org-any-link-re nil t)
9466 (progn
9467 (goto-char (match-beginning 0))
9468 (if (outline-invisible-p) (org-show-context)))
9469 (goto-char pos)
9470 (setq org-link-search-failed t)
9471 (error "No further link found"))))
9473 (defun org-translate-link (s)
9474 "Translate a link string if a translation function has been defined."
9475 (if (and org-link-translation-function
9476 (fboundp org-link-translation-function)
9477 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
9478 (progn
9479 (setq s (funcall org-link-translation-function
9480 (match-string 1) (match-string 2)))
9481 (concat (car s) ":" (cdr s)))
9484 (defun org-translate-link-from-planner (type path)
9485 "Translate a link from Emacs Planner syntax so that Org can follow it.
9486 This is still an experimental function, your mileage may vary."
9487 (cond
9488 ((member type '("http" "https" "news" "ftp"))
9489 ;; standard Internet links are the same.
9490 nil)
9491 ((and (equal type "irc") (string-match "^//" path))
9492 ;; Planner has two / at the beginning of an irc link, we have 1.
9493 ;; We should have zero, actually....
9494 (setq path (substring path 1)))
9495 ((and (equal type "lisp") (string-match "^/" path))
9496 ;; Planner has a slash, we do not.
9497 (setq type "elisp" path (substring path 1)))
9498 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9499 ;; A typical message link. Planner has the id after the final slash,
9500 ;; we separate it with a hash mark
9501 (setq path (concat (match-string 1 path) "#"
9502 (org-remove-angle-brackets (match-string 2 path)))))
9504 (cons type path))
9506 (defun org-find-file-at-mouse (ev)
9507 "Open file link or URL at mouse."
9508 (interactive "e")
9509 (mouse-set-point ev)
9510 (org-open-at-point 'in-emacs))
9512 (defun org-open-at-mouse (ev)
9513 "Open file link or URL at mouse.
9514 See the docstring of `org-open-file' for details."
9515 (interactive "e")
9516 (mouse-set-point ev)
9517 (if (eq major-mode 'org-agenda-mode)
9518 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
9519 (org-open-at-point))
9521 (defvar org-window-config-before-follow-link nil
9522 "The window configuration before following a link.
9523 This is saved in case the need arises to restore it.")
9525 (defvar org-open-link-marker (make-marker)
9526 "Marker pointing to the location where `org-open-at-point; was called.")
9528 ;;;###autoload
9529 (defun org-open-at-point-global ()
9530 "Follow a link like Org-mode does.
9531 This command can be called in any mode to follow a link that has
9532 Org-mode syntax."
9533 (interactive)
9534 (org-run-like-in-org-mode 'org-open-at-point))
9536 ;;;###autoload
9537 (defun org-open-link-from-string (s &optional arg reference-buffer)
9538 "Open a link in the string S, as if it was in Org-mode."
9539 (interactive "sLink: \nP")
9540 (let ((reference-buffer (or reference-buffer (current-buffer))))
9541 (with-temp-buffer
9542 (let ((org-inhibit-startup (not reference-buffer)))
9543 (org-mode)
9544 (insert s)
9545 (goto-char (point-min))
9546 (when reference-buffer
9547 (setq org-link-abbrev-alist-local
9548 (with-current-buffer reference-buffer
9549 org-link-abbrev-alist-local)))
9550 (org-open-at-point arg reference-buffer)))))
9552 (defvar org-open-at-point-functions nil
9553 "Hook that is run when following a link at point.
9555 Functions in this hook must return t if they identify and follow
9556 a link at point. If they don't find anything interesting at point,
9557 they must return nil.")
9559 (defun org-open-at-point (&optional arg reference-buffer)
9560 "Open link at or after point.
9561 If there is no link at point, this function will search forward up to
9562 the end of the current line.
9563 Normally, files will be opened by an appropriate application. If the
9564 optional prefix argument ARG is non-nil, Emacs will visit the file.
9565 With a double prefix argument, try to open outside of Emacs, in the
9566 application the system uses for this file type."
9567 (interactive "P")
9568 ;; if in a code block, then open the block's results
9569 (unless (call-interactively #'org-babel-open-src-block-result)
9570 (org-load-modules-maybe)
9571 (move-marker org-open-link-marker (point))
9572 (setq org-window-config-before-follow-link (current-window-configuration))
9573 (org-remove-occur-highlights nil nil t)
9574 (cond
9575 ((and (org-at-heading-p)
9576 (not (org-in-regexp
9577 (concat org-plain-link-re "\\|"
9578 org-bracket-link-regexp "\\|"
9579 org-angle-link-re "\\|"
9580 "[ \t]:[^ \t\n]+:[ \t]*$")))
9581 (not (get-text-property (point) 'org-linked-text)))
9582 (or (org-offer-links-in-entry arg)
9583 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
9584 ((run-hook-with-args-until-success 'org-open-at-point-functions))
9585 ((org-at-timestamp-p t) (org-follow-timestamp-link))
9586 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
9587 (not (org-in-regexp org-bracket-link-regexp)))
9588 (org-footnote-action))
9590 (let (type path link line search (pos (point)))
9591 (catch 'match
9592 (save-excursion
9593 (skip-chars-forward "^]\n\r")
9594 (when (org-in-regexp org-bracket-link-regexp 1)
9595 (setq link (org-extract-attributes
9596 (org-link-unescape (org-match-string-no-properties 1))))
9597 (while (string-match " *\n *" link)
9598 (setq link (replace-match " " t t link)))
9599 (setq link (org-link-expand-abbrev link))
9600 (cond
9601 ((or (file-name-absolute-p link)
9602 (string-match "^\\.\\.?/" link))
9603 (setq type "file" path link))
9604 ((string-match org-link-re-with-space3 link)
9605 (setq type (match-string 1 link) path (match-string 2 link)))
9606 (t (setq type "thisfile" path link)))
9607 (throw 'match t)))
9609 (when (get-text-property (point) 'org-linked-text)
9610 (setq type "thisfile"
9611 pos (if (get-text-property (1+ (point)) 'org-linked-text)
9612 (1+ (point)) (point))
9613 path (buffer-substring
9614 (or (previous-single-property-change pos 'org-linked-text)
9615 (point-min))
9616 (or (next-single-property-change pos 'org-linked-text)
9617 (point-max))))
9618 (throw 'match t))
9620 (save-excursion
9621 (when (or (org-in-regexp org-angle-link-re)
9622 (org-in-regexp org-plain-link-re))
9623 (setq type (match-string 1)
9624 path (org-link-unescape (match-string 2)))
9625 (throw 'match t)))
9626 (save-excursion
9627 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
9628 (setq type "tags"
9629 path (match-string 1))
9630 (while (string-match ":" path)
9631 (setq path (replace-match "+" t t path)))
9632 (throw 'match t)))
9633 (when (org-in-regexp "<\\([^><\n]+\\)>")
9634 (setq type "tree-match"
9635 path (match-string 1))
9636 (throw 'match t)))
9637 (unless path
9638 (error "No link found"))
9640 ;; switch back to reference buffer
9641 ;; needed when if called in a temporary buffer through
9642 ;; org-open-link-from-string
9643 (with-current-buffer (or reference-buffer (current-buffer))
9645 ;; Remove any trailing spaces in path
9646 (if (string-match " +\\'" path)
9647 (setq path (replace-match "" t t path)))
9648 (if (and org-link-translation-function
9649 (fboundp org-link-translation-function))
9650 ;; Check if we need to translate the link
9651 (let ((tmp (funcall org-link-translation-function type path)))
9652 (setq type (car tmp) path (cdr tmp))))
9654 (cond
9656 ((assoc type org-link-protocols)
9657 (funcall (nth 1 (assoc type org-link-protocols)) path))
9659 ((equal type "mailto")
9660 (let ((cmd (car org-link-mailto-program))
9661 (args (cdr org-link-mailto-program)) args1
9662 (address path) (subject "") a)
9663 (if (string-match "\\(.*\\)::\\(.*\\)" path)
9664 (setq address (match-string 1 path)
9665 subject (org-link-escape (match-string 2 path))))
9666 (while args
9667 (cond
9668 ((not (stringp (car args))) (push (pop args) args1))
9669 (t (setq a (pop args))
9670 (if (string-match "%a" a)
9671 (setq a (replace-match address t t a)))
9672 (if (string-match "%s" a)
9673 (setq a (replace-match subject t t a)))
9674 (push a args1))))
9675 (apply cmd (nreverse args1))))
9677 ((member type '("http" "https" "ftp" "news"))
9678 (browse-url (concat type ":" (if (org-string-match-p "[[:nonascii:] ]" path)
9679 (org-link-escape
9680 path org-link-escape-chars-browser)
9681 path))))
9683 ((string= type "doi")
9684 (browse-url (concat "http://dx.doi.org/" (if (org-string-match-p "[[:nonascii:] ]" path)
9685 (org-link-escape
9686 path org-link-escape-chars-browser)
9687 path))))
9689 ((member type '("message"))
9690 (browse-url (concat type ":" path)))
9692 ((string= type "tags")
9693 (org-tags-view arg path))
9695 ((string= type "tree-match")
9696 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
9698 ((string= type "file")
9699 (if (string-match "::\\([0-9]+\\)\\'" path)
9700 (setq line (string-to-number (match-string 1 path))
9701 path (substring path 0 (match-beginning 0)))
9702 (if (string-match "::\\(.+\\)\\'" path)
9703 (setq search (match-string 1 path)
9704 path (substring path 0 (match-beginning 0)))))
9705 (if (string-match "[*?{]" (file-name-nondirectory path))
9706 (dired path)
9707 (org-open-file path arg line search)))
9709 ((string= type "shell")
9710 (let ((cmd path))
9711 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
9712 (string-match org-confirm-shell-link-not-regexp cmd))
9713 (not org-confirm-shell-link-function)
9714 (funcall org-confirm-shell-link-function
9715 (format "Execute \"%s\" in shell? "
9716 (org-add-props cmd nil
9717 'face 'org-warning))))
9718 (progn
9719 (message "Executing %s" cmd)
9720 (shell-command cmd))
9721 (error "Abort"))))
9723 ((string= type "elisp")
9724 (let ((cmd path))
9725 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
9726 (string-match org-confirm-elisp-link-not-regexp cmd))
9727 (not org-confirm-elisp-link-function)
9728 (funcall org-confirm-elisp-link-function
9729 (format "Execute \"%s\" as elisp? "
9730 (org-add-props cmd nil
9731 'face 'org-warning))))
9732 (message "%s => %s" cmd
9733 (if (equal (string-to-char cmd) ?\()
9734 (eval (read cmd))
9735 (call-interactively (read cmd))))
9736 (error "Abort"))))
9738 ((and (string= type "thisfile")
9739 (run-hook-with-args-until-success
9740 'org-open-link-functions path)))
9742 ((string= type "thisfile")
9743 (if arg
9744 (switch-to-buffer-other-window
9745 (org-get-buffer-for-internal-link (current-buffer)))
9746 (org-mark-ring-push))
9747 (let ((cmd `(org-link-search
9748 ,path
9749 ,(cond ((equal arg '(4)) ''occur)
9750 ((equal arg '(16)) ''org-occur)
9751 (t nil))
9752 ,pos)))
9753 (condition-case nil (let ((org-link-search-inhibit-query t))
9754 (eval cmd))
9755 (error (progn (widen) (eval cmd))))))
9758 (browse-url-at-point)))))))
9759 (move-marker org-open-link-marker nil)
9760 (run-hook-with-args 'org-follow-link-hook)))
9762 (defun org-offer-links-in-entry (&optional nth zero)
9763 "Offer links in the current entry and follow the selected link.
9764 If there is only one link, follow it immediately as well.
9765 If NTH is an integer, immediately pick the NTH link found.
9766 If ZERO is a string, check also this string for a link, and if
9767 there is one, offer it as link number zero."
9768 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
9769 "\\(" org-angle-link-re "\\)\\|"
9770 "\\(" org-plain-link-re "\\)"))
9771 (cnt ?0)
9772 (in-emacs (if (integerp nth) nil nth))
9773 have-zero end links link c)
9774 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
9775 (push (match-string 0 zero) links)
9776 (setq cnt (1- cnt) have-zero t))
9777 (save-excursion
9778 (org-back-to-heading t)
9779 (setq end (save-excursion (outline-next-heading) (point)))
9780 (while (re-search-forward re end t)
9781 (push (match-string 0) links))
9782 (setq links (org-uniquify (reverse links))))
9784 (cond
9785 ((null links)
9786 (message "No links"))
9787 ((equal (length links) 1)
9788 (setq link (list (car links))))
9789 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
9790 (setq link (list (nth (if have-zero nth (1- nth)) links))))
9791 (t ; we have to select a link
9792 (save-excursion
9793 (save-window-excursion
9794 (delete-other-windows)
9795 (with-output-to-temp-buffer "*Select Link*"
9796 (mapc (lambda (l)
9797 (if (not (string-match org-bracket-link-regexp l))
9798 (princ (format "[%c] %s\n" (incf cnt)
9799 (org-remove-angle-brackets l)))
9800 (if (match-end 3)
9801 (princ (format "[%c] %s (%s)\n" (incf cnt)
9802 (match-string 3 l) (match-string 1 l)))
9803 (princ (format "[%c] %s\n" (incf cnt)
9804 (match-string 1 l))))))
9805 links))
9806 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
9807 (message "Select link to open, RET to open all:")
9808 (setq c (read-char-exclusive))
9809 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
9810 (when (equal c ?q) (error "Abort"))
9811 (if (equal c ?\C-m)
9812 (setq link links)
9813 (setq nth (- c ?0))
9814 (if have-zero (setq nth (1+ nth)))
9815 (unless (and (integerp nth) (>= (length links) nth))
9816 (error "Invalid link selection"))
9817 (setq link (list (nth (1- nth) links))))))
9818 (if link
9819 (let ((buf (current-buffer)))
9820 (dolist (l link)
9821 (org-open-link-from-string l in-emacs buf))
9823 nil)))
9825 ;; Add special file links that specify the way of opening
9827 (org-add-link-type "file+sys" 'org-open-file-with-system)
9828 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
9829 (defun org-open-file-with-system (path)
9830 "Open file at PATH using the system way of opening it."
9831 (org-open-file path 'system))
9832 (defun org-open-file-with-emacs (path)
9833 "Open file at PATH in Emacs."
9834 (org-open-file path 'emacs))
9835 (defun org-remove-file-link-modifiers ()
9836 "Remove the file link modifiers in `file+sys:' and `file+emacs:' links."
9837 (goto-char (point-min))
9838 (while (re-search-forward "\\<file\\+\\(sys\\|emacs\\):" nil t)
9839 (org-if-unprotected
9840 (replace-match "file:" t t))))
9841 (eval-after-load "org-exp"
9842 '(add-hook 'org-export-preprocess-before-normalizing-links-hook
9843 'org-remove-file-link-modifiers))
9845 ;;;; Time estimates
9847 (defun org-get-effort (&optional pom)
9848 "Get the effort estimate for the current entry."
9849 (org-entry-get pom org-effort-property))
9851 ;;; File search
9853 (defvar org-create-file-search-functions nil
9854 "List of functions to construct the right search string for a file link.
9855 These functions are called in turn with point at the location to
9856 which the link should point.
9858 A function in the hook should first test if it would like to
9859 handle this file type, for example by checking the `major-mode'
9860 or the file extension. If it decides not to handle this file, it
9861 should just return nil to give other functions a chance. If it
9862 does handle the file, it must return the search string to be used
9863 when following the link. The search string will be part of the
9864 file link, given after a double colon, and `org-open-at-point'
9865 will automatically search for it. If special measures must be
9866 taken to make the search successful, another function should be
9867 added to the companion hook `org-execute-file-search-functions',
9868 which see.
9870 A function in this hook may also use `setq' to set the variable
9871 `description' to provide a suggestion for the descriptive text to
9872 be used for this link when it gets inserted into an Org-mode
9873 buffer with \\[org-insert-link].")
9875 (defvar org-execute-file-search-functions nil
9876 "List of functions to execute a file search triggered by a link.
9878 Functions added to this hook must accept a single argument, the
9879 search string that was part of the file link, the part after the
9880 double colon. The function must first check if it would like to
9881 handle this search, for example by checking the `major-mode' or
9882 the file extension. If it decides not to handle this search, it
9883 should just return nil to give other functions a chance. If it
9884 does handle the search, it must return a non-nil value to keep
9885 other functions from trying.
9887 Each function can access the current prefix argument through the
9888 variable `current-prefix-argument'. Note that a single prefix is
9889 used to force opening a link in Emacs, so it may be good to only
9890 use a numeric or double prefix to guide the search function.
9892 In case this is needed, a function in this hook can also restore
9893 the window configuration before `org-open-at-point' was called using:
9895 (set-window-configuration org-window-config-before-follow-link)")
9897 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
9898 (defun org-link-search (s &optional type avoid-pos stealth)
9899 "Search for a link search option.
9900 If S is surrounded by forward slashes, it is interpreted as a
9901 regular expression. In org-mode files, this will create an `org-occur'
9902 sparse tree. In ordinary files, `occur' will be used to list matches.
9903 If the current buffer is in `dired-mode', grep will be used to search
9904 in all files. If AVOID-POS is given, ignore matches near that position.
9906 When optional argument STEALTH is non-nil, do not modify
9907 visibility around point, thus ignoring
9908 `org-show-hierarchy-above', `org-show-following-heading' and
9909 `org-show-siblings' variables."
9910 (let ((case-fold-search t)
9911 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
9912 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
9913 (append '(("") (" ") ("\t") ("\n"))
9914 org-emphasis-alist)
9915 "\\|") "\\)"))
9916 (pos (point))
9917 (pre nil) (post nil)
9918 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
9919 (cond
9920 ;; First check if there are any special search functions
9921 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
9922 ;; Now try the builtin stuff
9923 ((and (equal (string-to-char s0) ?#)
9924 (> (length s0) 1)
9925 (save-excursion
9926 (goto-char (point-min))
9927 (and
9928 (re-search-forward
9929 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
9930 (setq type 'dedicated
9931 pos (match-beginning 0))))
9932 ;; There is an exact target for this
9933 (goto-char pos)
9934 (org-back-to-heading t)))
9935 ((save-excursion
9936 (goto-char (point-min))
9937 (and
9938 (re-search-forward
9939 (concat "<<" (regexp-quote s0) ">>") nil t)
9940 (setq type 'dedicated
9941 pos (match-beginning 0))))
9942 ;; There is an exact target for this
9943 (goto-char pos))
9944 ((save-excursion
9945 (goto-char (point-min))
9946 (and
9947 (re-search-forward
9948 (format "^[ \t]*#\\+TARGET: %s" (regexp-quote s0)) nil t)
9949 (setq type 'dedicated pos (match-beginning 0))))
9950 ;; Found an invisible target.
9951 (goto-char pos))
9952 ((save-excursion
9953 (goto-char (point-min))
9954 (and
9955 (re-search-forward
9956 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
9957 (setq type 'dedicated pos (match-beginning 0))))
9958 ;; Found an element with a matching #+name affiliated keyword.
9959 (goto-char pos))
9960 ((and (string-match "^(\\(.*\\))$" s0)
9961 (save-excursion
9962 (goto-char (point-min))
9963 (and
9964 (re-search-forward
9965 (concat "[^[]" (regexp-quote
9966 (format org-coderef-label-format
9967 (match-string 1 s0))))
9968 nil t)
9969 (setq type 'dedicated
9970 pos (1+ (match-beginning 0))))))
9971 ;; There is a coderef target for this
9972 (goto-char pos))
9973 ((string-match "^/\\(.*\\)/$" s)
9974 ;; A regular expression
9975 (cond
9976 ((derived-mode-p 'org-mode)
9977 (org-occur (match-string 1 s)))
9978 ;;((eq major-mode 'dired-mode)
9979 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
9980 (t (org-do-occur (match-string 1 s)))))
9981 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
9982 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
9983 (goto-char (point-min))
9984 (cond
9985 ((let (case-fold-search)
9986 (re-search-forward (format org-complex-heading-regexp-format
9987 (regexp-quote s))
9988 nil t))
9989 ;; OK, found a match
9990 (setq type 'dedicated)
9991 (goto-char (match-beginning 0)))
9992 ((and (not org-link-search-inhibit-query)
9993 (eq org-link-search-must-match-exact-headline 'query-to-create)
9994 (y-or-n-p "No match - create this as a new heading? "))
9995 (goto-char (point-max))
9996 (or (bolp) (newline))
9997 (insert "* " s "\n")
9998 (beginning-of-line 0))
10000 (goto-char pos)
10001 (error "No match"))))
10003 ;; A normal search string
10004 (when (equal (string-to-char s) ?*)
10005 ;; Anchor on headlines, post may include tags.
10006 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10007 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10008 s (substring s 1)))
10009 (remove-text-properties
10010 0 (length s)
10011 '(face nil mouse-face nil keymap nil fontified nil) s)
10012 ;; Make a series of regular expressions to find a match
10013 (setq words (org-split-string s "[ \n\r\t]+")
10015 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10016 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10017 "\\)" markers)
10018 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
10019 re2a (concat "[ \t\r\n]" re2a_)
10020 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10021 re4 (concat "[^a-zA-Z_]" re4_)
10023 re1 (concat pre re2 post)
10024 re3 (concat pre (if pre re4_ re4) post)
10025 re5 (concat pre ".*" re4)
10026 re2 (concat pre re2)
10027 re2a (concat pre (if pre re2a_ re2a))
10028 re4 (concat pre (if pre re4_ re4))
10029 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10030 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10031 re5 "\\)"
10033 (cond
10034 ((eq type 'org-occur) (org-occur reall))
10035 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10036 (t (goto-char (point-min))
10037 (setq type 'fuzzy)
10038 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
10039 (org-search-not-self 1 re1 nil t)
10040 (org-search-not-self 1 re2 nil t)
10041 (org-search-not-self 1 re2a nil t)
10042 (org-search-not-self 1 re3 nil t)
10043 (org-search-not-self 1 re4 nil t)
10044 (org-search-not-self 1 re5 nil t)
10046 (goto-char (match-beginning 1))
10047 (goto-char pos)
10048 (error "No match"))))))
10049 (and (derived-mode-p 'org-mode)
10050 (not stealth)
10051 (org-show-context 'link-search))
10052 type))
10054 (defun org-search-not-self (group &rest args)
10055 "Execute `re-search-forward', but only accept matches that do not
10056 enclose the position of `org-open-link-marker'."
10057 (let ((m org-open-link-marker))
10058 (catch 'exit
10059 (while (apply 're-search-forward args)
10060 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10061 (goto-char (match-end group))
10062 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10063 (> (match-beginning 0) (marker-position m))
10064 (< (match-end 0) (marker-position m)))
10065 (save-match-data
10066 (or (not (org-in-regexp
10067 org-bracket-link-analytic-regexp 1))
10068 (not (match-end 4)) ; no description
10069 (and (<= (match-beginning 4) (point))
10070 (>= (match-end 4) (point))))))
10071 (throw 'exit (point))))))))
10073 (defun org-get-buffer-for-internal-link (buffer)
10074 "Return a buffer to be used for displaying the link target of internal links."
10075 (cond
10076 ((not org-display-internal-link-with-indirect-buffer)
10077 buffer)
10078 ((string-match "(Clone)$" (buffer-name buffer))
10079 (message "Buffer is already a clone, not making another one")
10080 ;; we also do not modify visibility in this case
10081 buffer)
10082 (t ; make a new indirect buffer for displaying the link
10083 (let* ((bn (buffer-name buffer))
10084 (ibn (concat bn "(Clone)"))
10085 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10086 (with-current-buffer ib (org-overview))
10087 ib))))
10089 (defun org-do-occur (regexp &optional cleanup)
10090 "Call the Emacs command `occur'.
10091 If CLEANUP is non-nil, remove the printout of the regular expression
10092 in the *Occur* buffer. This is useful if the regex is long and not useful
10093 to read."
10094 (occur regexp)
10095 (when cleanup
10096 (let ((cwin (selected-window)) win beg end)
10097 (when (setq win (get-buffer-window "*Occur*"))
10098 (select-window win))
10099 (goto-char (point-min))
10100 (when (re-search-forward "match[a-z]+" nil t)
10101 (setq beg (match-end 0))
10102 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10103 (setq end (1- (match-beginning 0)))))
10104 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10105 (goto-char (point-min))
10106 (select-window cwin))))
10108 ;;; The mark ring for links jumps
10110 (defvar org-mark-ring nil
10111 "Mark ring for positions before jumps in Org-mode.")
10112 (defvar org-mark-ring-last-goto nil
10113 "Last position in the mark ring used to go back.")
10114 ;; Fill and close the ring
10115 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10116 (loop for i from 1 to org-mark-ring-length do
10117 (push (make-marker) org-mark-ring))
10118 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10119 org-mark-ring)
10121 (defun org-mark-ring-push (&optional pos buffer)
10122 "Put the current position or POS into the mark ring and rotate it."
10123 (interactive)
10124 (setq pos (or pos (point)))
10125 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10126 (move-marker (car org-mark-ring)
10127 (or pos (point))
10128 (or buffer (current-buffer)))
10129 (message "%s"
10130 (substitute-command-keys
10131 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10133 (defun org-mark-ring-goto (&optional n)
10134 "Jump to the previous position in the mark ring.
10135 With prefix arg N, jump back that many stored positions. When
10136 called several times in succession, walk through the entire ring.
10137 Org-mode commands jumping to a different position in the current file,
10138 or to another Org-mode file, automatically push the old position
10139 onto the ring."
10140 (interactive "p")
10141 (let (p m)
10142 (if (eq last-command this-command)
10143 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10144 (setq p org-mark-ring))
10145 (setq org-mark-ring-last-goto p)
10146 (setq m (car p))
10147 (org-pop-to-buffer-same-window (marker-buffer m))
10148 (goto-char m)
10149 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10151 (defun org-remove-angle-brackets (s)
10152 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10153 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10155 (defun org-add-angle-brackets (s)
10156 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10157 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10159 (defun org-remove-double-quotes (s)
10160 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10161 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10164 ;;; Following specific links
10166 (defun org-follow-timestamp-link ()
10167 (cond
10168 ((org-at-date-range-p t)
10169 (let ((org-agenda-start-on-weekday)
10170 (t1 (match-string 1))
10171 (t2 (match-string 2)))
10172 (setq t1 (time-to-days (org-time-string-to-time t1))
10173 t2 (time-to-days (org-time-string-to-time t2)))
10174 (org-agenda-list nil t1 (1+ (- t2 t1)))))
10175 ((org-at-timestamp-p t)
10176 (org-agenda-list nil (time-to-days (org-time-string-to-time
10177 (substring (match-string 1) 0 10)))
10179 (t (error "This should not happen"))))
10182 ;;; Following file links
10183 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10184 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10185 (declare-function mailcap-mime-info
10186 "mailcap" (string &optional request no-decode))
10187 (defvar org-wait nil)
10188 (defun org-open-file (path &optional in-emacs line search)
10189 "Open the file at PATH.
10190 First, this expands any special file name abbreviations. Then the
10191 configuration variable `org-file-apps' is checked if it contains an
10192 entry for this file type, and if yes, the corresponding command is launched.
10194 If no application is found, Emacs simply visits the file.
10196 With optional prefix argument IN-EMACS, Emacs will visit the file.
10197 With a double \\[universal-argument] \\[universal-argument] \
10198 prefix arg, Org tries to avoid opening in Emacs
10199 and to use an external application to visit the file.
10201 Optional LINE specifies a line to go to, optional SEARCH a string
10202 to search for. If LINE or SEARCH is given, the file will be
10203 opened in Emacs, unless an entry from org-file-apps that makes
10204 use of groups in a regexp matches.
10206 If you want to change the way frames are used when following a
10207 link, please customize `org-link-frame-setup'.
10209 If the file does not exist, an error is thrown."
10210 (let* ((file (if (equal path "")
10211 buffer-file-name
10212 (substitute-in-file-name (expand-file-name path))))
10213 (file-apps (append org-file-apps (org-default-apps)))
10214 (apps (org-remove-if
10215 'org-file-apps-entry-match-against-dlink-p file-apps))
10216 (apps-dlink (org-remove-if-not
10217 'org-file-apps-entry-match-against-dlink-p file-apps))
10218 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10219 (dirp (if remp nil (file-directory-p file)))
10220 (file (if (and dirp org-open-directory-means-index-dot-org)
10221 (concat (file-name-as-directory file) "index.org")
10222 file))
10223 (a-m-a-p (assq 'auto-mode apps))
10224 (dfile (downcase file))
10225 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10226 (link (cond ((and (eq line nil)
10227 (eq search nil))
10228 file)
10229 (line
10230 (concat file "::" (number-to-string line)))
10231 (search
10232 (concat file "::" search))))
10233 (dlink (downcase link))
10234 (old-buffer (current-buffer))
10235 (old-pos (point))
10236 (old-mode major-mode)
10237 ext cmd link-match-data)
10238 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10239 (setq ext (match-string 1 dfile))
10240 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10241 (setq ext (match-string 1 dfile))))
10242 (cond
10243 ((member in-emacs '((16) system))
10244 (setq cmd (cdr (assoc 'system apps))))
10245 (in-emacs (setq cmd 'emacs))
10247 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10248 (and dirp (cdr (assoc 'directory apps)))
10249 ; first, try matching against apps-dlink
10250 ; if we get a match here, store the match data for later
10251 (let ((match (assoc-default dlink apps-dlink
10252 'string-match)))
10253 (if match
10254 (progn (setq link-match-data (match-data))
10255 match)
10256 (progn (setq in-emacs (or in-emacs line search))
10257 nil))) ; if we have no match in apps-dlink,
10258 ; always open the file in emacs if line or search
10259 ; is given (for backwards compatibility)
10260 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10261 'string-match)
10262 (cdr (assoc ext apps))
10263 (cdr (assoc t apps))))))
10264 (when (eq cmd 'system)
10265 (setq cmd (cdr (assoc 'system apps))))
10266 (when (eq cmd 'default)
10267 (setq cmd (cdr (assoc t apps))))
10268 (when (eq cmd 'mailcap)
10269 (require 'mailcap)
10270 (mailcap-parse-mailcaps)
10271 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10272 (command (mailcap-mime-info mime-type)))
10273 (if (stringp command)
10274 (setq cmd command)
10275 (setq cmd 'emacs))))
10276 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10277 (not (file-exists-p file))
10278 (not org-open-non-existing-files))
10279 (error "No such file: %s" file))
10280 (cond
10281 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10282 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10283 (while (string-match "['\"]%s['\"]" cmd)
10284 (setq cmd (replace-match "%s" t t cmd)))
10285 (while (string-match "%s" cmd)
10286 (setq cmd (replace-match
10287 (save-match-data
10288 (shell-quote-argument
10289 (convert-standard-filename file)))
10290 t t cmd)))
10292 ;; Replace "%1", "%2" etc. in command with group matches from regex
10293 (save-match-data
10294 (let ((match-index 1)
10295 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10296 (set-match-data link-match-data)
10297 (while (<= match-index number-of-groups)
10298 (let ((regex (concat "%" (number-to-string match-index)))
10299 (replace-with (match-string match-index dlink)))
10300 (while (string-match regex cmd)
10301 (setq cmd (replace-match replace-with t t cmd))))
10302 (setq match-index (+ match-index 1)))))
10304 (save-window-excursion
10305 (start-process-shell-command cmd nil cmd)
10306 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
10308 ((or (stringp cmd)
10309 (eq cmd 'emacs))
10310 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10311 (widen)
10312 (if line (org-goto-line line)
10313 (if search (org-link-search search))))
10314 ((consp cmd)
10315 (let ((file (convert-standard-filename file)))
10316 (save-match-data
10317 (set-match-data link-match-data)
10318 (eval cmd))))
10319 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10320 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
10321 (or (not (equal old-buffer (current-buffer)))
10322 (not (equal old-pos (point))))
10323 (org-mark-ring-push old-pos old-buffer))))
10325 (defun org-file-apps-entry-match-against-dlink-p (entry)
10326 "This function returns non-nil if `entry' uses a regular
10327 expression which should be matched against the whole link by
10328 org-open-file.
10330 It assumes that is the case when the entry uses a regular
10331 expression which has at least one grouping construct and the
10332 action is either a lisp form or a command string containing
10333 '%1', i.e. using at least one subexpression match as a
10334 parameter."
10335 (let ((selector (car entry))
10336 (action (cdr entry)))
10337 (if (stringp selector)
10338 (and (> (regexp-opt-depth selector) 0)
10339 (or (and (stringp action)
10340 (string-match "%[0-9]" action))
10341 (consp action)))
10342 nil)))
10344 (defun org-default-apps ()
10345 "Return the default applications for this operating system."
10346 (cond
10347 ((eq system-type 'darwin)
10348 org-file-apps-defaults-macosx)
10349 ((eq system-type 'windows-nt)
10350 org-file-apps-defaults-windowsnt)
10351 (t org-file-apps-defaults-gnu)))
10353 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10354 "Convert extensions to regular expressions in the cars of LIST.
10355 Also, weed out any non-string entries, because the return value is used
10356 only for regexp matching.
10357 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10358 point to the symbol `emacs', indicating that the file should
10359 be opened in Emacs."
10360 (append
10361 (delq nil
10362 (mapcar (lambda (x)
10363 (if (not (stringp (car x)))
10365 (if (string-match "\\W" (car x))
10367 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10368 list))
10369 (if add-auto-mode
10370 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10372 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10373 (defun org-file-remote-p (file)
10374 "Test whether FILE specifies a location on a remote system.
10375 Return non-nil if the location is indeed remote.
10377 For example, the filename \"/user@host:/foo\" specifies a location
10378 on the system \"/user@host:\"."
10379 (cond ((fboundp 'file-remote-p)
10380 (file-remote-p file))
10381 ((fboundp 'tramp-handle-file-remote-p)
10382 (tramp-handle-file-remote-p file))
10383 ((and (boundp 'ange-ftp-name-format)
10384 (string-match (car ange-ftp-name-format) file))
10386 (t nil)))
10389 ;;;; Refiling
10391 (defun org-get-org-file ()
10392 "Read a filename, with default directory `org-directory'."
10393 (let ((default (or org-default-notes-file remember-data-file)))
10394 (read-file-name (format "File name [%s]: " default)
10395 (file-name-as-directory org-directory)
10396 default)))
10398 (defun org-notes-order-reversed-p ()
10399 "Check if the current file should receive notes in reversed order."
10400 (cond
10401 ((not org-reverse-note-order) nil)
10402 ((eq t org-reverse-note-order) t)
10403 ((not (listp org-reverse-note-order)) nil)
10404 (t (catch 'exit
10405 (let ((all org-reverse-note-order)
10406 entry)
10407 (while (setq entry (pop all))
10408 (if (string-match (car entry) buffer-file-name)
10409 (throw 'exit (cdr entry))))
10410 nil)))))
10412 (defvar org-refile-target-table nil
10413 "The list of refile targets, created by `org-refile'.")
10415 (defvar org-agenda-new-buffers nil
10416 "Buffers created to visit agenda files.")
10418 (defvar org-refile-cache nil
10419 "Cache for refile targets.")
10421 (defvar org-refile-markers nil
10422 "All the markers used for caching refile locations.")
10424 (defun org-refile-marker (pos)
10425 "Get a new refile marker, but only if caching is in use."
10426 (if (not org-refile-use-cache)
10428 (let ((m (make-marker)))
10429 (move-marker m pos)
10430 (push m org-refile-markers)
10431 m)))
10433 (defun org-refile-cache-clear ()
10434 "Clear the refile cache and disable all the markers."
10435 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
10436 (setq org-refile-markers nil)
10437 (setq org-refile-cache nil)
10438 (message "Refile cache has been cleared"))
10440 (defun org-refile-cache-check-set (set)
10441 "Check if all the markers in the cache still have live buffers."
10442 (let (marker)
10443 (catch 'exit
10444 (while (and set (setq marker (nth 3 (pop set))))
10445 ;; if org-refile-use-outline-path is 'file, marker may be nil
10446 (when (and marker (null (marker-buffer marker)))
10447 (message "not found") (sit-for 3)
10448 (throw 'exit nil)))
10449 t)))
10451 (defun org-refile-cache-put (set &rest identifiers)
10452 "Push the refile targets SET into the cache, under IDENTIFIERS."
10453 (let* ((key (sha1 (prin1-to-string identifiers)))
10454 (entry (assoc key org-refile-cache)))
10455 (if entry
10456 (setcdr entry set)
10457 (push (cons key set) org-refile-cache))))
10459 (defun org-refile-cache-get (&rest identifiers)
10460 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10461 (cond
10462 ((not org-refile-cache) nil)
10463 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10465 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10466 org-refile-cache))))
10467 (and set (org-refile-cache-check-set set) set)))))
10469 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
10470 "Produce a table with refile targets."
10471 (let ((case-fold-search nil)
10472 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10473 (entries (or org-refile-targets '((nil . (:level . 1)))))
10474 targets tgs txt re files f desc descre fast-path-p level pos0)
10475 (message "Getting targets...")
10476 (with-current-buffer (or default-buffer (current-buffer))
10477 (while (setq entry (pop entries))
10478 (setq files (car entry) desc (cdr entry))
10479 (setq fast-path-p nil)
10480 (cond
10481 ((null files) (setq files (list (current-buffer))))
10482 ((eq files 'org-agenda-files)
10483 (setq files (org-agenda-files 'unrestricted)))
10484 ((and (symbolp files) (fboundp files))
10485 (setq files (funcall files)))
10486 ((and (symbolp files) (boundp files))
10487 (setq files (symbol-value files))))
10488 (if (stringp files) (setq files (list files)))
10489 (cond
10490 ((eq (car desc) :tag)
10491 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
10492 ((eq (car desc) :todo)
10493 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
10494 ((eq (car desc) :regexp)
10495 (setq descre (cdr desc)))
10496 ((eq (car desc) :level)
10497 (setq descre (concat "^\\*\\{" (number-to-string
10498 (if org-odd-levels-only
10499 (1- (* 2 (cdr desc)))
10500 (cdr desc)))
10501 "\\}[ \t]")))
10502 ((eq (car desc) :maxlevel)
10503 (setq fast-path-p t)
10504 (setq descre (concat "^\\*\\{1," (number-to-string
10505 (if org-odd-levels-only
10506 (1- (* 2 (cdr desc)))
10507 (cdr desc)))
10508 "\\}[ \t]")))
10509 (t (error "Bad refiling target description %s" desc)))
10510 (while (setq f (pop files))
10511 (with-current-buffer
10512 (if (bufferp f) f (org-get-agenda-file-buffer f))
10514 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
10515 (progn
10516 (if (bufferp f) (setq f (buffer-file-name
10517 (buffer-base-buffer f))))
10518 (setq f (and f (expand-file-name f)))
10519 (if (eq org-refile-use-outline-path 'file)
10520 (push (list (file-name-nondirectory f) f nil nil) tgs))
10521 (save-excursion
10522 (save-restriction
10523 (widen)
10524 (goto-char (point-min))
10525 (while (re-search-forward descre nil t)
10526 (goto-char (setq pos0 (point-at-bol)))
10527 (catch 'next
10528 (when org-refile-target-verify-function
10529 (save-match-data
10530 (or (funcall org-refile-target-verify-function)
10531 (throw 'next t))))
10532 (when (and (looking-at org-complex-heading-regexp)
10533 (not (member (match-string 4) excluded-entries))
10534 (match-string 4))
10535 (setq level (org-reduced-level
10536 (- (match-end 1) (match-beginning 1)))
10537 txt (org-link-display-format (match-string 4))
10538 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
10539 re (format org-complex-heading-regexp-format
10540 (regexp-quote (match-string 4))))
10541 (when org-refile-use-outline-path
10542 (setq txt (mapconcat
10543 'org-protect-slash
10544 (append
10545 (if (eq org-refile-use-outline-path
10546 'file)
10547 (list (file-name-nondirectory
10548 (buffer-file-name
10549 (buffer-base-buffer))))
10550 (if (eq org-refile-use-outline-path
10551 'full-file-path)
10552 (list (buffer-file-name
10553 (buffer-base-buffer)))))
10554 (org-get-outline-path fast-path-p
10555 level txt)
10556 (list txt))
10557 "/")))
10558 (push (list txt f re (org-refile-marker (point)))
10559 tgs)))
10560 (when (= (point) pos0)
10561 ;; verification function has not moved point
10562 (goto-char (point-at-eol))))))))
10563 (when org-refile-use-cache
10564 (org-refile-cache-put tgs (buffer-file-name) descre))
10565 (setq targets (append tgs targets))
10566 ))))
10567 (message "Getting targets...done")
10568 (nreverse targets)))
10570 (defun org-protect-slash (s)
10571 (while (string-match "/" s)
10572 (setq s (replace-match "\\" t t s)))
10575 (defvar org-olpa (make-vector 20 nil))
10577 (defun org-get-outline-path (&optional fastp level heading)
10578 "Return the outline path to the current entry, as a list.
10580 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
10581 routine which makes outline path derivations for an entire file,
10582 avoiding backtracing. Refile target collection makes use of that."
10583 (if fastp
10584 (progn
10585 (if (> level 19)
10586 (error "Outline path failure, more than 19 levels"))
10587 (loop for i from level upto 19 do
10588 (aset org-olpa i nil))
10589 (prog1
10590 (delq nil (append org-olpa nil))
10591 (aset org-olpa level heading)))
10592 (let (rtn case-fold-search)
10593 (save-excursion
10594 (save-restriction
10595 (widen)
10596 (while (org-up-heading-safe)
10597 (when (looking-at org-complex-heading-regexp)
10598 (push (org-match-string-no-properties 4) rtn)))
10599 rtn)))))
10601 (defun org-format-outline-path (path &optional width prefix)
10602 "Format the outline path PATH for display.
10603 Width is the maximum number of characters that is available.
10604 Prefix is a prefix to be included in the returned string,
10605 such as the file name."
10606 (setq width (or width 79))
10607 (if prefix (setq width (- width (length prefix))))
10608 (if (not path)
10609 (or prefix "")
10610 (let* ((nsteps (length path))
10611 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
10612 (maxwidth (if (<= total-width width)
10613 10000 ;; everything fits
10614 ;; we need to shorten the level headings
10615 (/ (- width nsteps) nsteps)))
10616 (org-odd-levels-only nil)
10617 (n 0)
10618 (total (1+ (length prefix))))
10619 (setq maxwidth (max maxwidth 10))
10620 (concat prefix
10621 (mapconcat
10622 (lambda (h)
10623 (setq n (1+ n))
10624 (if (and (= n nsteps) (< maxwidth 10000))
10625 (setq maxwidth (- total-width total)))
10626 (if (< (length h) maxwidth)
10627 (progn (setq total (+ total (length h) 1)) h)
10628 (setq h (substring h 0 (- maxwidth 2))
10629 total (+ total maxwidth 1))
10630 (if (string-match "[ \t]+\\'" h)
10631 (setq h (substring h 0 (match-beginning 0))))
10632 (setq h (concat h "..")))
10633 (org-add-props h nil 'face
10634 (nth (% (1- n) org-n-level-faces)
10635 org-level-faces))
10637 path "/")))))
10639 (defun org-display-outline-path (&optional file current)
10640 "Display the current outline path in the echo area."
10641 (interactive "P")
10642 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
10643 (case-fold-search nil)
10644 (path (and (derived-mode-p 'org-mode) (org-get-outline-path))))
10645 (if current (setq path (append path
10646 (save-excursion
10647 (org-back-to-heading t)
10648 (if (looking-at org-complex-heading-regexp)
10649 (list (match-string 4)))))))
10650 (message "%s"
10651 (org-format-outline-path
10652 path
10653 (1- (frame-width))
10654 (and file bfn (concat (file-name-nondirectory bfn) "/"))))))
10656 (defvar org-refile-history nil
10657 "History for refiling operations.")
10659 (defvar org-after-refile-insert-hook nil
10660 "Hook run after `org-refile' has inserted its stuff at the new location.
10661 Note that this is still *before* the stuff will be removed from
10662 the *old* location.")
10664 (defvar org-capture-last-stored-marker)
10665 (defun org-refile (&optional goto default-buffer rfloc)
10666 "Move the entry or entries at point to another heading.
10667 The list of target headings is compiled using the information in
10668 `org-refile-targets', which see.
10670 At the target location, the entry is filed as a subitem of the target
10671 heading. Depending on `org-reverse-note-order', the new subitem will
10672 either be the first or the last subitem.
10674 If there is an active region, all entries in that region will be moved.
10675 However, the region must fulfill the requirement that the first heading
10676 is the first one sets the top-level of the moved text - at most siblings
10677 below it are allowed.
10679 With prefix arg GOTO, the command will only visit the target location
10680 and not actually move anything.
10682 With a double prefix arg \\[universal-argument] \\[universal-argument], \
10683 go to the location where the last refiling operation has put the subtree.
10684 With a prefix argument of `2', refile to the running clock.
10686 RFLOC can be a refile location obtained in a different way.
10688 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
10690 If you are using target caching (see `org-refile-use-cache'),
10691 You have to clear the target cache in order to find new targets.
10692 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
10693 prefix argument (`C-u C-u C-u C-c C-w')."
10695 (interactive "P")
10696 (if (member goto '(0 (64)))
10697 (org-refile-cache-clear)
10698 (let* ((cbuf (current-buffer))
10699 (regionp (org-region-active-p))
10700 (region-start (and regionp (region-beginning)))
10701 (region-end (and regionp (region-end)))
10702 (region-length (and regionp (- region-end region-start)))
10703 (filename (buffer-file-name (buffer-base-buffer cbuf)))
10704 pos it nbuf file re level reversed)
10705 (setq last-command nil)
10706 (when regionp
10707 (goto-char region-start)
10708 (or (bolp) (goto-char (point-at-bol)))
10709 (setq region-start (point))
10710 (unless (or (org-kill-is-subtree-p
10711 (buffer-substring region-start region-end))
10712 (prog1 org-refile-active-region-within-subtree
10713 (org-toggle-heading)))
10714 (error "The region is not a (sequence of) subtree(s)")))
10715 (if (equal goto '(16))
10716 (org-refile-goto-last-stored)
10717 (when (or
10718 (and (equal goto 2)
10719 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
10720 (prog1
10721 (setq it (list (or org-clock-heading "running clock")
10722 (buffer-file-name
10723 (marker-buffer org-clock-hd-marker))
10725 (marker-position org-clock-hd-marker)))
10726 (setq goto nil)))
10727 (setq it (or rfloc
10728 (let (heading-text)
10729 (save-excursion
10730 (unless goto
10731 (org-back-to-heading t)
10732 (setq heading-text
10733 (nth 4 (org-heading-components))))
10734 (org-refile-get-location
10735 (cond (goto "Goto")
10736 (regionp "Refile region to")
10737 (t (concat "Refile subtree \""
10738 heading-text "\" to")))
10739 default-buffer
10740 (and (not (equal '(4) goto))
10741 org-refile-allow-creating-parent-nodes)
10742 goto))))))
10743 (setq file (nth 1 it)
10744 re (nth 2 it)
10745 pos (nth 3 it))
10746 (if (and (not goto)
10748 (equal (buffer-file-name) file)
10749 (if regionp
10750 (and (>= pos region-start)
10751 (<= pos region-end))
10752 (and (>= pos (point))
10753 (< pos (save-excursion
10754 (org-end-of-subtree t t))))))
10755 (error "Cannot refile to position inside the tree or region"))
10757 (setq nbuf (or (find-buffer-visiting file)
10758 (find-file-noselect file)))
10759 (if goto
10760 (progn
10761 (org-pop-to-buffer-same-window nbuf)
10762 (goto-char pos)
10763 (org-show-context 'org-goto))
10764 (if regionp
10765 (progn
10766 (org-kill-new (buffer-substring region-start region-end))
10767 (org-save-markers-in-region region-start region-end))
10768 (org-copy-subtree 1 nil t))
10769 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
10770 (find-file-noselect file)))
10771 (setq reversed (org-notes-order-reversed-p))
10772 (save-excursion
10773 (save-restriction
10774 (widen)
10775 (if pos
10776 (progn
10777 (goto-char pos)
10778 (looking-at org-outline-regexp)
10779 (setq level (org-get-valid-level (funcall outline-level) 1))
10780 (goto-char
10781 (if reversed
10782 (or (outline-next-heading) (point-max))
10783 (or (save-excursion (org-get-next-sibling))
10784 (org-end-of-subtree t t)
10785 (point-max)))))
10786 (setq level 1)
10787 (if (not reversed)
10788 (goto-char (point-max))
10789 (goto-char (point-min))
10790 (or (outline-next-heading) (goto-char (point-max)))))
10791 (if (not (bolp)) (newline))
10792 (org-paste-subtree level)
10793 (when org-log-refile
10794 (org-add-log-setup 'refile nil nil 'findpos
10795 org-log-refile)
10796 (unless (eq org-log-refile 'note)
10797 (save-excursion (org-add-log-note))))
10798 (and org-auto-align-tags (org-set-tags nil t))
10799 (bookmark-set "org-refile-last-stored")
10800 ;; If we are refiling for capture, make sure that the
10801 ;; last-capture pointers point here
10802 (when (org-bound-and-true-p org-refile-for-capture)
10803 (bookmark-set "org-capture-last-stored-marker")
10804 (move-marker org-capture-last-stored-marker (point)))
10805 (if (fboundp 'deactivate-mark) (deactivate-mark))
10806 (run-hooks 'org-after-refile-insert-hook))))
10807 (if regionp
10808 (delete-region (point) (+ (point) region-length))
10809 (org-cut-subtree))
10810 (when (featurep 'org-inlinetask)
10811 (org-inlinetask-remove-END-maybe))
10812 (setq org-markers-to-move nil)
10813 (message "Refiled to \"%s\" in file %s" (car it) file)))))))
10815 (defun org-refile-goto-last-stored ()
10816 "Go to the location where the last refile was stored."
10817 (interactive)
10818 (bookmark-jump "org-refile-last-stored")
10819 (message "This is the location of the last refile"))
10821 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
10822 no-exclude)
10823 "Prompt the user for a refile location, using PROMPT.
10824 PROMPT should not be suffixed with a colon and a space, because
10825 this function appends the default value from
10826 `org-refile-history' automatically, if that is not empty.
10827 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
10828 this is used for the GOTO interface."
10829 (let ((org-refile-targets org-refile-targets)
10830 (org-refile-use-outline-path org-refile-use-outline-path)
10831 excluded-entries)
10832 (when (and (derived-mode-p 'org-mode)
10833 (not org-refile-use-cache)
10834 (not no-exclude))
10835 (org-map-tree
10836 (lambda()
10837 (setq excluded-entries
10838 (append excluded-entries (list (org-get-heading t t)))))))
10839 (setq org-refile-target-table
10840 (org-refile-get-targets default-buffer excluded-entries)))
10841 (unless org-refile-target-table
10842 (error "No refile targets"))
10843 (let* ((prompt (concat prompt
10844 (and (car org-refile-history)
10845 (concat " (default " (car org-refile-history) ")"))
10846 ": "))
10847 (cbuf (current-buffer))
10848 (partial-completion-mode nil)
10849 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
10850 (cfunc (if (and org-refile-use-outline-path
10851 org-outline-path-complete-in-steps)
10852 'org-olpath-completing-read
10853 'org-icompleting-read))
10854 (extra (if org-refile-use-outline-path "/" ""))
10855 (filename (and cfn (expand-file-name cfn)))
10856 (tbl (mapcar
10857 (lambda (x)
10858 (if (and (not (member org-refile-use-outline-path
10859 '(file full-file-path)))
10860 (not (equal filename (nth 1 x))))
10861 (cons (concat (car x) extra " ("
10862 (file-name-nondirectory (nth 1 x)) ")")
10863 (cdr x))
10864 (cons (concat (car x) extra) (cdr x))))
10865 org-refile-target-table))
10866 (completion-ignore-case t)
10867 pa answ parent-target child parent old-hist)
10868 (setq old-hist org-refile-history)
10869 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
10870 nil 'org-refile-history (car org-refile-history)))
10871 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
10872 (org-refile-check-position pa)
10873 (if pa
10874 (progn
10875 (when (or (not org-refile-history)
10876 (not (eq old-hist org-refile-history))
10877 (not (equal (car pa) (car org-refile-history))))
10878 (setq org-refile-history
10879 (cons (car pa) (if (assoc (car org-refile-history) tbl)
10880 org-refile-history
10881 (cdr org-refile-history))))
10882 (if (equal (car org-refile-history) (nth 1 org-refile-history))
10883 (pop org-refile-history)))
10885 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
10886 (progn
10887 (setq parent (match-string 1 answ)
10888 child (match-string 2 answ))
10889 (setq parent-target (or (assoc parent tbl)
10890 (assoc (concat parent "/") tbl)))
10891 (when (and parent-target
10892 (or (eq new-nodes t)
10893 (and (eq new-nodes 'confirm)
10894 (y-or-n-p (format "Create new node \"%s\"? "
10895 child)))))
10896 (org-refile-new-child parent-target child)))
10897 (error "Invalid target location")))))
10899 (declare-function org-string-nw-p "org-macs.el" (s))
10900 (defun org-refile-check-position (refile-pointer)
10901 "Check if the refile pointer matches the readline to which it points."
10902 (let* ((file (nth 1 refile-pointer))
10903 (re (nth 2 refile-pointer))
10904 (pos (nth 3 refile-pointer))
10905 buffer)
10906 (when (org-string-nw-p re)
10907 (setq buffer (if (markerp pos)
10908 (marker-buffer pos)
10909 (or (find-buffer-visiting file)
10910 (find-file-noselect file))))
10911 (with-current-buffer buffer
10912 (save-excursion
10913 (save-restriction
10914 (widen)
10915 (goto-char pos)
10916 (beginning-of-line 1)
10917 (unless (org-looking-at-p re)
10918 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
10920 (defun org-refile-new-child (parent-target child)
10921 "Use refile target PARENT-TARGET to add new CHILD below it."
10922 (unless parent-target
10923 (error "Cannot find parent for new node"))
10924 (let ((file (nth 1 parent-target))
10925 (pos (nth 3 parent-target))
10926 level)
10927 (with-current-buffer (or (find-buffer-visiting file)
10928 (find-file-noselect file))
10929 (save-excursion
10930 (save-restriction
10931 (widen)
10932 (if pos
10933 (goto-char pos)
10934 (goto-char (point-max))
10935 (if (not (bolp)) (newline)))
10936 (when (looking-at org-outline-regexp)
10937 (setq level (funcall outline-level))
10938 (org-end-of-subtree t t))
10939 (org-back-over-empty-lines)
10940 (insert "\n" (make-string
10941 (if pos (org-get-valid-level level 1) 1) ?*)
10942 " " child "\n")
10943 (beginning-of-line 0)
10944 (list (concat (car parent-target) "/" child) file "" (point)))))))
10946 (defun org-olpath-completing-read (prompt collection &rest args)
10947 "Read an outline path like a file name."
10948 (let ((thetable collection)
10949 (org-completion-use-ido nil) ; does not work with ido.
10950 (org-completion-use-iswitchb nil)) ; or iswitchb
10951 (apply
10952 'org-icompleting-read prompt
10953 (lambda (string predicate &optional flag)
10954 (let (rtn r f (l (length string)))
10955 (cond
10956 ((eq flag nil)
10957 ;; try completion
10958 (try-completion string thetable))
10959 ((eq flag t)
10960 ;; all-completions
10961 (setq rtn (all-completions string thetable predicate))
10962 (mapcar
10963 (lambda (x)
10964 (setq r (substring x l))
10965 (if (string-match " ([^)]*)$" x)
10966 (setq f (match-string 0 x))
10967 (setq f ""))
10968 (if (string-match "/" r)
10969 (concat string (substring r 0 (match-end 0)) f)
10971 rtn))
10972 ((eq flag 'lambda)
10973 ;; exact match?
10974 (assoc string thetable)))
10976 args)))
10978 ;;;; Dynamic blocks
10980 (defun org-find-dblock (name)
10981 "Find the first dynamic block with name NAME in the buffer.
10982 If not found, stay at current position and return nil."
10983 (let (pos)
10984 (save-excursion
10985 (goto-char (point-min))
10986 (setq pos (and (re-search-forward (concat "^[ \t]*#\\+BEGIN:[ \t]+" name "\\>")
10987 nil t)
10988 (match-beginning 0))))
10989 (if pos (goto-char pos))
10990 pos))
10992 (defconst org-dblock-start-re
10993 "^[ \t]*#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
10994 "Matches the start line of a dynamic block, with parameters.")
10996 (defconst org-dblock-end-re "^[ \t]*#\\+END\\([: \t\r\n]\\|$\\)"
10997 "Matches the end of a dynamic block.")
10999 (defun org-create-dblock (plist)
11000 "Create a dynamic block section, with parameters taken from PLIST.
11001 PLIST must contain a :name entry which is used as name of the block."
11002 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11003 (end-of-line 1)
11004 (newline))
11005 (let ((col (current-column))
11006 (name (plist-get plist :name)))
11007 (insert "#+BEGIN: " name)
11008 (while plist
11009 (if (eq (car plist) :name)
11010 (setq plist (cddr plist))
11011 (insert " " (prin1-to-string (pop plist)))))
11012 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11013 (beginning-of-line -2)))
11015 (defun org-prepare-dblock ()
11016 "Prepare dynamic block for refresh.
11017 This empties the block, puts the cursor at the insert position and returns
11018 the property list including an extra property :name with the block name."
11019 (unless (looking-at org-dblock-start-re)
11020 (error "Not at a dynamic block"))
11021 (let* ((begdel (1+ (match-end 0)))
11022 (name (org-no-properties (match-string 1)))
11023 (params (append (list :name name)
11024 (read (concat "(" (match-string 3) ")")))))
11025 (save-excursion
11026 (beginning-of-line 1)
11027 (skip-chars-forward " \t")
11028 (setq params (plist-put params :indentation-column (current-column))))
11029 (unless (re-search-forward org-dblock-end-re nil t)
11030 (error "Dynamic block not terminated"))
11031 (setq params
11032 (append params
11033 (list :content (buffer-substring
11034 begdel (match-beginning 0)))))
11035 (delete-region begdel (match-beginning 0))
11036 (goto-char begdel)
11037 (open-line 1)
11038 params))
11040 (defun org-map-dblocks (&optional command)
11041 "Apply COMMAND to all dynamic blocks in the current buffer.
11042 If COMMAND is not given, use `org-update-dblock'."
11043 (let ((cmd (or command 'org-update-dblock)))
11044 (save-excursion
11045 (goto-char (point-min))
11046 (while (re-search-forward org-dblock-start-re nil t)
11047 (goto-char (match-beginning 0))
11048 (save-excursion
11049 (condition-case nil
11050 (funcall cmd)
11051 (error (message "Error during update of dynamic block"))))
11052 (unless (re-search-forward org-dblock-end-re nil t)
11053 (error "Dynamic block not terminated"))))))
11055 (defun org-dblock-update (&optional arg)
11056 "User command for updating dynamic blocks.
11057 Update the dynamic block at point. With prefix ARG, update all dynamic
11058 blocks in the buffer."
11059 (interactive "P")
11060 (if arg
11061 (org-update-all-dblocks)
11062 (or (looking-at org-dblock-start-re)
11063 (org-beginning-of-dblock))
11064 (org-update-dblock)))
11066 (defun org-update-dblock ()
11067 "Update the dynamic block at point.
11068 This means to empty the block, parse for parameters and then call
11069 the correct writing function."
11070 (interactive)
11071 (save-window-excursion
11072 (let* ((pos (point))
11073 (line (org-current-line))
11074 (params (org-prepare-dblock))
11075 (name (plist-get params :name))
11076 (indent (plist-get params :indentation-column))
11077 (cmd (intern (concat "org-dblock-write:" name))))
11078 (message "Updating dynamic block `%s' at line %d..." name line)
11079 (funcall cmd params)
11080 (message "Updating dynamic block `%s' at line %d...done" name line)
11081 (goto-char pos)
11082 (when (and indent (> indent 0))
11083 (setq indent (make-string indent ?\ ))
11084 (save-excursion
11085 (org-beginning-of-dblock)
11086 (forward-line 1)
11087 (while (not (looking-at org-dblock-end-re))
11088 (insert indent)
11089 (beginning-of-line 2))
11090 (when (looking-at org-dblock-end-re)
11091 (and (looking-at "[ \t]+")
11092 (replace-match ""))
11093 (insert indent)))))))
11095 (defun org-beginning-of-dblock ()
11096 "Find the beginning of the dynamic block at point.
11097 Error if there is no such block at point."
11098 (let ((pos (point))
11099 beg)
11100 (end-of-line 1)
11101 (if (and (re-search-backward org-dblock-start-re nil t)
11102 (setq beg (match-beginning 0))
11103 (re-search-forward org-dblock-end-re nil t)
11104 (> (match-end 0) pos))
11105 (goto-char beg)
11106 (goto-char pos)
11107 (error "Not in a dynamic block"))))
11109 ;;;###autoload
11110 (defun org-update-all-dblocks ()
11111 "Update all dynamic blocks in the buffer.
11112 This function can be used in a hook."
11113 (interactive)
11114 (when (derived-mode-p 'org-mode)
11115 (org-map-dblocks 'org-update-dblock)))
11118 ;;;; Completion
11120 (defconst org-additional-option-like-keywords
11121 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML:"
11122 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook:"
11123 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"
11124 "LATEX_CLASS:" "LATEX_CLASS_OPTIONS:" "ATTR_LaTeX:"
11125 "BEGIN:" "END:"
11126 "ORGTBL" "TBLFM:" "TBLNAME:"
11127 "BEGIN_EXAMPLE" "END_EXAMPLE"
11128 "BEGIN_QUOTE" "END_QUOTE"
11129 "BEGIN_VERSE" "END_VERSE"
11130 "BEGIN_CENTER" "END_CENTER"
11131 "BEGIN_SRC" "END_SRC"
11132 "BEGIN_RESULT" "END_RESULT"
11133 "NAME:" "RESULTS:"
11134 "HEADER:" "HEADERS:"
11135 "CATEGORY:" "COLUMNS:" "PROPERTY:"
11136 "CAPTION:" "LABEL:"
11137 "SETUPFILE:"
11138 "INCLUDE:"
11139 "BIND:"
11140 "MACRO:"))
11142 (defcustom org-structure-template-alist
11144 ("s" "#+BEGIN_SRC ?\n\n#+END_SRC"
11145 "<src lang=\"?\">\n\n</src>")
11146 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE"
11147 "<example>\n?\n</example>")
11148 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE"
11149 "<quote>\n?\n</quote>")
11150 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE"
11151 "<verse>\n?\n</verse>")
11152 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER"
11153 "<center>\n?\n</center>")
11154 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11155 "<literal style=\"latex\">\n?\n</literal>")
11156 ("L" "#+LaTeX: "
11157 "<literal style=\"latex\">?</literal>")
11158 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
11159 "<literal style=\"html\">\n?\n</literal>")
11160 ("H" "#+HTML: "
11161 "<literal style=\"html\">?</literal>")
11162 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
11163 ("A" "#+ASCII: ")
11164 ("i" "#+INDEX: ?"
11165 "#+INDEX: ?")
11166 ("I" "#+INCLUDE %file ?"
11167 "<include file=%file markup=\"?\">")
11169 "Structure completion elements.
11170 This is a list of abbreviation keys and values. The value gets inserted
11171 if you type `<' followed by the key and then press the completion key,
11172 usually `M-TAB'. %file will be replaced by a file name after prompting
11173 for the file using completion. The cursor will be placed at the position
11174 of the `?` in the template.
11175 There are two templates for each key, the first uses the original Org syntax,
11176 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11177 the default when the /org-mtags.el/ module has been loaded. See also the
11178 variable `org-mtags-prefer-muse-templates'."
11179 :group 'org-completion
11180 :type '(repeat
11181 (string :tag "Key")
11182 (string :tag "Template")
11183 (string :tag "Muse Template")))
11185 (defun org-try-structure-completion ()
11186 "Try to complete a structure template before point.
11187 This looks for strings like \"<e\" on an otherwise empty line and
11188 expands them."
11189 (let ((l (buffer-substring (point-at-bol) (point)))
11191 (when (and (looking-at "[ \t]*$")
11192 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
11193 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
11194 (org-complete-expand-structure-template (+ -1 (point-at-bol)
11195 (match-beginning 1)) a)
11196 t)))
11198 (defun org-complete-expand-structure-template (start cell)
11199 "Expand a structure template."
11200 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
11201 (rpl (nth (if musep 2 1) cell))
11202 (ind ""))
11203 (delete-region start (point))
11204 (when (string-match "\\`#\\+" rpl)
11205 (cond
11206 ((bolp))
11207 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
11208 (setq ind (buffer-substring (point-at-bol) (point))))
11209 (t (newline))))
11210 (setq start (point))
11211 (if (string-match "%file" rpl)
11212 (setq rpl (replace-match
11213 (concat
11214 "\""
11215 (save-match-data
11216 (abbreviate-file-name (read-file-name "Include file: ")))
11217 "\"")
11218 t t rpl)))
11219 (setq rpl (mapconcat 'identity (split-string rpl "\n")
11220 (concat "\n" ind)))
11221 (insert rpl)
11222 (if (re-search-backward "\\?" start t) (delete-char 1))))
11224 ;;;; TODO, DEADLINE, Comments
11226 (defun org-toggle-comment ()
11227 "Change the COMMENT state of an entry."
11228 (interactive)
11229 (save-excursion
11230 (org-back-to-heading)
11231 (let (case-fold-search)
11232 (cond
11233 ((looking-at (format org-heading-keyword-regexp-format
11234 org-comment-string))
11235 (goto-char (match-end 1))
11236 (looking-at (concat " +" org-comment-string))
11237 (replace-match "" t t)
11238 (when (eolp) (insert " ")))
11239 ((looking-at org-outline-regexp)
11240 (goto-char (match-end 0))
11241 (insert org-comment-string " "))))))
11243 (defvar org-last-todo-state-is-todo nil
11244 "This is non-nil when the last TODO state change led to a TODO state.
11245 If the last change removed the TODO tag or switched to DONE, then
11246 this is nil.")
11248 (defvar org-setting-tags nil) ; dynamically skipped
11250 (defvar org-todo-setup-filter-hook nil
11251 "Hook for functions that pre-filter todo specs.
11252 Each function takes a todo spec and returns either nil or the spec
11253 transformed into canonical form." )
11255 (defvar org-todo-get-default-hook nil
11256 "Hook for functions that get a default item for todo.
11257 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11258 nil or a string to be used for the todo mark." )
11260 (defvar org-agenda-headline-snapshot-before-repeat)
11262 (defun org-current-effective-time ()
11263 "Return current time adjusted for `org-extend-today-until' variable"
11264 (let* ((ct (org-current-time))
11265 (dct (decode-time ct))
11266 (ct1
11267 (if (and org-use-effective-time
11268 (< (nth 2 dct) org-extend-today-until))
11269 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct))
11270 ct)))
11271 ct1))
11273 (defun org-todo-yesterday (&optional arg)
11274 "Like `org-todo' but the time of change will be 23:59 of yesterday."
11275 (interactive "P")
11276 (if (eq major-mode 'org-agenda-mode)
11277 (apply 'org-agenda-todo-yesterday arg)
11278 (let* ((hour (third (decode-time
11279 (org-current-time))))
11280 (org-extend-today-until (1+ hour)))
11281 (org-todo arg))))
11283 (defun org-todo (&optional arg)
11284 "Change the TODO state of an item.
11285 The state of an item is given by a keyword at the start of the heading,
11286 like
11287 *** TODO Write paper
11288 *** DONE Call mom
11290 The different keywords are specified in the variable `org-todo-keywords'.
11291 By default the available states are \"TODO\" and \"DONE\".
11292 So for this example: when the item starts with TODO, it is changed to DONE.
11293 When it starts with DONE, the DONE is removed. And when neither TODO nor
11294 DONE are present, add TODO at the beginning of the heading.
11296 With \\[universal-argument] prefix arg, use completion to determine the new \
11297 state.
11298 With numeric prefix arg, switch to that state.
11299 With a double \\[universal-argument] prefix, switch to the next set of TODO \
11300 keywords (nextset).
11301 With a triple \\[universal-argument] prefix, circumvent any state blocking.
11302 With a numeric prefix arg of 0, inhibit note taking for the change.
11304 For calling through lisp, arg is also interpreted in the following way:
11305 'none -> empty state
11306 \"\"(empty string) -> switch to empty state
11307 'done -> switch to DONE
11308 'nextset -> switch to the next set of keywords
11309 'previousset -> switch to the previous set of keywords
11310 \"WAITING\" -> switch to the specified keyword, but only if it
11311 really is a member of `org-todo-keywords'."
11312 (interactive "P")
11313 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11314 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
11315 'region-start-level 'region))
11316 org-loop-over-headlines-in-active-region)
11317 (org-map-entries
11318 `(org-todo ,arg)
11319 org-loop-over-headlines-in-active-region
11320 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
11321 (if (equal arg '(16)) (setq arg 'nextset))
11322 (let ((org-blocker-hook org-blocker-hook)
11323 (case-fold-search nil))
11324 (when (equal arg '(64))
11325 (setq arg nil org-blocker-hook nil))
11326 (when (and org-blocker-hook
11327 (or org-inhibit-blocking
11328 (org-entry-get nil "NOBLOCKING")))
11329 (setq org-blocker-hook nil))
11330 (save-excursion
11331 (catch 'exit
11332 (org-back-to-heading t)
11333 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
11334 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
11335 (looking-at "\\(?: *\\|[ \t]*$\\)"))
11336 (let* ((match-data (match-data))
11337 (startpos (point-at-bol))
11338 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
11339 (org-log-done org-log-done)
11340 (org-log-repeat org-log-repeat)
11341 (org-todo-log-states org-todo-log-states)
11342 (org-inhibit-logging
11343 (if (equal arg 0)
11344 (progn (setq arg nil) 'note) org-inhibit-logging))
11345 (this (match-string 1))
11346 (hl-pos (match-beginning 0))
11347 (head (org-get-todo-sequence-head this))
11348 (ass (assoc head org-todo-kwd-alist))
11349 (interpret (nth 1 ass))
11350 (done-word (nth 3 ass))
11351 (final-done-word (nth 4 ass))
11352 (org-last-state (or this ""))
11353 (completion-ignore-case t)
11354 (member (member this org-todo-keywords-1))
11355 (tail (cdr member))
11356 (org-state (cond
11357 ((and org-todo-key-trigger
11358 (or (and (equal arg '(4))
11359 (eq org-use-fast-todo-selection 'prefix))
11360 (and (not arg) org-use-fast-todo-selection
11361 (not (eq org-use-fast-todo-selection
11362 'prefix)))))
11363 ;; Use fast selection
11364 (org-fast-todo-selection))
11365 ((and (equal arg '(4))
11366 (or (not org-use-fast-todo-selection)
11367 (not org-todo-key-trigger)))
11368 ;; Read a state with completion
11369 (org-icompleting-read
11370 "State: " (mapcar (lambda(x) (list x))
11371 org-todo-keywords-1)
11372 nil t))
11373 ((eq arg 'right)
11374 (if this
11375 (if tail (car tail) nil)
11376 (car org-todo-keywords-1)))
11377 ((eq arg 'left)
11378 (if (equal member org-todo-keywords-1)
11380 (if this
11381 (nth (- (length org-todo-keywords-1)
11382 (length tail) 2)
11383 org-todo-keywords-1)
11384 (org-last org-todo-keywords-1))))
11385 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
11386 (setq arg nil))) ; hack to fall back to cycling
11387 (arg
11388 ;; user or caller requests a specific state
11389 (cond
11390 ((equal arg "") nil)
11391 ((eq arg 'none) nil)
11392 ((eq arg 'done) (or done-word (car org-done-keywords)))
11393 ((eq arg 'nextset)
11394 (or (car (cdr (member head org-todo-heads)))
11395 (car org-todo-heads)))
11396 ((eq arg 'previousset)
11397 (let ((org-todo-heads (reverse org-todo-heads)))
11398 (or (car (cdr (member head org-todo-heads)))
11399 (car org-todo-heads))))
11400 ((car (member arg org-todo-keywords-1)))
11401 ((stringp arg)
11402 (error "State `%s' not valid in this file" arg))
11403 ((nth (1- (prefix-numeric-value arg))
11404 org-todo-keywords-1))))
11405 ((null member) (or head (car org-todo-keywords-1)))
11406 ((equal this final-done-word) nil) ;; -> make empty
11407 ((null tail) nil) ;; -> first entry
11408 ((memq interpret '(type priority))
11409 (if (eq this-command last-command)
11410 (car tail)
11411 (if (> (length tail) 0)
11412 (or done-word (car org-done-keywords))
11413 nil)))
11415 (car tail))))
11416 (org-state (or
11417 (run-hook-with-args-until-success
11418 'org-todo-get-default-hook org-state org-last-state)
11419 org-state))
11420 (next (if org-state (concat " " org-state " ") " "))
11421 (change-plist (list :type 'todo-state-change :from this :to org-state
11422 :position startpos))
11423 dolog now-done-p)
11424 (when org-blocker-hook
11425 (setq org-last-todo-state-is-todo
11426 (not (member this org-done-keywords)))
11427 (unless (save-excursion
11428 (save-match-data
11429 (org-with-wide-buffer
11430 (run-hook-with-args-until-failure
11431 'org-blocker-hook change-plist))))
11432 (if (org-called-interactively-p 'interactive)
11433 (error "TODO state change from %s to %s blocked" this org-state)
11434 ;; fail silently
11435 (message "TODO state change from %s to %s blocked" this org-state)
11436 (throw 'exit nil))))
11437 (store-match-data match-data)
11438 (replace-match next t t)
11439 (unless (pos-visible-in-window-p hl-pos)
11440 (message "TODO state changed to %s" (org-trim next)))
11441 (unless head
11442 (setq head (org-get-todo-sequence-head org-state)
11443 ass (assoc head org-todo-kwd-alist)
11444 interpret (nth 1 ass)
11445 done-word (nth 3 ass)
11446 final-done-word (nth 4 ass)))
11447 (when (memq arg '(nextset previousset))
11448 (message "Keyword-Set %d/%d: %s"
11449 (- (length org-todo-sets) -1
11450 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
11451 (length org-todo-sets)
11452 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
11453 (setq org-last-todo-state-is-todo
11454 (not (member org-state org-done-keywords)))
11455 (setq now-done-p (and (member org-state org-done-keywords)
11456 (not (member this org-done-keywords))))
11457 (and logging (org-local-logging logging))
11458 (when (and (or org-todo-log-states org-log-done)
11459 (not (eq org-inhibit-logging t))
11460 (not (memq arg '(nextset previousset))))
11461 ;; we need to look at recording a time and note
11462 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
11463 (nth 2 (assoc this org-todo-log-states))))
11464 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
11465 (setq dolog 'time))
11466 (when (and org-state
11467 (member org-state org-not-done-keywords)
11468 (not (member this org-not-done-keywords)))
11469 ;; This is now a todo state and was not one before
11470 ;; If there was a CLOSED time stamp, get rid of it.
11471 (org-add-planning-info nil nil 'closed))
11472 (when (and now-done-p org-log-done)
11473 ;; It is now done, and it was not done before
11474 (org-add-planning-info 'closed (org-current-effective-time))
11475 (if (and (not dolog) (eq 'note org-log-done))
11476 (org-add-log-setup 'done org-state this 'findpos 'note)))
11477 (when (and org-state dolog)
11478 ;; This is a non-nil state, and we need to log it
11479 (org-add-log-setup 'state org-state this 'findpos dolog)))
11480 ;; Fixup tag positioning
11481 (org-todo-trigger-tag-changes org-state)
11482 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
11483 (when org-provide-todo-statistics
11484 (org-update-parent-todo-statistics))
11485 (run-hooks 'org-after-todo-state-change-hook)
11486 (if (and arg (not (member org-state org-done-keywords)))
11487 (setq head (org-get-todo-sequence-head org-state)))
11488 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
11489 ;; Do we need to trigger a repeat?
11490 (when now-done-p
11491 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
11492 ;; This is for the agenda, take a snapshot of the headline.
11493 (save-match-data
11494 (setq org-agenda-headline-snapshot-before-repeat
11495 (org-get-heading))))
11496 (org-auto-repeat-maybe org-state))
11497 ;; Fixup cursor location if close to the keyword
11498 (if (and (outline-on-heading-p)
11499 (not (bolp))
11500 (save-excursion (beginning-of-line 1)
11501 (looking-at org-todo-line-regexp))
11502 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
11503 (progn
11504 (goto-char (or (match-end 2) (match-end 1)))
11505 (and (looking-at " ") (just-one-space))))
11506 (when org-trigger-hook
11507 (save-excursion
11508 (run-hook-with-args 'org-trigger-hook change-plist)))))))))
11510 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
11511 "Block turning an entry into a TODO, using the hierarchy.
11512 This checks whether the current task should be blocked from state
11513 changes. Such blocking occurs when:
11515 1. The task has children which are not all in a completed state.
11517 2. A task has a parent with the property :ORDERED:, and there
11518 are siblings prior to the current task with incomplete
11519 status.
11521 3. The parent of the task is blocked because it has siblings that should
11522 be done first, or is child of a block grandparent TODO entry."
11524 (if (not org-enforce-todo-dependencies)
11525 t ; if locally turned off don't block
11526 (catch 'dont-block
11527 ;; If this is not a todo state change, or if this entry is already DONE,
11528 ;; do not block
11529 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11530 (member (plist-get change-plist :from)
11531 (cons 'done org-done-keywords))
11532 (member (plist-get change-plist :to)
11533 (cons 'todo org-not-done-keywords))
11534 (not (plist-get change-plist :to)))
11535 (throw 'dont-block t))
11536 ;; If this task has children, and any are undone, it's blocked
11537 (save-excursion
11538 (org-back-to-heading t)
11539 (let ((this-level (funcall outline-level)))
11540 (outline-next-heading)
11541 (let ((child-level (funcall outline-level)))
11542 (while (and (not (eobp))
11543 (> child-level this-level))
11544 ;; this todo has children, check whether they are all
11545 ;; completed
11546 (if (and (not (org-entry-is-done-p))
11547 (org-entry-is-todo-p))
11548 (throw 'dont-block nil))
11549 (outline-next-heading)
11550 (setq child-level (funcall outline-level))))))
11551 ;; Otherwise, if the task's parent has the :ORDERED: property, and
11552 ;; any previous siblings are undone, it's blocked
11553 (save-excursion
11554 (org-back-to-heading t)
11555 (let* ((pos (point))
11556 (parent-pos (and (org-up-heading-safe) (point))))
11557 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11558 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11559 (forward-line 1)
11560 (re-search-forward org-not-done-heading-regexp pos t))
11561 (throw 'dont-block nil)) ; block, there is an older sibling not done.
11562 ;; Search further up the hierarchy, to see if an ancestor is blocked
11563 (while t
11564 (goto-char parent-pos)
11565 (if (not (looking-at org-not-done-heading-regexp))
11566 (throw 'dont-block t)) ; do not block, parent is not a TODO
11567 (setq pos (point))
11568 (setq parent-pos (and (org-up-heading-safe) (point)))
11569 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11570 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11571 (forward-line 1)
11572 (re-search-forward org-not-done-heading-regexp pos t))
11573 (throw 'dont-block nil)))))))) ; block, older sibling not done.
11575 (defcustom org-track-ordered-property-with-tag nil
11576 "Should the ORDERED property also be shown as a tag?
11577 The ORDERED property decides if an entry should require subtasks to be
11578 completed in sequence. Since a property is not very visible, setting
11579 this option means that toggling the ORDERED property with the command
11580 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
11581 not relevant for the behavior, but it makes things more visible.
11583 Note that toggling the tag with tags commands will not change the property
11584 and therefore not influence behavior!
11586 This can be t, meaning the tag ORDERED should be used, It can also be a
11587 string to select a different tag for this task."
11588 :group 'org-todo
11589 :type '(choice
11590 (const :tag "No tracking" nil)
11591 (const :tag "Track with ORDERED tag" t)
11592 (string :tag "Use other tag")))
11594 (defun org-toggle-ordered-property ()
11595 "Toggle the ORDERED property of the current entry.
11596 For better visibility, you can track the value of this property with a tag.
11597 See variable `org-track-ordered-property-with-tag'."
11598 (interactive)
11599 (let* ((t1 org-track-ordered-property-with-tag)
11600 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
11601 (save-excursion
11602 (org-back-to-heading)
11603 (if (org-entry-get nil "ORDERED")
11604 (progn
11605 (org-delete-property "ORDERED")
11606 (and tag (org-toggle-tag tag 'off))
11607 (message "Subtasks can be completed in arbitrary order"))
11608 (org-entry-put nil "ORDERED" "t")
11609 (and tag (org-toggle-tag tag 'on))
11610 (message "Subtasks must be completed in sequence")))))
11612 (defvar org-blocked-by-checkboxes) ; dynamically scoped
11613 (defun org-block-todo-from-checkboxes (change-plist)
11614 "Block turning an entry into a TODO, using checkboxes.
11615 This checks whether the current task should be blocked from state
11616 changes because there are unchecked boxes in this entry."
11617 (if (not org-enforce-todo-checkbox-dependencies)
11618 t ; if locally turned off don't block
11619 (catch 'dont-block
11620 ;; If this is not a todo state change, or if this entry is already DONE,
11621 ;; do not block
11622 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11623 (member (plist-get change-plist :from)
11624 (cons 'done org-done-keywords))
11625 (member (plist-get change-plist :to)
11626 (cons 'todo org-not-done-keywords))
11627 (not (plist-get change-plist :to)))
11628 (throw 'dont-block t))
11629 ;; If this task has checkboxes that are not checked, it's blocked
11630 (save-excursion
11631 (org-back-to-heading t)
11632 (let ((beg (point)) end)
11633 (outline-next-heading)
11634 (setq end (point))
11635 (goto-char beg)
11636 (if (org-list-search-forward
11637 (concat (org-item-beginning-re)
11638 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
11639 "\\[[- ]\\]")
11640 end t)
11641 (progn
11642 (if (boundp 'org-blocked-by-checkboxes)
11643 (setq org-blocked-by-checkboxes t))
11644 (throw 'dont-block nil)))))
11645 t))) ; do not block
11647 (defun org-entry-blocked-p ()
11648 "Is the current entry blocked?"
11649 (if (org-entry-get nil "NOBLOCKING")
11650 nil ;; Never block this entry
11651 (not
11652 (run-hook-with-args-until-failure
11653 'org-blocker-hook
11654 (list :type 'todo-state-change
11655 :position (point)
11656 :from 'todo
11657 :to 'done)))))
11659 (defun org-update-statistics-cookies (all)
11660 "Update the statistics cookie, either from TODO or from checkboxes.
11661 This should be called with the cursor in a line with a statistics cookie."
11662 (interactive "P")
11663 (if all
11664 (progn
11665 (org-update-checkbox-count 'all)
11666 (org-map-entries 'org-update-parent-todo-statistics))
11667 (if (not (org-at-heading-p))
11668 (org-update-checkbox-count)
11669 (let ((pos (move-marker (make-marker) (point)))
11670 end l1 l2)
11671 (ignore-errors (org-back-to-heading t))
11672 (if (not (org-at-heading-p))
11673 (org-update-checkbox-count)
11674 (setq l1 (org-outline-level))
11675 (setq end (save-excursion
11676 (outline-next-heading)
11677 (if (org-at-heading-p) (setq l2 (org-outline-level)))
11678 (point)))
11679 (if (and (save-excursion
11680 (re-search-forward
11681 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
11682 (not (save-excursion (re-search-forward
11683 ":COOKIE_DATA:.*\\<todo\\>" end t))))
11684 (org-update-checkbox-count)
11685 (if (and l2 (> l2 l1))
11686 (progn
11687 (goto-char end)
11688 (org-update-parent-todo-statistics))
11689 (goto-char pos)
11690 (beginning-of-line 1)
11691 (while (re-search-forward
11692 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
11693 (point-at-eol) t)
11694 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
11695 (goto-char pos)
11696 (move-marker pos nil)))))
11698 (defvar org-entry-property-inherited-from) ;; defined below
11699 (defun org-update-parent-todo-statistics ()
11700 "Update any statistics cookie in the parent of the current headline.
11701 When `org-hierarchical-todo-statistics' is nil, statistics will cover
11702 the entire subtree and this will travel up the hierarchy and update
11703 statistics everywhere."
11704 (let* ((prop (save-excursion (org-up-heading-safe)
11705 (org-entry-get nil "COOKIE_DATA" 'inherit)))
11706 (recursive (or (not org-hierarchical-todo-statistics)
11707 (and prop (string-match "\\<recursive\\>" prop))))
11708 (lim (or (and prop (marker-position org-entry-property-inherited-from))
11710 (first t)
11711 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
11712 level ltoggle l1 new ndel
11713 (cnt-all 0) (cnt-done 0) is-percent kwd
11714 checkbox-beg ov ovs ove cookie-present)
11715 (catch 'exit
11716 (save-excursion
11717 (beginning-of-line 1)
11718 (setq ltoggle (funcall outline-level))
11719 ;; Three situations are to consider:
11721 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
11722 ;; to the top-level ancestor on the headline;
11724 ;; 2. If parent has "recursive" property, repeat up to the
11725 ;; headline setting that property, taking inheritance into
11726 ;; account;
11728 ;; 3. Else, move up to direct parent and proceed only once.
11729 (while (and (setq level (org-up-heading-safe))
11730 (or recursive first)
11731 (>= (point) lim))
11732 (setq first nil cookie-present nil)
11733 (unless (and level
11734 (not (string-match
11735 "\\<checkbox\\>"
11736 (downcase (or (org-entry-get nil "COOKIE_DATA")
11737 "")))))
11738 (throw 'exit nil))
11739 (while (re-search-forward box-re (point-at-eol) t)
11740 (setq cnt-all 0 cnt-done 0 cookie-present t)
11741 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
11742 (save-match-data
11743 (unless (outline-next-heading) (throw 'exit nil))
11744 (while (and (looking-at org-complex-heading-regexp)
11745 (> (setq l1 (length (match-string 1))) level))
11746 (setq kwd (and (or recursive (= l1 ltoggle))
11747 (match-string 2)))
11748 (if (or (eq org-provide-todo-statistics 'all-headlines)
11749 (and (listp org-provide-todo-statistics)
11750 (or (member kwd org-provide-todo-statistics)
11751 (member kwd org-done-keywords))))
11752 (setq cnt-all (1+ cnt-all))
11753 (if (eq org-provide-todo-statistics t)
11754 (and kwd (setq cnt-all (1+ cnt-all)))))
11755 (and (member kwd org-done-keywords)
11756 (setq cnt-done (1+ cnt-done)))
11757 (outline-next-heading)))
11758 (setq new
11759 (if is-percent
11760 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
11761 (format "[%d/%d]" cnt-done cnt-all))
11762 ndel (- (match-end 0) checkbox-beg))
11763 ;; handle overlays when updating cookie from column view
11764 (when (setq ov (car (overlays-at checkbox-beg)))
11765 (setq ovs (overlay-start ov) ove (overlay-end ov))
11766 (delete-overlay ov))
11767 (goto-char checkbox-beg)
11768 (insert new)
11769 (delete-region (point) (+ (point) ndel))
11770 (when org-auto-align-tags (org-fix-tags-on-the-fly))
11771 (when ov (move-overlay ov ovs ove)))
11772 (when cookie-present
11773 (run-hook-with-args 'org-after-todo-statistics-hook
11774 cnt-done (- cnt-all cnt-done))))))
11775 (run-hooks 'org-todo-statistics-hook)))
11777 (defvar org-after-todo-statistics-hook nil
11778 "Hook that is called after a TODO statistics cookie has been updated.
11779 Each function is called with two arguments: the number of not-done entries
11780 and the number of done entries.
11782 For example, the following function, when added to this hook, will switch
11783 an entry to DONE when all children are done, and back to TODO when new
11784 entries are set to a TODO status. Note that this hook is only called
11785 when there is a statistics cookie in the headline!
11787 (defun org-summary-todo (n-done n-not-done)
11788 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
11789 (let (org-log-done org-log-states) ; turn off logging
11790 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
11793 (defvar org-todo-statistics-hook nil
11794 "Hook that is run whenever Org thinks TODO statistics should be updated.
11795 This hook runs even if there is no statistics cookie present, in which case
11796 `org-after-todo-statistics-hook' would not run.")
11798 (defun org-todo-trigger-tag-changes (state)
11799 "Apply the changes defined in `org-todo-state-tags-triggers'."
11800 (let ((l org-todo-state-tags-triggers)
11801 changes)
11802 (when (or (not state) (equal state ""))
11803 (setq changes (append changes (cdr (assoc "" l)))))
11804 (when (and (stringp state) (> (length state) 0))
11805 (setq changes (append changes (cdr (assoc state l)))))
11806 (when (member state org-not-done-keywords)
11807 (setq changes (append changes (cdr (assoc 'todo l)))))
11808 (when (member state org-done-keywords)
11809 (setq changes (append changes (cdr (assoc 'done l)))))
11810 (dolist (c changes)
11811 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
11813 (defun org-local-logging (value)
11814 "Get logging settings from a property VALUE."
11815 (let* (words w a)
11816 ;; directly set the variables, they are already local.
11817 (setq org-log-done nil
11818 org-log-repeat nil
11819 org-todo-log-states nil)
11820 (setq words (org-split-string value))
11821 (while (setq w (pop words))
11822 (cond
11823 ((setq a (assoc w org-startup-options))
11824 (and (member (nth 1 a) '(org-log-done org-log-repeat))
11825 (set (nth 1 a) (nth 2 a))))
11826 ((setq a (org-extract-log-state-settings w))
11827 (and (member (car a) org-todo-keywords-1)
11828 (push a org-todo-log-states)))))))
11830 (defun org-get-todo-sequence-head (kwd)
11831 "Return the head of the TODO sequence to which KWD belongs.
11832 If KWD is not set, check if there is a text property remembering the
11833 right sequence."
11834 (let (p)
11835 (cond
11836 ((not kwd)
11837 (or (get-text-property (point-at-bol) 'org-todo-head)
11838 (progn
11839 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
11840 nil (point-at-eol)))
11841 (get-text-property p 'org-todo-head))))
11842 ((not (member kwd org-todo-keywords-1))
11843 (car org-todo-keywords-1))
11844 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
11846 (defun org-fast-todo-selection ()
11847 "Fast TODO keyword selection with single keys.
11848 Returns the new TODO keyword, or nil if no state change should occur."
11849 (let* ((fulltable org-todo-key-alist)
11850 (done-keywords org-done-keywords) ;; needed for the faces.
11851 (maxlen (apply 'max (mapcar
11852 (lambda (x)
11853 (if (stringp (car x)) (string-width (car x)) 0))
11854 fulltable)))
11855 (expert nil)
11856 (fwidth (+ maxlen 3 1 3))
11857 (ncol (/ (- (window-width) 4) fwidth))
11858 tg cnt e c tbl
11859 groups ingroup)
11860 (save-excursion
11861 (save-window-excursion
11862 (if expert
11863 (set-buffer (get-buffer-create " *Org todo*"))
11864 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
11865 (erase-buffer)
11866 (org-set-local 'org-done-keywords done-keywords)
11867 (setq tbl fulltable cnt 0)
11868 (while (setq e (pop tbl))
11869 (cond
11870 ((equal e '(:startgroup))
11871 (push '() groups) (setq ingroup t)
11872 (when (not (= cnt 0))
11873 (setq cnt 0)
11874 (insert "\n"))
11875 (insert "{ "))
11876 ((equal e '(:endgroup))
11877 (setq ingroup nil cnt 0)
11878 (insert "}\n"))
11879 ((equal e '(:newline))
11880 (when (not (= cnt 0))
11881 (setq cnt 0)
11882 (insert "\n")
11883 (setq e (car tbl))
11884 (while (equal (car tbl) '(:newline))
11885 (insert "\n")
11886 (setq tbl (cdr tbl)))))
11888 (setq tg (car e) c (cdr e))
11889 (if ingroup (push tg (car groups)))
11890 (setq tg (org-add-props tg nil 'face
11891 (org-get-todo-face tg)))
11892 (if (and (= cnt 0) (not ingroup)) (insert " "))
11893 (insert "[" c "] " tg (make-string
11894 (- fwidth 4 (length tg)) ?\ ))
11895 (when (= (setq cnt (1+ cnt)) ncol)
11896 (insert "\n")
11897 (if ingroup (insert " "))
11898 (setq cnt 0)))))
11899 (insert "\n")
11900 (goto-char (point-min))
11901 (if (not expert) (org-fit-window-to-buffer))
11902 (message "[a-z..]:Set [SPC]:clear")
11903 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
11904 (cond
11905 ((or (= c ?\C-g)
11906 (and (= c ?q) (not (rassoc c fulltable))))
11907 (setq quit-flag t))
11908 ((= c ?\ ) nil)
11909 ((setq e (rassoc c fulltable) tg (car e))
11911 (t (setq quit-flag t)))))))
11913 (defun org-entry-is-todo-p ()
11914 (member (org-get-todo-state) org-not-done-keywords))
11916 (defun org-entry-is-done-p ()
11917 (member (org-get-todo-state) org-done-keywords))
11919 (defun org-get-todo-state ()
11920 (save-excursion
11921 (org-back-to-heading t)
11922 (and (looking-at org-todo-line-regexp)
11923 (match-end 2)
11924 (match-string 2))))
11926 (defun org-at-date-range-p (&optional inactive-ok)
11927 "Is the cursor inside a date range?"
11928 (interactive)
11929 (save-excursion
11930 (catch 'exit
11931 (let ((pos (point)))
11932 (skip-chars-backward "^[<\r\n")
11933 (skip-chars-backward "<[")
11934 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
11935 (>= (match-end 0) pos)
11936 (throw 'exit t))
11937 (skip-chars-backward "^<[\r\n")
11938 (skip-chars-backward "<[")
11939 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
11940 (>= (match-end 0) pos)
11941 (throw 'exit t)))
11942 nil)))
11944 (defun org-get-repeat (&optional tagline)
11945 "Check if there is a deadline/schedule with repeater in this entry."
11946 (save-match-data
11947 (save-excursion
11948 (org-back-to-heading t)
11949 (and (re-search-forward (if tagline
11950 (concat tagline "\\s-*" org-repeat-re)
11951 org-repeat-re)
11952 (org-entry-end-position) t)
11953 (match-string-no-properties 1)))))
11955 (defvar org-last-changed-timestamp)
11956 (defvar org-last-inserted-timestamp)
11957 (defvar org-log-post-message)
11958 (defvar org-log-note-purpose)
11959 (defvar org-log-note-how)
11960 (defvar org-log-note-extra)
11961 (defun org-auto-repeat-maybe (done-word)
11962 "Check if the current headline contains a repeated deadline/schedule.
11963 If yes, set TODO state back to what it was and change the base date
11964 of repeating deadline/scheduled time stamps to new date.
11965 This function is run automatically after each state change to a DONE state."
11966 ;; last-state is dynamically scoped into this function
11967 (let* ((repeat (org-get-repeat))
11968 (aa (assoc org-last-state org-todo-kwd-alist))
11969 (interpret (nth 1 aa))
11970 (head (nth 2 aa))
11971 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
11972 (msg "Entry repeats: ")
11973 (org-log-done nil)
11974 (org-todo-log-states nil)
11975 re type n what ts time to-state)
11976 (when repeat
11977 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
11978 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
11979 org-todo-repeat-to-state))
11980 (unless (and to-state (member to-state org-todo-keywords-1))
11981 (setq to-state (if (eq interpret 'type) org-last-state head)))
11982 (org-todo to-state)
11983 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
11984 (org-entry-put nil "LAST_REPEAT" (format-time-string
11985 (org-time-stamp-format t t))))
11986 (when org-log-repeat
11987 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
11988 (memq 'org-add-log-note post-command-hook))
11989 ;; OK, we are already setup for some record
11990 (if (eq org-log-repeat 'note)
11991 ;; make sure we take a note, not only a time stamp
11992 (setq org-log-note-how 'note))
11993 ;; Set up for taking a record
11994 (org-add-log-setup 'state (or done-word (car org-done-keywords))
11995 org-last-state
11996 'findpos org-log-repeat)))
11997 (org-back-to-heading t)
11998 (org-add-planning-info nil nil 'closed)
11999 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12000 org-deadline-time-regexp "\\)\\|\\("
12001 org-ts-regexp "\\)"))
12002 (while (re-search-forward
12003 re (save-excursion (outline-next-heading) (point)) t)
12004 (setq type (if (match-end 1) org-scheduled-string
12005 (if (match-end 3) org-deadline-string "Plain:"))
12006 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12007 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12008 (setq n (string-to-number (match-string 2 ts))
12009 what (match-string 3 ts))
12010 (if (equal what "w") (setq n (* n 7) what "d"))
12011 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12012 (error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12013 ;; Preparation, see if we need to modify the start date for the change
12014 (when (match-end 1)
12015 (setq time (save-match-data (org-time-string-to-time ts)))
12016 (cond
12017 ((equal (match-string 1 ts) ".")
12018 ;; Shift starting date to today
12019 (org-timestamp-change
12020 (- (org-today) (time-to-days time))
12021 'day))
12022 ((equal (match-string 1 ts) "+")
12023 (let ((nshiftmax 10) (nshift 0))
12024 (while (or (= nshift 0)
12025 (<= (time-to-days time)
12026 (time-to-days (current-time))))
12027 (when (= (incf nshift) nshiftmax)
12028 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12029 (error "Abort")))
12030 (org-timestamp-change n (cdr (assoc what whata)))
12031 (org-at-timestamp-p t)
12032 (setq ts (match-string 1))
12033 (setq time (save-match-data (org-time-string-to-time ts)))))
12034 (org-timestamp-change (- n) (cdr (assoc what whata)))
12035 ;; rematch, so that we have everything in place for the real shift
12036 (org-at-timestamp-p t)
12037 (setq ts (match-string 1))
12038 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12039 (org-timestamp-change n (cdr (assoc what whata)))
12040 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12041 (setq org-log-post-message msg)
12042 (message "%s" msg))))
12044 (defun org-show-todo-tree (arg)
12045 "Make a compact tree which shows all headlines marked with TODO.
12046 The tree will show the lines where the regexp matches, and all higher
12047 headlines above the match.
12048 With a \\[universal-argument] prefix, prompt for a regexp to match.
12049 With a numeric prefix N, construct a sparse tree for the Nth element
12050 of `org-todo-keywords-1'."
12051 (interactive "P")
12052 (let ((case-fold-search nil)
12053 (kwd-re
12054 (cond ((null arg) org-not-done-regexp)
12055 ((equal arg '(4))
12056 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12057 (mapcar 'list org-todo-keywords-1))))
12058 (concat "\\("
12059 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12060 "\\)\\>")))
12061 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12062 (regexp-quote (nth (1- (prefix-numeric-value arg))
12063 org-todo-keywords-1)))
12064 (t (error "Invalid prefix argument: %s" arg)))))
12065 (message "%d TODO entries found"
12066 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12068 (defun org-deadline (&optional remove time)
12069 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12070 With argument REMOVE, remove any deadline from the item.
12071 With argument TIME, set the deadline at the corresponding date. TIME
12072 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12073 (interactive "P")
12074 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12075 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12076 'region-start-level 'region))
12077 org-loop-over-headlines-in-active-region)
12078 (org-map-entries
12079 `(org-deadline ',remove ,time)
12080 org-loop-over-headlines-in-active-region
12081 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12082 (let* ((old-date (org-entry-get nil "DEADLINE"))
12083 (repeater (and old-date
12084 (string-match
12085 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12086 old-date)
12087 (match-string 1 old-date))))
12088 (if remove
12089 (progn
12090 (when (and old-date org-log-redeadline)
12091 (org-add-log-setup 'deldeadline nil old-date 'findpos
12092 org-log-redeadline))
12093 (org-remove-timestamp-with-keyword org-deadline-string)
12094 (message "Item no longer has a deadline."))
12095 (org-add-planning-info 'deadline time 'closed)
12096 (when (and old-date org-log-redeadline
12097 (not (equal old-date
12098 (substring org-last-inserted-timestamp 1 -1))))
12099 (org-add-log-setup 'redeadline nil old-date 'findpos
12100 org-log-redeadline))
12101 (when repeater
12102 (save-excursion
12103 (org-back-to-heading t)
12104 (when (re-search-forward (concat org-deadline-string " "
12105 org-last-inserted-timestamp)
12106 (save-excursion
12107 (outline-next-heading) (point)) t)
12108 (goto-char (1- (match-end 0)))
12109 (insert " " repeater)
12110 (setq org-last-inserted-timestamp
12111 (concat (substring org-last-inserted-timestamp 0 -1)
12112 " " repeater
12113 (substring org-last-inserted-timestamp -1))))))
12114 (message "Deadline on %s" org-last-inserted-timestamp)))))
12116 (defun org-schedule (&optional remove time)
12117 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12118 With argument REMOVE, remove any scheduling date from the item.
12119 With argument TIME, scheduled at the corresponding date. TIME can
12120 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12121 (interactive "P")
12122 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12123 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12124 'region-start-level 'region))
12125 org-loop-over-headlines-in-active-region)
12126 (org-map-entries
12127 `(org-schedule ',remove ,time)
12128 org-loop-over-headlines-in-active-region
12129 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12130 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12131 (repeater (and old-date
12132 (string-match
12133 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12134 old-date)
12135 (match-string 1 old-date))))
12136 (if remove
12137 (progn
12138 (when (and old-date org-log-reschedule)
12139 (org-add-log-setup 'delschedule nil old-date 'findpos
12140 org-log-reschedule))
12141 (org-remove-timestamp-with-keyword org-scheduled-string)
12142 (message "Item is no longer scheduled."))
12143 (org-add-planning-info 'scheduled time 'closed)
12144 (when (and old-date org-log-reschedule
12145 (not (equal old-date
12146 (substring org-last-inserted-timestamp 1 -1))))
12147 (org-add-log-setup 'reschedule nil old-date 'findpos
12148 org-log-reschedule))
12149 (when repeater
12150 (save-excursion
12151 (org-back-to-heading t)
12152 (when (re-search-forward (concat org-scheduled-string " "
12153 org-last-inserted-timestamp)
12154 (save-excursion
12155 (outline-next-heading) (point)) t)
12156 (goto-char (1- (match-end 0)))
12157 (insert " " repeater)
12158 (setq org-last-inserted-timestamp
12159 (concat (substring org-last-inserted-timestamp 0 -1)
12160 " " repeater
12161 (substring org-last-inserted-timestamp -1))))))
12162 (message "Scheduled to %s" org-last-inserted-timestamp)))))
12164 (defun org-get-scheduled-time (pom &optional inherit)
12165 "Get the scheduled time as a time tuple, of a format suitable
12166 for calling org-schedule with, or if there is no scheduling,
12167 returns nil."
12168 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12169 (when time
12170 (apply 'encode-time (org-parse-time-string time)))))
12172 (defun org-get-deadline-time (pom &optional inherit)
12173 "Get the deadline as a time tuple, of a format suitable for
12174 calling org-deadline with, or if there is no scheduling, returns
12175 nil."
12176 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12177 (when time
12178 (apply 'encode-time (org-parse-time-string time)))))
12180 (defun org-remove-timestamp-with-keyword (keyword)
12181 "Remove all time stamps with KEYWORD in the current entry."
12182 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12183 beg)
12184 (save-excursion
12185 (org-back-to-heading t)
12186 (setq beg (point))
12187 (outline-next-heading)
12188 (while (re-search-backward re beg t)
12189 (replace-match "")
12190 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12191 (equal (char-before) ?\ ))
12192 (backward-delete-char 1)
12193 (if (string-match "^[ \t]*$" (buffer-substring
12194 (point-at-bol) (point-at-eol)))
12195 (delete-region (point-at-bol)
12196 (min (point-max) (1+ (point-at-eol))))))))))
12198 (defun org-add-planning-info (what &optional time &rest remove)
12199 "Insert new timestamp with keyword in the line directly after the headline.
12200 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
12201 If non is given, the user is prompted for a date.
12202 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
12203 be removed."
12204 (interactive)
12205 (let (org-time-was-given org-end-time-was-given ts
12206 end default-time default-input)
12208 (catch 'exit
12209 (when (and (memq what '(scheduled deadline))
12210 (or (not time)
12211 (and (stringp time)
12212 (string-match "^[-+]+[0-9]" time))))
12213 ;; Try to get a default date/time from existing timestamp
12214 (save-excursion
12215 (org-back-to-heading t)
12216 (setq end (save-excursion (outline-next-heading) (point)))
12217 (when (re-search-forward (if (eq what 'scheduled)
12218 org-scheduled-time-regexp
12219 org-deadline-time-regexp)
12220 end t)
12221 (setq ts (match-string 1)
12222 default-time
12223 (apply 'encode-time (org-parse-time-string ts))
12224 default-input (and ts (org-get-compact-tod ts))))))
12225 (when what
12226 (setq time
12227 (if (stringp time)
12228 ;; This is a string (relative or absolute), set proper date
12229 (apply 'encode-time
12230 (org-read-date-analyze
12231 time default-time (decode-time default-time)))
12232 ;; If necessary, get the time from the user
12233 (or time (org-read-date nil 'to-time nil nil
12234 default-time default-input)))))
12236 (when (and org-insert-labeled-timestamps-at-point
12237 (member what '(scheduled deadline)))
12238 (insert
12239 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
12240 (org-insert-time-stamp time org-time-was-given
12241 nil nil nil (list org-end-time-was-given))
12242 (setq what nil))
12243 (save-excursion
12244 (save-restriction
12245 (let (col list elt ts buffer-invisibility-spec)
12246 (org-back-to-heading t)
12247 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
12248 (goto-char (match-end 1))
12249 (setq col (current-column))
12250 (goto-char (match-end 0))
12251 (if (eobp) (insert "\n") (forward-char 1))
12252 (when (and (not what)
12253 (not (looking-at
12254 (concat "[ \t]*"
12255 org-keyword-time-not-clock-regexp))))
12256 ;; Nothing to add, nothing to remove...... :-)
12257 (throw 'exit nil))
12258 (if (and (not (looking-at org-outline-regexp))
12259 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
12260 "[^\r\n]*"))
12261 (not (equal (match-string 1) org-clock-string)))
12262 (narrow-to-region (match-beginning 0) (match-end 0))
12263 (insert-before-markers "\n")
12264 (backward-char 1)
12265 (narrow-to-region (point) (point))
12266 (and org-adapt-indentation (org-indent-to-column col)))
12267 ;; Check if we have to remove something.
12268 (setq list (cons what remove))
12269 (while list
12270 (setq elt (pop list))
12271 (when (or (and (eq elt 'scheduled)
12272 (re-search-forward org-scheduled-time-regexp nil t))
12273 (and (eq elt 'deadline)
12274 (re-search-forward org-deadline-time-regexp nil t))
12275 (and (eq elt 'closed)
12276 (re-search-forward org-closed-time-regexp nil t)))
12277 (replace-match "")
12278 (if (looking-at "--+<[^>]+>") (replace-match ""))))
12279 (and (looking-at "[ \t]+") (replace-match ""))
12280 (and org-adapt-indentation (bolp) (org-indent-to-column col))
12281 (when what
12282 (insert
12283 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
12284 (cond ((eq what 'scheduled) org-scheduled-string)
12285 ((eq what 'deadline) org-deadline-string)
12286 ((eq what 'closed) org-closed-string))
12287 " ")
12288 (setq ts (org-insert-time-stamp
12289 time
12290 (or org-time-was-given
12291 (and (eq what 'closed) org-log-done-with-time))
12292 (eq what 'closed)
12293 nil nil (list org-end-time-was-given)))
12294 (insert
12295 (if (not (or (bolp) (eq (char-before) ?\ )
12296 (memq (char-after) '(32 10))
12297 (eobp))) " " ""))
12298 (end-of-line 1))
12299 (goto-char (point-min))
12300 (widen)
12301 (if (and (looking-at "[ \t]*\n")
12302 (equal (char-before) ?\n))
12303 (delete-region (1- (point)) (point-at-eol)))
12304 ts))))))
12306 (defvar org-log-note-marker (make-marker))
12307 (defvar org-log-note-purpose nil)
12308 (defvar org-log-note-state nil)
12309 (defvar org-log-note-previous-state nil)
12310 (defvar org-log-note-how nil)
12311 (defvar org-log-note-extra nil)
12312 (defvar org-log-note-window-configuration nil)
12313 (defvar org-log-note-return-to (make-marker))
12314 (defvar org-log-note-effective-time nil
12315 "Remembered current time so that dynamically scoped
12316 `org-extend-today-until' affects tha timestamps in state change
12317 log")
12319 (defvar org-log-post-message nil
12320 "Message to be displayed after a log note has been stored.
12321 The auto-repeater uses this.")
12323 (defun org-add-note ()
12324 "Add a note to the current entry.
12325 This is done in the same way as adding a state change note."
12326 (interactive)
12327 (org-add-log-setup 'note nil nil 'findpos nil))
12329 (defvar org-property-end-re)
12330 (defun org-add-log-setup (&optional purpose state prev-state
12331 findpos how extra)
12332 "Set up the post command hook to take a note.
12333 If this is about to TODO state change, the new state is expected in STATE.
12334 When FINDPOS is non-nil, find the correct position for the note in
12335 the current entry. If not, assume that it can be inserted at point.
12336 HOW is an indicator what kind of note should be created.
12337 EXTRA is additional text that will be inserted into the notes buffer."
12338 (let* ((org-log-into-drawer (org-log-into-drawer))
12339 (drawer (cond ((stringp org-log-into-drawer)
12340 org-log-into-drawer)
12341 (org-log-into-drawer "LOGBOOK")
12342 (t nil))))
12343 (save-restriction
12344 (save-excursion
12345 (when findpos
12346 (org-back-to-heading t)
12347 (narrow-to-region (point) (save-excursion
12348 (outline-next-heading) (point)))
12349 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
12350 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
12351 "[^\r\n]*\\)?"))
12352 (goto-char (match-end 0))
12353 (cond
12354 (drawer
12355 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
12356 nil t)
12357 (progn
12358 (goto-char (match-end 0))
12359 (or org-log-states-order-reversed
12360 (and (re-search-forward org-property-end-re nil t)
12361 (goto-char (1- (match-beginning 0))))))
12362 (insert "\n:" drawer ":\n:END:")
12363 (beginning-of-line 0)
12364 (org-indent-line-function)
12365 (beginning-of-line 2)
12366 (org-indent-line-function)
12367 (end-of-line 0)))
12368 ((and org-log-state-notes-insert-after-drawers
12369 (save-excursion
12370 (forward-line) (looking-at org-drawer-regexp)))
12371 (forward-line)
12372 (while (looking-at org-drawer-regexp)
12373 (goto-char (match-end 0))
12374 (re-search-forward org-property-end-re (point-max) t)
12375 (forward-line))
12376 (forward-line -1)))
12377 (unless org-log-states-order-reversed
12378 (and (= (char-after) ?\n) (forward-char 1))
12379 (org-skip-over-state-notes)
12380 (skip-chars-backward " \t\n\r")))
12381 (move-marker org-log-note-marker (point))
12382 (setq org-log-note-purpose purpose
12383 org-log-note-state state
12384 org-log-note-previous-state prev-state
12385 org-log-note-how how
12386 org-log-note-extra extra
12387 org-log-note-effective-time (org-current-effective-time))
12388 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
12390 (defun org-skip-over-state-notes ()
12391 "Skip past the list of State notes in an entry."
12392 (if (looking-at "\n[ \t]*- State") (forward-char 1))
12393 (when (ignore-errors (goto-char (org-in-item-p)))
12394 (let* ((struct (org-list-struct))
12395 (prevs (org-list-prevs-alist struct)))
12396 (while (looking-at "[ \t]*- State")
12397 (goto-char (or (org-list-get-next-item (point) struct prevs)
12398 (org-list-get-item-end (point) struct)))))))
12400 (defun org-add-log-note (&optional purpose)
12401 "Pop up a window for taking a note, and add this note later at point."
12402 (remove-hook 'post-command-hook 'org-add-log-note)
12403 (setq org-log-note-window-configuration (current-window-configuration))
12404 (delete-other-windows)
12405 (move-marker org-log-note-return-to (point))
12406 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
12407 (goto-char org-log-note-marker)
12408 (org-switch-to-buffer-other-window "*Org Note*")
12409 (erase-buffer)
12410 (if (memq org-log-note-how '(time state))
12411 (let (current-prefix-arg) (org-store-log-note))
12412 (let ((org-inhibit-startup t)) (org-mode))
12413 (insert (format "# Insert note for %s.
12414 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
12415 (cond
12416 ((eq org-log-note-purpose 'clock-out) "stopped clock")
12417 ((eq org-log-note-purpose 'done) "closed todo item")
12418 ((eq org-log-note-purpose 'state)
12419 (format "state change from \"%s\" to \"%s\""
12420 (or org-log-note-previous-state "")
12421 (or org-log-note-state "")))
12422 ((eq org-log-note-purpose 'reschedule)
12423 "rescheduling")
12424 ((eq org-log-note-purpose 'delschedule)
12425 "no longer scheduled")
12426 ((eq org-log-note-purpose 'redeadline)
12427 "changing deadline")
12428 ((eq org-log-note-purpose 'deldeadline)
12429 "removing deadline")
12430 ((eq org-log-note-purpose 'refile)
12431 "refiling")
12432 ((eq org-log-note-purpose 'note)
12433 "this entry")
12434 (t (error "This should not happen")))))
12435 (if org-log-note-extra (insert org-log-note-extra))
12436 (org-set-local 'org-finish-function 'org-store-log-note)
12437 (run-hooks 'org-log-buffer-setup-hook)))
12439 (defvar org-note-abort nil) ; dynamically scoped
12440 (defun org-store-log-note ()
12441 "Finish taking a log note, and insert it to where it belongs."
12442 (let ((txt (buffer-string))
12443 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
12444 lines ind bul)
12445 (kill-buffer (current-buffer))
12446 (while (string-match "\\`#.*\n[ \t\n]*" txt)
12447 (setq txt (replace-match "" t t txt)))
12448 (if (string-match "\\s-+\\'" txt)
12449 (setq txt (replace-match "" t t txt)))
12450 (setq lines (org-split-string txt "\n"))
12451 (when (and note (string-match "\\S-" note))
12452 (setq note
12453 (org-replace-escapes
12454 note
12455 (list (cons "%u" (user-login-name))
12456 (cons "%U" user-full-name)
12457 (cons "%t" (format-time-string
12458 (org-time-stamp-format 'long 'inactive)
12459 org-log-note-effective-time))
12460 (cons "%T" (format-time-string
12461 (org-time-stamp-format 'long nil)
12462 org-log-note-effective-time))
12463 (cons "%d" (format-time-string
12464 (org-time-stamp-format nil 'inactive)
12465 org-log-note-effective-time))
12466 (cons "%D" (format-time-string
12467 (org-time-stamp-format nil nil)
12468 org-log-note-effective-time))
12469 (cons "%s" (if org-log-note-state
12470 (concat "\"" org-log-note-state "\"")
12471 ""))
12472 (cons "%S" (if org-log-note-previous-state
12473 (concat "\"" org-log-note-previous-state "\"")
12474 "\"\"")))))
12475 (if lines (setq note (concat note " \\\\")))
12476 (push note lines))
12477 (when (or current-prefix-arg org-note-abort)
12478 (when org-log-into-drawer
12479 (org-remove-empty-drawer-at
12480 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
12481 org-log-note-marker))
12482 (setq lines nil))
12483 (when lines
12484 (with-current-buffer (marker-buffer org-log-note-marker)
12485 (save-excursion
12486 (goto-char org-log-note-marker)
12487 (move-marker org-log-note-marker nil)
12488 (end-of-line 1)
12489 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
12490 (setq ind (save-excursion
12491 (if (ignore-errors (goto-char (org-in-item-p)))
12492 (let ((struct (org-list-struct)))
12493 (org-list-get-ind
12494 (org-list-get-top-point struct) struct))
12495 (skip-chars-backward " \r\t\n")
12496 (cond
12497 ((and (org-at-heading-p)
12498 org-adapt-indentation)
12499 (1+ (org-current-level)))
12500 ((org-at-heading-p) 0)
12501 (t (org-get-indentation))))))
12502 (setq bul (org-list-bullet-string "-"))
12503 (org-indent-line-to ind)
12504 (insert bul (pop lines))
12505 (let ((ind-body (+ (length bul) ind)))
12506 (while lines
12507 (insert "\n")
12508 (org-indent-line-to ind-body)
12509 (insert (pop lines))))
12510 (message "Note stored")
12511 (org-back-to-heading t)
12512 (org-cycle-hide-drawers 'children)))))
12513 (set-window-configuration org-log-note-window-configuration)
12514 (with-current-buffer (marker-buffer org-log-note-return-to)
12515 (goto-char org-log-note-return-to))
12516 (move-marker org-log-note-return-to nil)
12517 (and org-log-post-message (message "%s" org-log-post-message)))
12519 (defun org-remove-empty-drawer-at (drawer pos)
12520 "Remove an empty drawer DRAWER at position POS.
12521 POS may also be a marker."
12522 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
12523 (save-excursion
12524 (save-restriction
12525 (widen)
12526 (goto-char pos)
12527 (if (org-in-regexp
12528 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
12529 (replace-match ""))))))
12531 (defun org-sparse-tree (&optional arg)
12532 "Create a sparse tree, prompt for the details.
12533 This command can create sparse trees. You first need to select the type
12534 of match used to create the tree:
12536 t Show all TODO entries.
12537 T Show entries with a specific TODO keyword.
12538 m Show entries selected by a tags/property match.
12539 p Enter a property name and its value (both with completion on existing
12540 names/values) and show entries with that property.
12541 r Show entries matching a regular expression (`/' can be used as well)
12542 d Show deadlines due within `org-deadline-warning-days'.
12543 b Show deadlines and scheduled items before a date.
12544 a Show deadlines and scheduled items after a date."
12545 (interactive "P")
12546 (let (ans kwd value)
12547 (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")
12548 (setq ans (read-char-exclusive))
12549 (cond
12550 ((equal ans ?d)
12551 (call-interactively 'org-check-deadlines))
12552 ((equal ans ?b)
12553 (call-interactively 'org-check-before-date))
12554 ((equal ans ?a)
12555 (call-interactively 'org-check-after-date))
12556 ((equal ans ?D)
12557 (call-interactively 'org-check-dates-range))
12558 ((equal ans ?t)
12559 (org-show-todo-tree nil))
12560 ((equal ans ?T)
12561 (org-show-todo-tree '(4)))
12562 ((member ans '(?T ?m))
12563 (call-interactively 'org-match-sparse-tree))
12564 ((member ans '(?p ?P))
12565 (setq kwd (org-icompleting-read "Property: "
12566 (mapcar 'list (org-buffer-property-keys))))
12567 (setq value (org-icompleting-read "Value: "
12568 (mapcar 'list (org-property-values kwd))))
12569 (unless (string-match "\\`{.*}\\'" value)
12570 (setq value (concat "\"" value "\"")))
12571 (org-match-sparse-tree arg (concat kwd "=" value)))
12572 ((member ans '(?r ?R ?/))
12573 (call-interactively 'org-occur))
12574 (t (error "No such sparse tree command \"%c\"" ans)))))
12576 (defvar org-occur-highlights nil
12577 "List of overlays used for occur matches.")
12578 (make-variable-buffer-local 'org-occur-highlights)
12579 (defvar org-occur-parameters nil
12580 "Parameters of the active org-occur calls.
12581 This is a list, each call to org-occur pushes as cons cell,
12582 containing the regular expression and the callback, onto the list.
12583 The list can contain several entries if `org-occur' has been called
12584 several time with the KEEP-PREVIOUS argument. Otherwise, this list
12585 will only contain one set of parameters. When the highlights are
12586 removed (for example with `C-c C-c', or with the next edit (depending
12587 on `org-remove-highlights-with-change'), this variable is emptied
12588 as well.")
12589 (make-variable-buffer-local 'org-occur-parameters)
12591 (defun org-occur (regexp &optional keep-previous callback)
12592 "Make a compact tree which shows all matches of REGEXP.
12593 The tree will show the lines where the regexp matches, and all higher
12594 headlines above the match. It will also show the heading after the match,
12595 to make sure editing the matching entry is easy.
12596 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
12597 call to `org-occur' will be kept, to allow stacking of calls to this
12598 command.
12599 If CALLBACK is non-nil, it is a function which is called to confirm
12600 that the match should indeed be shown."
12601 (interactive "sRegexp: \nP")
12602 (when (equal regexp "")
12603 (error "Regexp cannot be empty"))
12604 (unless keep-previous
12605 (org-remove-occur-highlights nil nil t))
12606 (push (cons regexp callback) org-occur-parameters)
12607 (let ((cnt 0))
12608 (save-excursion
12609 (goto-char (point-min))
12610 (if (or (not keep-previous) ; do not want to keep
12611 (not org-occur-highlights)) ; no previous matches
12612 ;; hide everything
12613 (org-overview))
12614 (while (re-search-forward regexp nil t)
12615 (when (or (not callback)
12616 (save-match-data (funcall callback)))
12617 (setq cnt (1+ cnt))
12618 (when org-highlight-sparse-tree-matches
12619 (org-highlight-new-match (match-beginning 0) (match-end 0)))
12620 (org-show-context 'occur-tree))))
12621 (when org-remove-highlights-with-change
12622 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
12623 nil 'local))
12624 (unless org-sparse-tree-open-archived-trees
12625 (org-hide-archived-subtrees (point-min) (point-max)))
12626 (run-hooks 'org-occur-hook)
12627 (if (org-called-interactively-p 'interactive)
12628 (message "%d match(es) for regexp %s" cnt regexp))
12629 cnt))
12631 (defun org-occur-next-match (&optional n reset)
12632 "Function for `next-error-function' to find sparse tree matches.
12633 N is the number of matches to move, when negative move backwards.
12634 RESET is entirely ignored - this function always goes back to the
12635 starting point when no match is found."
12636 (let* ((limit (if (< n 0) (point-min) (point-max)))
12637 (search-func (if (< n 0)
12638 'previous-single-char-property-change
12639 'next-single-char-property-change))
12640 (n (abs n))
12641 (pos (point))
12643 (catch 'exit
12644 (while (setq p1 (funcall search-func (point) 'org-type))
12645 (when (equal p1 limit)
12646 (goto-char pos)
12647 (error "No more matches"))
12648 (when (equal (get-char-property p1 'org-type) 'org-occur)
12649 (setq n (1- n))
12650 (when (= n 0)
12651 (goto-char p1)
12652 (throw 'exit (point))))
12653 (goto-char p1))
12654 (goto-char p1)
12655 (error "No more matches"))))
12657 (defun org-show-context (&optional key)
12658 "Make sure point and context are visible.
12659 How much context is shown depends upon the variables
12660 `org-show-hierarchy-above', `org-show-following-heading',
12661 `org-show-entry-below' and `org-show-siblings'."
12662 (let ((heading-p (org-at-heading-p t))
12663 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
12664 (following-p (org-get-alist-option org-show-following-heading key))
12665 (entry-p (org-get-alist-option org-show-entry-below key))
12666 (siblings-p (org-get-alist-option org-show-siblings key)))
12667 (catch 'exit
12668 ;; Show heading or entry text
12669 (if (and heading-p (not entry-p))
12670 (org-flag-heading nil) ; only show the heading
12671 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
12672 (org-show-hidden-entry))) ; show entire entry
12673 (when following-p
12674 ;; Show next sibling, or heading below text
12675 (save-excursion
12676 (and (if heading-p (org-goto-sibling) (outline-next-heading))
12677 (org-flag-heading nil))))
12678 (when siblings-p (org-show-siblings))
12679 (when hierarchy-p
12680 ;; show all higher headings, possibly with siblings
12681 (save-excursion
12682 (while (and (condition-case nil
12683 (progn (org-up-heading-all 1) t)
12684 (error nil))
12685 (not (bobp)))
12686 (org-flag-heading nil)
12687 (when siblings-p (org-show-siblings))))))))
12689 (defvar org-reveal-start-hook nil
12690 "Hook run before revealing a location.")
12692 (defun org-reveal (&optional siblings)
12693 "Show current entry, hierarchy above it, and the following headline.
12694 This can be used to show a consistent set of context around locations
12695 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
12696 not t for the search context.
12698 With optional argument SIBLINGS, on each level of the hierarchy all
12699 siblings are shown. This repairs the tree structure to what it would
12700 look like when opened with hierarchical calls to `org-cycle'.
12701 With double optional argument \\[universal-argument] \\[universal-argument], \
12702 go to the parent and show the
12703 entire tree."
12704 (interactive "P")
12705 (run-hooks 'org-reveal-start-hook)
12706 (let ((org-show-hierarchy-above t)
12707 (org-show-following-heading t)
12708 (org-show-siblings (if siblings t org-show-siblings)))
12709 (org-show-context nil))
12710 (when (equal siblings '(16))
12711 (save-excursion
12712 (when (org-up-heading-safe)
12713 (org-show-subtree)
12714 (run-hook-with-args 'org-cycle-hook 'subtree)))))
12716 (defun org-highlight-new-match (beg end)
12717 "Highlight from BEG to END and mark the highlight is an occur headline."
12718 (let ((ov (make-overlay beg end)))
12719 (overlay-put ov 'face 'secondary-selection)
12720 (overlay-put ov 'org-type 'org-occur)
12721 (push ov org-occur-highlights)))
12723 (defun org-remove-occur-highlights (&optional beg end noremove)
12724 "Remove the occur highlights from the buffer.
12725 BEG and END are ignored. If NOREMOVE is nil, remove this function
12726 from the `before-change-functions' in the current buffer."
12727 (interactive)
12728 (unless org-inhibit-highlight-removal
12729 (mapc 'delete-overlay org-occur-highlights)
12730 (setq org-occur-highlights nil)
12731 (setq org-occur-parameters nil)
12732 (unless noremove
12733 (remove-hook 'before-change-functions
12734 'org-remove-occur-highlights 'local))))
12736 ;;;; Priorities
12738 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
12739 "Regular expression matching the priority indicator.")
12741 (defvar org-remove-priority-next-time nil)
12743 (defun org-priority-up ()
12744 "Increase the priority of the current item."
12745 (interactive)
12746 (org-priority 'up))
12748 (defun org-priority-down ()
12749 "Decrease the priority of the current item."
12750 (interactive)
12751 (org-priority 'down))
12753 (defun org-priority (&optional action)
12754 "Change the priority of an item by ARG.
12755 ACTION can be `set', `up', `down', or a character."
12756 (interactive)
12757 (unless org-enable-priority-commands
12758 (error "Priority commands are disabled"))
12759 (setq action (or action 'set))
12760 (let (current new news have remove)
12761 (save-excursion
12762 (org-back-to-heading t)
12763 (if (looking-at org-priority-regexp)
12764 (setq current (string-to-char (match-string 2))
12765 have t))
12766 (cond
12767 ((eq action 'remove)
12768 (setq remove t new ?\ ))
12769 ((or (eq action 'set)
12770 (if (featurep 'xemacs) (characterp action) (integerp action)))
12771 (if (not (eq action 'set))
12772 (setq new action)
12773 (message "Priority %c-%c, SPC to remove: "
12774 org-highest-priority org-lowest-priority)
12775 (save-match-data
12776 (setq new (read-char-exclusive))))
12777 (if (and (= (upcase org-highest-priority) org-highest-priority)
12778 (= (upcase org-lowest-priority) org-lowest-priority))
12779 (setq new (upcase new)))
12780 (cond ((equal new ?\ ) (setq remove t))
12781 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
12782 (error "Priority must be between `%c' and `%c'"
12783 org-highest-priority org-lowest-priority))))
12784 ((eq action 'up)
12785 (setq new (if have
12786 (1- current) ; normal cycling
12787 ;; last priority was empty
12788 (if (eq last-command this-command)
12789 org-lowest-priority ; wrap around empty to lowest
12790 ;; default
12791 (if org-priority-start-cycle-with-default
12792 org-default-priority
12793 (1- org-default-priority))))))
12794 ((eq action 'down)
12795 (setq new (if have
12796 (1+ current) ; normal cycling
12797 ;; last priority was empty
12798 (if (eq last-command this-command)
12799 org-highest-priority ; wrap around empty to highest
12800 ;; default
12801 (if org-priority-start-cycle-with-default
12802 org-default-priority
12803 (1+ org-default-priority))))))
12804 (t (error "Invalid action")))
12805 (if (or (< (upcase new) org-highest-priority)
12806 (> (upcase new) org-lowest-priority))
12807 (if (and (memq action '(up down))
12808 (not have) (not (eq last-command this-command)))
12809 ;; `new' is from default priority
12810 (error
12811 "The default can not be set, see `org-default-priority' why")
12812 ;; normal cycling: `new' is beyond highest/lowest priority
12813 ;; and is wrapped around to the empty priority
12814 (setq remove t)))
12815 (setq news (format "%c" new))
12816 (if have
12817 (if remove
12818 (replace-match "" t t nil 1)
12819 (replace-match news t t nil 2))
12820 (if remove
12821 (error "No priority cookie found in line")
12822 (let ((case-fold-search nil))
12823 (looking-at org-todo-line-regexp))
12824 (if (match-end 2)
12825 (progn
12826 (goto-char (match-end 2))
12827 (insert " [#" news "]"))
12828 (goto-char (match-beginning 3))
12829 (insert "[#" news "] "))))
12830 (org-preserve-lc (org-set-tags nil 'align)))
12831 (if remove
12832 (message "Priority removed")
12833 (message "Priority of current item set to %s" news))))
12835 (defun org-get-priority (s)
12836 "Find priority cookie and return priority."
12837 (if (functionp org-get-priority-function)
12838 (funcall org-get-priority-function)
12839 (save-match-data
12840 (if (not (string-match org-priority-regexp s))
12841 (* 1000 (- org-lowest-priority org-default-priority))
12842 (* 1000 (- org-lowest-priority
12843 (string-to-char (match-string 2 s))))))))
12845 ;;;; Tags
12847 (defvar org-agenda-archives-mode)
12848 (defvar org-map-continue-from nil
12849 "Position from where mapping should continue.
12850 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
12852 (defvar org-scanner-tags nil
12853 "The current tag list while the tags scanner is running.")
12854 (defvar org-trust-scanner-tags nil
12855 "Should `org-get-tags-at' use the tags for the scanner.
12856 This is for internal dynamical scoping only.
12857 When this is non-nil, the function `org-get-tags-at' will return the value
12858 of `org-scanner-tags' instead of building the list by itself. This
12859 can lead to large speed-ups when the tags scanner is used in a file with
12860 many entries, and when the list of tags is retrieved, for example to
12861 obtain a list of properties. Building the tags list for each entry in such
12862 a file becomes an N^2 operation - but with this variable set, it scales
12863 as N.")
12865 (defun org-scan-tags (action matcher todo-only &optional start-level)
12866 "Scan headline tags with inheritance and produce output ACTION.
12868 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
12869 or `agenda' to produce an entry list for an agenda view. It can also be
12870 a Lisp form or a function that should be called at each matched headline, in
12871 this case the return value is a list of all return values from these calls.
12873 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
12874 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
12875 only lines with a not-done TODO keyword are included in the output.
12876 This should be the same variable that was scoped into
12877 and set by `org-make-tags-matcher' when it constructed MATCHER.
12879 START-LEVEL can be a string with asterisks, reducing the scope to
12880 headlines matching this string."
12881 (require 'org-agenda)
12882 (let* ((re (concat "^"
12883 (if start-level
12884 ;; Get the correct level to match
12885 (concat "\\*\\{" (number-to-string start-level) "\\} ")
12886 org-outline-regexp)
12887 " *\\(\\<\\("
12888 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
12889 (org-re
12890 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
12891 (props (list 'face 'default
12892 'done-face 'org-agenda-done
12893 'undone-face 'default
12894 'mouse-face 'highlight
12895 'org-not-done-regexp org-not-done-regexp
12896 'org-todo-regexp org-todo-regexp
12897 'org-complex-heading-regexp org-complex-heading-regexp
12898 'help-echo
12899 (format "mouse-2 or RET jump to org file %s"
12900 (abbreviate-file-name
12901 (or (buffer-file-name (buffer-base-buffer))
12902 (buffer-name (buffer-base-buffer)))))))
12903 (case-fold-search nil)
12904 (org-map-continue-from nil)
12905 lspos tags tags-list
12906 (tags-alist (list (cons 0 org-file-tags)))
12907 (llast 0) rtn rtn1 level category i txt
12908 todo marker entry priority)
12909 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
12910 (setq action (list 'lambda nil action)))
12911 (save-excursion
12912 (goto-char (point-min))
12913 (when (eq action 'sparse-tree)
12914 (org-overview)
12915 (org-remove-occur-highlights))
12916 (while (re-search-forward re nil t)
12917 (setq org-map-continue-from nil)
12918 (catch :skip
12919 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
12920 tags (if (match-end 4) (org-match-string-no-properties 4)))
12921 (goto-char (setq lspos (match-beginning 0)))
12922 (setq level (org-reduced-level (funcall outline-level))
12923 category (org-get-category))
12924 (setq i llast llast level)
12925 ;; remove tag lists from same and sublevels
12926 (while (>= i level)
12927 (when (setq entry (assoc i tags-alist))
12928 (setq tags-alist (delete entry tags-alist)))
12929 (setq i (1- i)))
12930 ;; add the next tags
12931 (when tags
12932 (setq tags (org-split-string tags ":")
12933 tags-alist
12934 (cons (cons level tags) tags-alist)))
12935 ;; compile tags for current headline
12936 (setq tags-list
12937 (if org-use-tag-inheritance
12938 (apply 'append (mapcar 'cdr (reverse tags-alist)))
12939 tags)
12940 org-scanner-tags tags-list)
12941 (when org-use-tag-inheritance
12942 (setcdr (car tags-alist)
12943 (mapcar (lambda (x)
12944 (setq x (copy-sequence x))
12945 (org-add-prop-inherited x))
12946 (cdar tags-alist))))
12947 (when (and tags org-use-tag-inheritance
12948 (or (not (eq t org-use-tag-inheritance))
12949 org-tags-exclude-from-inheritance))
12950 ;; selective inheritance, remove uninherited ones
12951 (setcdr (car tags-alist)
12952 (org-remove-uninherited-tags (cdar tags-alist))))
12953 (when (and
12955 ;; eval matcher only when the todo condition is OK
12956 (and (or (not todo-only) (member todo org-not-done-keywords))
12957 (let ((case-fold-search t) (org-trust-scanner-tags t))
12958 (eval matcher)))
12960 ;; Call the skipper, but return t if it does not skip,
12961 ;; so that the `and' form continues evaluating
12962 (progn
12963 (unless (eq action 'sparse-tree) (org-agenda-skip))
12966 ;; Check if timestamps are deselecting this entry
12967 (or (not todo-only)
12968 (and (member todo org-not-done-keywords)
12969 (or (not org-agenda-tags-todo-honor-ignore-options)
12970 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
12972 ;; Extra check for the archive tag
12973 ;; FIXME: Does the skipper already do this????
12975 (not (member org-archive-tag tags-list))
12976 ;; we have an archive tag, should we use this anyway?
12977 (or (not org-agenda-skip-archived-trees)
12978 (and (eq action 'agenda) org-agenda-archives-mode))))
12980 ;; select this headline
12982 (cond
12983 ((eq action 'sparse-tree)
12984 (and org-highlight-sparse-tree-matches
12985 (org-get-heading) (match-end 0)
12986 (org-highlight-new-match
12987 (match-beginning 1) (match-end 1)))
12988 (org-show-context 'tags-tree))
12989 ((eq action 'agenda)
12990 (setq txt (org-agenda-format-item
12992 (concat
12993 (if (eq org-tags-match-list-sublevels 'indented)
12994 (make-string (1- level) ?.) "")
12995 (org-get-heading))
12996 category
12997 tags-list)
12998 priority (org-get-priority txt))
12999 (goto-char lspos)
13000 (setq marker (org-agenda-new-marker))
13001 (org-add-props txt props
13002 'org-marker marker 'org-hd-marker marker 'org-category category
13003 'todo-state todo
13004 'priority priority 'type "tagsmatch")
13005 (push txt rtn))
13006 ((functionp action)
13007 (setq org-map-continue-from nil)
13008 (save-excursion
13009 (setq rtn1 (funcall action))
13010 (push rtn1 rtn)))
13011 (t (error "Invalid action")))
13013 ;; if we are to skip sublevels, jump to end of subtree
13014 (unless org-tags-match-list-sublevels
13015 (org-end-of-subtree t)
13016 (backward-char 1))))
13017 ;; Get the correct position from where to continue
13018 (if org-map-continue-from
13019 (goto-char org-map-continue-from)
13020 (and (= (point) lspos) (end-of-line 1)))))
13021 (when (and (eq action 'sparse-tree)
13022 (not org-sparse-tree-open-archived-trees))
13023 (org-hide-archived-subtrees (point-min) (point-max)))
13024 (nreverse rtn)))
13026 (defun org-remove-uninherited-tags (tags)
13027 "Remove all tags that are not inherited from the list TAGS."
13028 (cond
13029 ((eq org-use-tag-inheritance t)
13030 (if org-tags-exclude-from-inheritance
13031 (org-delete-all org-tags-exclude-from-inheritance tags)
13032 tags))
13033 ((not org-use-tag-inheritance) nil)
13034 ((stringp org-use-tag-inheritance)
13035 (delq nil (mapcar
13036 (lambda (x)
13037 (if (and (string-match org-use-tag-inheritance x)
13038 (not (member x org-tags-exclude-from-inheritance)))
13039 x nil))
13040 tags)))
13041 ((listp org-use-tag-inheritance)
13042 (delq nil (mapcar
13043 (lambda (x)
13044 (if (member x org-use-tag-inheritance) x nil))
13045 tags)))))
13047 (defun org-match-sparse-tree (&optional todo-only match)
13048 "Create a sparse tree according to tags string MATCH.
13049 MATCH can contain positive and negative selection of tags, like
13050 \"+WORK+URGENT-WITHBOSS\".
13051 If optional argument TODO-ONLY is non-nil, only select lines that are
13052 also TODO lines."
13053 (interactive "P")
13054 (org-prepare-agenda-buffers (list (current-buffer)))
13055 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13057 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13059 (defvar org-cached-props nil)
13060 (defun org-cached-entry-get (pom property)
13061 (if (or (eq t org-use-property-inheritance)
13062 (and (stringp org-use-property-inheritance)
13063 (string-match org-use-property-inheritance property))
13064 (and (listp org-use-property-inheritance)
13065 (member property org-use-property-inheritance)))
13066 ;; Caching is not possible, check it directly
13067 (org-entry-get pom property 'inherit)
13068 ;; Get all properties, so that we can do complicated checks easily
13069 (cdr (assoc property (or org-cached-props
13070 (setq org-cached-props
13071 (org-entry-properties pom)))))))
13073 (defun org-global-tags-completion-table (&optional files)
13074 "Return the list of all tags in all agenda buffer/files.
13075 Optional FILES argument is a list of files to which can be used
13076 instead of the agenda files."
13077 (save-excursion
13078 (org-uniquify
13079 (delq nil
13080 (apply 'append
13081 (mapcar
13082 (lambda (file)
13083 (set-buffer (find-file-noselect file))
13084 (append (org-get-buffer-tags)
13085 (mapcar (lambda (x) (if (stringp (car-safe x))
13086 (list (car-safe x)) nil))
13087 org-tag-alist)))
13088 (if (and files (car files))
13089 files
13090 (org-agenda-files))))))))
13092 (defun org-make-tags-matcher (match)
13093 "Create the TAGS/TODO matcher form for the selection string MATCH.
13095 The variable `todo-only' is scoped dynamically into this function; it will be
13096 set to t if the matcher restricts matching to TODO entries,
13097 otherwise will not be touched.
13099 Returns a cons of the selection string MATCH and the constructed
13100 lisp form implementing the matcher. The matcher is to be
13101 evaluated at an Org entry, with point on the headline,
13102 and returns t if the entry matches the
13103 selection string MATCH. The returned lisp form references
13104 two variables with information about the entry, which must be
13105 bound around the form's evaluation: todo, the TODO keyword at the
13106 entry (or nil of none); and tags-list, the list of all tags at the
13107 entry including inherited ones. Additionally, the category
13108 of the entry (if any) must be specified as the text property
13109 'org-category on the headline.
13111 See also `org-scan-tags'.
13113 (declare (special todo-only))
13114 (unless (boundp 'todo-only)
13115 (error "org-make-tags-matcher expects todo-only to be scoped in"))
13116 (unless match
13117 ;; Get a new match request, with completion
13118 (let ((org-last-tags-completion-table
13119 (org-global-tags-completion-table)))
13120 (setq match (org-completing-read-no-i
13121 "Match: " 'org-tags-completion-function nil nil nil
13122 'org-tags-history))))
13124 ;; Parse the string and create a lisp form
13125 (let ((match0 match)
13126 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
13127 minus tag mm
13128 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
13129 orterms term orlist re-p str-p level-p level-op time-p
13130 prop-p pn pv po gv rest)
13131 (if (string-match "/+" match)
13132 ;; match contains also a todo-matching request
13133 (progn
13134 (setq tagsmatch (substring match 0 (match-beginning 0))
13135 todomatch (substring match (match-end 0)))
13136 (if (string-match "^!" todomatch)
13137 (setq todo-only t todomatch (substring todomatch 1)))
13138 (if (string-match "^\\s-*$" todomatch)
13139 (setq todomatch nil)))
13140 ;; only matching tags
13141 (setq tagsmatch match todomatch nil))
13143 ;; Make the tags matcher
13144 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
13145 (setq tagsmatcher t)
13146 (setq orterms (org-split-string tagsmatch "|") orlist nil)
13147 (while (setq term (pop orterms))
13148 (while (and (equal (substring term -1) "\\") orterms)
13149 (setq term (concat term "|" (pop orterms)))) ; repair bad split
13150 (while (string-match re term)
13151 (setq rest (substring term (match-end 0))
13152 minus (and (match-end 1)
13153 (equal (match-string 1 term) "-"))
13154 tag (save-match-data (replace-regexp-in-string
13155 "\\\\-" "-"
13156 (match-string 2 term)))
13157 re-p (equal (string-to-char tag) ?{)
13158 level-p (match-end 4)
13159 prop-p (match-end 5)
13160 mm (cond
13161 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
13162 (level-p
13163 (setq level-op (org-op-to-function (match-string 3 term)))
13164 `(,level-op level ,(string-to-number
13165 (match-string 4 term))))
13166 (prop-p
13167 (setq pn (match-string 5 term)
13168 po (match-string 6 term)
13169 pv (match-string 7 term)
13170 re-p (equal (string-to-char pv) ?{)
13171 str-p (equal (string-to-char pv) ?\")
13172 time-p (save-match-data
13173 (string-match "^\"[[<].*[]>]\"$" pv))
13174 pv (if (or re-p str-p) (substring pv 1 -1) pv))
13175 (if time-p (setq pv (org-matcher-time pv)))
13176 (setq po (org-op-to-function po (if time-p 'time str-p)))
13177 (cond
13178 ((equal pn "CATEGORY")
13179 (setq gv '(get-text-property (point) 'org-category)))
13180 ((equal pn "TODO")
13181 (setq gv 'todo))
13183 (setq gv `(org-cached-entry-get nil ,pn))))
13184 (if re-p
13185 (if (eq po 'org<>)
13186 `(not (string-match ,pv (or ,gv "")))
13187 `(string-match ,pv (or ,gv "")))
13188 (if str-p
13189 `(,po (or ,gv "") ,pv)
13190 `(,po (string-to-number (or ,gv ""))
13191 ,(string-to-number pv) ))))
13192 (t `(member ,tag tags-list)))
13193 mm (if minus (list 'not mm) mm)
13194 term rest)
13195 (push mm tagsmatcher))
13196 (push (if (> (length tagsmatcher) 1)
13197 (cons 'and tagsmatcher)
13198 (car tagsmatcher))
13199 orlist)
13200 (setq tagsmatcher nil))
13201 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
13202 (setq tagsmatcher
13203 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
13204 ;; Make the todo matcher
13205 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
13206 (setq todomatcher t)
13207 (setq orterms (org-split-string todomatch "|") orlist nil)
13208 (while (setq term (pop orterms))
13209 (while (string-match re term)
13210 (setq minus (and (match-end 1)
13211 (equal (match-string 1 term) "-"))
13212 kwd (match-string 2 term)
13213 re-p (equal (string-to-char kwd) ?{)
13214 term (substring term (match-end 0))
13215 mm (if re-p
13216 `(string-match ,(substring kwd 1 -1) todo)
13217 (list 'equal 'todo kwd))
13218 mm (if minus (list 'not mm) mm))
13219 (push mm todomatcher))
13220 (push (if (> (length todomatcher) 1)
13221 (cons 'and todomatcher)
13222 (car todomatcher))
13223 orlist)
13224 (setq todomatcher nil))
13225 (setq todomatcher (if (> (length orlist) 1)
13226 (cons 'or orlist) (car orlist))))
13228 ;; Return the string and lisp forms of the matcher
13229 (setq matcher (if todomatcher
13230 (list 'and tagsmatcher todomatcher)
13231 tagsmatcher))
13232 (when todo-only
13233 (setq matcher (list 'and '(member todo org-not-done-keywords)
13234 matcher)))
13235 (cons match0 matcher)))
13237 (defun org-op-to-function (op &optional stringp)
13238 "Turn an operator into the appropriate function."
13239 (setq op
13240 (cond
13241 ((equal op "<" ) '(< string< org-time<))
13242 ((equal op ">" ) '(> org-string> org-time>))
13243 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
13244 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
13245 ((member op '("=" "==")) '(= string= org-time=))
13246 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
13247 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
13249 (defun org<> (a b) (not (= a b)))
13250 (defun org-string<= (a b) (or (string= a b) (string< a b)))
13251 (defun org-string>= (a b) (not (string< a b)))
13252 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
13253 (defun org-string<> (a b) (not (string= a b)))
13254 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
13255 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
13256 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
13257 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
13258 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
13259 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
13260 (defun org-2ft (s)
13261 "Convert S to a floating point time.
13262 If S is already a number, just return it. If it is a string, parse
13263 it as a time string and apply `float-time' to it. If S is nil, just return 0."
13264 (cond
13265 ((numberp s) s)
13266 ((stringp s)
13267 (condition-case nil
13268 (float-time (apply 'encode-time (org-parse-time-string s)))
13269 (error 0.)))
13270 (t 0.)))
13272 (defun org-time-today ()
13273 "Time in seconds today at 0:00.
13274 Returns the float number of seconds since the beginning of the
13275 epoch to the beginning of today (00:00)."
13276 (float-time (apply 'encode-time
13277 (append '(0 0 0) (nthcdr 3 (decode-time))))))
13279 (defun org-matcher-time (s)
13280 "Interpret a time comparison value."
13281 (save-match-data
13282 (cond
13283 ((string= s "<now>") (float-time))
13284 ((string= s "<today>") (org-time-today))
13285 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
13286 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
13287 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
13288 (+ (org-time-today)
13289 (* (string-to-number (match-string 1 s))
13290 (cdr (assoc (match-string 2 s)
13291 '(("d" . 86400.0) ("w" . 604800.0)
13292 ("m" . 2678400.0) ("y" . 31557600.0)))))))
13293 (t (org-2ft s)))))
13295 (defun org-match-any-p (re list)
13296 "Does re match any element of list?"
13297 (setq list (mapcar (lambda (x) (string-match re x)) list))
13298 (delq nil list))
13300 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
13301 (defvar org-tags-overlay (make-overlay 1 1))
13302 (org-detach-overlay org-tags-overlay)
13304 (defun org-get-local-tags-at (&optional pos)
13305 "Get a list of tags defined in the current headline."
13306 (org-get-tags-at pos 'local))
13308 (defun org-get-local-tags ()
13309 "Get a list of tags defined in the current headline."
13310 (org-get-tags-at nil 'local))
13312 (defun org-get-tags-at (&optional pos local)
13313 "Get a list of all headline tags applicable at POS.
13314 POS defaults to point. If tags are inherited, the list contains
13315 the targets in the same sequence as the headlines appear, i.e.
13316 the tags of the current headline come last.
13317 When LOCAL is non-nil, only return tags from the current headline,
13318 ignore inherited ones."
13319 (interactive)
13320 (if (and org-trust-scanner-tags
13321 (or (not pos) (equal pos (point)))
13322 (not local))
13323 org-scanner-tags
13324 (let (tags ltags lastpos parent)
13325 (save-excursion
13326 (save-restriction
13327 (widen)
13328 (goto-char (or pos (point)))
13329 (save-match-data
13330 (catch 'done
13331 (condition-case nil
13332 (progn
13333 (org-back-to-heading t)
13334 (while (not (equal lastpos (point)))
13335 (setq lastpos (point))
13336 (when (looking-at
13337 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
13338 (setq ltags (org-split-string
13339 (org-match-string-no-properties 1) ":"))
13340 (when parent
13341 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
13342 (setq tags (append
13343 (if parent
13344 (org-remove-uninherited-tags ltags)
13345 ltags)
13346 tags)))
13347 (or org-use-tag-inheritance (throw 'done t))
13348 (if local (throw 'done t))
13349 (or (org-up-heading-safe) (error nil))
13350 (setq parent t)))
13351 (error nil)))))
13352 (if local
13353 tags
13354 (append (org-remove-uninherited-tags org-file-tags) tags))))))
13356 (defun org-add-prop-inherited (s)
13357 (add-text-properties 0 (length s) '(inherited t) s)
13360 (defun org-toggle-tag (tag &optional onoff)
13361 "Toggle the tag TAG for the current line.
13362 If ONOFF is `on' or `off', don't toggle but set to this state."
13363 (let (res current)
13364 (save-excursion
13365 (org-back-to-heading t)
13366 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
13367 (point-at-eol) t)
13368 (progn
13369 (setq current (match-string 1))
13370 (replace-match ""))
13371 (setq current ""))
13372 (setq current (nreverse (org-split-string current ":")))
13373 (cond
13374 ((eq onoff 'on)
13375 (setq res t)
13376 (or (member tag current) (push tag current)))
13377 ((eq onoff 'off)
13378 (or (not (member tag current)) (setq current (delete tag current))))
13379 (t (if (member tag current)
13380 (setq current (delete tag current))
13381 (setq res t)
13382 (push tag current))))
13383 (end-of-line 1)
13384 (if current
13385 (progn
13386 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
13387 (org-set-tags nil t))
13388 (delete-horizontal-space))
13389 (run-hooks 'org-after-tags-change-hook))
13390 res))
13392 (defun org-align-tags-here (to-col)
13393 ;; Assumes that this is a headline
13394 (let ((pos (point)) (col (current-column)) ncol tags-l p)
13395 (beginning-of-line 1)
13396 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13397 (< pos (match-beginning 2)))
13398 (progn
13399 (setq tags-l (- (match-end 2) (match-beginning 2)))
13400 (goto-char (match-beginning 1))
13401 (insert " ")
13402 (delete-region (point) (1+ (match-beginning 2)))
13403 (setq ncol (max (current-column)
13404 (1+ col)
13405 (if (> to-col 0)
13406 to-col
13407 (- (abs to-col) tags-l))))
13408 (setq p (point))
13409 (insert (make-string (- ncol (current-column)) ?\ ))
13410 (setq ncol (current-column))
13411 (when indent-tabs-mode (tabify p (point-at-eol)))
13412 (org-move-to-column (min ncol col) t))
13413 (goto-char pos))))
13415 (defun org-set-tags-command (&optional arg just-align)
13416 "Call the set-tags command for the current entry."
13417 (interactive "P")
13418 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
13419 (org-set-tags arg just-align)
13420 (save-excursion
13421 (org-back-to-heading t)
13422 (org-set-tags arg just-align))))
13424 (defun org-set-tags-to (data)
13425 "Set the tags of the current entry to DATA, replacing the current tags.
13426 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
13427 If DATA is nil or the empty string, any tags will be removed."
13428 (interactive "sTags: ")
13429 (setq data
13430 (cond
13431 ((eq data nil) "")
13432 ((equal data "") "")
13433 ((stringp data)
13434 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
13435 ":"))
13436 ((listp data)
13437 (concat ":" (mapconcat 'identity data ":") ":"))
13438 (t nil)))
13439 (when data
13440 (save-excursion
13441 (org-back-to-heading t)
13442 (when (looking-at org-complex-heading-regexp)
13443 (if (match-end 5)
13444 (progn
13445 (goto-char (match-beginning 5))
13446 (insert data)
13447 (delete-region (point) (point-at-eol))
13448 (org-set-tags nil 'align))
13449 (goto-char (point-at-eol))
13450 (insert " " data)
13451 (org-set-tags nil 'align)))
13452 (beginning-of-line 1)
13453 (if (looking-at ".*?\\([ \t]+\\)$")
13454 (delete-region (match-beginning 1) (match-end 1))))))
13456 (defun org-align-all-tags ()
13457 "Align the tags i all headings."
13458 (interactive)
13459 (save-excursion
13460 (or (ignore-errors (org-back-to-heading t))
13461 (outline-next-heading))
13462 (if (org-at-heading-p)
13463 (org-set-tags t)
13464 (message "No headings"))))
13466 (defvar org-indent-indentation-per-level)
13467 (defun org-set-tags (&optional arg just-align)
13468 "Set the tags for the current headline.
13469 With prefix ARG, realign all tags in headings in the current buffer."
13470 (interactive "P")
13471 (let* ((re org-outline-regexp-bol)
13472 (current (unless arg (org-get-tags-string)))
13473 (col (current-column))
13474 (org-setting-tags t)
13475 table current-tags inherited-tags ; computed below when needed
13476 tags p0 c0 c1 rpl di tc level)
13477 (if arg
13478 (save-excursion
13479 (goto-char (point-min))
13480 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
13481 (while (re-search-forward re nil t)
13482 (org-set-tags nil t)
13483 (end-of-line 1)))
13484 (message "All tags realigned to column %d" org-tags-column))
13485 (if just-align
13486 (setq tags current)
13487 ;; Get a new set of tags from the user
13488 (save-excursion
13489 (setq table (append org-tag-persistent-alist
13490 (or org-tag-alist (org-get-buffer-tags))
13491 (and
13492 org-complete-tags-always-offer-all-agenda-tags
13493 (org-global-tags-completion-table
13494 (org-agenda-files))))
13495 org-last-tags-completion-table table
13496 current-tags (org-split-string current ":")
13497 inherited-tags (nreverse
13498 (nthcdr (length current-tags)
13499 (nreverse (org-get-tags-at))))
13500 tags
13501 (if (or (eq t org-use-fast-tag-selection)
13502 (and org-use-fast-tag-selection
13503 (delq nil (mapcar 'cdr table))))
13504 (org-fast-tag-selection
13505 current-tags inherited-tags table
13506 (if org-fast-tag-selection-include-todo
13507 org-todo-key-alist))
13508 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
13509 (org-trim
13510 (org-icompleting-read "Tags: "
13511 'org-tags-completion-function
13512 nil nil current 'org-tags-history))))))
13513 (while (string-match "[-+&]+" tags)
13514 ;; No boolean logic, just a list
13515 (setq tags (replace-match ":" t t tags))))
13517 (setq tags (replace-regexp-in-string "[,]" ":" tags))
13519 (if org-tags-sort-function
13520 (setq tags (mapconcat 'identity
13521 (sort (org-split-string
13522 tags (org-re "[^[:alnum:]_@#%]+"))
13523 org-tags-sort-function) ":")))
13525 (if (string-match "\\`[\t ]*\\'" tags)
13526 (setq tags "")
13527 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
13528 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
13530 ;; Insert new tags at the correct column
13531 (beginning-of-line 1)
13532 (setq level (or (and (looking-at org-outline-regexp)
13533 (- (match-end 0) (point) 1))
13535 (cond
13536 ((and (equal current "") (equal tags "")))
13537 ((re-search-forward
13538 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
13539 (point-at-eol) t)
13540 (if (equal tags "")
13541 (setq rpl "")
13542 (goto-char (match-beginning 0))
13543 (setq c0 (current-column)
13544 ;; compute offset for the case of org-indent-mode active
13545 di (if org-indent-mode
13546 (* (1- org-indent-indentation-per-level) (1- level))
13548 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
13549 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
13550 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
13551 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
13552 (replace-match rpl t t)
13553 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
13554 tags)
13555 (t (error "Tags alignment failed")))
13556 (org-move-to-column col)
13557 (unless just-align
13558 (run-hooks 'org-after-tags-change-hook)))))
13560 (defun org-change-tag-in-region (beg end tag off)
13561 "Add or remove TAG for each entry in the region.
13562 This works in the agenda, and also in an org-mode buffer."
13563 (interactive
13564 (list (region-beginning) (region-end)
13565 (let ((org-last-tags-completion-table
13566 (if (derived-mode-p 'org-mode)
13567 (org-get-buffer-tags)
13568 (org-global-tags-completion-table))))
13569 (org-icompleting-read
13570 "Tag: " 'org-tags-completion-function nil nil nil
13571 'org-tags-history))
13572 (progn
13573 (message "[s]et or [r]emove? ")
13574 (equal (read-char-exclusive) ?r))))
13575 (if (fboundp 'deactivate-mark) (deactivate-mark))
13576 (let ((agendap (equal major-mode 'org-agenda-mode))
13577 l1 l2 m buf pos newhead (cnt 0))
13578 (goto-char end)
13579 (setq l2 (1- (org-current-line)))
13580 (goto-char beg)
13581 (setq l1 (org-current-line))
13582 (loop for l from l1 to l2 do
13583 (org-goto-line l)
13584 (setq m (get-text-property (point) 'org-hd-marker))
13585 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
13586 (and agendap m))
13587 (setq buf (if agendap (marker-buffer m) (current-buffer))
13588 pos (if agendap m (point)))
13589 (with-current-buffer buf
13590 (save-excursion
13591 (save-restriction
13592 (goto-char pos)
13593 (setq cnt (1+ cnt))
13594 (org-toggle-tag tag (if off 'off 'on))
13595 (setq newhead (org-get-heading)))))
13596 (and agendap (org-agenda-change-all-lines newhead m))))
13597 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
13599 (defun org-tags-completion-function (string predicate &optional flag)
13600 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
13601 (confirm (lambda (x) (stringp (car x)))))
13602 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
13603 (setq s1 (match-string 1 string)
13604 s2 (match-string 2 string))
13605 (setq s1 "" s2 string))
13606 (cond
13607 ((eq flag nil)
13608 ;; try completion
13609 (setq rtn (try-completion s2 ctable confirm))
13610 (if (stringp rtn)
13611 (setq rtn
13612 (concat s1 s2 (substring rtn (length s2))
13613 (if (and org-add-colon-after-tag-completion
13614 (assoc rtn ctable))
13615 ":" ""))))
13616 rtn)
13617 ((eq flag t)
13618 ;; all-completions
13619 (all-completions s2 ctable confirm)
13621 ((eq flag 'lambda)
13622 ;; exact match?
13623 (assoc s2 ctable)))
13626 (defun org-fast-tag-insert (kwd tags face &optional end)
13627 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
13628 (insert (format "%-12s" (concat kwd ":"))
13629 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
13630 (or end "")))
13632 (defun org-fast-tag-show-exit (flag)
13633 (save-excursion
13634 (org-goto-line 3)
13635 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
13636 (replace-match ""))
13637 (when flag
13638 (end-of-line 1)
13639 (org-move-to-column (- (window-width) 19) t)
13640 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
13642 (defun org-set-current-tags-overlay (current prefix)
13643 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
13644 (if (featurep 'xemacs)
13645 (org-overlay-display org-tags-overlay (concat prefix s)
13646 'secondary-selection)
13647 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
13648 (org-overlay-display org-tags-overlay (concat prefix s)))))
13650 (defvar org-last-tag-selection-key nil)
13651 (defun org-fast-tag-selection (current inherited table &optional todo-table)
13652 "Fast tag selection with single keys.
13653 CURRENT is the current list of tags in the headline, INHERITED is the
13654 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
13655 possibly with grouping information. TODO-TABLE is a similar table with
13656 TODO keywords, should these have keys assigned to them.
13657 If the keys are nil, a-z are automatically assigned.
13658 Returns the new tags string, or nil to not change the current settings."
13659 (let* ((fulltable (append table todo-table))
13660 (maxlen (apply 'max (mapcar
13661 (lambda (x)
13662 (if (stringp (car x)) (string-width (car x)) 0))
13663 fulltable)))
13664 (buf (current-buffer))
13665 (expert (eq org-fast-tag-selection-single-key 'expert))
13666 (buffer-tags nil)
13667 (fwidth (+ maxlen 3 1 3))
13668 (ncol (/ (- (window-width) 4) fwidth))
13669 (i-face 'org-done)
13670 (c-face 'org-todo)
13671 tg cnt e c char c1 c2 ntable tbl rtn
13672 ov-start ov-end ov-prefix
13673 (exit-after-next org-fast-tag-selection-single-key)
13674 (done-keywords org-done-keywords)
13675 groups ingroup)
13676 (save-excursion
13677 (beginning-of-line 1)
13678 (if (looking-at
13679 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13680 (setq ov-start (match-beginning 1)
13681 ov-end (match-end 1)
13682 ov-prefix "")
13683 (setq ov-start (1- (point-at-eol))
13684 ov-end (1+ ov-start))
13685 (skip-chars-forward "^\n\r")
13686 (setq ov-prefix
13687 (concat
13688 (buffer-substring (1- (point)) (point))
13689 (if (> (current-column) org-tags-column)
13691 (make-string (- org-tags-column (current-column)) ?\ ))))))
13692 (move-overlay org-tags-overlay ov-start ov-end)
13693 (save-window-excursion
13694 (if expert
13695 (set-buffer (get-buffer-create " *Org tags*"))
13696 (delete-other-windows)
13697 (split-window-vertically)
13698 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
13699 (erase-buffer)
13700 (org-set-local 'org-done-keywords done-keywords)
13701 (org-fast-tag-insert "Inherited" inherited i-face "\n")
13702 (org-fast-tag-insert "Current" current c-face "\n\n")
13703 (org-fast-tag-show-exit exit-after-next)
13704 (org-set-current-tags-overlay current ov-prefix)
13705 (setq tbl fulltable char ?a cnt 0)
13706 (while (setq e (pop tbl))
13707 (cond
13708 ((equal (car e) :startgroup)
13709 (push '() groups) (setq ingroup t)
13710 (when (not (= cnt 0))
13711 (setq cnt 0)
13712 (insert "\n"))
13713 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
13714 ((equal (car e) :endgroup)
13715 (setq ingroup nil cnt 0)
13716 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
13717 ((equal e '(:newline))
13718 (when (not (= cnt 0))
13719 (setq cnt 0)
13720 (insert "\n")
13721 (setq e (car tbl))
13722 (while (equal (car tbl) '(:newline))
13723 (insert "\n")
13724 (setq tbl (cdr tbl)))))
13726 (setq tg (copy-sequence (car e)) c2 nil)
13727 (if (cdr e)
13728 (setq c (cdr e))
13729 ;; automatically assign a character.
13730 (setq c1 (string-to-char
13731 (downcase (substring
13732 tg (if (= (string-to-char tg) ?@) 1 0)))))
13733 (if (or (rassoc c1 ntable) (rassoc c1 table))
13734 (while (or (rassoc char ntable) (rassoc char table))
13735 (setq char (1+ char)))
13736 (setq c2 c1))
13737 (setq c (or c2 char)))
13738 (if ingroup (push tg (car groups)))
13739 (setq tg (org-add-props tg nil 'face
13740 (cond
13741 ((not (assoc tg table))
13742 (org-get-todo-face tg))
13743 ((member tg current) c-face)
13744 ((member tg inherited) i-face)
13745 (t nil))))
13746 (if (and (= cnt 0) (not ingroup)) (insert " "))
13747 (insert "[" c "] " tg (make-string
13748 (- fwidth 4 (length tg)) ?\ ))
13749 (push (cons tg c) ntable)
13750 (when (= (setq cnt (1+ cnt)) ncol)
13751 (insert "\n")
13752 (if ingroup (insert " "))
13753 (setq cnt 0)))))
13754 (setq ntable (nreverse ntable))
13755 (insert "\n")
13756 (goto-char (point-min))
13757 (if (not expert) (org-fit-window-to-buffer))
13758 (setq rtn
13759 (catch 'exit
13760 (while t
13761 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
13762 (if (not groups) "no " "")
13763 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
13764 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13765 (setq org-last-tag-selection-key c)
13766 (cond
13767 ((= c ?\r) (throw 'exit t))
13768 ((= c ?!)
13769 (setq groups (not groups))
13770 (goto-char (point-min))
13771 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
13772 ((= c ?\C-c)
13773 (if (not expert)
13774 (org-fast-tag-show-exit
13775 (setq exit-after-next (not exit-after-next)))
13776 (setq expert nil)
13777 (delete-other-windows)
13778 (set-window-buffer (split-window-vertically) " *Org tags*")
13779 (org-switch-to-buffer-other-window " *Org tags*")
13780 (org-fit-window-to-buffer)))
13781 ((or (= c ?\C-g)
13782 (and (= c ?q) (not (rassoc c ntable))))
13783 (org-detach-overlay org-tags-overlay)
13784 (setq quit-flag t))
13785 ((= c ?\ )
13786 (setq current nil)
13787 (if exit-after-next (setq exit-after-next 'now)))
13788 ((= c ?\t)
13789 (condition-case nil
13790 (setq tg (org-icompleting-read
13791 "Tag: "
13792 (or buffer-tags
13793 (with-current-buffer buf
13794 (org-get-buffer-tags)))))
13795 (quit (setq tg "")))
13796 (when (string-match "\\S-" tg)
13797 (add-to-list 'buffer-tags (list tg))
13798 (if (member tg current)
13799 (setq current (delete tg current))
13800 (push tg current)))
13801 (if exit-after-next (setq exit-after-next 'now)))
13802 ((setq e (rassoc c todo-table) tg (car e))
13803 (with-current-buffer buf
13804 (save-excursion (org-todo tg)))
13805 (if exit-after-next (setq exit-after-next 'now)))
13806 ((setq e (rassoc c ntable) tg (car e))
13807 (if (member tg current)
13808 (setq current (delete tg current))
13809 (loop for g in groups do
13810 (if (member tg g)
13811 (mapc (lambda (x)
13812 (setq current (delete x current)))
13813 g)))
13814 (push tg current))
13815 (if exit-after-next (setq exit-after-next 'now))))
13817 ;; Create a sorted list
13818 (setq current
13819 (sort current
13820 (lambda (a b)
13821 (assoc b (cdr (memq (assoc a ntable) ntable))))))
13822 (if (eq exit-after-next 'now) (throw 'exit t))
13823 (goto-char (point-min))
13824 (beginning-of-line 2)
13825 (delete-region (point) (point-at-eol))
13826 (org-fast-tag-insert "Current" current c-face)
13827 (org-set-current-tags-overlay current ov-prefix)
13828 (while (re-search-forward
13829 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
13830 (setq tg (match-string 1))
13831 (add-text-properties
13832 (match-beginning 1) (match-end 1)
13833 (list 'face
13834 (cond
13835 ((member tg current) c-face)
13836 ((member tg inherited) i-face)
13837 (t (get-text-property (match-beginning 1) 'face))))))
13838 (goto-char (point-min)))))
13839 (org-detach-overlay org-tags-overlay)
13840 (if rtn
13841 (mapconcat 'identity current ":")
13842 nil))))
13844 (defun org-get-tags-string ()
13845 "Get the TAGS string in the current headline."
13846 (unless (org-at-heading-p t)
13847 (error "Not on a heading"))
13848 (save-excursion
13849 (beginning-of-line 1)
13850 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13851 (org-match-string-no-properties 1)
13852 "")))
13854 (defun org-get-tags ()
13855 "Get the list of tags specified in the current headline."
13856 (org-split-string (org-get-tags-string) ":"))
13858 (defun org-get-buffer-tags ()
13859 "Get a table of all tags used in the buffer, for completion."
13860 (let (tags)
13861 (save-excursion
13862 (goto-char (point-min))
13863 (while (re-search-forward
13864 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
13865 (when (equal (char-after (point-at-bol 0)) ?*)
13866 (mapc (lambda (x) (add-to-list 'tags x))
13867 (org-split-string (org-match-string-no-properties 1) ":")))))
13868 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
13869 (mapcar 'list tags)))
13871 ;;;; The mapping API
13873 ;;;###autoload
13874 (defun org-map-entries (func &optional match scope &rest skip)
13875 "Call FUNC at each headline selected by MATCH in SCOPE.
13877 FUNC is a function or a lisp form. The function will be called without
13878 arguments, with the cursor positioned at the beginning of the headline.
13879 The return values of all calls to the function will be collected and
13880 returned as a list.
13882 The call to FUNC will be wrapped into a save-excursion form, so FUNC
13883 does not need to preserve point. After evaluation, the cursor will be
13884 moved to the end of the line (presumably of the headline of the
13885 processed entry) and search continues from there. Under some
13886 circumstances, this may not produce the wanted results. For example,
13887 if you have removed (e.g. archived) the current (sub)tree it could
13888 mean that the next entry will be skipped entirely. In such cases, you
13889 can specify the position from where search should continue by making
13890 FUNC set the variable `org-map-continue-from' to the desired buffer
13891 position.
13893 MATCH is a tags/property/todo match as it is used in the agenda tags view.
13894 Only headlines that are matched by this query will be considered during
13895 the iteration. When MATCH is nil or t, all headlines will be
13896 visited by the iteration.
13898 SCOPE determines the scope of this command. It can be any of:
13900 nil The current buffer, respecting the restriction if any
13901 tree The subtree started with the entry at point
13902 region The entries within the active region, if any
13903 region-start-level
13904 The entries within the active region, but only those at
13905 the same level than the first one.
13906 file The current buffer, without restriction
13907 file-with-archives
13908 The current buffer, and any archives associated with it
13909 agenda All agenda files
13910 agenda-with-archives
13911 All agenda files with any archive files associated with them
13912 \(file1 file2 ...)
13913 If this is a list, all files in the list will be scanned
13915 The remaining args are treated as settings for the skipping facilities of
13916 the scanner. The following items can be given here:
13918 archive skip trees with the archive tag.
13919 comment skip trees with the COMMENT keyword
13920 function or Emacs Lisp form:
13921 will be used as value for `org-agenda-skip-function', so whenever
13922 the function returns t, FUNC will not be called for that
13923 entry and search will continue from the point where the
13924 function leaves it.
13926 If your function needs to retrieve the tags including inherited tags
13927 at the *current* entry, you can use the value of the variable
13928 `org-scanner-tags' which will be much faster than getting the value
13929 with `org-get-tags-at'. If your function gets properties with
13930 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
13931 to t around the call to `org-entry-properties' to get the same speedup.
13932 Note that if your function moves around to retrieve tags and properties at
13933 a *different* entry, you cannot use these techniques."
13934 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
13935 (not (org-region-active-p)))
13936 (let* ((org-agenda-archives-mode nil) ; just to make sure
13937 (org-agenda-skip-archived-trees (memq 'archive skip))
13938 (org-agenda-skip-comment-trees (memq 'comment skip))
13939 (org-agenda-skip-function
13940 (car (org-delete-all '(comment archive) skip)))
13941 (org-tags-match-list-sublevels t)
13942 (start-level (eq scope 'region-start-level))
13943 matcher file res
13944 org-todo-keywords-for-agenda
13945 org-done-keywords-for-agenda
13946 org-todo-keyword-alist-for-agenda
13947 org-drawers-for-agenda
13948 org-tag-alist-for-agenda
13949 todo-only)
13951 (cond
13952 ((eq match t) (setq matcher t))
13953 ((eq match nil) (setq matcher t))
13954 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
13956 (save-excursion
13957 (save-restriction
13958 (cond ((eq scope 'tree)
13959 (org-back-to-heading t)
13960 (org-narrow-to-subtree)
13961 (setq scope nil))
13962 ((and (or (eq scope 'region) (eq scope 'region-start-level))
13963 (org-region-active-p))
13964 ;; If needed, set start-level to a string like "2"
13965 (when start-level
13966 (save-excursion
13967 (goto-char (region-beginning))
13968 (unless (org-at-heading-p) (outline-next-heading))
13969 (setq start-level (org-current-level))))
13970 (narrow-to-region (region-beginning)
13971 (save-excursion
13972 (goto-char (region-end))
13973 (unless (and (bolp) (org-at-heading-p))
13974 (outline-next-heading))
13975 (point)))
13976 (setq scope nil)))
13978 (if (not scope)
13979 (progn
13980 (org-prepare-agenda-buffers
13981 (list (buffer-file-name (current-buffer))))
13982 (setq res (org-scan-tags func matcher todo-only start-level)))
13983 ;; Get the right scope
13984 (cond
13985 ((and scope (listp scope) (symbolp (car scope)))
13986 (setq scope (eval scope)))
13987 ((eq scope 'agenda)
13988 (setq scope (org-agenda-files t)))
13989 ((eq scope 'agenda-with-archives)
13990 (setq scope (org-agenda-files t))
13991 (setq scope (org-add-archive-files scope)))
13992 ((eq scope 'file)
13993 (setq scope (list (buffer-file-name))))
13994 ((eq scope 'file-with-archives)
13995 (setq scope (org-add-archive-files (list (buffer-file-name))))))
13996 (org-prepare-agenda-buffers scope)
13997 (while (setq file (pop scope))
13998 (with-current-buffer (org-find-base-buffer-visiting file)
13999 (save-excursion
14000 (save-restriction
14001 (widen)
14002 (goto-char (point-min))
14003 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
14004 res)))
14006 ;;;; Properties
14008 ;;; Setting and retrieving properties
14010 (defconst org-special-properties
14011 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
14012 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM")
14013 "The special properties valid in Org-mode.
14015 These are properties that are not defined in the property drawer,
14016 but in some other way.")
14018 (defconst org-default-properties
14019 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
14020 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
14021 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
14022 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
14023 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
14024 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
14025 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
14026 "Some properties that are used by Org-mode for various purposes.
14027 Being in this list makes sure that they are offered for completion.")
14029 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
14030 "Regular expression matching the first line of a property drawer.")
14032 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
14033 "Regular expression matching the last line of a property drawer.")
14035 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
14036 "Regular expression matching the first line of a property drawer.")
14038 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
14039 "Regular expression matching the first line of a property drawer.")
14041 (defconst org-property-drawer-re
14042 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
14043 org-property-end-re "\\)\n?")
14044 "Matches an entire property drawer.")
14046 (defconst org-clock-drawer-re
14047 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
14048 org-property-end-re "\\)\n?")
14049 "Matches an entire clock drawer.")
14051 (defsubst org-re-property (property)
14052 "Return a regexp matching PROPERTY.
14053 Match group 1 will be set to the value "
14054 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
14056 (defun org-property-action ()
14057 "Do an action on properties."
14058 (interactive)
14059 (let (c)
14060 (org-at-property-p)
14061 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14062 (setq c (read-char-exclusive))
14063 (cond
14064 ((equal c ?s)
14065 (call-interactively 'org-set-property))
14066 ((equal c ?d)
14067 (call-interactively 'org-delete-property))
14068 ((equal c ?D)
14069 (call-interactively 'org-delete-property-globally))
14070 ((equal c ?c)
14071 (call-interactively 'org-compute-property-at-point))
14072 (t (error "No such property action %c" c)))))
14074 (defun org-set-effort (&optional value)
14075 "Set the effort property of the current entry.
14076 With numerical prefix arg, use the nth allowed value, 0 stands for the 10th
14077 allowed value."
14078 (interactive "P")
14079 (if (equal value 0) (setq value 10))
14080 (let* ((completion-ignore-case t)
14081 (prop org-effort-property)
14082 (cur (org-entry-get nil prop))
14083 (allowed (org-property-get-allowed-values nil prop 'table))
14084 (existing (mapcar 'list (org-property-values prop)))
14086 (val (cond
14087 ((stringp value) value)
14088 ((and allowed (integerp value))
14089 (or (car (nth (1- value) allowed))
14090 (car (org-last allowed))))
14091 (allowed
14092 (message "Select 1-9,0, [RET%s]: %s"
14093 (if cur (concat "=" cur) "")
14094 (mapconcat 'car allowed " "))
14095 (setq rpl (read-char-exclusive))
14096 (if (equal rpl ?\r)
14098 (setq rpl (- rpl ?0))
14099 (if (equal rpl 0) (setq rpl 10))
14100 (if (and (> rpl 0) (<= rpl (length allowed)))
14101 (car (nth (1- rpl) allowed))
14102 (org-completing-read "Effort: " allowed nil))))
14104 (let (org-completion-use-ido org-completion-use-iswitchb)
14105 (org-completing-read
14106 (concat "Effort " (if (and cur (string-match "\\S-" cur))
14107 (concat "[" cur "]") "")
14108 ": ")
14109 existing nil nil "" nil cur))))))
14110 (unless (equal (org-entry-get nil prop) val)
14111 (org-entry-put nil prop val))
14112 (message "%s is now %s" prop val)))
14114 (defun org-at-property-p ()
14115 "Is cursor inside a property drawer?"
14116 (save-excursion
14117 (beginning-of-line 1)
14118 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
14119 (save-match-data ;; Used by calling procedures
14120 (let ((p (point))
14121 (range (unless (org-before-first-heading-p)
14122 (org-get-property-block))))
14123 (and range (<= (car range) p) (< p (cdr range))))))))
14125 (defun org-get-property-block (&optional beg end force)
14126 "Return the (beg . end) range of the body of the property drawer.
14127 BEG and END can be beginning and end of subtree, if not given
14128 they will be found.
14129 If the drawer does not exist and FORCE is non-nil, create the drawer."
14130 (catch 'exit
14131 (save-excursion
14132 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
14133 (end (or end (progn (outline-next-heading) (point)))))
14134 (goto-char beg)
14135 (if (re-search-forward org-property-start-re end t)
14136 (setq beg (1+ (match-end 0)))
14137 (if force
14138 (save-excursion
14139 (org-insert-property-drawer)
14140 (setq end (progn (outline-next-heading) (point))))
14141 (throw 'exit nil))
14142 (goto-char beg)
14143 (if (re-search-forward org-property-start-re end t)
14144 (setq beg (1+ (match-end 0)))))
14145 (if (re-search-forward org-property-end-re end t)
14146 (setq end (match-beginning 0))
14147 (or force (throw 'exit nil))
14148 (goto-char beg)
14149 (setq end beg)
14150 (org-indent-line-function)
14151 (insert ":END:\n"))
14152 (cons beg end)))))
14154 (defun org-entry-properties (&optional pom which specific)
14155 "Get all properties of the entry at point-or-marker POM.
14156 This includes the TODO keyword, the tags, time strings for deadline,
14157 scheduled, and clocking, and any additional properties defined in the
14158 entry. The return value is an alist, keys may occur multiple times
14159 if the property key was used several times.
14160 POM may also be nil, in which case the current entry is used.
14161 If WHICH is nil or `all', get all properties. If WHICH is
14162 `special' or `standard', only get that subclass. If WHICH
14163 is a string only get exactly this property. SPECIFIC can be a string, the
14164 specific property we are interested in. Specifying it can speed
14165 things up because then unnecessary parsing is avoided."
14166 (setq which (or which 'all))
14167 (org-with-point-at pom
14168 (let ((clockstr (substring org-clock-string 0 -1))
14169 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
14170 (case-fold-search nil)
14171 beg end range props sum-props key key1 value string clocksum)
14172 (save-excursion
14173 (when (condition-case nil
14174 (and (derived-mode-p 'org-mode) (org-back-to-heading t))
14175 (error nil))
14176 (setq beg (point))
14177 (setq sum-props (get-text-property (point) 'org-summaries))
14178 (setq clocksum (get-text-property (point) :org-clock-minutes))
14179 (outline-next-heading)
14180 (setq end (point))
14181 (when (memq which '(all special))
14182 ;; Get the special properties, like TODO and tags
14183 (goto-char beg)
14184 (when (and (or (not specific) (string= specific "TODO"))
14185 (looking-at org-todo-line-regexp) (match-end 2))
14186 (push (cons "TODO" (org-match-string-no-properties 2)) props))
14187 (when (and (or (not specific) (string= specific "PRIORITY"))
14188 (looking-at org-priority-regexp))
14189 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
14190 (when (or (not specific) (string= specific "FILE"))
14191 (push (cons "FILE" buffer-file-name) props))
14192 (when (and (or (not specific) (string= specific "TAGS"))
14193 (setq value (org-get-tags-string))
14194 (string-match "\\S-" value))
14195 (push (cons "TAGS" value) props))
14196 (when (and (or (not specific) (string= specific "ALLTAGS"))
14197 (setq value (org-get-tags-at)))
14198 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
14199 ":"))
14200 props))
14201 (when (or (not specific) (string= specific "BLOCKED"))
14202 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
14203 (when (or (not specific)
14204 (member specific
14205 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
14206 "TIMESTAMP" "TIMESTAMP_IA")))
14207 (catch 'match
14208 (while (re-search-forward org-maybe-keyword-time-regexp end t)
14209 (setq key (if (match-end 1)
14210 (substring (org-match-string-no-properties 1)
14211 0 -1))
14212 string (if (equal key clockstr)
14213 (org-no-properties
14214 (org-trim
14215 (buffer-substring
14216 (match-beginning 3) (goto-char
14217 (point-at-eol)))))
14218 (substring (org-match-string-no-properties 3)
14219 1 -1)))
14220 ;; Get the correct property name from the key. This is
14221 ;; necessary if the user has configured time keywords.
14222 (setq key1 (concat key ":"))
14223 (cond
14224 ((not key)
14225 (setq key
14226 (if (= (char-after (match-beginning 3)) ?\[)
14227 "TIMESTAMP_IA" "TIMESTAMP")))
14228 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
14229 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
14230 ((equal key1 org-closed-string) (setq key "CLOSED"))
14231 ((equal key1 org-clock-string) (setq key "CLOCK")))
14232 (if (and specific (equal key specific) (not (equal key "CLOCK")))
14233 (progn
14234 (push (cons key string) props)
14235 ;; no need to search further if match is found
14236 (throw 'match t))
14237 (when (or (equal key "CLOCK") (not (assoc key props)))
14238 (push (cons key string) props))))))
14241 (when (memq which '(all standard))
14242 ;; Get the standard properties, like :PROP: ...
14243 (setq range (org-get-property-block beg end))
14244 (when range
14245 (goto-char (car range))
14246 (while (re-search-forward
14247 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
14248 (cdr range) t)
14249 (setq key (org-match-string-no-properties 1)
14250 value (org-trim (or (org-match-string-no-properties 2) "")))
14251 (unless (member key excluded)
14252 (push (cons key (or value "")) props)))))
14253 (if clocksum
14254 (push (cons "CLOCKSUM"
14255 (org-columns-number-to-string (/ (float clocksum) 60.)
14256 'add_times))
14257 props))
14258 (unless (assoc "CATEGORY" props)
14259 (push (cons "CATEGORY" (org-get-category)) props))
14260 (append sum-props (nreverse props)))))))
14262 (defun org-entry-get (pom property &optional inherit literal-nil)
14263 "Get value of PROPERTY for entry at point-or-marker POM.
14264 If INHERIT is non-nil and the entry does not have the property,
14265 then also check higher levels of the hierarchy.
14266 If INHERIT is the symbol `selective', use inheritance only if the setting
14267 in `org-use-property-inheritance' selects PROPERTY for inheritance.
14268 If the property is present but empty, the return value is the empty string.
14269 If the property is not present at all, nil is returned.
14271 If LITERAL-NIL is set, return the string value \"nil\" as a string,
14272 do not interpret it as the list atom nil. This is used for inheritance
14273 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
14274 (org-with-point-at pom
14275 (if (and inherit (if (eq inherit 'selective)
14276 (org-property-inherit-p property)
14278 (org-entry-get-with-inheritance property literal-nil)
14279 (if (member property org-special-properties)
14280 ;; We need a special property. Use `org-entry-properties' to
14281 ;; retrieve it, but specify the wanted property
14282 (cdr (assoc property (org-entry-properties nil 'special property)))
14283 (let ((range (unless (org-before-first-heading-p)
14284 (org-get-property-block)))
14285 (props (list (or (assoc property org-file-properties)
14286 (assoc property org-global-properties)
14287 (assoc property org-global-properties-fixed))))
14288 val)
14289 (flet ((ap (key)
14290 (when (re-search-forward
14291 (org-re-property key) (cdr range) t)
14292 (setq props
14293 (org-update-property-plist
14295 (if (match-end 1)
14296 (org-match-string-no-properties 1) "")
14297 props)))))
14298 (when (and range (goto-char (car range)))
14299 (ap property)
14300 (goto-char (car range))
14301 (while (ap (concat property "+")))
14302 (setq val (cdr (assoc property props)))
14303 (when val (if literal-nil val (org-not-nil val))))))))))
14305 (defun org-property-or-variable-value (var &optional inherit)
14306 "Check if there is a property fixing the value of VAR.
14307 If yes, return this value. If not, return the current value of the variable."
14308 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14309 (if (and prop (stringp prop) (string-match "\\S-" prop))
14310 (read prop)
14311 (symbol-value var))))
14313 (defun org-entry-delete (pom property)
14314 "Delete the property PROPERTY from entry at point-or-marker POM."
14315 (org-with-point-at pom
14316 (if (member property org-special-properties)
14317 nil ; cannot delete these properties.
14318 (let ((range (org-get-property-block)))
14319 (if (and range
14320 (goto-char (car range))
14321 (re-search-forward
14322 (org-re-property property)
14323 (cdr range) t))
14324 (progn
14325 (delete-region (match-beginning 0) (1+ (point-at-eol)))
14327 nil)))))
14329 ;; Multi-values properties are properties that contain multiple values
14330 ;; These values are assumed to be single words, separated by whitespace.
14331 (defun org-entry-add-to-multivalued-property (pom property value)
14332 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
14333 (let* ((old (org-entry-get pom property))
14334 (values (and old (org-split-string old "[ \t]"))))
14335 (setq value (org-entry-protect-space value))
14336 (unless (member value values)
14337 (setq values (cons value values))
14338 (org-entry-put pom property
14339 (mapconcat 'identity values " ")))))
14341 (defun org-entry-remove-from-multivalued-property (pom property value)
14342 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
14343 (let* ((old (org-entry-get pom property))
14344 (values (and old (org-split-string old "[ \t]"))))
14345 (setq value (org-entry-protect-space value))
14346 (when (member value values)
14347 (setq values (delete value values))
14348 (org-entry-put pom property
14349 (mapconcat 'identity values " ")))))
14351 (defun org-entry-member-in-multivalued-property (pom property value)
14352 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
14353 (let* ((old (org-entry-get pom property))
14354 (values (and old (org-split-string old "[ \t]"))))
14355 (setq value (org-entry-protect-space value))
14356 (member value values)))
14358 (defun org-entry-get-multivalued-property (pom property)
14359 "Return a list of values in a multivalued property."
14360 (let* ((value (org-entry-get pom property))
14361 (values (and value (org-split-string value "[ \t]"))))
14362 (mapcar 'org-entry-restore-space values)))
14364 (defun org-entry-put-multivalued-property (pom property &rest values)
14365 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
14366 VALUES should be a list of strings. Spaces will be protected."
14367 (org-entry-put pom property
14368 (mapconcat 'org-entry-protect-space values " "))
14369 (let* ((value (org-entry-get pom property))
14370 (values (and value (org-split-string value "[ \t]"))))
14371 (mapcar 'org-entry-restore-space values)))
14373 (defun org-entry-protect-space (s)
14374 "Protect spaces and newline in string S."
14375 (while (string-match " " s)
14376 (setq s (replace-match "%20" t t s)))
14377 (while (string-match "\n" s)
14378 (setq s (replace-match "%0A" t t s)))
14381 (defun org-entry-restore-space (s)
14382 "Restore spaces and newline in string S."
14383 (while (string-match "%20" s)
14384 (setq s (replace-match " " t t s)))
14385 (while (string-match "%0A" s)
14386 (setq s (replace-match "\n" t t s)))
14389 (defvar org-entry-property-inherited-from (make-marker)
14390 "Marker pointing to the entry from where a property was inherited.
14391 Each call to `org-entry-get-with-inheritance' will set this marker to the
14392 location of the entry where the inheritance search matched. If there was
14393 no match, the marker will point nowhere.
14394 Note that also `org-entry-get' calls this function, if the INHERIT flag
14395 is set.")
14397 (defun org-entry-get-with-inheritance (property &optional literal-nil)
14398 "Get entry property, and search higher levels if not present.
14399 The search will stop at the first ancestor which has the property defined.
14400 If the value found is \"nil\", return nil to show that the property
14401 should be considered as undefined (this is the meaning of nil here).
14402 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
14403 (move-marker org-entry-property-inherited-from nil)
14404 (let (tmp)
14405 (unless (org-before-first-heading-p)
14406 (save-excursion
14407 (save-restriction
14408 (widen)
14409 (catch 'ex
14410 (while t
14411 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
14412 (org-back-to-heading t)
14413 (move-marker org-entry-property-inherited-from (point))
14414 (throw 'ex tmp))
14415 (or (org-up-heading-safe) (throw 'ex nil)))))))
14416 (setq tmp (or tmp
14417 (cdr (assoc property org-file-properties))
14418 (cdr (assoc property org-global-properties))
14419 (cdr (assoc property org-global-properties-fixed))))
14420 (if literal-nil tmp (org-not-nil tmp))))
14422 (defvar org-property-changed-functions nil
14423 "Hook called when the value of a property has changed.
14424 Each hook function should accept two arguments, the name of the property
14425 and the new value.")
14427 (defun org-entry-put (pom property value)
14428 "Set PROPERTY to VALUE for entry at point-or-marker POM."
14429 (org-with-point-at pom
14430 (org-back-to-heading t)
14431 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
14432 range)
14433 (cond
14434 ((equal property "TODO")
14435 (when (and (stringp value) (string-match "\\S-" value)
14436 (not (member value org-todo-keywords-1)))
14437 (error "\"%s\" is not a valid TODO state" value))
14438 (if (or (not value)
14439 (not (string-match "\\S-" value)))
14440 (setq value 'none))
14441 (org-todo value)
14442 (org-set-tags nil 'align))
14443 ((equal property "PRIORITY")
14444 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
14445 (string-to-char value) ?\ ))
14446 (org-set-tags nil 'align))
14447 ((equal property "SCHEDULED")
14448 (if (re-search-forward org-scheduled-time-regexp end t)
14449 (cond
14450 ((eq value 'earlier) (org-timestamp-change -1 'day))
14451 ((eq value 'later) (org-timestamp-change 1 'day))
14452 (t (call-interactively 'org-schedule)))
14453 (call-interactively 'org-schedule)))
14454 ((equal property "DEADLINE")
14455 (if (re-search-forward org-deadline-time-regexp end t)
14456 (cond
14457 ((eq value 'earlier) (org-timestamp-change -1 'day))
14458 ((eq value 'later) (org-timestamp-change 1 'day))
14459 (t (call-interactively 'org-deadline)))
14460 (call-interactively 'org-deadline)))
14461 ((member property org-special-properties)
14462 (error "The %s property can not yet be set with `org-entry-put'"
14463 property))
14464 (t ; a non-special property
14465 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
14466 (setq range (org-get-property-block beg end 'force))
14467 (goto-char (car range))
14468 (if (re-search-forward
14469 (org-re-property property) (cdr range) t)
14470 (progn
14471 (delete-region (match-beginning 0) (match-end 0))
14472 (goto-char (match-beginning 0)))
14473 (goto-char (cdr range))
14474 (insert "\n")
14475 (backward-char 1)
14476 (org-indent-line-function))
14477 (insert ":" property ":")
14478 (and value (insert " " value))
14479 (org-indent-line-function)))))
14480 (run-hook-with-args 'org-property-changed-functions property value)))
14482 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
14483 "Get all property keys in the current buffer.
14484 With INCLUDE-SPECIALS, also list the special properties that reflect things
14485 like tags and TODO state.
14486 With INCLUDE-DEFAULTS, also include properties that has special meaning
14487 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
14488 and others.
14489 With INCLUDE-COLUMNS, also include property names given in COLUMN
14490 formats in the current buffer."
14491 (let (rtn range cfmt s p)
14492 (save-excursion
14493 (save-restriction
14494 (widen)
14495 (goto-char (point-min))
14496 (while (re-search-forward org-property-start-re nil t)
14497 (setq range (org-get-property-block))
14498 (goto-char (car range))
14499 (while (re-search-forward
14500 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
14501 (cdr range) t)
14502 (add-to-list 'rtn (org-match-string-no-properties 1)))
14503 (outline-next-heading))))
14505 (when include-specials
14506 (setq rtn (append org-special-properties rtn)))
14508 (when include-defaults
14509 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
14510 (add-to-list 'rtn org-effort-property))
14512 (when include-columns
14513 (save-excursion
14514 (save-restriction
14515 (widen)
14516 (goto-char (point-min))
14517 (while (re-search-forward
14518 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
14519 nil t)
14520 (setq cfmt (match-string 2) s 0)
14521 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
14522 cfmt s)
14523 (setq s (match-end 0)
14524 p (match-string 1 cfmt))
14525 (unless (or (equal p "ITEM")
14526 (member p org-special-properties))
14527 (add-to-list 'rtn (match-string 1 cfmt))))))))
14529 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
14531 (defun org-property-values (key)
14532 "Return a list of all values of property KEY in the current buffer."
14533 (save-excursion
14534 (save-restriction
14535 (widen)
14536 (goto-char (point-min))
14537 (let ((re (org-re-property key))
14538 values)
14539 (while (re-search-forward re nil t)
14540 (add-to-list 'values (org-trim (match-string 1))))
14541 (delete "" values)))))
14543 (defun org-insert-property-drawer ()
14544 "Insert a property drawer into the current entry."
14545 (org-back-to-heading t)
14546 (looking-at org-outline-regexp)
14547 (let ((indent (if org-adapt-indentation
14548 (- (match-end 0) (match-beginning 0))
14550 (beg (point))
14551 (re (concat "^[ \t]*" org-keyword-time-regexp))
14552 end hiddenp)
14553 (outline-next-heading)
14554 (setq end (point))
14555 (goto-char beg)
14556 (while (re-search-forward re end t))
14557 (setq hiddenp (outline-invisible-p))
14558 (end-of-line 1)
14559 (and (equal (char-after) ?\n) (forward-char 1))
14560 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
14561 (if (member (match-string 1) '("CLOCK:" ":END:"))
14562 ;; just skip this line
14563 (beginning-of-line 2)
14564 ;; Drawer start, find the end
14565 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
14566 (beginning-of-line 1)))
14567 (org-skip-over-state-notes)
14568 (skip-chars-backward " \t\n\r")
14569 (if (eq (char-before) ?*) (forward-char 1))
14570 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
14571 (beginning-of-line 0)
14572 (org-indent-to-column indent)
14573 (beginning-of-line 2)
14574 (org-indent-to-column indent)
14575 (beginning-of-line 0)
14576 (if hiddenp
14577 (save-excursion
14578 (org-back-to-heading t)
14579 (hide-entry))
14580 (org-flag-drawer t))))
14582 (defun org-insert-drawer (&optional arg drawer)
14583 "Insert a drawer at point.
14585 Optional argument DRAWER, when non-nil, is a string representing
14586 drawer's name. Otherwise, the user is prompted for a name.
14588 If a region is active, insert the drawer around that region
14589 instead.
14591 Point is left between drawer's boundaries."
14592 (interactive "P")
14593 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
14594 "LOGBOOK"))
14595 ;; SYSTEM-DRAWERS is a list of drawer names that are used
14596 ;; internally by Org. They are meant to be inserted
14597 ;; automatically.
14598 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
14599 ;; Remove system drawers from list. Note: For some reason,
14600 ;; `org-completing-read' ignores the predicate while
14601 ;; `completing-read' handles it fine.
14602 (drawer (if arg "PROPERTIES"
14603 (or drawer
14604 (completing-read
14605 "Drawer: " org-drawers
14606 (lambda (d) (not (member d system-drawers))))))))
14607 (cond
14608 ;; With C-u, fall back on `org-insert-property-drawer'
14609 (arg (org-insert-property-drawer))
14610 ;; With an active region, insert a drawer at point.
14611 ((not (org-region-active-p))
14612 (progn
14613 (unless (bolp) (insert "\n"))
14614 (insert (format ":%s:\n\n:END:\n" drawer))
14615 (forward-line -2)))
14616 ;; Otherwise, insert the drawer at point
14618 (let ((rbeg (region-beginning))
14619 (rend (copy-marker (region-end))))
14620 (unwind-protect
14621 (progn
14622 (goto-char rbeg)
14623 (beginning-of-line)
14624 (when (save-excursion
14625 (re-search-forward org-outline-regexp-bol rend t))
14626 (error "Drawers cannot contain headlines"))
14627 ;; Position point at the beginning of the first
14628 ;; non-blank line in region. Insert drawer's opening
14629 ;; there, then indent it.
14630 (org-skip-whitespace)
14631 (beginning-of-line)
14632 (insert ":" drawer ":\n")
14633 (forward-line -1)
14634 (indent-for-tab-command)
14635 ;; Move point to the beginning of the first blank line
14636 ;; after the last non-blank line in region. Insert
14637 ;; drawer's closing, then indent it.
14638 (goto-char rend)
14639 (skip-chars-backward " \r\t\n")
14640 (insert "\n:END:")
14641 (indent-for-tab-command)
14642 (unless (eolp) (insert "\n")))
14643 ;; Clear marker, whatever the outcome of insertion is.
14644 (set-marker rend nil)))))))
14646 (defvar org-property-set-functions-alist nil
14647 "Property set function alist.
14648 Each entry should have the following format:
14650 (PROPERTY . READ-FUNCTION)
14652 The read function will be called with the same argument as
14653 `org-completing-read'.")
14655 (defun org-set-property-function (property)
14656 "Get the function that should be used to set PROPERTY.
14657 This is computed according to `org-property-set-functions-alist'."
14658 (or (cdr (assoc property org-property-set-functions-alist))
14659 'org-completing-read))
14661 (defun org-read-property-value (property)
14662 "Read PROPERTY value from user."
14663 (let* ((completion-ignore-case t)
14664 (allowed (org-property-get-allowed-values nil property 'table))
14665 (cur (org-entry-get nil property))
14666 (prompt (concat property " value"
14667 (if (and cur (string-match "\\S-" cur))
14668 (concat " [" cur "]") "") ": "))
14669 (set-function (org-set-property-function property))
14670 (val (if allowed
14671 (funcall set-function prompt allowed nil
14672 (not (get-text-property 0 'org-unrestricted
14673 (caar allowed))))
14674 (let (org-completion-use-ido org-completion-use-iswitchb)
14675 (funcall set-function prompt
14676 (mapcar 'list (org-property-values property))
14677 nil nil "" nil cur)))))
14678 (if (equal val "")
14680 val)))
14682 (defvar org-last-set-property nil)
14683 (defun org-read-property-name ()
14684 "Read a property name."
14685 (let* ((completion-ignore-case t)
14686 (keys (org-buffer-property-keys nil t t))
14687 (default-prop (or (save-excursion
14688 (save-match-data
14689 (beginning-of-line)
14690 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
14691 (null (string= (match-string 1) "END"))
14692 (match-string 1))))
14693 org-last-set-property))
14694 (property (org-icompleting-read
14695 (concat "Property"
14696 (if default-prop (concat " [" default-prop "]") "")
14697 ": ")
14698 (mapcar 'list keys)
14699 nil nil nil nil
14700 default-prop
14702 (if (member property keys)
14703 property
14704 (or (cdr (assoc (downcase property)
14705 (mapcar (lambda (x) (cons (downcase x) x))
14706 keys)))
14707 property))))
14709 (defun org-set-property (property value)
14710 "In the current entry, set PROPERTY to VALUE.
14711 When called interactively, this will prompt for a property name, offering
14712 completion on existing and default properties. And then it will prompt
14713 for a value, offering completion either on allowed values (via an inherited
14714 xxx_ALL property) or on existing values in other instances of this property
14715 in the current file."
14716 (interactive (list nil nil))
14717 (let* ((property (or property (org-read-property-name)))
14718 (value (or value (org-read-property-value property)))
14719 (fn (cadr (assoc property org-properties-postprocess-alist))))
14720 (setq org-last-set-property property)
14721 ;; Possibly postprocess the inserted value:
14722 (when fn (setq value (funcall fn value)))
14723 (unless (equal (org-entry-get nil property) value)
14724 (org-entry-put nil property value))))
14726 (defun org-delete-property (property)
14727 "In the current entry, delete PROPERTY."
14728 (interactive
14729 (let* ((completion-ignore-case t)
14730 (prop (org-icompleting-read "Property: "
14731 (org-entry-properties nil 'standard))))
14732 (list prop)))
14733 (message "Property %s %s" property
14734 (if (org-entry-delete nil property)
14735 "deleted"
14736 "was not present in the entry")))
14738 (defun org-delete-property-globally (property)
14739 "Remove PROPERTY globally, from all entries."
14740 (interactive
14741 (let* ((completion-ignore-case t)
14742 (prop (org-icompleting-read
14743 "Globally remove property: "
14744 (mapcar 'list (org-buffer-property-keys)))))
14745 (list prop)))
14746 (save-excursion
14747 (save-restriction
14748 (widen)
14749 (goto-char (point-min))
14750 (let ((cnt 0))
14751 (while (re-search-forward
14752 (org-re-property property)
14753 nil t)
14754 (setq cnt (1+ cnt))
14755 (delete-region (match-beginning 0) (1+ (point-at-eol))))
14756 (message "Property \"%s\" removed from %d entries" property cnt)))))
14758 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
14760 (defun org-compute-property-at-point ()
14761 "Compute the property at point.
14762 This looks for an enclosing column format, extracts the operator and
14763 then applies it to the property in the column format's scope."
14764 (interactive)
14765 (unless (org-at-property-p)
14766 (error "Not at a property"))
14767 (let ((prop (org-match-string-no-properties 2)))
14768 (org-columns-get-format-and-top-level)
14769 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
14770 (error "No operator defined for property %s" prop))
14771 (org-columns-compute prop)))
14773 (defvar org-property-allowed-value-functions nil
14774 "Hook for functions supplying allowed values for a specific property.
14775 The functions must take a single argument, the name of the property, and
14776 return a flat list of allowed values. If \":ETC\" is one of
14777 the values, this means that these values are intended as defaults for
14778 completion, but that other values should be allowed too.
14779 The functions must return nil if they are not responsible for this
14780 property.")
14782 (defun org-property-get-allowed-values (pom property &optional table)
14783 "Get allowed values for the property PROPERTY.
14784 When TABLE is non-nil, return an alist that can directly be used for
14785 completion."
14786 (let (vals)
14787 (cond
14788 ((equal property "TODO")
14789 (setq vals (org-with-point-at pom
14790 (append org-todo-keywords-1 '("")))))
14791 ((equal property "PRIORITY")
14792 (let ((n org-lowest-priority))
14793 (while (>= n org-highest-priority)
14794 (push (char-to-string n) vals)
14795 (setq n (1- n)))))
14796 ((member property org-special-properties))
14797 ((setq vals (run-hook-with-args-until-success
14798 'org-property-allowed-value-functions property)))
14800 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
14801 (when (and vals (string-match "\\S-" vals))
14802 (setq vals (car (read-from-string (concat "(" vals ")"))))
14803 (setq vals (mapcar (lambda (x)
14804 (cond ((stringp x) x)
14805 ((numberp x) (number-to-string x))
14806 ((symbolp x) (symbol-name x))
14807 (t "???")))
14808 vals)))))
14809 (when (member ":ETC" vals)
14810 (setq vals (remove ":ETC" vals))
14811 (org-add-props (car vals) '(org-unrestricted t)))
14812 (if table (mapcar 'list vals) vals)))
14814 (defun org-property-previous-allowed-value (&optional previous)
14815 "Switch to the next allowed value for this property."
14816 (interactive)
14817 (org-property-next-allowed-value t))
14819 (defun org-property-next-allowed-value (&optional previous)
14820 "Switch to the next allowed value for this property."
14821 (interactive)
14822 (unless (org-at-property-p)
14823 (error "Not at a property"))
14824 (let* ((key (match-string 2))
14825 (value (match-string 3))
14826 (allowed (or (org-property-get-allowed-values (point) key)
14827 (and (member value '("[ ]" "[-]" "[X]"))
14828 '("[ ]" "[X]"))))
14829 nval)
14830 (unless allowed
14831 (error "Allowed values for this property have not been defined"))
14832 (if previous (setq allowed (reverse allowed)))
14833 (if (member value allowed)
14834 (setq nval (car (cdr (member value allowed)))))
14835 (setq nval (or nval (car allowed)))
14836 (if (equal nval value)
14837 (error "Only one allowed value for this property"))
14838 (org-at-property-p)
14839 (replace-match (concat " :" key ": " nval) t t)
14840 (org-indent-line-function)
14841 (beginning-of-line 1)
14842 (skip-chars-forward " \t")
14843 (run-hook-with-args 'org-property-changed-functions key nval)))
14845 (defun org-find-olp (path &optional this-buffer)
14846 "Return a marker pointing to the entry at outline path OLP.
14847 If anything goes wrong, throw an error.
14848 You can wrap this call to catch the error like this:
14850 (condition-case msg
14851 (org-mobile-locate-entry (match-string 4))
14852 (error (nth 1 msg)))
14854 The return value will then be either a string with the error message,
14855 or a marker if everything is OK.
14857 If THIS-BUFFER is set, the outline path does not contain a file,
14858 only headings."
14859 (let* ((file (if this-buffer buffer-file-name (pop path)))
14860 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
14861 (level 1)
14862 (lmin 1)
14863 (lmax 1)
14864 limit re end found pos heading cnt flevel)
14865 (unless buffer (error "File not found :%s" file))
14866 (with-current-buffer buffer
14867 (save-excursion
14868 (save-restriction
14869 (widen)
14870 (setq limit (point-max))
14871 (goto-char (point-min))
14872 (while (setq heading (pop path))
14873 (setq re (format org-complex-heading-regexp-format
14874 (regexp-quote heading)))
14875 (setq cnt 0 pos (point))
14876 (while (re-search-forward re end t)
14877 (setq level (- (match-end 1) (match-beginning 1)))
14878 (if (and (>= level lmin) (<= level lmax))
14879 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
14880 (when (= cnt 0) (error "Heading not found on level %d: %s"
14881 lmax heading))
14882 (when (> cnt 1) (error "Heading not unique on level %d: %s"
14883 lmax heading))
14884 (goto-char found)
14885 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
14886 (setq end (save-excursion (org-end-of-subtree t t))))
14887 (when (org-at-heading-p)
14888 (move-marker (make-marker) (point))))))))
14890 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
14891 "Find node HEADING in BUFFER.
14892 Return a marker to the heading if it was found, or nil if not.
14893 If POS-ONLY is set, return just the position instead of a marker.
14895 The heading text must match exact, but it may have a TODO keyword,
14896 a priority cookie and tags in the standard locations."
14897 (with-current-buffer (or buffer (current-buffer))
14898 (save-excursion
14899 (save-restriction
14900 (widen)
14901 (goto-char (point-min))
14902 (let (case-fold-search)
14903 (if (re-search-forward
14904 (format org-complex-heading-regexp-format
14905 (regexp-quote heading)) nil t)
14906 (if pos-only
14907 (match-beginning 0)
14908 (move-marker (make-marker) (match-beginning 0)))))))))
14910 (defun org-find-exact-heading-in-directory (heading &optional dir)
14911 "Find Org node headline HEADING in all .org files in directory DIR.
14912 When the target headline is found, return a marker to this location."
14913 (let ((files (directory-files (or dir default-directory)
14914 nil "\\`[^.#].*\\.org\\'"))
14915 file visiting m buffer)
14916 (catch 'found
14917 (while (setq file (pop files))
14918 (message "trying %s" file)
14919 (setq visiting (org-find-base-buffer-visiting file))
14920 (setq buffer (or visiting (find-file-noselect file)))
14921 (setq m (org-find-exact-headline-in-buffer
14922 heading buffer))
14923 (when (and (not m) (not visiting)) (kill-buffer buffer))
14924 (and m (throw 'found m))))))
14926 (defun org-find-entry-with-id (ident)
14927 "Locate the entry that contains the ID property with exact value IDENT.
14928 IDENT can be a string, a symbol or a number, this function will search for
14929 the string representation of it.
14930 Return the position where this entry starts, or nil if there is no such entry."
14931 (interactive "sID: ")
14932 (let ((id (cond
14933 ((stringp ident) ident)
14934 ((symbol-name ident) (symbol-name ident))
14935 ((numberp ident) (number-to-string ident))
14936 (t (error "IDENT %s must be a string, symbol or number" ident))))
14937 (case-fold-search nil))
14938 (save-excursion
14939 (save-restriction
14940 (widen)
14941 (goto-char (point-min))
14942 (when (re-search-forward
14943 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
14944 nil t)
14945 (org-back-to-heading t)
14946 (point))))))
14948 ;;;; Timestamps
14950 (defvar org-last-changed-timestamp nil)
14951 (defvar org-last-inserted-timestamp nil
14952 "The last time stamp inserted with `org-insert-time-stamp'.")
14953 (defvar org-time-was-given) ; dynamically scoped parameter
14954 (defvar org-end-time-was-given) ; dynamically scoped parameter
14955 (defvar org-ts-what) ; dynamically scoped parameter
14957 (defun org-time-stamp (arg &optional inactive)
14958 "Prompt for a date/time and insert a time stamp.
14959 If the user specifies a time like HH:MM, or if this command is called
14960 with a prefix argument, the time stamp will contain date and time.
14961 Otherwise, only the date will be included. All parts of a date not
14962 specified by the user will be filled in from the current date/time.
14963 So if you press just return without typing anything, the time stamp
14964 will represent the current date/time. If there is already a timestamp
14965 at the cursor, it will be modified."
14966 (interactive "P")
14967 (let* ((ts nil)
14968 (default-time
14969 ;; Default time is either today, or, when entering a range,
14970 ;; the range start.
14971 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
14972 (save-excursion
14973 (re-search-backward
14974 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
14975 (- (point) 20) t)))
14976 (apply 'encode-time (org-parse-time-string (match-string 1)))
14977 (current-time)))
14978 (default-input (and ts (org-get-compact-tod ts)))
14979 (repeater (save-excursion
14980 (save-match-data
14981 (beginning-of-line)
14982 (when (re-search-forward
14983 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
14984 (save-excursion (progn (end-of-line) (point))) t)
14985 (match-string 0)))))
14986 org-time-was-given org-end-time-was-given time)
14987 (cond
14988 ((and (org-at-timestamp-p t)
14989 (memq last-command '(org-time-stamp org-time-stamp-inactive))
14990 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
14991 (insert "--")
14992 (setq time (let ((this-command this-command))
14993 (org-read-date arg 'totime nil nil
14994 default-time default-input inactive)))
14995 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
14996 ((org-at-timestamp-p t)
14997 (setq time (let ((this-command this-command))
14998 (org-read-date arg 'totime nil nil default-time default-input inactive)))
14999 (when (org-at-timestamp-p t) ; just to get the match data
15000 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
15001 (replace-match "")
15002 (setq org-last-changed-timestamp
15003 (org-insert-time-stamp
15004 time (or org-time-was-given arg)
15005 inactive nil nil (list org-end-time-was-given)))
15006 (when repeater (goto-char (1- (point))) (insert " " repeater)
15007 (setq org-last-changed-timestamp
15008 (concat (substring org-last-inserted-timestamp 0 -1)
15009 " " repeater ">"))))
15010 (message "Timestamp updated"))
15012 (setq time (let ((this-command this-command))
15013 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15014 (org-insert-time-stamp time (or org-time-was-given arg) inactive
15015 nil nil (list org-end-time-was-given))))))
15017 ;; FIXME: can we use this for something else, like computing time differences?
15018 (defun org-get-compact-tod (s)
15019 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
15020 (let* ((t1 (match-string 1 s))
15021 (h1 (string-to-number (match-string 2 s)))
15022 (m1 (string-to-number (match-string 3 s)))
15023 (t2 (and (match-end 4) (match-string 5 s)))
15024 (h2 (and t2 (string-to-number (match-string 6 s))))
15025 (m2 (and t2 (string-to-number (match-string 7 s))))
15026 dh dm)
15027 (if (not t2)
15029 (setq dh (- h2 h1) dm (- m2 m1))
15030 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
15031 (concat t1 "+" (number-to-string dh)
15032 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
15034 (defun org-time-stamp-inactive (&optional arg)
15035 "Insert an inactive time stamp.
15036 An inactive time stamp is enclosed in square brackets instead of angle
15037 brackets. It is inactive in the sense that it does not trigger agenda entries,
15038 does not link to the calendar and cannot be changed with the S-cursor keys.
15039 So these are more for recording a certain time/date."
15040 (interactive "P")
15041 (org-time-stamp arg 'inactive))
15043 (defvar org-date-ovl (make-overlay 1 1))
15044 (overlay-put org-date-ovl 'face 'org-date-selected)
15045 (org-detach-overlay org-date-ovl)
15047 (defvar org-ans1) ; dynamically scoped parameter
15048 (defvar org-ans2) ; dynamically scoped parameter
15050 (defvar org-plain-time-of-day-regexp) ; defined below
15052 (defvar org-overriding-default-time nil) ; dynamically scoped
15053 (defvar org-read-date-overlay nil)
15054 (defvar org-dcst nil) ; dynamically scoped
15055 (defvar org-read-date-history nil)
15056 (defvar org-read-date-final-answer nil)
15057 (defvar org-read-date-analyze-futurep nil)
15058 (defvar org-read-date-analyze-forced-year nil)
15059 (defvar org-read-date-inactive)
15061 (defun org-read-date (&optional org-with-time to-time from-string prompt
15062 default-time default-input inactive)
15063 "Read a date, possibly a time, and make things smooth for the user.
15064 The prompt will suggest to enter an ISO date, but you can also enter anything
15065 which will at least partially be understood by `parse-time-string'.
15066 Unrecognized parts of the date will default to the current day, month, year,
15067 hour and minute. If this command is called to replace a timestamp at point,
15068 or to enter the second timestamp of a range, the default time is taken
15069 from the existing stamp. Furthermore, the command prefers the future,
15070 so if you are giving a date where the year is not given, and the day-month
15071 combination is already past in the current year, it will assume you
15072 mean next year. For details, see the manual. A few examples:
15074 3-2-5 --> 2003-02-05
15075 feb 15 --> currentyear-02-15
15076 2/15 --> currentyear-02-15
15077 sep 12 9 --> 2009-09-12
15078 12:45 --> today 12:45
15079 22 sept 0:34 --> currentyear-09-22 0:34
15080 12 --> currentyear-currentmonth-12
15081 Fri --> nearest Friday (today or later)
15082 etc.
15084 Furthermore you can specify a relative date by giving, as the *first* thing
15085 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
15086 change in days weeks, months, years.
15087 With a single plus or minus, the date is relative to today. With a double
15088 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
15089 +4d --> four days from today
15090 +4 --> same as above
15091 +2w --> two weeks from today
15092 ++5 --> five days from default date
15094 The function understands only English month and weekday abbreviations.
15096 While prompting, a calendar is popped up - you can also select the
15097 date with the mouse (button 1). The calendar shows a period of three
15098 months. To scroll it to other months, use the keys `>' and `<'.
15099 If you don't like the calendar, turn it off with
15100 \(setq org-read-date-popup-calendar nil)
15102 With optional argument TO-TIME, the date will immediately be converted
15103 to an internal time.
15104 With an optional argument WITH-TIME, the prompt will suggest to also
15105 insert a time. Note that when WITH-TIME is not set, you can still
15106 enter a time, and this function will inform the calling routine about
15107 this change. The calling routine may then choose to change the format
15108 used to insert the time stamp into the buffer to include the time.
15109 With optional argument FROM-STRING, read from this string instead from
15110 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
15111 the time/date that is used for everything that is not specified by the
15112 user."
15113 (require 'parse-time)
15114 (let* ((org-time-stamp-rounding-minutes
15115 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
15116 (org-dcst org-display-custom-times)
15117 (ct (org-current-time))
15118 (org-def (or org-overriding-default-time default-time ct))
15119 (org-defdecode (decode-time org-def))
15120 (dummy (progn
15121 (when (< (nth 2 org-defdecode) org-extend-today-until)
15122 (setcar (nthcdr 2 org-defdecode) -1)
15123 (setcar (nthcdr 1 org-defdecode) 59)
15124 (setq org-def (apply 'encode-time org-defdecode)
15125 org-defdecode (decode-time org-def)))))
15126 (calendar-frame-setup nil)
15127 (calendar-setup nil)
15128 (calendar-move-hook nil)
15129 (calendar-view-diary-initially-flag nil)
15130 (calendar-view-holidays-initially-flag nil)
15131 (timestr (format-time-string
15132 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
15133 (prompt (concat (if prompt (concat prompt " ") "")
15134 (format "Date+time [%s]: " timestr)))
15135 ans (org-ans0 "") org-ans1 org-ans2 final)
15137 (cond
15138 (from-string (setq ans from-string))
15139 (org-read-date-popup-calendar
15140 (save-excursion
15141 (save-window-excursion
15142 (calendar)
15143 (org-eval-in-calendar '(setq cursor-type nil) t)
15144 (unwind-protect
15145 (progn
15146 (calendar-forward-day (- (time-to-days org-def)
15147 (calendar-absolute-from-gregorian
15148 (calendar-current-date))))
15149 (org-eval-in-calendar nil t)
15150 (let* ((old-map (current-local-map))
15151 (map (copy-keymap calendar-mode-map))
15152 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
15153 (org-defkey map (kbd "RET") 'org-calendar-select)
15154 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
15155 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
15156 (org-defkey minibuffer-local-map [(meta shift left)]
15157 (lambda () (interactive)
15158 (org-eval-in-calendar '(calendar-backward-month 1))))
15159 (org-defkey minibuffer-local-map [(meta shift right)]
15160 (lambda () (interactive)
15161 (org-eval-in-calendar '(calendar-forward-month 1))))
15162 (org-defkey minibuffer-local-map [(meta shift up)]
15163 (lambda () (interactive)
15164 (org-eval-in-calendar '(calendar-backward-year 1))))
15165 (org-defkey minibuffer-local-map [(meta shift down)]
15166 (lambda () (interactive)
15167 (org-eval-in-calendar '(calendar-forward-year 1))))
15168 (org-defkey minibuffer-local-map [?\e (shift left)]
15169 (lambda () (interactive)
15170 (org-eval-in-calendar '(calendar-backward-month 1))))
15171 (org-defkey minibuffer-local-map [?\e (shift right)]
15172 (lambda () (interactive)
15173 (org-eval-in-calendar '(calendar-forward-month 1))))
15174 (org-defkey minibuffer-local-map [?\e (shift up)]
15175 (lambda () (interactive)
15176 (org-eval-in-calendar '(calendar-backward-year 1))))
15177 (org-defkey minibuffer-local-map [?\e (shift down)]
15178 (lambda () (interactive)
15179 (org-eval-in-calendar '(calendar-forward-year 1))))
15180 (org-defkey minibuffer-local-map [(shift up)]
15181 (lambda () (interactive)
15182 (org-eval-in-calendar '(calendar-backward-week 1))))
15183 (org-defkey minibuffer-local-map [(shift down)]
15184 (lambda () (interactive)
15185 (org-eval-in-calendar '(calendar-forward-week 1))))
15186 (org-defkey minibuffer-local-map [(shift left)]
15187 (lambda () (interactive)
15188 (org-eval-in-calendar '(calendar-backward-day 1))))
15189 (org-defkey minibuffer-local-map [(shift right)]
15190 (lambda () (interactive)
15191 (org-eval-in-calendar '(calendar-forward-day 1))))
15192 (org-defkey minibuffer-local-map ">"
15193 (lambda () (interactive)
15194 (org-eval-in-calendar '(scroll-calendar-left 1))))
15195 (org-defkey minibuffer-local-map "<"
15196 (lambda () (interactive)
15197 (org-eval-in-calendar '(scroll-calendar-right 1))))
15198 (org-defkey minibuffer-local-map "\C-v"
15199 (lambda () (interactive)
15200 (org-eval-in-calendar
15201 '(calendar-scroll-left-three-months 1))))
15202 (org-defkey minibuffer-local-map "\M-v"
15203 (lambda () (interactive)
15204 (org-eval-in-calendar
15205 '(calendar-scroll-right-three-months 1))))
15206 (run-hooks 'org-read-date-minibuffer-setup-hook)
15207 (unwind-protect
15208 (progn
15209 (use-local-map map)
15210 (setq org-read-date-inactive inactive)
15211 (add-hook 'post-command-hook 'org-read-date-display)
15212 (setq org-ans0 (read-string prompt default-input
15213 'org-read-date-history nil))
15214 ;; org-ans0: from prompt
15215 ;; org-ans1: from mouse click
15216 ;; org-ans2: from calendar motion
15217 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
15218 (remove-hook 'post-command-hook 'org-read-date-display)
15219 (use-local-map old-map)
15220 (when org-read-date-overlay
15221 (delete-overlay org-read-date-overlay)
15222 (setq org-read-date-overlay nil)))))
15223 (bury-buffer "*Calendar*")))))
15225 (t ; Naked prompt only
15226 (unwind-protect
15227 (setq ans (read-string prompt default-input
15228 'org-read-date-history timestr))
15229 (when org-read-date-overlay
15230 (delete-overlay org-read-date-overlay)
15231 (setq org-read-date-overlay nil)))))
15233 (setq final (org-read-date-analyze ans org-def org-defdecode))
15235 (when org-read-date-analyze-forced-year
15236 (message "Year was forced into %s"
15237 (if org-read-date-force-compatible-dates
15238 "compatible range (1970-2037)"
15239 "range representable on this machine"))
15240 (ding))
15242 ;; One round trip to get rid of 34th of August and stuff like that....
15243 (setq final (decode-time (apply 'encode-time final)))
15245 (setq org-read-date-final-answer ans)
15247 (if to-time
15248 (apply 'encode-time final)
15249 (if (and (boundp 'org-time-was-given) org-time-was-given)
15250 (format "%04d-%02d-%02d %02d:%02d"
15251 (nth 5 final) (nth 4 final) (nth 3 final)
15252 (nth 2 final) (nth 1 final))
15253 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
15255 (defvar org-def)
15256 (defvar org-defdecode)
15257 (defvar org-with-time)
15258 (defun org-read-date-display ()
15259 "Display the current date prompt interpretation in the minibuffer."
15260 (when org-read-date-display-live
15261 (when org-read-date-overlay
15262 (delete-overlay org-read-date-overlay))
15263 (when (minibufferp (current-buffer))
15264 (save-excursion
15265 (end-of-line 1)
15266 (while (not (equal (buffer-substring
15267 (max (point-min) (- (point) 4)) (point))
15268 " "))
15269 (insert " ")))
15270 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
15271 " " (or org-ans1 org-ans2)))
15272 (org-end-time-was-given nil)
15273 (f (org-read-date-analyze ans org-def org-defdecode))
15274 (fmts (if org-dcst
15275 org-time-stamp-custom-formats
15276 org-time-stamp-formats))
15277 (fmt (if (or org-with-time
15278 (and (boundp 'org-time-was-given) org-time-was-given))
15279 (cdr fmts)
15280 (car fmts)))
15281 (txt (format-time-string fmt (apply 'encode-time f)))
15282 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
15283 (txt (concat "=> " txt)))
15284 (when (and org-end-time-was-given
15285 (string-match org-plain-time-of-day-regexp txt))
15286 (setq txt (concat (substring txt 0 (match-end 0)) "-"
15287 org-end-time-was-given
15288 (substring txt (match-end 0)))))
15289 (when org-read-date-analyze-futurep
15290 (setq txt (concat txt " (=>F)")))
15291 (setq org-read-date-overlay
15292 (make-overlay (1- (point-at-eol)) (point-at-eol)))
15293 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
15295 (defun org-read-date-analyze (ans org-def org-defdecode)
15296 "Analyze the combined answer of the date prompt."
15297 ;; FIXME: cleanup and comment
15298 (let ((nowdecode (decode-time (current-time)))
15299 delta deltan deltaw deltadef year month day
15300 hour minute second wday pm h2 m2 tl wday1
15301 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
15302 (setq org-read-date-analyze-futurep nil
15303 org-read-date-analyze-forced-year nil)
15304 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
15305 (setq ans "+0"))
15307 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
15308 (setq ans (replace-match "" t t ans)
15309 deltan (car delta)
15310 deltaw (nth 1 delta)
15311 deltadef (nth 2 delta)))
15313 ;; Check if there is an iso week date in there
15314 ;; If yes, store the info and postpone interpreting it until the rest
15315 ;; of the parsing is done
15316 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
15317 (setq iso-year (if (match-end 1)
15318 (org-small-year-to-year
15319 (string-to-number (match-string 1 ans))))
15320 iso-weekday (if (match-end 3)
15321 (string-to-number (match-string 3 ans)))
15322 iso-week (string-to-number (match-string 2 ans)))
15323 (setq ans (replace-match "" t t ans)))
15325 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
15326 (when (string-match
15327 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
15328 (setq year (if (match-end 2)
15329 (string-to-number (match-string 2 ans))
15330 (progn (setq kill-year t)
15331 (string-to-number (format-time-string "%Y"))))
15332 month (string-to-number (match-string 3 ans))
15333 day (string-to-number (match-string 4 ans)))
15334 (if (< year 100) (setq year (+ 2000 year)))
15335 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15336 t nil ans)))
15338 ;; Help matching dotted european dates
15339 (when (string-match
15340 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\. ?\\([1-9][0-9][0-9][0-9]\\)?" ans)
15341 (setq year (if (match-end 3)
15342 (string-to-number (match-string 3 ans))
15343 (progn (setq kill-year t)
15344 (string-to-number (format-time-string "%Y"))))
15345 day (string-to-number (match-string 1 ans))
15346 month (string-to-number (match-string 2 ans))
15347 ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15348 t nil ans)))
15350 ;; Help matching american dates, like 5/30 or 5/30/7
15351 (when (string-match
15352 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
15353 (setq year (if (match-end 4)
15354 (string-to-number (match-string 4 ans))
15355 (progn (setq kill-year t)
15356 (string-to-number (format-time-string "%Y"))))
15357 month (string-to-number (match-string 1 ans))
15358 day (string-to-number (match-string 2 ans)))
15359 (if (< year 100) (setq year (+ 2000 year)))
15360 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15361 t nil ans)))
15362 ;; Help matching am/pm times, because `parse-time-string' does not do that.
15363 ;; If there is a time with am/pm, and *no* time without it, we convert
15364 ;; so that matching will be successful.
15365 (loop for i from 1 to 2 do ; twice, for end time as well
15366 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
15367 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
15368 (setq hour (string-to-number (match-string 1 ans))
15369 minute (if (match-end 3)
15370 (string-to-number (match-string 3 ans))
15372 pm (equal ?p
15373 (string-to-char (downcase (match-string 4 ans)))))
15374 (if (and (= hour 12) (not pm))
15375 (setq hour 0)
15376 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
15377 (setq ans (replace-match (format "%02d:%02d" hour minute)
15378 t t ans))))
15380 ;; Check if a time range is given as a duration
15381 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
15382 (setq hour (string-to-number (match-string 1 ans))
15383 h2 (+ hour (string-to-number (match-string 3 ans)))
15384 minute (string-to-number (match-string 2 ans))
15385 m2 (+ minute (if (match-end 5) (string-to-number
15386 (match-string 5 ans))0)))
15387 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
15388 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
15389 t t ans)))
15391 ;; Check if there is a time range
15392 (when (boundp 'org-end-time-was-given)
15393 (setq org-time-was-given nil)
15394 (when (and (string-match org-plain-time-of-day-regexp ans)
15395 (match-end 8))
15396 (setq org-end-time-was-given (match-string 8 ans))
15397 (setq ans (concat (substring ans 0 (match-beginning 7))
15398 (substring ans (match-end 7))))))
15400 (setq tl (parse-time-string ans)
15401 day (or (nth 3 tl) (nth 3 org-defdecode))
15402 month (or (nth 4 tl)
15403 (if (and org-read-date-prefer-future
15404 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
15405 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
15406 (nth 4 org-defdecode)))
15407 year (or (and (not kill-year) (nth 5 tl))
15408 (if (and org-read-date-prefer-future
15409 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
15410 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
15411 (nth 5 org-defdecode)))
15412 hour (or (nth 2 tl) (nth 2 org-defdecode))
15413 minute (or (nth 1 tl) (nth 1 org-defdecode))
15414 second (or (nth 0 tl) 0)
15415 wday (nth 6 tl))
15417 (when (and (eq org-read-date-prefer-future 'time)
15418 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
15419 (equal day (nth 3 nowdecode))
15420 (equal month (nth 4 nowdecode))
15421 (equal year (nth 5 nowdecode))
15422 (nth 2 tl)
15423 (or (< (nth 2 tl) (nth 2 nowdecode))
15424 (and (= (nth 2 tl) (nth 2 nowdecode))
15425 (nth 1 tl)
15426 (< (nth 1 tl) (nth 1 nowdecode)))))
15427 (setq day (1+ day)
15428 futurep t))
15430 ;; Special date definitions below
15431 (cond
15432 (iso-week
15433 ;; There was an iso week
15434 (require 'cal-iso)
15435 (setq futurep nil)
15436 (setq year (or iso-year year)
15437 day (or iso-weekday wday 1)
15438 wday nil ; to make sure that the trigger below does not match
15439 iso-date (calendar-gregorian-from-absolute
15440 (calendar-absolute-from-iso
15441 (list iso-week day year))))
15442 ; FIXME: Should we also push ISO weeks into the future?
15443 ; (when (and org-read-date-prefer-future
15444 ; (not iso-year)
15445 ; (< (calendar-absolute-from-gregorian iso-date)
15446 ; (time-to-days (current-time))))
15447 ; (setq year (1+ year)
15448 ; iso-date (calendar-gregorian-from-absolute
15449 ; (calendar-absolute-from-iso
15450 ; (list iso-week day year)))))
15451 (setq month (car iso-date)
15452 year (nth 2 iso-date)
15453 day (nth 1 iso-date)))
15454 (deltan
15455 (setq futurep nil)
15456 (unless deltadef
15457 (let ((now (decode-time (current-time))))
15458 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
15459 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
15460 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
15461 ((equal deltaw "m") (setq month (+ month deltan)))
15462 ((equal deltaw "y") (setq year (+ year deltan)))))
15463 ((and wday (not (nth 3 tl)))
15464 (setq futurep nil)
15465 ;; Weekday was given, but no day, so pick that day in the week
15466 ;; on or after the derived date.
15467 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
15468 (unless (equal wday wday1)
15469 (setq day (+ day (% (- wday wday1 -7) 7))))))
15470 (if (and (boundp 'org-time-was-given)
15471 (nth 2 tl))
15472 (setq org-time-was-given t))
15473 (if (< year 100) (setq year (+ 2000 year)))
15474 ;; Check of the date is representable
15475 (if org-read-date-force-compatible-dates
15476 (progn
15477 (if (< year 1970)
15478 (setq year 1970 org-read-date-analyze-forced-year t))
15479 (if (> year 2037)
15480 (setq year 2037 org-read-date-analyze-forced-year t)))
15481 (condition-case nil
15482 (ignore (encode-time second minute hour day month year))
15483 (error
15484 (setq year (nth 5 org-defdecode))
15485 (setq org-read-date-analyze-forced-year t))))
15486 (setq org-read-date-analyze-futurep futurep)
15487 (list second minute hour day month year)))
15489 (defvar parse-time-weekdays)
15490 (defun org-read-date-get-relative (s today default)
15491 "Check string S for special relative date string.
15492 TODAY and DEFAULT are internal times, for today and for a default.
15493 Return shift list (N what def-flag)
15494 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
15495 N is the number of WHATs to shift.
15496 DEF-FLAG is t when a double ++ or -- indicates shift relative to
15497 the DEFAULT date rather than TODAY."
15498 (require 'parse-time)
15499 (when (and
15500 (string-match
15501 (concat
15502 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
15503 "\\([0-9]+\\)?"
15504 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
15505 "\\([ \t]\\|$\\)") s)
15506 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
15507 (let* ((dir (if (> (match-end 1) (match-beginning 1))
15508 (string-to-char (substring (match-string 1 s) -1))
15509 ?+))
15510 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
15511 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
15512 (what (if (match-end 3) (match-string 3 s) "d"))
15513 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
15514 (date (if rel default today))
15515 (wday (nth 6 (decode-time date)))
15516 delta)
15517 (if wday1
15518 (progn
15519 (setq delta (mod (+ 7 (- wday1 wday)) 7))
15520 (if (= dir ?-) (setq delta (- delta 7)))
15521 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
15522 (list delta "d" rel))
15523 (list (* n (if (= dir ?-) -1 1)) what rel)))))
15525 (defun org-order-calendar-date-args (arg1 arg2 arg3)
15526 "Turn a user-specified date into the internal representation.
15527 The internal representation needed by the calendar is (month day year).
15528 This is a wrapper to handle the brain-dead convention in calendar that
15529 user function argument order change dependent on argument order."
15530 (if (boundp 'calendar-date-style)
15531 (cond
15532 ((eq calendar-date-style 'american)
15533 (list arg1 arg2 arg3))
15534 ((eq calendar-date-style 'european)
15535 (list arg2 arg1 arg3))
15536 ((eq calendar-date-style 'iso)
15537 (list arg2 arg3 arg1)))
15538 (with-no-warnings ;; european-calendar-style is obsolete as of version 23.1
15539 (if (org-bound-and-true-p european-calendar-style)
15540 (list arg2 arg1 arg3)
15541 (list arg1 arg2 arg3)))))
15543 (defun org-eval-in-calendar (form &optional keepdate)
15544 "Eval FORM in the calendar window and return to current window.
15545 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
15546 otherwise stick to the current value of `org-ans2'."
15547 (let ((sf (selected-frame))
15548 (sw (selected-window)))
15549 (select-window (get-buffer-window "*Calendar*" t))
15550 (eval form)
15551 (when (and (not keepdate) (calendar-cursor-to-date))
15552 (let* ((date (calendar-cursor-to-date))
15553 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15554 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
15555 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
15556 (select-window sw)
15557 (org-select-frame-set-input-focus sf)))
15559 (defun org-calendar-select ()
15560 "Return to `org-read-date' with the date currently selected.
15561 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15562 (interactive)
15563 (when (calendar-cursor-to-date)
15564 (let* ((date (calendar-cursor-to-date))
15565 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15566 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15567 (if (active-minibuffer-window) (exit-minibuffer))))
15569 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
15570 "Insert a date stamp for the date given by the internal TIME.
15571 WITH-HM means use the stamp format that includes the time of the day.
15572 INACTIVE means use square brackets instead of angular ones, so that the
15573 stamp will not contribute to the agenda.
15574 PRE and POST are optional strings to be inserted before and after the
15575 stamp.
15576 The command returns the inserted time stamp."
15577 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
15578 stamp)
15579 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
15580 (insert-before-markers (or pre ""))
15581 (when (listp extra)
15582 (setq extra (car extra))
15583 (if (and (stringp extra)
15584 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
15585 (setq extra (format "-%02d:%02d"
15586 (string-to-number (match-string 1 extra))
15587 (string-to-number (match-string 2 extra))))
15588 (setq extra nil)))
15589 (when extra
15590 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
15591 (insert-before-markers (setq stamp (format-time-string fmt time)))
15592 (insert-before-markers (or post ""))
15593 (setq org-last-inserted-timestamp stamp)))
15595 (defun org-toggle-time-stamp-overlays ()
15596 "Toggle the use of custom time stamp formats."
15597 (interactive)
15598 (setq org-display-custom-times (not org-display-custom-times))
15599 (unless org-display-custom-times
15600 (let ((p (point-min)) (bmp (buffer-modified-p)))
15601 (while (setq p (next-single-property-change p 'display))
15602 (if (and (get-text-property p 'display)
15603 (eq (get-text-property p 'face) 'org-date))
15604 (remove-text-properties
15605 p (setq p (next-single-property-change p 'display))
15606 '(display t))))
15607 (set-buffer-modified-p bmp)))
15608 (if (featurep 'xemacs)
15609 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
15610 (org-restart-font-lock)
15611 (setq org-table-may-need-update t)
15612 (if org-display-custom-times
15613 (message "Time stamps are overlaid with custom format")
15614 (message "Time stamp overlays removed")))
15616 (defun org-display-custom-time (beg end)
15617 "Overlay modified time stamp format over timestamp between BEG and END."
15618 (let* ((ts (buffer-substring beg end))
15619 t1 w1 with-hm tf time str w2 (off 0))
15620 (save-match-data
15621 (setq t1 (org-parse-time-string ts t))
15622 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
15623 (setq off (- (match-end 0) (match-beginning 0)))))
15624 (setq end (- end off))
15625 (setq w1 (- end beg)
15626 with-hm (and (nth 1 t1) (nth 2 t1))
15627 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
15628 time (org-fix-decoded-time t1)
15629 str (org-add-props
15630 (format-time-string
15631 (substring tf 1 -1) (apply 'encode-time time))
15632 nil 'mouse-face 'highlight)
15633 w2 (length str))
15634 (if (not (= w2 w1))
15635 (add-text-properties (1+ beg) (+ 2 beg)
15636 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
15637 (if (featurep 'xemacs)
15638 (progn
15639 (put-text-property beg end 'invisible t)
15640 (put-text-property beg end 'end-glyph (make-glyph str)))
15641 (put-text-property beg end 'display str))))
15643 (defun org-translate-time (string)
15644 "Translate all timestamps in STRING to custom format.
15645 But do this only if the variable `org-display-custom-times' is set."
15646 (when org-display-custom-times
15647 (save-match-data
15648 (let* ((start 0)
15649 (re org-ts-regexp-both)
15650 t1 with-hm inactive tf time str beg end)
15651 (while (setq start (string-match re string start))
15652 (setq beg (match-beginning 0)
15653 end (match-end 0)
15654 t1 (save-match-data
15655 (org-parse-time-string (substring string beg end) t))
15656 with-hm (and (nth 1 t1) (nth 2 t1))
15657 inactive (equal (substring string beg (1+ beg)) "[")
15658 tf (funcall (if with-hm 'cdr 'car)
15659 org-time-stamp-custom-formats)
15660 time (org-fix-decoded-time t1)
15661 str (format-time-string
15662 (concat
15663 (if inactive "[" "<") (substring tf 1 -1)
15664 (if inactive "]" ">"))
15665 (apply 'encode-time time))
15666 string (replace-match str t t string)
15667 start (+ start (length str)))))))
15668 string)
15670 (defun org-fix-decoded-time (time)
15671 "Set 0 instead of nil for the first 6 elements of time.
15672 Don't touch the rest."
15673 (let ((n 0))
15674 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
15676 (defun org-days-to-time (timestamp-string)
15677 "Difference between TIMESTAMP-STRING and now in days."
15678 (- (time-to-days (org-time-string-to-time timestamp-string))
15679 (time-to-days (current-time))))
15681 (defun org-deadline-close (timestamp-string &optional ndays)
15682 "Is the time in TIMESTAMP-STRING close to the current date?"
15683 (setq ndays (or ndays (org-get-wdays timestamp-string)))
15684 (and (< (org-days-to-time timestamp-string) ndays)
15685 (not (org-entry-is-done-p))))
15687 (defun org-get-wdays (ts)
15688 "Get the deadline lead time appropriate for timestring TS."
15689 (cond
15690 ((<= org-deadline-warning-days 0)
15691 ;; 0 or negative, enforce this value no matter what
15692 (- org-deadline-warning-days))
15693 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
15694 ;; lead time is specified.
15695 (floor (* (string-to-number (match-string 1 ts))
15696 (cdr (assoc (match-string 2 ts)
15697 '(("d" . 1) ("w" . 7)
15698 ("m" . 30.4) ("y" . 365.25)))))))
15699 ;; go for the default.
15700 (t org-deadline-warning-days)))
15702 (defun org-calendar-select-mouse (ev)
15703 "Return to `org-read-date' with the date currently selected.
15704 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15705 (interactive "e")
15706 (mouse-set-point ev)
15707 (when (calendar-cursor-to-date)
15708 (let* ((date (calendar-cursor-to-date))
15709 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15710 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15711 (if (active-minibuffer-window) (exit-minibuffer))))
15713 (defun org-check-deadlines (ndays)
15714 "Check if there are any deadlines due or past due.
15715 A deadline is considered due if it happens within `org-deadline-warning-days'
15716 days from today's date. If the deadline appears in an entry marked DONE,
15717 it is not shown. The prefix arg NDAYS can be used to test that many
15718 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
15719 (interactive "P")
15720 (let* ((org-warn-days
15721 (cond
15722 ((equal ndays '(4)) 100000)
15723 (ndays (prefix-numeric-value ndays))
15724 (t (abs org-deadline-warning-days))))
15725 (case-fold-search nil)
15726 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
15727 (callback
15728 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
15730 (message "%d deadlines past-due or due within %d days"
15731 (org-occur regexp nil callback)
15732 org-warn-days)))
15734 (defun org-check-before-date (date)
15735 "Check if there are deadlines or scheduled entries before DATE."
15736 (interactive (list (org-read-date)))
15737 (let ((case-fold-search nil)
15738 (regexp (concat "\\<\\(" org-deadline-string
15739 "\\|" org-scheduled-string
15740 "\\) *<\\([^>]+\\)>"))
15741 (callback
15742 (lambda () (time-less-p
15743 (org-time-string-to-time (match-string 2))
15744 (org-time-string-to-time date)))))
15745 (message "%d entries before %s"
15746 (org-occur regexp nil callback) date)))
15748 (defun org-check-after-date (date)
15749 "Check if there are deadlines or scheduled entries after DATE."
15750 (interactive (list (org-read-date)))
15751 (let ((case-fold-search nil)
15752 (regexp (concat "\\<\\(" org-deadline-string
15753 "\\|" org-scheduled-string
15754 "\\) *<\\([^>]+\\)>"))
15755 (callback
15756 (lambda () (not
15757 (time-less-p
15758 (org-time-string-to-time (match-string 2))
15759 (org-time-string-to-time date))))))
15760 (message "%d entries after %s"
15761 (org-occur regexp nil callback) date)))
15763 (defun org-check-dates-range (start-date end-date)
15764 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
15765 (interactive (list (org-read-date nil nil nil "Range starts")
15766 (org-read-date nil nil nil "Range end")))
15767 (let ((case-fold-search nil)
15768 (regexp (concat "\\<\\(" org-deadline-string
15769 "\\|" org-scheduled-string
15770 "\\) *<\\([^>]+\\)>"))
15771 (callback
15772 (lambda ()
15773 (let ((match (match-string 2)))
15774 (and
15775 (not (time-less-p
15776 (org-time-string-to-time match)
15777 (org-time-string-to-time start-date)))
15778 (time-less-p
15779 (org-time-string-to-time match)
15780 (org-time-string-to-time end-date)))))))
15781 (message "%d entries between %s and %s"
15782 (org-occur regexp nil callback) start-date end-date)))
15784 (defun org-evaluate-time-range (&optional to-buffer)
15785 "Evaluate a time range by computing the difference between start and end.
15786 Normally the result is just printed in the echo area, but with prefix arg
15787 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
15788 If the time range is actually in a table, the result is inserted into the
15789 next column.
15790 For time difference computation, a year is assumed to be exactly 365
15791 days in order to avoid rounding problems."
15792 (interactive "P")
15794 (org-clock-update-time-maybe)
15795 (save-excursion
15796 (unless (org-at-date-range-p t)
15797 (goto-char (point-at-bol))
15798 (re-search-forward org-tr-regexp-both (point-at-eol) t))
15799 (if (not (org-at-date-range-p t))
15800 (error "Not at a time-stamp range, and none found in current line")))
15801 (let* ((ts1 (match-string 1))
15802 (ts2 (match-string 2))
15803 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
15804 (match-end (match-end 0))
15805 (time1 (org-time-string-to-time ts1))
15806 (time2 (org-time-string-to-time ts2))
15807 (t1 (org-float-time time1))
15808 (t2 (org-float-time time2))
15809 (diff (abs (- t2 t1)))
15810 (negative (< (- t2 t1) 0))
15811 ;; (ys (floor (* 365 24 60 60)))
15812 (ds (* 24 60 60))
15813 (hs (* 60 60))
15814 (fy "%dy %dd %02d:%02d")
15815 (fy1 "%dy %dd")
15816 (fd "%dd %02d:%02d")
15817 (fd1 "%dd")
15818 (fh "%02d:%02d")
15819 y d h m align)
15820 (if havetime
15821 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
15823 d (floor (/ diff ds)) diff (mod diff ds)
15824 h (floor (/ diff hs)) diff (mod diff hs)
15825 m (floor (/ diff 60)))
15826 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
15828 d (floor (+ (/ diff ds) 0.5))
15829 h 0 m 0))
15830 (if (not to-buffer)
15831 (message "%s" (org-make-tdiff-string y d h m))
15832 (if (org-at-table-p)
15833 (progn
15834 (goto-char match-end)
15835 (setq align t)
15836 (and (looking-at " *|") (goto-char (match-end 0))))
15837 (goto-char match-end))
15838 (if (looking-at
15839 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
15840 (replace-match ""))
15841 (if negative (insert " -"))
15842 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
15843 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
15844 (insert " " (format fh h m))))
15845 (if align (org-table-align))
15846 (message "Time difference inserted")))))
15848 (defun org-make-tdiff-string (y d h m)
15849 (let ((fmt "")
15850 (l nil))
15851 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
15852 l (push y l)))
15853 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
15854 l (push d l)))
15855 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
15856 l (push h l)))
15857 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
15858 l (push m l)))
15859 (apply 'format fmt (nreverse l))))
15861 (defun org-time-string-to-time (s &optional buffer pos)
15862 (condition-case errdata
15863 (apply 'encode-time (org-parse-time-string s))
15864 (error (error "Bad timestamp `%s'%s\nError was: %s"
15865 s (if (not (and buffer pos))
15867 (format " at %d in buffer `%s'" pos buffer))
15868 (cdr errdata)))))
15870 (defun org-time-string-to-seconds (s)
15871 (org-float-time (org-time-string-to-time s)))
15873 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
15874 "Convert a time stamp to an absolute day number.
15875 If there is a specifier for a cyclic time stamp, get the closest date to
15876 DAYNR.
15877 PREFER and SHOW-ALL are passed through to `org-closest-date'.
15878 The variable date is bound by the calendar when this is called."
15879 (cond
15880 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
15881 (if (org-diary-sexp-entry (match-string 1 s) "" date)
15882 daynr
15883 (+ daynr 1000)))
15884 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
15885 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
15886 (time-to-days (current-time))) (match-string 0 s)
15887 prefer show-all))
15888 (t (time-to-days
15889 (condition-case errdata
15890 (apply 'encode-time (org-parse-time-string s))
15891 (error (error "Bad timestamp `%s'%s\nError was: %s"
15892 s (if (not (and buffer pos))
15894 (format " at %d in buffer `%s'" pos buffer))
15895 (cdr errdata))))))))
15897 (defun org-days-to-iso-week (days)
15898 "Return the iso week number."
15899 (require 'cal-iso)
15900 (car (calendar-iso-from-absolute days)))
15902 (defun org-small-year-to-year (year)
15903 "Convert 2-digit years into 4-digit years.
15904 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
15905 The year 2000 cannot be abbreviated. Any year larger than 99
15906 is returned unchanged."
15907 (if (< year 38)
15908 (setq year (+ 2000 year))
15909 (if (< year 100)
15910 (setq year (+ 1900 year))))
15911 year)
15913 (defun org-time-from-absolute (d)
15914 "Return the time corresponding to date D.
15915 D may be an absolute day number, or a calendar-type list (month day year)."
15916 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
15917 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
15919 (defun org-calendar-holiday ()
15920 "List of holidays, for Diary display in Org-mode."
15921 (require 'holidays)
15922 (let ((hl (funcall
15923 (if (fboundp 'calendar-check-holidays)
15924 'calendar-check-holidays 'check-calendar-holidays) date)))
15925 (if hl (mapconcat 'identity hl "; "))))
15927 (defun org-diary-sexp-entry (sexp entry date)
15928 "Process a SEXP diary ENTRY for DATE."
15929 (require 'diary-lib)
15930 (let ((result (if calendar-debug-sexp
15931 (let ((stack-trace-on-error t))
15932 (eval (car (read-from-string sexp))))
15933 (condition-case nil
15934 (eval (car (read-from-string sexp)))
15935 (error
15936 (beep)
15937 (message "Bad sexp at line %d in %s: %s"
15938 (org-current-line)
15939 (buffer-file-name) sexp)
15940 (sleep-for 2))))))
15941 (cond ((stringp result) (split-string result "; "))
15942 ((and (consp result)
15943 (not (consp (cdr result)))
15944 (stringp (cdr result))) (cdr result))
15945 ((and (consp result)
15946 (stringp (car result))) result)
15947 (result entry)
15948 (t nil))))
15950 (defun org-diary-to-ical-string (frombuf)
15951 "Get iCalendar entries from diary entries in buffer FROMBUF.
15952 This uses the icalendar.el library."
15953 (let* ((tmpdir (if (featurep 'xemacs)
15954 (temp-directory)
15955 temporary-file-directory))
15956 (tmpfile (make-temp-name
15957 (expand-file-name "orgics" tmpdir)))
15958 buf rtn b e)
15959 (with-current-buffer frombuf
15960 (icalendar-export-region (point-min) (point-max) tmpfile)
15961 (setq buf (find-buffer-visiting tmpfile))
15962 (set-buffer buf)
15963 (goto-char (point-min))
15964 (if (re-search-forward "^BEGIN:VEVENT" nil t)
15965 (setq b (match-beginning 0)))
15966 (goto-char (point-max))
15967 (if (re-search-backward "^END:VEVENT" nil t)
15968 (setq e (match-end 0)))
15969 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
15970 (kill-buffer buf)
15971 (delete-file tmpfile)
15972 rtn))
15974 (defun org-closest-date (start current change prefer show-all)
15975 "Find the date closest to CURRENT that is consistent with START and CHANGE.
15976 When PREFER is `past', return a date that is either CURRENT or past.
15977 When PREFER is `future', return a date that is either CURRENT or future.
15978 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
15979 ;; Make the proper lists from the dates
15980 (catch 'exit
15981 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
15982 dn dw sday cday n1 n2 n0
15983 d m y y1 y2 date1 date2 nmonths nm ny m2)
15985 (setq start (org-date-to-gregorian start)
15986 current (org-date-to-gregorian
15987 (if show-all
15988 current
15989 (time-to-days (current-time))))
15990 sday (calendar-absolute-from-gregorian start)
15991 cday (calendar-absolute-from-gregorian current))
15993 (if (<= cday sday) (throw 'exit sday))
15995 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
15996 (setq dn (string-to-number (match-string 1 change))
15997 dw (cdr (assoc (match-string 2 change) a1)))
15998 (error "Invalid change specifier: %s" change))
15999 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
16000 (cond
16001 ((eq dw 'day)
16002 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
16003 n2 (+ n1 dn)))
16004 ((eq dw 'year)
16005 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
16006 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
16007 (setq date1 (list m d y1)
16008 n1 (calendar-absolute-from-gregorian date1)
16009 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
16010 n2 (calendar-absolute-from-gregorian date2)))
16011 ((eq dw 'month)
16012 ;; approx number of month between the two dates
16013 (setq nmonths (floor (/ (- cday sday) 30.436875)))
16014 ;; How often does dn fit in there?
16015 (setq d (nth 1 start) m (car start) y (nth 2 start)
16016 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
16017 m (+ m nm)
16018 ny (floor (/ m 12))
16019 y (+ y ny)
16020 m (- m (* ny 12)))
16021 (while (> m 12) (setq m (- m 12) y (1+ y)))
16022 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
16023 (setq m2 (+ m dn) y2 y)
16024 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16025 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
16026 (while (<= n2 cday)
16027 (setq n1 n2 m m2 y y2)
16028 (setq m2 (+ m dn) y2 y)
16029 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16030 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
16031 ;; Make sure n1 is the earlier date
16032 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
16033 (if show-all
16034 (cond
16035 ((eq prefer 'past) (if (= cday n2) n2 n1))
16036 ((eq prefer 'future) (if (= cday n1) n1 n2))
16037 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
16038 (cond
16039 ((eq prefer 'past) (if (= cday n2) n2 n1))
16040 ((eq prefer 'future) (if (= cday n1) n1 n2))
16041 (t (if (= cday n1) n1 n2)))))))
16043 (defun org-date-to-gregorian (date)
16044 "Turn any specification of DATE into a Gregorian date for the calendar."
16045 (cond ((integerp date) (calendar-gregorian-from-absolute date))
16046 ((and (listp date) (= (length date) 3)) date)
16047 ((stringp date)
16048 (setq date (org-parse-time-string date))
16049 (list (nth 4 date) (nth 3 date) (nth 5 date)))
16050 ((listp date)
16051 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
16053 (defun org-parse-time-string (s &optional nodefault)
16054 "Parse the standard Org-mode time string.
16055 This should be a lot faster than the normal `parse-time-string'.
16056 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
16057 hour and minute fields will be nil if not given."
16058 (if (string-match org-ts-regexp0 s)
16059 (list 0
16060 (if (or (match-beginning 8) (not nodefault))
16061 (string-to-number (or (match-string 8 s) "0")))
16062 (if (or (match-beginning 7) (not nodefault))
16063 (string-to-number (or (match-string 7 s) "0")))
16064 (string-to-number (match-string 4 s))
16065 (string-to-number (match-string 3 s))
16066 (string-to-number (match-string 2 s))
16067 nil nil nil)
16068 (error "Not a standard Org-mode time string: %s" s)))
16070 (defun org-timestamp-up (&optional arg)
16071 "Increase the date item at the cursor by one.
16072 If the cursor is on the year, change the year. If it is on the month,
16073 the day or the time, change that.
16074 With prefix ARG, change by that many units."
16075 (interactive "p")
16076 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
16078 (defun org-timestamp-down (&optional arg)
16079 "Decrease the date item at the cursor by one.
16080 If the cursor is on the year, change the year. If it is on the month,
16081 the day or the time, change that.
16082 With prefix ARG, change by that many units."
16083 (interactive "p")
16084 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
16086 (defun org-timestamp-up-day (&optional arg)
16087 "Increase the date in the time stamp by one day.
16088 With prefix ARG, change that many days."
16089 (interactive "p")
16090 (if (and (not (org-at-timestamp-p t))
16091 (org-at-heading-p))
16092 (org-todo 'up)
16093 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
16095 (defun org-timestamp-down-day (&optional arg)
16096 "Decrease the date in the time stamp by one day.
16097 With prefix ARG, change that many days."
16098 (interactive "p")
16099 (if (and (not (org-at-timestamp-p t))
16100 (org-at-heading-p))
16101 (org-todo 'down)
16102 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
16104 (defun org-at-timestamp-p (&optional inactive-ok)
16105 "Determine if the cursor is in or at a timestamp."
16106 (interactive)
16107 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
16108 (pos (point))
16109 (ans (or (looking-at tsr)
16110 (save-excursion
16111 (skip-chars-backward "^[<\n\r\t")
16112 (if (> (point) (point-min)) (backward-char 1))
16113 (and (looking-at tsr)
16114 (> (- (match-end 0) pos) -1))))))
16115 (and ans
16116 (boundp 'org-ts-what)
16117 (setq org-ts-what
16118 (cond
16119 ((= pos (match-beginning 0)) 'bracket)
16120 ;; Point is considered to be "on the bracket" whether
16121 ;; it's really on it or right after it.
16122 ((or (= pos (1- (match-end 0)))
16123 (= pos (match-end 0))) 'bracket)
16124 ((org-pos-in-match-range pos 2) 'year)
16125 ((org-pos-in-match-range pos 3) 'month)
16126 ((org-pos-in-match-range pos 7) 'hour)
16127 ((org-pos-in-match-range pos 8) 'minute)
16128 ((or (org-pos-in-match-range pos 4)
16129 (org-pos-in-match-range pos 5)) 'day)
16130 ((and (> pos (or (match-end 8) (match-end 5)))
16131 (< pos (match-end 0)))
16132 (- pos (or (match-end 8) (match-end 5))))
16133 (t 'day))))
16134 ans))
16136 (defun org-toggle-timestamp-type ()
16137 "Toggle the type (<active> or [inactive]) of a time stamp."
16138 (interactive)
16139 (when (org-at-timestamp-p t)
16140 (let ((beg (match-beginning 0)) (end (match-end 0))
16141 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
16142 (save-excursion
16143 (goto-char beg)
16144 (while (re-search-forward "[][<>]" end t)
16145 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
16146 t t)))
16147 (message "Timestamp is now %sactive"
16148 (if (equal (char-after beg) ?<) "" "in")))))
16150 (defun org-timestamp-change (n &optional what updown)
16151 "Change the date in the time stamp at point.
16152 The date will be changed by N times WHAT. WHAT can be `day', `month',
16153 `year', `minute', `second'. If WHAT is not given, the cursor position
16154 in the timestamp determines what will be changed."
16155 (let ((origin (point)) origin-cat
16156 with-hm inactive
16157 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
16158 org-ts-what
16159 extra rem
16160 ts time time0)
16161 (if (not (org-at-timestamp-p t))
16162 (error "Not at a timestamp"))
16163 (if (and (not what) (eq org-ts-what 'bracket))
16164 (org-toggle-timestamp-type)
16165 ;; Point isn't on brackets. Remember the part of the time-stamp
16166 ;; the point was in. Indeed, size of time-stamps may change,
16167 ;; but point must be kept in the same category nonetheless.
16168 (setq origin-cat org-ts-what)
16169 (if (and (not what) (not (eq org-ts-what 'day))
16170 org-display-custom-times
16171 (get-text-property (point) 'display)
16172 (not (get-text-property (1- (point)) 'display)))
16173 (setq org-ts-what 'day))
16174 (setq org-ts-what (or what org-ts-what)
16175 inactive (= (char-after (match-beginning 0)) ?\[)
16176 ts (match-string 0))
16177 (replace-match "")
16178 (if (string-match
16179 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
16181 (setq extra (match-string 1 ts)))
16182 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
16183 (setq with-hm t))
16184 (setq time0 (org-parse-time-string ts))
16185 (when (and updown
16186 (eq org-ts-what 'minute)
16187 (not current-prefix-arg))
16188 ;; This looks like s-up and s-down. Change by one rounding step.
16189 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
16190 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
16191 (setcar (cdr time0) (+ (nth 1 time0)
16192 (if (> n 0) (- rem) (- dm rem))))))
16193 (setq time
16194 (encode-time (or (car time0) 0)
16195 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
16196 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
16197 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
16198 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
16199 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
16200 (nthcdr 6 time0)))
16201 (when (and (member org-ts-what '(hour minute))
16202 extra
16203 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
16204 (setq extra (org-modify-ts-extra
16205 extra
16206 (if (eq org-ts-what 'hour) 2 5)
16207 n dm)))
16208 (when (integerp org-ts-what)
16209 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
16210 (if (eq what 'calendar)
16211 (let ((cal-date (org-get-date-from-calendar)))
16212 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
16213 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
16214 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
16215 (setcar time0 (or (car time0) 0))
16216 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
16217 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
16218 (setq time (apply 'encode-time time0))))
16219 ;; Insert the new time-stamp, and ensure point stays in the same
16220 ;; category as before (i.e. not after the last position in that
16221 ;; category).
16222 (let ((pos (point)))
16223 ;; Stay before inserted string. `save-excursion' is of no use.
16224 (setq org-last-changed-timestamp
16225 (org-insert-time-stamp time with-hm inactive nil nil extra))
16226 (goto-char pos))
16227 (save-match-data
16228 (looking-at org-ts-regexp3)
16229 (goto-char (cond
16230 ;; `day' category ends before `hour' if any, or at
16231 ;; the end of the day name.
16232 ((eq origin-cat 'day)
16233 (min (or (match-beginning 7) (1- (match-end 5))) origin))
16234 ((eq origin-cat 'hour) (min (match-end 7) origin))
16235 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
16236 ((integerp origin-cat) (min (1- (match-end 0)) origin))
16237 ;; `year' and `month' have both fixed size: point
16238 ;; couldn't have moved into another part.
16239 (t origin))))
16240 ;; Update clock if on a CLOCK line.
16241 (org-clock-update-time-maybe)
16242 ;; Try to recenter the calendar window, if any.
16243 (if (and org-calendar-follow-timestamp-change
16244 (get-buffer-window "*Calendar*" t)
16245 (memq org-ts-what '(day month year)))
16246 (org-recenter-calendar (time-to-days time))))))
16248 (defun org-modify-ts-extra (s pos n dm)
16249 "Change the different parts of the lead-time and repeat fields in timestamp."
16250 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
16251 ng h m new rem)
16252 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
16253 (cond
16254 ((or (org-pos-in-match-range pos 2)
16255 (org-pos-in-match-range pos 3))
16256 (setq m (string-to-number (match-string 3 s))
16257 h (string-to-number (match-string 2 s)))
16258 (if (org-pos-in-match-range pos 2)
16259 (setq h (+ h n))
16260 (setq n (* dm (org-no-warnings (signum n))))
16261 (when (not (= 0 (setq rem (% m dm))))
16262 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
16263 (setq m (+ m n)))
16264 (if (< m 0) (setq m (+ m 60) h (1- h)))
16265 (if (> m 59) (setq m (- m 60) h (1+ h)))
16266 (setq h (min 24 (max 0 h)))
16267 (setq ng 1 new (format "-%02d:%02d" h m)))
16268 ((org-pos-in-match-range pos 6)
16269 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
16270 ((org-pos-in-match-range pos 5)
16271 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
16273 ((org-pos-in-match-range pos 9)
16274 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
16275 ((org-pos-in-match-range pos 8)
16276 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
16278 (when ng
16279 (setq s (concat
16280 (substring s 0 (match-beginning ng))
16282 (substring s (match-end ng))))))
16285 (defun org-recenter-calendar (date)
16286 "If the calendar is visible, recenter it to DATE."
16287 (let ((cwin (get-buffer-window "*Calendar*" t)))
16288 (when cwin
16289 (let ((calendar-move-hook nil))
16290 (with-selected-window cwin
16291 (calendar-goto-date (if (listp date) date
16292 (calendar-gregorian-from-absolute date))))))))
16294 (defun org-goto-calendar (&optional arg)
16295 "Go to the Emacs calendar at the current date.
16296 If there is a time stamp in the current line, go to that date.
16297 A prefix ARG can be used to force the current date."
16298 (interactive "P")
16299 (let ((tsr org-ts-regexp) diff
16300 (calendar-move-hook nil)
16301 (calendar-view-holidays-initially-flag nil)
16302 (calendar-view-diary-initially-flag nil))
16303 (if (or (org-at-timestamp-p)
16304 (save-excursion
16305 (beginning-of-line 1)
16306 (looking-at (concat ".*" tsr))))
16307 (let ((d1 (time-to-days (current-time)))
16308 (d2 (time-to-days
16309 (org-time-string-to-time (match-string 1)))))
16310 (setq diff (- d2 d1))))
16311 (calendar)
16312 (calendar-goto-today)
16313 (if (and diff (not arg)) (calendar-forward-day diff))))
16315 (defun org-get-date-from-calendar ()
16316 "Return a list (month day year) of date at point in calendar."
16317 (with-current-buffer "*Calendar*"
16318 (save-match-data
16319 (calendar-cursor-to-date))))
16321 (defun org-date-from-calendar ()
16322 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
16323 If there is already a time stamp at the cursor position, update it."
16324 (interactive)
16325 (if (org-at-timestamp-p t)
16326 (org-timestamp-change 0 'calendar)
16327 (let ((cal-date (org-get-date-from-calendar)))
16328 (org-insert-time-stamp
16329 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
16331 (defun org-minutes-to-hh:mm-string (m)
16332 "Compute H:MM from a number of minutes."
16333 (let ((h (/ m 60)))
16334 (setq m (- m (* 60 h)))
16335 (format org-time-clocksum-format h m)))
16337 (defun org-hh:mm-string-to-minutes (s)
16338 "Convert a string H:MM to a number of minutes.
16339 If the string is just a number, interpret it as minutes.
16340 In fact, the first hh:mm or number in the string will be taken,
16341 there can be extra stuff in the string.
16342 If no number is found, the return value is 0."
16343 (cond
16344 ((integerp s) s)
16345 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
16346 (+ (* (string-to-number (match-string 1 s)) 60)
16347 (string-to-number (match-string 2 s))))
16348 ((string-match "\\([0-9]+\\)" s)
16349 (string-to-number (match-string 1 s)))
16350 (t 0)))
16352 (defcustom org-effort-durations
16353 `(("h" . 60)
16354 ("d" . ,(* 60 8))
16355 ("w" . ,(* 60 8 5))
16356 ("m" . ,(* 60 8 5 4))
16357 ("y" . ,(* 60 8 5 40)))
16358 "Conversion factor to minutes for an effort modifier.
16360 Each entry has the form (MODIFIER . MINUTES).
16362 In an effort string, a number followed by MODIFIER is multiplied
16363 by the specified number of MINUTES to obtain an effort in
16364 minutes.
16366 For example, if the value of this variable is ((\"hours\" . 60)), then an
16367 effort string \"2hours\" is equivalent to 120 minutes."
16368 :group 'org-agenda
16369 :version "24.1"
16370 :type '(alist :key-type (string :tag "Modifier")
16371 :value-type (number :tag "Minutes")))
16373 (defun org-duration-string-to-minutes (s)
16374 "Convert a duration string S to minutes.
16376 A bare number is interpreted as minutes, modifiers can be set by
16377 customizing `org-effort-durations' (which see).
16379 Entries containing a colon are interpreted as H:MM by
16380 `org-hh:mm-string-to-minutes'."
16381 (let ((result 0)
16382 (re (concat "\\([0-9]+\\) *\\("
16383 (regexp-opt (mapcar 'car org-effort-durations))
16384 "\\)")))
16385 (while (string-match re s)
16386 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
16387 (string-to-number (match-string 1 s))))
16388 (setq s (replace-match "" nil t s)))
16389 (incf result (org-hh:mm-string-to-minutes s))
16390 result))
16392 ;;;; Files
16394 (defun org-save-all-org-buffers ()
16395 "Save all Org-mode buffers without user confirmation."
16396 (interactive)
16397 (message "Saving all Org-mode buffers...")
16398 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
16399 (when (featurep 'org-id) (org-id-locations-save))
16400 (message "Saving all Org-mode buffers... done"))
16402 (defun org-revert-all-org-buffers ()
16403 "Revert all Org-mode buffers.
16404 Prompt for confirmation when there are unsaved changes.
16405 Be sure you know what you are doing before letting this function
16406 overwrite your changes.
16408 This function is useful in a setup where one tracks org files
16409 with a version control system, to revert on one machine after pulling
16410 changes from another. I believe the procedure must be like this:
16412 1. M-x org-save-all-org-buffers
16413 2. Pull changes from the other machine, resolve conflicts
16414 3. M-x org-revert-all-org-buffers"
16415 (interactive)
16416 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
16417 (error "Abort"))
16418 (save-excursion
16419 (save-window-excursion
16420 (mapc
16421 (lambda (b)
16422 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
16423 (with-current-buffer b buffer-file-name))
16424 (org-pop-to-buffer-same-window b)
16425 (revert-buffer t 'no-confirm)))
16426 (buffer-list))
16427 (when (and (featurep 'org-id) org-id-track-globally)
16428 (org-id-locations-load)))))
16430 ;;;; Agenda files
16432 ;;;###autoload
16433 (defun org-switchb (&optional arg)
16434 "Switch between Org buffers.
16435 With one prefix argument, restrict available buffers to files.
16436 With two prefix arguments, restrict available buffers to agenda files.
16438 Defaults to `iswitchb' for buffer name completion.
16439 Set `org-completion-use-ido' to make it use ido instead."
16440 (interactive "P")
16441 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
16442 ((equal arg '(16)) (org-buffer-list 'agenda))
16443 (t (org-buffer-list))))
16444 (org-completion-use-iswitchb org-completion-use-iswitchb)
16445 (org-completion-use-ido org-completion-use-ido))
16446 (unless (or org-completion-use-ido org-completion-use-iswitchb)
16447 (setq org-completion-use-iswitchb t))
16448 (org-pop-to-buffer-same-window
16449 (org-icompleting-read "Org buffer: "
16450 (mapcar 'list (mapcar 'buffer-name blist))
16451 nil t))))
16453 ;;; Define some older names previously used for this functionality
16454 ;;;###autoload
16455 (defalias 'org-ido-switchb 'org-switchb)
16456 ;;;###autoload
16457 (defalias 'org-iswitchb 'org-switchb)
16459 (defun org-buffer-list (&optional predicate exclude-tmp)
16460 "Return a list of Org buffers.
16461 PREDICATE can be `export', `files' or `agenda'.
16463 export restrict the list to Export buffers.
16464 files restrict the list to buffers visiting Org files.
16465 agenda restrict the list to buffers visiting agenda files.
16467 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
16468 (let* ((bfn nil)
16469 (agenda-files (and (eq predicate 'agenda)
16470 (mapcar 'file-truename (org-agenda-files t))))
16471 (filter
16472 (cond
16473 ((eq predicate 'files)
16474 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
16475 ((eq predicate 'export)
16476 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
16477 ((eq predicate 'agenda)
16478 (lambda (b)
16479 (with-current-buffer b
16480 (and (derived-mode-p 'org-mode)
16481 (setq bfn (buffer-file-name b))
16482 (member (file-truename bfn) agenda-files)))))
16483 (t (lambda (b) (with-current-buffer b
16484 (or (derived-mode-p 'org-mode)
16485 (string-match "\*Org .*Export"
16486 (buffer-name b)))))))))
16487 (delq nil
16488 (mapcar
16489 (lambda(b)
16490 (if (and (funcall filter b)
16491 (or (not exclude-tmp)
16492 (not (string-match "tmp" (buffer-name b)))))
16494 nil))
16495 (buffer-list)))))
16497 (defun org-agenda-files (&optional unrestricted archives)
16498 "Get the list of agenda files.
16499 Optional UNRESTRICTED means return the full list even if a restriction
16500 is currently in place.
16501 When ARCHIVES is t, include all archive files that are really being
16502 used by the agenda files. If ARCHIVE is `ifmode', do this only if
16503 `org-agenda-archives-mode' is t."
16504 (let ((files
16505 (cond
16506 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
16507 ((stringp org-agenda-files) (org-read-agenda-file-list))
16508 ((listp org-agenda-files) org-agenda-files)
16509 (t (error "Invalid value of `org-agenda-files'")))))
16510 (setq files (apply 'append
16511 (mapcar (lambda (f)
16512 (if (file-directory-p f)
16513 (directory-files
16514 f t org-agenda-file-regexp)
16515 (list f)))
16516 files)))
16517 (when org-agenda-skip-unavailable-files
16518 (setq files (delq nil
16519 (mapcar (function
16520 (lambda (file)
16521 (and (file-readable-p file) file)))
16522 files))))
16523 (when (or (eq archives t)
16524 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
16525 (setq files (org-add-archive-files files)))
16526 files))
16528 (defun org-agenda-file-p (&optional file)
16529 "Return non-nil, if FILE is an agenda file.
16530 If FILE is omitted, use the file associated with the current
16531 buffer."
16532 (member (or file (buffer-file-name))
16533 (org-agenda-files t)))
16535 (defun org-edit-agenda-file-list ()
16536 "Edit the list of agenda files.
16537 Depending on setup, this either uses customize to edit the variable
16538 `org-agenda-files', or it visits the file that is holding the list. In the
16539 latter case, the buffer is set up in a way that saving it automatically kills
16540 the buffer and restores the previous window configuration."
16541 (interactive)
16542 (if (stringp org-agenda-files)
16543 (let ((cw (current-window-configuration)))
16544 (find-file org-agenda-files)
16545 (org-set-local 'org-window-configuration cw)
16546 (org-add-hook 'after-save-hook
16547 (lambda ()
16548 (set-window-configuration
16549 (prog1 org-window-configuration
16550 (kill-buffer (current-buffer))))
16551 (org-install-agenda-files-menu)
16552 (message "New agenda file list installed"))
16553 nil 'local)
16554 (message "%s" (substitute-command-keys
16555 "Edit list and finish with \\[save-buffer]")))
16556 (customize-variable 'org-agenda-files)))
16558 (defun org-store-new-agenda-file-list (list)
16559 "Set new value for the agenda file list and save it correctly."
16560 (if (stringp org-agenda-files)
16561 (let ((fe (org-read-agenda-file-list t)) b u)
16562 (while (setq b (find-buffer-visiting org-agenda-files))
16563 (kill-buffer b))
16564 (with-temp-file org-agenda-files
16565 (insert
16566 (mapconcat
16567 (lambda (f) ;; Keep un-expanded entries.
16568 (if (setq u (assoc f fe))
16569 (cdr u)
16571 list "\n")
16572 "\n")))
16573 (let ((org-mode-hook nil) (org-inhibit-startup t)
16574 (org-insert-mode-line-in-empty-file nil))
16575 (setq org-agenda-files list)
16576 (customize-save-variable 'org-agenda-files org-agenda-files))))
16578 (defun org-read-agenda-file-list (&optional pair-with-expansion)
16579 "Read the list of agenda files from a file.
16580 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
16581 filenames, used by `org-store-new-agenda-file-list' to write back
16582 un-expanded file names."
16583 (when (file-directory-p org-agenda-files)
16584 (error "`org-agenda-files' cannot be a single directory"))
16585 (when (stringp org-agenda-files)
16586 (with-temp-buffer
16587 (insert-file-contents org-agenda-files)
16588 (mapcar
16589 (lambda (f)
16590 (let ((e (expand-file-name (substitute-in-file-name f)
16591 org-directory)))
16592 (if pair-with-expansion
16593 (cons e f)
16594 e)))
16595 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
16597 ;;;###autoload
16598 (defun org-cycle-agenda-files ()
16599 "Cycle through the files in `org-agenda-files'.
16600 If the current buffer visits an agenda file, find the next one in the list.
16601 If the current buffer does not, find the first agenda file."
16602 (interactive)
16603 (let* ((fs (org-agenda-files t))
16604 (files (append fs (list (car fs))))
16605 (tcf (if buffer-file-name (file-truename buffer-file-name)))
16606 file)
16607 (unless files (error "No agenda files"))
16608 (catch 'exit
16609 (while (setq file (pop files))
16610 (if (equal (file-truename file) tcf)
16611 (when (car files)
16612 (find-file (car files))
16613 (throw 'exit t))))
16614 (find-file (car fs)))
16615 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
16617 (defun org-agenda-file-to-front (&optional to-end)
16618 "Move/add the current file to the top of the agenda file list.
16619 If the file is not present in the list, it is added to the front. If it is
16620 present, it is moved there. With optional argument TO-END, add/move to the
16621 end of the list."
16622 (interactive "P")
16623 (let ((org-agenda-skip-unavailable-files nil)
16624 (file-alist (mapcar (lambda (x)
16625 (cons (file-truename x) x))
16626 (org-agenda-files t)))
16627 (ctf (file-truename buffer-file-name))
16628 x had)
16629 (setq x (assoc ctf file-alist) had x)
16631 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
16632 (if to-end
16633 (setq file-alist (append (delq x file-alist) (list x)))
16634 (setq file-alist (cons x (delq x file-alist))))
16635 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
16636 (org-install-agenda-files-menu)
16637 (message "File %s to %s of agenda file list"
16638 (if had "moved" "added") (if to-end "end" "front"))))
16640 (defun org-remove-file (&optional file)
16641 "Remove current file from the list of files in variable `org-agenda-files'.
16642 These are the files which are being checked for agenda entries.
16643 Optional argument FILE means use this file instead of the current."
16644 (interactive)
16645 (let* ((org-agenda-skip-unavailable-files nil)
16646 (file (or file buffer-file-name))
16647 (true-file (file-truename file))
16648 (afile (abbreviate-file-name file))
16649 (files (delq nil (mapcar
16650 (lambda (x)
16651 (if (equal true-file
16652 (file-truename x))
16653 nil x))
16654 (org-agenda-files t)))))
16655 (if (not (= (length files) (length (org-agenda-files t))))
16656 (progn
16657 (org-store-new-agenda-file-list files)
16658 (org-install-agenda-files-menu)
16659 (message "Removed file: %s" afile))
16660 (message "File was not in list: %s (not removed)" afile))))
16662 (defun org-file-menu-entry (file)
16663 (vector file (list 'find-file file) t))
16665 (defun org-check-agenda-file (file)
16666 "Make sure FILE exists. If not, ask user what to do."
16667 (when (not (file-exists-p file))
16668 (message "non-existent agenda file %s. [R]emove from list or [A]bort?"
16669 (abbreviate-file-name file))
16670 (let ((r (downcase (read-char-exclusive))))
16671 (cond
16672 ((equal r ?r)
16673 (org-remove-file file)
16674 (throw 'nextfile t))
16675 (t (error "Abort"))))))
16677 (defun org-get-agenda-file-buffer (file)
16678 "Get a buffer visiting FILE. If the buffer needs to be created, add
16679 it to the list of buffers which might be released later."
16680 (let ((buf (org-find-base-buffer-visiting file)))
16681 (if buf
16682 buf ; just return it
16683 ;; Make a new buffer and remember it
16684 (setq buf (find-file-noselect file))
16685 (if buf (push buf org-agenda-new-buffers))
16686 buf)))
16688 (defun org-release-buffers (blist)
16689 "Release all buffers in list, asking the user for confirmation when needed.
16690 When a buffer is unmodified, it is just killed. When modified, it is saved
16691 \(if the user agrees) and then killed."
16692 (let (buf file)
16693 (while (setq buf (pop blist))
16694 (setq file (buffer-file-name buf))
16695 (when (and (buffer-modified-p buf)
16696 file
16697 (y-or-n-p (format "Save file %s? " file)))
16698 (with-current-buffer buf (save-buffer)))
16699 (kill-buffer buf))))
16701 (defun org-prepare-agenda-buffers (files)
16702 "Create buffers for all agenda files, protect archived trees and comments."
16703 (interactive)
16704 (let ((pa '(:org-archived t))
16705 (pc '(:org-comment t))
16706 (pall '(:org-archived t :org-comment t))
16707 (inhibit-read-only t)
16708 (rea (concat ":" org-archive-tag ":"))
16709 bmp file re)
16710 (save-excursion
16711 (save-restriction
16712 (while (setq file (pop files))
16713 (catch 'nextfile
16714 (if (bufferp file)
16715 (set-buffer file)
16716 (org-check-agenda-file file)
16717 (set-buffer (org-get-agenda-file-buffer file)))
16718 (widen)
16719 (setq bmp (buffer-modified-p))
16720 (org-refresh-category-properties)
16721 (setq org-todo-keywords-for-agenda
16722 (append org-todo-keywords-for-agenda org-todo-keywords-1))
16723 (setq org-done-keywords-for-agenda
16724 (append org-done-keywords-for-agenda org-done-keywords))
16725 (setq org-todo-keyword-alist-for-agenda
16726 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
16727 (setq org-drawers-for-agenda
16728 (append org-drawers-for-agenda org-drawers))
16729 (setq org-tag-alist-for-agenda
16730 (append org-tag-alist-for-agenda org-tag-alist))
16732 (save-excursion
16733 (remove-text-properties (point-min) (point-max) pall)
16734 (when org-agenda-skip-archived-trees
16735 (goto-char (point-min))
16736 (while (re-search-forward rea nil t)
16737 (if (org-at-heading-p t)
16738 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
16739 (goto-char (point-min))
16740 (setq re (format org-heading-keyword-regexp-format
16741 org-comment-string))
16742 (while (re-search-forward re nil t)
16743 (add-text-properties
16744 (match-beginning 0) (org-end-of-subtree t) pc)))
16745 (set-buffer-modified-p bmp)))))
16746 (setq org-todo-keywords-for-agenda
16747 (org-uniquify org-todo-keywords-for-agenda))
16748 (setq org-todo-keyword-alist-for-agenda
16749 (org-uniquify org-todo-keyword-alist-for-agenda)
16750 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
16752 ;;;; Embedded LaTeX
16754 (defvar org-cdlatex-mode-map (make-sparse-keymap)
16755 "Keymap for the minor `org-cdlatex-mode'.")
16757 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
16758 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
16759 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
16760 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
16761 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
16763 (defvar org-cdlatex-texmathp-advice-is-done nil
16764 "Flag remembering if we have applied the advice to texmathp already.")
16766 (define-minor-mode org-cdlatex-mode
16767 "Toggle the minor `org-cdlatex-mode'.
16768 This mode supports entering LaTeX environment and math in LaTeX fragments
16769 in Org-mode.
16770 \\{org-cdlatex-mode-map}"
16771 nil " OCDL" nil
16772 (when org-cdlatex-mode
16773 (require 'cdlatex)
16774 (run-hooks 'cdlatex-mode-hook)
16775 (cdlatex-compute-tables))
16776 (unless org-cdlatex-texmathp-advice-is-done
16777 (setq org-cdlatex-texmathp-advice-is-done t)
16778 (defadvice texmathp (around org-math-always-on activate)
16779 "Always return t in org-mode buffers.
16780 This is because we want to insert math symbols without dollars even outside
16781 the LaTeX math segments. If Orgmode thinks that point is actually inside
16782 an embedded LaTeX fragment, let texmathp do its job.
16783 \\[org-cdlatex-mode-map]"
16784 (interactive)
16785 (let (p)
16786 (cond
16787 ((not (derived-mode-p 'org-mode)) ad-do-it)
16788 ((eq this-command 'cdlatex-math-symbol)
16789 (setq ad-return-value t
16790 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
16792 (let ((p (org-inside-LaTeX-fragment-p)))
16793 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
16794 (setq ad-return-value t
16795 texmathp-why '("Org-mode embedded math" . 0))
16796 (if p ad-do-it)))))))))
16798 (defun turn-on-org-cdlatex ()
16799 "Unconditionally turn on `org-cdlatex-mode'."
16800 (org-cdlatex-mode 1))
16802 (defun org-inside-LaTeX-fragment-p ()
16803 "Test if point is inside a LaTeX fragment.
16804 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
16805 sequence appearing also before point.
16806 Even though the matchers for math are configurable, this function assumes
16807 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
16808 delimiters are skipped when they have been removed by customization.
16809 The return value is nil, or a cons cell with the delimiter and the
16810 position of this delimiter.
16812 This function does a reasonably good job, but can locally be fooled by
16813 for example currency specifications. For example it will assume being in
16814 inline math after \"$22.34\". The LaTeX fragment formatter will only format
16815 fragments that are properly closed, but during editing, we have to live
16816 with the uncertainty caused by missing closing delimiters. This function
16817 looks only before point, not after."
16818 (catch 'exit
16819 (let ((pos (point))
16820 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
16821 (lim (progn
16822 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
16823 (point)))
16824 dd-on str (start 0) m re)
16825 (goto-char pos)
16826 (when dodollar
16827 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
16828 re (nth 1 (assoc "$" org-latex-regexps)))
16829 (while (string-match re str start)
16830 (cond
16831 ((= (match-end 0) (length str))
16832 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
16833 ((= (match-end 0) (- (length str) 5))
16834 (throw 'exit nil))
16835 (t (setq start (match-end 0))))))
16836 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
16837 (goto-char pos)
16838 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
16839 (and (match-beginning 2) (throw 'exit nil))
16840 ;; count $$
16841 (while (re-search-backward "\\$\\$" lim t)
16842 (setq dd-on (not dd-on)))
16843 (goto-char pos)
16844 (if dd-on (cons "$$" m))))))
16846 (defun org-inside-latex-macro-p ()
16847 "Is point inside a LaTeX macro or its arguments?"
16848 (save-match-data
16849 (org-in-regexp
16850 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
16852 (defun org-try-cdlatex-tab ()
16853 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
16854 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
16855 - inside a LaTeX fragment, or
16856 - after the first word in a line, where an abbreviation expansion could
16857 insert a LaTeX environment."
16858 (when org-cdlatex-mode
16859 (cond
16860 ;; Before any word on the line: No expansion possible.
16861 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
16862 ;; Just after first word on the line: Expand it. Make sure it
16863 ;; cannot happen on headlines, though.
16864 ((save-excursion
16865 (skip-chars-backward "a-zA-Z0-9*")
16866 (skip-chars-backward " \t")
16867 (and (bolp) (not (org-at-heading-p))))
16868 (cdlatex-tab) t)
16869 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
16871 (defun org-cdlatex-underscore-caret (&optional arg)
16872 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
16873 Revert to the normal definition outside of these fragments."
16874 (interactive "P")
16875 (if (org-inside-LaTeX-fragment-p)
16876 (call-interactively 'cdlatex-sub-superscript)
16877 (let (org-cdlatex-mode)
16878 (call-interactively (key-binding (vector last-input-event))))))
16880 (defun org-cdlatex-math-modify (&optional arg)
16881 "Execute `cdlatex-math-modify' in LaTeX fragments.
16882 Revert to the normal definition outside of these fragments."
16883 (interactive "P")
16884 (if (org-inside-LaTeX-fragment-p)
16885 (call-interactively 'cdlatex-math-modify)
16886 (let (org-cdlatex-mode)
16887 (call-interactively (key-binding (vector last-input-event))))))
16889 (defvar org-latex-fragment-image-overlays nil
16890 "List of overlays carrying the images of latex fragments.")
16891 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
16893 (defun org-remove-latex-fragment-image-overlays ()
16894 "Remove all overlays with LaTeX fragment images in current buffer."
16895 (mapc 'delete-overlay org-latex-fragment-image-overlays)
16896 (setq org-latex-fragment-image-overlays nil))
16898 (defun org-preview-latex-fragment (&optional subtree)
16899 "Preview the LaTeX fragment at point, or all locally or globally.
16900 If the cursor is in a LaTeX fragment, create the image and overlay
16901 it over the source code. If there is no fragment at point, display
16902 all fragments in the current text, from one headline to the next. With
16903 prefix SUBTREE, display all fragments in the current subtree. With a
16904 double prefix arg \\[universal-argument] \\[universal-argument], or when \
16905 the cursor is before the first headline,
16906 display all fragments in the buffer.
16907 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
16908 (interactive "P")
16909 (unless buffer-file-name
16910 (error "Can't preview LaTeX fragment in a non-file buffer"))
16911 (org-remove-latex-fragment-image-overlays)
16912 (save-excursion
16913 (save-restriction
16914 (let (beg end at msg)
16915 (cond
16916 ((or (equal subtree '(16))
16917 (not (save-excursion
16918 (re-search-backward org-outline-regexp-bol nil t))))
16919 (setq beg (point-min) end (point-max)
16920 msg "Creating images for buffer...%s"))
16921 ((equal subtree '(4))
16922 (org-back-to-heading)
16923 (setq beg (point) end (org-end-of-subtree t)
16924 msg "Creating images for subtree...%s"))
16926 (if (setq at (org-inside-LaTeX-fragment-p))
16927 (goto-char (max (point-min) (- (cdr at) 2)))
16928 (org-back-to-heading))
16929 (setq beg (point) end (progn (outline-next-heading) (point))
16930 msg (if at "Creating image...%s"
16931 "Creating images for entry...%s"))))
16932 (message msg "")
16933 (narrow-to-region beg end)
16934 (goto-char beg)
16935 (org-format-latex
16936 (concat "ltxpng/" (file-name-sans-extension
16937 (file-name-nondirectory
16938 buffer-file-name)))
16939 default-directory 'overlays msg at 'forbuffer
16940 org-latex-create-formula-image-program)
16941 (message msg "done. Use `C-c C-c' to remove images.")))))
16943 (defvar org-latex-regexps
16944 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
16945 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
16946 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
16947 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
16948 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
16949 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
16950 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
16951 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
16952 "Regular expressions for matching embedded LaTeX.")
16954 (defvar org-export-have-math nil) ;; dynamic scoping
16955 (defun org-format-latex (prefix &optional dir overlays msg at
16956 forbuffer processing-type)
16957 "Replace LaTeX fragments with links to an image, and produce images.
16958 Some of the options can be changed using the variable
16959 `org-format-latex-options'."
16960 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
16961 (let* ((prefixnodir (file-name-nondirectory prefix))
16962 (absprefix (expand-file-name prefix dir))
16963 (todir (file-name-directory absprefix))
16964 (opt org-format-latex-options)
16965 (matchers (plist-get opt :matchers))
16966 (re-list org-latex-regexps)
16967 (org-format-latex-header-extra
16968 (plist-get (org-infile-export-plist) :latex-header-extra))
16969 (cnt 0) txt hash link beg end re e checkdir
16970 executables-checked string
16971 m n block-type block linkfile movefile ov)
16972 ;; Check the different regular expressions
16973 (while (setq e (pop re-list))
16974 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
16975 block (if block-type "\n\n" ""))
16976 (when (member m matchers)
16977 (goto-char (point-min))
16978 (while (re-search-forward re nil t)
16979 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
16980 (not (get-text-property (match-beginning n)
16981 'org-protected))
16982 (or (not overlays)
16983 (not (eq (get-char-property (match-beginning n)
16984 'org-overlay-type)
16985 'org-latex-overlay))))
16986 (setq org-export-have-math t)
16987 (cond
16988 ((eq processing-type 'verbatim)
16989 ;; Leave the text verbatim, just protect it
16990 (add-text-properties (match-beginning n) (match-end n)
16991 '(org-protected t)))
16992 ((eq processing-type 'mathjax)
16993 ;; Prepare for MathJax processing
16994 (setq string (match-string n))
16995 (if (member m '("$" "$1"))
16996 (save-excursion
16997 (delete-region (match-beginning n) (match-end n))
16998 (goto-char (match-beginning n))
16999 (insert (org-add-props (concat "\\(" (substring string 1 -1)
17000 "\\)")
17001 '(org-protected t))))
17002 (add-text-properties (match-beginning n) (match-end n)
17003 '(org-protected t))))
17004 ((or (eq processing-type 'dvipng)
17005 (eq processing-type 'imagemagick))
17006 ;; Process to an image
17007 (setq txt (match-string n)
17008 beg (match-beginning n) end (match-end n)
17009 cnt (1+ cnt))
17010 (let (print-length print-level) ; make sure full list is printed
17011 (setq hash (sha1 (prin1-to-string
17012 (list org-format-latex-header
17013 org-format-latex-header-extra
17014 org-export-latex-default-packages-alist
17015 org-export-latex-packages-alist
17016 org-format-latex-options
17017 forbuffer txt)))
17018 linkfile (format "%s_%s.png" prefix hash)
17019 movefile (format "%s_%s.png" absprefix hash)))
17020 (setq link (concat block "[[file:" linkfile "]]" block))
17021 (if msg (message msg cnt))
17022 (goto-char beg)
17023 (unless checkdir ; make sure the directory exists
17024 (setq checkdir t)
17025 (or (file-directory-p todir) (make-directory todir t)))
17026 (cond
17027 ((eq processing-type 'dvipng)
17028 (unless executables-checked
17029 (org-check-external-command
17030 "latex" "needed to convert LaTeX fragments to images")
17031 (org-check-external-command
17032 "dvipng" "needed to convert LaTeX fragments to images")
17033 (setq executables-checked t))
17034 (unless (file-exists-p movefile)
17035 (org-create-formula-image-with-dvipng
17036 txt movefile opt forbuffer)))
17037 ((eq processing-type 'imagemagick)
17038 (unless executables-checked
17039 (org-check-external-command
17040 "converte" "you need to install imagemagick")
17041 (setq executables-checked t))
17042 (unless (file-exists-p movefile)
17043 (org-create-formula-image-with-imagemagick
17044 txt movefile opt forbuffer))))
17045 (if overlays
17046 (progn
17047 (mapc (lambda (o)
17048 (if (eq (overlay-get o 'org-overlay-type)
17049 'org-latex-overlay)
17050 (delete-overlay o)))
17051 (overlays-in beg end))
17052 (setq ov (make-overlay beg end))
17053 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
17054 (if (featurep 'xemacs)
17055 (progn
17056 (overlay-put ov 'invisible t)
17057 (overlay-put
17058 ov 'end-glyph
17059 (make-glyph (vector 'png :file movefile))))
17060 (overlay-put
17061 ov 'display
17062 (list 'image :type 'png :file movefile :ascent 'center)))
17063 (push ov org-latex-fragment-image-overlays)
17064 (goto-char end))
17065 (delete-region beg end)
17066 (insert (org-add-props link
17067 (list 'org-latex-src
17068 (replace-regexp-in-string
17069 "\"" "" txt)
17070 'org-latex-src-embed-type
17071 (if block-type 'paragraph 'character))))))
17072 ((eq processing-type 'mathml)
17073 ;; Process to MathML
17074 (unless executables-checked
17075 (unless (save-match-data (org-format-latex-mathml-available-p))
17076 (error "LaTeX to MathML converter not configured"))
17077 (setq executables-checked t))
17078 (setq txt (match-string n)
17079 beg (match-beginning n) end (match-end n)
17080 cnt (1+ cnt))
17081 (if msg (message msg cnt))
17082 (goto-char beg)
17083 (delete-region beg end)
17084 (insert (org-format-latex-as-mathml
17085 txt block-type prefix dir)))
17087 (error "Unknown conversion type %s for latex fragments"
17088 processing-type)))))))))
17090 (defun org-create-math-formula (latex-frag &optional mathml-file)
17091 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
17092 Use `org-latex-to-mathml-convert-command'. If the conversion is
17093 sucessful, return the portion between \"<math...> </math>\"
17094 elements otherwise return nil. When MATHML-FILE is specified,
17095 write the results in to that file. When invoked as an
17096 interactive command, prompt for LATEX-FRAG, with initial value
17097 set to the current active region and echo the results for user
17098 inspection."
17099 (interactive (list (let ((frag (when (region-active-p)
17100 (buffer-substring-no-properties
17101 (region-beginning) (region-end)))))
17102 (read-string "LaTeX Fragment: " frag nil frag))))
17103 (unless latex-frag (error "Invalid latex-frag"))
17104 (let* ((tmp-in-file (file-relative-name
17105 (make-temp-name (expand-file-name "ltxmathml-in"))))
17106 (ignore (write-region latex-frag nil tmp-in-file))
17107 (tmp-out-file (file-relative-name
17108 (make-temp-name (expand-file-name "ltxmathml-out"))))
17109 (cmd (format-spec
17110 org-latex-to-mathml-convert-command
17111 `((?j . ,(shell-quote-argument
17112 (expand-file-name org-latex-to-mathml-jar-file)))
17113 (?I . ,(shell-quote-argument tmp-in-file))
17114 (?o . ,(shell-quote-argument tmp-out-file)))))
17115 mathml shell-command-output)
17116 (when (org-called-interactively-p 'any)
17117 (unless (org-format-latex-mathml-available-p)
17118 (error "LaTeX to MathML converter not configured")))
17119 (message "Running %s" cmd)
17120 (setq shell-command-output (shell-command-to-string cmd))
17121 (setq mathml
17122 (when (file-readable-p tmp-out-file)
17123 (with-current-buffer (find-file-noselect tmp-out-file t)
17124 (goto-char (point-min))
17125 (when (re-search-forward
17126 (concat
17127 (regexp-quote
17128 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
17129 "\\(.\\|\n\\)*"
17130 (regexp-quote "</math>")) nil t)
17131 (prog1 (match-string 0) (kill-buffer))))))
17132 (cond
17133 (mathml
17134 (setq mathml
17135 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
17136 (when mathml-file
17137 (write-region mathml nil mathml-file))
17138 (when (org-called-interactively-p 'any)
17139 (message mathml)))
17140 ((message "LaTeX to MathML conversion failed")
17141 (message shell-command-output)))
17142 (delete-file tmp-in-file)
17143 (when (file-exists-p tmp-out-file)
17144 (delete-file tmp-out-file))
17145 mathml))
17147 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
17148 prefix &optional dir)
17149 "Use `org-create-math-formula' but check local cache first."
17150 (let* ((absprefix (expand-file-name prefix dir))
17151 (print-length nil) (print-level nil)
17152 (formula-id (concat
17153 "formula-"
17154 (sha1
17155 (prin1-to-string
17156 (list latex-frag
17157 org-latex-to-mathml-convert-command)))))
17158 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
17159 (formula-cache-dir (file-name-directory formula-cache)))
17161 (unless (file-directory-p formula-cache-dir)
17162 (make-directory formula-cache-dir t))
17164 (unless (file-exists-p formula-cache)
17165 (org-create-math-formula latex-frag formula-cache))
17167 (if (file-exists-p formula-cache)
17168 ;; Successful conversion. Return the link to MathML file.
17169 (org-add-props
17170 (format "[[file:%s]]" (file-relative-name formula-cache dir))
17171 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
17172 'org-latex-src-embed-type (if latex-frag-type
17173 'paragraph 'character)))
17174 ;; Failed conversion. Return the LaTeX fragment verbatim
17175 (add-text-properties
17176 0 (1- (length latex-frag)) '(org-protected t) latex-frag)
17177 latex-frag)))
17179 ;; This function borrows from Ganesh Swami's latex2png.el
17180 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
17181 "This calls dvipng."
17182 (require 'org-latex)
17183 (let* ((tmpdir (if (featurep 'xemacs)
17184 (temp-directory)
17185 temporary-file-directory))
17186 (texfilebase (make-temp-name
17187 (expand-file-name "orgtex" tmpdir)))
17188 (texfile (concat texfilebase ".tex"))
17189 (dvifile (concat texfilebase ".dvi"))
17190 (pngfile (concat texfilebase ".png"))
17191 (fnh (if (featurep 'xemacs)
17192 (font-height (face-font 'default))
17193 (face-attribute 'default :height nil)))
17194 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17195 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17196 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17197 "Black"))
17198 (bg (or (plist-get options (if buffer :background :html-background))
17199 "Transparent")))
17200 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
17201 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
17202 (with-temp-file texfile
17203 (insert (org-splice-latex-header
17204 org-format-latex-header
17205 org-export-latex-default-packages-alist
17206 org-export-latex-packages-alist t
17207 org-format-latex-header-extra))
17208 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")
17209 (require 'org-latex)
17210 (org-export-latex-fix-inputenc))
17211 (let ((dir default-directory))
17212 (condition-case nil
17213 (progn
17214 (cd tmpdir)
17215 (call-process "latex" nil nil nil texfile))
17216 (error nil))
17217 (cd dir))
17218 (if (not (file-exists-p dvifile))
17219 (progn (message "Failed to create dvi file from %s" texfile) nil)
17220 (condition-case nil
17221 (if (featurep 'xemacs)
17222 (call-process "dvipng" nil nil nil
17223 "-fg" fg "-bg" bg
17224 "-T" "tight"
17225 "-o" pngfile
17226 dvifile)
17227 (call-process "dvipng" nil nil nil
17228 "-fg" fg "-bg" bg
17229 "-D" dpi
17230 ;;"-x" scale "-y" scale
17231 "-T" "tight"
17232 "-o" pngfile
17233 dvifile))
17234 (error nil))
17235 (if (not (file-exists-p pngfile))
17236 (if org-format-latex-signal-error
17237 (error "Failed to create png file from %s" texfile)
17238 (message "Failed to create png file from %s" texfile)
17239 nil)
17240 ;; Use the requested file name and clean up
17241 (copy-file pngfile tofile 'replace)
17242 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
17243 (delete-file (concat texfilebase e)))
17244 pngfile))))
17246 (defvar org-latex-to-pdf-process) ;; Defined in org-latex.el
17247 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
17248 "This calls convert, which is included into imagemagick."
17249 (require 'org-latex)
17250 (let* ((tmpdir (if (featurep 'xemacs)
17251 (temp-directory)
17252 temporary-file-directory))
17253 (texfilebase (make-temp-name
17254 (expand-file-name "orgtex" tmpdir)))
17255 (texfile (concat texfilebase ".tex"))
17256 (pdffile (concat texfilebase ".pdf"))
17257 (pngfile (concat texfilebase ".png"))
17258 (fnh (if (featurep 'xemacs)
17259 (font-height (face-font 'default))
17260 (face-attribute 'default :height nil)))
17261 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17262 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17263 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17264 "black"))
17265 (bg (or (plist-get options (if buffer :background :html-background))
17266 "white")))
17267 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
17268 (setq fg (org-latex-color-format fg)))
17269 (if (eq bg 'default) (setq bg (org-latex-color :background))
17270 (setq bg (org-latex-color-format
17271 (if (string= bg "Transparent")(setq bg "white")))))
17272 (with-temp-file texfile
17273 (insert (org-splice-latex-header
17274 org-format-latex-header
17275 org-export-latex-default-packages-alist
17276 org-export-latex-packages-alist t
17277 org-format-latex-header-extra))
17278 (insert "\n\\begin{document}\n"
17279 "\\definecolor{fg}{rgb}{" fg "}\n"
17280 "\\definecolor{bg}{rgb}{" bg "}\n"
17281 "\n\\pagecolor{bg}\n"
17282 "\n{\\color{fg}\n"
17283 string
17284 "\n}\n"
17285 "\n\\end{document}\n" )
17286 (require 'org-latex)
17287 (org-export-latex-fix-inputenc))
17288 (let ((dir default-directory) cmd cmds latex-frags-cmds)
17289 (condition-case nil
17290 (progn
17291 (cd tmpdir)
17292 (setq cmds org-latex-to-pdf-process)
17293 (while cmds
17294 (setq latex-frags-cmds (pop cmds))
17295 (if (listp latex-frags-cmds)
17296 (setq cmds nil)
17297 (setq latex-frags-cmds (list (car org-latex-to-pdf-process)))))
17298 (while latex-frags-cmds
17299 (setq cmd (pop latex-frags-cmds))
17300 (while (string-match "%b" cmd)
17301 (setq cmd (replace-match
17302 (save-match-data
17303 (shell-quote-argument texfile))
17304 t t cmd)))
17305 (while (string-match "%f" cmd)
17306 (setq cmd (replace-match
17307 (save-match-data
17308 (shell-quote-argument (file-name-nondirectory texfile)))
17309 t t cmd)))
17310 (while (string-match "%o" cmd)
17311 (setq cmd (replace-match
17312 (save-match-data
17313 (shell-quote-argument (file-name-directory texfile)))
17314 t t cmd)))
17315 (shell-command cmd)))
17316 (error nil))
17317 (cd dir))
17318 (if (not (file-exists-p pdffile))
17319 (progn (message "Failed to create pdf file from %s" texfile) nil)
17320 (condition-case nil
17321 (if (featurep 'xemacs)
17322 (call-process "convert" nil nil nil
17323 "-density" "96"
17324 "-trim"
17325 "-antialias"
17326 pdffile
17327 "-quality" "100"
17328 ;; "-sharpen" "0x1.0"
17329 pngfile)
17330 (call-process "convert" nil nil nil
17331 "-density" dpi
17332 "-trim"
17333 "-antialias"
17334 pdffile
17335 "-quality" "100"
17336 ; "-sharpen" "0x1.0"
17337 pngfile))
17338 (error nil))
17339 (if (not (file-exists-p pngfile))
17340 (if org-format-latex-signal-error
17341 (error "Failed to create png file from %s" texfile)
17342 (message "Failed to create png file from %s" texfile)
17343 nil)
17344 ;; Use the requested file name and clean up
17345 (copy-file pngfile tofile 'replace)
17346 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
17347 (delete-file (concat texfilebase e)))
17348 pngfile))))
17350 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
17351 "Fill a LaTeX header template TPL.
17352 In the template, the following place holders will be recognized:
17354 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
17355 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
17356 [PACKAGES] \\usepackage statements for PKG
17357 [NO-PACKAGES] do not include PKG
17358 [EXTRA] the string EXTRA
17359 [NO-EXTRA] do not include EXTRA
17361 For backward compatibility, if both the positive and the negative place
17362 holder is missing, the positive one (without the \"NO-\") will be
17363 assumed to be present at the end of the template.
17364 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
17365 EXTRA is a string.
17366 SNIPPETS-P indicates if this is run to create snippet images for HTML."
17367 (let (rpl (end ""))
17368 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
17369 (setq rpl (if (or (match-end 1) (not def-pkg))
17370 "" (org-latex-packages-to-string def-pkg snippets-p t))
17371 tpl (replace-match rpl t t tpl))
17372 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
17374 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
17375 (setq rpl (if (or (match-end 1) (not pkg))
17376 "" (org-latex-packages-to-string pkg snippets-p t))
17377 tpl (replace-match rpl t t tpl))
17378 (if pkg (setq end
17379 (concat end "\n"
17380 (org-latex-packages-to-string pkg snippets-p)))))
17382 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
17383 (setq rpl (if (or (match-end 1) (not extra))
17384 "" (concat extra "\n"))
17385 tpl (replace-match rpl t t tpl))
17386 (if (and extra (string-match "\\S-" extra))
17387 (setq end (concat end "\n" extra))))
17389 (if (string-match "\\S-" end)
17390 (concat tpl "\n" end)
17391 tpl)))
17393 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
17394 "Turn an alist of packages into a string with the \\usepackage macros."
17395 (setq pkg (mapconcat (lambda(p)
17396 (cond
17397 ((stringp p) p)
17398 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
17399 (format "%% Package %s omitted" (cadr p)))
17400 ((equal "" (car p))
17401 (format "\\usepackage{%s}" (cadr p)))
17403 (format "\\usepackage[%s]{%s}"
17404 (car p) (cadr p)))))
17406 "\n"))
17407 (if newline (concat pkg "\n") pkg))
17409 (defun org-dvipng-color (attr)
17410 "Return a RGB color specification for dvipng."
17411 (apply 'format "rgb %s %s %s"
17412 (mapcar 'org-normalize-color
17413 (if (featurep 'xemacs)
17414 (color-rgb-components
17415 (face-property 'default
17416 (cond ((eq attr :foreground) 'foreground)
17417 ((eq attr :background) 'background))))
17418 (color-values (face-attribute 'default attr nil))))))
17420 (defun org-latex-color (attr)
17421 "Return a RGB color for the LaTeX color package."
17422 (apply 'format "%s,%s,%s"
17423 (mapcar 'org-normalize-color
17424 (if (featurep 'xemacs)
17425 (color-rgb-components
17426 (face-property 'default
17427 (cond ((eq attr :foreground) 'foreground)
17428 ((eq attr :background) 'background))))
17429 (color-values (face-attribute 'default attr nil))))))
17431 (defun org-latex-color-format (color-name)
17432 "Convert COLOR-NAME to a RGB color value."
17433 (apply 'format "%s,%s,%s"
17434 (mapcar 'org-normalize-color
17435 (color-values color-name))))
17437 (defun org-normalize-color (value)
17438 "Return string to be used as color value for an RGB component."
17439 (format "%g" (/ value 65535.0)))
17441 ;; Image display
17444 (defvar org-inline-image-overlays nil)
17445 (make-variable-buffer-local 'org-inline-image-overlays)
17447 (defun org-toggle-inline-images (&optional include-linked)
17448 "Toggle the display of inline images.
17449 INCLUDE-LINKED is passed to `org-display-inline-images'."
17450 (interactive "P")
17451 (if org-inline-image-overlays
17452 (progn
17453 (org-remove-inline-images)
17454 (message "Inline image display turned off"))
17455 (org-display-inline-images include-linked)
17456 (if org-inline-image-overlays
17457 (message "%d images displayed inline"
17458 (length org-inline-image-overlays))
17459 (message "No images to display inline"))))
17461 (defun org-display-inline-images (&optional include-linked refresh beg end)
17462 "Display inline images.
17463 Normally only links without a description part are inlined, because this
17464 is how it will work for export. When INCLUDE-LINKED is set, also links
17465 with a description part will be inlined. This can be nice for a quick
17466 look at those images, but it does not reflect what exported files will look
17467 like.
17468 When REFRESH is set, refresh existing images between BEG and END.
17469 This will create new image displays only if necessary.
17470 BEG and END default to the buffer boundaries."
17471 (interactive "P")
17472 (unless refresh
17473 (org-remove-inline-images)
17474 (if (fboundp 'clear-image-cache) (clear-image-cache)))
17475 (save-excursion
17476 (save-restriction
17477 (widen)
17478 (setq beg (or beg (point-min)) end (or end (point-max)))
17479 (goto-char beg)
17480 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
17481 (substring (org-image-file-name-regexp) 0 -2)
17482 "\\)\\]" (if include-linked "" "\\]")))
17483 old file ov img)
17484 (while (re-search-forward re end t)
17485 (setq old (get-char-property-and-overlay (match-beginning 1)
17486 'org-image-overlay))
17487 (setq file (expand-file-name
17488 (concat (or (match-string 3) "") (match-string 4))))
17489 (when (file-exists-p file)
17490 (if (and (car-safe old) refresh)
17491 (image-refresh (overlay-get (cdr old) 'display))
17492 (setq img (save-match-data (create-image file)))
17493 (when img
17494 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
17495 (overlay-put ov 'display img)
17496 (overlay-put ov 'face 'default)
17497 (overlay-put ov 'org-image-overlay t)
17498 (overlay-put ov 'modification-hooks
17499 (list 'org-display-inline-modification-hook))
17500 (push ov org-inline-image-overlays)))))))))
17502 (defun org-display-inline-modification-hook (ov after beg end &optional len)
17503 "Remove inline-display overlay if a corresponding region is modified."
17504 (let ((inhibit-modification-hooks t))
17505 (when (and ov after)
17506 (delete ov org-inline-image-overlays)
17507 (delete-overlay ov))))
17509 (defun org-remove-inline-images ()
17510 "Remove inline display of images."
17511 (interactive)
17512 (mapc 'delete-overlay org-inline-image-overlays)
17513 (setq org-inline-image-overlays nil))
17515 ;;;; Key bindings
17517 ;; Outline functions from `outline-mode-prefix-map'
17518 ;; that can be remapped in Org:
17519 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
17520 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
17521 (define-key org-mode-map [remap outline-forward-same-level]
17522 'org-forward-same-level)
17523 (define-key org-mode-map [remap outline-backward-same-level]
17524 'org-backward-same-level)
17525 (define-key org-mode-map [remap show-branches]
17526 'org-kill-note-or-show-branches)
17527 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
17528 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
17529 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
17531 ;; Outline functions from `outline-mode-prefix-map'
17532 ;; that can not be remapped in Org:
17533 ;; - the column "key binding" shows whether the Outline function is still
17534 ;; available in Org mode on the same key that it has been bound to in
17535 ;; Outline mode:
17536 ;; - "overridden": key used for a different functionality in Org mode
17537 ;; - else: key still bound to the same Outline function in Org mode
17538 ;; | Outline function | key binding | Org replacement |
17539 ;; |------------------------------------+-------------+-----------------------|
17540 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
17541 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
17542 ;; | `show-children' | `C-c C-i' | visibility cycling |
17543 ;; | `hide-subtree' | overridden | visibility cycling |
17544 ;; | `outline-up-heading' | `C-c C-u' | still same function |
17545 ;; | `hide-body' | overridden | no replacement |
17546 ;; | `show-all' | overridden | no replacement |
17547 ;; | `hide-entry' | overridden | visibility cycling |
17548 ;; | `show-entry' | overridden | no replacement |
17549 ;; | `hide-leaves' | overridden | no replacement |
17550 ;; | `hide-sublevels' | overridden | no replacement |
17551 ;; | `hide-other' | overridden | no replacement |
17552 ;; | `outline-move-subtree-up' | `C-c C-^' | better: org-shiftup |
17553 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
17555 ;; Make `C-c C-x' a prefix key
17556 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
17558 ;; TAB key with modifiers
17559 (org-defkey org-mode-map "\C-i" 'org-cycle)
17560 (org-defkey org-mode-map [(tab)] 'org-cycle)
17561 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
17562 (org-defkey org-mode-map "\M-\t" 'pcomplete)
17563 ;; The following line is necessary under Suse GNU/Linux
17564 (unless (featurep 'xemacs)
17565 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
17566 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
17567 (define-key org-mode-map [backtab] 'org-shifttab)
17569 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
17570 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
17571 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
17573 ;; Cursor keys with modifiers
17574 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
17575 (org-defkey org-mode-map [(meta right)] 'org-metaright)
17576 (org-defkey org-mode-map [(meta up)] 'org-metaup)
17577 (org-defkey org-mode-map [(meta down)] 'org-metadown)
17579 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
17580 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
17581 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
17582 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
17584 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
17585 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
17586 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
17587 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
17589 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
17590 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
17591 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
17592 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
17594 ;; Babel keys
17595 (define-key org-mode-map org-babel-key-prefix org-babel-map)
17596 (mapc (lambda (pair)
17597 (define-key org-babel-map (car pair) (cdr pair)))
17598 org-babel-key-bindings)
17600 ;;; Extra keys for tty access.
17601 ;; We only set them when really needed because otherwise the
17602 ;; menus don't show the simple keys
17604 (when (or org-use-extra-keys
17605 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
17606 (not window-system))
17607 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
17608 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
17609 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
17610 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
17611 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
17612 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
17613 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
17614 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
17615 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
17616 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
17617 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
17618 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
17619 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
17620 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
17621 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
17622 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
17623 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
17624 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
17625 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
17626 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
17627 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
17628 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
17629 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
17630 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
17631 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
17632 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
17633 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
17634 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
17636 ;; All the other keys
17638 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
17639 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
17640 (if (boundp 'narrow-map)
17641 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
17642 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
17643 (if (boundp 'narrow-map)
17644 (org-defkey narrow-map "b" 'org-narrow-to-block)
17645 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
17646 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-same-level)
17647 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-same-level)
17648 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
17649 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
17650 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
17651 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
17652 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
17653 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
17654 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
17655 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
17656 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
17657 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
17658 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
17659 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
17660 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
17661 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
17662 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
17663 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
17664 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
17665 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
17666 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
17667 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
17668 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
17669 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
17670 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
17671 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
17672 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
17673 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
17674 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
17675 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
17676 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
17677 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
17678 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
17679 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
17680 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
17681 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
17682 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
17683 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
17684 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
17685 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
17686 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
17687 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
17688 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
17689 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
17690 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
17691 (org-defkey org-mode-map "\C-c^" 'org-sort)
17692 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
17693 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
17694 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
17695 (org-defkey org-mode-map "\C-m" 'org-return)
17696 (org-defkey org-mode-map "\C-j" 'org-return-indent)
17697 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
17698 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
17699 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
17700 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
17701 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
17702 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
17703 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
17704 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
17705 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
17706 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
17707 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
17708 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
17709 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
17710 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
17711 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
17712 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
17713 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
17714 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
17715 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
17716 (org-defkey org-mode-map "\C-c\C-@" 'org-mark-list)
17717 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
17718 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
17720 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
17721 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
17722 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
17723 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
17725 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
17726 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
17727 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
17728 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
17729 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
17730 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
17731 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
17732 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
17733 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
17734 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
17735 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
17736 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
17737 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
17738 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
17739 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
17740 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
17741 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
17742 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
17744 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
17745 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
17746 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
17747 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
17748 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
17750 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
17752 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
17754 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
17755 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
17757 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
17760 (when (featurep 'xemacs)
17761 (org-defkey org-mode-map 'button3 'popup-mode-menu))
17764 (defconst org-speed-commands-default
17766 ("Outline Navigation")
17767 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
17768 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
17769 ("f" . (org-speed-move-safe 'org-forward-same-level))
17770 ("b" . (org-speed-move-safe 'org-backward-same-level))
17771 ("u" . (org-speed-move-safe 'outline-up-heading))
17772 ("j" . org-goto)
17773 ("g" . (org-refile t))
17774 ("Outline Visibility")
17775 ("c" . org-cycle)
17776 ("C" . org-shifttab)
17777 (" " . org-display-outline-path)
17778 ("Outline Structure Editing")
17779 ("U" . org-shiftmetaup)
17780 ("D" . org-shiftmetadown)
17781 ("r" . org-metaright)
17782 ("l" . org-metaleft)
17783 ("R" . org-shiftmetaright)
17784 ("L" . org-shiftmetaleft)
17785 ("i" . (progn (forward-char 1) (call-interactively
17786 'org-insert-heading-respect-content)))
17787 ("^" . org-sort)
17788 ("w" . org-refile)
17789 ("a" . org-archive-subtree-default-with-confirmation)
17790 ("." . org-mark-subtree)
17791 ("Clock Commands")
17792 ("I" . org-clock-in)
17793 ("O" . org-clock-out)
17794 ("Meta Data Editing")
17795 ("t" . org-todo)
17796 ("0" . (org-priority ?\ ))
17797 ("1" . (org-priority ?A))
17798 ("2" . (org-priority ?B))
17799 ("3" . (org-priority ?C))
17800 (";" . org-set-tags-command)
17801 ("e" . org-set-effort)
17802 ("Agenda Views etc")
17803 ("v" . org-agenda)
17804 ("/" . org-sparse-tree)
17805 ("Misc")
17806 ("o" . org-open-at-point)
17807 ("?" . org-speed-command-help)
17808 ("<" . (org-agenda-set-restriction-lock 'subtree))
17809 (">" . (org-agenda-remove-restriction-lock))
17811 "The default speed commands.")
17813 (defun org-print-speed-command (e)
17814 (if (> (length (car e)) 1)
17815 (progn
17816 (princ "\n")
17817 (princ (car e))
17818 (princ "\n")
17819 (princ (make-string (length (car e)) ?-))
17820 (princ "\n"))
17821 (princ (car e))
17822 (princ " ")
17823 (if (symbolp (cdr e))
17824 (princ (symbol-name (cdr e)))
17825 (prin1 (cdr e)))
17826 (princ "\n")))
17828 (defun org-speed-command-help ()
17829 "Show the available speed commands."
17830 (interactive)
17831 (if (not org-use-speed-commands)
17832 (error "Speed commands are not activated, customize `org-use-speed-commands'")
17833 (with-output-to-temp-buffer "*Help*"
17834 (princ "User-defined Speed commands\n===========================\n")
17835 (mapc 'org-print-speed-command org-speed-commands-user)
17836 (princ "\n")
17837 (princ "Built-in Speed commands\n=======================\n")
17838 (mapc 'org-print-speed-command org-speed-commands-default))
17839 (with-current-buffer "*Help*"
17840 (setq truncate-lines t))))
17842 (defun org-speed-move-safe (cmd)
17843 "Execute CMD, but make sure that the cursor always ends up in a headline.
17844 If not, return to the original position and throw an error."
17845 (interactive)
17846 (let ((pos (point)))
17847 (call-interactively cmd)
17848 (unless (and (bolp) (org-at-heading-p))
17849 (goto-char pos)
17850 (error "Boundary reached while executing %s" cmd))))
17852 (defvar org-self-insert-command-undo-counter 0)
17854 (defvar org-table-auto-blank-field) ; defined in org-table.el
17855 (defvar org-speed-command nil)
17857 (defun org-speed-command-default-hook (keys)
17858 "Hook for activating single-letter speed commands.
17859 `org-speed-commands-default' specifies a minimal command set.
17860 Use `org-speed-commands-user' for further customization."
17861 (when (or (and (bolp) (looking-at org-outline-regexp))
17862 (and (functionp org-use-speed-commands)
17863 (funcall org-use-speed-commands)))
17864 (cdr (assoc keys (append org-speed-commands-user
17865 org-speed-commands-default)))))
17867 (defun org-babel-speed-command-hook (keys)
17868 "Hook for activating single-letter code block commands."
17869 (when (and (bolp) (looking-at org-babel-src-block-regexp))
17870 (cdr (assoc keys org-babel-key-bindings))))
17872 (defcustom org-speed-command-hook
17873 '(org-speed-command-default-hook org-babel-speed-command-hook)
17874 "Hook for activating speed commands at strategic locations.
17875 Hook functions are called in sequence until a valid handler is
17876 found.
17878 Each hook takes a single argument, a user-pressed command key
17879 which is also a `self-insert-command' from the global map.
17881 Within the hook, examine the cursor position and the command key
17882 and return nil or a valid handler as appropriate. Handler could
17883 be one of an interactive command, a function, or a form.
17885 Set `org-use-speed-commands' to non-nil value to enable this
17886 hook. The default setting is `org-speed-command-default-hook'."
17887 :group 'org-structure
17888 :version "24.1"
17889 :type 'hook)
17891 (defun org-self-insert-command (N)
17892 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
17893 If the cursor is in a table looking at whitespace, the whitespace is
17894 overwritten, and the table is not marked as requiring realignment."
17895 (interactive "p")
17896 (org-check-before-invisible-edit 'insert)
17897 (cond
17898 ((and org-use-speed-commands
17899 (setq org-speed-command
17900 (run-hook-with-args-until-success
17901 'org-speed-command-hook (this-command-keys))))
17902 (cond
17903 ((commandp org-speed-command)
17904 (setq this-command org-speed-command)
17905 (call-interactively org-speed-command))
17906 ((functionp org-speed-command)
17907 (funcall org-speed-command))
17908 ((and org-speed-command (listp org-speed-command))
17909 (eval org-speed-command))
17910 (t (let (org-use-speed-commands)
17911 (call-interactively 'org-self-insert-command)))))
17912 ((and
17913 (org-table-p)
17914 (progn
17915 ;; check if we blank the field, and if that triggers align
17916 (and (featurep 'org-table) org-table-auto-blank-field
17917 (member last-command
17918 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
17919 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
17920 ;; got extra space, this field does not determine column width
17921 (let (org-table-may-need-update) (org-table-blank-field))
17922 ;; no extra space, this field may determine column width
17923 (org-table-blank-field)))
17925 (eq N 1)
17926 (looking-at "[^|\n]* |"))
17927 (let (org-table-may-need-update)
17928 (goto-char (1- (match-end 0)))
17929 (backward-delete-char 1)
17930 (goto-char (match-beginning 0))
17931 (self-insert-command N)))
17933 (setq org-table-may-need-update t)
17934 (self-insert-command N)
17935 (org-fix-tags-on-the-fly)
17936 (if org-self-insert-cluster-for-undo
17937 (if (not (eq last-command 'org-self-insert-command))
17938 (setq org-self-insert-command-undo-counter 1)
17939 (if (>= org-self-insert-command-undo-counter 20)
17940 (setq org-self-insert-command-undo-counter 1)
17941 (and (> org-self-insert-command-undo-counter 0)
17942 buffer-undo-list (listp buffer-undo-list)
17943 (not (cadr buffer-undo-list)) ; remove nil entry
17944 (setcdr buffer-undo-list (cddr buffer-undo-list)))
17945 (setq org-self-insert-command-undo-counter
17946 (1+ org-self-insert-command-undo-counter))))))))
17948 (defun org-check-before-invisible-edit (kind)
17949 "Check is editing if kind KIND would be dangerous with invisible text around.
17950 The detailed reaction depends on the user option `org-catch-invisible-edits'."
17951 ;; First, try to get out of here as quickly as possible, to reduce overhead
17952 (if (and org-catch-invisible-edits
17953 (or (not (boundp 'visible-mode)) (not visible-mode))
17954 (or (get-char-property (point) 'invisible)
17955 (get-char-property (max (point-min) (1- (point))) 'invisible)))
17956 ;; OK, we need to take a closer look
17957 (let* ((invisible-at-point (get-char-property (point) 'invisible))
17958 (invisible-before-point (if (bobp) nil (get-char-property
17959 (1- (point)) 'invisible)))
17960 (border-and-ok-direction
17962 ;; Check if we are acting predictably before invisible text
17963 (and invisible-at-point (not invisible-before-point)
17964 (memq kind '(insert delete-backward)))
17965 ;; Check if we are acting predictably after invisible text
17966 ;; This works not well, and I have turned it off. It seems
17967 ;; better to always show and stop after invisible text.
17968 ;; (and (not invisible-at-point) invisible-before-point
17969 ;; (memq kind '(insert delete)))
17972 (when (or (memq invisible-at-point '(outline org-hide-block))
17973 (memq invisible-before-point '(outline org-hide-block)))
17974 (if (eq org-catch-invisible-edits 'error)
17975 (error "Editing in invisible areas is prohibited - make visible first"))
17976 ;; Make the area visible
17977 (save-excursion
17978 (if invisible-before-point
17979 (goto-char (previous-single-char-property-change
17980 (point) 'invisible)))
17981 (org-cycle))
17982 (cond
17983 ((eq org-catch-invisible-edits 'show)
17984 ;; That's it, we do the edit after showing
17985 (message
17986 "Unfolding invisible region around point before editing")
17987 (sit-for 1))
17988 ((and (eq org-catch-invisible-edits 'smart)
17989 border-and-ok-direction)
17990 (message "Unfolding invisible region around point before editing"))
17992 ;; Don't do the edit, make the user repeat it in full visibility
17993 (error "Edit in invisible region aborted, repeat to confirm with text visible")))))))
17995 (defun org-fix-tags-on-the-fly ()
17996 (when (and (equal (char-after (point-at-bol)) ?*)
17997 (org-at-heading-p))
17998 (org-align-tags-here org-tags-column)))
18000 (defun org-delete-backward-char (N)
18001 "Like `delete-backward-char', insert whitespace at field end in tables.
18002 When deleting backwards, in tables this function will insert whitespace in
18003 front of the next \"|\" separator, to keep the table aligned. The table will
18004 still be marked for re-alignment if the field did fill the entire column,
18005 because, in this case the deletion might narrow the column."
18006 (interactive "p")
18007 (org-check-before-invisible-edit 'delete-backward)
18008 (if (and (org-table-p)
18009 (eq N 1)
18010 (string-match "|" (buffer-substring (point-at-bol) (point)))
18011 (looking-at ".*?|"))
18012 (let ((pos (point))
18013 (noalign (looking-at "[^|\n\r]* |"))
18014 (c org-table-may-need-update))
18015 (backward-delete-char N)
18016 (if (not overwrite-mode)
18017 (progn
18018 (skip-chars-forward "^|")
18019 (insert " ")
18020 (goto-char (1- pos))))
18021 ;; noalign: if there were two spaces at the end, this field
18022 ;; does not determine the width of the column.
18023 (if noalign (setq org-table-may-need-update c)))
18024 (backward-delete-char N)
18025 (org-fix-tags-on-the-fly)))
18027 (defun org-delete-char (N)
18028 "Like `delete-char', but insert whitespace at field end in tables.
18029 When deleting characters, in tables this function will insert whitespace in
18030 front of the next \"|\" separator, to keep the table aligned. The table will
18031 still be marked for re-alignment if the field did fill the entire column,
18032 because, in this case the deletion might narrow the column."
18033 (interactive "p")
18034 (org-check-before-invisible-edit 'delete)
18035 (if (and (org-table-p)
18036 (not (bolp))
18037 (not (= (char-after) ?|))
18038 (eq N 1))
18039 (if (looking-at ".*?|")
18040 (let ((pos (point))
18041 (noalign (looking-at "[^|\n\r]* |"))
18042 (c org-table-may-need-update))
18043 (replace-match (concat
18044 (substring (match-string 0) 1 -1)
18045 " |"))
18046 (goto-char pos)
18047 ;; noalign: if there were two spaces at the end, this field
18048 ;; does not determine the width of the column.
18049 (if noalign (setq org-table-may-need-update c)))
18050 (delete-char N))
18051 (delete-char N)
18052 (org-fix-tags-on-the-fly)))
18054 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
18055 (put 'org-self-insert-command 'delete-selection t)
18056 (put 'orgtbl-self-insert-command 'delete-selection t)
18057 (put 'org-delete-char 'delete-selection 'supersede)
18058 (put 'org-delete-backward-char 'delete-selection 'supersede)
18059 (put 'org-yank 'delete-selection 'yank)
18061 ;; Make `flyspell-mode' delay after some commands
18062 (put 'org-self-insert-command 'flyspell-delayed t)
18063 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
18064 (put 'org-delete-char 'flyspell-delayed t)
18065 (put 'org-delete-backward-char 'flyspell-delayed t)
18067 ;; Make pabbrev-mode expand after org-mode commands
18068 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
18069 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
18071 ;; How to do this: Measure non-white length of current string
18072 ;; If equal to column width, we should realign.
18074 (defun org-remap (map &rest commands)
18075 "In MAP, remap the functions given in COMMANDS.
18076 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
18077 (let (new old)
18078 (while commands
18079 (setq old (pop commands) new (pop commands))
18080 (if (fboundp 'command-remapping)
18081 (org-defkey map (vector 'remap old) new)
18082 (substitute-key-definition old new map global-map)))))
18084 (when (eq org-enable-table-editor 'optimized)
18085 ;; If the user wants maximum table support, we need to hijack
18086 ;; some standard editing functions
18087 (org-remap org-mode-map
18088 'self-insert-command 'org-self-insert-command
18089 'delete-char 'org-delete-char
18090 'delete-backward-char 'org-delete-backward-char)
18091 (org-defkey org-mode-map "|" 'org-force-self-insert))
18093 (defvar org-ctrl-c-ctrl-c-hook nil
18094 "Hook for functions attaching themselves to `C-c C-c'.
18096 This can be used to add additional functionality to the C-c C-c
18097 key which executes context-dependent commands. This hook is run
18098 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
18099 run after the last test.
18101 Each function will be called with no arguments. The function
18102 must check if the context is appropriate for it to act. If yes,
18103 it should do its thing and then return a non-nil value. If the
18104 context is wrong, just do nothing and return nil.")
18106 (defvar org-ctrl-c-ctrl-c-final-hook nil
18107 "Hook for functions attaching themselves to `C-c C-c'.
18109 This can be used to add additional functionality to the C-c C-c
18110 key which executes context-dependent commands. This hook is run
18111 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
18112 before the first test.
18114 Each function will be called with no arguments. The function
18115 must check if the context is appropriate for it to act. If yes,
18116 it should do its thing and then return a non-nil value. If the
18117 context is wrong, just do nothing and return nil.")
18119 (defvar org-tab-first-hook nil
18120 "Hook for functions to attach themselves to TAB.
18121 See `org-ctrl-c-ctrl-c-hook' for more information.
18122 This hook runs as the first action when TAB is pressed, even before
18123 `org-cycle' messes around with the `outline-regexp' to cater for
18124 inline tasks and plain list item folding.
18125 If any function in this hook returns t, any other actions that
18126 would have been caused by TAB (such as table field motion or visibility
18127 cycling) will not occur.")
18129 (defvar org-tab-after-check-for-table-hook nil
18130 "Hook for functions to attach themselves to TAB.
18131 See `org-ctrl-c-ctrl-c-hook' for more information.
18132 This hook runs after it has been established that the cursor is not in a
18133 table, but before checking if the cursor is in a headline or if global cycling
18134 should be done.
18135 If any function in this hook returns t, not other actions like visibility
18136 cycling will be done.")
18138 (defvar org-tab-after-check-for-cycling-hook nil
18139 "Hook for functions to attach themselves to TAB.
18140 See `org-ctrl-c-ctrl-c-hook' for more information.
18141 This hook runs after it has been established that not table field motion and
18142 not visibility should be done because of current context. This is probably
18143 the place where a package like yasnippets can hook in.")
18145 (defvar org-tab-before-tab-emulation-hook nil
18146 "Hook for functions to attach themselves to TAB.
18147 See `org-ctrl-c-ctrl-c-hook' for more information.
18148 This hook runs after every other options for TAB have been exhausted, but
18149 before indentation and \t insertion takes place.")
18151 (defvar org-metaleft-hook nil
18152 "Hook for functions attaching themselves to `M-left'.
18153 See `org-ctrl-c-ctrl-c-hook' for more information.")
18154 (defvar org-metaright-hook nil
18155 "Hook for functions attaching themselves to `M-right'.
18156 See `org-ctrl-c-ctrl-c-hook' for more information.")
18157 (defvar org-metaup-hook nil
18158 "Hook for functions attaching themselves to `M-up'.
18159 See `org-ctrl-c-ctrl-c-hook' for more information.")
18160 (defvar org-metadown-hook nil
18161 "Hook for functions attaching themselves to `M-down'.
18162 See `org-ctrl-c-ctrl-c-hook' for more information.")
18163 (defvar org-shiftmetaleft-hook nil
18164 "Hook for functions attaching themselves to `M-S-left'.
18165 See `org-ctrl-c-ctrl-c-hook' for more information.")
18166 (defvar org-shiftmetaright-hook nil
18167 "Hook for functions attaching themselves to `M-S-right'.
18168 See `org-ctrl-c-ctrl-c-hook' for more information.")
18169 (defvar org-shiftmetaup-hook nil
18170 "Hook for functions attaching themselves to `M-S-up'.
18171 See `org-ctrl-c-ctrl-c-hook' for more information.")
18172 (defvar org-shiftmetadown-hook nil
18173 "Hook for functions attaching themselves to `M-S-down'.
18174 See `org-ctrl-c-ctrl-c-hook' for more information.")
18175 (defvar org-metareturn-hook nil
18176 "Hook for functions attaching themselves to `M-RET'.
18177 See `org-ctrl-c-ctrl-c-hook' for more information.")
18178 (defvar org-shiftup-hook nil
18179 "Hook for functions attaching themselves to `S-up'.
18180 See `org-ctrl-c-ctrl-c-hook' for more information.")
18181 (defvar org-shiftup-final-hook nil
18182 "Hook for functions attaching themselves to `S-up'.
18183 This one runs after all other options except shift-select have been excluded.
18184 See `org-ctrl-c-ctrl-c-hook' for more information.")
18185 (defvar org-shiftdown-hook nil
18186 "Hook for functions attaching themselves to `S-down'.
18187 See `org-ctrl-c-ctrl-c-hook' for more information.")
18188 (defvar org-shiftdown-final-hook nil
18189 "Hook for functions attaching themselves to `S-down'.
18190 This one runs after all other options except shift-select have been excluded.
18191 See `org-ctrl-c-ctrl-c-hook' for more information.")
18192 (defvar org-shiftleft-hook nil
18193 "Hook for functions attaching themselves to `S-left'.
18194 See `org-ctrl-c-ctrl-c-hook' for more information.")
18195 (defvar org-shiftleft-final-hook nil
18196 "Hook for functions attaching themselves to `S-left'.
18197 This one runs after all other options except shift-select have been excluded.
18198 See `org-ctrl-c-ctrl-c-hook' for more information.")
18199 (defvar org-shiftright-hook nil
18200 "Hook for functions attaching themselves to `S-right'.
18201 See `org-ctrl-c-ctrl-c-hook' for more information.")
18202 (defvar org-shiftright-final-hook nil
18203 "Hook for functions attaching themselves to `S-right'.
18204 This one runs after all other options except shift-select have been excluded.
18205 See `org-ctrl-c-ctrl-c-hook' for more information.")
18207 (defun org-modifier-cursor-error ()
18208 "Throw an error, a modified cursor command was applied in wrong context."
18209 (error "This command is active in special context like tables, headlines or items"))
18211 (defun org-shiftselect-error ()
18212 "Throw an error because Shift-Cursor command was applied in wrong context."
18213 (if (and (boundp 'shift-select-mode) shift-select-mode)
18214 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
18215 (error "This command works only in special context like headlines or timestamps")))
18217 (defun org-call-for-shift-select (cmd)
18218 (let ((this-command-keys-shift-translated t))
18219 (call-interactively cmd)))
18221 (defun org-shifttab (&optional arg)
18222 "Global visibility cycling or move to previous table field.
18223 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
18224 on context.
18225 See the individual commands for more information."
18226 (interactive "P")
18227 (cond
18228 ((org-at-table-p) (call-interactively 'org-table-previous-field))
18229 ((integerp arg)
18230 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
18231 (message "Content view to level: %d" arg)
18232 (org-content (prefix-numeric-value arg2))
18233 (setq org-cycle-global-status 'overview)))
18234 (t (call-interactively 'org-global-cycle))))
18236 (defun org-shiftmetaleft ()
18237 "Promote subtree or delete table column.
18238 Calls `org-promote-subtree', `org-outdent-item-tree', or
18239 `org-table-delete-column', depending on context. See the
18240 individual commands for more information."
18241 (interactive)
18242 (cond
18243 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
18244 ((org-at-table-p) (call-interactively 'org-table-delete-column))
18245 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
18246 ((if (not (org-region-active-p)) (org-at-item-p)
18247 (save-excursion (goto-char (region-beginning))
18248 (org-at-item-p)))
18249 (call-interactively 'org-outdent-item-tree))
18250 (t (org-modifier-cursor-error))))
18252 (defun org-shiftmetaright ()
18253 "Demote subtree or insert table column.
18254 Calls `org-demote-subtree', `org-indent-item-tree', or
18255 `org-table-insert-column', depending on context. See the
18256 individual commands for more information."
18257 (interactive)
18258 (cond
18259 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
18260 ((org-at-table-p) (call-interactively 'org-table-insert-column))
18261 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
18262 ((if (not (org-region-active-p)) (org-at-item-p)
18263 (save-excursion (goto-char (region-beginning))
18264 (org-at-item-p)))
18265 (call-interactively 'org-indent-item-tree))
18266 (t (org-modifier-cursor-error))))
18268 (defun org-shiftmetaup (&optional arg)
18269 "Move subtree up or kill table row.
18270 Calls `org-move-subtree-up' or `org-table-kill-row' or
18271 `org-move-item-up' depending on context. See the individual commands
18272 for more information."
18273 (interactive "P")
18274 (cond
18275 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
18276 ((org-at-table-p) (call-interactively 'org-table-kill-row))
18277 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18278 ((org-at-item-p) (call-interactively 'org-move-item-up))
18279 (t (org-modifier-cursor-error))))
18281 (defun org-shiftmetadown (&optional arg)
18282 "Move subtree down or insert table row.
18283 Calls `org-move-subtree-down' or `org-table-insert-row' or
18284 `org-move-item-down', depending on context. See the individual
18285 commands for more information."
18286 (interactive "P")
18287 (cond
18288 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
18289 ((org-at-table-p) (call-interactively 'org-table-insert-row))
18290 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
18291 ((org-at-item-p) (call-interactively 'org-move-item-down))
18292 (t (org-modifier-cursor-error))))
18294 (defsubst org-hidden-tree-error ()
18295 (error
18296 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
18298 (defun org-metaleft (&optional arg)
18299 "Promote heading or move table column to left.
18300 Calls `org-do-promote' or `org-table-move-column', depending on context.
18301 With no specific context, calls the Emacs default `backward-word'.
18302 See the individual commands for more information."
18303 (interactive "P")
18304 (cond
18305 ((run-hook-with-args-until-success 'org-metaleft-hook))
18306 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
18307 ((org-with-limited-levels
18308 (or (org-at-heading-p)
18309 (and (org-region-active-p)
18310 (save-excursion
18311 (goto-char (region-beginning))
18312 (org-at-heading-p)))))
18313 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18314 (call-interactively 'org-do-promote))
18315 ;; At an inline task.
18316 ((org-at-heading-p)
18317 (call-interactively 'org-inlinetask-promote))
18318 ((or (org-at-item-p)
18319 (and (org-region-active-p)
18320 (save-excursion
18321 (goto-char (region-beginning))
18322 (org-at-item-p))))
18323 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
18324 (call-interactively 'org-outdent-item))
18325 (t (call-interactively 'backward-word))))
18327 (defun org-metaright (&optional arg)
18328 "Demote a subtree, a list item or move table column to right.
18329 In front of a drawer or a block keyword, indent it correctly.
18330 With no specific context, calls the Emacs default `forward-word'.
18331 See the individual commands for more information."
18332 (interactive "P")
18333 (cond
18334 ((run-hook-with-args-until-success 'org-metaright-hook))
18335 ((org-at-table-p) (call-interactively 'org-table-move-column))
18336 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
18337 ((org-at-block-p) (call-interactively 'org-indent-block))
18338 ((org-with-limited-levels
18339 (or (org-at-heading-p)
18340 (and (org-region-active-p)
18341 (save-excursion
18342 (goto-char (region-beginning))
18343 (org-at-heading-p)))))
18344 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18345 (call-interactively 'org-do-demote))
18346 ;; At an inline task.
18347 ((org-at-heading-p)
18348 (call-interactively 'org-inlinetask-demote))
18349 ((or (org-at-item-p)
18350 (and (org-region-active-p)
18351 (save-excursion
18352 (goto-char (region-beginning))
18353 (org-at-item-p))))
18354 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
18355 (call-interactively 'org-indent-item))
18356 (t (call-interactively 'forward-word))))
18358 (defun org-check-for-hidden (what)
18359 "Check if there are hidden headlines/items in the current visual line.
18360 WHAT can be either `headlines' or `items'. If the current line is
18361 an outline or item heading and it has a folded subtree below it,
18362 this function returns t, nil otherwise."
18363 (let ((re (cond
18364 ((eq what 'headlines) org-outline-regexp-bol)
18365 ((eq what 'items) (org-item-beginning-re))
18366 (t (error "This should not happen"))))
18367 beg end)
18368 (save-excursion
18369 (catch 'exit
18370 (unless (org-region-active-p)
18371 (setq beg (point-at-bol))
18372 (beginning-of-line 2)
18373 (while (and (not (eobp)) ;; this is like `next-line'
18374 (get-char-property (1- (point)) 'invisible))
18375 (beginning-of-line 2))
18376 (setq end (point))
18377 (goto-char beg)
18378 (goto-char (point-at-eol))
18379 (setq end (max end (point)))
18380 (while (re-search-forward re end t)
18381 (if (get-char-property (match-beginning 0) 'invisible)
18382 (throw 'exit t))))
18383 nil))))
18385 (defun org-metaup (&optional arg)
18386 "Move subtree up or move table row up.
18387 Calls `org-move-subtree-up' or `org-table-move-row' or
18388 `org-move-item-up', depending on context. See the individual commands
18389 for more information."
18390 (interactive "P")
18391 (cond
18392 ((run-hook-with-args-until-success 'org-metaup-hook))
18393 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
18394 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18395 ((org-at-item-p) (call-interactively 'org-move-item-up))
18396 (t (transpose-lines 1) (beginning-of-line -1))))
18398 (defun org-metadown (&optional arg)
18399 "Move subtree down or move table row down.
18400 Calls `org-move-subtree-down' or `org-table-move-row' or
18401 `org-move-item-down', depending on context. See the individual
18402 commands for more information."
18403 (interactive "P")
18404 (cond
18405 ((run-hook-with-args-until-success 'org-metadown-hook))
18406 ((org-at-table-p) (call-interactively 'org-table-move-row))
18407 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
18408 ((org-at-item-p) (call-interactively 'org-move-item-down))
18409 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
18411 (defun org-shiftup (&optional arg)
18412 "Increase item in timestamp or increase priority of current headline.
18413 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
18414 depending on context. See the individual commands for more information."
18415 (interactive "P")
18416 (cond
18417 ((run-hook-with-args-until-success 'org-shiftup-hook))
18418 ((and org-support-shift-select (org-region-active-p))
18419 (org-call-for-shift-select 'previous-line))
18420 ((org-at-timestamp-p t)
18421 (call-interactively (if org-edit-timestamp-down-means-later
18422 'org-timestamp-down 'org-timestamp-up)))
18423 ((and (not (eq org-support-shift-select 'always))
18424 org-enable-priority-commands
18425 (org-at-heading-p))
18426 (call-interactively 'org-priority-up))
18427 ((and (not org-support-shift-select) (org-at-item-p))
18428 (call-interactively 'org-previous-item))
18429 ((org-clocktable-try-shift 'up arg))
18430 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
18431 (org-support-shift-select
18432 (org-call-for-shift-select 'previous-line))
18433 (t (org-shiftselect-error))))
18435 (defun org-shiftdown (&optional arg)
18436 "Decrease item in timestamp or decrease priority of current headline.
18437 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
18438 depending on context. See the individual commands for more information."
18439 (interactive "P")
18440 (cond
18441 ((run-hook-with-args-until-success 'org-shiftdown-hook))
18442 ((and org-support-shift-select (org-region-active-p))
18443 (org-call-for-shift-select 'next-line))
18444 ((org-at-timestamp-p t)
18445 (call-interactively (if org-edit-timestamp-down-means-later
18446 'org-timestamp-up 'org-timestamp-down)))
18447 ((and (not (eq org-support-shift-select 'always))
18448 org-enable-priority-commands
18449 (org-at-heading-p))
18450 (call-interactively 'org-priority-down))
18451 ((and (not org-support-shift-select) (org-at-item-p))
18452 (call-interactively 'org-next-item))
18453 ((org-clocktable-try-shift 'down arg))
18454 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
18455 (org-support-shift-select
18456 (org-call-for-shift-select 'next-line))
18457 (t (org-shiftselect-error))))
18459 (defun org-shiftright (&optional arg)
18460 "Cycle the thing at point or in the current line, depending on context.
18461 Depending on context, this does one of the following:
18463 - switch a timestamp at point one day into the future
18464 - on a headline, switch to the next TODO keyword.
18465 - on an item, switch entire list to the next bullet type
18466 - on a property line, switch to the next allowed value
18467 - on a clocktable definition line, move time block into the future"
18468 (interactive "P")
18469 (cond
18470 ((run-hook-with-args-until-success 'org-shiftright-hook))
18471 ((and org-support-shift-select (org-region-active-p))
18472 (org-call-for-shift-select 'forward-char))
18473 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
18474 ((and (not (eq org-support-shift-select 'always))
18475 (org-at-heading-p))
18476 (let ((org-inhibit-logging
18477 (not org-treat-S-cursor-todo-selection-as-state-change))
18478 (org-inhibit-blocking
18479 (not org-treat-S-cursor-todo-selection-as-state-change)))
18480 (org-call-with-arg 'org-todo 'right)))
18481 ((or (and org-support-shift-select
18482 (not (eq org-support-shift-select 'always))
18483 (org-at-item-bullet-p))
18484 (and (not org-support-shift-select) (org-at-item-p)))
18485 (org-call-with-arg 'org-cycle-list-bullet nil))
18486 ((and (not (eq org-support-shift-select 'always))
18487 (org-at-property-p))
18488 (call-interactively 'org-property-next-allowed-value))
18489 ((org-clocktable-try-shift 'right arg))
18490 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
18491 (org-support-shift-select
18492 (org-call-for-shift-select 'forward-char))
18493 (t (org-shiftselect-error))))
18495 (defun org-shiftleft (&optional arg)
18496 "Cycle the thing at point or in the current line, depending on context.
18497 Depending on context, this does one of the following:
18499 - switch a timestamp at point one day into the past
18500 - on a headline, switch to the previous TODO keyword.
18501 - on an item, switch entire list to the previous bullet type
18502 - on a property line, switch to the previous allowed value
18503 - on a clocktable definition line, move time block into the past"
18504 (interactive "P")
18505 (cond
18506 ((run-hook-with-args-until-success 'org-shiftleft-hook))
18507 ((and org-support-shift-select (org-region-active-p))
18508 (org-call-for-shift-select 'backward-char))
18509 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
18510 ((and (not (eq org-support-shift-select 'always))
18511 (org-at-heading-p))
18512 (let ((org-inhibit-logging
18513 (not org-treat-S-cursor-todo-selection-as-state-change))
18514 (org-inhibit-blocking
18515 (not org-treat-S-cursor-todo-selection-as-state-change)))
18516 (org-call-with-arg 'org-todo 'left)))
18517 ((or (and org-support-shift-select
18518 (not (eq org-support-shift-select 'always))
18519 (org-at-item-bullet-p))
18520 (and (not org-support-shift-select) (org-at-item-p)))
18521 (org-call-with-arg 'org-cycle-list-bullet 'previous))
18522 ((and (not (eq org-support-shift-select 'always))
18523 (org-at-property-p))
18524 (call-interactively 'org-property-previous-allowed-value))
18525 ((org-clocktable-try-shift 'left arg))
18526 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
18527 (org-support-shift-select
18528 (org-call-for-shift-select 'backward-char))
18529 (t (org-shiftselect-error))))
18531 (defun org-shiftcontrolright ()
18532 "Switch to next TODO set."
18533 (interactive)
18534 (cond
18535 ((and org-support-shift-select (org-region-active-p))
18536 (org-call-for-shift-select 'forward-word))
18537 ((and (not (eq org-support-shift-select 'always))
18538 (org-at-heading-p))
18539 (org-call-with-arg 'org-todo 'nextset))
18540 (org-support-shift-select
18541 (org-call-for-shift-select 'forward-word))
18542 (t (org-shiftselect-error))))
18544 (defun org-shiftcontrolleft ()
18545 "Switch to previous TODO set."
18546 (interactive)
18547 (cond
18548 ((and org-support-shift-select (org-region-active-p))
18549 (org-call-for-shift-select 'backward-word))
18550 ((and (not (eq org-support-shift-select 'always))
18551 (org-at-heading-p))
18552 (org-call-with-arg 'org-todo 'previousset))
18553 (org-support-shift-select
18554 (org-call-for-shift-select 'backward-word))
18555 (t (org-shiftselect-error))))
18557 (defun org-shiftcontrolup ()
18558 "Change timestamps synchronously up in CLOCK log lines."
18559 (interactive)
18560 (cond ((and (not org-support-shift-select)
18561 (org-at-clock-log-p)
18562 (org-at-timestamp-p t))
18563 (org-clock-timestamps-up))
18564 (t (org-shiftselect-error))))
18566 (defun org-shiftcontroldown ()
18567 "Change timestamps synchronously down in CLOCK log lines."
18568 (interactive)
18569 (cond ((and (not org-support-shift-select)
18570 (org-at-clock-log-p)
18571 (org-at-timestamp-p t))
18572 (org-clock-timestamps-down))
18573 (t (org-shiftselect-error))))
18575 (defun org-ctrl-c-ret ()
18576 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
18577 (interactive)
18578 (cond
18579 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
18580 (t (call-interactively 'org-insert-heading))))
18582 (defun org-find-visible ()
18583 (let ((s (point)))
18584 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
18585 (get-char-property s 'invisible)))
18587 (defun org-find-invisible ()
18588 (let ((s (point)))
18589 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
18590 (not (get-char-property s 'invisible))))
18593 (defun org-copy-visible (beg end)
18594 "Copy the visible parts of the region."
18595 (interactive "r")
18596 (let (snippets s)
18597 (save-excursion
18598 (save-restriction
18599 (narrow-to-region beg end)
18600 (setq s (goto-char (point-min)))
18601 (while (not (= (point) (point-max)))
18602 (goto-char (org-find-invisible))
18603 (push (buffer-substring s (point)) snippets)
18604 (setq s (goto-char (org-find-visible))))))
18605 (kill-new (apply 'concat (nreverse snippets)))))
18607 (defun org-copy-special ()
18608 "Copy region in table or copy current subtree.
18609 Calls `org-table-copy' or `org-copy-subtree', depending on context.
18610 See the individual commands for more information."
18611 (interactive)
18612 (call-interactively
18613 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
18615 (defun org-cut-special ()
18616 "Cut region in table or cut current subtree.
18617 Calls `org-table-copy' or `org-cut-subtree', depending on context.
18618 See the individual commands for more information."
18619 (interactive)
18620 (call-interactively
18621 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
18623 (defun org-paste-special (arg)
18624 "Paste rectangular region into table, or past subtree relative to level.
18625 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
18626 See the individual commands for more information."
18627 (interactive "P")
18628 (if (org-at-table-p)
18629 (org-table-paste-rectangle)
18630 (org-paste-subtree arg)))
18632 (defun org-edit-special (&optional arg)
18633 "Call a special editor for the stuff at point.
18634 When at a table, call the formula editor with `org-table-edit-formulas'.
18635 When at the first line of an src example, call `org-edit-src-code'.
18636 When in an #+include line, visit the include file. Otherwise call
18637 `ffap' to visit the file at point."
18638 (interactive)
18639 ;; possibly prep session before editing source
18640 (when arg
18641 (let* ((info (org-babel-get-src-block-info))
18642 (lang (nth 0 info))
18643 (params (nth 2 info))
18644 (session (cdr (assoc :session params))))
18645 (when (and info session) ;; we are in a source-code block with a session
18646 (funcall
18647 (intern (concat "org-babel-prep-session:" lang)) session params))))
18648 (cond ;; proceed with `org-edit-special'
18649 ((save-excursion
18650 (beginning-of-line 1)
18651 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
18652 (find-file (org-trim (match-string 1))))
18653 ((org-edit-src-code))
18654 ((org-edit-fixed-width-region))
18655 ((org-at-table.el-p)
18656 (org-edit-src-code))
18657 ((or (org-at-table-p)
18658 (save-excursion
18659 (beginning-of-line 1)
18660 (let ((case-fold-search )) (looking-at "[ \t]*#\\+tblfm:"))))
18661 (call-interactively 'org-table-edit-formulas))
18662 (t (call-interactively 'ffap))))
18664 (defvar org-table-coordinate-overlays) ; defined in org-table.el
18665 (defun org-ctrl-c-ctrl-c (&optional arg)
18666 "Set tags in headline, or update according to changed information at point.
18668 This command does many different things, depending on context:
18670 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
18671 this is what we do.
18673 - If the cursor is on a statistics cookie, update it.
18675 - If the cursor is in a headline, prompt for tags and insert them
18676 into the current line, aligned to `org-tags-column'. When called
18677 with prefix arg, realign all tags in the current buffer.
18679 - If the cursor is in one of the special #+KEYWORD lines, this
18680 triggers scanning the buffer for these lines and updating the
18681 information.
18683 - If the cursor is inside a table, realign the table. This command
18684 works even if the automatic table editor has been turned off.
18686 - If the cursor is on a #+TBLFM line, re-apply the formulas to
18687 the entire table.
18689 - If the cursor is at a footnote reference or definition, jump to
18690 the corresponding definition or references, respectively.
18692 - If the cursor is a the beginning of a dynamic block, update it.
18694 - If the current buffer is a capture buffer, close note and file it.
18696 - If the cursor is on a <<<target>>>, update radio targets and
18697 corresponding links in this buffer.
18699 - If the cursor is on a numbered item in a plain list, renumber the
18700 ordered list.
18702 - If the cursor is on a checkbox, toggle it.
18704 - If the cursor is on a code block, evaluate it. The variable
18705 `org-confirm-babel-evaluate' can be used to control prompting
18706 before code block evaluation, by default every code block
18707 evaluation requires confirmation. Code block evaluation can be
18708 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
18709 (interactive "P")
18710 (let ((org-enable-table-editor t))
18711 (cond
18712 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
18713 org-occur-highlights
18714 org-latex-fragment-image-overlays)
18715 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
18716 (org-remove-occur-highlights)
18717 (org-remove-latex-fragment-image-overlays)
18718 (message "Temporary highlights/overlays removed from current buffer"))
18719 ((and (local-variable-p 'org-finish-function (current-buffer))
18720 (fboundp org-finish-function))
18721 (funcall org-finish-function))
18722 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
18723 ((org-in-regexp org-ts-regexp-both)
18724 (org-timestamp-change 0 'day))
18725 ((or (looking-at org-property-start-re)
18726 (org-at-property-p))
18727 (call-interactively 'org-property-action))
18728 ((org-at-target-p) (call-interactively 'org-update-radio-target-regexp))
18729 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
18730 (or (org-at-heading-p) (org-at-item-p)))
18731 (call-interactively 'org-update-statistics-cookies))
18732 ((org-at-heading-p) (call-interactively 'org-set-tags))
18733 ((org-at-table.el-p)
18734 (message "Use C-c ' to edit table.el tables"))
18735 ((org-at-table-p)
18736 (org-table-maybe-eval-formula)
18737 (if arg
18738 (call-interactively 'org-table-recalculate)
18739 (org-table-maybe-recalculate-line))
18740 (call-interactively 'org-table-align)
18741 (orgtbl-send-table 'maybe))
18742 ((or (org-footnote-at-reference-p)
18743 (org-footnote-at-definition-p))
18744 (call-interactively 'org-footnote-action))
18745 ((org-at-item-checkbox-p)
18746 ;; Cursor at a checkbox: repair list and update checkboxes. Send
18747 ;; list only if at top item.
18748 (let* ((cbox (match-string 1))
18749 (struct (org-list-struct))
18750 (old-struct (copy-tree struct))
18751 (parents (org-list-parents-alist struct))
18752 (orderedp (org-entry-get nil "ORDERED"))
18753 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
18754 block-item)
18755 ;; Use a light version of `org-toggle-checkbox' to avoid
18756 ;; computing list structure twice.
18757 (let ((new-box (cond
18758 ((equal arg '(16)) "[-]")
18759 ((equal arg '(4)) nil)
18760 ((equal "[X]" cbox) "[ ]")
18761 (t "[X]"))))
18762 (if (and firstp arg)
18763 ;; If at first item of sub-list, remove check-box from
18764 ;; every item at the same level.
18765 (mapc
18766 (lambda (pos) (org-list-set-checkbox pos struct new-box))
18767 (org-list-get-all-items
18768 (point-at-bol) struct (org-list-prevs-alist struct)))
18769 (org-list-set-checkbox (point-at-bol) struct new-box)))
18770 ;; Replicate `org-list-write-struct', while grabbing a return
18771 ;; value from `org-list-struct-fix-box'.
18772 (org-list-struct-fix-ind struct parents 2)
18773 (org-list-struct-fix-item-end struct)
18774 (let ((prevs (org-list-prevs-alist struct)))
18775 (org-list-struct-fix-bul struct prevs)
18776 (org-list-struct-fix-ind struct parents)
18777 (setq block-item
18778 (org-list-struct-fix-box struct parents prevs orderedp)))
18779 (org-list-struct-apply-struct struct old-struct)
18780 (org-update-checkbox-count-maybe)
18781 (when block-item
18782 (message
18783 "Checkboxes were removed due to unchecked box at line %d"
18784 (org-current-line block-item)))
18785 (when firstp (org-list-send-list 'maybe))))
18786 ((org-at-item-p)
18787 ;; Cursor at an item: repair list. Do checkbox related actions
18788 ;; only if function was called with an argument. Send list only
18789 ;; if at top item.
18790 (let* ((struct (org-list-struct))
18791 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
18792 old-struct)
18793 (when arg
18794 (setq old-struct (copy-tree struct))
18795 (if firstp
18796 ;; If at first item of sub-list, add check-box to every
18797 ;; item at the same level.
18798 (mapc
18799 (lambda (pos)
18800 (unless (org-list-get-checkbox pos struct)
18801 (org-list-set-checkbox pos struct "[ ]")))
18802 (org-list-get-all-items
18803 (point-at-bol) struct (org-list-prevs-alist struct)))
18804 (org-list-set-checkbox (point-at-bol) struct "[ ]")))
18805 (org-list-write-struct
18806 struct (org-list-parents-alist struct) old-struct)
18807 (when arg (org-update-checkbox-count-maybe))
18808 (when firstp (org-list-send-list 'maybe))))
18809 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
18810 ;; Dynamic block
18811 (beginning-of-line 1)
18812 (save-excursion (org-update-dblock)))
18813 ((save-excursion
18814 (let ((case-fold-search t))
18815 (beginning-of-line 1)
18816 (looking-at "[ \t]*#\\+\\([a-z]+\\)")))
18817 (cond
18818 ((or (equal (match-string 1) "TBLFM")
18819 (equal (match-string 1) "tblfm"))
18820 ;; Recalculate the table before this line
18821 (save-excursion
18822 (beginning-of-line 1)
18823 (skip-chars-backward " \r\n\t")
18824 (if (org-at-table-p)
18825 (org-call-with-arg 'org-table-recalculate (or arg t)))))
18827 (let ((org-inhibit-startup-visibility-stuff t)
18828 (org-startup-align-all-tables nil))
18829 (when (boundp 'org-table-coordinate-overlays)
18830 (mapc 'delete-overlay org-table-coordinate-overlays)
18831 (setq org-table-coordinate-overlays nil))
18832 (org-save-outline-visibility 'use-markers (org-mode-restart)))
18833 (message "Local setup has been refreshed"))))
18834 ((org-clock-update-time-maybe))
18836 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
18837 (error "C-c C-c can do nothing useful at this location"))))))
18839 (defun org-mode-restart ()
18840 "Restart Org-mode, to scan again for special lines.
18841 Also updates the keyword regular expressions."
18842 (interactive)
18843 (org-mode)
18844 (message "Org-mode restarted"))
18846 (defun org-kill-note-or-show-branches ()
18847 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
18848 (interactive)
18849 (if (not org-finish-function)
18850 (progn
18851 (hide-subtree)
18852 (call-interactively 'show-branches))
18853 (let ((org-note-abort t))
18854 (funcall org-finish-function))))
18856 (defun org-return (&optional indent)
18857 "Goto next table row or insert a newline.
18858 Calls `org-table-next-row' or `newline', depending on context.
18859 See the individual commands for more information."
18860 (interactive)
18861 (cond
18862 ((or (bobp) (org-in-src-block-p))
18863 (if indent (newline-and-indent) (newline)))
18864 ((org-at-table-p)
18865 (org-table-justify-field-maybe)
18866 (call-interactively 'org-table-next-row))
18867 ;; when `newline-and-indent' is called within a list, make sure
18868 ;; text moved stays inside the item.
18869 ((and (org-in-item-p) indent)
18870 (if (and (org-at-item-p) (>= (point) (match-end 0)))
18871 (progn
18872 (save-match-data (newline))
18873 (org-indent-line-to (length (match-string 0))))
18874 (let ((ind (org-get-indentation)))
18875 (newline)
18876 (if (org-looking-back org-list-end-re)
18877 (org-indent-line-function)
18878 (org-indent-line-to ind)))))
18879 ((and org-return-follows-link
18880 (let ((tprop (get-text-property (point) 'face)))
18881 (or (eq tprop 'org-link)
18882 (and (listp tprop) (memq 'org-link tprop)))))
18883 (call-interactively 'org-open-at-point))
18884 ((and (org-at-heading-p)
18885 (looking-at
18886 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
18887 (org-show-entry)
18888 (end-of-line 1)
18889 (newline))
18890 (t (if indent (newline-and-indent) (newline)))))
18892 (defun org-return-indent ()
18893 "Goto next table row or insert a newline and indent.
18894 Calls `org-table-next-row' or `newline-and-indent', depending on
18895 context. See the individual commands for more information."
18896 (interactive)
18897 (org-return t))
18899 (defun org-ctrl-c-star ()
18900 "Compute table, or change heading status of lines.
18901 Calls `org-table-recalculate' or `org-toggle-heading',
18902 depending on context."
18903 (interactive)
18904 (cond
18905 ((org-at-table-p)
18906 (call-interactively 'org-table-recalculate))
18908 ;; Convert all lines in region to list items
18909 (call-interactively 'org-toggle-heading))))
18911 (defun org-ctrl-c-minus ()
18912 "Insert separator line in table or modify bullet status of line.
18913 Also turns a plain line or a region of lines into list items.
18914 Calls `org-table-insert-hline', `org-toggle-item', or
18915 `org-cycle-list-bullet', depending on context."
18916 (interactive)
18917 (cond
18918 ((org-at-table-p)
18919 (call-interactively 'org-table-insert-hline))
18920 ((org-region-active-p)
18921 (call-interactively 'org-toggle-item))
18922 ((org-in-item-p)
18923 (call-interactively 'org-cycle-list-bullet))
18925 (call-interactively 'org-toggle-item))))
18927 (defun org-toggle-item (arg)
18928 "Convert headings or normal lines to items, items to normal lines.
18929 If there is no active region, only the current line is considered.
18931 If the first non blank line in the region is an headline, convert
18932 all headlines to items, shifting text accordingly.
18934 If it is an item, convert all items to normal lines.
18936 If it is normal text, change region into an item. With a prefix
18937 argument ARG, change each line in region into an item."
18938 (interactive "P")
18939 (let ((shift-text
18940 (function
18941 ;; Shift text in current section to IND, from point to END.
18942 ;; The function leaves point to END line.
18943 (lambda (ind end)
18944 (let ((min-i 1000) (end (copy-marker end)))
18945 ;; First determine the minimum indentation (MIN-I) of
18946 ;; the text.
18947 (save-excursion
18948 (catch 'exit
18949 (while (< (point) end)
18950 (let ((i (org-get-indentation)))
18951 (cond
18952 ;; Skip blank lines and inline tasks.
18953 ((looking-at "^[ \t]*$"))
18954 ((looking-at org-outline-regexp-bol))
18955 ;; We can't find less than 0 indentation.
18956 ((zerop i) (throw 'exit (setq min-i 0)))
18957 ((< i min-i) (setq min-i i))))
18958 (forward-line))))
18959 ;; Then indent each line so that a line indented to
18960 ;; MIN-I becomes indented to IND. Ignore blank lines
18961 ;; and inline tasks in the process.
18962 (let ((delta (- ind min-i)))
18963 (while (< (point) end)
18964 (unless (or (looking-at "^[ \t]*$")
18965 (looking-at org-outline-regexp-bol))
18966 (org-indent-line-to (+ (org-get-indentation) delta)))
18967 (forward-line)))))))
18968 (skip-blanks
18969 (function
18970 ;; Return beginning of first non-blank line, starting from
18971 ;; line at POS.
18972 (lambda (pos)
18973 (save-excursion
18974 (goto-char pos)
18975 (skip-chars-forward " \r\t\n")
18976 (point-at-bol)))))
18977 beg end)
18978 ;; Determine boundaries of changes.
18979 (if (org-region-active-p)
18980 (setq beg (funcall skip-blanks (region-beginning))
18981 end (copy-marker (region-end)))
18982 (setq beg (funcall skip-blanks (point-at-bol))
18983 end (copy-marker (point-at-eol))))
18984 ;; Depending on the starting line, choose an action on the text
18985 ;; between BEG and END.
18986 (org-with-limited-levels
18987 (save-excursion
18988 (goto-char beg)
18989 (cond
18990 ;; Case 1. Start at an item: de-itemize. Note that it only
18991 ;; happens when a region is active: `org-ctrl-c-minus'
18992 ;; would call `org-cycle-list-bullet' otherwise.
18993 ((org-at-item-p)
18994 (while (< (point) end)
18995 (when (org-at-item-p)
18996 (skip-chars-forward " \t")
18997 (delete-region (point) (match-end 0)))
18998 (forward-line)))
18999 ;; Case 2. Start at an heading: convert to items.
19000 ((org-at-heading-p)
19001 (let* ((bul (org-list-bullet-string "-"))
19002 (bul-len (length bul))
19003 ;; Indentation of the first heading. It should be
19004 ;; relative to the indentation of its parent, if any.
19005 (start-ind (save-excursion
19006 (cond
19007 ((not org-adapt-indentation) 0)
19008 ((not (outline-previous-heading)) 0)
19009 (t (length (match-string 0))))))
19010 ;; Level of first heading. Further headings will be
19011 ;; compared to it to determine hierarchy in the list.
19012 (ref-level (org-reduced-level (org-outline-level))))
19013 (while (< (point) end)
19014 (let* ((level (org-reduced-level (org-outline-level)))
19015 (delta (max 0 (- level ref-level))))
19016 ;; If current headline is less indented than the first
19017 ;; one, set it as reference, in order to preserve
19018 ;; subtrees.
19019 (when (< level ref-level) (setq ref-level level))
19020 (replace-match bul t t)
19021 (org-indent-line-to (+ start-ind (* delta bul-len)))
19022 ;; Ensure all text down to END (or SECTION-END) belongs
19023 ;; to the newly created item.
19024 (let ((section-end (save-excursion
19025 (or (outline-next-heading) (point)))))
19026 (forward-line)
19027 (funcall shift-text
19028 (+ start-ind (* (1+ delta) bul-len))
19029 (min end section-end)))))))
19030 ;; Case 3. Normal line with ARG: turn each non-item line into
19031 ;; an item.
19032 (arg
19033 (while (< (point) end)
19034 (unless (or (org-at-heading-p) (org-at-item-p))
19035 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
19036 (replace-match
19037 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
19038 (forward-line)))
19039 ;; Case 4. Normal line without ARG: make the first line of
19040 ;; region an item, and shift indentation of others
19041 ;; lines to set them as item's body.
19042 (t (let* ((bul (org-list-bullet-string "-"))
19043 (bul-len (length bul))
19044 (ref-ind (org-get-indentation)))
19045 (skip-chars-forward " \t")
19046 (insert bul)
19047 (forward-line)
19048 (while (< (point) end)
19049 ;; Ensure that lines less indented than first one
19050 ;; still get included in item body.
19051 (funcall shift-text
19052 (+ ref-ind bul-len)
19053 (min end (save-excursion (or (outline-next-heading)
19054 (point)))))
19055 (forward-line)))))))))
19057 (defun org-toggle-heading (&optional nstars)
19058 "Convert headings to normal text, or items or text to headings.
19059 If there is no active region, only the current line is considered.
19061 If the first non blank line is an headline, remove the stars from
19062 all headlines in the region.
19064 If it is a plain list item, turn all plain list items into headings.
19066 If it is a normal line, turn each and every normal line (i.e. not
19067 an heading or an item) in the region into a heading.
19069 When converting a line into a heading, the number of stars is chosen
19070 such that the lines become children of the current entry. However,
19071 when a prefix argument is given, its value determines the number of
19072 stars to add."
19073 (interactive "P")
19074 (let ((skip-blanks
19075 (function
19076 ;; Return beginning of first non-blank line, starting from
19077 ;; line at POS.
19078 (lambda (pos)
19079 (save-excursion
19080 (goto-char pos)
19081 (skip-chars-forward " \r\t\n")
19082 (point-at-bol)))))
19083 beg end)
19084 ;; Determine boundaries of changes. If region ends at a bol, do
19085 ;; not consider the last line to be in the region.
19086 (if (org-region-active-p)
19087 (setq beg (funcall skip-blanks (region-beginning))
19088 end (copy-marker (save-excursion
19089 (goto-char (region-end))
19090 (if (bolp) (point) (point-at-eol)))))
19091 (setq beg (funcall skip-blanks (point-at-bol))
19092 end (copy-marker (point-at-eol))))
19093 ;; Ensure inline tasks don't count as headings.
19094 (org-with-limited-levels
19095 (save-excursion
19096 (goto-char beg)
19097 (cond
19098 ;; Case 1. Started at an heading: de-star headings.
19099 ((org-at-heading-p)
19100 (while (< (point) end)
19101 (when (org-at-heading-p t)
19102 (looking-at org-outline-regexp) (replace-match ""))
19103 (forward-line)))
19104 ;; Case 2. Started at an item: change items into headlines.
19105 ;; One star will be added by `org-list-to-subtree'.
19106 ((org-at-item-p)
19107 (let* ((stars (make-string
19108 (if nstars
19109 ;; subtract the star that will be added again by
19110 ;; `org-list-to-subtree'
19111 (1- (prefix-numeric-value current-prefix-arg))
19112 (or (org-current-level) 0))
19113 ?*))
19114 (add-stars
19115 (cond (nstars "") ; stars from prefix only
19116 ((equal stars "") "") ; before first heading
19117 (org-odd-levels-only "*") ; inside heading, odd
19118 (t "")))) ; inside heading, oddeven
19119 (while (< (point) end)
19120 (when (org-at-item-p)
19121 ;; Pay attention to cases when region ends before list.
19122 (let* ((struct (org-list-struct))
19123 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
19124 (save-restriction
19125 (narrow-to-region (point) list-end)
19126 (insert
19127 (org-list-to-subtree
19128 (org-list-parse-list t)
19129 '(:istart (concat stars add-stars (funcall get-stars depth))
19130 :icount (concat stars add-stars (funcall get-stars depth))))))))
19131 (forward-line))))
19132 ;; Case 3. Started at normal text: make every line an heading,
19133 ;; skipping headlines and items.
19134 (t (let* ((stars (make-string
19135 (if nstars
19136 (prefix-numeric-value current-prefix-arg)
19137 (or (org-current-level) 0))
19138 ?*))
19139 (add-stars
19140 (cond (nstars "") ; stars from prefix only
19141 ((equal stars "") "*") ; before first heading
19142 (org-odd-levels-only "**") ; inside heading, odd
19143 (t "*"))) ; inside heading, oddeven
19144 (rpl (concat stars add-stars " ")))
19145 (while (< (point) end)
19146 (when (and (not (org-at-heading-p)) (not (org-at-item-p))
19147 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
19148 (replace-match (concat rpl (match-string 2))))
19149 (forward-line)))))))))
19151 (defun org-meta-return (&optional arg)
19152 "Insert a new heading or wrap a region in a table.
19153 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
19154 See the individual commands for more information."
19155 (interactive "P")
19156 (cond
19157 ((run-hook-with-args-until-success 'org-metareturn-hook))
19158 ((or (org-at-drawer-p) (org-at-property-p))
19159 (newline-and-indent))
19160 ((org-at-table-p)
19161 (call-interactively 'org-table-wrap-region))
19162 (t (call-interactively 'org-insert-heading))))
19164 ;;; Menu entries
19166 ;; Define the Org-mode menus
19167 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
19168 '("Tbl"
19169 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
19170 ["Next Field" org-cycle (org-at-table-p)]
19171 ["Previous Field" org-shifttab (org-at-table-p)]
19172 ["Next Row" org-return (org-at-table-p)]
19173 "--"
19174 ["Blank Field" org-table-blank-field (org-at-table-p)]
19175 ["Edit Field" org-table-edit-field (org-at-table-p)]
19176 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
19177 "--"
19178 ("Column"
19179 ["Move Column Left" org-metaleft (org-at-table-p)]
19180 ["Move Column Right" org-metaright (org-at-table-p)]
19181 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
19182 ["Insert Column" org-shiftmetaright (org-at-table-p)])
19183 ("Row"
19184 ["Move Row Up" org-metaup (org-at-table-p)]
19185 ["Move Row Down" org-metadown (org-at-table-p)]
19186 ["Delete Row" org-shiftmetaup (org-at-table-p)]
19187 ["Insert Row" org-shiftmetadown (org-at-table-p)]
19188 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
19189 "--"
19190 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
19191 ("Rectangle"
19192 ["Copy Rectangle" org-copy-special (org-at-table-p)]
19193 ["Cut Rectangle" org-cut-special (org-at-table-p)]
19194 ["Paste Rectangle" org-paste-special (org-at-table-p)]
19195 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
19196 "--"
19197 ("Calculate"
19198 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
19199 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
19200 ["Edit Formulas" org-edit-special (org-at-table-p)]
19201 "--"
19202 ["Recalculate line" org-table-recalculate (org-at-table-p)]
19203 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
19204 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
19205 "--"
19206 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
19207 "--"
19208 ["Sum Column/Rectangle" org-table-sum
19209 (or (org-at-table-p) (org-region-active-p))]
19210 ["Which Column?" org-table-current-column (org-at-table-p)])
19211 ["Debug Formulas"
19212 org-table-toggle-formula-debugger
19213 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
19214 ["Show Col/Row Numbers"
19215 org-table-toggle-coordinate-overlays
19216 :style toggle
19217 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
19218 "--"
19219 ["Create" org-table-create (and (not (org-at-table-p))
19220 org-enable-table-editor)]
19221 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
19222 ["Import from File" org-table-import (not (org-at-table-p))]
19223 ["Export to File" org-table-export (org-at-table-p)]
19224 "--"
19225 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
19227 (easy-menu-define org-org-menu org-mode-map "Org menu"
19228 '("Org"
19229 ("Show/Hide"
19230 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
19231 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
19232 ["Sparse Tree..." org-sparse-tree t]
19233 ["Reveal Context" org-reveal t]
19234 ["Show All" show-all t]
19235 "--"
19236 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
19237 "--"
19238 ["New Heading" org-insert-heading t]
19239 ("Navigate Headings"
19240 ["Up" outline-up-heading t]
19241 ["Next" outline-next-visible-heading t]
19242 ["Previous" outline-previous-visible-heading t]
19243 ["Next Same Level" outline-forward-same-level t]
19244 ["Previous Same Level" outline-backward-same-level t]
19245 "--"
19246 ["Jump" org-goto t])
19247 ("Edit Structure"
19248 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
19249 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
19250 "--"
19251 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
19252 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
19253 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
19254 "--"
19255 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
19256 "--"
19257 ["Copy visible text" org-copy-visible t]
19258 "--"
19259 ["Promote Heading" org-metaleft (not (org-at-table-p))]
19260 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
19261 ["Demote Heading" org-metaright (not (org-at-table-p))]
19262 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
19263 "--"
19264 ["Sort Region/Children" org-sort (not (org-at-table-p))]
19265 "--"
19266 ["Convert to odd levels" org-convert-to-odd-levels t]
19267 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
19268 ("Editing"
19269 ["Emphasis..." org-emphasize t]
19270 ["Edit Source Example" org-edit-special t]
19271 "--"
19272 ["Footnote new/jump" org-footnote-action t]
19273 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
19274 ("Archive"
19275 ["Archive (default method)" org-archive-subtree-default t]
19276 "--"
19277 ["Move Subtree to Archive file" org-advertized-archive-subtree t]
19278 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
19279 ["Move subtree to Archive sibling" org-archive-to-archive-sibling t]
19281 "--"
19282 ("Hyperlinks"
19283 ["Store Link (Global)" org-store-link t]
19284 ["Find existing link to here" org-occur-link-in-agenda-files t]
19285 ["Insert Link" org-insert-link t]
19286 ["Follow Link" org-open-at-point t]
19287 "--"
19288 ["Next link" org-next-link t]
19289 ["Previous link" org-previous-link t]
19290 "--"
19291 ["Descriptive Links"
19292 org-toggle-link-display
19293 :style radio
19294 :selected org-descriptive-links
19296 ["Literal Links"
19297 org-toggle-link-display
19298 :style radio
19299 :selected (not org-descriptive-links)])
19300 "--"
19301 ("TODO Lists"
19302 ["TODO/DONE/-" org-todo t]
19303 ("Select keyword"
19304 ["Next keyword" org-shiftright (org-at-heading-p)]
19305 ["Previous keyword" org-shiftleft (org-at-heading-p)]
19306 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
19307 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
19308 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
19309 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
19310 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
19311 "--"
19312 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
19313 :selected org-enforce-todo-dependencies :style toggle :active t]
19314 "Settings for tree at point"
19315 ["Do Children sequentially" org-toggle-ordered-property :style radio
19316 :selected (org-entry-get nil "ORDERED")
19317 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
19318 ["Do Children parallel" org-toggle-ordered-property :style radio
19319 :selected (not (org-entry-get nil "ORDERED"))
19320 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
19321 "--"
19322 ["Set Priority" org-priority t]
19323 ["Priority Up" org-shiftup t]
19324 ["Priority Down" org-shiftdown t]
19325 "--"
19326 ["Get news from all feeds" org-feed-update-all t]
19327 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
19328 ["Customize feeds" (customize-variable 'org-feed-alist) t])
19329 ("TAGS and Properties"
19330 ["Set Tags" org-set-tags-command t]
19331 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
19332 "--"
19333 ["Set property" org-set-property t]
19334 ["Column view of properties" org-columns t]
19335 ["Insert Column View DBlock" org-insert-columns-dblock t])
19336 ("Dates and Scheduling"
19337 ["Timestamp" org-time-stamp t]
19338 ["Timestamp (inactive)" org-time-stamp-inactive t]
19339 ("Change Date"
19340 ["1 Day Later" org-shiftright t]
19341 ["1 Day Earlier" org-shiftleft t]
19342 ["1 ... Later" org-shiftup t]
19343 ["1 ... Earlier" org-shiftdown t])
19344 ["Compute Time Range" org-evaluate-time-range t]
19345 ["Schedule Item" org-schedule t]
19346 ["Deadline" org-deadline t]
19347 "--"
19348 ["Custom time format" org-toggle-time-stamp-overlays
19349 :style radio :selected org-display-custom-times]
19350 "--"
19351 ["Goto Calendar" org-goto-calendar t]
19352 ["Date from Calendar" org-date-from-calendar t]
19353 "--"
19354 ["Start/Restart Timer" org-timer-start t]
19355 ["Pause/Continue Timer" org-timer-pause-or-continue t]
19356 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
19357 ["Insert Timer String" org-timer t]
19358 ["Insert Timer Item" org-timer-item t])
19359 ("Logging work"
19360 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
19361 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
19362 ["Clock out" org-clock-out t]
19363 ["Clock cancel" org-clock-cancel t]
19364 "--"
19365 ["Mark as default task" org-clock-mark-default-task t]
19366 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
19367 ["Goto running clock" org-clock-goto t]
19368 "--"
19369 ["Display times" org-clock-display t]
19370 ["Create clock table" org-clock-report t]
19371 "--"
19372 ["Record DONE time"
19373 (progn (setq org-log-done (not org-log-done))
19374 (message "Switching to %s will %s record a timestamp"
19375 (car org-done-keywords)
19376 (if org-log-done "automatically" "not")))
19377 :style toggle :selected org-log-done])
19378 "--"
19379 ["Agenda Command..." org-agenda t]
19380 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
19381 ("File List for Agenda")
19382 ("Special views current file"
19383 ["TODO Tree" org-show-todo-tree t]
19384 ["Check Deadlines" org-check-deadlines t]
19385 ["Timeline" org-timeline t]
19386 ["Tags/Property tree" org-match-sparse-tree t])
19387 "--"
19388 ["Export/Publish..." org-export t]
19389 ("LaTeX"
19390 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
19391 :selected org-cdlatex-mode]
19392 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
19393 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
19394 ["Modify math symbol" org-cdlatex-math-modify
19395 (org-inside-LaTeX-fragment-p)]
19396 ["Insert citation" org-reftex-citation t]
19397 "--"
19398 ["Template for BEAMER" (progn (require 'org-beamer)
19399 (org-insert-beamer-options-template)) t])
19400 "--"
19401 ("MobileOrg"
19402 ["Push Files and Views" org-mobile-push t]
19403 ["Get Captured and Flagged" org-mobile-pull t]
19404 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
19405 "--"
19406 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
19407 "--"
19408 ("Documentation"
19409 ["Show Version" org-version t]
19410 ["Info Documentation" org-info t])
19411 ("Customize"
19412 ["Browse Org Group" org-customize t]
19413 "--"
19414 ["Expand This Menu" org-create-customize-menu
19415 (fboundp 'customize-menu-create)])
19416 ["Send bug report" org-submit-bug-report t]
19417 "--"
19418 ("Refresh/Reload"
19419 ["Refresh setup current buffer" org-mode-restart t]
19420 ["Reload Org (after update)" org-reload t]
19421 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
19424 (defun org-info (&optional node)
19425 "Read documentation for Org-mode in the info system.
19426 With optional NODE, go directly to that node."
19427 (interactive)
19428 (info (format "(org)%s" (or node ""))))
19430 ;;;###autoload
19431 (defun org-submit-bug-report ()
19432 "Submit a bug report on Org-mode via mail.
19434 Don't hesitate to report any problems or inaccurate documentation.
19436 If you don't have setup sending mail from (X)Emacs, please copy the
19437 output buffer into your mail program, as it gives us important
19438 information about your Org-mode version and configuration."
19439 (interactive)
19440 (require 'reporter)
19441 (org-load-modules-maybe)
19442 (org-require-autoloaded-modules)
19443 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
19444 (reporter-submit-bug-report
19445 "emacs-orgmode@gnu.org"
19446 (org-version)
19447 (let (list)
19448 (save-window-excursion
19449 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
19450 (delete-other-windows)
19451 (erase-buffer)
19452 (insert "You are about to submit a bug report to the Org-mode mailing list.
19454 We would like to add your full Org-mode and Outline configuration to the
19455 bug report. This greatly simplifies the work of the maintainer and
19456 other experts on the mailing list.
19458 HOWEVER, some variables you have customized may contain private
19459 information. The names of customers, colleagues, or friends, might
19460 appear in the form of file names, tags, todo states, or search strings.
19461 If you answer yes to the prompt, you might want to check and remove
19462 such private information before sending the email.")
19463 (add-text-properties (point-min) (point-max) '(face org-warning))
19464 (when (yes-or-no-p "Include your Org-mode configuration ")
19465 (mapatoms
19466 (lambda (v)
19467 (and (boundp v)
19468 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
19469 (or (and (symbol-value v)
19470 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
19471 (and
19472 (get v 'custom-type) (get v 'standard-value)
19473 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
19474 (push v list)))))
19475 (kill-buffer (get-buffer "*Warn about privacy*"))
19476 list))
19477 nil nil
19478 "Remember to cover the basics, that is, what you expected to happen and
19479 what in fact did happen. You don't know how to make a good report? See
19481 http://orgmode.org/manual/Feedback.html#Feedback
19483 Your bug report will be posted to the Org-mode mailing list.
19484 ------------------------------------------------------------------------")
19485 (save-excursion
19486 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
19487 (replace-match "\\1Bug: \\3 [\\2]")))))
19490 (defun org-install-agenda-files-menu ()
19491 (let ((bl (buffer-list)))
19492 (save-excursion
19493 (while bl
19494 (set-buffer (pop bl))
19495 (if (derived-mode-p 'org-mode) (setq bl nil)))
19496 (when (derived-mode-p 'org-mode)
19497 (easy-menu-change
19498 '("Org") "File List for Agenda"
19499 (append
19500 (list
19501 ["Edit File List" (org-edit-agenda-file-list) t]
19502 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
19503 ["Remove Current File from List" org-remove-file t]
19504 ["Cycle through agenda files" org-cycle-agenda-files t]
19505 ["Occur in all agenda files" org-occur-in-agenda-files t]
19506 "--")
19507 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
19509 ;;;; Documentation
19511 ;;;###autoload
19512 (defun org-require-autoloaded-modules ()
19513 (interactive)
19514 (mapc 'require
19515 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
19516 org-docbook org-exp org-html org-icalendar
19517 org-id org-latex
19518 org-publish org-remember org-table
19519 org-timer org-xoxo)))
19521 ;;;###autoload
19522 (defun org-reload (&optional uncompiled)
19523 "Reload all org lisp files.
19524 With prefix arg UNCOMPILED, load the uncompiled versions."
19525 (interactive "P")
19526 (require 'find-func)
19527 (let* ((file-re "^\\(org\\|orgtbl\\)\\(\\.el\\|-.*\\.el\\)")
19528 (dir-org (file-name-directory (org-find-library-name "org")))
19529 (dir-org-contrib (ignore-errors
19530 (file-name-directory
19531 (org-find-library-name "org-contribdir"))))
19532 (babel-files
19533 (mapcar (lambda (el) (concat "ob" (when el (format "-%s" el)) ".el"))
19534 (append (list nil "comint" "eval" "exp" "keys"
19535 "lob" "ref" "table" "tangle")
19536 (delq nil
19537 (mapcar
19538 (lambda (lang)
19539 (when (cdr lang) (symbol-name (car lang))))
19540 org-babel-load-languages)))))
19541 (files
19542 (append (directory-files dir-org t file-re)
19543 babel-files
19544 (and dir-org-contrib
19545 (directory-files dir-org-contrib t file-re))))
19546 (remove-re (concat (if (featurep 'xemacs)
19547 "org-colview" "org-colview-xemacs")
19548 "\\'")))
19549 (setq files (mapcar 'file-name-sans-extension files))
19550 (setq files (mapcar
19551 (lambda (x) (if (string-match remove-re x) nil x))
19552 files))
19553 (setq files (delq nil files))
19554 (mapc
19555 (lambda (f)
19556 (when (featurep (intern (file-name-nondirectory f)))
19557 (if (and (not uncompiled)
19558 (file-exists-p (concat f ".elc")))
19559 (load (concat f ".elc") nil nil t)
19560 (load (concat f ".el") nil nil t))))
19561 files))
19562 (org-version))
19564 ;;;###autoload
19565 (defun org-customize ()
19566 "Call the customize function with org as argument."
19567 (interactive)
19568 (org-load-modules-maybe)
19569 (org-require-autoloaded-modules)
19570 (customize-browse 'org))
19572 (defun org-create-customize-menu ()
19573 "Create a full customization menu for Org-mode, insert it into the menu."
19574 (interactive)
19575 (org-load-modules-maybe)
19576 (org-require-autoloaded-modules)
19577 (if (fboundp 'customize-menu-create)
19578 (progn
19579 (easy-menu-change
19580 '("Org") "Customize"
19581 `(["Browse Org group" org-customize t]
19582 "--"
19583 ,(customize-menu-create 'org)
19584 ["Set" Custom-set t]
19585 ["Save" Custom-save t]
19586 ["Reset to Current" Custom-reset-current t]
19587 ["Reset to Saved" Custom-reset-saved t]
19588 ["Reset to Standard Settings" Custom-reset-standard t]))
19589 (message "\"Org\"-menu now contains full customization menu"))
19590 (error "Cannot expand menu (outdated version of cus-edit.el)")))
19592 ;;;; Miscellaneous stuff
19594 ;;; Generally useful functions
19596 (defun org-get-at-bol (property)
19597 "Get text property PROPERTY at beginning of line."
19598 (get-text-property (point-at-bol) property))
19600 (defun org-find-text-property-in-string (prop s)
19601 "Return the first non-nil value of property PROP in string S."
19602 (or (get-text-property 0 prop s)
19603 (get-text-property (or (next-single-property-change 0 prop s) 0)
19604 prop s)))
19606 (defun org-display-warning (message) ;; Copied from Emacs-Muse
19607 "Display the given MESSAGE as a warning."
19608 (if (fboundp 'display-warning)
19609 (display-warning 'org message
19610 (if (featurep 'xemacs) 'warning :warning))
19611 (let ((buf (get-buffer-create "*Org warnings*")))
19612 (with-current-buffer buf
19613 (goto-char (point-max))
19614 (insert "Warning (Org): " message)
19615 (unless (bolp)
19616 (newline)))
19617 (display-buffer buf)
19618 (sit-for 0))))
19620 (defun org-eval (form)
19621 "Eval FORM and return result."
19622 (condition-case error
19623 (eval form)
19624 (error (format "%%![Error: %s]" error))))
19626 (defun org-in-clocktable-p ()
19627 "Check if the cursor is in a clocktable."
19628 (let ((pos (point)) start)
19629 (save-excursion
19630 (end-of-line 1)
19631 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
19632 (setq start (match-beginning 0))
19633 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
19634 (>= (match-end 0) pos)
19635 start))))
19637 (defun org-in-commented-line ()
19638 "Is point in a line starting with `#'?"
19639 (equal (char-after (point-at-bol)) ?#))
19641 (defun org-in-indented-comment-line ()
19642 "Is point in a line starting with `#' after some white space?"
19643 (save-excursion
19644 (save-match-data
19645 (goto-char (point-at-bol))
19646 (looking-at "[ \t]*#"))))
19648 (defun org-in-verbatim-emphasis ()
19649 (save-match-data
19650 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
19652 (defun org-goto-marker-or-bmk (marker &optional bookmark)
19653 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
19654 (if (and marker (marker-buffer marker)
19655 (buffer-live-p (marker-buffer marker)))
19656 (progn
19657 (org-pop-to-buffer-same-window (marker-buffer marker))
19658 (if (or (> marker (point-max)) (< marker (point-min)))
19659 (widen))
19660 (goto-char marker)
19661 (org-show-context 'org-goto))
19662 (if bookmark
19663 (bookmark-jump bookmark)
19664 (error "Cannot find location"))))
19666 (defun org-quote-csv-field (s)
19667 "Quote field for inclusion in CSV material."
19668 (if (string-match "[\",]" s)
19669 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
19672 (defun org-force-self-insert (N)
19673 "Needed to enforce self-insert under remapping."
19674 (interactive "p")
19675 (self-insert-command N))
19677 (defun org-string-width (s)
19678 "Compute width of string, ignoring invisible characters.
19679 This ignores character with invisibility property `org-link', and also
19680 characters with property `org-cwidth', because these will become invisible
19681 upon the next fontification round."
19682 (let (b l)
19683 (when (or (eq t buffer-invisibility-spec)
19684 (assq 'org-link buffer-invisibility-spec))
19685 (while (setq b (text-property-any 0 (length s)
19686 'invisible 'org-link s))
19687 (setq s (concat (substring s 0 b)
19688 (substring s (or (next-single-property-change
19689 b 'invisible s) (length s)))))))
19690 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
19691 (setq s (concat (substring s 0 b)
19692 (substring s (or (next-single-property-change
19693 b 'org-cwidth s) (length s))))))
19694 (setq l (string-width s) b -1)
19695 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
19696 (setq l (- l (get-text-property b 'org-dwidth-n s))))
19699 (defun org-shorten-string (s maxlength)
19700 "Shorten string S so tht it is no longer than MAXLENGTH characters.
19701 If the string is shorter or has length MAXLENGTH, just return the
19702 original string. If it is longer, the functions finds a space in the
19703 string, breaks this string off at that locations and adds three dots
19704 as ellipsis. Including the ellipsis, the string will not be longer
19705 than MAXLENGTH. If finding a good breaking point in the string does
19706 not work, the string is just chopped off in the middle of a word
19707 if necessary."
19708 (if (<= (length s) maxlength)
19710 (let* ((n (max (- maxlength 4) 1))
19711 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
19712 (if (string-match re s)
19713 (concat (match-string 1 s) "...")
19714 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
19716 (defun org-get-indentation (&optional line)
19717 "Get the indentation of the current line, interpreting tabs.
19718 When LINE is given, assume it represents a line and compute its indentation."
19719 (if line
19720 (if (string-match "^ *" (org-remove-tabs line))
19721 (match-end 0))
19722 (save-excursion
19723 (beginning-of-line 1)
19724 (skip-chars-forward " \t")
19725 (current-column))))
19727 (defun org-get-string-indentation (s)
19728 "What indentation has S due to SPACE and TAB at the beginning of the string?"
19729 (let ((n -1) (i 0) (w tab-width) c)
19730 (catch 'exit
19731 (while (< (setq n (1+ n)) (length s))
19732 (setq c (aref s n))
19733 (cond ((= c ?\ ) (setq i (1+ i)))
19734 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
19735 (t (throw 'exit t)))))
19738 (defun org-remove-tabs (s &optional width)
19739 "Replace tabulators in S with spaces.
19740 Assumes that s is a single line, starting in column 0."
19741 (setq width (or width tab-width))
19742 (while (string-match "\t" s)
19743 (setq s (replace-match
19744 (make-string
19745 (- (* width (/ (+ (match-beginning 0) width) width))
19746 (match-beginning 0)) ?\ )
19747 t t s)))
19750 (defun org-fix-indentation (line ind)
19751 "Fix indentation in LINE.
19752 IND is a cons cell with target and minimum indentation.
19753 If the current indentation in LINE is smaller than the minimum,
19754 leave it alone. If it is larger than ind, set it to the target."
19755 (let* ((l (org-remove-tabs line))
19756 (i (org-get-indentation l))
19757 (i1 (car ind)) (i2 (cdr ind)))
19758 (if (>= i i2) (setq l (substring line i2)))
19759 (if (> i1 0)
19760 (concat (make-string i1 ?\ ) l)
19761 l)))
19763 (defun org-remove-indentation (code &optional n)
19764 "Remove the maximum common indentation from the lines in CODE.
19765 N may optionally be the number of spaces to remove."
19766 (with-temp-buffer
19767 (insert code)
19768 (org-do-remove-indentation n)
19769 (buffer-string)))
19771 (defun org-do-remove-indentation (&optional n)
19772 "Remove the maximum common indentation from the buffer."
19773 (untabify (point-min) (point-max))
19774 (let ((min 10000) re)
19775 (if n
19776 (setq min n)
19777 (goto-char (point-min))
19778 (while (re-search-forward "^ *[^ \n]" nil t)
19779 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
19780 (unless (or (= min 0) (= min 10000))
19781 (setq re (format "^ \\{%d\\}" min))
19782 (goto-char (point-min))
19783 (while (re-search-forward re nil t)
19784 (replace-match "")
19785 (end-of-line 1))
19786 min)))
19788 (defun org-fill-template (template alist)
19789 "Find each %key of ALIST in TEMPLATE and replace it."
19790 (let ((case-fold-search nil)
19791 entry key value)
19792 (setq alist (sort (copy-sequence alist)
19793 (lambda (a b) (< (length (car a)) (length (car b))))))
19794 (while (setq entry (pop alist))
19795 (setq template
19796 (replace-regexp-in-string
19797 (concat "%" (regexp-quote (car entry)))
19798 (cdr entry) template t t)))
19799 template))
19801 (defun org-base-buffer (buffer)
19802 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
19803 (if (not buffer)
19804 buffer
19805 (or (buffer-base-buffer buffer)
19806 buffer)))
19808 (defun org-trim (s)
19809 "Remove whitespace at beginning and end of string."
19810 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
19811 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
19814 (defun org-wrap (string &optional width lines)
19815 "Wrap string to either a number of lines, or a width in characters.
19816 If WIDTH is non-nil, the string is wrapped to that width, however many lines
19817 that costs. If there is a word longer than WIDTH, the text is actually
19818 wrapped to the length of that word.
19819 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
19820 many lines, whatever width that takes.
19821 The return value is a list of lines, without newlines at the end."
19822 (let* ((words (org-split-string string "[ \t\n]+"))
19823 (maxword (apply 'max (mapcar 'org-string-width words)))
19824 w ll)
19825 (cond (width
19826 (org-do-wrap words (max maxword width)))
19827 (lines
19828 (setq w maxword)
19829 (setq ll (org-do-wrap words maxword))
19830 (if (<= (length ll) lines)
19832 (setq ll words)
19833 (while (> (length ll) lines)
19834 (setq w (1+ w))
19835 (setq ll (org-do-wrap words w)))
19836 ll))
19837 (t (error "Cannot wrap this")))))
19839 (defun org-do-wrap (words width)
19840 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
19841 (let (lines line)
19842 (while words
19843 (setq line (pop words))
19844 (while (and words (< (+ (length line) (length (car words))) width))
19845 (setq line (concat line " " (pop words))))
19846 (setq lines (push line lines)))
19847 (nreverse lines)))
19849 (defun org-split-string (string &optional separators)
19850 "Splits STRING into substrings at SEPARATORS.
19851 No empty strings are returned if there are matches at the beginning
19852 and end of string."
19853 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
19854 (start 0)
19855 notfirst
19856 (list nil))
19857 (while (and (string-match rexp string
19858 (if (and notfirst
19859 (= start (match-beginning 0))
19860 (< start (length string)))
19861 (1+ start) start))
19862 (< (match-beginning 0) (length string)))
19863 (setq notfirst t)
19864 (or (eq (match-beginning 0) 0)
19865 (and (eq (match-beginning 0) (match-end 0))
19866 (eq (match-beginning 0) start))
19867 (setq list
19868 (cons (substring string start (match-beginning 0))
19869 list)))
19870 (setq start (match-end 0)))
19871 (or (eq start (length string))
19872 (setq list
19873 (cons (substring string start)
19874 list)))
19875 (nreverse list)))
19877 (defun org-quote-vert (s)
19878 "Replace \"|\" with \"\\vert\"."
19879 (while (string-match "|" s)
19880 (setq s (replace-match "\\vert" t t s)))
19883 (defun org-uuidgen-p (s)
19884 "Is S an ID created by UUIDGEN?"
19885 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
19887 (defun org-in-src-block-p nil
19888 "Whether point is in a code source block."
19889 (let (ov)
19890 (when (setq ov (overlays-at (point)))
19891 (memq 'org-block-background
19892 (overlay-properties
19893 (car ov))))))
19895 (defun org-context ()
19896 "Return a list of contexts of the current cursor position.
19897 If several contexts apply, all are returned.
19898 Each context entry is a list with a symbol naming the context, and
19899 two positions indicating start and end of the context. Possible
19900 contexts are:
19902 :headline anywhere in a headline
19903 :headline-stars on the leading stars in a headline
19904 :todo-keyword on a TODO keyword (including DONE) in a headline
19905 :tags on the TAGS in a headline
19906 :priority on the priority cookie in a headline
19907 :item on the first line of a plain list item
19908 :item-bullet on the bullet/number of a plain list item
19909 :checkbox on the checkbox in a plain list item
19910 :table in an org-mode table
19911 :table-special on a special filed in a table
19912 :table-table in a table.el table
19913 :clocktable in a clocktable
19914 :src-block in a source block
19915 :link on a hyperlink
19916 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
19917 :target on a <<target>>
19918 :radio-target on a <<<radio-target>>>
19919 :latex-fragment on a LaTeX fragment
19920 :latex-preview on a LaTeX fragment with overlaid preview image
19922 This function expects the position to be visible because it uses font-lock
19923 faces as a help to recognize the following contexts: :table-special, :link,
19924 and :keyword."
19925 (let* ((f (get-text-property (point) 'face))
19926 (faces (if (listp f) f (list f)))
19927 (case-fold-search t)
19928 (p (point)) clist o)
19929 ;; First the large context
19930 (cond
19931 ((org-at-heading-p t)
19932 (push (list :headline (point-at-bol) (point-at-eol)) clist)
19933 (when (progn
19934 (beginning-of-line 1)
19935 (looking-at org-todo-line-tags-regexp))
19936 (push (org-point-in-group p 1 :headline-stars) clist)
19937 (push (org-point-in-group p 2 :todo-keyword) clist)
19938 (push (org-point-in-group p 4 :tags) clist))
19939 (goto-char p)
19940 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
19941 (if (looking-at "\\[#[A-Z0-9]\\]")
19942 (push (org-point-in-group p 0 :priority) clist)))
19944 ((org-at-item-p)
19945 (push (org-point-in-group p 2 :item-bullet) clist)
19946 (push (list :item (point-at-bol)
19947 (save-excursion (org-end-of-item) (point)))
19948 clist)
19949 (and (org-at-item-checkbox-p)
19950 (push (org-point-in-group p 0 :checkbox) clist)))
19952 ((org-at-table-p)
19953 (push (list :table (org-table-begin) (org-table-end)) clist)
19954 (if (memq 'org-formula faces)
19955 (push (list :table-special
19956 (previous-single-property-change p 'face)
19957 (next-single-property-change p 'face)) clist)))
19958 ((org-at-table-p 'any)
19959 (push (list :table-table) clist)))
19960 (goto-char p)
19962 ;; New the "medium" contexts: clocktables, source blocks
19963 (cond ((org-in-clocktable-p)
19964 (push (list :clocktable
19965 (and (or (looking-at "#\\+BEGIN: clocktable")
19966 (search-backward "#+BEGIN: clocktable" nil t))
19967 (match-beginning 0))
19968 (and (re-search-forward "#\\+END:?" nil t)
19969 (match-end 0))) clist))
19970 ((org-in-src-block-p)
19971 (push (list :src-block
19972 (and (or (looking-at "#\\+BEGIN_SRC")
19973 (search-backward "#+BEGIN_SRC" nil t))
19974 (match-beginning 0))
19975 (and (search-forward "#+END_SRC" nil t)
19976 (match-beginning 0))) clist)))
19977 (goto-char p)
19979 ;; Now the small context
19980 (cond
19981 ((org-at-timestamp-p)
19982 (push (org-point-in-group p 0 :timestamp) clist))
19983 ((memq 'org-link faces)
19984 (push (list :link
19985 (previous-single-property-change p 'face)
19986 (next-single-property-change p 'face)) clist))
19987 ((memq 'org-special-keyword faces)
19988 (push (list :keyword
19989 (previous-single-property-change p 'face)
19990 (next-single-property-change p 'face)) clist))
19991 ((org-at-target-p)
19992 (push (org-point-in-group p 0 :target) clist)
19993 (goto-char (1- (match-beginning 0)))
19994 (if (looking-at org-radio-target-regexp)
19995 (push (org-point-in-group p 0 :radio-target) clist))
19996 (goto-char p))
19997 ((setq o (car (delq nil
19998 (mapcar
19999 (lambda (x)
20000 (if (memq x org-latex-fragment-image-overlays) x))
20001 (overlays-at (point))))))
20002 (push (list :latex-fragment
20003 (overlay-start o) (overlay-end o)) clist)
20004 (push (list :latex-preview
20005 (overlay-start o) (overlay-end o)) clist))
20006 ((org-inside-LaTeX-fragment-p)
20007 ;; FIXME: positions wrong.
20008 (push (list :latex-fragment (point) (point)) clist)))
20010 (setq clist (nreverse (delq nil clist)))
20011 clist))
20013 ;; FIXME: Compare with at-regexp-p Do we need both?
20014 (defun org-in-regexp (re &optional nlines visually)
20015 "Check if point is inside a match of regexp.
20016 Normally only the current line is checked, but you can include NLINES extra
20017 lines both before and after point into the search.
20018 If VISUALLY is set, require that the cursor is not after the match but
20019 really on, so that the block visually is on the match."
20020 (catch 'exit
20021 (let ((pos (point))
20022 (eol (point-at-eol (+ 1 (or nlines 0))))
20023 (inc (if visually 1 0)))
20024 (save-excursion
20025 (beginning-of-line (- 1 (or nlines 0)))
20026 (while (re-search-forward re eol t)
20027 (if (and (<= (match-beginning 0) pos)
20028 (>= (+ inc (match-end 0)) pos))
20029 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
20031 (defun org-at-regexp-p (regexp)
20032 "Is point inside a match of REGEXP in the current line?"
20033 (catch 'exit
20034 (save-excursion
20035 (let ((pos (point)) (end (point-at-eol)))
20036 (beginning-of-line 1)
20037 (while (re-search-forward regexp end t)
20038 (if (and (<= (match-beginning 0) pos)
20039 (>= (match-end 0) pos))
20040 (throw 'exit t)))
20041 nil))))
20043 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
20044 "Non-nil when point is between matches of START-RE and END-RE.
20046 Also return a non-nil value when point is on one of the matches.
20048 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
20049 buffer positions. Default values are the positions of headlines
20050 surrounding the point.
20052 The functions returns a cons cell whose car (resp. cdr) is the
20053 position before START-RE (resp. after END-RE)."
20054 (save-match-data
20055 (let ((pos (point))
20056 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
20057 (limit-down (or lim-down (save-excursion (outline-next-heading))))
20058 beg end)
20059 (save-excursion
20060 ;; Point is on a block when on START-RE or if START-RE can be
20061 ;; found before it...
20062 (and (or (org-at-regexp-p start-re)
20063 (re-search-backward start-re limit-up t))
20064 (setq beg (match-beginning 0))
20065 ;; ... and END-RE after it...
20066 (goto-char (match-end 0))
20067 (re-search-forward end-re limit-down t)
20068 (> (setq end (match-end 0)) pos)
20069 ;; ... without another START-RE in-between.
20070 (goto-char (match-beginning 0))
20071 (not (re-search-backward start-re (1+ beg) t))
20072 ;; Return value.
20073 (cons beg end))))))
20075 (defun org-in-block-p (names)
20076 "Non-nil when point belongs to a block whose name belongs to NAMES.
20078 NAMES is a list of strings containing names of blocks.
20080 Return first block name matched, or nil. Beware that in case of
20081 nested blocks, the returned name may not belong to the closest
20082 block from point."
20083 (save-match-data
20084 (catch 'exit
20085 (let ((case-fold-search t)
20086 (lim-up (save-excursion (outline-previous-heading)))
20087 (lim-down (save-excursion (outline-next-heading))))
20088 (mapc (lambda (name)
20089 (let ((n (regexp-quote name)))
20090 (when (org-between-regexps-p
20091 (concat "^[ \t]*#\\+begin_" n)
20092 (concat "^[ \t]*#\\+end_" n)
20093 lim-up lim-down)
20094 (throw 'exit n))))
20095 names))
20096 nil)))
20098 (defun org-occur-in-agenda-files (regexp &optional nlines)
20099 "Call `multi-occur' with buffers for all agenda files."
20100 (interactive "sOrg-files matching: \np")
20101 (let* ((files (org-agenda-files))
20102 (tnames (mapcar 'file-truename files))
20103 (extra org-agenda-text-search-extra-files)
20105 (when (eq (car extra) 'agenda-archives)
20106 (setq extra (cdr extra))
20107 (setq files (org-add-archive-files files)))
20108 (while (setq f (pop extra))
20109 (unless (member (file-truename f) tnames)
20110 (add-to-list 'files f 'append)
20111 (add-to-list 'tnames (file-truename f) 'append)))
20112 (multi-occur
20113 (mapcar (lambda (x)
20114 (with-current-buffer
20115 (or (get-file-buffer x) (find-file-noselect x))
20116 (widen)
20117 (current-buffer)))
20118 files)
20119 regexp)))
20121 (if (boundp 'occur-mode-find-occurrence-hook)
20122 ;; Emacs 23
20123 (add-hook 'occur-mode-find-occurrence-hook
20124 (lambda ()
20125 (when (derived-mode-p 'org-mode)
20126 (org-reveal))))
20127 ;; Emacs 22
20128 (defadvice occur-mode-goto-occurrence
20129 (after org-occur-reveal activate)
20130 (and (derived-mode-p 'org-mode) (org-reveal)))
20131 (defadvice occur-mode-goto-occurrence-other-window
20132 (after org-occur-reveal activate)
20133 (and (derived-mode-p 'org-mode) (org-reveal)))
20134 (defadvice occur-mode-display-occurrence
20135 (after org-occur-reveal activate)
20136 (when (derived-mode-p 'org-mode)
20137 (let ((pos (occur-mode-find-occurrence)))
20138 (with-current-buffer (marker-buffer pos)
20139 (save-excursion
20140 (goto-char pos)
20141 (org-reveal)))))))
20143 (defun org-occur-link-in-agenda-files ()
20144 "Create a link and search for it in the agendas.
20145 The link is not stored in `org-stored-links', it is just created
20146 for the search purpose."
20147 (interactive)
20148 (let ((link (condition-case nil
20149 (org-store-link nil)
20150 (error "Unable to create a link to here"))))
20151 (org-occur-in-agenda-files (regexp-quote link))))
20153 (defun org-uniquify (list)
20154 "Remove duplicate elements from LIST."
20155 (let (res)
20156 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
20157 res))
20159 (defun org-delete-all (elts list)
20160 "Remove all elements in ELTS from LIST."
20161 (while elts
20162 (setq list (delete (pop elts) list)))
20163 list)
20165 (defun org-count (cl-item cl-seq)
20166 "Count the number of occurrences of ITEM in SEQ.
20167 Taken from `count' in cl-seq.el with all keyword arguments removed."
20168 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
20169 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
20170 (while (< cl-start cl-end)
20171 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
20172 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
20173 (setq cl-start (1+ cl-start)))
20174 cl-count))
20176 (defun org-remove-if (predicate seq)
20177 "Remove everything from SEQ that fulfills PREDICATE."
20178 (let (res e)
20179 (while seq
20180 (setq e (pop seq))
20181 (if (not (funcall predicate e)) (push e res)))
20182 (nreverse res)))
20184 (defun org-remove-if-not (predicate seq)
20185 "Remove everything from SEQ that does not fulfill PREDICATE."
20186 (let (res e)
20187 (while seq
20188 (setq e (pop seq))
20189 (if (funcall predicate e) (push e res)))
20190 (nreverse res)))
20192 (defun org-reduce (cl-func cl-seq &rest cl-keys)
20193 "Reduce two-argument FUNCTION across SEQ.
20194 Taken from `reduce' in cl-seq.el with all keyword arguments but
20195 \":initial-value\" removed."
20196 (let ((cl-accum (cond ((memq :initial-value cl-keys)
20197 (cadr (memq :initial-value cl-keys)))
20198 (cl-seq (pop cl-seq))
20199 (t (funcall cl-func)))))
20200 (while cl-seq
20201 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
20202 cl-accum))
20204 (defun org-back-over-empty-lines ()
20205 "Move backwards over whitespace, to the beginning of the first empty line.
20206 Returns the number of empty lines passed."
20207 (let ((pos (point)))
20208 (if (cdr (assoc 'heading org-blank-before-new-entry))
20209 (skip-chars-backward " \t\n\r")
20210 (unless (eobp)
20211 (forward-line -1)))
20212 (beginning-of-line 2)
20213 (goto-char (min (point) pos))
20214 (count-lines (point) pos)))
20216 (defun org-skip-whitespace ()
20217 (skip-chars-forward " \t\n\r"))
20219 (defun org-point-in-group (point group &optional context)
20220 "Check if POINT is in match-group GROUP.
20221 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
20222 match. If the match group does not exist or point is not inside it,
20223 return nil."
20224 (and (match-beginning group)
20225 (>= point (match-beginning group))
20226 (<= point (match-end group))
20227 (if context
20228 (list context (match-beginning group) (match-end group))
20229 t)))
20231 (defun org-switch-to-buffer-other-window (&rest args)
20232 "Switch to buffer in a second window on the current frame.
20233 In particular, do not allow pop-up frames.
20234 Returns the newly created buffer."
20235 (let (pop-up-frames special-display-buffer-names special-display-regexps
20236 special-display-function)
20237 (apply 'switch-to-buffer-other-window args)))
20239 (defun org-combine-plists (&rest plists)
20240 "Create a single property list from all plists in PLISTS.
20241 The process starts by copying the first list, and then setting properties
20242 from the other lists. Settings in the last list are the most significant
20243 ones and overrule settings in the other lists."
20244 (let ((rtn (copy-sequence (pop plists)))
20245 p v ls)
20246 (while plists
20247 (setq ls (pop plists))
20248 (while ls
20249 (setq p (pop ls) v (pop ls))
20250 (setq rtn (plist-put rtn p v))))
20251 rtn))
20253 (defun org-move-line-down (arg)
20254 "Move the current line down. With prefix argument, move it past ARG lines."
20255 (interactive "p")
20256 (let ((col (current-column))
20257 beg end pos)
20258 (beginning-of-line 1) (setq beg (point))
20259 (beginning-of-line 2) (setq end (point))
20260 (beginning-of-line (+ 1 arg))
20261 (setq pos (move-marker (make-marker) (point)))
20262 (insert (delete-and-extract-region beg end))
20263 (goto-char pos)
20264 (org-move-to-column col)))
20266 (defun org-move-line-up (arg)
20267 "Move the current line up. With prefix argument, move it past ARG lines."
20268 (interactive "p")
20269 (let ((col (current-column))
20270 beg end pos)
20271 (beginning-of-line 1) (setq beg (point))
20272 (beginning-of-line 2) (setq end (point))
20273 (beginning-of-line (- arg))
20274 (setq pos (move-marker (make-marker) (point)))
20275 (insert (delete-and-extract-region beg end))
20276 (goto-char pos)
20277 (org-move-to-column col)))
20279 (defun org-replace-escapes (string table)
20280 "Replace %-escapes in STRING with values in TABLE.
20281 TABLE is an association list with keys like \"%a\" and string values.
20282 The sequences in STRING may contain normal field width and padding information,
20283 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
20284 so values can contain further %-escapes if they are define later in TABLE."
20285 (let ((tbl (copy-alist table))
20286 (case-fold-search nil)
20287 (pchg 0)
20288 e re rpl)
20289 (while (setq e (pop tbl))
20290 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
20291 (when (and (cdr e) (string-match re (cdr e)))
20292 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
20293 (safe "SREF"))
20294 (add-text-properties 0 3 (list 'sref sref) safe)
20295 (setcdr e (replace-match safe t t (cdr e)))))
20296 (while (string-match re string)
20297 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
20298 (cdr e)))
20299 (setq string (replace-match rpl t t string))))
20300 (while (setq pchg (next-property-change pchg string))
20301 (let ((sref (get-text-property pchg 'sref string)))
20302 (when (and sref (string-match "SREF" string pchg))
20303 (setq string (replace-match sref t t string)))))
20304 string))
20306 (defun org-sublist (list start end)
20307 "Return a section of LIST, from START to END.
20308 Counting starts at 1."
20309 (let (rtn (c start))
20310 (setq list (nthcdr (1- start) list))
20311 (while (and list (<= c end))
20312 (push (pop list) rtn)
20313 (setq c (1+ c)))
20314 (nreverse rtn)))
20316 (defun org-find-base-buffer-visiting (file)
20317 "Like `find-buffer-visiting' but always return the base buffer and
20318 not an indirect buffer."
20319 (let ((buf (or (get-file-buffer file)
20320 (find-buffer-visiting file))))
20321 (if buf
20322 (or (buffer-base-buffer buf) buf)
20323 nil)))
20325 (defun org-image-file-name-regexp (&optional extensions)
20326 "Return regexp matching the file names of images.
20327 If EXTENSIONS is given, only match these."
20328 (if (and (not extensions) (fboundp 'image-file-name-regexp))
20329 (image-file-name-regexp)
20330 (let ((image-file-name-extensions
20331 (or extensions
20332 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
20333 "xbm" "xpm" "pbm" "pgm" "ppm"))))
20334 (concat "\\."
20335 (regexp-opt (nconc (mapcar 'upcase
20336 image-file-name-extensions)
20337 image-file-name-extensions)
20339 "\\'"))))
20341 (defun org-file-image-p (file &optional extensions)
20342 "Return non-nil if FILE is an image."
20343 (save-match-data
20344 (string-match (org-image-file-name-regexp extensions) file)))
20346 (defun org-get-cursor-date ()
20347 "Return the date at cursor in as a time.
20348 This works in the calendar and in the agenda, anywhere else it just
20349 returns the current time."
20350 (let (date day defd)
20351 (cond
20352 ((eq major-mode 'calendar-mode)
20353 (setq date (calendar-cursor-to-date)
20354 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
20355 ((eq major-mode 'org-agenda-mode)
20356 (setq day (get-text-property (point) 'day))
20357 (if day
20358 (setq date (calendar-gregorian-from-absolute day)
20359 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
20360 (nth 2 date))))))
20361 (or defd (current-time))))
20363 (defvar org-agenda-action-marker (make-marker)
20364 "Marker pointing to the entry for the next agenda action.")
20366 (defun org-mark-entry-for-agenda-action ()
20367 "Mark the current entry as target of an agenda action.
20368 Agenda actions are actions executed from the agenda with the key `k',
20369 which make use of the date at the cursor."
20370 (interactive)
20371 (move-marker org-agenda-action-marker
20372 (save-excursion (org-back-to-heading t) (point))
20373 (current-buffer))
20374 (message
20375 "Entry marked for action; press `k' at desired date in agenda or calendar"))
20377 (defun org-mark-subtree ()
20378 "Mark the current subtree.
20379 This puts point at the start of the current subtree, and mark at the end.
20381 If point is in an inline task, mark that task instead."
20382 (interactive)
20383 (let ((inline-task-p
20384 (and (featurep 'org-inlinetask)
20385 (org-inlinetask-in-task-p)))
20386 (beg))
20387 ;; Get beginning of subtree
20388 (cond
20389 (inline-task-p (org-inlinetask-goto-beginning))
20390 ((org-at-heading-p) (beginning-of-line))
20391 (t (org-with-limited-levels (outline-previous-visible-heading 1))))
20392 (setq beg (point))
20393 ;; Get end of it
20394 (if inline-task-p
20395 (org-inlinetask-goto-end)
20396 (org-end-of-subtree))
20397 ;; Mark zone
20398 (push-mark (point) nil t)
20399 (goto-char beg)))
20401 ;;; Paragraph filling stuff.
20402 ;; We want this to be just right, so use the full arsenal.
20404 (defun org-indent-line-function ()
20405 "Indent line depending on context."
20406 (interactive)
20407 (if org-indent-line-fallback-function
20408 (funcall org-indent-line-fallback-function)
20409 (let* ((pos (point))
20410 (itemp (org-at-item-p))
20411 (case-fold-search t)
20412 (org-drawer-regexp (or org-drawer-regexp "\000"))
20413 (inline-task-p (and (featurep 'org-inlinetask)
20414 (org-inlinetask-in-task-p)))
20415 (inline-re (and inline-task-p
20416 (org-inlinetask-outline-regexp)))
20417 column)
20418 (beginning-of-line 1)
20419 (cond
20420 ;; Comments
20421 ((looking-at "# ") (setq column 0))
20422 ;; Headings
20423 ((looking-at org-outline-regexp) (setq column 0))
20424 ;; Included files
20425 ((looking-at "#\\+include:") (setq column 0))
20426 ;; Footnote definition
20427 ((looking-at org-footnote-definition-re) (setq column 0))
20428 ;; Literal examples
20429 ((looking-at "[ \t]*:\\( \\|$\\)")
20430 (setq column (org-get-indentation))) ; do nothing
20431 ;; Lists
20432 ((ignore-errors (goto-char (org-in-item-p)))
20433 (setq column (if itemp
20434 (org-get-indentation)
20435 (org-list-item-body-column (point))))
20436 (goto-char pos))
20437 ;; Drawers
20438 ((and (looking-at "[ \t]*:END:")
20439 (save-excursion (re-search-backward org-drawer-regexp nil t)))
20440 (save-excursion
20441 (goto-char (1- (match-beginning 1)))
20442 (setq column (current-column))))
20443 ;; Special blocks
20444 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
20445 (save-excursion
20446 (re-search-backward
20447 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
20448 (setq column (org-get-indentation (match-string 0))))
20449 ((and (not (looking-at "[ \t]*#\\+begin_"))
20450 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
20451 (save-excursion
20452 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
20453 (setq column
20454 (cond ((equal (downcase (match-string 1)) "src")
20455 ;; src blocks: let `org-edit-src-exit' handle them
20456 (org-get-indentation))
20457 ((equal (downcase (match-string 1)) "example")
20458 (max (org-get-indentation)
20459 (org-get-indentation (match-string 0))))
20461 (org-get-indentation (match-string 0))))))
20462 ;; This line has nothing special, look at the previous relevant
20463 ;; line to compute indentation
20465 (beginning-of-line 0)
20466 (while (and (not (bobp))
20467 (not (looking-at org-drawer-regexp))
20468 ;; When point started in an inline task, do not move
20469 ;; above task starting line.
20470 (not (and inline-task-p (looking-at inline-re)))
20471 ;; Skip drawers, blocks, empty lines, verbatim,
20472 ;; comments, tables, footnotes definitions, lists,
20473 ;; inline tasks.
20474 (or (and (looking-at "[ \t]*:END:")
20475 (re-search-backward org-drawer-regexp nil t))
20476 (and (looking-at "[ \t]*#\\+end_")
20477 (re-search-backward "[ \t]*#\\+begin_"nil t))
20478 (looking-at "[ \t]*[\n:#|]")
20479 (looking-at org-footnote-definition-re)
20480 (and (ignore-errors (goto-char (org-in-item-p)))
20481 (goto-char
20482 (org-list-get-top-point (org-list-struct))))
20483 (and (not inline-task-p)
20484 (featurep 'org-inlinetask)
20485 (org-inlinetask-in-task-p)
20486 (or (org-inlinetask-goto-beginning) t))))
20487 (beginning-of-line 0))
20488 (cond
20489 ;; There was an heading above.
20490 ((looking-at "\\*+[ \t]+")
20491 (if (not org-adapt-indentation)
20492 (setq column 0)
20493 (goto-char (match-end 0))
20494 (setq column (current-column))))
20495 ;; A drawer had started and is unfinished
20496 ((looking-at org-drawer-regexp)
20497 (goto-char (1- (match-beginning 1)))
20498 (setq column (current-column)))
20499 ;; Else, nothing noticeable found: get indentation and go on.
20500 (t (setq column (org-get-indentation))))))
20501 ;; Now apply indentation and move cursor accordingly
20502 (goto-char pos)
20503 (if (<= (current-column) (current-indentation))
20504 (org-indent-line-to column)
20505 (save-excursion (org-indent-line-to column)))
20506 ;; Special polishing for properties, see `org-property-format'
20507 (setq column (current-column))
20508 (beginning-of-line 1)
20509 (if (looking-at
20510 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
20511 (replace-match (concat (match-string 1)
20512 (format org-property-format
20513 (match-string 2) (match-string 3)))
20514 t t))
20515 (org-move-to-column column))))
20517 (defun org-indent-drawer ()
20518 "Indent the drawer at point."
20519 (interactive)
20520 (let ((p (point))
20521 (e (and (save-excursion (re-search-forward ":END:" nil t))
20522 (match-end 0)))
20523 (folded
20524 (save-excursion
20525 (end-of-line)
20526 (when (overlays-at (point))
20527 (member 'invisible (overlay-properties
20528 (car (overlays-at (point)))))))))
20529 (when folded (org-cycle))
20530 (indent-for-tab-command)
20531 (while (and (move-beginning-of-line 2) (< (point) e))
20532 (indent-for-tab-command))
20533 (goto-char p)
20534 (when folded (org-cycle)))
20535 (message "Drawer at point indented"))
20537 (defun org-indent-block ()
20538 "Indent the block at point."
20539 (interactive)
20540 (let ((p (point))
20541 (case-fold-search t)
20542 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
20543 (match-end 0)))
20544 (folded
20545 (save-excursion
20546 (end-of-line)
20547 (when (overlays-at (point))
20548 (member 'invisible (overlay-properties
20549 (car (overlays-at (point)))))))))
20550 (when folded (org-cycle))
20551 (indent-for-tab-command)
20552 (while (and (move-beginning-of-line 2) (< (point) e))
20553 (indent-for-tab-command))
20554 (goto-char p)
20555 (when folded (org-cycle)))
20556 (message "Block at point indented"))
20558 (defvar org-adaptive-fill-regexp-backup adaptive-fill-regexp
20559 "Variable to store copy of `adaptive-fill-regexp'.
20560 Since `adaptive-fill-regexp' is set to never match, we need to
20561 store a backup of its value before entering `org-mode' so that
20562 the functionality can be provided as a fall-back.")
20564 (defun org-set-autofill-regexps ()
20565 (interactive)
20566 ;; In the paragraph separator we include headlines, because filling
20567 ;; text in a line directly attached to a headline would otherwise
20568 ;; fill the headline as well.
20569 (org-set-local 'comment-start-skip "^#+[ \t]*")
20570 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|#]")
20571 ;; The paragraph starter includes hand-formatted lists.
20572 (org-set-local
20573 'paragraph-start
20574 (concat
20575 "\f" "\\|"
20576 "[ ]*$" "\\|"
20577 org-outline-regexp "\\|"
20578 "[ \t]*#" "\\|"
20579 (org-item-re) "\\|"
20580 "[ \t]*[:|]" "\\|"
20581 "\\$\\$" "\\|"
20582 "\\\\\\(begin\\|end\\|[][]\\)"))
20583 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
20584 ;; But only if the user has not turned off tables or fixed-width regions
20585 (org-set-local
20586 'auto-fill-inhibit-regexp
20587 (concat org-outline-regexp
20588 "\\|#\\+"
20589 "\\|[ \t]*" org-keyword-time-regexp
20590 (if (or org-enable-table-editor org-enable-fixed-width-editor)
20591 (concat
20592 "\\|[ \t]*["
20593 (if org-enable-table-editor "|" "")
20594 (if org-enable-fixed-width-editor ":" "")
20595 "]"))))
20596 ;; We use our own fill-paragraph function, to make sure that tables
20597 ;; and fixed-width regions are not wrapped. That function will pass
20598 ;; through to `fill-paragraph' when appropriate.
20599 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
20600 ;; Prevent auto-fill from inserting unwanted new items.
20601 (if (boundp 'fill-nobreak-predicate)
20602 (org-set-local
20603 'fill-nobreak-predicate
20604 (org-uniquify
20605 (append fill-nobreak-predicate
20606 '(org-fill-item-nobreak-p org-fill-line-break-nobreak-p)))))
20607 ;; Adaptive filling: To get full control, first make sure that
20608 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
20609 (unless (local-variable-p 'adaptive-fill-regexp (current-buffer))
20610 (org-set-local 'org-adaptive-fill-regexp-backup
20611 adaptive-fill-regexp))
20612 (org-set-local 'adaptive-fill-regexp "\000")
20613 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
20614 (org-set-local 'adaptive-fill-function
20615 'org-adaptive-fill-function)
20616 (org-set-local
20617 'align-mode-rules-list
20618 '((org-in-buffer-settings
20619 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
20620 (modes . '(org-mode))))))
20622 (defun org-fill-item-nobreak-p ()
20623 "Non-nil when a line break at point would insert a new item."
20624 (and (looking-at (org-item-re)) (org-list-in-valid-context-p)))
20626 (defun org-fill-line-break-nobreak-p ()
20627 "Non-nil when a line break at point would create an Org line break."
20628 (save-excursion
20629 (skip-chars-backward "[ \t]")
20630 (skip-chars-backward "\\\\")
20631 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
20633 (defun org-fill-paragraph (&optional justify)
20634 "Re-align a table, pass through to fill-paragraph if no table."
20635 (let ((table-p (org-at-table-p))
20636 (table.el-p (org-at-table.el-p))
20637 (itemp (org-in-item-p)))
20638 (cond ((and (equal (char-after (point-at-bol)) ?*)
20639 (save-excursion (goto-char (point-at-bol))
20640 (looking-at org-outline-regexp)))
20641 t) ; skip headlines
20642 (table.el-p t) ; skip table.el tables
20643 (table-p (org-table-align) t) ; align Org tables
20644 (itemp ; align text in items
20645 (let* ((struct (save-excursion (goto-char itemp)
20646 (org-list-struct)))
20647 (parents (org-list-parents-alist struct))
20648 (children (org-list-get-children itemp struct parents))
20649 beg end prev next prefix)
20650 ;; Determine in which part of item point is: before
20651 ;; first child, after last child, between two
20652 ;; sub-lists, or simply in item if there's no child.
20653 (cond
20654 ((not children)
20655 (setq prefix (make-string (org-list-item-body-column itemp) ?\ )
20656 beg itemp
20657 end (org-list-get-item-end itemp struct)))
20658 ((< (point) (setq next (car children)))
20659 (setq prefix (make-string (org-list-item-body-column itemp) ?\ )
20660 beg itemp
20661 end next))
20662 ((> (point) (setq prev (car (last children))))
20663 (setq beg (org-list-get-item-end prev struct)
20664 end (org-list-get-item-end itemp struct)
20665 prefix (save-excursion
20666 (goto-char beg)
20667 (skip-chars-forward " \t")
20668 (make-string (current-column) ?\ ))))
20669 (t (catch 'exit
20670 (while (setq next (pop children))
20671 (if (> (point) next)
20672 (setq prev next)
20673 (setq beg (org-list-get-item-end prev struct)
20674 end next
20675 prefix (save-excursion
20676 (goto-char beg)
20677 (skip-chars-forward " \t")
20678 (make-string (current-column) ?\ )))
20679 (throw 'exit nil))))))
20680 ;; Use `fill-paragraph' with buffer narrowed to item
20681 ;; without any child, and with our computed PREFIX.
20682 (flet ((fill-context-prefix (from to &optional flr) prefix))
20683 (save-restriction
20684 (narrow-to-region beg end)
20685 (save-excursion (fill-paragraph justify)))) t))
20686 ;; Special case where point is not in a list but is on
20687 ;; a paragraph adjacent to a list: make sure this paragraph
20688 ;; doesn't get merged with the end of the list by narrowing
20689 ;; buffer first.
20690 ((and (derived-mode-p 'org-mode)
20691 (save-excursion (forward-paragraph -1)
20692 (setq itemp (org-in-item-p))))
20693 (let ((struct (save-excursion (goto-char itemp)
20694 (org-list-struct))))
20695 (save-restriction
20696 (narrow-to-region (org-list-get-bottom-point struct)
20697 (save-excursion (forward-paragraph 1)
20698 (point)))
20699 (fill-paragraph justify) t)))
20700 ;; Don't fill schedule/deadline line before a paragraph
20701 ;; This only makes sense in real org-mode buffers
20702 ((and (eq major-mode 'org-mode)
20703 (save-excursion (forward-paragraph -1)
20704 (or (looking-at (concat "^[^\n]*" org-scheduled-regexp ".*$"))
20705 (looking-at (concat "^[^\n]*" org-deadline-regexp ".*$")))))
20706 (save-restriction
20707 (narrow-to-region (1+ (match-end 0))
20708 (save-excursion (forward-paragraph 1) (point)))
20709 (fill-paragraph justify) t))
20710 ;; Else falls back on `org-fill-paragraph-fallback-function'
20711 (org-fill-paragraph-fallback-function
20712 (funcall org-fill-paragraph-fallback-function justify))
20713 ;; Else simply call `fill-paragraph'.
20714 (t nil))))
20716 ;; For reference, this is the default value of adaptive-fill-regexp
20717 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
20719 (defun org-adaptive-fill-function ()
20720 "Return a fill prefix for org-mode files."
20721 (let (itemp)
20722 (save-excursion
20723 (cond
20724 ;; Comment line
20725 ((looking-at "#[ \t]+")
20726 (match-string-no-properties 0))
20727 ;; Plain list item
20728 ((org-at-item-p)
20729 (make-string (org-list-item-body-column (point-at-bol)) ?\ ))
20730 ;; Point is in a list after `backward-paragraph': original
20731 ;; point wasn't in the list, or filling would have been taken
20732 ;; care of by `org-auto-fill-function', but the list and the
20733 ;; real paragraph are not separated by a blank line. Thus, move
20734 ;; point after the list to go back to real paragraph and
20735 ;; determine fill-prefix.
20736 ((setq itemp (org-in-item-p))
20737 (goto-char itemp)
20738 (let* ((struct (org-list-struct))
20739 (bottom (org-list-get-bottom-point struct)))
20740 (goto-char bottom)
20741 (make-string (org-get-indentation) ?\ )))
20742 ;; Other text
20743 ((looking-at org-adaptive-fill-regexp-backup)
20744 (match-string-no-properties 0))))))
20746 (defun org-auto-fill-function ()
20747 "Auto-fill function."
20748 (let (itemp prefix)
20749 ;; When in a list, compute an appropriate fill-prefix and make
20750 ;; sure it will be used by `do-auto-fill'.
20751 (cond ((setq itemp (org-in-item-p))
20752 (progn
20753 (setq prefix (make-string (org-list-item-body-column itemp) ?\ ))
20754 (flet ((fill-context-prefix (from to &optional flr) prefix))
20755 (do-auto-fill))))
20756 (org-auto-fill-fallback-function
20757 (let ((fill-prefix ""))
20758 (funcall org-auto-fill-fallback-function)))
20759 ;; Else just use `do-auto-fill'.
20760 (t (do-auto-fill)))))
20762 ;;; Other stuff.
20764 (defun org-toggle-fixed-width-section (arg)
20765 "Toggle the fixed-width export.
20766 If there is no active region, the QUOTE keyword at the current headline is
20767 inserted or removed. When present, it causes the text between this headline
20768 and the next to be exported as fixed-width text, and unmodified.
20769 If there is an active region, this command adds or removes a colon as the
20770 first character of this line. If the first character of a line is a colon,
20771 this line is also exported in fixed-width font."
20772 (interactive "P")
20773 (let* ((cc 0)
20774 (regionp (org-region-active-p))
20775 (beg (if regionp (region-beginning) (point)))
20776 (end (if regionp (region-end)))
20777 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
20778 (case-fold-search nil)
20779 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
20780 off)
20781 (if regionp
20782 (save-excursion
20783 (goto-char beg)
20784 (setq cc (current-column))
20785 (beginning-of-line 1)
20786 (setq off (looking-at re))
20787 (while (> nlines 0)
20788 (setq nlines (1- nlines))
20789 (beginning-of-line 1)
20790 (cond
20791 (arg
20792 (org-move-to-column cc t)
20793 (insert ": \n")
20794 (forward-line -1))
20795 ((and off (looking-at re))
20796 (replace-match "" t t nil 1))
20797 ((not off) (org-move-to-column cc t) (insert ": ")))
20798 (forward-line 1)))
20799 (save-excursion
20800 (org-back-to-heading)
20801 (cond
20802 ((looking-at (format org-heading-keyword-regexp-format
20803 org-quote-string))
20804 (goto-char (match-end 1))
20805 (looking-at (concat " +" org-quote-string))
20806 (replace-match "" t t)
20807 (when (eolp) (insert " ")))
20808 ((looking-at org-outline-regexp)
20809 (goto-char (match-end 0))
20810 (insert org-quote-string " ")))))))
20812 (defun org-reftex-citation ()
20813 "Use reftex-citation to insert a citation into the buffer.
20814 This looks for a line like
20816 #+BIBLIOGRAPHY: foo plain option:-d
20818 and derives from it that foo.bib is the bibliography file relevant
20819 for this document. It then installs the necessary environment for RefTeX
20820 to work in this buffer and calls `reftex-citation' to insert a citation
20821 into the buffer.
20823 Export of such citations to both LaTeX and HTML is handled by the contributed
20824 package org-exp-bibtex by Taru Karttunen."
20825 (interactive)
20826 (let ((reftex-docstruct-symbol 'rds)
20827 (reftex-cite-format "\\cite{%l}")
20828 rds bib)
20829 (save-excursion
20830 (save-restriction
20831 (widen)
20832 (let ((case-fold-search t)
20833 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
20834 (if (not (save-excursion
20835 (or (re-search-forward re nil t)
20836 (re-search-backward re nil t))))
20837 (error "No bibliography defined in file")
20838 (setq bib (concat (match-string 1) ".bib")
20839 rds (list (list 'bib bib)))))))
20840 (call-interactively 'reftex-citation)))
20842 ;;;; Functions extending outline functionality
20844 (defun org-beginning-of-line (&optional arg)
20845 "Go to the beginning of the current line. If that is invisible, continue
20846 to a visible line beginning. This makes the function of C-a more intuitive.
20847 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
20848 first attempt, and only move to after the tags when the cursor is already
20849 beyond the end of the headline."
20850 (interactive "P")
20851 (let ((pos (point))
20852 (special (if (consp org-special-ctrl-a/e)
20853 (car org-special-ctrl-a/e)
20854 org-special-ctrl-a/e))
20855 refpos)
20856 (if (org-bound-and-true-p line-move-visual)
20857 (beginning-of-visual-line 1)
20858 (beginning-of-line 1))
20859 (if (and arg (fboundp 'move-beginning-of-line))
20860 (call-interactively 'move-beginning-of-line)
20861 (if (bobp)
20863 (backward-char 1)
20864 (if (org-truely-invisible-p)
20865 (while (and (not (bobp)) (org-truely-invisible-p))
20866 (backward-char 1)
20867 (beginning-of-line 1))
20868 (forward-char 1))))
20869 (when special
20870 (cond
20871 ((and (looking-at org-complex-heading-regexp)
20872 (= (char-after (match-end 1)) ?\ ))
20873 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
20874 (point-at-eol)))
20875 (goto-char
20876 (if (eq special t)
20877 (cond ((> pos refpos) refpos)
20878 ((= pos (point)) refpos)
20879 (t (point)))
20880 (cond ((> pos (point)) (point))
20881 ((not (eq last-command this-command)) (point))
20882 (t refpos)))))
20883 ((org-at-item-p)
20884 ;; Being at an item and not looking at an the item means point
20885 ;; was previously moved to beginning of a visual line, which
20886 ;; doesn't contain the item. Therefore, do nothing special,
20887 ;; just stay here.
20888 (when (looking-at org-list-full-item-re)
20889 ;; Set special position at first white space character after
20890 ;; bullet, and check-box, if any.
20891 (let ((after-bullet
20892 (let ((box (match-end 3)))
20893 (if (not box) (match-end 1)
20894 (let ((after (char-after box)))
20895 (if (and after (= after ? )) (1+ box) box))))))
20896 ;; Special case: Move point to special position when
20897 ;; currently after it or at beginning of line.
20898 (if (eq special t)
20899 (when (or (> pos after-bullet) (= (point) pos))
20900 (goto-char after-bullet))
20901 ;; Reversed case: Move point to special position when
20902 ;; point was already at beginning of line and command is
20903 ;; repeated.
20904 (when (and (= (point) pos) (eq last-command this-command))
20905 (goto-char after-bullet))))))))
20906 (org-no-warnings
20907 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
20909 (defun org-end-of-line (&optional arg)
20910 "Go to the end of the line.
20911 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
20912 first attempt, and only move to after the tags when the cursor is already
20913 beyond the end of the headline."
20914 (interactive "P")
20915 (let ((special (if (consp org-special-ctrl-a/e)
20916 (cdr org-special-ctrl-a/e)
20917 org-special-ctrl-a/e)))
20918 (cond
20919 ((or (not special) arg
20920 (not (or (org-at-heading-p) (org-at-item-p) (org-at-drawer-p))))
20921 (call-interactively
20922 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
20923 ((fboundp 'move-end-of-line) 'move-end-of-line)
20924 (t 'end-of-line))))
20925 ((org-at-heading-p)
20926 (let ((pos (point)))
20927 (beginning-of-line 1)
20928 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
20929 (if (eq special t)
20930 (if (or (< pos (match-beginning 1))
20931 (= pos (match-end 0)))
20932 (goto-char (match-beginning 1))
20933 (goto-char (match-end 0)))
20934 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
20935 (goto-char (match-end 0))
20936 (goto-char (match-beginning 1))))
20937 (call-interactively (if (fboundp 'move-end-of-line)
20938 'move-end-of-line
20939 'end-of-line)))))
20940 ((org-at-drawer-p)
20941 (move-end-of-line 1)
20942 (when (overlays-at (1- (point))) (backward-char 1)))
20943 ;; At an item: Move before any hidden text.
20944 (t (call-interactively
20945 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
20946 ((fboundp 'move-end-of-line) 'move-end-of-line)
20947 (t 'end-of-line)))))
20948 (org-no-warnings
20949 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
20951 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
20952 (define-key org-mode-map "\C-e" 'org-end-of-line)
20954 (defun org-backward-sentence (&optional arg)
20955 "Go to beginning of sentence, or beginning of table field.
20956 This will call `backward-sentence' or `org-table-beginning-of-field',
20957 depending on context."
20958 (interactive "P")
20959 (cond
20960 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
20961 (t (call-interactively 'backward-sentence))))
20963 (defun org-forward-sentence (&optional arg)
20964 "Go to end of sentence, or end of table field.
20965 This will call `forward-sentence' or `org-table-end-of-field',
20966 depending on context."
20967 (interactive "P")
20968 (cond
20969 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
20970 (t (call-interactively 'forward-sentence))))
20972 (define-key org-mode-map "\M-a" 'org-backward-sentence)
20973 (define-key org-mode-map "\M-e" 'org-forward-sentence)
20975 (defun org-kill-line (&optional arg)
20976 "Kill line, to tags or end of line."
20977 (interactive "P")
20978 (cond
20979 ((or (not org-special-ctrl-k)
20980 (bolp)
20981 (not (org-at-heading-p)))
20982 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
20983 org-ctrl-k-protect-subtree)
20984 (if (or (eq org-ctrl-k-protect-subtree 'error)
20985 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
20986 (error "C-k aborted - would kill hidden subtree")))
20987 (call-interactively
20988 (if (and (boundp 'visual-line-mode) visual-line-mode) 'kill-visual-line 'kill-line)))
20989 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
20990 (kill-region (point) (match-beginning 1))
20991 (org-set-tags nil t))
20992 (t (kill-region (point) (point-at-eol)))))
20994 (define-key org-mode-map "\C-k" 'org-kill-line)
20996 (defun org-yank (&optional arg)
20997 "Yank. If the kill is a subtree, treat it specially.
20998 This command will look at the current kill and check if is a single
20999 subtree, or a series of subtrees[1]. If it passes the test, and if the
21000 cursor is at the beginning of a line or after the stars of a currently
21001 empty headline, then the yank is handled specially. How exactly depends
21002 on the value of the following variables, both set by default.
21004 org-yank-folded-subtrees
21005 When set, the subtree(s) will be folded after insertion, but only
21006 if doing so would now swallow text after the yanked text.
21008 org-yank-adjusted-subtrees
21009 When set, the subtree will be promoted or demoted in order to
21010 fit into the local outline tree structure, which means that the level
21011 will be adjusted so that it becomes the smaller one of the two
21012 *visible* surrounding headings.
21014 Any prefix to this command will cause `yank' to be called directly with
21015 no special treatment. In particular, a simple \\[universal-argument] prefix \
21016 will just
21017 plainly yank the text as it is.
21019 \[1] The test checks if the first non-white line is a heading
21020 and if there are no other headings with fewer stars."
21021 (interactive "P")
21022 (org-yank-generic 'yank arg))
21024 (defun org-yank-generic (command arg)
21025 "Perform some yank-like command.
21027 This function implements the behavior described in the `org-yank'
21028 documentation. However, it has been generalized to work for any
21029 interactive command with similar behavior."
21031 ;; pretend to be command COMMAND
21032 (setq this-command command)
21034 (if arg
21035 (call-interactively command)
21037 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
21038 (and (org-kill-is-subtree-p)
21039 (or (bolp)
21040 (and (looking-at "[ \t]*$")
21041 (string-match
21042 "\\`\\*+\\'"
21043 (buffer-substring (point-at-bol) (point)))))))
21044 swallowp)
21045 (cond
21046 ((and subtreep org-yank-folded-subtrees)
21047 (let ((beg (point))
21048 end)
21049 (if (and subtreep org-yank-adjusted-subtrees)
21050 (org-paste-subtree nil nil 'for-yank)
21051 (call-interactively command))
21053 (setq end (point))
21054 (goto-char beg)
21055 (when (and (bolp) subtreep
21056 (not (setq swallowp
21057 (org-yank-folding-would-swallow-text beg end))))
21058 (org-with-limited-levels
21059 (or (looking-at org-outline-regexp)
21060 (re-search-forward org-outline-regexp-bol end t))
21061 (while (and (< (point) end) (looking-at org-outline-regexp))
21062 (hide-subtree)
21063 (org-cycle-show-empty-lines 'folded)
21064 (condition-case nil
21065 (outline-forward-same-level 1)
21066 (error (goto-char end))))))
21067 (when swallowp
21068 (message
21069 "Inserted text not folded because that would swallow text"))
21071 (goto-char end)
21072 (skip-chars-forward " \t\n\r")
21073 (beginning-of-line 1)
21074 (push-mark beg 'nomsg)))
21075 ((and subtreep org-yank-adjusted-subtrees)
21076 (let ((beg (point-at-bol)))
21077 (org-paste-subtree nil nil 'for-yank)
21078 (push-mark beg 'nomsg)))
21080 (call-interactively command))))))
21082 (defun org-yank-folding-would-swallow-text (beg end)
21083 "Would hide-subtree at BEG swallow any text after END?"
21084 (let (level)
21085 (org-with-limited-levels
21086 (save-excursion
21087 (goto-char beg)
21088 (when (or (looking-at org-outline-regexp)
21089 (re-search-forward org-outline-regexp-bol end t))
21090 (setq level (org-outline-level)))
21091 (goto-char end)
21092 (skip-chars-forward " \t\r\n\v\f")
21093 (if (or (eobp)
21094 (and (bolp) (looking-at org-outline-regexp)
21095 (<= (org-outline-level) level)))
21096 nil ; Nothing would be swallowed
21097 t))))) ; something would swallow
21099 (define-key org-mode-map "\C-y" 'org-yank)
21101 (defun org-truely-invisible-p ()
21102 "Check if point is at a character currently not visible.
21103 This version does not only check the character property, but also
21104 `visible-mode'."
21105 ;; Early versions of noutline don't have `outline-invisible-p'.
21106 (if (org-bound-and-true-p visible-mode)
21108 (outline-invisible-p)))
21110 (defun org-invisible-p2 ()
21111 "Check if point is at a character currently not visible."
21112 (save-excursion
21113 (if (and (eolp) (not (bobp))) (backward-char 1))
21114 ;; Early versions of noutline don't have `outline-invisible-p'.
21115 (outline-invisible-p)))
21117 (defun org-back-to-heading (&optional invisible-ok)
21118 "Call `outline-back-to-heading', but provide a better error message."
21119 (condition-case nil
21120 (outline-back-to-heading invisible-ok)
21121 (error (error "Before first headline at position %d in buffer %s"
21122 (point) (current-buffer)))))
21124 (defun org-beginning-of-defun ()
21125 "Go to the beginning of the subtree, i.e. back to the heading."
21126 (org-back-to-heading))
21127 (defun org-end-of-defun ()
21128 "Go to the end of the subtree."
21129 (org-end-of-subtree nil t))
21131 (defun org-before-first-heading-p ()
21132 "Before first heading?"
21133 (save-excursion
21134 (end-of-line)
21135 (null (re-search-backward org-outline-regexp-bol nil t))))
21137 (defun org-at-heading-p (&optional ignored)
21138 (outline-on-heading-p t))
21139 ;; Compatibility alias with Org versions < 7.8.03
21140 (defalias 'org-on-heading-p 'org-at-heading-p)
21142 (defun org-at-drawer-p nil
21143 "Is cursor at a drawer keyword?"
21144 (save-excursion
21145 (move-beginning-of-line 1)
21146 (looking-at org-drawer-regexp)))
21148 (defun org-at-block-p nil
21149 "Is cursor at a block keyword?"
21150 (save-excursion
21151 (move-beginning-of-line 1)
21152 (looking-at org-block-regexp)))
21154 (defun org-point-at-end-of-empty-headline ()
21155 "If point is at the end of an empty headline, return t, else nil.
21156 If the heading only contains a TODO keyword, it is still still considered
21157 empty."
21158 (and (looking-at "[ \t]*$")
21159 (when org-todo-line-regexp
21160 (save-excursion
21161 (beginning-of-line 1)
21162 (let ((case-fold-search nil))
21163 (looking-at org-todo-line-regexp)
21164 (string= (match-string 3) ""))))))
21166 (defun org-at-heading-or-item-p ()
21167 (or (org-at-heading-p) (org-at-item-p)))
21169 (defun org-at-target-p ()
21170 (or (org-in-regexp org-radio-target-regexp)
21171 (org-in-regexp org-target-regexp)))
21172 ;; Compatibility alias with Org versions < 7.8.03
21173 (defalias 'org-on-target-p 'org-at-target-p)
21175 (defun org-up-heading-all (arg)
21176 "Move to the heading line of which the present line is a subheading.
21177 This function considers both visible and invisible heading lines.
21178 With argument, move up ARG levels."
21179 (if (fboundp 'outline-up-heading-all)
21180 (outline-up-heading-all arg) ; emacs 21 version of outline.el
21181 (outline-up-heading arg t))) ; emacs 22 version of outline.el
21183 (defun org-up-heading-safe ()
21184 "Move to the heading line of which the present line is a subheading.
21185 This version will not throw an error. It will return the level of the
21186 headline found, or nil if no higher level is found.
21188 Also, this function will be a lot faster than `outline-up-heading',
21189 because it relies on stars being the outline starters. This can really
21190 make a significant difference in outlines with very many siblings."
21191 (let (start-level re)
21192 (org-back-to-heading t)
21193 (setq start-level (funcall outline-level))
21194 (if (equal start-level 1)
21196 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
21197 (if (re-search-backward re nil t)
21198 (funcall outline-level)))))
21200 (defun org-first-sibling-p ()
21201 "Is this heading the first child of its parents?"
21202 (interactive)
21203 (let ((re org-outline-regexp-bol)
21204 level l)
21205 (unless (org-at-heading-p t)
21206 (error "Not at a heading"))
21207 (setq level (funcall outline-level))
21208 (save-excursion
21209 (if (not (re-search-backward re nil t))
21211 (setq l (funcall outline-level))
21212 (< l level)))))
21214 (defun org-goto-sibling (&optional previous)
21215 "Goto the next sibling, even if it is invisible.
21216 When PREVIOUS is set, go to the previous sibling instead. Returns t
21217 when a sibling was found. When none is found, return nil and don't
21218 move point."
21219 (let ((fun (if previous 're-search-backward 're-search-forward))
21220 (pos (point))
21221 (re org-outline-regexp-bol)
21222 level l)
21223 (when (condition-case nil (org-back-to-heading t) (error nil))
21224 (setq level (funcall outline-level))
21225 (catch 'exit
21226 (or previous (forward-char 1))
21227 (while (funcall fun re nil t)
21228 (setq l (funcall outline-level))
21229 (when (< l level) (goto-char pos) (throw 'exit nil))
21230 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
21231 (goto-char pos)
21232 nil))))
21234 (defun org-show-siblings ()
21235 "Show all siblings of the current headline."
21236 (save-excursion
21237 (while (org-goto-sibling) (org-flag-heading nil)))
21238 (save-excursion
21239 (while (org-goto-sibling 'previous)
21240 (org-flag-heading nil))))
21242 (defun org-goto-first-child ()
21243 "Goto the first child, even if it is invisible.
21244 Return t when a child was found. Otherwise don't move point and
21245 return nil."
21246 (let (level (pos (point)) (re org-outline-regexp-bol))
21247 (when (condition-case nil (org-back-to-heading t) (error nil))
21248 (setq level (outline-level))
21249 (forward-char 1)
21250 (if (and (re-search-forward re nil t) (> (outline-level) level))
21251 (progn (goto-char (match-beginning 0)) t)
21252 (goto-char pos) nil))))
21254 (defun org-show-hidden-entry ()
21255 "Show an entry where even the heading is hidden."
21256 (save-excursion
21257 (org-show-entry)))
21259 (defun org-flag-heading (flag &optional entry)
21260 "Flag the current heading. FLAG non-nil means make invisible.
21261 When ENTRY is non-nil, show the entire entry."
21262 (save-excursion
21263 (org-back-to-heading t)
21264 ;; Check if we should show the entire entry
21265 (if entry
21266 (progn
21267 (org-show-entry)
21268 (save-excursion
21269 (and (outline-next-heading)
21270 (org-flag-heading nil))))
21271 (outline-flag-region (max (point-min) (1- (point)))
21272 (save-excursion (outline-end-of-heading) (point))
21273 flag))))
21275 (defun org-get-next-sibling ()
21276 "Move to next heading of the same level, and return point.
21277 If there is no such heading, return nil.
21278 This is like outline-next-sibling, but invisible headings are ok."
21279 (let ((level (funcall outline-level)))
21280 (outline-next-heading)
21281 (while (and (not (eobp)) (> (funcall outline-level) level))
21282 (outline-next-heading))
21283 (if (or (eobp) (< (funcall outline-level) level))
21285 (point))))
21287 (defun org-get-last-sibling ()
21288 "Move to previous heading of the same level, and return point.
21289 If there is no such heading, return nil."
21290 (let ((opoint (point))
21291 (level (funcall outline-level)))
21292 (outline-previous-heading)
21293 (when (and (/= (point) opoint) (outline-on-heading-p t))
21294 (while (and (> (funcall outline-level) level)
21295 (not (bobp)))
21296 (outline-previous-heading))
21297 (if (< (funcall outline-level) level)
21299 (point)))))
21301 (defun org-end-of-subtree (&optional invisible-OK to-heading)
21302 ;; This contains an exact copy of the original function, but it uses
21303 ;; `org-back-to-heading', to make it work also in invisible
21304 ;; trees. And is uses an invisible-OK argument.
21305 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
21306 ;; Furthermore, when used inside Org, finding the end of a large subtree
21307 ;; with many children and grandchildren etc, this can be much faster
21308 ;; than the outline version.
21309 (org-back-to-heading invisible-OK)
21310 (let ((first t)
21311 (level (funcall outline-level)))
21312 (if (and (derived-mode-p 'org-mode) (< level 1000))
21313 ;; A true heading (not a plain list item), in Org-mode
21314 ;; This means we can easily find the end by looking
21315 ;; only for the right number of stars. Using a regexp to do
21316 ;; this is so much faster than using a Lisp loop.
21317 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
21318 (forward-char 1)
21319 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
21320 ;; something else, do it the slow way
21321 (while (and (not (eobp))
21322 (or first (> (funcall outline-level) level)))
21323 (setq first nil)
21324 (outline-next-heading)))
21325 (unless to-heading
21326 (if (memq (preceding-char) '(?\n ?\^M))
21327 (progn
21328 ;; Go to end of line before heading
21329 (forward-char -1)
21330 (if (memq (preceding-char) '(?\n ?\^M))
21331 ;; leave blank line before heading
21332 (forward-char -1))))))
21333 (point))
21335 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
21336 "Use Org version in org-mode, for dramatic speed-up."
21337 (if (derived-mode-p 'org-mode)
21338 (progn
21339 (org-end-of-subtree nil t)
21340 (unless (eobp) (backward-char 1)))
21341 ad-do-it))
21343 (defun org-end-of-meta-data-and-drawers ()
21344 "Jump to the first text after meta data and drawers in the current entry.
21345 This will move over empty lines, lines with planning time stamps,
21346 clocking lines, and drawers."
21347 (org-back-to-heading t)
21348 (let ((end (save-excursion (outline-next-heading) (point)))
21349 (re (concat "\\(" org-drawer-regexp "\\)"
21350 "\\|" "[ \t]*" org-keyword-time-regexp)))
21351 (forward-line 1)
21352 (while (re-search-forward re end t)
21353 (if (not (match-end 1))
21354 ;; empty or planning line
21355 (forward-line 1)
21356 ;; a drawer, find the end
21357 (re-search-forward "^[ \t]*:END:" end 'move)
21358 (forward-line 1)))
21359 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
21360 (point)))
21362 (defun org-forward-same-level (arg &optional invisible-ok)
21363 "Move forward to the arg'th subheading at same level as this one.
21364 Stop at the first and last subheadings of a superior heading.
21365 Normally this only looks at visible headings, but when INVISIBLE-OK is non-nil
21366 it wil also look at invisible ones."
21367 (interactive "p")
21368 (org-back-to-heading invisible-ok)
21369 (org-at-heading-p)
21370 (let* ((level (- (match-end 0) (match-beginning 0) 1))
21371 (re (format "^\\*\\{1,%d\\} " level))
21373 (forward-char 1)
21374 (while (> arg 0)
21375 (while (and (re-search-forward re nil 'move)
21376 (setq l (- (match-end 0) (match-beginning 0) 1))
21377 (= l level)
21378 (not invisible-ok)
21379 (progn (backward-char 1) (outline-invisible-p)))
21380 (if (< l level) (setq arg 1)))
21381 (setq arg (1- arg)))
21382 (beginning-of-line 1)))
21384 (defun org-backward-same-level (arg &optional invisible-ok)
21385 "Move backward to the arg'th subheading at same level as this one.
21386 Stop at the first and last subheadings of a superior heading."
21387 (interactive "p")
21388 (org-back-to-heading)
21389 (org-at-heading-p)
21390 (let* ((level (- (match-end 0) (match-beginning 0) 1))
21391 (re (format "^\\*\\{1,%d\\} " level))
21393 (while (> arg 0)
21394 (while (and (re-search-backward re nil 'move)
21395 (setq l (- (match-end 0) (match-beginning 0) 1))
21396 (= l level)
21397 (not invisible-ok)
21398 (outline-invisible-p))
21399 (if (< l level) (setq arg 1)))
21400 (setq arg (1- arg)))))
21402 (defun org-show-subtree ()
21403 "Show everything after this heading at deeper levels."
21404 (interactive)
21405 (outline-flag-region
21406 (point)
21407 (save-excursion
21408 (org-end-of-subtree t t))
21409 nil))
21411 (defun org-show-entry ()
21412 "Show the body directly following this heading.
21413 Show the heading too, if it is currently invisible."
21414 (interactive)
21415 (save-excursion
21416 (condition-case nil
21417 (progn
21418 (org-back-to-heading t)
21419 (outline-flag-region
21420 (max (point-min) (1- (point)))
21421 (save-excursion
21422 (if (re-search-forward
21423 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
21424 (match-beginning 1)
21425 (point-max)))
21426 nil)
21427 (org-cycle-hide-drawers 'children))
21428 (error nil))))
21430 (defun org-make-options-regexp (kwds &optional extra)
21431 "Make a regular expression for keyword lines."
21432 (concat
21434 "#?[ \t]*\\+\\("
21435 (mapconcat 'regexp-quote kwds "\\|")
21436 (if extra (concat "\\|" extra))
21437 "\\):[ \t]*"
21438 "\\(.*\\)"))
21440 ;; Make isearch reveal the necessary context
21441 (defun org-isearch-end ()
21442 "Reveal context after isearch exits."
21443 (when isearch-success ; only if search was successful
21444 (if (featurep 'xemacs)
21445 ;; Under XEmacs, the hook is run in the correct place,
21446 ;; we directly show the context.
21447 (org-show-context 'isearch)
21448 ;; In Emacs the hook runs *before* restoring the overlays.
21449 ;; So we have to use a one-time post-command-hook to do this.
21450 ;; (Emacs 22 has a special variable, see function `org-mode')
21451 (unless (and (boundp 'isearch-mode-end-hook-quit)
21452 isearch-mode-end-hook-quit)
21453 ;; Only when the isearch was not quitted.
21454 (org-add-hook 'post-command-hook 'org-isearch-post-command
21455 'append 'local)))))
21457 (defun org-isearch-post-command ()
21458 "Remove self from hook, and show context."
21459 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
21460 (org-show-context 'isearch))
21463 ;;;; Integration with and fixes for other packages
21465 ;;; Imenu support
21467 (defvar org-imenu-markers nil
21468 "All markers currently used by Imenu.")
21469 (make-variable-buffer-local 'org-imenu-markers)
21471 (defun org-imenu-new-marker (&optional pos)
21472 "Return a new marker for use by Imenu, and remember the marker."
21473 (let ((m (make-marker)))
21474 (move-marker m (or pos (point)))
21475 (push m org-imenu-markers)
21478 (defun org-imenu-get-tree ()
21479 "Produce the index for Imenu."
21480 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
21481 (setq org-imenu-markers nil)
21482 (let* ((n org-imenu-depth)
21483 (re (concat "^" (org-get-limited-outline-regexp)))
21484 (subs (make-vector (1+ n) nil))
21485 (last-level 0)
21486 m level head)
21487 (save-excursion
21488 (save-restriction
21489 (widen)
21490 (goto-char (point-max))
21491 (while (re-search-backward re nil t)
21492 (setq level (org-reduced-level (funcall outline-level)))
21493 (when (and (<= level n)
21494 (looking-at org-complex-heading-regexp))
21495 (setq head (org-link-display-format
21496 (org-match-string-no-properties 4))
21497 m (org-imenu-new-marker))
21498 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
21499 (if (>= level last-level)
21500 (push (cons head m) (aref subs level))
21501 (push (cons head (aref subs (1+ level))) (aref subs level))
21502 (loop for i from (1+ level) to n do (aset subs i nil)))
21503 (setq last-level level)))))
21504 (aref subs 1)))
21506 (eval-after-load "imenu"
21507 '(progn
21508 (add-hook 'imenu-after-jump-hook
21509 (lambda ()
21510 (if (derived-mode-p 'org-mode)
21511 (org-show-context 'org-goto))))))
21513 (defun org-link-display-format (link)
21514 "Replace a link with either the description, or the link target
21515 if no description is present"
21516 (save-match-data
21517 (if (string-match org-bracket-link-analytic-regexp link)
21518 (replace-match (if (match-end 5)
21519 (match-string 5 link)
21520 (concat (match-string 1 link)
21521 (match-string 3 link)))
21522 nil t link)
21523 link)))
21525 (defun org-toggle-link-display ()
21526 "Toggle the literal or descriptive display of links."
21527 (interactive)
21528 (if org-descriptive-links
21529 (progn (org-remove-from-invisibility-spec '(org-link))
21530 (org-restart-font-lock)
21531 (setq org-descriptive-links nil))
21532 (progn (add-to-invisibility-spec '(org-link))
21533 (org-restart-font-lock)
21534 (setq org-descriptive-links t))))
21536 ;; Speedbar support
21538 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
21539 "Overlay marking the agenda restriction line in speedbar.")
21540 (overlay-put org-speedbar-restriction-lock-overlay
21541 'face 'org-agenda-restriction-lock)
21542 (overlay-put org-speedbar-restriction-lock-overlay
21543 'help-echo "Agendas are currently limited to this item.")
21544 (org-detach-overlay org-speedbar-restriction-lock-overlay)
21546 (defun org-speedbar-set-agenda-restriction ()
21547 "Restrict future agenda commands to the location at point in speedbar.
21548 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
21549 (interactive)
21550 (require 'org-agenda)
21551 (let (p m tp np dir txt)
21552 (cond
21553 ((setq p (text-property-any (point-at-bol) (point-at-eol)
21554 'org-imenu t))
21555 (setq m (get-text-property p 'org-imenu-marker))
21556 (with-current-buffer (marker-buffer m)
21557 (goto-char m)
21558 (org-agenda-set-restriction-lock 'subtree)))
21559 ((setq p (text-property-any (point-at-bol) (point-at-eol)
21560 'speedbar-function 'speedbar-find-file))
21561 (setq tp (previous-single-property-change
21562 (1+ p) 'speedbar-function)
21563 np (next-single-property-change
21564 tp 'speedbar-function)
21565 dir (speedbar-line-directory)
21566 txt (buffer-substring-no-properties (or tp (point-min))
21567 (or np (point-max))))
21568 (with-current-buffer (find-file-noselect
21569 (let ((default-directory dir))
21570 (expand-file-name txt)))
21571 (unless (derived-mode-p 'org-mode)
21572 (error "Cannot restrict to non-Org-mode file"))
21573 (org-agenda-set-restriction-lock 'file)))
21574 (t (error "Don't know how to restrict Org-mode's agenda")))
21575 (move-overlay org-speedbar-restriction-lock-overlay
21576 (point-at-bol) (point-at-eol))
21577 (setq current-prefix-arg nil)
21578 (org-agenda-maybe-redo)))
21580 (eval-after-load "speedbar"
21581 '(progn
21582 (speedbar-add-supported-extension ".org")
21583 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
21584 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
21585 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
21586 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
21587 (add-hook 'speedbar-visiting-tag-hook
21588 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
21590 ;;; Fixes and Hacks for problems with other packages
21592 ;; Make flyspell not check words in links, to not mess up our keymap
21593 (defun org-mode-flyspell-verify ()
21594 "Don't let flyspell put overlays at active buttons, or on
21595 {todo,all-time,additional-option-like}-keywords."
21596 (let ((pos (max (1- (point)) (point-min)))
21597 (word (thing-at-point 'word)))
21598 (and (not (get-text-property pos 'keymap))
21599 (not (get-text-property pos 'org-no-flyspell))
21600 (not (member word org-todo-keywords-1))
21601 (not (member word org-all-time-keywords))
21602 (not (member word org-additional-option-like-keywords)))))
21604 (defun org-remove-flyspell-overlays-in (beg end)
21605 "Remove flyspell overlays in region."
21606 (and (org-bound-and-true-p flyspell-mode)
21607 (fboundp 'flyspell-delete-region-overlays)
21608 (flyspell-delete-region-overlays beg end))
21609 (add-text-properties beg end '(org-no-flyspell t)))
21611 ;; Make `bookmark-jump' shows the jump location if it was hidden.
21612 (eval-after-load "bookmark"
21613 '(if (boundp 'bookmark-after-jump-hook)
21614 ;; We can use the hook
21615 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
21616 ;; Hook not available, use advice
21617 (defadvice bookmark-jump (after org-make-visible activate)
21618 "Make the position visible."
21619 (org-bookmark-jump-unhide))))
21621 ;; Make sure saveplace shows the location if it was hidden
21622 (eval-after-load "saveplace"
21623 '(defadvice save-place-find-file-hook (after org-make-visible activate)
21624 "Make the position visible."
21625 (org-bookmark-jump-unhide)))
21627 ;; Make sure ecb shows the location if it was hidden
21628 (eval-after-load "ecb"
21629 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
21630 "Make hierarchy visible when jumping into location from ECB tree buffer."
21631 (if (derived-mode-p 'org-mode)
21632 (org-show-context))))
21634 (defun org-bookmark-jump-unhide ()
21635 "Unhide the current position, to show the bookmark location."
21636 (and (derived-mode-p 'org-mode)
21637 (or (outline-invisible-p)
21638 (save-excursion (goto-char (max (point-min) (1- (point))))
21639 (outline-invisible-p)))
21640 (org-show-context 'bookmark-jump)))
21642 ;; Make session.el ignore our circular variable
21643 (eval-after-load "session"
21644 '(add-to-list 'session-globals-exclude 'org-mark-ring))
21646 ;;;; Experimental code
21648 (defun org-closed-in-range ()
21649 "Sparse tree of items closed in a certain time range.
21650 Still experimental, may disappear in the future."
21651 (interactive)
21652 ;; Get the time interval from the user.
21653 (let* ((time1 (org-float-time
21654 (org-read-date nil 'to-time nil "Starting date: ")))
21655 (time2 (org-float-time
21656 (org-read-date nil 'to-time nil "End date:")))
21657 ;; callback function
21658 (callback (lambda ()
21659 (let ((time
21660 (org-float-time
21661 (apply 'encode-time
21662 (org-parse-time-string
21663 (match-string 1))))))
21664 ;; check if time in interval
21665 (and (>= time time1) (<= time time2))))))
21666 ;; make tree, check each match with the callback
21667 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
21669 ;;;; Finish up
21671 (provide 'org)
21673 (run-hooks 'org-load-hook)
21675 ;;; org.el ends here