Fix bugs about computing durations in the column view.
[org-mode/org-mode-NeilSmithlineMods.git] / lisp / org.el
blob8776664041ec3a34e703584f97dbe9a6dd787b69
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)
4947 ;;;###autoload
4948 (define-derived-mode org-mode outline-mode "Org"
4949 "Outline-based notes management and organizer, alias
4950 \"Carsten's outline-mode for keeping track of everything.\"
4952 Org-mode develops organizational tasks around a NOTES file which
4953 contains information about projects as plain text. Org-mode is
4954 implemented on top of outline-mode, which is ideal to keep the content
4955 of large files well structured. It supports ToDo items, deadlines and
4956 time stamps, which magically appear in the diary listing of the Emacs
4957 calendar. Tables are easily created with a built-in table editor.
4958 Plain text URL-like links connect to websites, emails (VM), Usenet
4959 messages (Gnus), BBDB entries, and any files related to the project.
4960 For printing and sharing of notes, an Org-mode file (or a part of it)
4961 can be exported as a structured ASCII or HTML file.
4963 The following commands are available:
4965 \\{org-mode-map}"
4967 ;; Get rid of Outline menus, they are not needed
4968 ;; Need to do this here because define-derived-mode sets up
4969 ;; the keymap so late. Still, it is a waste to call this each time
4970 ;; we switch another buffer into org-mode.
4971 (if (featurep 'xemacs)
4972 (when (boundp 'outline-mode-menu-heading)
4973 ;; Assume this is Greg's port, it uses easymenu
4974 (easy-menu-remove outline-mode-menu-heading)
4975 (easy-menu-remove outline-mode-menu-show)
4976 (easy-menu-remove outline-mode-menu-hide))
4977 (define-key org-mode-map [menu-bar headings] 'undefined)
4978 (define-key org-mode-map [menu-bar hide] 'undefined)
4979 (define-key org-mode-map [menu-bar show] 'undefined))
4981 (org-load-modules-maybe)
4982 (easy-menu-add org-org-menu)
4983 (easy-menu-add org-tbl-menu)
4984 (org-install-agenda-files-menu)
4985 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
4986 (add-to-invisibility-spec '(org-cwidth))
4987 (add-to-invisibility-spec '(org-hide-block . t))
4988 (when (featurep 'xemacs)
4989 (org-set-local 'line-move-ignore-invisible t))
4990 (org-set-local 'outline-regexp org-outline-regexp)
4991 (org-set-local 'outline-level 'org-outline-level)
4992 (setq bidi-paragraph-direction 'left-to-right)
4993 (when (and org-ellipsis
4994 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
4995 (fboundp 'make-glyph-code))
4996 (unless org-display-table
4997 (setq org-display-table (make-display-table)))
4998 (set-display-table-slot
4999 org-display-table 4
5000 (vconcat (mapcar
5001 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5002 org-ellipsis)))
5003 (if (stringp org-ellipsis) org-ellipsis "..."))))
5004 (setq buffer-display-table org-display-table))
5005 (org-set-regexps-and-options)
5006 (when (and org-tag-faces (not org-tags-special-faces-re))
5007 ;; tag faces set outside customize.... force initialization.
5008 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5009 ;; Calc embedded
5010 (org-set-local 'calc-embedded-open-mode "# ")
5011 (modify-syntax-entry ?@ "w")
5012 (if org-startup-truncated (setq truncate-lines t))
5013 (org-set-local 'font-lock-unfontify-region-function
5014 'org-unfontify-region)
5015 ;; Activate before-change-function
5016 (org-set-local 'org-table-may-need-update t)
5017 (org-add-hook 'before-change-functions 'org-before-change-function nil
5018 'local)
5019 ;; Check for running clock before killing a buffer
5020 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5021 ;; Paragraphs and auto-filling
5022 (org-set-autofill-regexps)
5023 (setq indent-line-function 'org-indent-line-function)
5024 (org-update-radio-target-regexp)
5025 ;; Beginning/end of defun
5026 (org-set-local 'beginning-of-defun-function 'org-beginning-of-defun)
5027 (org-set-local 'end-of-defun-function 'org-end-of-defun)
5028 ;; Next error for sparse trees
5029 (org-set-local 'next-error-function 'org-occur-next-match)
5030 ;; Make sure dependence stuff works reliably, even for users who set it
5031 ;; too late :-(
5032 (if org-enforce-todo-dependencies
5033 (add-hook 'org-blocker-hook
5034 'org-block-todo-from-children-or-siblings-or-parent)
5035 (remove-hook 'org-blocker-hook
5036 'org-block-todo-from-children-or-siblings-or-parent))
5037 (if org-enforce-todo-checkbox-dependencies
5038 (add-hook 'org-blocker-hook
5039 'org-block-todo-from-checkboxes)
5040 (remove-hook 'org-blocker-hook
5041 'org-block-todo-from-checkboxes))
5043 ;; Comment characters
5044 (org-set-local 'comment-start "#")
5045 (org-set-local 'comment-padding " ")
5047 ;; Align options lines
5048 (org-set-local
5049 'align-mode-rules-list
5050 '((org-in-buffer-settings
5051 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5052 (modes . '(org-mode)))))
5054 ;; Imenu
5055 (org-set-local 'imenu-create-index-function
5056 'org-imenu-get-tree)
5058 ;; Make isearch reveal context
5059 (if (or (featurep 'xemacs)
5060 (not (boundp 'outline-isearch-open-invisible-function)))
5061 ;; Emacs 21 and XEmacs make use of the hook
5062 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5063 ;; Emacs 22 deals with this through a special variable
5064 (org-set-local 'outline-isearch-open-invisible-function
5065 (lambda (&rest ignore) (org-show-context 'isearch))))
5067 ;; Turn on org-beamer-mode?
5068 (and org-startup-with-beamer-mode (org-beamer-mode 1))
5070 ;; Setup the pcomplete hooks
5071 (set (make-local-variable 'pcomplete-command-completion-function)
5072 'org-pcomplete-initial)
5073 (set (make-local-variable 'pcomplete-command-name-function)
5074 'org-command-at-point)
5075 (set (make-local-variable 'pcomplete-default-completion-function)
5076 'ignore)
5077 (set (make-local-variable 'pcomplete-parse-arguments-function)
5078 'org-parse-arguments)
5079 (set (make-local-variable 'pcomplete-termination-string) "")
5080 (when (>= emacs-major-version 23)
5081 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5083 ;; If empty file that did not turn on org-mode automatically, make it to.
5084 (if (and org-insert-mode-line-in-empty-file
5085 (org-called-interactively-p 'any)
5086 (= (point-min) (point-max)))
5087 (insert "# -*- mode: org -*-\n\n"))
5088 (unless org-inhibit-startup
5089 (when org-startup-align-all-tables
5090 (let ((bmp (buffer-modified-p)))
5091 (org-table-map-tables 'org-table-align 'quietly)
5092 (set-buffer-modified-p bmp)))
5093 (when org-startup-with-inline-images
5094 (org-display-inline-images))
5095 (when org-startup-indented
5096 (require 'org-indent)
5097 (org-indent-mode 1))
5098 (unless org-inhibit-startup-visibility-stuff
5099 (org-set-startup-visibility))))
5101 (when (fboundp 'abbrev-table-put)
5102 (abbrev-table-put org-mode-abbrev-table
5103 :parents (list text-mode-abbrev-table)))
5105 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5107 (defun org-current-time ()
5108 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
5109 (if (> (car org-time-stamp-rounding-minutes) 1)
5110 (let ((r (car org-time-stamp-rounding-minutes))
5111 (time (decode-time)))
5112 (apply 'encode-time
5113 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5114 (nthcdr 2 time))))
5115 (current-time)))
5117 (defun org-today ()
5118 "Return today date, considering `org-extend-today-until'."
5119 (time-to-days
5120 (time-subtract (current-time)
5121 (list 0 (* 3600 org-extend-today-until) 0))))
5123 ;;;; Font-Lock stuff, including the activators
5125 (defvar org-mouse-map (make-sparse-keymap))
5126 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5127 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5128 (when org-mouse-1-follows-link
5129 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5130 (when org-tab-follows-link
5131 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5132 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5134 (require 'font-lock)
5136 (defconst org-non-link-chars "]\t\n\r<>")
5137 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5138 "shell" "elisp" "doi" "message"))
5139 (defvar org-link-types-re nil
5140 "Matches a link that has a url-like prefix like \"http:\"")
5141 (defvar org-link-re-with-space nil
5142 "Matches a link with spaces, optional angular brackets around it.")
5143 (defvar org-link-re-with-space2 nil
5144 "Matches a link with spaces, optional angular brackets around it.")
5145 (defvar org-link-re-with-space3 nil
5146 "Matches a link with spaces, only for internal part in bracket links.")
5147 (defvar org-angle-link-re nil
5148 "Matches link with angular brackets, spaces are allowed.")
5149 (defvar org-plain-link-re nil
5150 "Matches plain link, without spaces.")
5151 (defvar org-bracket-link-regexp nil
5152 "Matches a link in double brackets.")
5153 (defvar org-bracket-link-analytic-regexp nil
5154 "Regular expression used to analyze links.
5155 Here is what the match groups contain after a match:
5156 1: http:
5157 2: http
5158 3: path
5159 4: [desc]
5160 5: desc")
5161 (defvar org-bracket-link-analytic-regexp++ nil
5162 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5163 (defvar org-any-link-re nil
5164 "Regular expression matching any link.")
5166 (defcustom org-match-sexp-depth 3
5167 "Number of stacked braces for sub/superscript matching.
5168 This has to be set before loading org.el to be effective."
5169 :group 'org-export-translation ; ??????????????????????????/
5170 :type 'integer)
5172 (defun org-create-multibrace-regexp (left right n)
5173 "Create a regular expression which will match a balanced sexp.
5174 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5175 as single character strings.
5176 The regexp returned will match the entire expression including the
5177 delimiters. It will also define a single group which contains the
5178 match except for the outermost delimiters. The maximum depth of
5179 stacked delimiters is N. Escaping delimiters is not possible."
5180 (let* ((nothing (concat "[^" left right "]*?"))
5181 (or "\\|")
5182 (re nothing)
5183 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5184 (while (> n 1)
5185 (setq n (1- n)
5186 re (concat re or next)
5187 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5188 (concat left "\\(" re "\\)" right)))
5190 (defvar org-match-substring-regexp
5191 (concat
5192 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5193 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5194 "\\|"
5195 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5196 "\\|"
5197 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5198 "The regular expression matching a sub- or superscript.")
5200 (defvar org-match-substring-with-braces-regexp
5201 (concat
5202 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5203 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5204 "\\)")
5205 "The regular expression matching a sub- or superscript, forcing braces.")
5207 (defun org-make-link-regexps ()
5208 "Update the link regular expressions.
5209 This should be called after the variable `org-link-types' has changed."
5210 (setq org-link-types-re
5211 (concat
5212 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5213 org-link-re-with-space
5214 (concat
5215 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5216 "\\([^" org-non-link-chars " ]"
5217 "[^" org-non-link-chars "]*"
5218 "[^" org-non-link-chars " ]\\)>?")
5219 org-link-re-with-space2
5220 (concat
5221 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5222 "\\([^" org-non-link-chars " ]"
5223 "[^\t\n\r]*"
5224 "[^" org-non-link-chars " ]\\)>?")
5225 org-link-re-with-space3
5226 (concat
5227 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5228 "\\([^" org-non-link-chars " ]"
5229 "[^\t\n\r]*\\)")
5230 org-angle-link-re
5231 (concat
5232 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5233 "\\([^" org-non-link-chars " ]"
5234 "[^" org-non-link-chars "]*"
5235 "\\)>")
5236 org-plain-link-re
5237 (concat
5238 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5239 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5240 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5241 org-bracket-link-regexp
5242 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5243 org-bracket-link-analytic-regexp
5244 (concat
5245 "\\[\\["
5246 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5247 "\\([^]]+\\)"
5248 "\\]"
5249 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5250 "\\]")
5251 org-bracket-link-analytic-regexp++
5252 (concat
5253 "\\[\\["
5254 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5255 "\\([^]]+\\)"
5256 "\\]"
5257 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5258 "\\]")
5259 org-any-link-re
5260 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5261 org-angle-link-re "\\)\\|\\("
5262 org-plain-link-re "\\)")))
5264 (org-make-link-regexps)
5266 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5267 "Regular expression for fast time stamp matching.")
5268 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5269 "Regular expression for fast time stamp matching.")
5270 (defconst org-ts-regexp0
5271 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5272 "Regular expression matching time strings for analysis.
5273 This one does not require the space after the date, so it can be used
5274 on a string that terminates immediately after the date.")
5275 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5276 "Regular expression matching time strings for analysis.")
5277 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5278 "Regular expression matching time stamps, with groups.")
5279 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5280 "Regular expression matching time stamps (also [..]), with groups.")
5281 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5282 "Regular expression matching a time stamp range.")
5283 (defconst org-tr-regexp-both
5284 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5285 "Regular expression matching a time stamp range.")
5286 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5287 org-ts-regexp "\\)?")
5288 "Regular expression matching a time stamp or time stamp range.")
5289 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5290 org-ts-regexp-both "\\)?")
5291 "Regular expression matching a time stamp or time stamp range.
5292 The time stamps may be either active or inactive.")
5294 (defvar org-emph-face nil)
5296 (defun org-do-emphasis-faces (limit)
5297 "Run through the buffer and add overlays to emphasized strings."
5298 (let (rtn a)
5299 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5300 (if (not (= (char-after (match-beginning 3))
5301 (char-after (match-beginning 4))))
5302 (progn
5303 (setq rtn t)
5304 (setq a (assoc (match-string 3) org-emphasis-alist))
5305 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5306 'face
5307 (nth 1 a))
5308 (and (nth 4 a)
5309 (org-remove-flyspell-overlays-in
5310 (match-beginning 0) (match-end 0)))
5311 (add-text-properties (match-beginning 2) (match-end 2)
5312 '(font-lock-multiline t org-emphasis t))
5313 (when org-hide-emphasis-markers
5314 (add-text-properties (match-end 4) (match-beginning 5)
5315 '(invisible org-link))
5316 (add-text-properties (match-beginning 3) (match-end 3)
5317 '(invisible org-link)))))
5318 (backward-char 1))
5319 rtn))
5321 (defun org-emphasize (&optional char)
5322 "Insert or change an emphasis, i.e. a font like bold or italic.
5323 If there is an active region, change that region to a new emphasis.
5324 If there is no region, just insert the marker characters and position
5325 the cursor between them.
5326 CHAR should be either the marker character, or the first character of the
5327 HTML tag associated with that emphasis. If CHAR is a space, the means
5328 to remove the emphasis of the selected region.
5329 If char is not given (for example in an interactive call) it
5330 will be prompted for."
5331 (interactive)
5332 (let ((eal org-emphasis-alist) e det
5333 (erc org-emphasis-regexp-components)
5334 (prompt "")
5335 (string "") beg end move tag c s)
5336 (if (org-region-active-p)
5337 (setq beg (region-beginning) end (region-end)
5338 string (buffer-substring beg end))
5339 (setq move t))
5341 (while (setq e (pop eal))
5342 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5343 c (aref tag 0))
5344 (push (cons c (string-to-char (car e))) det)
5345 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5346 (substring tag 1)))))
5347 (setq det (nreverse det))
5348 (unless char
5349 (message "%s" (concat "Emphasis marker or tag:" prompt))
5350 (setq char (read-char-exclusive)))
5351 (setq char (or (cdr (assoc char det)) char))
5352 (if (equal char ?\ )
5353 (setq s "" move nil)
5354 (unless (assoc (char-to-string char) org-emphasis-alist)
5355 (error "No such emphasis marker: \"%c\"" char))
5356 (setq s (char-to-string char)))
5357 (while (and (> (length string) 1)
5358 (equal (substring string 0 1) (substring string -1))
5359 (assoc (substring string 0 1) org-emphasis-alist))
5360 (setq string (substring string 1 -1)))
5361 (setq string (concat s string s))
5362 (if beg (delete-region beg end))
5363 (unless (or (bolp)
5364 (string-match (concat "[" (nth 0 erc) "\n]")
5365 (char-to-string (char-before (point)))))
5366 (insert " "))
5367 (unless (or (eobp)
5368 (string-match (concat "[" (nth 1 erc) "\n]")
5369 (char-to-string (char-after (point)))))
5370 (insert " ") (backward-char 1))
5371 (insert string)
5372 (and move (backward-char 1))))
5374 (defconst org-nonsticky-props
5375 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
5377 (defsubst org-rear-nonsticky-at (pos)
5378 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5380 (defun org-activate-plain-links (limit)
5381 "Run through the buffer and add overlays to links."
5382 (catch 'exit
5383 (let (f)
5384 (if (re-search-forward org-plain-link-re limit t)
5385 (progn
5386 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5387 (setq f (get-text-property (match-beginning 0) 'face))
5388 (if (or (eq f 'org-tag)
5389 (and (listp f) (memq 'org-tag f)))
5391 (add-text-properties (match-beginning 0) (match-end 0)
5392 (list 'mouse-face 'highlight
5393 'face 'org-link
5394 'keymap org-mouse-map))
5395 (org-rear-nonsticky-at (match-end 0)))
5396 t)))))
5398 (defun org-activate-code (limit)
5399 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5400 (progn
5401 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5402 (remove-text-properties (match-beginning 0) (match-end 0)
5403 '(display t invisible t intangible t))
5404 t)))
5406 (defcustom org-src-fontify-natively nil
5407 "When non-nil, fontify code in code blocks."
5408 :type 'boolean
5409 :version "24.1"
5410 :group 'org-appearance
5411 :group 'org-babel)
5413 (defun org-fontify-meta-lines-and-blocks (limit)
5414 (condition-case nil
5415 (org-fontify-meta-lines-and-blocks-1 limit)
5416 (error (message "org-mode fontification error"))))
5418 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5419 "Fontify #+ lines and blocks, in the correct ways."
5420 (let ((case-fold-search t))
5421 (if (re-search-forward
5422 "^\\([ \t]*#\\+\\(\\([a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5423 limit t)
5424 (let ((beg (match-beginning 0))
5425 (block-start (match-end 0))
5426 (block-end nil)
5427 (lang (match-string 7))
5428 (beg1 (line-beginning-position 2))
5429 (dc1 (downcase (match-string 2)))
5430 (dc3 (downcase (match-string 3)))
5431 end end1 quoting block-type ovl)
5432 (cond
5433 ((member dc1 '("html:" "ascii:" "latex:" "docbook:"))
5434 ;; a single line of backend-specific content
5435 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5436 (remove-text-properties (match-beginning 0) (match-end 0)
5437 '(display t invisible t intangible t))
5438 (add-text-properties (match-beginning 1) (match-end 3)
5439 '(font-lock-fontified t face org-meta-line))
5440 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5441 '(font-lock-fontified t face org-block))
5442 ; for backend-specific code
5444 ((and (match-end 4) (equal dc3 "begin"))
5445 ;; Truly a block
5446 (setq block-type (downcase (match-string 5))
5447 quoting (member block-type org-protecting-blocks))
5448 (when (re-search-forward
5449 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5450 nil t) ;; on purpose, we look further than LIMIT
5451 (setq end (min (point-max) (match-end 0))
5452 end1 (min (point-max) (1- (match-beginning 0))))
5453 (setq block-end (match-beginning 0))
5454 (when quoting
5455 (remove-text-properties beg end
5456 '(display t invisible t intangible t)))
5457 (add-text-properties
5458 beg end
5459 '(font-lock-fontified t font-lock-multiline t))
5460 (add-text-properties beg beg1 '(face org-meta-line))
5461 (add-text-properties end1 (min (point-max) (1+ end))
5462 '(face org-meta-line)) ; for end_src
5463 (cond
5464 ((and lang (not (string= lang "")) org-src-fontify-natively)
5465 (org-src-font-lock-fontify-block lang block-start block-end)
5466 ;; remove old background overlays
5467 (mapc (lambda (ov)
5468 (if (eq (overlay-get ov 'face) 'org-block-background)
5469 (delete-overlay ov)))
5470 (overlays-at (/ (+ beg1 block-end) 2)))
5471 ;; add a background overlay
5472 (setq ovl (make-overlay beg1 block-end))
5473 (overlay-put ovl 'face 'org-block-background)
5474 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5475 (quoting
5476 (add-text-properties beg1 (min (point-max) (1+ end1))
5477 '(face org-block))) ; end of source block
5478 ((not org-fontify-quote-and-verse-blocks))
5479 ((string= block-type "quote")
5480 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5481 ((string= block-type "verse")
5482 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5483 (add-text-properties beg beg1 '(face org-block-begin-line))
5484 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5485 '(face org-block-end-line))
5487 ((member dc1 '("title:" "author:" "email:" "date:"))
5488 (add-text-properties
5489 beg (match-end 3)
5490 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5491 '(font-lock-fontified t invisible t)
5492 '(font-lock-fontified t face org-document-info-keyword)))
5493 (add-text-properties
5494 (match-beginning 6) (match-end 6)
5495 (if (string-equal dc1 "title:")
5496 '(font-lock-fontified t face org-document-title)
5497 '(font-lock-fontified t face org-document-info))))
5498 ((not (member (char-after beg) '(?\ ?\t)))
5499 ;; just any other in-buffer setting, but not indented
5500 (add-text-properties
5501 beg (match-end 0)
5502 '(font-lock-fontified t face org-meta-line))
5504 ((or (member dc1 '("begin:" "end:" "caption:" "label:"
5505 "orgtbl:" "tblfm:" "tblname:" "results:"
5506 "call:" "header:" "headers:" "name:"))
5507 (and (match-end 4) (equal dc3 "attr")))
5508 (add-text-properties
5509 beg (match-end 0)
5510 '(font-lock-fontified t face org-meta-line))
5512 ((member dc3 '(" " ""))
5513 (add-text-properties
5514 beg (match-end 0)
5515 '(font-lock-fontified t face font-lock-comment-face)))
5516 (t nil))))))
5518 (defun org-strip-protective-commas (beg end)
5519 "Strip protective commas between BEG and END in the current buffer."
5520 (interactive "r")
5521 (save-excursion
5522 (save-match-data
5523 (goto-char beg)
5524 (let ((front-line (save-excursion
5525 (re-search-forward
5526 "[^[:space:]]" end t)
5527 (goto-char (match-beginning 0))
5528 (current-column))))
5529 (while (re-search-forward "^[ \t]*\\(,\\)\\([*]\\|#\\+\\)" end t)
5530 (goto-char (match-beginning 1))
5531 (when (= (current-column) front-line)
5532 (replace-match "" nil nil nil 1)))))))
5534 (defun org-activate-angle-links (limit)
5535 "Run through the buffer and add overlays to links."
5536 (if (re-search-forward org-angle-link-re limit t)
5537 (progn
5538 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5539 (add-text-properties (match-beginning 0) (match-end 0)
5540 (list 'mouse-face 'highlight
5541 'keymap org-mouse-map))
5542 (org-rear-nonsticky-at (match-end 0))
5543 t)))
5545 (defun org-activate-footnote-links (limit)
5546 "Run through the buffer and add overlays to footnotes."
5547 (let ((fn (org-footnote-next-reference-or-definition limit)))
5548 (when fn
5549 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5550 (org-remove-flyspell-overlays-in beg end)
5551 (add-text-properties beg end
5552 (list 'mouse-face 'highlight
5553 'keymap org-mouse-map
5554 'help-echo
5555 (if (= (point-at-bol) beg)
5556 "Footnote definition"
5557 "Footnote reference")
5558 'font-lock-fontified t
5559 'font-lock-multiline t
5560 'face 'org-footnote))))))
5562 (defun org-activate-bracket-links (limit)
5563 "Run through the buffer and add overlays to bracketed links."
5564 (if (re-search-forward org-bracket-link-regexp limit t)
5565 (let* ((help (concat "LINK: "
5566 (org-match-string-no-properties 1)))
5567 ;; FIXME: above we should remove the escapes.
5568 ;; but that requires another match, protecting match data,
5569 ;; a lot of overhead for font-lock.
5570 (ip (org-maybe-intangible
5571 (list 'invisible 'org-link
5572 'keymap org-mouse-map 'mouse-face 'highlight
5573 'font-lock-multiline t 'help-echo help)))
5574 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5575 'font-lock-multiline t 'help-echo help)))
5576 ;; We need to remove the invisible property here. Table narrowing
5577 ;; may have made some of this invisible.
5578 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5579 (remove-text-properties (match-beginning 0) (match-end 0)
5580 '(invisible nil))
5581 (if (match-end 3)
5582 (progn
5583 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5584 (org-rear-nonsticky-at (match-beginning 3))
5585 (add-text-properties (match-beginning 3) (match-end 3) vp)
5586 (org-rear-nonsticky-at (match-end 3))
5587 (add-text-properties (match-end 3) (match-end 0) ip)
5588 (org-rear-nonsticky-at (match-end 0)))
5589 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5590 (org-rear-nonsticky-at (match-beginning 1))
5591 (add-text-properties (match-beginning 1) (match-end 1) vp)
5592 (org-rear-nonsticky-at (match-end 1))
5593 (add-text-properties (match-end 1) (match-end 0) ip)
5594 (org-rear-nonsticky-at (match-end 0)))
5595 t)))
5597 (defun org-activate-dates (limit)
5598 "Run through the buffer and add overlays to dates."
5599 (if (re-search-forward org-tsr-regexp-both limit t)
5600 (progn
5601 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5602 (add-text-properties (match-beginning 0) (match-end 0)
5603 (list 'mouse-face 'highlight
5604 'keymap org-mouse-map))
5605 (org-rear-nonsticky-at (match-end 0))
5606 (when org-display-custom-times
5607 (if (match-end 3)
5608 (org-display-custom-time (match-beginning 3) (match-end 3)))
5609 (org-display-custom-time (match-beginning 1) (match-end 1)))
5610 t)))
5612 (defvar org-target-link-regexp nil
5613 "Regular expression matching radio targets in plain text.")
5614 (make-variable-buffer-local 'org-target-link-regexp)
5615 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5616 "Regular expression matching a link target.")
5617 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5618 "Regular expression matching a radio target.")
5619 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5620 "Regular expression matching any target.")
5622 (defun org-activate-target-links (limit)
5623 "Run through the buffer and add overlays to target matches."
5624 (when org-target-link-regexp
5625 (let ((case-fold-search t))
5626 (if (re-search-forward org-target-link-regexp limit t)
5627 (progn
5628 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5629 (add-text-properties (match-beginning 0) (match-end 0)
5630 (list 'mouse-face 'highlight
5631 'keymap org-mouse-map
5632 'help-echo "Radio target link"
5633 'org-linked-text t))
5634 (org-rear-nonsticky-at (match-end 0))
5635 t)))))
5637 (defun org-update-radio-target-regexp ()
5638 "Find all radio targets in this file and update the regular expression."
5639 (interactive)
5640 (when (memq 'radio org-activate-links)
5641 (setq org-target-link-regexp
5642 (org-make-target-link-regexp (org-all-targets 'radio)))
5643 (org-restart-font-lock)))
5645 (defun org-hide-wide-columns (limit)
5646 (let (s e)
5647 (setq s (text-property-any (point) (or limit (point-max))
5648 'org-cwidth t))
5649 (when s
5650 (setq e (next-single-property-change s 'org-cwidth))
5651 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5652 (goto-char e)
5653 t)))
5655 (defvar org-latex-and-specials-regexp nil
5656 "Regular expression for highlighting export special stuff.")
5657 (defvar org-match-substring-regexp)
5658 (defvar org-match-substring-with-braces-regexp)
5660 ;; This should be with the exporter code, but we also use if for font-locking
5661 (defconst org-export-html-special-string-regexps
5662 '(("\\\\-" . "&shy;")
5663 ("---\\([^-]\\)" . "&mdash;\\1")
5664 ("--\\([^-]\\)" . "&ndash;\\1")
5665 ("\\.\\.\\." . "&hellip;"))
5666 "Regular expressions for special string conversion.")
5669 (defun org-compute-latex-and-specials-regexp ()
5670 "Compute regular expression for stuff treated specially by exporters."
5671 (if (not org-highlight-latex-fragments-and-specials)
5672 (org-set-local 'org-latex-and-specials-regexp nil)
5673 (require 'org-exp)
5674 (let*
5675 ((matchers (plist-get org-format-latex-options :matchers))
5676 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5677 org-latex-regexps)))
5678 (org-export-allow-BIND nil)
5679 (options (org-combine-plists (org-default-export-plist)
5680 (org-infile-export-plist)))
5681 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5682 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5683 (org-export-with-TeX-macros (plist-get options :TeX-macros))
5684 (org-export-html-expand (plist-get options :expand-quoted-html))
5685 (org-export-with-special-strings (plist-get options :special-strings))
5686 (re-sub
5687 (cond
5688 ((equal org-export-with-sub-superscripts '{})
5689 (list org-match-substring-with-braces-regexp))
5690 (org-export-with-sub-superscripts
5691 (list org-match-substring-regexp))
5692 (t nil)))
5693 (re-latex
5694 (if org-export-with-LaTeX-fragments
5695 (mapcar (lambda (x) (nth 1 x)) latexs)))
5696 (re-macros
5697 (if org-export-with-TeX-macros
5698 (list (concat "\\\\"
5699 (regexp-opt
5700 (append
5702 (delq nil
5703 (mapcar 'car-safe
5704 (append org-entities-user
5705 org-entities)))
5706 (if (boundp 'org-latex-entities)
5707 (mapcar (lambda (x)
5708 (or (car-safe x) x))
5709 org-latex-entities)
5710 nil))
5711 'words))) ; FIXME
5713 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5714 (re-special (if org-export-with-special-strings
5715 (mapcar (lambda (x) (car x))
5716 org-export-html-special-string-regexps)))
5717 (re-rest
5718 (delq nil
5719 (list
5720 (if org-export-html-expand "@<[^>\n]+>")
5721 ))))
5722 (org-set-local
5723 'org-latex-and-specials-regexp
5724 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5725 re-rest) "\\|")))))
5727 (defun org-do-latex-and-special-faces (limit)
5728 "Run through the buffer and add overlays to links."
5729 (when org-latex-and-specials-regexp
5730 (let (rtn d)
5731 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5732 limit t))
5733 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5734 'face))
5735 '(org-code org-verbatim underline)))
5736 (progn
5737 (setq rtn t
5738 d (cond ((member (char-after (1+ (match-beginning 0)))
5739 '(?_ ?^)) 1)
5740 (t 0)))
5741 (font-lock-prepend-text-property
5742 (+ d (match-beginning 0)) (match-end 0)
5743 'face 'org-latex-and-export-specials)
5744 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5745 '(font-lock-multiline t)))))
5746 rtn)))
5748 (defun org-restart-font-lock ()
5749 "Restart `font-lock-mode', to force refontification."
5750 (when (and (boundp 'font-lock-mode) font-lock-mode)
5751 (font-lock-mode -1)
5752 (font-lock-mode 1)))
5754 (defun org-all-targets (&optional radio)
5755 "Return a list of all targets in this file.
5756 With optional argument RADIO, only find radio targets."
5757 (let ((re (if radio org-radio-target-regexp org-target-regexp))
5758 rtn)
5759 (save-excursion
5760 (goto-char (point-min))
5761 (while (re-search-forward re nil t)
5762 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
5763 rtn)))
5765 (defun org-make-target-link-regexp (targets)
5766 "Make regular expression matching all strings in TARGETS.
5767 The regular expression finds the targets also if there is a line break
5768 between words."
5769 (and targets
5770 (concat
5771 "\\<\\("
5772 (mapconcat
5773 (lambda (x)
5774 (setq x (regexp-quote x))
5775 (while (string-match " +" x)
5776 (setq x (replace-match "\\s-+" t t x)))
5778 targets
5779 "\\|")
5780 "\\)\\>")))
5782 (defun org-activate-tags (limit)
5783 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
5784 (progn
5785 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5786 (add-text-properties (match-beginning 1) (match-end 1)
5787 (list 'mouse-face 'highlight
5788 'keymap org-mouse-map))
5789 (org-rear-nonsticky-at (match-end 1))
5790 t)))
5792 (defun org-outline-level ()
5793 "Compute the outline level of the heading at point.
5794 This function assumes that the cursor is at the beginning of a line matched
5795 by `outline-regexp'. Otherwise it returns garbage.
5796 If this is called at a normal headline, the level is the number of stars.
5797 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
5798 (save-excursion
5799 (looking-at org-outline-regexp)
5800 (1- (- (match-end 0) (match-beginning 0)))))
5802 (defvar org-font-lock-keywords nil)
5804 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\+?\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
5805 "Regular expression matching a property line.")
5807 (defvar org-font-lock-hook nil
5808 "Functions to be called for special font lock stuff.")
5810 (defvar org-font-lock-set-keywords-hook nil
5811 "Functions that can manipulate `org-font-lock-extra-keywords'.
5812 This is called after `org-font-lock-extra-keywords' is defined, but before
5813 it is installed to be used by font lock. This can be useful if something
5814 needs to be inserted at a specific position in the font-lock sequence.")
5816 (defun org-font-lock-hook (limit)
5817 (run-hook-with-args 'org-font-lock-hook limit))
5819 (defun org-set-font-lock-defaults ()
5820 (let* ((em org-fontify-emphasized-text)
5821 (lk org-activate-links)
5822 (org-font-lock-extra-keywords
5823 (list
5824 ;; Call the hook
5825 '(org-font-lock-hook)
5826 ;; Headlines
5827 `(,(if org-fontify-whole-heading-line
5828 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
5829 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
5830 (1 (org-get-level-face 1))
5831 (2 (org-get-level-face 2))
5832 (3 (org-get-level-face 3)))
5833 ;; Table lines
5834 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5835 (1 'org-table t))
5836 ;; Table internals
5837 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5838 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5839 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5840 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
5841 ;; Drawers
5842 (list org-drawer-regexp '(0 'org-special-keyword t))
5843 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5844 ;; Properties
5845 (list org-property-re
5846 '(1 'org-special-keyword t)
5847 '(3 'org-property-value t))
5848 ;; Links
5849 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5850 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5851 (if (memq 'plain lk) '(org-activate-plain-links))
5852 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5853 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5854 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5855 (if (memq 'footnote lk) '(org-activate-footnote-links))
5856 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5857 '(org-hide-wide-columns (0 nil append))
5858 ;; TODO keyword
5859 (list (format org-heading-keyword-regexp-format
5860 org-todo-regexp)
5861 '(2 (org-get-todo-face 2) t))
5862 ;; DONE
5863 (if org-fontify-done-headline
5864 (list (format org-heading-keyword-regexp-format
5865 (concat
5866 "\\(?:"
5867 (mapconcat 'regexp-quote org-done-keywords "\\|")
5868 "\\)"))
5869 '(2 'org-headline-done t))
5870 nil)
5871 ;; Priorities
5872 '(org-font-lock-add-priority-faces)
5873 ;; Tags
5874 '(org-font-lock-add-tag-faces)
5875 ;; Special keywords
5876 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5877 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5878 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5879 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5880 ;; Emphasis
5881 (if em
5882 (if (featurep 'xemacs)
5883 '(org-do-emphasis-faces (0 nil append))
5884 '(org-do-emphasis-faces)))
5885 ;; Checkboxes
5886 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
5887 1 'org-checkbox prepend)
5888 (if (cdr (assq 'checkbox org-list-automatic-rules))
5889 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5890 (0 (org-get-checkbox-statistics-face) t)))
5891 ;; Description list items
5892 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
5893 1 'org-list-dt prepend)
5894 ;; ARCHIVEd headings
5895 (list (concat
5896 org-outline-regexp-bol
5897 "\\(.*:" org-archive-tag ":.*\\)")
5898 '(1 'org-archived prepend))
5899 ;; Specials
5900 '(org-do-latex-and-special-faces)
5901 '(org-fontify-entities)
5902 '(org-raise-scripts)
5903 ;; Code
5904 '(org-activate-code (1 'org-code t))
5905 ;; COMMENT
5906 (list (format org-heading-keyword-regexp-format
5907 (concat "\\("
5908 org-comment-string "\\|" org-quote-string
5909 "\\)"))
5910 '(2 'org-special-keyword t))
5911 '("^#.*" (0 'font-lock-comment-face t))
5912 ;; Blocks and meta lines
5913 '(org-fontify-meta-lines-and-blocks)
5915 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5916 (run-hooks 'org-font-lock-set-keywords-hook)
5917 ;; Now set the full font-lock-keywords
5918 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5919 (org-set-local 'font-lock-defaults
5920 '(org-font-lock-keywords t nil nil backward-paragraph))
5921 (kill-local-variable 'font-lock-keywords) nil))
5923 (defun org-toggle-pretty-entities ()
5924 "Toggle the composition display of entities as UTF8 characters."
5925 (interactive)
5926 (org-set-local 'org-pretty-entities (not org-pretty-entities))
5927 (org-restart-font-lock)
5928 (if org-pretty-entities
5929 (message "Entities are displayed as UTF8 characters")
5930 (save-restriction
5931 (widen)
5932 (org-decompose-region (point-min) (point-max))
5933 (message "Entities are displayed plain"))))
5935 (defun org-fontify-entities (limit)
5936 "Find an entity to fontify."
5937 (let (ee)
5938 (when org-pretty-entities
5939 (catch 'match
5940 (while (re-search-forward
5941 "\\\\\\(frac[13][24]\\|[a-zA-Z]+\\)\\($\\|[^[:alpha:]\n]\\)"
5942 limit t)
5943 (if (and (not (org-in-indented-comment-line))
5944 (setq ee (org-entity-get (match-string 1)))
5945 (= (length (nth 6 ee)) 1))
5946 (progn
5947 (add-text-properties
5948 (match-beginning 0) (match-end 1)
5949 (list 'font-lock-fontified t))
5950 (compose-region (match-beginning 0) (match-end 1)
5951 (nth 6 ee) nil)
5952 (backward-char 1)
5953 (throw 'match t))))
5954 nil))))
5956 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
5957 "Fontify string S like in Org-mode."
5958 (with-temp-buffer
5959 (insert s)
5960 (let ((org-odd-levels-only odd-levels))
5961 (org-mode)
5962 (font-lock-fontify-buffer)
5963 (buffer-string))))
5965 (defvar org-m nil)
5966 (defvar org-l nil)
5967 (defvar org-f nil)
5968 (defun org-get-level-face (n)
5969 "Get the right face for match N in font-lock matching of headlines."
5970 (setq org-l (- (match-end 2) (match-beginning 1) 1))
5971 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
5972 (if org-cycle-level-faces
5973 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
5974 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
5975 (cond
5976 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
5977 ((eq n 2) org-f)
5978 (t (if org-level-color-stars-only nil org-f))))
5981 (defun org-get-todo-face (kwd)
5982 "Get the right face for a TODO keyword KWD.
5983 If KWD is a number, get the corresponding match group."
5984 (if (numberp kwd) (setq kwd (match-string kwd)))
5985 (or (org-face-from-face-or-color
5986 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
5987 (and (member kwd org-done-keywords) 'org-done)
5988 'org-todo))
5990 (defun org-face-from-face-or-color (context inherit face-or-color)
5991 "Create a face list that inherits INHERIT, but sets the foreground color.
5992 When FACE-OR-COLOR is not a string, just return it."
5993 (if (stringp face-or-color)
5994 (list :inherit inherit
5995 (cdr (assoc context org-faces-easy-properties))
5996 face-or-color)
5997 face-or-color))
5999 (defun org-font-lock-add-tag-faces (limit)
6000 "Add the special tag faces."
6001 (when (and org-tag-faces org-tags-special-faces-re)
6002 (while (re-search-forward org-tags-special-faces-re limit t)
6003 (add-text-properties (match-beginning 1) (match-end 1)
6004 (list 'face (org-get-tag-face 1)
6005 'font-lock-fontified t))
6006 (backward-char 1))))
6008 (defun org-font-lock-add-priority-faces (limit)
6009 "Add the special priority faces."
6010 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6011 (add-text-properties
6012 (match-beginning 0) (match-end 0)
6013 (list 'face (or (org-face-from-face-or-color
6014 'priority 'org-special-keyword
6015 (cdr (assoc (char-after (match-beginning 1))
6016 org-priority-faces)))
6017 'org-special-keyword)
6018 'font-lock-fontified t))))
6020 (defun org-get-tag-face (kwd)
6021 "Get the right face for a TODO keyword KWD.
6022 If KWD is a number, get the corresponding match group."
6023 (if (numberp kwd) (setq kwd (match-string kwd)))
6024 (or (org-face-from-face-or-color
6025 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6026 'org-tag))
6028 (defun org-unfontify-region (beg end &optional maybe_loudly)
6029 "Remove fontification and activation overlays from links."
6030 (font-lock-default-unfontify-region beg end)
6031 (let* ((buffer-undo-list t)
6032 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6033 (inhibit-modification-hooks t)
6034 deactivate-mark buffer-file-name buffer-file-truename)
6035 (org-decompose-region beg end)
6036 (remove-text-properties beg end
6037 '(mouse-face t keymap t org-linked-text t
6038 invisible t intangible t
6039 org-no-flyspell t org-emphasis t))
6040 (org-remove-font-lock-display-properties beg end)))
6042 (defconst org-script-display '(((raise -0.3) (height 0.7))
6043 ((raise 0.3) (height 0.7))
6044 ((raise -0.5))
6045 ((raise 0.5)))
6046 "Display properties for showing superscripts and subscripts.")
6048 (defun org-remove-font-lock-display-properties (beg end)
6049 "Remove specific display properties that have been added by font lock.
6050 The will remove the raise properties that are used to show superscripts
6051 and subscripts."
6052 (let (next prop)
6053 (while (< beg end)
6054 (setq next (next-single-property-change beg 'display nil end)
6055 prop (get-text-property beg 'display))
6056 (if (member prop org-script-display)
6057 (put-text-property beg next 'display nil))
6058 (setq beg next))))
6060 (defun org-raise-scripts (limit)
6061 "Add raise properties to sub/superscripts."
6062 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6063 (if (re-search-forward
6064 (if (eq org-use-sub-superscripts t)
6065 org-match-substring-regexp
6066 org-match-substring-with-braces-regexp)
6067 limit t)
6068 (let* ((pos (point)) table-p comment-p
6069 (mpos (match-beginning 3))
6070 (emph-p (get-text-property mpos 'org-emphasis))
6071 (link-p (get-text-property mpos 'mouse-face))
6072 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6073 (goto-char (point-at-bol))
6074 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6075 comment-p (org-looking-at-p "[ \t]*#"))
6076 (goto-char pos)
6077 ;; FIXME: Should we go back one character here, for a_b^c
6078 ;; (goto-char (1- pos)) ;????????????????????
6079 (if (or comment-p emph-p link-p keyw-p)
6081 (put-text-property (match-beginning 3) (match-end 0)
6082 'display
6083 (if (equal (char-after (match-beginning 2)) ?^)
6084 (nth (if table-p 3 1) org-script-display)
6085 (nth (if table-p 2 0) org-script-display)))
6086 (add-text-properties (match-beginning 2) (match-end 2)
6087 (list 'invisible t
6088 'org-dwidth t 'org-dwidth-n 1))
6089 (if (and (eq (char-after (match-beginning 3)) ?{)
6090 (eq (char-before (match-end 3)) ?}))
6091 (progn
6092 (add-text-properties
6093 (match-beginning 3) (1+ (match-beginning 3))
6094 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6095 (add-text-properties
6096 (1- (match-end 3)) (match-end 3)
6097 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6098 t)))))
6100 ;;;; Visibility cycling, including org-goto and indirect buffer
6102 ;;; Cycling
6104 (defvar org-cycle-global-status nil)
6105 (make-variable-buffer-local 'org-cycle-global-status)
6106 (defvar org-cycle-subtree-status nil)
6107 (make-variable-buffer-local 'org-cycle-subtree-status)
6109 ;;;###autoload
6111 (defvar org-inlinetask-min-level)
6113 (defun org-cycle (&optional arg)
6114 "TAB-action and visibility cycling for Org-mode.
6116 This is the command invoked in Org-mode by the TAB key. Its main purpose
6117 is outline visibility cycling, but it also invokes other actions
6118 in special contexts.
6120 - When this function is called with a prefix argument, rotate the entire
6121 buffer through 3 states (global cycling)
6122 1. OVERVIEW: Show only top-level headlines.
6123 2. CONTENTS: Show all headlines of all levels, but no body text.
6124 3. SHOW ALL: Show everything.
6125 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6126 determined by the variable `org-startup-folded', and by any VISIBILITY
6127 properties in the buffer.
6128 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6129 including any drawers.
6131 - When inside a table, re-align the table and move to the next field.
6133 - When point is at the beginning of a headline, rotate the subtree started
6134 by this line through 3 different states (local cycling)
6135 1. FOLDED: Only the main headline is shown.
6136 2. CHILDREN: The main headline and the direct children are shown.
6137 From this state, you can move to one of the children
6138 and zoom in further.
6139 3. SUBTREE: Show the entire subtree, including body text.
6140 If there is no subtree, switch directly from CHILDREN to FOLDED.
6142 - When point is at the beginning of an empty headline and the variable
6143 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6144 of the headline by demoting and promoting it to likely levels. This
6145 speeds up creation document structure by pressing TAB once or several
6146 times right after creating a new headline.
6148 - When there is a numeric prefix, go up to a heading with level ARG, do
6149 a `show-subtree' and return to the previous cursor position. If ARG
6150 is negative, go up that many levels.
6152 - When point is not at the beginning of a headline, execute the global
6153 binding for TAB, which is re-indenting the line. See the option
6154 `org-cycle-emulate-tab' for details.
6156 - Special case: if point is at the beginning of the buffer and there is
6157 no headline in line 1, this function will act as if called with prefix arg
6158 (C-u TAB, same as S-TAB) also when called without prefix arg.
6159 But only if also the variable `org-cycle-global-at-bob' is t."
6160 (interactive "P")
6161 (org-load-modules-maybe)
6162 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6163 (and org-cycle-level-after-item/entry-creation
6164 (or (org-cycle-level)
6165 (org-cycle-item-indentation))))
6166 (let* ((limit-level
6167 (or org-cycle-max-level
6168 (and (boundp 'org-inlinetask-min-level)
6169 org-inlinetask-min-level
6170 (1- org-inlinetask-min-level))))
6171 (nstars (and limit-level
6172 (if org-odd-levels-only
6173 (and limit-level (1- (* limit-level 2)))
6174 limit-level)))
6175 (org-outline-regexp
6176 (if (not (derived-mode-p 'org-mode))
6177 outline-regexp
6178 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6179 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6180 (not (looking-at org-outline-regexp))))
6181 (org-cycle-hook
6182 (if bob-special
6183 (delq 'org-optimize-window-after-visibility-change
6184 (copy-sequence org-cycle-hook))
6185 org-cycle-hook))
6186 (pos (point)))
6188 (if (or bob-special (equal arg '(4)))
6189 ;; special case: use global cycling
6190 (setq arg t))
6192 (cond
6194 ((equal arg '(16))
6195 (setq last-command 'dummy)
6196 (org-set-startup-visibility)
6197 (message "Startup visibility, plus VISIBILITY properties"))
6199 ((equal arg '(64))
6200 (show-all)
6201 (message "Entire buffer visible, including drawers"))
6203 ;; Table: enter it or move to the next field.
6204 ((org-at-table-p 'any)
6205 (if (org-at-table.el-p)
6206 (message "Use C-c ' to edit table.el tables")
6207 (if arg (org-table-edit-field t)
6208 (org-table-justify-field-maybe)
6209 (call-interactively 'org-table-next-field))))
6211 ((run-hook-with-args-until-success
6212 'org-tab-after-check-for-table-hook))
6214 ;; Global cycling: delegate to `org-cycle-internal-global'.
6215 ((eq arg t) (org-cycle-internal-global))
6217 ;; Drawers: delegate to `org-flag-drawer'.
6218 ((and org-drawers org-drawer-regexp
6219 (save-excursion
6220 (beginning-of-line 1)
6221 (looking-at org-drawer-regexp)))
6222 (org-flag-drawer ; toggle block visibility
6223 (not (get-char-property (match-end 0) 'invisible))))
6225 ;; Show-subtree, ARG levels up from here.
6226 ((integerp arg)
6227 (save-excursion
6228 (org-back-to-heading)
6229 (outline-up-heading (if (< arg 0) (- arg)
6230 (- (funcall outline-level) arg)))
6231 (org-show-subtree)))
6233 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6234 ((and (featurep 'org-inlinetask)
6235 (org-inlinetask-at-task-p)
6236 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6237 (org-inlinetask-toggle-visibility))
6239 ((org-try-cdlatex-tab))
6241 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6242 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6243 (save-excursion (beginning-of-line 1)
6244 (looking-at org-outline-regexp)))
6245 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6246 (org-cycle-internal-local))
6248 ;; From there: TAB emulation and template completion.
6249 (buffer-read-only (org-back-to-heading))
6251 ((run-hook-with-args-until-success
6252 'org-tab-after-check-for-cycling-hook))
6254 ((org-try-structure-completion))
6256 ((run-hook-with-args-until-success
6257 'org-tab-before-tab-emulation-hook))
6259 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6260 (or (not (bolp))
6261 (not (looking-at org-outline-regexp))))
6262 (call-interactively (global-key-binding "\t")))
6264 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6265 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6266 (or (and (eq org-cycle-emulate-tab 'white)
6267 (= (match-end 0) (point-at-eol)))
6268 (and (eq org-cycle-emulate-tab 'whitestart)
6269 (>= (match-end 0) pos))))
6271 (eq org-cycle-emulate-tab t))
6272 (call-interactively (global-key-binding "\t")))
6274 (t (save-excursion
6275 (org-back-to-heading)
6276 (org-cycle)))))))
6278 (defun org-cycle-internal-global ()
6279 "Do the global cycling action."
6280 ;; Hack to avoid display of messages for .org attachments in Gnus
6281 (let ((ga (string-match "\\*fontification" (buffer-name))))
6282 (cond
6283 ((and (eq last-command this-command)
6284 (eq org-cycle-global-status 'overview))
6285 ;; We just created the overview - now do table of contents
6286 ;; This can be slow in very large buffers, so indicate action
6287 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6288 (unless ga (message "CONTENTS..."))
6289 (org-content)
6290 (unless ga (message "CONTENTS...done"))
6291 (setq org-cycle-global-status 'contents)
6292 (run-hook-with-args 'org-cycle-hook 'contents))
6294 ((and (eq last-command this-command)
6295 (eq org-cycle-global-status 'contents))
6296 ;; We just showed the table of contents - now show everything
6297 (run-hook-with-args 'org-pre-cycle-hook 'all)
6298 (show-all)
6299 (unless ga (message "SHOW ALL"))
6300 (setq org-cycle-global-status 'all)
6301 (run-hook-with-args 'org-cycle-hook 'all))
6304 ;; Default action: go to overview
6305 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6306 (org-overview)
6307 (unless ga (message "OVERVIEW"))
6308 (setq org-cycle-global-status 'overview)
6309 (run-hook-with-args 'org-cycle-hook 'overview)))))
6311 (defun org-cycle-internal-local ()
6312 "Do the local cycling action."
6313 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6314 ;; First, determine end of headline (EOH), end of subtree or item
6315 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6316 (save-excursion
6317 (if (org-at-item-p)
6318 (progn
6319 (beginning-of-line)
6320 (setq struct (org-list-struct))
6321 (setq eoh (point-at-eol))
6322 (setq eos (org-list-get-item-end-before-blank (point) struct))
6323 (setq has-children (org-list-has-child-p (point) struct)))
6324 (org-back-to-heading)
6325 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6326 (setq eos (save-excursion
6327 (org-end-of-subtree t)
6328 (unless (eobp)
6329 (skip-chars-forward " \t\n"))
6330 (if (eobp) (point) (1- (point)))))
6331 (setq has-children
6332 (or (save-excursion
6333 (let ((level (funcall outline-level)))
6334 (outline-next-heading)
6335 (and (org-at-heading-p t)
6336 (> (funcall outline-level) level))))
6337 (save-excursion
6338 (org-list-search-forward (org-item-beginning-re) eos t)))))
6339 ;; Determine end invisible part of buffer (EOL)
6340 (beginning-of-line 2)
6341 ;; XEmacs doesn't have `next-single-char-property-change'
6342 (if (featurep 'xemacs)
6343 (while (and (not (eobp)) ;; this is like `next-line'
6344 (get-char-property (1- (point)) 'invisible))
6345 (beginning-of-line 2))
6346 (while (and (not (eobp)) ;; this is like `next-line'
6347 (get-char-property (1- (point)) 'invisible))
6348 (goto-char (next-single-char-property-change (point) 'invisible))
6349 (and (eolp) (beginning-of-line 2))))
6350 (setq eol (point)))
6351 ;; Find out what to do next and set `this-command'
6352 (cond
6353 ((= eos eoh)
6354 ;; Nothing is hidden behind this heading
6355 (run-hook-with-args 'org-pre-cycle-hook 'empty)
6356 (message "EMPTY ENTRY")
6357 (setq org-cycle-subtree-status nil)
6358 (save-excursion
6359 (goto-char eos)
6360 (outline-next-heading)
6361 (if (outline-invisible-p) (org-flag-heading nil))))
6362 ((and (or (>= eol eos)
6363 (not (string-match "\\S-" (buffer-substring eol eos))))
6364 (or has-children
6365 (not (setq children-skipped
6366 org-cycle-skip-children-state-if-no-children))))
6367 ;; Entire subtree is hidden in one line: children view
6368 (run-hook-with-args 'org-pre-cycle-hook 'children)
6369 (if (org-at-item-p)
6370 (org-list-set-item-visibility (point-at-bol) struct 'children)
6371 (org-show-entry)
6372 (org-with-limited-levels (show-children))
6373 ;; FIXME: This slows down the func way too much.
6374 ;; How keep drawers hidden in subtree anyway?
6375 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6376 ;; (org-cycle-hide-drawers 'subtree))
6378 ;; Fold every list in subtree to top-level items.
6379 (when (eq org-cycle-include-plain-lists 'integrate)
6380 (save-excursion
6381 (org-back-to-heading)
6382 (while (org-list-search-forward (org-item-beginning-re) eos t)
6383 (beginning-of-line 1)
6384 (let* ((struct (org-list-struct))
6385 (prevs (org-list-prevs-alist struct))
6386 (end (org-list-get-bottom-point struct)))
6387 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6388 (org-list-get-all-items (point) struct prevs))
6389 (goto-char end))))))
6390 (message "CHILDREN")
6391 (save-excursion
6392 (goto-char eos)
6393 (outline-next-heading)
6394 (if (outline-invisible-p) (org-flag-heading nil)))
6395 (setq org-cycle-subtree-status 'children)
6396 (run-hook-with-args 'org-cycle-hook 'children))
6397 ((or children-skipped
6398 (and (eq last-command this-command)
6399 (eq org-cycle-subtree-status 'children)))
6400 ;; We just showed the children, or no children are there,
6401 ;; now show everything.
6402 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
6403 (outline-flag-region eoh eos nil)
6404 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6405 (setq org-cycle-subtree-status 'subtree)
6406 (run-hook-with-args 'org-cycle-hook 'subtree))
6408 ;; Default action: hide the subtree.
6409 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6410 (outline-flag-region eoh eos t)
6411 (message "FOLDED")
6412 (setq org-cycle-subtree-status 'folded)
6413 (run-hook-with-args 'org-cycle-hook 'folded)))))
6415 ;;;###autoload
6416 (defun org-global-cycle (&optional arg)
6417 "Cycle the global visibility. For details see `org-cycle'.
6418 With \\[universal-argument] prefix arg, switch to startup visibility.
6419 With a numeric prefix, show all headlines up to that level."
6420 (interactive "P")
6421 (let ((org-cycle-include-plain-lists
6422 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6423 (cond
6424 ((integerp arg)
6425 (show-all)
6426 (hide-sublevels arg)
6427 (setq org-cycle-global-status 'contents))
6428 ((equal arg '(4))
6429 (org-set-startup-visibility)
6430 (message "Startup visibility, plus VISIBILITY properties."))
6432 (org-cycle '(4))))))
6434 (defun org-set-startup-visibility ()
6435 "Set the visibility required by startup options and properties."
6436 (cond
6437 ((eq org-startup-folded t)
6438 (org-cycle '(4)))
6439 ((eq org-startup-folded 'content)
6440 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6441 (org-cycle '(4)) (org-cycle '(4)))))
6442 (unless (eq org-startup-folded 'showeverything)
6443 (if org-hide-block-startup (org-hide-block-all))
6444 (org-set-visibility-according-to-property 'no-cleanup)
6445 (org-cycle-hide-archived-subtrees 'all)
6446 (org-cycle-hide-drawers 'all)
6447 (org-cycle-show-empty-lines t)))
6449 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6450 "Switch subtree visibilities according to :VISIBILITY: property."
6451 (interactive)
6452 (let (org-show-entry-below state)
6453 (save-excursion
6454 (goto-char (point-min))
6455 (while (re-search-forward
6456 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6457 nil t)
6458 (setq state (match-string 1))
6459 (save-excursion
6460 (org-back-to-heading t)
6461 (hide-subtree)
6462 (org-reveal)
6463 (cond
6464 ((equal state '("fold" "folded"))
6465 (hide-subtree))
6466 ((equal state "children")
6467 (org-show-hidden-entry)
6468 (show-children))
6469 ((equal state "content")
6470 (save-excursion
6471 (save-restriction
6472 (org-narrow-to-subtree)
6473 (org-content))))
6474 ((member state '("all" "showall"))
6475 (show-subtree)))))
6476 (unless no-cleanup
6477 (org-cycle-hide-archived-subtrees 'all)
6478 (org-cycle-hide-drawers 'all)
6479 (org-cycle-show-empty-lines 'all)))))
6481 ;; This function uses outline-regexp instead of the more fundamental
6482 ;; org-outline-regexp so that org-cycle-global works outside of Org
6483 ;; buffers, where outline-regexp is needed.
6484 (defun org-overview ()
6485 "Switch to overview mode, showing only top-level headlines.
6486 Really, this shows all headlines with level equal or greater than the level
6487 of the first headline in the buffer. This is important, because if the
6488 first headline is not level one, then (hide-sublevels 1) gives confusing
6489 results."
6490 (interactive)
6491 (let ((level (save-excursion
6492 (goto-char (point-min))
6493 (if (re-search-forward (concat "^" outline-regexp) nil t)
6494 (progn
6495 (goto-char (match-beginning 0))
6496 (funcall outline-level))))))
6497 (and level (hide-sublevels level))))
6499 (defun org-content (&optional arg)
6500 "Show all headlines in the buffer, like a table of contents.
6501 With numerical argument N, show content up to level N."
6502 (interactive "P")
6503 (save-excursion
6504 ;; Visit all headings and show their offspring
6505 (and (integerp arg) (org-overview))
6506 (goto-char (point-max))
6507 (catch 'exit
6508 (while (and (progn (condition-case nil
6509 (outline-previous-visible-heading 1)
6510 (error (goto-char (point-min))))
6512 (looking-at org-outline-regexp))
6513 (if (integerp arg)
6514 (show-children (1- arg))
6515 (show-branches))
6516 (if (bobp) (throw 'exit nil))))))
6519 (defun org-optimize-window-after-visibility-change (state)
6520 "Adjust the window after a change in outline visibility.
6521 This function is the default value of the hook `org-cycle-hook'."
6522 (when (get-buffer-window (current-buffer))
6523 (cond
6524 ((eq state 'content) nil)
6525 ((eq state 'all) nil)
6526 ((eq state 'folded) nil)
6527 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6528 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6530 (defun org-remove-empty-overlays-at (pos)
6531 "Remove outline overlays that do not contain non-white stuff."
6532 (mapc
6533 (lambda (o)
6534 (and (eq 'outline (overlay-get o 'invisible))
6535 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6536 (overlay-end o))))
6537 (delete-overlay o)))
6538 (overlays-at pos)))
6540 (defun org-clean-visibility-after-subtree-move ()
6541 "Fix visibility issues after moving a subtree."
6542 ;; First, find a reasonable region to look at:
6543 ;; Start two siblings above, end three below
6544 (let* ((beg (save-excursion
6545 (and (org-get-last-sibling)
6546 (org-get-last-sibling))
6547 (point)))
6548 (end (save-excursion
6549 (and (org-get-next-sibling)
6550 (org-get-next-sibling)
6551 (org-get-next-sibling))
6552 (if (org-at-heading-p)
6553 (point-at-eol)
6554 (point))))
6555 (level (looking-at "\\*+"))
6556 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6557 (save-excursion
6558 (save-restriction
6559 (narrow-to-region beg end)
6560 (when re
6561 ;; Properly fold already folded siblings
6562 (goto-char (point-min))
6563 (while (re-search-forward re nil t)
6564 (if (and (not (outline-invisible-p))
6565 (save-excursion
6566 (goto-char (point-at-eol)) (outline-invisible-p)))
6567 (hide-entry))))
6568 (org-cycle-show-empty-lines 'overview)
6569 (org-cycle-hide-drawers 'overview)))))
6571 (defun org-cycle-show-empty-lines (state)
6572 "Show empty lines above all visible headlines.
6573 The region to be covered depends on STATE when called through
6574 `org-cycle-hook'. Lisp program can use t for STATE to get the
6575 entire buffer covered. Note that an empty line is only shown if there
6576 are at least `org-cycle-separator-lines' empty lines before the headline."
6577 (when (not (= org-cycle-separator-lines 0))
6578 (save-excursion
6579 (let* ((n (abs org-cycle-separator-lines))
6580 (re (cond
6581 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6582 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6583 (t (let ((ns (number-to-string (- n 2))))
6584 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6585 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6586 beg end b e)
6587 (cond
6588 ((memq state '(overview contents t))
6589 (setq beg (point-min) end (point-max)))
6590 ((memq state '(children folded))
6591 (setq beg (point) end (progn (org-end-of-subtree t t)
6592 (beginning-of-line 2)
6593 (point)))))
6594 (when beg
6595 (goto-char beg)
6596 (while (re-search-forward re end t)
6597 (unless (get-char-property (match-end 1) 'invisible)
6598 (setq e (match-end 1))
6599 (if (< org-cycle-separator-lines 0)
6600 (setq b (save-excursion
6601 (goto-char (match-beginning 0))
6602 (org-back-over-empty-lines)
6603 (if (save-excursion
6604 (goto-char (max (point-min) (1- (point))))
6605 (org-at-heading-p))
6606 (1- (point))
6607 (point))))
6608 (setq b (match-beginning 1)))
6609 (outline-flag-region b e nil)))))))
6610 ;; Never hide empty lines at the end of the file.
6611 (save-excursion
6612 (goto-char (point-max))
6613 (outline-previous-heading)
6614 (outline-end-of-heading)
6615 (if (and (looking-at "[ \t\n]+")
6616 (= (match-end 0) (point-max)))
6617 (outline-flag-region (point) (match-end 0) nil))))
6619 (defun org-show-empty-lines-in-parent ()
6620 "Move to the parent and re-show empty lines before visible headlines."
6621 (save-excursion
6622 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6623 (org-cycle-show-empty-lines context))))
6625 (defun org-files-list ()
6626 "Return `org-agenda-files' list, plus all open org-mode files.
6627 This is useful for operations that need to scan all of a user's
6628 open and agenda-wise Org files."
6629 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6630 (dolist (buf (buffer-list))
6631 (with-current-buffer buf
6632 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
6633 (let ((file (expand-file-name (buffer-file-name))))
6634 (unless (member file files)
6635 (push file files))))))
6636 files))
6638 (defsubst org-entry-beginning-position ()
6639 "Return the beginning position of the current entry."
6640 (save-excursion (outline-back-to-heading t) (point)))
6642 (defsubst org-entry-end-position ()
6643 "Return the end position of the current entry."
6644 (save-excursion (outline-next-heading) (point)))
6646 (defun org-cycle-hide-drawers (state)
6647 "Re-hide all drawers after a visibility state change."
6648 (when (and (derived-mode-p 'org-mode)
6649 (not (memq state '(overview folded contents))))
6650 (save-excursion
6651 (let* ((globalp (memq state '(contents all)))
6652 (beg (if globalp (point-min) (point)))
6653 (end (if globalp (point-max)
6654 (if (eq state 'children)
6655 (save-excursion (outline-next-heading) (point))
6656 (org-end-of-subtree t)))))
6657 (goto-char beg)
6658 (while (re-search-forward org-drawer-regexp end t)
6659 (org-flag-drawer t))))))
6661 (defun org-flag-drawer (flag)
6662 (save-excursion
6663 (beginning-of-line 1)
6664 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6665 (let ((b (match-end 0)))
6666 (if (re-search-forward
6667 "^[ \t]*:END:"
6668 (save-excursion (outline-next-heading) (point)) t)
6669 (outline-flag-region b (point-at-eol) flag)
6670 (error ":END: line missing at position %s" b))))))
6672 (defun org-subtree-end-visible-p ()
6673 "Is the end of the current subtree visible?"
6674 (pos-visible-in-window-p
6675 (save-excursion (org-end-of-subtree t) (point))))
6677 (defun org-first-headline-recenter (&optional N)
6678 "Move cursor to the first headline and recenter the headline.
6679 Optional argument N means put the headline into the Nth line of the window."
6680 (goto-char (point-min))
6681 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
6682 (beginning-of-line)
6683 (recenter (prefix-numeric-value N))))
6685 ;;; Saving and restoring visibility
6687 (defun org-outline-overlay-data (&optional use-markers)
6688 "Return a list of the locations of all outline overlays.
6689 These are overlays with the `invisible' property value `outline'.
6690 The return value is a list of cons cells, with start and stop
6691 positions for each overlay.
6692 If USE-MARKERS is set, return the positions as markers."
6693 (let (beg end)
6694 (save-excursion
6695 (save-restriction
6696 (widen)
6697 (delq nil
6698 (mapcar (lambda (o)
6699 (when (eq (overlay-get o 'invisible) 'outline)
6700 (setq beg (overlay-start o)
6701 end (overlay-end o))
6702 (and beg end (> end beg)
6703 (if use-markers
6704 (cons (move-marker (make-marker) beg)
6705 (move-marker (make-marker) end))
6706 (cons beg end)))))
6707 (overlays-in (point-min) (point-max))))))))
6709 (defun org-set-outline-overlay-data (data)
6710 "Create visibility overlays for all positions in DATA.
6711 DATA should have been made by `org-outline-overlay-data'."
6712 (let (o)
6713 (save-excursion
6714 (save-restriction
6715 (widen)
6716 (show-all)
6717 (mapc (lambda (c)
6718 (outline-flag-region (car c) (cdr c) t))
6719 data)))))
6721 ;;; Folding of blocks
6723 (defvar org-hide-block-overlays nil
6724 "Overlays hiding blocks.")
6725 (make-variable-buffer-local 'org-hide-block-overlays)
6727 (defun org-block-map (function &optional start end)
6728 "Call FUNCTION at the head of all source blocks in the current buffer.
6729 Optional arguments START and END can be used to limit the range."
6730 (let ((start (or start (point-min)))
6731 (end (or end (point-max))))
6732 (save-excursion
6733 (goto-char start)
6734 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
6735 (save-excursion
6736 (save-match-data
6737 (goto-char (match-beginning 0))
6738 (funcall function)))))))
6740 (defun org-hide-block-toggle-all ()
6741 "Toggle the visibility of all blocks in the current buffer."
6742 (org-block-map #'org-hide-block-toggle))
6744 (defun org-hide-block-all ()
6745 "Fold all blocks in the current buffer."
6746 (interactive)
6747 (org-show-block-all)
6748 (org-block-map #'org-hide-block-toggle-maybe))
6750 (defun org-show-block-all ()
6751 "Unfold all blocks in the current buffer."
6752 (interactive)
6753 (mapc 'delete-overlay org-hide-block-overlays)
6754 (setq org-hide-block-overlays nil))
6756 (defun org-hide-block-toggle-maybe ()
6757 "Toggle visibility of block at point."
6758 (interactive)
6759 (let ((case-fold-search t))
6760 (if (save-excursion
6761 (beginning-of-line 1)
6762 (looking-at org-block-regexp))
6763 (progn (org-hide-block-toggle)
6764 t) ;; to signal that we took action
6765 nil))) ;; to signal that we did not
6767 (defun org-hide-block-toggle (&optional force)
6768 "Toggle the visibility of the current block."
6769 (interactive)
6770 (save-excursion
6771 (beginning-of-line)
6772 (if (re-search-forward org-block-regexp nil t)
6773 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
6774 (end (match-end 0)) ;; end of entire body
6776 (if (memq t (mapcar (lambda (overlay)
6777 (eq (overlay-get overlay 'invisible)
6778 'org-hide-block))
6779 (overlays-at start)))
6780 (if (or (not force) (eq force 'off))
6781 (mapc (lambda (ov)
6782 (when (member ov org-hide-block-overlays)
6783 (setq org-hide-block-overlays
6784 (delq ov org-hide-block-overlays)))
6785 (when (eq (overlay-get ov 'invisible)
6786 'org-hide-block)
6787 (delete-overlay ov)))
6788 (overlays-at start)))
6789 (setq ov (make-overlay start end))
6790 (overlay-put ov 'invisible 'org-hide-block)
6791 ;; make the block accessible to isearch
6792 (overlay-put
6793 ov 'isearch-open-invisible
6794 (lambda (ov)
6795 (when (member ov org-hide-block-overlays)
6796 (setq org-hide-block-overlays
6797 (delq ov org-hide-block-overlays)))
6798 (when (eq (overlay-get ov 'invisible)
6799 'org-hide-block)
6800 (delete-overlay ov))))
6801 (push ov org-hide-block-overlays)))
6802 (error "Not looking at a source block"))))
6804 ;; org-tab-after-check-for-cycling-hook
6805 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
6806 ;; Remove overlays when changing major mode
6807 (add-hook 'org-mode-hook
6808 (lambda () (org-add-hook 'change-major-mode-hook
6809 'org-show-block-all 'append 'local)))
6811 ;;; Org-goto
6813 (defvar org-goto-window-configuration nil)
6814 (defvar org-goto-marker nil)
6815 (defvar org-goto-map
6816 (let ((map (make-sparse-keymap)))
6817 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
6818 (while (setq cmd (pop cmds))
6819 (substitute-key-definition cmd cmd map global-map)))
6820 (suppress-keymap map)
6821 (org-defkey map "\C-m" 'org-goto-ret)
6822 (org-defkey map [(return)] 'org-goto-ret)
6823 (org-defkey map [(left)] 'org-goto-left)
6824 (org-defkey map [(right)] 'org-goto-right)
6825 (org-defkey map [(control ?g)] 'org-goto-quit)
6826 (org-defkey map "\C-i" 'org-cycle)
6827 (org-defkey map [(tab)] 'org-cycle)
6828 (org-defkey map [(down)] 'outline-next-visible-heading)
6829 (org-defkey map [(up)] 'outline-previous-visible-heading)
6830 (if org-goto-auto-isearch
6831 (if (fboundp 'define-key-after)
6832 (define-key-after map [t] 'org-goto-local-auto-isearch)
6833 nil)
6834 (org-defkey map "q" 'org-goto-quit)
6835 (org-defkey map "n" 'outline-next-visible-heading)
6836 (org-defkey map "p" 'outline-previous-visible-heading)
6837 (org-defkey map "f" 'outline-forward-same-level)
6838 (org-defkey map "b" 'outline-backward-same-level)
6839 (org-defkey map "u" 'outline-up-heading))
6840 (org-defkey map "/" 'org-occur)
6841 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
6842 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
6843 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
6844 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
6845 (org-defkey map "\C-c\C-u" 'outline-up-heading)
6846 map))
6848 (defconst org-goto-help
6849 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
6850 RET=jump to location [Q]uit and return to previous location
6851 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
6853 (defvar org-goto-start-pos) ; dynamically scoped parameter
6855 ;; FIXME: Docstring does not mention both interfaces
6856 (defun org-goto (&optional alternative-interface)
6857 "Look up a different location in the current file, keeping current visibility.
6859 When you want look-up or go to a different location in a
6860 document, the fastest way is often to fold the entire buffer and
6861 then dive into the tree. This method has the disadvantage, that
6862 the previous location will be folded, which may not be what you
6863 want.
6865 This command works around this by showing a copy of the current
6866 buffer in an indirect buffer, in overview mode. You can dive
6867 into the tree in that copy, use org-occur and incremental search
6868 to find a location. When pressing RET or `Q', the command
6869 returns to the original buffer in which the visibility is still
6870 unchanged. After RET it will also jump to the location selected
6871 in the indirect buffer and expose the headline hierarchy above.
6873 With a prefix argument, use the alternative interface: e.g. if
6874 `org-goto-interface' is 'outline use 'outline-path-completion."
6875 (interactive "P")
6876 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
6877 (org-refile-use-outline-path t)
6878 (org-refile-target-verify-function nil)
6879 (interface
6880 (if (not alternative-interface)
6881 org-goto-interface
6882 (if (eq org-goto-interface 'outline)
6883 'outline-path-completion
6884 'outline)))
6885 (org-goto-start-pos (point))
6886 (selected-point
6887 (if (eq interface 'outline)
6888 (car (org-get-location (current-buffer) org-goto-help))
6889 (let ((pa (org-refile-get-location "Goto" nil nil t)))
6890 (org-refile-check-position pa)
6891 (nth 3 pa)))))
6892 (if selected-point
6893 (progn
6894 (org-mark-ring-push org-goto-start-pos)
6895 (goto-char selected-point)
6896 (if (or (outline-invisible-p) (org-invisible-p2))
6897 (org-show-context 'org-goto)))
6898 (message "Quit"))))
6900 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
6901 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
6902 (defvar org-goto-local-auto-isearch-map) ; defined below
6904 (defun org-get-location (buf help)
6905 "Let the user select a location in the Org-mode buffer BUF.
6906 This function uses a recursive edit. It returns the selected position
6907 or nil."
6908 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
6909 (isearch-hide-immediately nil)
6910 (isearch-search-fun-function
6911 (lambda () 'org-goto-local-search-headings))
6912 (org-goto-selected-point org-goto-exit-command)
6913 (pop-up-frames nil)
6914 (special-display-buffer-names nil)
6915 (special-display-regexps nil)
6916 (special-display-function nil))
6917 (save-excursion
6918 (save-window-excursion
6919 (delete-other-windows)
6920 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
6921 (org-pop-to-buffer-same-window
6922 (condition-case nil
6923 (make-indirect-buffer (current-buffer) "*org-goto*")
6924 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
6925 (with-output-to-temp-buffer "*Help*"
6926 (princ help))
6927 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
6928 (setq buffer-read-only nil)
6929 (let ((org-startup-truncated t)
6930 (org-startup-folded nil)
6931 (org-startup-align-all-tables nil))
6932 (org-mode)
6933 (org-overview))
6934 (setq buffer-read-only t)
6935 (if (and (boundp 'org-goto-start-pos)
6936 (integer-or-marker-p org-goto-start-pos))
6937 (let ((org-show-hierarchy-above t)
6938 (org-show-siblings t)
6939 (org-show-following-heading t))
6940 (goto-char org-goto-start-pos)
6941 (and (outline-invisible-p) (org-show-context)))
6942 (goto-char (point-min)))
6943 (let (org-special-ctrl-a/e) (org-beginning-of-line))
6944 (message "Select location and press RET")
6945 (use-local-map org-goto-map)
6946 (recursive-edit)
6948 (kill-buffer "*org-goto*")
6949 (cons org-goto-selected-point org-goto-exit-command)))
6951 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
6952 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
6953 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
6954 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
6956 (defun org-goto-local-search-headings (string bound noerror)
6957 "Search and make sure that any matches are in headlines."
6958 (catch 'return
6959 (while (if isearch-forward
6960 (search-forward string bound noerror)
6961 (search-backward string bound noerror))
6962 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
6963 (and (member :headline context)
6964 (not (member :tags context))))
6965 (throw 'return (point))))))
6967 (defun org-goto-local-auto-isearch ()
6968 "Start isearch."
6969 (interactive)
6970 (goto-char (point-min))
6971 (let ((keys (this-command-keys)))
6972 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
6973 (isearch-mode t)
6974 (isearch-process-search-char (string-to-char keys)))))
6976 (defun org-goto-ret (&optional arg)
6977 "Finish `org-goto' by going to the new location."
6978 (interactive "P")
6979 (setq org-goto-selected-point (point)
6980 org-goto-exit-command 'return)
6981 (throw 'exit nil))
6983 (defun org-goto-left ()
6984 "Finish `org-goto' by going to the new location."
6985 (interactive)
6986 (if (org-at-heading-p)
6987 (progn
6988 (beginning-of-line 1)
6989 (setq org-goto-selected-point (point)
6990 org-goto-exit-command 'left)
6991 (throw 'exit nil))
6992 (error "Not on a heading")))
6994 (defun org-goto-right ()
6995 "Finish `org-goto' by going to the new location."
6996 (interactive)
6997 (if (org-at-heading-p)
6998 (progn
6999 (setq org-goto-selected-point (point)
7000 org-goto-exit-command 'right)
7001 (throw 'exit nil))
7002 (error "Not on a heading")))
7004 (defun org-goto-quit ()
7005 "Finish `org-goto' without cursor motion."
7006 (interactive)
7007 (setq org-goto-selected-point nil)
7008 (setq org-goto-exit-command 'quit)
7009 (throw 'exit nil))
7011 ;;; Indirect buffer display of subtrees
7013 (defvar org-indirect-dedicated-frame nil
7014 "This is the frame being used for indirect tree display.")
7015 (defvar org-last-indirect-buffer nil)
7017 (defun org-tree-to-indirect-buffer (&optional arg)
7018 "Create indirect buffer and narrow it to current subtree.
7019 With numerical prefix ARG, go up to this level and then take that tree.
7020 If ARG is negative, go up that many levels.
7021 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7022 indirect buffer previously made with this command, to avoid proliferation of
7023 indirect buffers. However, when you call the command with a \
7024 \\[universal-argument] prefix, or
7025 when `org-indirect-buffer-display' is `new-frame', the last buffer
7026 is kept so that you can work with several indirect buffers at the same time.
7027 If `org-indirect-buffer-display' is `dedicated-frame', the \
7028 \\[universal-argument] prefix also
7029 requests that a new frame be made for the new buffer, so that the dedicated
7030 frame is not changed."
7031 (interactive "P")
7032 (let ((cbuf (current-buffer))
7033 (cwin (selected-window))
7034 (pos (point))
7035 beg end level heading ibuf)
7036 (save-excursion
7037 (org-back-to-heading t)
7038 (when (numberp arg)
7039 (setq level (org-outline-level))
7040 (if (< arg 0) (setq arg (+ level arg)))
7041 (while (> (setq level (org-outline-level)) arg)
7042 (outline-up-heading 1 t)))
7043 (setq beg (point)
7044 heading (org-get-heading))
7045 (org-end-of-subtree t t)
7046 (if (org-at-heading-p) (backward-char 1))
7047 (setq end (point)))
7048 (if (and (buffer-live-p org-last-indirect-buffer)
7049 (not (eq org-indirect-buffer-display 'new-frame))
7050 (not arg))
7051 (kill-buffer org-last-indirect-buffer))
7052 (setq ibuf (org-get-indirect-buffer cbuf)
7053 org-last-indirect-buffer ibuf)
7054 (cond
7055 ((or (eq org-indirect-buffer-display 'new-frame)
7056 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7057 (select-frame (make-frame))
7058 (delete-other-windows)
7059 (org-pop-to-buffer-same-window ibuf)
7060 (org-set-frame-title heading))
7061 ((eq org-indirect-buffer-display 'dedicated-frame)
7062 (raise-frame
7063 (select-frame (or (and org-indirect-dedicated-frame
7064 (frame-live-p org-indirect-dedicated-frame)
7065 org-indirect-dedicated-frame)
7066 (setq org-indirect-dedicated-frame (make-frame)))))
7067 (delete-other-windows)
7068 (org-pop-to-buffer-same-window ibuf)
7069 (org-set-frame-title (concat "Indirect: " heading)))
7070 ((eq org-indirect-buffer-display 'current-window)
7071 (org-pop-to-buffer-same-window ibuf))
7072 ((eq org-indirect-buffer-display 'other-window)
7073 (pop-to-buffer ibuf))
7074 (t (error "Invalid value")))
7075 (if (featurep 'xemacs)
7076 (save-excursion (org-mode) (turn-on-font-lock)))
7077 (narrow-to-region beg end)
7078 (show-all)
7079 (goto-char pos)
7080 (run-hook-with-args 'org-cycle-hook 'all)
7081 (and (window-live-p cwin) (select-window cwin))))
7083 (defun org-get-indirect-buffer (&optional buffer)
7084 (setq buffer (or buffer (current-buffer)))
7085 (let ((n 1) (base (buffer-name buffer)) bname)
7086 (while (buffer-live-p
7087 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7088 (setq n (1+ n)))
7089 (condition-case nil
7090 (make-indirect-buffer buffer bname 'clone)
7091 (error (make-indirect-buffer buffer bname)))))
7093 (defun org-set-frame-title (title)
7094 "Set the title of the current frame to the string TITLE."
7095 ;; FIXME: how to name a single frame in XEmacs???
7096 (unless (featurep 'xemacs)
7097 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7099 ;;;; Structure editing
7101 ;;; Inserting headlines
7103 (defun org-previous-line-empty-p ()
7104 (save-excursion
7105 (and (not (bobp))
7106 (or (beginning-of-line 0) t)
7107 (save-match-data
7108 (looking-at "[ \t]*$")))))
7110 (defun org-insert-heading (&optional force-heading invisible-ok)
7111 "Insert a new heading or item with same depth at point.
7112 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
7113 If point is at the beginning of a headline, insert a sibling before the
7114 current headline. If point is not at the beginning, split the line,
7115 create the new headline with the text in the current line after point
7116 \(but see also the variable `org-M-RET-may-split-line').
7118 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7119 This is important for non-interactive uses of the command."
7120 (interactive "P")
7121 (if (or (= (buffer-size) 0)
7122 (and (not (save-excursion
7123 (and (ignore-errors (org-back-to-heading invisible-ok))
7124 (org-at-heading-p))))
7125 (or force-heading (not (org-in-item-p)))))
7126 (progn
7127 (insert "\n* ")
7128 (run-hooks 'org-insert-heading-hook))
7129 (when (or force-heading (not (org-insert-item)))
7130 (let* ((empty-line-p nil)
7131 (level nil)
7132 (on-heading (org-at-heading-p))
7133 (head (save-excursion
7134 (condition-case nil
7135 (progn
7136 (org-back-to-heading invisible-ok)
7137 (when (and (not on-heading)
7138 (featurep 'org-inlinetask)
7139 (integerp org-inlinetask-min-level)
7140 (>= (length (match-string 0))
7141 org-inlinetask-min-level))
7142 ;; Find a heading level before the inline task
7143 (while (and (setq level (org-up-heading-safe))
7144 (>= level org-inlinetask-min-level)))
7145 (if (org-at-heading-p)
7146 (org-back-to-heading invisible-ok)
7147 (error "This should not happen")))
7148 (setq empty-line-p (org-previous-line-empty-p))
7149 (match-string 0))
7150 (error "*"))))
7151 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7152 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7153 pos hide-previous previous-pos)
7154 (cond
7155 ((and (org-at-heading-p) (bolp)
7156 (or (bobp)
7157 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
7158 ;; insert before the current line
7159 (open-line (if blank 2 1)))
7160 ((and (bolp)
7161 (not org-insert-heading-respect-content)
7162 (or (bobp)
7163 (save-excursion
7164 (backward-char 1) (not (outline-invisible-p)))))
7165 ;; insert right here
7166 nil)
7168 ;; somewhere in the line
7169 (save-excursion
7170 (setq previous-pos (point-at-bol))
7171 (end-of-line)
7172 (setq hide-previous (outline-invisible-p)))
7173 (and org-insert-heading-respect-content (org-show-subtree))
7174 (let ((split
7175 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
7176 (save-excursion
7177 (let ((p (point)))
7178 (goto-char (point-at-bol))
7179 (and (looking-at org-complex-heading-regexp)
7180 (match-beginning 4)
7181 (> p (match-beginning 4)))))))
7182 tags pos)
7183 (cond
7184 (org-insert-heading-respect-content
7185 (org-end-of-subtree nil t)
7186 (when (featurep 'org-inlinetask)
7187 (while (and (not (eobp))
7188 (looking-at "\\(\\*+\\)[ \t]+")
7189 (>= (length (match-string 1))
7190 org-inlinetask-min-level))
7191 (org-end-of-subtree nil t)))
7192 (or (bolp) (newline))
7193 (or (org-previous-line-empty-p)
7194 (and blank (newline)))
7195 (open-line 1))
7196 ((org-at-heading-p)
7197 (when hide-previous
7198 (show-children)
7199 (org-show-entry))
7200 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7201 (setq tags (and (match-end 2) (match-string 2)))
7202 (and (match-end 1)
7203 (delete-region (match-beginning 1) (match-end 1)))
7204 (setq pos (point-at-bol))
7205 (or split (end-of-line 1))
7206 (delete-horizontal-space)
7207 (if (string-match "\\`\\*+\\'"
7208 (buffer-substring (point-at-bol) (point)))
7209 (insert " "))
7210 (newline (if blank 2 1))
7211 (when tags
7212 (save-excursion
7213 (goto-char pos)
7214 (end-of-line 1)
7215 (insert " " tags)
7216 (org-set-tags nil 'align))))
7218 (or split (end-of-line 1))
7219 (newline (if blank 2 1)))))))
7220 (insert head) (just-one-space)
7221 (setq pos (point))
7222 (end-of-line 1)
7223 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7224 (when (and org-insert-heading-respect-content hide-previous)
7225 (save-excursion
7226 (goto-char previous-pos)
7227 (hide-subtree)))
7228 (run-hooks 'org-insert-heading-hook)))))
7230 (defun org-get-heading (&optional no-tags no-todo)
7231 "Return the heading of the current entry, without the stars.
7232 When NO-TAGS is non-nil, don't include tags.
7233 When NO-TODO is non-nil, don't include TODO keywords."
7234 (save-excursion
7235 (org-back-to-heading t)
7236 (cond
7237 ((and no-tags no-todo)
7238 (looking-at org-complex-heading-regexp)
7239 (match-string 4))
7240 (no-tags
7241 (looking-at (concat org-outline-regexp
7242 "\\(.*?\\)"
7243 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7244 (match-string 1))
7245 (no-todo
7246 (looking-at org-todo-line-regexp)
7247 (match-string 3))
7248 (t (looking-at org-heading-regexp)
7249 (match-string 2)))))
7251 (defun org-heading-components ()
7252 "Return the components of the current heading.
7253 This is a list with the following elements:
7254 - the level as an integer
7255 - the reduced level, different if `org-odd-levels-only' is set.
7256 - the TODO keyword, or nil
7257 - the priority character, like ?A, or nil if no priority is given
7258 - the headline text itself, or the tags string if no headline text
7259 - the tags string, or nil."
7260 (save-excursion
7261 (org-back-to-heading t)
7262 (if (let (case-fold-search) (looking-at org-complex-heading-regexp))
7263 (list (length (match-string 1))
7264 (org-reduced-level (length (match-string 1)))
7265 (org-match-string-no-properties 2)
7266 (and (match-end 3) (aref (match-string 3) 2))
7267 (org-match-string-no-properties 4)
7268 (org-match-string-no-properties 5)))))
7270 (defun org-get-entry ()
7271 "Get the entry text, after heading, entire subtree."
7272 (save-excursion
7273 (org-back-to-heading t)
7274 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7276 (defun org-insert-heading-after-current ()
7277 "Insert a new heading with same level as current, after current subtree."
7278 (interactive)
7279 (org-back-to-heading)
7280 (org-insert-heading)
7281 (org-move-subtree-down)
7282 (end-of-line 1))
7284 (defun org-insert-heading-respect-content ()
7285 (interactive)
7286 (let ((org-insert-heading-respect-content t))
7287 (org-insert-heading t)))
7289 (defun org-insert-todo-heading-respect-content (&optional force-state)
7290 (interactive "P")
7291 (let ((org-insert-heading-respect-content t))
7292 (org-insert-todo-heading force-state t)))
7294 (defun org-insert-todo-heading (arg &optional force-heading)
7295 "Insert a new heading with the same level and TODO state as current heading.
7296 If the heading has no TODO state, or if the state is DONE, use the first
7297 state (TODO by default). Also with prefix arg, force first state."
7298 (interactive "P")
7299 (when (or force-heading (not (org-insert-item 'checkbox)))
7300 (org-insert-heading force-heading)
7301 (save-excursion
7302 (org-back-to-heading)
7303 (outline-previous-heading)
7304 (looking-at org-todo-line-regexp))
7305 (let*
7306 ((new-mark-x
7307 (if (or arg
7308 (not (match-beginning 2))
7309 (member (match-string 2) org-done-keywords))
7310 (car org-todo-keywords-1)
7311 (match-string 2)))
7312 (new-mark
7314 (run-hook-with-args-until-success
7315 'org-todo-get-default-hook new-mark-x nil)
7316 new-mark-x)))
7317 (beginning-of-line 1)
7318 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7319 (if org-treat-insert-todo-heading-as-state-change
7320 (org-todo new-mark)
7321 (insert new-mark " "))))
7322 (when org-provide-todo-statistics
7323 (org-update-parent-todo-statistics))))
7325 (defun org-insert-subheading (arg)
7326 "Insert a new subheading and demote it.
7327 Works for outline headings and for plain lists alike."
7328 (interactive "P")
7329 (org-insert-heading arg)
7330 (cond
7331 ((org-at-heading-p) (org-do-demote))
7332 ((org-at-item-p) (org-indent-item))))
7334 (defun org-insert-todo-subheading (arg)
7335 "Insert a new subheading with TODO keyword or checkbox and demote it.
7336 Works for outline headings and for plain lists alike."
7337 (interactive "P")
7338 (org-insert-todo-heading arg)
7339 (cond
7340 ((org-at-heading-p) (org-do-demote))
7341 ((org-at-item-p) (org-indent-item))))
7343 ;;; Promotion and Demotion
7345 (defvar org-after-demote-entry-hook nil
7346 "Hook run after an entry has been demoted.
7347 The cursor will be at the beginning of the entry.
7348 When a subtree is being demoted, the hook will be called for each node.")
7350 (defvar org-after-promote-entry-hook nil
7351 "Hook run after an entry has been promoted.
7352 The cursor will be at the beginning of the entry.
7353 When a subtree is being promoted, the hook will be called for each node.")
7355 (defun org-promote-subtree ()
7356 "Promote the entire subtree.
7357 See also `org-promote'."
7358 (interactive)
7359 (save-excursion
7360 (org-with-limited-levels (org-map-tree 'org-promote)))
7361 (org-fix-position-after-promote))
7363 (defun org-demote-subtree ()
7364 "Demote the entire subtree. See `org-demote'.
7365 See also `org-promote'."
7366 (interactive)
7367 (save-excursion
7368 (org-with-limited-levels (org-map-tree 'org-demote)))
7369 (org-fix-position-after-promote))
7372 (defun org-do-promote ()
7373 "Promote the current heading higher up the tree.
7374 If the region is active in `transient-mark-mode', promote all headings
7375 in the region."
7376 (interactive)
7377 (save-excursion
7378 (if (org-region-active-p)
7379 (org-map-region 'org-promote (region-beginning) (region-end))
7380 (org-promote)))
7381 (org-fix-position-after-promote))
7383 (defun org-do-demote ()
7384 "Demote the current heading lower down the tree.
7385 If the region is active in `transient-mark-mode', demote all headings
7386 in the region."
7387 (interactive)
7388 (save-excursion
7389 (if (org-region-active-p)
7390 (org-map-region 'org-demote (region-beginning) (region-end))
7391 (org-demote)))
7392 (org-fix-position-after-promote))
7394 (defun org-fix-position-after-promote ()
7395 "Make sure that after pro/demotion cursor position is right."
7396 (let ((pos (point)))
7397 (when (save-excursion
7398 (beginning-of-line 1)
7399 (looking-at org-todo-line-regexp)
7400 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7401 (cond ((eobp) (insert " "))
7402 ((eolp) (insert " "))
7403 ((equal (char-after) ?\ ) (forward-char 1))))))
7405 (defun org-current-level ()
7406 "Return the level of the current entry, or nil if before the first headline.
7407 The level is the number of stars at the beginning of the headline."
7408 (save-excursion
7409 (org-with-limited-levels
7410 (if (ignore-errors (org-back-to-heading t))
7411 (funcall outline-level)))))
7413 (defun org-get-previous-line-level ()
7414 "Return the outline depth of the last headline before the current line.
7415 Returns 0 for the first headline in the buffer, and nil if before the
7416 first headline."
7417 (let ((current-level (org-current-level))
7418 (prev-level (when (> (line-number-at-pos) 1)
7419 (save-excursion
7420 (beginning-of-line 0)
7421 (org-current-level)))))
7422 (cond ((null current-level) nil) ; Before first headline
7423 ((null prev-level) 0) ; At first headline
7424 (prev-level))))
7426 (defun org-reduced-level (l)
7427 "Compute the effective level of a heading.
7428 This takes into account the setting of `org-odd-levels-only'."
7429 (cond
7430 ((zerop l) 0)
7431 (org-odd-levels-only (1+ (floor (/ l 2))))
7432 (t l)))
7434 (defun org-level-increment ()
7435 "Return the number of stars that will be added or removed at a
7436 time to headlines when structure editing, based on the value of
7437 `org-odd-levels-only'."
7438 (if org-odd-levels-only 2 1))
7440 (defun org-get-valid-level (level &optional change)
7441 "Rectify a level change under the influence of `org-odd-levels-only'
7442 LEVEL is a current level, CHANGE is by how much the level should be
7443 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7444 even level numbers will become the next higher odd number."
7445 (if org-odd-levels-only
7446 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7447 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7448 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7449 (max 1 (+ level (or change 0)))))
7451 (if (boundp 'define-obsolete-function-alias)
7452 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7453 (define-obsolete-function-alias 'org-get-legal-level
7454 'org-get-valid-level)
7455 (define-obsolete-function-alias 'org-get-legal-level
7456 'org-get-valid-level "23.1")))
7458 (defun org-promote ()
7459 "Promote the current heading higher up the tree.
7460 If the region is active in `transient-mark-mode', promote all headings
7461 in the region."
7462 (org-back-to-heading t)
7463 (let* ((level (save-match-data (funcall outline-level)))
7464 (after-change-functions (remove 'flyspell-after-change-function
7465 after-change-functions))
7466 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7467 (diff (abs (- level (length up-head) -1))))
7468 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
7469 (replace-match up-head nil t)
7470 ;; Fixup tag positioning
7471 (and org-auto-align-tags (org-set-tags nil t))
7472 (if org-adapt-indentation (org-fixup-indentation (- diff)))
7473 (run-hooks 'org-after-promote-entry-hook)))
7475 (defun org-demote ()
7476 "Demote the current heading lower down the tree.
7477 If the region is active in `transient-mark-mode', demote all headings
7478 in the region."
7479 (org-back-to-heading t)
7480 (let* ((level (save-match-data (funcall outline-level)))
7481 (after-change-functions (remove 'flyspell-after-change-function
7482 after-change-functions))
7483 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7484 (diff (abs (- level (length down-head) -1))))
7485 (replace-match down-head nil t)
7486 ;; Fixup tag positioning
7487 (and org-auto-align-tags (org-set-tags nil t))
7488 (if org-adapt-indentation (org-fixup-indentation diff))
7489 (run-hooks 'org-after-demote-entry-hook)))
7491 (defun org-cycle-level ()
7492 "Cycle the level of an empty headline through possible states.
7493 This goes first to child, then to parent, level, then up the hierarchy.
7494 After top level, it switches back to sibling level."
7495 (interactive)
7496 (let ((org-adapt-indentation nil))
7497 (when (org-point-at-end-of-empty-headline)
7498 (setq this-command 'org-cycle-level) ; Only needed for caching
7499 (let ((cur-level (org-current-level))
7500 (prev-level (org-get-previous-line-level)))
7501 (cond
7502 ;; If first headline in file, promote to top-level.
7503 ((= prev-level 0)
7504 (loop repeat (/ (- cur-level 1) (org-level-increment))
7505 do (org-do-promote)))
7506 ;; If same level as prev, demote one.
7507 ((= prev-level cur-level)
7508 (org-do-demote))
7509 ;; If parent is top-level, promote to top level if not already.
7510 ((= prev-level 1)
7511 (loop repeat (/ (- cur-level 1) (org-level-increment))
7512 do (org-do-promote)))
7513 ;; If top-level, return to prev-level.
7514 ((= cur-level 1)
7515 (loop repeat (/ (- prev-level 1) (org-level-increment))
7516 do (org-do-demote)))
7517 ;; If less than prev-level, promote one.
7518 ((< cur-level prev-level)
7519 (org-do-promote))
7520 ;; If deeper than prev-level, promote until higher than
7521 ;; prev-level.
7522 ((> cur-level prev-level)
7523 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7524 do (org-do-promote))))
7525 t))))
7527 (defun org-map-tree (fun)
7528 "Call FUN for every heading underneath the current one."
7529 (org-back-to-heading)
7530 (let ((level (funcall outline-level)))
7531 (save-excursion
7532 (funcall fun)
7533 (while (and (progn
7534 (outline-next-heading)
7535 (> (funcall outline-level) level))
7536 (not (eobp)))
7537 (funcall fun)))))
7539 (defun org-map-region (fun beg end)
7540 "Call FUN for every heading between BEG and END."
7541 (let ((org-ignore-region t))
7542 (save-excursion
7543 (setq end (copy-marker end))
7544 (goto-char beg)
7545 (if (and (re-search-forward org-outline-regexp-bol nil t)
7546 (< (point) end))
7547 (funcall fun))
7548 (while (and (progn
7549 (outline-next-heading)
7550 (< (point) end))
7551 (not (eobp)))
7552 (funcall fun)))))
7554 (defvar org-property-end-re) ; silence byte-compiler
7555 (defun org-fixup-indentation (diff)
7556 "Change the indentation in the current entry by DIFF.
7557 However, if any line in the current entry has no indentation, or if it
7558 would end up with no indentation after the change, nothing at all is done."
7559 (save-excursion
7560 (let ((end (save-excursion (outline-next-heading)
7561 (point-marker)))
7562 (prohibit (if (> diff 0)
7563 "^\\S-"
7564 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7565 col)
7566 (unless (save-excursion (end-of-line 1)
7567 (re-search-forward prohibit end t))
7568 (while (and (< (point) end)
7569 (re-search-forward "^[ \t]+" end t))
7570 (goto-char (match-end 0))
7571 (setq col (current-column))
7572 (if (< diff 0) (replace-match ""))
7573 (org-indent-to-column (+ diff col))))
7574 (move-marker end nil))))
7576 (defun org-convert-to-odd-levels ()
7577 "Convert an org-mode file with all levels allowed to one with odd levels.
7578 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7579 level 5 etc."
7580 (interactive)
7581 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7582 (let ((outline-level 'org-outline-level)
7583 (org-odd-levels-only nil) n)
7584 (save-excursion
7585 (goto-char (point-min))
7586 (while (re-search-forward "^\\*\\*+ " nil t)
7587 (setq n (- (length (match-string 0)) 2))
7588 (while (>= (setq n (1- n)) 0)
7589 (org-demote))
7590 (end-of-line 1))))))
7592 (defun org-convert-to-oddeven-levels ()
7593 "Convert an org-mode file with only odd levels to one with odd/even levels.
7594 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7595 file contains a section with an even level, conversion would
7596 destroy the structure of the file. An error is signaled in this
7597 case."
7598 (interactive)
7599 (goto-char (point-min))
7600 ;; First check if there are no even levels
7601 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7602 (org-show-context t)
7603 (error "Not all levels are odd in this file. Conversion not possible"))
7604 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
7605 (let ((outline-regexp org-outline-regexp)
7606 (outline-level 'org-outline-level)
7607 (org-odd-levels-only nil) n)
7608 (save-excursion
7609 (goto-char (point-min))
7610 (while (re-search-forward "^\\*\\*+ " nil t)
7611 (setq n (/ (1- (length (match-string 0))) 2))
7612 (while (>= (setq n (1- n)) 0)
7613 (org-promote))
7614 (end-of-line 1))))))
7616 (defun org-tr-level (n)
7617 "Make N odd if required."
7618 (if org-odd-levels-only (1+ (/ n 2)) n))
7620 ;;; Vertical tree motion, cutting and pasting of subtrees
7622 (defun org-move-subtree-up (&optional arg)
7623 "Move the current subtree up past ARG headlines of the same level."
7624 (interactive "p")
7625 (org-move-subtree-down (- (prefix-numeric-value arg))))
7627 (defun org-move-subtree-down (&optional arg)
7628 "Move the current subtree down past ARG headlines of the same level."
7629 (interactive "p")
7630 (setq arg (prefix-numeric-value arg))
7631 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
7632 'org-get-last-sibling))
7633 (ins-point (make-marker))
7634 (cnt (abs arg))
7635 (col (current-column))
7636 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
7637 ;; Select the tree
7638 (org-back-to-heading)
7639 (setq beg0 (point))
7640 (save-excursion
7641 (setq ne-beg (org-back-over-empty-lines))
7642 (setq beg (point)))
7643 (save-match-data
7644 (save-excursion (outline-end-of-heading)
7645 (setq folded (outline-invisible-p)))
7646 (outline-end-of-subtree))
7647 (outline-next-heading)
7648 (setq ne-end (org-back-over-empty-lines))
7649 (setq end (point))
7650 (goto-char beg0)
7651 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
7652 ;; include less whitespace
7653 (save-excursion
7654 (goto-char beg)
7655 (forward-line (- ne-beg ne-end))
7656 (setq beg (point))))
7657 ;; Find insertion point, with error handling
7658 (while (> cnt 0)
7659 (or (and (funcall movfunc) (looking-at org-outline-regexp))
7660 (progn (goto-char beg0)
7661 (error "Cannot move past superior level or buffer limit")))
7662 (setq cnt (1- cnt)))
7663 (if (> arg 0)
7664 ;; Moving forward - still need to move over subtree
7665 (progn (org-end-of-subtree t t)
7666 (save-excursion
7667 (org-back-over-empty-lines)
7668 (or (bolp) (newline)))))
7669 (setq ne-ins (org-back-over-empty-lines))
7670 (move-marker ins-point (point))
7671 (setq txt (buffer-substring beg end))
7672 (org-save-markers-in-region beg end)
7673 (delete-region beg end)
7674 (org-remove-empty-overlays-at beg)
7675 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
7676 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
7677 (and (not (bolp)) (looking-at "\n") (forward-char 1))
7678 (let ((bbb (point)))
7679 (insert-before-markers txt)
7680 (org-reinstall-markers-in-region bbb)
7681 (move-marker ins-point bbb))
7682 (or (bolp) (insert "\n"))
7683 (setq ins-end (point))
7684 (goto-char ins-point)
7685 (org-skip-whitespace)
7686 (when (and (< arg 0)
7687 (org-first-sibling-p)
7688 (> ne-ins ne-beg))
7689 ;; Move whitespace back to beginning
7690 (save-excursion
7691 (goto-char ins-end)
7692 (let ((kill-whole-line t))
7693 (kill-line (- ne-ins ne-beg)) (point)))
7694 (insert (make-string (- ne-ins ne-beg) ?\n)))
7695 (move-marker ins-point nil)
7696 (if folded
7697 (hide-subtree)
7698 (org-show-entry)
7699 (show-children)
7700 (org-cycle-hide-drawers 'children))
7701 (org-clean-visibility-after-subtree-move)
7702 ;; move back to the initial column we were at
7703 (move-to-column col)))
7705 (defvar org-subtree-clip ""
7706 "Clipboard for cut and paste of subtrees.
7707 This is actually only a copy of the kill, because we use the normal kill
7708 ring. We need it to check if the kill was created by `org-copy-subtree'.")
7710 (defvar org-subtree-clip-folded nil
7711 "Was the last copied subtree folded?
7712 This is used to fold the tree back after pasting.")
7714 (defun org-cut-subtree (&optional n)
7715 "Cut the current subtree into the clipboard.
7716 With prefix arg N, cut this many sequential subtrees.
7717 This is a short-hand for marking the subtree and then cutting it."
7718 (interactive "p")
7719 (org-copy-subtree n 'cut))
7721 (defun org-copy-subtree (&optional n cut force-store-markers)
7722 "Cut the current subtree into the clipboard.
7723 With prefix arg N, cut this many sequential subtrees.
7724 This is a short-hand for marking the subtree and then copying it.
7725 If CUT is non-nil, actually cut the subtree.
7726 If FORCE-STORE-MARKERS is non-nil, store the relative locations
7727 of some markers in the region, even if CUT is non-nil. This is
7728 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
7729 (interactive "p")
7730 (let (beg end folded (beg0 (point)))
7731 (if (org-called-interactively-p 'any)
7732 (org-back-to-heading nil) ; take what looks like a subtree
7733 (org-back-to-heading t)) ; take what is really there
7734 (org-back-over-empty-lines)
7735 (setq beg (point))
7736 (skip-chars-forward " \t\r\n")
7737 (save-match-data
7738 (save-excursion (outline-end-of-heading)
7739 (setq folded (outline-invisible-p)))
7740 (condition-case nil
7741 (org-forward-same-level (1- n) t)
7742 (error nil))
7743 (org-end-of-subtree t t))
7744 (org-back-over-empty-lines)
7745 (setq end (point))
7746 (goto-char beg0)
7747 (when (> end beg)
7748 (setq org-subtree-clip-folded folded)
7749 (when (or cut force-store-markers)
7750 (org-save-markers-in-region beg end))
7751 (if cut (kill-region beg end) (copy-region-as-kill beg end))
7752 (setq org-subtree-clip (current-kill 0))
7753 (message "%s: Subtree(s) with %d characters"
7754 (if cut "Cut" "Copied")
7755 (length org-subtree-clip)))))
7757 (defun org-paste-subtree (&optional level tree for-yank)
7758 "Paste the clipboard as a subtree, with modification of headline level.
7759 The entire subtree is promoted or demoted in order to match a new headline
7760 level.
7762 If the cursor is at the beginning of a headline, the same level as
7763 that headline is used to paste the tree
7765 If not, the new level is derived from the *visible* headings
7766 before and after the insertion point, and taken to be the inferior headline
7767 level of the two. So if the previous visible heading is level 3 and the
7768 next is level 4 (or vice versa), level 4 will be used for insertion.
7769 This makes sure that the subtree remains an independent subtree and does
7770 not swallow low level entries.
7772 You can also force a different level, either by using a numeric prefix
7773 argument, or by inserting the heading marker by hand. For example, if the
7774 cursor is after \"*****\", then the tree will be shifted to level 5.
7776 If optional TREE is given, use this text instead of the kill ring.
7778 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
7779 move back over whitespace before inserting, and move point to the end of
7780 the inserted text when done."
7781 (interactive "P")
7782 (setq tree (or tree (and kill-ring (current-kill 0))))
7783 (unless (org-kill-is-subtree-p tree)
7784 (error "%s"
7785 (substitute-command-keys
7786 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
7787 (org-with-limited-levels
7788 (let* ((visp (not (outline-invisible-p)))
7789 (txt tree)
7790 (^re_ "\\(\\*+\\)[ \t]*")
7791 (old-level (if (string-match org-outline-regexp-bol txt)
7792 (- (match-end 0) (match-beginning 0) 1)
7793 -1))
7794 (force-level (cond (level (prefix-numeric-value level))
7795 ((and (looking-at "[ \t]*$")
7796 (string-match
7797 "^\\*+$" (buffer-substring
7798 (point-at-bol) (point))))
7799 (- (match-end 1) (match-beginning 1)))
7800 ((and (bolp)
7801 (looking-at org-outline-regexp))
7802 (- (match-end 0) (point) 1))
7803 (t nil)))
7804 (previous-level (save-excursion
7805 (condition-case nil
7806 (progn
7807 (outline-previous-visible-heading 1)
7808 (if (looking-at ^re_)
7809 (- (match-end 0) (match-beginning 0) 1)
7811 (error 1))))
7812 (next-level (save-excursion
7813 (condition-case nil
7814 (progn
7815 (or (looking-at org-outline-regexp)
7816 (outline-next-visible-heading 1))
7817 (if (looking-at ^re_)
7818 (- (match-end 0) (match-beginning 0) 1)
7820 (error 1))))
7821 (new-level (or force-level (max previous-level next-level)))
7822 (shift (if (or (= old-level -1)
7823 (= new-level -1)
7824 (= old-level new-level))
7826 (- new-level old-level)))
7827 (delta (if (> shift 0) -1 1))
7828 (func (if (> shift 0) 'org-demote 'org-promote))
7829 (org-odd-levels-only nil)
7830 beg end newend)
7831 ;; Remove the forced level indicator
7832 (if force-level
7833 (delete-region (point-at-bol) (point)))
7834 ;; Paste
7835 (beginning-of-line (if (bolp) 1 2))
7836 (unless for-yank (org-back-over-empty-lines))
7837 (setq beg (point))
7838 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
7839 (insert-before-markers txt)
7840 (unless (string-match "\n\\'" txt) (insert "\n"))
7841 (setq newend (point))
7842 (org-reinstall-markers-in-region beg)
7843 (setq end (point))
7844 (goto-char beg)
7845 (skip-chars-forward " \t\n\r")
7846 (setq beg (point))
7847 (if (and (outline-invisible-p) visp)
7848 (save-excursion (outline-show-heading)))
7849 ;; Shift if necessary
7850 (unless (= shift 0)
7851 (save-restriction
7852 (narrow-to-region beg end)
7853 (while (not (= shift 0))
7854 (org-map-region func (point-min) (point-max))
7855 (setq shift (+ delta shift)))
7856 (goto-char (point-min))
7857 (setq newend (point-max))))
7858 (when (or (org-called-interactively-p 'interactive) for-yank)
7859 (message "Clipboard pasted as level %d subtree" new-level))
7860 (if (and (not for-yank) ; in this case, org-yank will decide about folding
7861 kill-ring
7862 (eq org-subtree-clip (current-kill 0))
7863 org-subtree-clip-folded)
7864 ;; The tree was folded before it was killed/copied
7865 (hide-subtree))
7866 (and for-yank (goto-char newend)))))
7868 (defun org-kill-is-subtree-p (&optional txt)
7869 "Check if the current kill is an outline subtree, or a set of trees.
7870 Returns nil if kill does not start with a headline, or if the first
7871 headline level is not the largest headline level in the tree.
7872 So this will actually accept several entries of equal levels as well,
7873 which is OK for `org-paste-subtree'.
7874 If optional TXT is given, check this string instead of the current kill."
7875 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
7876 (re (org-get-limited-outline-regexp))
7877 (^re (concat "^" re))
7878 (start-level (and kill
7879 (string-match
7880 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
7881 kill)
7882 (- (match-end 2) (match-beginning 2) 1)))
7883 (start (1+ (or (match-beginning 2) -1))))
7884 (if (not start-level)
7885 (progn
7886 nil) ;; does not even start with a heading
7887 (catch 'exit
7888 (while (setq start (string-match ^re kill (1+ start)))
7889 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
7890 (throw 'exit nil)))
7891 t))))
7893 (defvar org-markers-to-move nil
7894 "Markers that should be moved with a cut-and-paste operation.
7895 Those markers are stored together with their positions relative to
7896 the start of the region.")
7898 (defun org-save-markers-in-region (beg end)
7899 "Check markers in region.
7900 If these markers are between BEG and END, record their position relative
7901 to BEG, so that after moving the block of text, we can put the markers back
7902 into place.
7903 This function gets called just before an entry or tree gets cut from the
7904 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
7905 called immediately, to move the markers with the entries."
7906 (setq org-markers-to-move nil)
7907 (when (featurep 'org-clock)
7908 (org-clock-save-markers-for-cut-and-paste beg end))
7909 (when (featurep 'org-agenda)
7910 (org-agenda-save-markers-for-cut-and-paste beg end)))
7912 (defun org-check-and-save-marker (marker beg end)
7913 "Check if MARKER is between BEG and END.
7914 If yes, remember the marker and the distance to BEG."
7915 (when (and (marker-buffer marker)
7916 (equal (marker-buffer marker) (current-buffer)))
7917 (if (and (>= marker beg) (< marker end))
7918 (push (cons marker (- marker beg)) org-markers-to-move))))
7920 (defun org-reinstall-markers-in-region (beg)
7921 "Move all remembered markers to their position relative to BEG."
7922 (mapc (lambda (x)
7923 (move-marker (car x) (+ beg (cdr x))))
7924 org-markers-to-move)
7925 (setq org-markers-to-move nil))
7927 (defun org-narrow-to-subtree ()
7928 "Narrow buffer to the current subtree."
7929 (interactive)
7930 (save-excursion
7931 (save-match-data
7932 (org-with-limited-levels
7933 (narrow-to-region
7934 (progn (org-back-to-heading t) (point))
7935 (progn (org-end-of-subtree t t)
7936 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
7937 (point)))))))
7939 (defun org-narrow-to-block ()
7940 "Narrow buffer to the current block."
7941 (interactive)
7942 (let* ((case-fold-search t)
7943 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
7944 "^[ \t]*#\\+end_.*")))
7945 (if blockp
7946 (narrow-to-region (car blockp) (cdr blockp))
7947 (error "Not in a block"))))
7949 (eval-when-compile
7950 (defvar org-property-drawer-re))
7952 (defvar org-property-start-re) ;; defined below
7953 (defun org-clone-subtree-with-time-shift (n &optional shift)
7954 "Clone the task (subtree) at point N times.
7955 The clones will be inserted as siblings.
7957 In interactive use, the user will be prompted for the number of
7958 clones to be produced, and for a time SHIFT, which may be a
7959 repeater as used in time stamps, for example `+3d'.
7961 When a valid repeater is given and the entry contains any time
7962 stamps, the clones will become a sequence in time, with time
7963 stamps in the subtree shifted for each clone produced. If SHIFT
7964 is nil or the empty string, time stamps will be left alone. The
7965 ID property of the original subtree is removed.
7967 If the original subtree did contain time stamps with a repeater,
7968 the following will happen:
7969 - the repeater will be removed in each clone
7970 - an additional clone will be produced, with the current, unshifted
7971 date(s) in the entry.
7972 - the original entry will be placed *after* all the clones, with
7973 repeater intact.
7974 - the start days in the repeater in the original entry will be shifted
7975 to past the last clone.
7976 In this way you can spell out a number of instances of a repeating task,
7977 and still retain the repeater to cover future instances of the task."
7978 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
7979 (let (beg end template task idprop
7980 shift-n shift-what doshift nmin nmax (n-no-remove -1)
7981 (drawer-re org-drawer-regexp))
7982 (if (not (and (integerp n) (> n 0)))
7983 (error "Invalid number of replications %s" n))
7984 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
7985 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
7986 shift)))
7987 (error "Invalid shift specification %s" shift))
7988 (when doshift
7989 (setq shift-n (string-to-number (match-string 1 shift))
7990 shift-what (cdr (assoc (match-string 2 shift)
7991 '(("d" . day) ("w" . week)
7992 ("m" . month) ("y" . year))))))
7993 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
7994 (setq nmin 1 nmax n)
7995 (org-back-to-heading t)
7996 (setq beg (point))
7997 (setq idprop (org-entry-get nil "ID"))
7998 (org-end-of-subtree t t)
7999 (or (bolp) (insert "\n"))
8000 (setq end (point))
8001 (setq template (buffer-substring beg end))
8002 (when (and doshift
8003 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8004 (delete-region beg end)
8005 (setq end beg)
8006 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8007 (goto-char end)
8008 (loop for n from nmin to nmax do
8009 ;; prepare clone
8010 (with-temp-buffer
8011 (insert template)
8012 (org-mode)
8013 (goto-char (point-min))
8014 (org-show-subtree)
8015 (and idprop (if org-clone-delete-id
8016 (org-entry-delete nil "ID")
8017 (org-id-get-create t)))
8018 (unless (= n 0)
8019 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8020 (kill-whole-line))
8021 (goto-char (point-min))
8022 (while (re-search-forward drawer-re nil t)
8023 (mapc (lambda (d)
8024 (org-remove-empty-drawer-at d (point))) org-drawers)))
8025 (goto-char (point-min))
8026 (when doshift
8027 (while (re-search-forward org-ts-regexp-both nil t)
8028 (org-timestamp-change (* n shift-n) shift-what))
8029 (unless (= n n-no-remove)
8030 (goto-char (point-min))
8031 (while (re-search-forward org-ts-regexp nil t)
8032 (save-excursion
8033 (goto-char (match-beginning 0))
8034 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8035 (delete-region (match-beginning 1) (match-end 1)))))))
8036 (setq task (buffer-string)))
8037 (insert task))
8038 (goto-char beg)))
8040 ;;; Outline Sorting
8042 (defun org-sort (with-case)
8043 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8044 Optional argument WITH-CASE means sort case-sensitively."
8045 (interactive "P")
8046 (cond
8047 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8048 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8050 (org-call-with-arg 'org-sort-entries with-case))))
8052 (defun org-sort-remove-invisible (s)
8053 (remove-text-properties 0 (length s) org-rm-props s)
8054 (while (string-match org-bracket-link-regexp s)
8055 (setq s (replace-match (if (match-end 2)
8056 (match-string 3 s)
8057 (match-string 1 s)) t t s)))
8060 (defvar org-priority-regexp) ; defined later in the file
8062 (defvar org-after-sorting-entries-or-items-hook nil
8063 "Hook that is run after a bunch of entries or items have been sorted.
8064 When children are sorted, the cursor is in the parent line when this
8065 hook gets called. When a region or a plain list is sorted, the cursor
8066 will be in the first entry of the sorted region/list.")
8068 (defun org-sort-entries
8069 (&optional with-case sorting-type getkey-func compare-func property)
8070 "Sort entries on a certain level of an outline tree.
8071 If there is an active region, the entries in the region are sorted.
8072 Else, if the cursor is before the first entry, sort the top-level items.
8073 Else, the children of the entry at point are sorted.
8075 Sorting can be alphabetically, numerically, by date/time as given by
8076 a time stamp, by a property or by priority.
8078 The command prompts for the sorting type unless it has been given to the
8079 function through the SORTING-TYPE argument, which needs to be a character,
8080 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F). Here is the
8081 precise meaning of each character:
8083 n Numerically, by converting the beginning of the entry/item to a number.
8084 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8085 t By date/time, either the first active time stamp in the entry, or, if
8086 none exist, by the first inactive one.
8087 s By the scheduled date/time.
8088 d By deadline date/time.
8089 c By creation time, which is assumed to be the first inactive time stamp
8090 at the beginning of a line.
8091 p By priority according to the cookie.
8092 r By the value of a property.
8094 Capital letters will reverse the sort order.
8096 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8097 called with point at the beginning of the record. It must return either
8098 a string or a number that should serve as the sorting key for that record.
8100 Comparing entries ignores case by default. However, with an optional argument
8101 WITH-CASE, the sorting considers case as well."
8102 (interactive "P")
8103 (let ((case-func (if with-case 'identity 'downcase))
8104 start beg end stars re re2
8105 txt what tmp)
8106 ;; Find beginning and end of region to sort
8107 (cond
8108 ((org-region-active-p)
8109 ;; we will sort the region
8110 (setq end (region-end)
8111 what "region")
8112 (goto-char (region-beginning))
8113 (if (not (org-at-heading-p)) (outline-next-heading))
8114 (setq start (point)))
8115 ((or (org-at-heading-p)
8116 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8117 ;; we will sort the children of the current headline
8118 (org-back-to-heading)
8119 (setq start (point)
8120 end (progn (org-end-of-subtree t t)
8121 (or (bolp) (insert "\n"))
8122 (org-back-over-empty-lines)
8123 (point))
8124 what "children")
8125 (goto-char start)
8126 (show-subtree)
8127 (outline-next-heading))
8129 ;; we will sort the top-level entries in this file
8130 (goto-char (point-min))
8131 (or (org-at-heading-p) (outline-next-heading))
8132 (setq start (point))
8133 (goto-char (point-max))
8134 (beginning-of-line 1)
8135 (when (looking-at ".*?\\S-")
8136 ;; File ends in a non-white line
8137 (end-of-line 1)
8138 (insert "\n"))
8139 (setq end (point-max))
8140 (setq what "top-level")
8141 (goto-char start)
8142 (show-all)))
8144 (setq beg (point))
8145 (if (>= beg end) (error "Nothing to sort"))
8147 (looking-at "\\(\\*+\\)")
8148 (setq stars (match-string 1)
8149 re (concat "^" (regexp-quote stars) " +")
8150 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8151 txt (buffer-substring beg end))
8152 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8153 (if (and (not (equal stars "*")) (string-match re2 txt))
8154 (error "Region to sort contains a level above the first entry"))
8156 (unless sorting-type
8157 (message
8158 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8159 [t]ime [s]cheduled [d]eadline [c]reated
8160 A/N/T/S/D/C/P/O/F means reversed:"
8161 what)
8162 (setq sorting-type (read-char-exclusive))
8164 (and (= (downcase sorting-type) ?f)
8165 (setq getkey-func
8166 (org-icompleting-read "Sort using function: "
8167 obarray 'fboundp t nil nil))
8168 (setq getkey-func (intern getkey-func)))
8170 (and (= (downcase sorting-type) ?r)
8171 (setq property
8172 (org-icompleting-read "Property: "
8173 (mapcar 'list (org-buffer-property-keys t))
8174 nil t))))
8176 (message "Sorting entries...")
8178 (save-restriction
8179 (narrow-to-region start end)
8180 (let ((dcst (downcase sorting-type))
8181 (case-fold-search nil)
8182 (now (current-time)))
8183 (sort-subr
8184 (/= dcst sorting-type)
8185 ;; This function moves to the beginning character of the "record" to
8186 ;; be sorted.
8187 (lambda nil
8188 (if (re-search-forward re nil t)
8189 (goto-char (match-beginning 0))
8190 (goto-char (point-max))))
8191 ;; This function moves to the last character of the "record" being
8192 ;; sorted.
8193 (lambda nil
8194 (save-match-data
8195 (condition-case nil
8196 (outline-forward-same-level 1)
8197 (error
8198 (goto-char (point-max))))))
8199 ;; This function returns the value that gets sorted against.
8200 (lambda nil
8201 (cond
8202 ((= dcst ?n)
8203 (if (looking-at org-complex-heading-regexp)
8204 (string-to-number (match-string 4))
8205 nil))
8206 ((= dcst ?a)
8207 (if (looking-at org-complex-heading-regexp)
8208 (funcall case-func (match-string 4))
8209 nil))
8210 ((= dcst ?t)
8211 (let ((end (save-excursion (outline-next-heading) (point))))
8212 (if (or (re-search-forward org-ts-regexp end t)
8213 (re-search-forward org-ts-regexp-both end t))
8214 (org-time-string-to-seconds (match-string 0))
8215 (org-float-time now))))
8216 ((= dcst ?c)
8217 (let ((end (save-excursion (outline-next-heading) (point))))
8218 (if (re-search-forward
8219 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8220 end t)
8221 (org-time-string-to-seconds (match-string 0))
8222 (org-float-time now))))
8223 ((= dcst ?s)
8224 (let ((end (save-excursion (outline-next-heading) (point))))
8225 (if (re-search-forward org-scheduled-time-regexp end t)
8226 (org-time-string-to-seconds (match-string 1))
8227 (org-float-time now))))
8228 ((= dcst ?d)
8229 (let ((end (save-excursion (outline-next-heading) (point))))
8230 (if (re-search-forward org-deadline-time-regexp end t)
8231 (org-time-string-to-seconds (match-string 1))
8232 (org-float-time now))))
8233 ((= dcst ?p)
8234 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8235 (string-to-char (match-string 2))
8236 org-default-priority))
8237 ((= dcst ?r)
8238 (or (org-entry-get nil property) ""))
8239 ((= dcst ?o)
8240 (if (looking-at org-complex-heading-regexp)
8241 (- 9999 (length (member (match-string 2)
8242 org-todo-keywords-1)))))
8243 ((= dcst ?f)
8244 (if getkey-func
8245 (progn
8246 (setq tmp (funcall getkey-func))
8247 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8248 tmp)
8249 (error "Invalid key function `%s'" getkey-func)))
8250 (t (error "Invalid sorting type `%c'" sorting-type))))
8252 (cond
8253 ((= dcst ?a) 'string<)
8254 ((= dcst ?f) compare-func)
8255 ((member dcst '(?p ?t ?s ?d ?c)) '<)
8256 (t nil)))))
8257 (run-hooks 'org-after-sorting-entries-or-items-hook)
8258 (message "Sorting entries...done")))
8260 (defun org-do-sort (table what &optional with-case sorting-type)
8261 "Sort TABLE of WHAT according to SORTING-TYPE.
8262 The user will be prompted for the SORTING-TYPE if the call to this
8263 function does not specify it. WHAT is only for the prompt, to indicate
8264 what is being sorted. The sorting key will be extracted from
8265 the car of the elements of the table.
8266 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8267 (unless sorting-type
8268 (message
8269 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
8270 what)
8271 (setq sorting-type (read-char-exclusive)))
8272 (let ((dcst (downcase sorting-type))
8273 extractfun comparefun)
8274 ;; Define the appropriate functions
8275 (cond
8276 ((= dcst ?n)
8277 (setq extractfun 'string-to-number
8278 comparefun (if (= dcst sorting-type) '< '>)))
8279 ((= dcst ?a)
8280 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8281 (lambda(x) (downcase (org-sort-remove-invisible x))))
8282 comparefun (if (= dcst sorting-type)
8283 'string<
8284 (lambda (a b) (and (not (string< a b))
8285 (not (string= a b)))))))
8286 ((= dcst ?t)
8287 (setq extractfun
8288 (lambda (x)
8289 (if (or (string-match org-ts-regexp x)
8290 (string-match org-ts-regexp-both x))
8291 (org-float-time
8292 (org-time-string-to-time (match-string 0 x)))
8294 comparefun (if (= dcst sorting-type) '< '>)))
8295 (t (error "Invalid sorting type `%c'" sorting-type)))
8297 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8298 table)
8299 (lambda (a b) (funcall comparefun (car a) (car b))))))
8302 ;;; The orgstruct minor mode
8304 ;; Define a minor mode which can be used in other modes in order to
8305 ;; integrate the org-mode structure editing commands.
8307 ;; This is really a hack, because the org-mode structure commands use
8308 ;; keys which normally belong to the major mode. Here is how it
8309 ;; works: The minor mode defines all the keys necessary to operate the
8310 ;; structure commands, but wraps the commands into a function which
8311 ;; tests if the cursor is currently at a headline or a plain list
8312 ;; item. If that is the case, the structure command is used,
8313 ;; temporarily setting many Org-mode variables like regular
8314 ;; expressions for filling etc. However, when any of those keys is
8315 ;; used at a different location, function uses `key-binding' to look
8316 ;; up if the key has an associated command in another currently active
8317 ;; keymap (minor modes, major mode, global), and executes that
8318 ;; command. There might be problems if any of the keys is otherwise
8319 ;; used as a prefix key.
8321 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
8322 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
8323 ;; addresses this by checking explicitly for both bindings.
8325 (defvar orgstruct-mode-map (make-sparse-keymap)
8326 "Keymap for the minor `orgstruct-mode'.")
8328 (defvar org-local-vars nil
8329 "List of local variables, for use by `orgstruct-mode'.")
8331 ;;;###autoload
8332 (define-minor-mode orgstruct-mode
8333 "Toggle the minor mode `orgstruct-mode'.
8334 This mode is for using Org-mode structure commands in other
8335 modes. The following keys behave as if Org-mode were active, if
8336 the cursor is on a headline, or on a plain list item (both as
8337 defined by Org-mode).
8339 M-up Move entry/item up
8340 M-down Move entry/item down
8341 M-left Promote
8342 M-right Demote
8343 M-S-up Move entry/item up
8344 M-S-down Move entry/item down
8345 M-S-left Promote subtree
8346 M-S-right Demote subtree
8347 M-q Fill paragraph and items like in Org-mode
8348 C-c ^ Sort entries
8349 C-c - Cycle list bullet
8350 TAB Cycle item visibility
8351 M-RET Insert new heading/item
8352 S-M-RET Insert new TODO heading / Checkbox item
8353 C-c C-c Set tags / toggle checkbox"
8354 nil " OrgStruct" nil
8355 (org-load-modules-maybe)
8356 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
8358 ;;;###autoload
8359 (defun turn-on-orgstruct ()
8360 "Unconditionally turn on `orgstruct-mode'."
8361 (orgstruct-mode 1))
8363 (defvar org-fb-vars nil)
8364 (make-variable-buffer-local 'org-fb-vars)
8365 (defun orgstruct++-mode (&optional arg)
8366 "Toggle `orgstruct-mode', the enhanced version of it.
8367 In addition to setting orgstruct-mode, this also exports all indentation
8368 and autofilling variables from org-mode into the buffer. It will also
8369 recognize item context in multiline items.
8370 Note that turning off orgstruct-mode will *not* remove the
8371 indentation/paragraph settings. This can only be done by refreshing the
8372 major mode, for example with \\[normal-mode]."
8373 (interactive "P")
8374 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8375 (if (< arg 1)
8376 (progn (orgstruct-mode -1)
8377 (mapc (lambda(v)
8378 (org-set-local (car v)
8379 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8380 org-fb-vars))
8381 (orgstruct-mode 1)
8382 (setq org-fb-vars nil)
8383 (let (var val)
8384 (mapc
8385 (lambda (x)
8386 (when (string-match
8387 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
8388 (symbol-name (car x)))
8389 (setq var (car x) val (nth 1 x))
8390 (push (list var `(quote ,(eval var))) org-fb-vars)
8391 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8392 org-local-vars)
8393 (org-set-local 'orgstruct-is-++ t))))
8395 (defvar orgstruct-is-++ nil
8396 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8397 (make-variable-buffer-local 'orgstruct-is-++)
8399 ;;;###autoload
8400 (defun turn-on-orgstruct++ ()
8401 "Unconditionally turn on `orgstruct++-mode'."
8402 (orgstruct++-mode 1))
8404 (defun orgstruct-error ()
8405 "Error when there is no default binding for a structure key."
8406 (interactive)
8407 (error "This key has no function outside structure elements"))
8409 (defun orgstruct-setup ()
8410 "Setup orgstruct keymaps."
8411 (let ((nfunc 0)
8412 (bindings
8413 (list
8414 '([(meta up)] org-metaup)
8415 '([(meta down)] org-metadown)
8416 '([(meta left)] org-metaleft)
8417 '([(meta right)] org-metaright)
8418 '([(meta shift up)] org-shiftmetaup)
8419 '([(meta shift down)] org-shiftmetadown)
8420 '([(meta shift left)] org-shiftmetaleft)
8421 '([(meta shift right)] org-shiftmetaright)
8422 '([?\e (up)] org-metaup)
8423 '([?\e (down)] org-metadown)
8424 '([?\e (left)] org-metaleft)
8425 '([?\e (right)] org-metaright)
8426 '([?\e (shift up)] org-shiftmetaup)
8427 '([?\e (shift down)] org-shiftmetadown)
8428 '([?\e (shift left)] org-shiftmetaleft)
8429 '([?\e (shift right)] org-shiftmetaright)
8430 '([(shift up)] org-shiftup)
8431 '([(shift down)] org-shiftdown)
8432 '([(shift left)] org-shiftleft)
8433 '([(shift right)] org-shiftright)
8434 '("\C-c\C-c" org-ctrl-c-ctrl-c)
8435 '("\M-q" fill-paragraph)
8436 '("\C-c^" org-sort)
8437 '("\C-c-" org-cycle-list-bullet)))
8438 elt key fun cmd)
8439 (while (setq elt (pop bindings))
8440 (setq nfunc (1+ nfunc))
8441 (setq key (org-key (car elt))
8442 fun (nth 1 elt)
8443 cmd (orgstruct-make-binding fun nfunc key))
8444 (org-defkey orgstruct-mode-map key cmd))
8446 ;; Special treatment needed for TAB and RET
8447 (org-defkey orgstruct-mode-map [(tab)]
8448 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
8449 (org-defkey orgstruct-mode-map "\C-i"
8450 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
8452 (org-defkey orgstruct-mode-map "\M-\C-m"
8453 (orgstruct-make-binding 'org-insert-heading 105
8454 "\M-\C-m" [(meta return)]))
8455 (org-defkey orgstruct-mode-map [(meta return)]
8456 (orgstruct-make-binding 'org-insert-heading 106
8457 [(meta return)] "\M-\C-m"))
8459 (org-defkey orgstruct-mode-map [(shift meta return)]
8460 (orgstruct-make-binding 'org-insert-todo-heading 107
8461 [(meta return)] "\M-\C-m"))
8463 (org-defkey orgstruct-mode-map "\e\C-m"
8464 (orgstruct-make-binding 'org-insert-heading 108
8465 "\e\C-m" [?\e (return)]))
8466 (org-defkey orgstruct-mode-map [?\e (return)]
8467 (orgstruct-make-binding 'org-insert-heading 109
8468 [?\e (return)] "\e\C-m"))
8469 (org-defkey orgstruct-mode-map [?\e (shift return)]
8470 (orgstruct-make-binding 'org-insert-todo-heading 110
8471 [?\e (return)] "\e\C-m"))
8473 (unless org-local-vars
8474 (setq org-local-vars (org-get-local-variables)))
8478 (defun orgstruct-make-binding (fun n &rest keys)
8479 "Create a function for binding in the structure minor mode.
8480 FUN is the command to call inside a table. N is used to create a unique
8481 command name. KEYS are keys that should be checked in for a command
8482 to execute outside of tables."
8483 (eval
8484 (list 'defun
8485 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
8486 '(arg)
8487 (concat "In Structure, run `" (symbol-name fun) "'.\n"
8488 "Outside of structure, run the binding of `"
8489 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
8490 "'.")
8491 '(interactive "p")
8492 (list 'if
8493 `(org-context-p 'headline 'item
8494 (and orgstruct-is-++
8495 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
8496 'item-body))
8497 (list 'org-run-like-in-org-mode (list 'quote fun))
8498 (list 'let '(orgstruct-mode)
8499 (list 'call-interactively
8500 (append '(or)
8501 (mapcar (lambda (k)
8502 (list 'key-binding k))
8503 keys)
8504 '('orgstruct-error))))))))
8506 (defun org-context-p (&rest contexts)
8507 "Check if local context is any of CONTEXTS.
8508 Possible values in the list of contexts are `table', `headline', and `item'."
8509 (let ((pos (point)))
8510 (goto-char (point-at-bol))
8511 (prog1 (or (and (memq 'table contexts)
8512 (looking-at "[ \t]*|"))
8513 (and (memq 'headline contexts)
8514 (looking-at org-outline-regexp))
8515 (and (memq 'item contexts)
8516 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
8517 (and (memq 'item-body contexts)
8518 (org-in-item-p)))
8519 (goto-char pos))))
8521 (defun org-get-local-variables ()
8522 "Return a list of all local variables in an org-mode buffer."
8523 (let (varlist)
8524 (with-current-buffer (get-buffer-create "*Org tmp*")
8525 (erase-buffer)
8526 (org-mode)
8527 (setq varlist (buffer-local-variables)))
8528 (kill-buffer "*Org tmp*")
8529 (delq nil
8530 (mapcar
8531 (lambda (x)
8532 (setq x
8533 (if (symbolp x)
8534 (list x)
8535 (list (car x) (list 'quote (cdr x)))))
8536 (if (string-match
8537 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
8538 (symbol-name (car x)))
8539 x nil))
8540 varlist))))
8542 (defun org-clone-local-variables (from-buffer &optional regexp)
8543 "Clone local variables from FROM-BUFFER.
8544 Optional argument REGEXP selects variables to clone."
8545 (mapc
8546 (lambda (pair)
8547 (and (symbolp (car pair))
8548 (or (null regexp)
8549 (string-match regexp (symbol-name (car pair))))
8550 (set (make-local-variable (car pair))
8551 (cdr pair))))
8552 (buffer-local-variables from-buffer)))
8554 ;;;###autoload
8555 (defun org-run-like-in-org-mode (cmd)
8556 "Run a command, pretending that the current buffer is in Org-mode.
8557 This will temporarily bind local variables that are typically bound in
8558 Org-mode to the values they have in Org-mode, and then interactively
8559 call CMD."
8560 (org-load-modules-maybe)
8561 (unless org-local-vars
8562 (setq org-local-vars (org-get-local-variables)))
8563 (eval (list 'let org-local-vars
8564 (list 'call-interactively (list 'quote cmd)))))
8566 ;;;; Archiving
8568 (defun org-get-category (&optional pos force-refresh)
8569 "Get the category applying to position POS."
8570 (save-match-data
8571 (if force-refresh (org-refresh-category-properties))
8572 (let ((pos (or pos (point))))
8573 (or (get-text-property pos 'org-category)
8574 (progn (org-refresh-category-properties)
8575 (get-text-property pos 'org-category))))))
8577 (defun org-refresh-category-properties ()
8578 "Refresh category text properties in the buffer."
8579 (let ((inhibit-read-only t)
8580 (def-cat (cond
8581 ((null org-category)
8582 (if buffer-file-name
8583 (file-name-sans-extension
8584 (file-name-nondirectory buffer-file-name))
8585 "???"))
8586 ((symbolp org-category) (symbol-name org-category))
8587 (t org-category)))
8588 beg end cat pos optionp)
8589 (org-unmodified
8590 (save-excursion
8591 (save-restriction
8592 (widen)
8593 (goto-char (point-min))
8594 (put-text-property (point) (point-max) 'org-category def-cat)
8595 (while (re-search-forward
8596 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8597 (setq pos (match-end 0)
8598 optionp (equal (char-after (match-beginning 0)) ?#)
8599 cat (org-trim (match-string 2)))
8600 (if optionp
8601 (setq beg (point-at-bol) end (point-max))
8602 (org-back-to-heading t)
8603 (setq beg (point) end (org-end-of-subtree t t)))
8604 (put-text-property beg end 'org-category cat)
8605 (put-text-property beg end 'org-category-position beg)
8606 (goto-char pos)))))))
8609 ;;;; Link Stuff
8611 ;;; Link abbreviations
8613 (defun org-link-expand-abbrev (link)
8614 "Apply replacements as defined in `org-link-abbrev-alist'."
8615 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
8616 (let* ((key (match-string 1 link))
8617 (as (or (assoc key org-link-abbrev-alist-local)
8618 (assoc key org-link-abbrev-alist)))
8619 (tag (and (match-end 2) (match-string 3 link)))
8620 rpl)
8621 (if (not as)
8622 link
8623 (setq rpl (cdr as))
8624 (cond
8625 ((symbolp rpl) (funcall rpl tag))
8626 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
8627 ((string-match "%h" rpl)
8628 (replace-match (url-hexify-string (or tag "")) t t rpl))
8629 (t (concat rpl tag)))))
8630 link))
8632 ;;; Storing and inserting links
8634 (defvar org-insert-link-history nil
8635 "Minibuffer history for links inserted with `org-insert-link'.")
8637 (defvar org-stored-links nil
8638 "Contains the links stored with `org-store-link'.")
8640 (defvar org-store-link-plist nil
8641 "Plist with info about the most recently link created with `org-store-link'.")
8643 (defvar org-link-protocols nil
8644 "Link protocols added to Org-mode using `org-add-link-type'.")
8646 (defvar org-store-link-functions nil
8647 "List of functions that are called to create and store a link.
8648 Each function will be called in turn until one returns a non-nil
8649 value. Each function should check if it is responsible for creating
8650 this link (for example by looking at the major mode).
8651 If not, it must exit and return nil.
8652 If yes, it should return a non-nil value after a calling
8653 `org-store-link-props' with a list of properties and values.
8654 Special properties are:
8656 :type The link prefix, like \"http\". This must be given.
8657 :link The link, like \"http://www.astro.uva.nl/~dominik\".
8658 This is obligatory as well.
8659 :description Optional default description for the second pair
8660 of brackets in an Org-mode link. The user can still change
8661 this when inserting this link into an Org-mode buffer.
8663 In addition to these, any additional properties can be specified
8664 and then used in remember templates.")
8666 (defun org-add-link-type (type &optional follow export)
8667 "Add TYPE to the list of `org-link-types'.
8668 Re-compute all regular expressions depending on `org-link-types'
8670 FOLLOW and EXPORT are two functions.
8672 FOLLOW should take the link path as the single argument and do whatever
8673 is necessary to follow the link, for example find a file or display
8674 a mail message.
8676 EXPORT should format the link path for export to one of the export formats.
8677 It should be a function accepting three arguments:
8679 path the path of the link, the text after the prefix (like \"http:\")
8680 desc the description of the link, if any, or a description added by
8681 org-export-normalize-links if there is none
8682 format the export format, a symbol like `html' or `latex' or `ascii'..
8684 The function may use the FORMAT information to return different values
8685 depending on the format. The return value will be put literally into
8686 the exported file. If the return value is nil, this means Org should
8687 do what it normally does with links which do not have EXPORT defined.
8689 Org-mode has a built-in default for exporting links. If you are happy with
8690 this default, there is no need to define an export function for the link
8691 type. For a simple example of an export function, see `org-bbdb.el'."
8692 (add-to-list 'org-link-types type t)
8693 (org-make-link-regexps)
8694 (if (assoc type org-link-protocols)
8695 (setcdr (assoc type org-link-protocols) (list follow export))
8696 (push (list type follow export) org-link-protocols)))
8698 (defvar org-agenda-buffer-name)
8700 ;;;###autoload
8701 (defun org-store-link (arg)
8702 "\\<org-mode-map>Store an org-link to the current location.
8703 This link is added to `org-stored-links' and can later be inserted
8704 into an org-buffer with \\[org-insert-link].
8706 For some link types, a prefix arg is interpreted:
8707 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
8708 For file links, arg negates `org-context-in-file-links'."
8709 (interactive "P")
8710 (org-load-modules-maybe)
8711 (setq org-store-link-plist nil) ; reset
8712 (org-with-limited-levels
8713 (let (link cpltxt desc description search txt custom-id agenda-link)
8714 (cond
8716 ((run-hook-with-args-until-success 'org-store-link-functions)
8717 (setq link (plist-get org-store-link-plist :link)
8718 desc (or (plist-get org-store-link-plist :description) link)))
8720 ((org-src-edit-buffer-p)
8721 (let (label gc)
8722 (while (or (not label)
8723 (save-excursion
8724 (save-restriction
8725 (widen)
8726 (goto-char (point-min))
8727 (re-search-forward
8728 (regexp-quote (format org-coderef-label-format label))
8729 nil t))))
8730 (when label (message "Label exists already") (sit-for 2))
8731 (setq label (read-string "Code line label: " label)))
8732 (end-of-line 1)
8733 (setq link (format org-coderef-label-format label))
8734 (setq gc (- 79 (length link)))
8735 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
8736 (insert link)
8737 (setq link (concat "(" label ")") desc nil)))
8739 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
8740 ;; We are in the agenda, link to referenced location
8741 (let ((m (or (get-text-property (point) 'org-hd-marker)
8742 (get-text-property (point) 'org-marker))))
8743 (when m
8744 (org-with-point-at m
8745 (setq agenda-link
8746 (if (org-called-interactively-p 'any)
8747 (call-interactively 'org-store-link)
8748 (org-store-link nil)))))))
8750 ((eq major-mode 'calendar-mode)
8751 (let ((cd (calendar-cursor-to-date)))
8752 (setq link
8753 (format-time-string
8754 (car org-time-stamp-formats)
8755 (apply 'encode-time
8756 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
8757 nil nil nil))))
8758 (org-store-link-props :type "calendar" :date cd)))
8760 ((eq major-mode 'w3-mode)
8761 (setq cpltxt (if (and (buffer-name)
8762 (not (string-match "Untitled" (buffer-name))))
8763 (buffer-name)
8764 (url-view-url t))
8765 link (org-make-link (url-view-url t)))
8766 (org-store-link-props :type "w3" :url (url-view-url t)))
8768 ((eq major-mode 'w3m-mode)
8769 (setq cpltxt (or w3m-current-title w3m-current-url)
8770 link (org-make-link w3m-current-url))
8771 (org-store-link-props :type "w3m" :url (url-view-url t)))
8773 ((setq search (run-hook-with-args-until-success
8774 'org-create-file-search-functions))
8775 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
8776 "::" search))
8777 (setq cpltxt (or description link)))
8779 ((eq major-mode 'image-mode)
8780 (setq cpltxt (concat "file:"
8781 (abbreviate-file-name buffer-file-name))
8782 link (org-make-link cpltxt))
8783 (org-store-link-props :type "image" :file buffer-file-name))
8785 ((eq major-mode 'dired-mode)
8786 ;; link to the file in the current line
8787 (let ((file (dired-get-filename nil t)))
8788 (setq file (if file
8789 (abbreviate-file-name
8790 (expand-file-name (dired-get-filename nil t)))
8791 ;; otherwise, no file so use current directory.
8792 default-directory))
8793 (setq cpltxt (concat "file:" file)
8794 link (org-make-link cpltxt))))
8796 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
8797 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
8798 (cond
8799 ((org-in-regexp "<<\\(.*?\\)>>")
8800 (setq cpltxt
8801 (concat "file:"
8802 (abbreviate-file-name
8803 (buffer-file-name (buffer-base-buffer)))
8804 "::" (match-string 1))
8805 link (org-make-link cpltxt)))
8806 ((and (featurep 'org-id)
8807 (or (eq org-link-to-org-use-id t)
8808 (and (eq org-link-to-org-use-id 'create-if-interactive)
8809 (org-called-interactively-p 'any))
8810 (and (eq org-link-to-org-use-id
8811 'create-if-interactive-and-no-custom-id)
8812 (org-called-interactively-p 'any)
8813 (not custom-id))
8814 (and org-link-to-org-use-id
8815 (org-entry-get nil "ID"))))
8816 ;; We can make a link using the ID.
8817 (setq link (condition-case nil
8818 (prog1 (org-id-store-link)
8819 (setq desc (plist-get org-store-link-plist
8820 :description)))
8821 (error
8822 ;; probably before first headline, link to file only
8823 (concat "file:"
8824 (abbreviate-file-name
8825 (buffer-file-name (buffer-base-buffer))))))))
8827 ;; Just link to current headline
8828 (setq cpltxt (concat "file:"
8829 (abbreviate-file-name
8830 (buffer-file-name (buffer-base-buffer)))))
8831 ;; Add a context search string
8832 (when (org-xor org-context-in-file-links arg)
8833 (setq txt (cond
8834 ((org-at-heading-p) nil)
8835 ((org-region-active-p)
8836 (buffer-substring (region-beginning) (region-end)))
8837 (t nil)))
8838 (when (or (null txt) (string-match "\\S-" txt))
8839 (setq cpltxt
8840 (concat cpltxt "::"
8841 (condition-case nil
8842 (org-make-org-heading-search-string txt)
8843 (error "")))
8844 desc (or (nth 4 (ignore-errors
8845 (org-heading-components))) "NONE"))))
8846 (if (string-match "::\\'" cpltxt)
8847 (setq cpltxt (substring cpltxt 0 -2)))
8848 (setq link (org-make-link cpltxt)))))
8850 ((buffer-file-name (buffer-base-buffer))
8851 ;; Just link to this file here.
8852 (setq cpltxt (concat "file:"
8853 (abbreviate-file-name
8854 (buffer-file-name (buffer-base-buffer)))))
8855 ;; Add a context string
8856 (when (org-xor org-context-in-file-links arg)
8857 (setq txt (if (org-region-active-p)
8858 (buffer-substring (region-beginning) (region-end))
8859 (buffer-substring (point-at-bol) (point-at-eol))))
8860 ;; Only use search option if there is some text.
8861 (when (string-match "\\S-" txt)
8862 (setq cpltxt
8863 (concat cpltxt "::" (org-make-org-heading-search-string txt))
8864 desc "NONE")))
8865 (setq link (org-make-link cpltxt)))
8867 ((org-called-interactively-p 'interactive)
8868 (error "Cannot link to a buffer which is not visiting a file"))
8870 (t (setq link nil)))
8872 (if (consp link) (setq cpltxt (car link) link (cdr link)))
8873 (setq link (or link cpltxt)
8874 desc (or desc cpltxt))
8875 (if (equal desc "NONE") (setq desc nil))
8877 (if (and (or (org-called-interactively-p 'any) executing-kbd-macro) link)
8878 (progn
8879 (setq org-stored-links
8880 (cons (list link desc) org-stored-links))
8881 (message "Stored: %s" (or desc link))
8882 (when custom-id
8883 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
8884 "::#" custom-id))
8885 (setq org-stored-links
8886 (cons (list link desc) org-stored-links))))
8887 (or agenda-link (and link (org-make-link-string link desc)))))))
8889 (defun org-store-link-props (&rest plist)
8890 "Store link properties, extract names and addresses."
8891 (let (x adr)
8892 (when (setq x (plist-get plist :from))
8893 (setq adr (mail-extract-address-components x))
8894 (setq plist (plist-put plist :fromname (car adr)))
8895 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
8896 (when (setq x (plist-get plist :to))
8897 (setq adr (mail-extract-address-components x))
8898 (setq plist (plist-put plist :toname (car adr)))
8899 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
8900 (let ((from (plist-get plist :from))
8901 (to (plist-get plist :to)))
8902 (when (and from to org-from-is-user-regexp)
8903 (setq plist
8904 (plist-put plist :fromto
8905 (if (string-match org-from-is-user-regexp from)
8906 (concat "to %t")
8907 (concat "from %f"))))))
8908 (setq org-store-link-plist plist))
8910 (defun org-add-link-props (&rest plist)
8911 "Add these properties to the link property list."
8912 (let (key value)
8913 (while plist
8914 (setq key (pop plist) value (pop plist))
8915 (setq org-store-link-plist
8916 (plist-put org-store-link-plist key value)))))
8918 (defun org-email-link-description (&optional fmt)
8919 "Return the description part of an email link.
8920 This takes information from `org-store-link-plist' and formats it
8921 according to FMT (default from `org-email-link-description-format')."
8922 (setq fmt (or fmt org-email-link-description-format))
8923 (let* ((p org-store-link-plist)
8924 (to (plist-get p :toaddress))
8925 (from (plist-get p :fromaddress))
8926 (table
8927 (list
8928 (cons "%c" (plist-get p :fromto))
8929 (cons "%F" (plist-get p :from))
8930 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
8931 (cons "%T" (plist-get p :to))
8932 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
8933 (cons "%s" (plist-get p :subject))
8934 (cons "%d" (plist-get p :date))
8935 (cons "%m" (plist-get p :message-id)))))
8936 (when (string-match "%c" fmt)
8937 ;; Check if the user wrote this message
8938 (if (and org-from-is-user-regexp from to
8939 (save-match-data (string-match org-from-is-user-regexp from)))
8940 (setq fmt (replace-match "to %t" t t fmt))
8941 (setq fmt (replace-match "from %f" t t fmt))))
8942 (org-replace-escapes fmt table)))
8944 (defun org-make-org-heading-search-string (&optional string heading)
8945 "Make search string for STRING or current headline."
8946 (interactive)
8947 (let ((s (or string (org-get-heading)))
8948 (lines org-context-in-file-links))
8949 (unless (and string (not heading))
8950 ;; We are using a headline, clean up garbage in there.
8951 (if (string-match org-todo-regexp s)
8952 (setq s (replace-match "" t t s)))
8953 (if (string-match (org-re ":[[:alnum:]_@#%:]+:[ \t]*$") s)
8954 (setq s (replace-match "" t t s)))
8955 (setq s (org-trim s))
8956 (if (string-match (concat "^\\(" org-quote-string "\\|"
8957 org-comment-string "\\)") s)
8958 (setq s (replace-match "" t t s)))
8959 (while (string-match org-ts-regexp s)
8960 (setq s (replace-match "" t t s))))
8961 (or string (setq s (concat "*" s))) ; Add * for headlines
8962 (when (and string (integerp lines) (> lines 0))
8963 (let ((slines (org-split-string s "\n")))
8964 (when (< lines (length slines))
8965 (setq s (mapconcat
8966 'identity
8967 (reverse (nthcdr (- (length slines) lines)
8968 (reverse slines))) "\n")))))
8969 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
8971 (defun org-make-link (&rest strings)
8972 "Concatenate STRINGS."
8973 (apply 'concat strings))
8975 (defun org-make-link-string (link &optional description)
8976 "Make a link with brackets, consisting of LINK and DESCRIPTION."
8977 (unless (string-match "\\S-" link)
8978 (error "Empty link"))
8979 (when (and description
8980 (stringp description)
8981 (not (string-match "\\S-" description)))
8982 (setq description nil))
8983 (when (stringp description)
8984 ;; Remove brackets from the description, they are fatal.
8985 (while (string-match "\\[" description)
8986 (setq description (replace-match "{" t t description)))
8987 (while (string-match "\\]" description)
8988 (setq description (replace-match "}" t t description))))
8989 (when (equal link description)
8990 ;; No description needed, it is identical
8991 (setq description nil))
8992 (when (and (not description)
8993 (not (string-match (org-image-file-name-regexp) link))
8994 (not (equal link (org-link-escape link))))
8995 (setq description (org-extract-attributes link)))
8996 (setq link
8997 (cond ((string-match (org-image-file-name-regexp) link) link)
8998 ((string-match org-link-types-re link)
8999 (concat (match-string 1 link)
9000 (org-link-escape (substring link (match-end 1)))))
9001 (t (org-link-escape link))))
9002 (concat "[[" link "]"
9003 (if description (concat "[" description "]") "")
9004 "]"))
9006 (defconst org-link-escape-chars
9007 '(?\ ?\[ ?\] ?\; ?\= ?\+)
9008 "List of characters that should be escaped in link.
9009 This is the list that is used for internal purposes.")
9011 (defvar org-url-encoding-use-url-hexify nil)
9013 (defconst org-link-escape-chars-browser
9014 '(?\ )
9015 "List of escapes for characters that are problematic in links.
9016 This is the list that is used before handing over to the browser.")
9018 (defun org-link-escape (text &optional table merge)
9019 "Return percent escaped representation of TEXT.
9020 TEXT is a string with the text to escape.
9021 Optional argument TABLE is a list with characters that should be
9022 escaped. When nil, `org-link-escape-chars' is used.
9023 If optional argument MERGE is set, merge TABLE into
9024 `org-link-escape-chars'."
9025 (if (and org-url-encoding-use-url-hexify (not table))
9026 (url-hexify-string text)
9027 (cond
9028 ((and table merge)
9029 (mapc (lambda (defchr)
9030 (unless (member defchr table)
9031 (setq table (cons defchr table)))) org-link-escape-chars))
9032 ((null table)
9033 (setq table org-link-escape-chars)))
9034 (mapconcat
9035 (lambda (char)
9036 (if (or (member char table)
9037 (< char 32) (= char 37) (> char 126))
9038 (mapconcat (lambda (sequence-element)
9039 (format "%%%.2X" sequence-element))
9040 (or (encode-coding-char char 'utf-8)
9041 (error "Unable to percent escape character: %s"
9042 (char-to-string char))) "")
9043 (char-to-string char))) text "")))
9045 (defun org-link-unescape (str)
9046 "Unhex hexified Unicode strings as returned from the JavaScript function
9047 encodeURIComponent. E.g. `%C3%B6' is the german Umlaut `ö'."
9048 (unless (and (null str) (string= "" str))
9049 (let ((pos 0) (case-fold-search t) unhexed)
9050 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9051 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9052 (setq str (replace-match unhexed t t str))
9053 (setq pos (+ pos (length unhexed))))))
9054 str)
9056 (defun org-link-unescape-compound (hex)
9057 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German Umlaut `ö'.
9058 Note: this function also decodes single byte encodings like
9059 `%E1' (\"á\") if not followed by another `%[A-F0-9]{2}' group."
9060 (save-match-data
9061 (let* ((bytes (cdr (split-string hex "%")))
9062 (ret "")
9063 (eat 0)
9064 (sum 0))
9065 (while bytes
9066 (let* ((val (string-to-number (pop bytes) 16))
9067 (shift-xor
9068 (if (= 0 eat)
9069 (cond
9070 ((>= val 252) (cons 6 252))
9071 ((>= val 248) (cons 5 248))
9072 ((>= val 240) (cons 4 240))
9073 ((>= val 224) (cons 3 224))
9074 ((>= val 192) (cons 2 192))
9075 (t (cons 0 0)))
9076 (cons 6 128))))
9077 (if (>= val 192) (setq eat (car shift-xor)))
9078 (setq val (logxor val (cdr shift-xor)))
9079 (setq sum (+ (lsh sum (car shift-xor)) val))
9080 (if (> eat 0) (setq eat (- eat 1)))
9081 (cond
9082 ((= 0 eat) ;multi byte
9083 (setq ret (concat ret (org-char-to-string sum)))
9084 (setq sum 0))
9085 ((not bytes) ; single byte(s)
9086 (setq ret (org-link-unescape-single-byte-sequence hex))))
9087 )) ;; end (while bytes
9088 ret )))
9090 (defun org-link-unescape-single-byte-sequence (hex)
9091 "Unhexify hex-encoded single byte character sequences."
9092 (mapconcat (lambda (byte)
9093 (char-to-string (string-to-number byte 16)))
9094 (cdr (split-string hex "%")) ""))
9096 (defun org-xor (a b)
9097 "Exclusive or."
9098 (if a (not b) b))
9100 (defun org-fixup-message-id-for-http (s)
9101 "Replace special characters in a message id, so it can be used in an http query."
9102 (when (string-match "%" s)
9103 (setq s (mapconcat (lambda (c)
9104 (if (eq c ?%)
9105 "%25"
9106 (char-to-string c)))
9107 s "")))
9108 (while (string-match "<" s)
9109 (setq s (replace-match "%3C" t t s)))
9110 (while (string-match ">" s)
9111 (setq s (replace-match "%3E" t t s)))
9112 (while (string-match "@" s)
9113 (setq s (replace-match "%40" t t s)))
9116 (defun org-link-prettify (link)
9117 "Return a human-readable representation of LINK.
9118 The car of LINK must be a raw link the cdr of LINK must be either
9119 a link description or nil."
9120 (let ((desc (or (cadr link) "<no description>")))
9121 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9122 "[[" (car link) "]]")))
9124 ;;;###autoload
9125 (defun org-insert-link-global ()
9126 "Insert a link like Org-mode does.
9127 This command can be called in any mode to insert a link in Org-mode syntax."
9128 (interactive)
9129 (org-load-modules-maybe)
9130 (org-run-like-in-org-mode 'org-insert-link))
9132 (defun org-insert-link (&optional complete-file link-location default-description)
9133 "Insert a link. At the prompt, enter the link.
9135 Completion can be used to insert any of the link protocol prefixes like
9136 http or ftp in use.
9138 The history can be used to select a link previously stored with
9139 `org-store-link'. When the empty string is entered (i.e. if you just
9140 press RET at the prompt), the link defaults to the most recently
9141 stored link. As SPC triggers completion in the minibuffer, you need to
9142 use M-SPC or C-q SPC to force the insertion of a space character.
9144 You will also be prompted for a description, and if one is given, it will
9145 be displayed in the buffer instead of the link.
9147 If there is already a link at point, this command will allow you to edit link
9148 and description parts.
9150 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9151 be selected using completion. The path to the file will be relative to the
9152 current directory if the file is in the current directory or a subdirectory.
9153 Otherwise, the link will be the absolute path as completed in the minibuffer
9154 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9155 option `org-link-file-path-type'.
9157 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9158 the current directory or below.
9160 With three \\[universal-argument] prefixes, negate the meaning of
9161 `org-keep-stored-link-after-insertion'.
9163 If `org-make-link-description-function' is non-nil, this function will be
9164 called with the link target, and the result will be the default
9165 link description.
9167 If the LINK-LOCATION parameter is non-nil, this value will be
9168 used as the link location instead of reading one interactively.
9170 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9171 be used as the default description."
9172 (interactive "P")
9173 (let* ((wcf (current-window-configuration))
9174 (region (if (org-region-active-p)
9175 (buffer-substring (region-beginning) (region-end))))
9176 (remove (and region (list (region-beginning) (region-end))))
9177 (desc region)
9178 tmphist ; byte-compile incorrectly complains about this
9179 (link link-location)
9180 entry file all-prefixes)
9181 (cond
9182 (link-location) ; specified by arg, just use it.
9183 ((org-in-regexp org-bracket-link-regexp 1)
9184 ;; We do have a link at point, and we are going to edit it.
9185 (setq remove (list (match-beginning 0) (match-end 0)))
9186 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9187 (setq link (read-string "Link: "
9188 (org-link-unescape
9189 (org-match-string-no-properties 1)))))
9190 ((or (org-in-regexp org-angle-link-re)
9191 (org-in-regexp org-plain-link-re))
9192 ;; Convert to bracket link
9193 (setq remove (list (match-beginning 0) (match-end 0))
9194 link (read-string "Link: "
9195 (org-remove-angle-brackets (match-string 0)))))
9196 ((member complete-file '((4) (16)))
9197 ;; Completing read for file names.
9198 (setq link (org-file-complete-link complete-file)))
9200 ;; Read link, with completion for stored links.
9201 (with-output-to-temp-buffer "*Org Links*"
9202 (princ "Insert a link.
9203 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9204 (when org-stored-links
9205 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9206 (princ (mapconcat 'org-link-prettify
9207 (reverse org-stored-links) "\n"))))
9208 (let ((cw (selected-window)))
9209 (select-window (get-buffer-window "*Org Links*" 'visible))
9210 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9211 (unless (pos-visible-in-window-p (point-max))
9212 (org-fit-window-to-buffer))
9213 (and (window-live-p cw) (select-window cw)))
9214 ;; Fake a link history, containing the stored links.
9215 (setq tmphist (append (mapcar 'car org-stored-links)
9216 org-insert-link-history))
9217 (setq all-prefixes (append (mapcar 'car org-link-abbrev-alist-local)
9218 (mapcar 'car org-link-abbrev-alist)
9219 org-link-types))
9220 (unwind-protect
9221 (progn
9222 (setq link
9223 (let ((org-completion-use-ido nil)
9224 (org-completion-use-iswitchb nil))
9225 (org-completing-read
9226 "Link: "
9227 (append
9228 (mapcar (lambda (x) (list (concat x ":")))
9229 all-prefixes)
9230 (mapcar 'car org-stored-links))
9231 nil nil nil
9232 'tmphist
9233 (car (car org-stored-links)))))
9234 (if (not (string-match "\\S-" link))
9235 (error "No link selected"))
9236 (if (or (member link all-prefixes)
9237 (and (equal ":" (substring link -1))
9238 (member (substring link 0 -1) all-prefixes)
9239 (setq link (substring link 0 -1))))
9240 (setq link (org-link-try-special-completion link))))
9241 (set-window-configuration wcf)
9242 (kill-buffer "*Org Links*"))
9243 (setq entry (assoc link org-stored-links))
9244 (or entry (push link org-insert-link-history))
9245 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9246 (not org-keep-stored-link-after-insertion))
9247 (setq org-stored-links (delq (assoc link org-stored-links)
9248 org-stored-links)))
9249 (setq desc (or desc (nth 1 entry)))))
9251 (if (string-match org-plain-link-re link)
9252 ;; URL-like link, normalize the use of angular brackets.
9253 (setq link (org-make-link (org-remove-angle-brackets link))))
9255 ;; Check if we are linking to the current file with a search option
9256 ;; If yes, simplify the link by using only the search option.
9257 (when (and buffer-file-name
9258 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
9259 (let* ((path (match-string 1 link))
9260 (case-fold-search nil)
9261 (search (match-string 2 link)))
9262 (save-match-data
9263 (if (equal (file-truename buffer-file-name) (file-truename path))
9264 ;; We are linking to this same file, with a search option
9265 (setq link search)))))
9267 ;; Check if we can/should use a relative path. If yes, simplify the link
9268 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
9269 (let* ((type (match-string 1 link))
9270 (path (match-string 2 link))
9271 (origpath path)
9272 (case-fold-search nil))
9273 (cond
9274 ((or (eq org-link-file-path-type 'absolute)
9275 (equal complete-file '(16)))
9276 (setq path (abbreviate-file-name (expand-file-name path))))
9277 ((eq org-link-file-path-type 'noabbrev)
9278 (setq path (expand-file-name path)))
9279 ((eq org-link-file-path-type 'relative)
9280 (setq path (file-relative-name path)))
9282 (save-match-data
9283 (if (string-match (concat "^" (regexp-quote
9284 (expand-file-name
9285 (file-name-as-directory
9286 default-directory))))
9287 (expand-file-name path))
9288 ;; We are linking a file with relative path name.
9289 (setq path (substring (expand-file-name path)
9290 (match-end 0)))
9291 (setq path (abbreviate-file-name (expand-file-name path)))))))
9292 (setq link (concat type path))
9293 (if (equal desc origpath)
9294 (setq desc path))))
9296 (if org-make-link-description-function
9297 (setq desc (funcall org-make-link-description-function link desc))
9298 (if default-description (setq desc default-description)))
9300 (setq desc (read-string "Description: " desc))
9301 (unless (string-match "\\S-" desc) (setq desc nil))
9302 (if remove (apply 'delete-region remove))
9303 (insert (org-make-link-string link desc))))
9305 (defun org-link-try-special-completion (type)
9306 "If there is completion support for link type TYPE, offer it."
9307 (let ((fun (intern (concat "org-" type "-complete-link"))))
9308 (if (functionp fun)
9309 (funcall fun)
9310 (read-string "Link (no completion support): " (concat type ":")))))
9312 (defun org-file-complete-link (&optional arg)
9313 "Create a file link using completion."
9314 (let (file link)
9315 (setq file (read-file-name "File: "))
9316 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9317 (pwd1 (file-name-as-directory (abbreviate-file-name
9318 (expand-file-name ".")))))
9319 (cond
9320 ((equal arg '(16))
9321 (setq link (org-make-link
9322 "file:"
9323 (abbreviate-file-name (expand-file-name file)))))
9324 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9325 (setq link (org-make-link "file:" (match-string 1 file))))
9326 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9327 (expand-file-name file))
9328 (setq link (org-make-link
9329 "file:" (match-string 1 (expand-file-name file)))))
9330 (t (setq link (org-make-link "file:" file)))))
9331 link))
9333 (defun org-completing-read (&rest args)
9334 "Completing-read with SPACE being a normal character."
9335 (let ((enable-recursive-minibuffers t)
9336 (minibuffer-local-completion-map
9337 (copy-keymap minibuffer-local-completion-map)))
9338 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
9339 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
9340 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
9341 (apply 'org-icompleting-read args)))
9343 (defun org-completing-read-no-i (&rest args)
9344 (let (org-completion-use-ido org-completion-use-iswitchb)
9345 (apply 'org-completing-read args)))
9347 (defun org-iswitchb-completing-read (prompt choices &rest args)
9348 "Use iswitch as a completing-read replacement to choose from choices.
9349 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
9350 from."
9351 (let* ((iswitchb-use-virtual-buffers nil)
9352 (iswitchb-make-buflist-hook
9353 (lambda ()
9354 (setq iswitchb-temp-buflist choices))))
9355 (iswitchb-read-buffer prompt)))
9357 (defun org-icompleting-read (&rest args)
9358 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
9359 (org-without-partial-completion
9360 (if (and org-completion-use-ido
9361 (fboundp 'ido-completing-read)
9362 (boundp 'ido-mode) ido-mode
9363 (listp (second args)))
9364 (let ((ido-enter-matching-directory nil))
9365 (apply 'ido-completing-read (concat (car args))
9366 (if (consp (car (nth 1 args)))
9367 (mapcar 'car (nth 1 args))
9368 (nth 1 args))
9369 (cddr args)))
9370 (if (and org-completion-use-iswitchb
9371 (boundp 'iswitchb-mode) iswitchb-mode
9372 (listp (second args)))
9373 (apply 'org-iswitchb-completing-read (concat (car args))
9374 (if (consp (car (nth 1 args)))
9375 (mapcar 'car (nth 1 args))
9376 (nth 1 args))
9377 (cddr args))
9378 (apply 'completing-read args)))))
9380 (defun org-extract-attributes (s)
9381 "Extract the attributes cookie from a string and set as text property."
9382 (let (a attr (start 0) key value)
9383 (save-match-data
9384 (when (string-match "{{\\([^}]+\\)}}$" s)
9385 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
9386 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
9387 (setq key (match-string 1 a) value (match-string 2 a)
9388 start (match-end 0)
9389 attr (plist-put attr (intern key) value))))
9390 (org-add-props s nil 'org-attr attr))
9393 (defun org-extract-attributes-from-string (tag)
9394 (let (key value attr)
9395 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
9396 (setq key (match-string 1 tag) value (match-string 2 tag)
9397 tag (replace-match "" t t tag)
9398 attr (plist-put attr (intern key) value)))
9399 (cons tag attr)))
9401 (defun org-attributes-to-string (plist)
9402 "Format a property list into an HTML attribute list."
9403 (let ((s "") key value)
9404 (while plist
9405 (setq key (pop plist) value (pop plist))
9406 (and value
9407 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
9410 ;;; Opening/following a link
9412 (defvar org-link-search-failed nil)
9414 (defvar org-open-link-functions nil
9415 "Hook for functions finding a plain text link.
9416 These functions must take a single argument, the link content.
9417 They will be called for links that look like [[link text][description]]
9418 when LINK TEXT does not have a protocol like \"http:\" and does not look
9419 like a filename (e.g. \"./blue.png\").
9421 These functions will be called *before* Org attempts to resolve the
9422 link by doing text searches in the current buffer - so if you want a
9423 link \"[[target]]\" to still find \"<<target>>\", your function should
9424 handle this as a special case.
9426 When the function does handle the link, it must return a non-nil value.
9427 If it decides that it is not responsible for this link, it must return
9428 nil to indicate that that Org-mode can continue with other options
9429 like exact and fuzzy text search.")
9431 (defun org-next-link ()
9432 "Move forward to the next link.
9433 If the link is in hidden text, expose it."
9434 (interactive)
9435 (when (and org-link-search-failed (eq this-command last-command))
9436 (goto-char (point-min))
9437 (message "Link search wrapped back to beginning of buffer"))
9438 (setq org-link-search-failed nil)
9439 (let* ((pos (point))
9440 (ct (org-context))
9441 (a (assoc :link ct)))
9442 (if a (goto-char (nth 2 a)))
9443 (if (re-search-forward org-any-link-re nil t)
9444 (progn
9445 (goto-char (match-beginning 0))
9446 (if (outline-invisible-p) (org-show-context)))
9447 (goto-char pos)
9448 (setq org-link-search-failed t)
9449 (error "No further link found"))))
9451 (defun org-previous-link ()
9452 "Move backward to the previous link.
9453 If the link is in hidden text, expose it."
9454 (interactive)
9455 (when (and org-link-search-failed (eq this-command last-command))
9456 (goto-char (point-max))
9457 (message "Link search wrapped back to end of buffer"))
9458 (setq org-link-search-failed nil)
9459 (let* ((pos (point))
9460 (ct (org-context))
9461 (a (assoc :link ct)))
9462 (if a (goto-char (nth 1 a)))
9463 (if (re-search-backward org-any-link-re nil t)
9464 (progn
9465 (goto-char (match-beginning 0))
9466 (if (outline-invisible-p) (org-show-context)))
9467 (goto-char pos)
9468 (setq org-link-search-failed t)
9469 (error "No further link found"))))
9471 (defun org-translate-link (s)
9472 "Translate a link string if a translation function has been defined."
9473 (if (and org-link-translation-function
9474 (fboundp org-link-translation-function)
9475 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
9476 (progn
9477 (setq s (funcall org-link-translation-function
9478 (match-string 1 s) (match-string 2 s)))
9479 (concat (car s) ":" (cdr s)))
9482 (defun org-translate-link-from-planner (type path)
9483 "Translate a link from Emacs Planner syntax so that Org can follow it.
9484 This is still an experimental function, your mileage may vary."
9485 (cond
9486 ((member type '("http" "https" "news" "ftp"))
9487 ;; standard Internet links are the same.
9488 nil)
9489 ((and (equal type "irc") (string-match "^//" path))
9490 ;; Planner has two / at the beginning of an irc link, we have 1.
9491 ;; We should have zero, actually....
9492 (setq path (substring path 1)))
9493 ((and (equal type "lisp") (string-match "^/" path))
9494 ;; Planner has a slash, we do not.
9495 (setq type "elisp" path (substring path 1)))
9496 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9497 ;; A typical message link. Planner has the id after the final slash,
9498 ;; we separate it with a hash mark
9499 (setq path (concat (match-string 1 path) "#"
9500 (org-remove-angle-brackets (match-string 2 path)))))
9502 (cons type path))
9504 (defun org-find-file-at-mouse (ev)
9505 "Open file link or URL at mouse."
9506 (interactive "e")
9507 (mouse-set-point ev)
9508 (org-open-at-point 'in-emacs))
9510 (defun org-open-at-mouse (ev)
9511 "Open file link or URL at mouse.
9512 See the docstring of `org-open-file' for details."
9513 (interactive "e")
9514 (mouse-set-point ev)
9515 (if (eq major-mode 'org-agenda-mode)
9516 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
9517 (org-open-at-point))
9519 (defvar org-window-config-before-follow-link nil
9520 "The window configuration before following a link.
9521 This is saved in case the need arises to restore it.")
9523 (defvar org-open-link-marker (make-marker)
9524 "Marker pointing to the location where `org-open-at-point; was called.")
9526 ;;;###autoload
9527 (defun org-open-at-point-global ()
9528 "Follow a link like Org-mode does.
9529 This command can be called in any mode to follow a link that has
9530 Org-mode syntax."
9531 (interactive)
9532 (org-run-like-in-org-mode 'org-open-at-point))
9534 ;;;###autoload
9535 (defun org-open-link-from-string (s &optional arg reference-buffer)
9536 "Open a link in the string S, as if it was in Org-mode."
9537 (interactive "sLink: \nP")
9538 (let ((reference-buffer (or reference-buffer (current-buffer))))
9539 (with-temp-buffer
9540 (let ((org-inhibit-startup (not reference-buffer)))
9541 (org-mode)
9542 (insert s)
9543 (goto-char (point-min))
9544 (when reference-buffer
9545 (setq org-link-abbrev-alist-local
9546 (with-current-buffer reference-buffer
9547 org-link-abbrev-alist-local)))
9548 (org-open-at-point arg reference-buffer)))))
9550 (defvar org-open-at-point-functions nil
9551 "Hook that is run when following a link at point.
9553 Functions in this hook must return t if they identify and follow
9554 a link at point. If they don't find anything interesting at point,
9555 they must return nil.")
9557 (defun org-open-at-point (&optional arg reference-buffer)
9558 "Open link at or after point.
9559 If there is no link at point, this function will search forward up to
9560 the end of the current line.
9561 Normally, files will be opened by an appropriate application. If the
9562 optional prefix argument ARG is non-nil, Emacs will visit the file.
9563 With a double prefix argument, try to open outside of Emacs, in the
9564 application the system uses for this file type."
9565 (interactive "P")
9566 ;; if in a code block, then open the block's results
9567 (unless (call-interactively #'org-babel-open-src-block-result)
9568 (org-load-modules-maybe)
9569 (move-marker org-open-link-marker (point))
9570 (setq org-window-config-before-follow-link (current-window-configuration))
9571 (org-remove-occur-highlights nil nil t)
9572 (cond
9573 ((and (org-at-heading-p)
9574 (not (org-in-regexp
9575 (concat org-plain-link-re "\\|"
9576 org-bracket-link-regexp "\\|"
9577 org-angle-link-re "\\|"
9578 "[ \t]:[^ \t\n]+:[ \t]*$")))
9579 (not (get-text-property (point) 'org-linked-text)))
9580 (or (org-offer-links-in-entry arg)
9581 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
9582 ((run-hook-with-args-until-success 'org-open-at-point-functions))
9583 ((org-at-timestamp-p t) (org-follow-timestamp-link))
9584 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
9585 (not (org-in-regexp org-bracket-link-regexp)))
9586 (org-footnote-action))
9588 (let (type path link line search (pos (point)))
9589 (catch 'match
9590 (save-excursion
9591 (skip-chars-forward "^]\n\r")
9592 (when (org-in-regexp org-bracket-link-regexp 1)
9593 (setq link (org-extract-attributes
9594 (org-link-unescape (org-match-string-no-properties 1))))
9595 (while (string-match " *\n *" link)
9596 (setq link (replace-match " " t t link)))
9597 (setq link (org-link-expand-abbrev link))
9598 (cond
9599 ((or (file-name-absolute-p link)
9600 (string-match "^\\.\\.?/" link))
9601 (setq type "file" path link))
9602 ((string-match org-link-re-with-space3 link)
9603 (setq type (match-string 1 link) path (match-string 2 link)))
9604 (t (setq type "thisfile" path link)))
9605 (throw 'match t)))
9607 (when (get-text-property (point) 'org-linked-text)
9608 (setq type "thisfile"
9609 pos (if (get-text-property (1+ (point)) 'org-linked-text)
9610 (1+ (point)) (point))
9611 path (buffer-substring
9612 (or (previous-single-property-change pos 'org-linked-text)
9613 (point-min))
9614 (or (next-single-property-change pos 'org-linked-text)
9615 (point-max))))
9616 (throw 'match t))
9618 (save-excursion
9619 (when (or (org-in-regexp org-angle-link-re)
9620 (org-in-regexp org-plain-link-re))
9621 (setq type (match-string 1)
9622 path (org-link-unescape (match-string 2)))
9623 (throw 'match t)))
9624 (save-excursion
9625 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
9626 (setq type "tags"
9627 path (match-string 1))
9628 (while (string-match ":" path)
9629 (setq path (replace-match "+" t t path)))
9630 (throw 'match t)))
9631 (when (org-in-regexp "<\\([^><\n]+\\)>")
9632 (setq type "tree-match"
9633 path (match-string 1))
9634 (throw 'match t)))
9635 (unless path
9636 (error "No link found"))
9638 ;; switch back to reference buffer
9639 ;; needed when if called in a temporary buffer through
9640 ;; org-open-link-from-string
9641 (with-current-buffer (or reference-buffer (current-buffer))
9643 ;; Remove any trailing spaces in path
9644 (if (string-match " +\\'" path)
9645 (setq path (replace-match "" t t path)))
9646 (if (and org-link-translation-function
9647 (fboundp org-link-translation-function))
9648 ;; Check if we need to translate the link
9649 (let ((tmp (funcall org-link-translation-function type path)))
9650 (setq type (car tmp) path (cdr tmp))))
9652 (cond
9654 ((assoc type org-link-protocols)
9655 (funcall (nth 1 (assoc type org-link-protocols)) path))
9657 ((equal type "mailto")
9658 (let ((cmd (car org-link-mailto-program))
9659 (args (cdr org-link-mailto-program)) args1
9660 (address path) (subject "") a)
9661 (if (string-match "\\(.*\\)::\\(.*\\)" path)
9662 (setq address (match-string 1 path)
9663 subject (org-link-escape (match-string 2 path))))
9664 (while args
9665 (cond
9666 ((not (stringp (car args))) (push (pop args) args1))
9667 (t (setq a (pop args))
9668 (if (string-match "%a" a)
9669 (setq a (replace-match address t t a)))
9670 (if (string-match "%s" a)
9671 (setq a (replace-match subject t t a)))
9672 (push a args1))))
9673 (apply cmd (nreverse args1))))
9675 ((member type '("http" "https" "ftp" "news"))
9676 (browse-url (concat type ":" (if (org-string-match-p "[[:nonascii:] ]" path)
9677 (org-link-escape
9678 path org-link-escape-chars-browser)
9679 path))))
9681 ((string= type "doi")
9682 (browse-url (concat "http://dx.doi.org/" (if (org-string-match-p "[[:nonascii:] ]" path)
9683 (org-link-escape
9684 path org-link-escape-chars-browser)
9685 path))))
9687 ((member type '("message"))
9688 (browse-url (concat type ":" path)))
9690 ((string= type "tags")
9691 (org-tags-view arg path))
9693 ((string= type "tree-match")
9694 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
9696 ((string= type "file")
9697 (if (string-match "::\\([0-9]+\\)\\'" path)
9698 (setq line (string-to-number (match-string 1 path))
9699 path (substring path 0 (match-beginning 0)))
9700 (if (string-match "::\\(.+\\)\\'" path)
9701 (setq search (match-string 1 path)
9702 path (substring path 0 (match-beginning 0)))))
9703 (if (string-match "[*?{]" (file-name-nondirectory path))
9704 (dired path)
9705 (org-open-file path arg line search)))
9707 ((string= type "shell")
9708 (let ((cmd path))
9709 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
9710 (string-match org-confirm-shell-link-not-regexp cmd))
9711 (not org-confirm-shell-link-function)
9712 (funcall org-confirm-shell-link-function
9713 (format "Execute \"%s\" in shell? "
9714 (org-add-props cmd nil
9715 'face 'org-warning))))
9716 (progn
9717 (message "Executing %s" cmd)
9718 (shell-command cmd))
9719 (error "Abort"))))
9721 ((string= type "elisp")
9722 (let ((cmd path))
9723 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
9724 (string-match org-confirm-elisp-link-not-regexp cmd))
9725 (not org-confirm-elisp-link-function)
9726 (funcall org-confirm-elisp-link-function
9727 (format "Execute \"%s\" as elisp? "
9728 (org-add-props cmd nil
9729 'face 'org-warning))))
9730 (message "%s => %s" cmd
9731 (if (equal (string-to-char cmd) ?\()
9732 (eval (read cmd))
9733 (call-interactively (read cmd))))
9734 (error "Abort"))))
9736 ((and (string= type "thisfile")
9737 (run-hook-with-args-until-success
9738 'org-open-link-functions path)))
9740 ((string= type "thisfile")
9741 (if arg
9742 (switch-to-buffer-other-window
9743 (org-get-buffer-for-internal-link (current-buffer)))
9744 (org-mark-ring-push))
9745 (let ((cmd `(org-link-search
9746 ,path
9747 ,(cond ((equal arg '(4)) ''occur)
9748 ((equal arg '(16)) ''org-occur)
9749 (t nil))
9750 ,pos)))
9751 (condition-case nil (let ((org-link-search-inhibit-query t))
9752 (eval cmd))
9753 (error (progn (widen) (eval cmd))))))
9756 (browse-url-at-point)))))))
9757 (move-marker org-open-link-marker nil)
9758 (run-hook-with-args 'org-follow-link-hook)))
9760 (defun org-offer-links-in-entry (&optional nth zero)
9761 "Offer links in the current entry and follow the selected link.
9762 If there is only one link, follow it immediately as well.
9763 If NTH is an integer, immediately pick the NTH link found.
9764 If ZERO is a string, check also this string for a link, and if
9765 there is one, offer it as link number zero."
9766 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
9767 "\\(" org-angle-link-re "\\)\\|"
9768 "\\(" org-plain-link-re "\\)"))
9769 (cnt ?0)
9770 (in-emacs (if (integerp nth) nil nth))
9771 have-zero end links link c)
9772 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
9773 (push (match-string 0 zero) links)
9774 (setq cnt (1- cnt) have-zero t))
9775 (save-excursion
9776 (org-back-to-heading t)
9777 (setq end (save-excursion (outline-next-heading) (point)))
9778 (while (re-search-forward re end t)
9779 (push (match-string 0) links))
9780 (setq links (org-uniquify (reverse links))))
9782 (cond
9783 ((null links)
9784 (message "No links"))
9785 ((equal (length links) 1)
9786 (setq link (list (car links))))
9787 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
9788 (setq link (list (nth (if have-zero nth (1- nth)) links))))
9789 (t ; we have to select a link
9790 (save-excursion
9791 (save-window-excursion
9792 (delete-other-windows)
9793 (with-output-to-temp-buffer "*Select Link*"
9794 (mapc (lambda (l)
9795 (if (not (string-match org-bracket-link-regexp l))
9796 (princ (format "[%c] %s\n" (incf cnt)
9797 (org-remove-angle-brackets l)))
9798 (if (match-end 3)
9799 (princ (format "[%c] %s (%s)\n" (incf cnt)
9800 (match-string 3 l) (match-string 1 l)))
9801 (princ (format "[%c] %s\n" (incf cnt)
9802 (match-string 1 l))))))
9803 links))
9804 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
9805 (message "Select link to open, RET to open all:")
9806 (setq c (read-char-exclusive))
9807 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
9808 (when (equal c ?q) (error "Abort"))
9809 (if (equal c ?\C-m)
9810 (setq link links)
9811 (setq nth (- c ?0))
9812 (if have-zero (setq nth (1+ nth)))
9813 (unless (and (integerp nth) (>= (length links) nth))
9814 (error "Invalid link selection"))
9815 (setq link (list (nth (1- nth) links))))))
9816 (if link
9817 (let ((buf (current-buffer)))
9818 (dolist (l link)
9819 (org-open-link-from-string l in-emacs buf))
9821 nil)))
9823 ;; Add special file links that specify the way of opening
9825 (org-add-link-type "file+sys" 'org-open-file-with-system)
9826 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
9827 (defun org-open-file-with-system (path)
9828 "Open file at PATH using the system way of opening it."
9829 (org-open-file path 'system))
9830 (defun org-open-file-with-emacs (path)
9831 "Open file at PATH in Emacs."
9832 (org-open-file path 'emacs))
9833 (defun org-remove-file-link-modifiers ()
9834 "Remove the file link modifiers in `file+sys:' and `file+emacs:' links."
9835 (goto-char (point-min))
9836 (while (re-search-forward "\\<file\\+\\(sys\\|emacs\\):" nil t)
9837 (org-if-unprotected
9838 (replace-match "file:" t t))))
9839 (eval-after-load "org-exp"
9840 '(add-hook 'org-export-preprocess-before-normalizing-links-hook
9841 'org-remove-file-link-modifiers))
9843 ;;;; Time estimates
9845 (defun org-get-effort (&optional pom)
9846 "Get the effort estimate for the current entry."
9847 (org-entry-get pom org-effort-property))
9849 ;;; File search
9851 (defvar org-create-file-search-functions nil
9852 "List of functions to construct the right search string for a file link.
9853 These functions are called in turn with point at the location to
9854 which the link should point.
9856 A function in the hook should first test if it would like to
9857 handle this file type, for example by checking the `major-mode'
9858 or the file extension. If it decides not to handle this file, it
9859 should just return nil to give other functions a chance. If it
9860 does handle the file, it must return the search string to be used
9861 when following the link. The search string will be part of the
9862 file link, given after a double colon, and `org-open-at-point'
9863 will automatically search for it. If special measures must be
9864 taken to make the search successful, another function should be
9865 added to the companion hook `org-execute-file-search-functions',
9866 which see.
9868 A function in this hook may also use `setq' to set the variable
9869 `description' to provide a suggestion for the descriptive text to
9870 be used for this link when it gets inserted into an Org-mode
9871 buffer with \\[org-insert-link].")
9873 (defvar org-execute-file-search-functions nil
9874 "List of functions to execute a file search triggered by a link.
9876 Functions added to this hook must accept a single argument, the
9877 search string that was part of the file link, the part after the
9878 double colon. The function must first check if it would like to
9879 handle this search, for example by checking the `major-mode' or
9880 the file extension. If it decides not to handle this search, it
9881 should just return nil to give other functions a chance. If it
9882 does handle the search, it must return a non-nil value to keep
9883 other functions from trying.
9885 Each function can access the current prefix argument through the
9886 variable `current-prefix-argument'. Note that a single prefix is
9887 used to force opening a link in Emacs, so it may be good to only
9888 use a numeric or double prefix to guide the search function.
9890 In case this is needed, a function in this hook can also restore
9891 the window configuration before `org-open-at-point' was called using:
9893 (set-window-configuration org-window-config-before-follow-link)")
9895 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
9896 (defun org-link-search (s &optional type avoid-pos stealth)
9897 "Search for a link search option.
9898 If S is surrounded by forward slashes, it is interpreted as a
9899 regular expression. In org-mode files, this will create an `org-occur'
9900 sparse tree. In ordinary files, `occur' will be used to list matches.
9901 If the current buffer is in `dired-mode', grep will be used to search
9902 in all files. If AVOID-POS is given, ignore matches near that position.
9904 When optional argument STEALTH is non-nil, do not modify
9905 visibility around point, thus ignoring
9906 `org-show-hierarchy-above', `org-show-following-heading' and
9907 `org-show-siblings' variables."
9908 (let ((case-fold-search t)
9909 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
9910 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
9911 (append '(("") (" ") ("\t") ("\n"))
9912 org-emphasis-alist)
9913 "\\|") "\\)"))
9914 (pos (point))
9915 (pre nil) (post nil)
9916 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
9917 (cond
9918 ;; First check if there are any special search functions
9919 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
9920 ;; Now try the builtin stuff
9921 ((and (equal (string-to-char s0) ?#)
9922 (> (length s0) 1)
9923 (save-excursion
9924 (goto-char (point-min))
9925 (and
9926 (re-search-forward
9927 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
9928 (setq type 'dedicated
9929 pos (match-beginning 0))))
9930 ;; There is an exact target for this
9931 (goto-char pos)
9932 (org-back-to-heading t)))
9933 ((save-excursion
9934 (goto-char (point-min))
9935 (and
9936 (re-search-forward
9937 (concat "<<" (regexp-quote s0) ">>") nil t)
9938 (setq type 'dedicated
9939 pos (match-beginning 0))))
9940 ;; There is an exact target for this
9941 (goto-char pos))
9942 ((save-excursion
9943 (goto-char (point-min))
9944 (and
9945 (re-search-forward
9946 (format "^[ \t]*#\\+TARGET: %s" (regexp-quote s0)) nil t)
9947 (setq type 'dedicated pos (match-beginning 0))))
9948 ;; Found an invisible target.
9949 (goto-char pos))
9950 ((save-excursion
9951 (goto-char (point-min))
9952 (and
9953 (re-search-forward
9954 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
9955 (setq type 'dedicated pos (match-beginning 0))))
9956 ;; Found an element with a matching #+name affiliated keyword.
9957 (goto-char pos))
9958 ((and (string-match "^(\\(.*\\))$" s0)
9959 (save-excursion
9960 (goto-char (point-min))
9961 (and
9962 (re-search-forward
9963 (concat "[^[]" (regexp-quote
9964 (format org-coderef-label-format
9965 (match-string 1 s0))))
9966 nil t)
9967 (setq type 'dedicated
9968 pos (1+ (match-beginning 0))))))
9969 ;; There is a coderef target for this
9970 (goto-char pos))
9971 ((string-match "^/\\(.*\\)/$" s)
9972 ;; A regular expression
9973 (cond
9974 ((derived-mode-p 'org-mode)
9975 (org-occur (match-string 1 s)))
9976 ;;((eq major-mode 'dired-mode)
9977 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
9978 (t (org-do-occur (match-string 1 s)))))
9979 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
9980 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
9981 (goto-char (point-min))
9982 (cond
9983 ((let (case-fold-search)
9984 (re-search-forward (format org-complex-heading-regexp-format
9985 (regexp-quote s))
9986 nil t))
9987 ;; OK, found a match
9988 (setq type 'dedicated)
9989 (goto-char (match-beginning 0)))
9990 ((and (not org-link-search-inhibit-query)
9991 (eq org-link-search-must-match-exact-headline 'query-to-create)
9992 (y-or-n-p "No match - create this as a new heading? "))
9993 (goto-char (point-max))
9994 (or (bolp) (newline))
9995 (insert "* " s "\n")
9996 (beginning-of-line 0))
9998 (goto-char pos)
9999 (error "No match"))))
10001 ;; A normal search string
10002 (when (equal (string-to-char s) ?*)
10003 ;; Anchor on headlines, post may include tags.
10004 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10005 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10006 s (substring s 1)))
10007 (remove-text-properties
10008 0 (length s)
10009 '(face nil mouse-face nil keymap nil fontified nil) s)
10010 ;; Make a series of regular expressions to find a match
10011 (setq words (org-split-string s "[ \n\r\t]+")
10013 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10014 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10015 "\\)" markers)
10016 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
10017 re2a (concat "[ \t\r\n]" re2a_)
10018 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10019 re4 (concat "[^a-zA-Z_]" re4_)
10021 re1 (concat pre re2 post)
10022 re3 (concat pre (if pre re4_ re4) post)
10023 re5 (concat pre ".*" re4)
10024 re2 (concat pre re2)
10025 re2a (concat pre (if pre re2a_ re2a))
10026 re4 (concat pre (if pre re4_ re4))
10027 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10028 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10029 re5 "\\)"
10031 (cond
10032 ((eq type 'org-occur) (org-occur reall))
10033 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10034 (t (goto-char (point-min))
10035 (setq type 'fuzzy)
10036 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
10037 (org-search-not-self 1 re1 nil t)
10038 (org-search-not-self 1 re2 nil t)
10039 (org-search-not-self 1 re2a nil t)
10040 (org-search-not-self 1 re3 nil t)
10041 (org-search-not-self 1 re4 nil t)
10042 (org-search-not-self 1 re5 nil t)
10044 (goto-char (match-beginning 1))
10045 (goto-char pos)
10046 (error "No match"))))))
10047 (and (derived-mode-p 'org-mode)
10048 (not stealth)
10049 (org-show-context 'link-search))
10050 type))
10052 (defun org-search-not-self (group &rest args)
10053 "Execute `re-search-forward', but only accept matches that do not
10054 enclose the position of `org-open-link-marker'."
10055 (let ((m org-open-link-marker))
10056 (catch 'exit
10057 (while (apply 're-search-forward args)
10058 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10059 (goto-char (match-end group))
10060 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10061 (> (match-beginning 0) (marker-position m))
10062 (< (match-end 0) (marker-position m)))
10063 (save-match-data
10064 (or (not (org-in-regexp
10065 org-bracket-link-analytic-regexp 1))
10066 (not (match-end 4)) ; no description
10067 (and (<= (match-beginning 4) (point))
10068 (>= (match-end 4) (point))))))
10069 (throw 'exit (point))))))))
10071 (defun org-get-buffer-for-internal-link (buffer)
10072 "Return a buffer to be used for displaying the link target of internal links."
10073 (cond
10074 ((not org-display-internal-link-with-indirect-buffer)
10075 buffer)
10076 ((string-match "(Clone)$" (buffer-name buffer))
10077 (message "Buffer is already a clone, not making another one")
10078 ;; we also do not modify visibility in this case
10079 buffer)
10080 (t ; make a new indirect buffer for displaying the link
10081 (let* ((bn (buffer-name buffer))
10082 (ibn (concat bn "(Clone)"))
10083 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10084 (with-current-buffer ib (org-overview))
10085 ib))))
10087 (defun org-do-occur (regexp &optional cleanup)
10088 "Call the Emacs command `occur'.
10089 If CLEANUP is non-nil, remove the printout of the regular expression
10090 in the *Occur* buffer. This is useful if the regex is long and not useful
10091 to read."
10092 (occur regexp)
10093 (when cleanup
10094 (let ((cwin (selected-window)) win beg end)
10095 (when (setq win (get-buffer-window "*Occur*"))
10096 (select-window win))
10097 (goto-char (point-min))
10098 (when (re-search-forward "match[a-z]+" nil t)
10099 (setq beg (match-end 0))
10100 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10101 (setq end (1- (match-beginning 0)))))
10102 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10103 (goto-char (point-min))
10104 (select-window cwin))))
10106 ;;; The mark ring for links jumps
10108 (defvar org-mark-ring nil
10109 "Mark ring for positions before jumps in Org-mode.")
10110 (defvar org-mark-ring-last-goto nil
10111 "Last position in the mark ring used to go back.")
10112 ;; Fill and close the ring
10113 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10114 (loop for i from 1 to org-mark-ring-length do
10115 (push (make-marker) org-mark-ring))
10116 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10117 org-mark-ring)
10119 (defun org-mark-ring-push (&optional pos buffer)
10120 "Put the current position or POS into the mark ring and rotate it."
10121 (interactive)
10122 (setq pos (or pos (point)))
10123 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10124 (move-marker (car org-mark-ring)
10125 (or pos (point))
10126 (or buffer (current-buffer)))
10127 (message "%s"
10128 (substitute-command-keys
10129 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10131 (defun org-mark-ring-goto (&optional n)
10132 "Jump to the previous position in the mark ring.
10133 With prefix arg N, jump back that many stored positions. When
10134 called several times in succession, walk through the entire ring.
10135 Org-mode commands jumping to a different position in the current file,
10136 or to another Org-mode file, automatically push the old position
10137 onto the ring."
10138 (interactive "p")
10139 (let (p m)
10140 (if (eq last-command this-command)
10141 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10142 (setq p org-mark-ring))
10143 (setq org-mark-ring-last-goto p)
10144 (setq m (car p))
10145 (org-pop-to-buffer-same-window (marker-buffer m))
10146 (goto-char m)
10147 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10149 (defun org-remove-angle-brackets (s)
10150 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10151 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10153 (defun org-add-angle-brackets (s)
10154 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10155 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10157 (defun org-remove-double-quotes (s)
10158 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10159 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10162 ;;; Following specific links
10164 (defun org-follow-timestamp-link ()
10165 (cond
10166 ((org-at-date-range-p t)
10167 (let ((org-agenda-start-on-weekday)
10168 (t1 (match-string 1))
10169 (t2 (match-string 2)))
10170 (setq t1 (time-to-days (org-time-string-to-time t1))
10171 t2 (time-to-days (org-time-string-to-time t2)))
10172 (org-agenda-list nil t1 (1+ (- t2 t1)))))
10173 ((org-at-timestamp-p t)
10174 (org-agenda-list nil (time-to-days (org-time-string-to-time
10175 (substring (match-string 1) 0 10)))
10177 (t (error "This should not happen"))))
10180 ;;; Following file links
10181 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10182 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10183 (declare-function mailcap-mime-info
10184 "mailcap" (string &optional request no-decode))
10185 (defvar org-wait nil)
10186 (defun org-open-file (path &optional in-emacs line search)
10187 "Open the file at PATH.
10188 First, this expands any special file name abbreviations. Then the
10189 configuration variable `org-file-apps' is checked if it contains an
10190 entry for this file type, and if yes, the corresponding command is launched.
10192 If no application is found, Emacs simply visits the file.
10194 With optional prefix argument IN-EMACS, Emacs will visit the file.
10195 With a double \\[universal-argument] \\[universal-argument] \
10196 prefix arg, Org tries to avoid opening in Emacs
10197 and to use an external application to visit the file.
10199 Optional LINE specifies a line to go to, optional SEARCH a string
10200 to search for. If LINE or SEARCH is given, the file will be
10201 opened in Emacs, unless an entry from org-file-apps that makes
10202 use of groups in a regexp matches.
10204 If you want to change the way frames are used when following a
10205 link, please customize `org-link-frame-setup'.
10207 If the file does not exist, an error is thrown."
10208 (let* ((file (if (equal path "")
10209 buffer-file-name
10210 (substitute-in-file-name (expand-file-name path))))
10211 (file-apps (append org-file-apps (org-default-apps)))
10212 (apps (org-remove-if
10213 'org-file-apps-entry-match-against-dlink-p file-apps))
10214 (apps-dlink (org-remove-if-not
10215 'org-file-apps-entry-match-against-dlink-p file-apps))
10216 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10217 (dirp (if remp nil (file-directory-p file)))
10218 (file (if (and dirp org-open-directory-means-index-dot-org)
10219 (concat (file-name-as-directory file) "index.org")
10220 file))
10221 (a-m-a-p (assq 'auto-mode apps))
10222 (dfile (downcase file))
10223 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10224 (link (cond ((and (eq line nil)
10225 (eq search nil))
10226 file)
10227 (line
10228 (concat file "::" (number-to-string line)))
10229 (search
10230 (concat file "::" search))))
10231 (dlink (downcase link))
10232 (old-buffer (current-buffer))
10233 (old-pos (point))
10234 (old-mode major-mode)
10235 ext cmd link-match-data)
10236 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10237 (setq ext (match-string 1 dfile))
10238 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10239 (setq ext (match-string 1 dfile))))
10240 (cond
10241 ((member in-emacs '((16) system))
10242 (setq cmd (cdr (assoc 'system apps))))
10243 (in-emacs (setq cmd 'emacs))
10245 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10246 (and dirp (cdr (assoc 'directory apps)))
10247 ; first, try matching against apps-dlink
10248 ; if we get a match here, store the match data for later
10249 (let ((match (assoc-default dlink apps-dlink
10250 'string-match)))
10251 (if match
10252 (progn (setq link-match-data (match-data))
10253 match)
10254 (progn (setq in-emacs (or in-emacs line search))
10255 nil))) ; if we have no match in apps-dlink,
10256 ; always open the file in emacs if line or search
10257 ; is given (for backwards compatibility)
10258 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10259 'string-match)
10260 (cdr (assoc ext apps))
10261 (cdr (assoc t apps))))))
10262 (when (eq cmd 'system)
10263 (setq cmd (cdr (assoc 'system apps))))
10264 (when (eq cmd 'default)
10265 (setq cmd (cdr (assoc t apps))))
10266 (when (eq cmd 'mailcap)
10267 (require 'mailcap)
10268 (mailcap-parse-mailcaps)
10269 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10270 (command (mailcap-mime-info mime-type)))
10271 (if (stringp command)
10272 (setq cmd command)
10273 (setq cmd 'emacs))))
10274 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10275 (not (file-exists-p file))
10276 (not org-open-non-existing-files))
10277 (error "No such file: %s" file))
10278 (cond
10279 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10280 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10281 (while (string-match "['\"]%s['\"]" cmd)
10282 (setq cmd (replace-match "%s" t t cmd)))
10283 (while (string-match "%s" cmd)
10284 (setq cmd (replace-match
10285 (save-match-data
10286 (shell-quote-argument
10287 (convert-standard-filename file)))
10288 t t cmd)))
10290 ;; Replace "%1", "%2" etc. in command with group matches from regex
10291 (save-match-data
10292 (let ((match-index 1)
10293 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10294 (set-match-data link-match-data)
10295 (while (<= match-index number-of-groups)
10296 (let ((regex (concat "%" (number-to-string match-index)))
10297 (replace-with (match-string match-index dlink)))
10298 (while (string-match regex cmd)
10299 (setq cmd (replace-match replace-with t t cmd))))
10300 (setq match-index (+ match-index 1)))))
10302 (save-window-excursion
10303 (start-process-shell-command cmd nil cmd)
10304 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
10306 ((or (stringp cmd)
10307 (eq cmd 'emacs))
10308 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10309 (widen)
10310 (if line (org-goto-line line)
10311 (if search (org-link-search search))))
10312 ((consp cmd)
10313 (let ((file (convert-standard-filename file)))
10314 (save-match-data
10315 (set-match-data link-match-data)
10316 (eval cmd))))
10317 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10318 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
10319 (or (not (equal old-buffer (current-buffer)))
10320 (not (equal old-pos (point))))
10321 (org-mark-ring-push old-pos old-buffer))))
10323 (defun org-file-apps-entry-match-against-dlink-p (entry)
10324 "This function returns non-nil if `entry' uses a regular
10325 expression which should be matched against the whole link by
10326 org-open-file.
10328 It assumes that is the case when the entry uses a regular
10329 expression which has at least one grouping construct and the
10330 action is either a lisp form or a command string containing
10331 '%1', i.e. using at least one subexpression match as a
10332 parameter."
10333 (let ((selector (car entry))
10334 (action (cdr entry)))
10335 (if (stringp selector)
10336 (and (> (regexp-opt-depth selector) 0)
10337 (or (and (stringp action)
10338 (string-match "%[0-9]" action))
10339 (consp action)))
10340 nil)))
10342 (defun org-default-apps ()
10343 "Return the default applications for this operating system."
10344 (cond
10345 ((eq system-type 'darwin)
10346 org-file-apps-defaults-macosx)
10347 ((eq system-type 'windows-nt)
10348 org-file-apps-defaults-windowsnt)
10349 (t org-file-apps-defaults-gnu)))
10351 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10352 "Convert extensions to regular expressions in the cars of LIST.
10353 Also, weed out any non-string entries, because the return value is used
10354 only for regexp matching.
10355 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10356 point to the symbol `emacs', indicating that the file should
10357 be opened in Emacs."
10358 (append
10359 (delq nil
10360 (mapcar (lambda (x)
10361 (if (not (stringp (car x)))
10363 (if (string-match "\\W" (car x))
10365 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10366 list))
10367 (if add-auto-mode
10368 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10370 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10371 (defun org-file-remote-p (file)
10372 "Test whether FILE specifies a location on a remote system.
10373 Return non-nil if the location is indeed remote.
10375 For example, the filename \"/user@host:/foo\" specifies a location
10376 on the system \"/user@host:\"."
10377 (cond ((fboundp 'file-remote-p)
10378 (file-remote-p file))
10379 ((fboundp 'tramp-handle-file-remote-p)
10380 (tramp-handle-file-remote-p file))
10381 ((and (boundp 'ange-ftp-name-format)
10382 (string-match (car ange-ftp-name-format) file))
10384 (t nil)))
10387 ;;;; Refiling
10389 (defun org-get-org-file ()
10390 "Read a filename, with default directory `org-directory'."
10391 (let ((default (or org-default-notes-file remember-data-file)))
10392 (read-file-name (format "File name [%s]: " default)
10393 (file-name-as-directory org-directory)
10394 default)))
10396 (defun org-notes-order-reversed-p ()
10397 "Check if the current file should receive notes in reversed order."
10398 (cond
10399 ((not org-reverse-note-order) nil)
10400 ((eq t org-reverse-note-order) t)
10401 ((not (listp org-reverse-note-order)) nil)
10402 (t (catch 'exit
10403 (let ((all org-reverse-note-order)
10404 entry)
10405 (while (setq entry (pop all))
10406 (if (string-match (car entry) buffer-file-name)
10407 (throw 'exit (cdr entry))))
10408 nil)))))
10410 (defvar org-refile-target-table nil
10411 "The list of refile targets, created by `org-refile'.")
10413 (defvar org-agenda-new-buffers nil
10414 "Buffers created to visit agenda files.")
10416 (defvar org-refile-cache nil
10417 "Cache for refile targets.")
10419 (defvar org-refile-markers nil
10420 "All the markers used for caching refile locations.")
10422 (defun org-refile-marker (pos)
10423 "Get a new refile marker, but only if caching is in use."
10424 (if (not org-refile-use-cache)
10426 (let ((m (make-marker)))
10427 (move-marker m pos)
10428 (push m org-refile-markers)
10429 m)))
10431 (defun org-refile-cache-clear ()
10432 "Clear the refile cache and disable all the markers."
10433 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
10434 (setq org-refile-markers nil)
10435 (setq org-refile-cache nil)
10436 (message "Refile cache has been cleared"))
10438 (defun org-refile-cache-check-set (set)
10439 "Check if all the markers in the cache still have live buffers."
10440 (let (marker)
10441 (catch 'exit
10442 (while (and set (setq marker (nth 3 (pop set))))
10443 ;; if org-refile-use-outline-path is 'file, marker may be nil
10444 (when (and marker (null (marker-buffer marker)))
10445 (message "not found") (sit-for 3)
10446 (throw 'exit nil)))
10447 t)))
10449 (defun org-refile-cache-put (set &rest identifiers)
10450 "Push the refile targets SET into the cache, under IDENTIFIERS."
10451 (let* ((key (sha1 (prin1-to-string identifiers)))
10452 (entry (assoc key org-refile-cache)))
10453 (if entry
10454 (setcdr entry set)
10455 (push (cons key set) org-refile-cache))))
10457 (defun org-refile-cache-get (&rest identifiers)
10458 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10459 (cond
10460 ((not org-refile-cache) nil)
10461 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10463 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10464 org-refile-cache))))
10465 (and set (org-refile-cache-check-set set) set)))))
10467 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
10468 "Produce a table with refile targets."
10469 (let ((case-fold-search nil)
10470 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10471 (entries (or org-refile-targets '((nil . (:level . 1)))))
10472 targets tgs txt re files f desc descre fast-path-p level pos0)
10473 (message "Getting targets...")
10474 (with-current-buffer (or default-buffer (current-buffer))
10475 (while (setq entry (pop entries))
10476 (setq files (car entry) desc (cdr entry))
10477 (setq fast-path-p nil)
10478 (cond
10479 ((null files) (setq files (list (current-buffer))))
10480 ((eq files 'org-agenda-files)
10481 (setq files (org-agenda-files 'unrestricted)))
10482 ((and (symbolp files) (fboundp files))
10483 (setq files (funcall files)))
10484 ((and (symbolp files) (boundp files))
10485 (setq files (symbol-value files))))
10486 (if (stringp files) (setq files (list files)))
10487 (cond
10488 ((eq (car desc) :tag)
10489 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
10490 ((eq (car desc) :todo)
10491 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
10492 ((eq (car desc) :regexp)
10493 (setq descre (cdr desc)))
10494 ((eq (car desc) :level)
10495 (setq descre (concat "^\\*\\{" (number-to-string
10496 (if org-odd-levels-only
10497 (1- (* 2 (cdr desc)))
10498 (cdr desc)))
10499 "\\}[ \t]")))
10500 ((eq (car desc) :maxlevel)
10501 (setq fast-path-p t)
10502 (setq descre (concat "^\\*\\{1," (number-to-string
10503 (if org-odd-levels-only
10504 (1- (* 2 (cdr desc)))
10505 (cdr desc)))
10506 "\\}[ \t]")))
10507 (t (error "Bad refiling target description %s" desc)))
10508 (while (setq f (pop files))
10509 (with-current-buffer
10510 (if (bufferp f) f (org-get-agenda-file-buffer f))
10512 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
10513 (progn
10514 (if (bufferp f) (setq f (buffer-file-name
10515 (buffer-base-buffer f))))
10516 (setq f (and f (expand-file-name f)))
10517 (if (eq org-refile-use-outline-path 'file)
10518 (push (list (file-name-nondirectory f) f nil nil) tgs))
10519 (save-excursion
10520 (save-restriction
10521 (widen)
10522 (goto-char (point-min))
10523 (while (re-search-forward descre nil t)
10524 (goto-char (setq pos0 (point-at-bol)))
10525 (catch 'next
10526 (when org-refile-target-verify-function
10527 (save-match-data
10528 (or (funcall org-refile-target-verify-function)
10529 (throw 'next t))))
10530 (when (and (looking-at org-complex-heading-regexp)
10531 (not (member (match-string 4) excluded-entries))
10532 (match-string 4))
10533 (setq level (org-reduced-level
10534 (- (match-end 1) (match-beginning 1)))
10535 txt (org-link-display-format (match-string 4))
10536 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
10537 re (format org-complex-heading-regexp-format
10538 (regexp-quote (match-string 4))))
10539 (when org-refile-use-outline-path
10540 (setq txt (mapconcat
10541 'org-protect-slash
10542 (append
10543 (if (eq org-refile-use-outline-path
10544 'file)
10545 (list (file-name-nondirectory
10546 (buffer-file-name
10547 (buffer-base-buffer))))
10548 (if (eq org-refile-use-outline-path
10549 'full-file-path)
10550 (list (buffer-file-name
10551 (buffer-base-buffer)))))
10552 (org-get-outline-path fast-path-p
10553 level txt)
10554 (list txt))
10555 "/")))
10556 (push (list txt f re (org-refile-marker (point)))
10557 tgs)))
10558 (when (= (point) pos0)
10559 ;; verification function has not moved point
10560 (goto-char (point-at-eol))))))))
10561 (when org-refile-use-cache
10562 (org-refile-cache-put tgs (buffer-file-name) descre))
10563 (setq targets (append tgs targets))
10564 ))))
10565 (message "Getting targets...done")
10566 (nreverse targets)))
10568 (defun org-protect-slash (s)
10569 (while (string-match "/" s)
10570 (setq s (replace-match "\\" t t s)))
10573 (defvar org-olpa (make-vector 20 nil))
10575 (defun org-get-outline-path (&optional fastp level heading)
10576 "Return the outline path to the current entry, as a list.
10578 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
10579 routine which makes outline path derivations for an entire file,
10580 avoiding backtracing. Refile target collection makes use of that."
10581 (if fastp
10582 (progn
10583 (if (> level 19)
10584 (error "Outline path failure, more than 19 levels"))
10585 (loop for i from level upto 19 do
10586 (aset org-olpa i nil))
10587 (prog1
10588 (delq nil (append org-olpa nil))
10589 (aset org-olpa level heading)))
10590 (let (rtn case-fold-search)
10591 (save-excursion
10592 (save-restriction
10593 (widen)
10594 (while (org-up-heading-safe)
10595 (when (looking-at org-complex-heading-regexp)
10596 (push (org-match-string-no-properties 4) rtn)))
10597 rtn)))))
10599 (defun org-format-outline-path (path &optional width prefix)
10600 "Format the outline path PATH for display.
10601 Width is the maximum number of characters that is available.
10602 Prefix is a prefix to be included in the returned string,
10603 such as the file name."
10604 (setq width (or width 79))
10605 (if prefix (setq width (- width (length prefix))))
10606 (if (not path)
10607 (or prefix "")
10608 (let* ((nsteps (length path))
10609 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
10610 (maxwidth (if (<= total-width width)
10611 10000 ;; everything fits
10612 ;; we need to shorten the level headings
10613 (/ (- width nsteps) nsteps)))
10614 (org-odd-levels-only nil)
10615 (n 0)
10616 (total (1+ (length prefix))))
10617 (setq maxwidth (max maxwidth 10))
10618 (concat prefix
10619 (mapconcat
10620 (lambda (h)
10621 (setq n (1+ n))
10622 (if (and (= n nsteps) (< maxwidth 10000))
10623 (setq maxwidth (- total-width total)))
10624 (if (< (length h) maxwidth)
10625 (progn (setq total (+ total (length h) 1)) h)
10626 (setq h (substring h 0 (- maxwidth 2))
10627 total (+ total maxwidth 1))
10628 (if (string-match "[ \t]+\\'" h)
10629 (setq h (substring h 0 (match-beginning 0))))
10630 (setq h (concat h "..")))
10631 (org-add-props h nil 'face
10632 (nth (% (1- n) org-n-level-faces)
10633 org-level-faces))
10635 path "/")))))
10637 (defun org-display-outline-path (&optional file current)
10638 "Display the current outline path in the echo area."
10639 (interactive "P")
10640 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
10641 (case-fold-search nil)
10642 (path (and (derived-mode-p 'org-mode) (org-get-outline-path))))
10643 (if current (setq path (append path
10644 (save-excursion
10645 (org-back-to-heading t)
10646 (if (looking-at org-complex-heading-regexp)
10647 (list (match-string 4)))))))
10648 (message "%s"
10649 (org-format-outline-path
10650 path
10651 (1- (frame-width))
10652 (and file bfn (concat (file-name-nondirectory bfn) "/"))))))
10654 (defvar org-refile-history nil
10655 "History for refiling operations.")
10657 (defvar org-after-refile-insert-hook nil
10658 "Hook run after `org-refile' has inserted its stuff at the new location.
10659 Note that this is still *before* the stuff will be removed from
10660 the *old* location.")
10662 (defvar org-capture-last-stored-marker)
10663 (defun org-refile (&optional goto default-buffer rfloc)
10664 "Move the entry or entries at point to another heading.
10665 The list of target headings is compiled using the information in
10666 `org-refile-targets', which see.
10668 At the target location, the entry is filed as a subitem of the target
10669 heading. Depending on `org-reverse-note-order', the new subitem will
10670 either be the first or the last subitem.
10672 If there is an active region, all entries in that region will be moved.
10673 However, the region must fulfill the requirement that the first heading
10674 is the first one sets the top-level of the moved text - at most siblings
10675 below it are allowed.
10677 With prefix arg GOTO, the command will only visit the target location
10678 and not actually move anything.
10680 With a double prefix arg \\[universal-argument] \\[universal-argument], \
10681 go to the location where the last refiling operation has put the subtree.
10682 With a prefix argument of `2', refile to the running clock.
10684 RFLOC can be a refile location obtained in a different way.
10686 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
10688 If you are using target caching (see `org-refile-use-cache'),
10689 You have to clear the target cache in order to find new targets.
10690 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
10691 prefix argument (`C-u C-u C-u C-c C-w')."
10693 (interactive "P")
10694 (if (member goto '(0 (64)))
10695 (org-refile-cache-clear)
10696 (let* ((cbuf (current-buffer))
10697 (regionp (org-region-active-p))
10698 (region-start (and regionp (region-beginning)))
10699 (region-end (and regionp (region-end)))
10700 (region-length (and regionp (- region-end region-start)))
10701 (filename (buffer-file-name (buffer-base-buffer cbuf)))
10702 pos it nbuf file re level reversed)
10703 (setq last-command nil)
10704 (when regionp
10705 (goto-char region-start)
10706 (or (bolp) (goto-char (point-at-bol)))
10707 (setq region-start (point))
10708 (unless (or (org-kill-is-subtree-p
10709 (buffer-substring region-start region-end))
10710 (prog1 org-refile-active-region-within-subtree
10711 (org-toggle-heading)))
10712 (error "The region is not a (sequence of) subtree(s)")))
10713 (if (equal goto '(16))
10714 (org-refile-goto-last-stored)
10715 (when (or
10716 (and (equal goto 2)
10717 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
10718 (prog1
10719 (setq it (list (or org-clock-heading "running clock")
10720 (buffer-file-name
10721 (marker-buffer org-clock-hd-marker))
10723 (marker-position org-clock-hd-marker)))
10724 (setq goto nil)))
10725 (setq it (or rfloc
10726 (let (heading-text)
10727 (save-excursion
10728 (unless goto
10729 (org-back-to-heading t)
10730 (setq heading-text
10731 (nth 4 (org-heading-components))))
10732 (org-refile-get-location
10733 (cond (goto "Goto")
10734 (regionp "Refile region to")
10735 (t (concat "Refile subtree \""
10736 heading-text "\" to")))
10737 default-buffer
10738 (and (not (equal '(4) goto))
10739 org-refile-allow-creating-parent-nodes)
10740 goto))))))
10741 (setq file (nth 1 it)
10742 re (nth 2 it)
10743 pos (nth 3 it))
10744 (if (and (not goto)
10746 (equal (buffer-file-name) file)
10747 (if regionp
10748 (and (>= pos region-start)
10749 (<= pos region-end))
10750 (and (>= pos (point))
10751 (< pos (save-excursion
10752 (org-end-of-subtree t t))))))
10753 (error "Cannot refile to position inside the tree or region"))
10755 (setq nbuf (or (find-buffer-visiting file)
10756 (find-file-noselect file)))
10757 (if goto
10758 (progn
10759 (org-pop-to-buffer-same-window nbuf)
10760 (goto-char pos)
10761 (org-show-context 'org-goto))
10762 (if regionp
10763 (progn
10764 (org-kill-new (buffer-substring region-start region-end))
10765 (org-save-markers-in-region region-start region-end))
10766 (org-copy-subtree 1 nil t))
10767 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
10768 (find-file-noselect file)))
10769 (setq reversed (org-notes-order-reversed-p))
10770 (save-excursion
10771 (save-restriction
10772 (widen)
10773 (if pos
10774 (progn
10775 (goto-char pos)
10776 (looking-at org-outline-regexp)
10777 (setq level (org-get-valid-level (funcall outline-level) 1))
10778 (goto-char
10779 (if reversed
10780 (or (outline-next-heading) (point-max))
10781 (or (save-excursion (org-get-next-sibling))
10782 (org-end-of-subtree t t)
10783 (point-max)))))
10784 (setq level 1)
10785 (if (not reversed)
10786 (goto-char (point-max))
10787 (goto-char (point-min))
10788 (or (outline-next-heading) (goto-char (point-max)))))
10789 (if (not (bolp)) (newline))
10790 (org-paste-subtree level)
10791 (when org-log-refile
10792 (org-add-log-setup 'refile nil nil 'findpos
10793 org-log-refile)
10794 (unless (eq org-log-refile 'note)
10795 (save-excursion (org-add-log-note))))
10796 (and org-auto-align-tags (org-set-tags nil t))
10797 (bookmark-set "org-refile-last-stored")
10798 ;; If we are refiling for capture, make sure that the
10799 ;; last-capture pointers point here
10800 (when (org-bound-and-true-p org-refile-for-capture)
10801 (bookmark-set "org-capture-last-stored-marker")
10802 (move-marker org-capture-last-stored-marker (point)))
10803 (if (fboundp 'deactivate-mark) (deactivate-mark))
10804 (run-hooks 'org-after-refile-insert-hook))))
10805 (if regionp
10806 (delete-region (point) (+ (point) region-length))
10807 (org-cut-subtree))
10808 (when (featurep 'org-inlinetask)
10809 (org-inlinetask-remove-END-maybe))
10810 (setq org-markers-to-move nil)
10811 (message "Refiled to \"%s\" in file %s" (car it) file)))))))
10813 (defun org-refile-goto-last-stored ()
10814 "Go to the location where the last refile was stored."
10815 (interactive)
10816 (bookmark-jump "org-refile-last-stored")
10817 (message "This is the location of the last refile"))
10819 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
10820 no-exclude)
10821 "Prompt the user for a refile location, using PROMPT.
10822 PROMPT should not be suffixed with a colon and a space, because
10823 this function appends the default value from
10824 `org-refile-history' automatically, if that is not empty.
10825 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
10826 this is used for the GOTO interface."
10827 (let ((org-refile-targets org-refile-targets)
10828 (org-refile-use-outline-path org-refile-use-outline-path)
10829 excluded-entries)
10830 (when (and (derived-mode-p 'org-mode)
10831 (not org-refile-use-cache)
10832 (not no-exclude))
10833 (org-map-tree
10834 (lambda()
10835 (setq excluded-entries
10836 (append excluded-entries (list (org-get-heading t t)))))))
10837 (setq org-refile-target-table
10838 (org-refile-get-targets default-buffer excluded-entries)))
10839 (unless org-refile-target-table
10840 (error "No refile targets"))
10841 (let* ((prompt (concat prompt
10842 (and (car org-refile-history)
10843 (concat " (default " (car org-refile-history) ")"))
10844 ": "))
10845 (cbuf (current-buffer))
10846 (partial-completion-mode nil)
10847 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
10848 (cfunc (if (and org-refile-use-outline-path
10849 org-outline-path-complete-in-steps)
10850 'org-olpath-completing-read
10851 'org-icompleting-read))
10852 (extra (if org-refile-use-outline-path "/" ""))
10853 (filename (and cfn (expand-file-name cfn)))
10854 (tbl (mapcar
10855 (lambda (x)
10856 (if (and (not (member org-refile-use-outline-path
10857 '(file full-file-path)))
10858 (not (equal filename (nth 1 x))))
10859 (cons (concat (car x) extra " ("
10860 (file-name-nondirectory (nth 1 x)) ")")
10861 (cdr x))
10862 (cons (concat (car x) extra) (cdr x))))
10863 org-refile-target-table))
10864 (completion-ignore-case t)
10865 pa answ parent-target child parent old-hist)
10866 (setq old-hist org-refile-history)
10867 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
10868 nil 'org-refile-history (car org-refile-history)))
10869 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
10870 (org-refile-check-position pa)
10871 (if pa
10872 (progn
10873 (when (or (not org-refile-history)
10874 (not (eq old-hist org-refile-history))
10875 (not (equal (car pa) (car org-refile-history))))
10876 (setq org-refile-history
10877 (cons (car pa) (if (assoc (car org-refile-history) tbl)
10878 org-refile-history
10879 (cdr org-refile-history))))
10880 (if (equal (car org-refile-history) (nth 1 org-refile-history))
10881 (pop org-refile-history)))
10883 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
10884 (progn
10885 (setq parent (match-string 1 answ)
10886 child (match-string 2 answ))
10887 (setq parent-target (or (assoc parent tbl)
10888 (assoc (concat parent "/") tbl)))
10889 (when (and parent-target
10890 (or (eq new-nodes t)
10891 (and (eq new-nodes 'confirm)
10892 (y-or-n-p (format "Create new node \"%s\"? "
10893 child)))))
10894 (org-refile-new-child parent-target child)))
10895 (error "Invalid target location")))))
10897 (declare-function org-string-nw-p "org-macs.el" (s))
10898 (defun org-refile-check-position (refile-pointer)
10899 "Check if the refile pointer matches the readline to which it points."
10900 (let* ((file (nth 1 refile-pointer))
10901 (re (nth 2 refile-pointer))
10902 (pos (nth 3 refile-pointer))
10903 buffer)
10904 (when (org-string-nw-p re)
10905 (setq buffer (if (markerp pos)
10906 (marker-buffer pos)
10907 (or (find-buffer-visiting file)
10908 (find-file-noselect file))))
10909 (with-current-buffer buffer
10910 (save-excursion
10911 (save-restriction
10912 (widen)
10913 (goto-char pos)
10914 (beginning-of-line 1)
10915 (unless (org-looking-at-p re)
10916 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
10918 (defun org-refile-new-child (parent-target child)
10919 "Use refile target PARENT-TARGET to add new CHILD below it."
10920 (unless parent-target
10921 (error "Cannot find parent for new node"))
10922 (let ((file (nth 1 parent-target))
10923 (pos (nth 3 parent-target))
10924 level)
10925 (with-current-buffer (or (find-buffer-visiting file)
10926 (find-file-noselect file))
10927 (save-excursion
10928 (save-restriction
10929 (widen)
10930 (if pos
10931 (goto-char pos)
10932 (goto-char (point-max))
10933 (if (not (bolp)) (newline)))
10934 (when (looking-at org-outline-regexp)
10935 (setq level (funcall outline-level))
10936 (org-end-of-subtree t t))
10937 (org-back-over-empty-lines)
10938 (insert "\n" (make-string
10939 (if pos (org-get-valid-level level 1) 1) ?*)
10940 " " child "\n")
10941 (beginning-of-line 0)
10942 (list (concat (car parent-target) "/" child) file "" (point)))))))
10944 (defun org-olpath-completing-read (prompt collection &rest args)
10945 "Read an outline path like a file name."
10946 (let ((thetable collection)
10947 (org-completion-use-ido nil) ; does not work with ido.
10948 (org-completion-use-iswitchb nil)) ; or iswitchb
10949 (apply
10950 'org-icompleting-read prompt
10951 (lambda (string predicate &optional flag)
10952 (let (rtn r f (l (length string)))
10953 (cond
10954 ((eq flag nil)
10955 ;; try completion
10956 (try-completion string thetable))
10957 ((eq flag t)
10958 ;; all-completions
10959 (setq rtn (all-completions string thetable predicate))
10960 (mapcar
10961 (lambda (x)
10962 (setq r (substring x l))
10963 (if (string-match " ([^)]*)$" x)
10964 (setq f (match-string 0 x))
10965 (setq f ""))
10966 (if (string-match "/" r)
10967 (concat string (substring r 0 (match-end 0)) f)
10969 rtn))
10970 ((eq flag 'lambda)
10971 ;; exact match?
10972 (assoc string thetable)))
10974 args)))
10976 ;;;; Dynamic blocks
10978 (defun org-find-dblock (name)
10979 "Find the first dynamic block with name NAME in the buffer.
10980 If not found, stay at current position and return nil."
10981 (let (pos)
10982 (save-excursion
10983 (goto-char (point-min))
10984 (setq pos (and (re-search-forward (concat "^[ \t]*#\\+BEGIN:[ \t]+" name "\\>")
10985 nil t)
10986 (match-beginning 0))))
10987 (if pos (goto-char pos))
10988 pos))
10990 (defconst org-dblock-start-re
10991 "^[ \t]*#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
10992 "Matches the start line of a dynamic block, with parameters.")
10994 (defconst org-dblock-end-re "^[ \t]*#\\+END\\([: \t\r\n]\\|$\\)"
10995 "Matches the end of a dynamic block.")
10997 (defun org-create-dblock (plist)
10998 "Create a dynamic block section, with parameters taken from PLIST.
10999 PLIST must contain a :name entry which is used as name of the block."
11000 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11001 (end-of-line 1)
11002 (newline))
11003 (let ((col (current-column))
11004 (name (plist-get plist :name)))
11005 (insert "#+BEGIN: " name)
11006 (while plist
11007 (if (eq (car plist) :name)
11008 (setq plist (cddr plist))
11009 (insert " " (prin1-to-string (pop plist)))))
11010 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11011 (beginning-of-line -2)))
11013 (defun org-prepare-dblock ()
11014 "Prepare dynamic block for refresh.
11015 This empties the block, puts the cursor at the insert position and returns
11016 the property list including an extra property :name with the block name."
11017 (unless (looking-at org-dblock-start-re)
11018 (error "Not at a dynamic block"))
11019 (let* ((begdel (1+ (match-end 0)))
11020 (name (org-no-properties (match-string 1)))
11021 (params (append (list :name name)
11022 (read (concat "(" (match-string 3) ")")))))
11023 (save-excursion
11024 (beginning-of-line 1)
11025 (skip-chars-forward " \t")
11026 (setq params (plist-put params :indentation-column (current-column))))
11027 (unless (re-search-forward org-dblock-end-re nil t)
11028 (error "Dynamic block not terminated"))
11029 (setq params
11030 (append params
11031 (list :content (buffer-substring
11032 begdel (match-beginning 0)))))
11033 (delete-region begdel (match-beginning 0))
11034 (goto-char begdel)
11035 (open-line 1)
11036 params))
11038 (defun org-map-dblocks (&optional command)
11039 "Apply COMMAND to all dynamic blocks in the current buffer.
11040 If COMMAND is not given, use `org-update-dblock'."
11041 (let ((cmd (or command 'org-update-dblock)))
11042 (save-excursion
11043 (goto-char (point-min))
11044 (while (re-search-forward org-dblock-start-re nil t)
11045 (goto-char (match-beginning 0))
11046 (save-excursion
11047 (condition-case nil
11048 (funcall cmd)
11049 (error (message "Error during update of dynamic block"))))
11050 (unless (re-search-forward org-dblock-end-re nil t)
11051 (error "Dynamic block not terminated"))))))
11053 (defun org-dblock-update (&optional arg)
11054 "User command for updating dynamic blocks.
11055 Update the dynamic block at point. With prefix ARG, update all dynamic
11056 blocks in the buffer."
11057 (interactive "P")
11058 (if arg
11059 (org-update-all-dblocks)
11060 (or (looking-at org-dblock-start-re)
11061 (org-beginning-of-dblock))
11062 (org-update-dblock)))
11064 (defun org-update-dblock ()
11065 "Update the dynamic block at point.
11066 This means to empty the block, parse for parameters and then call
11067 the correct writing function."
11068 (interactive)
11069 (save-window-excursion
11070 (let* ((pos (point))
11071 (line (org-current-line))
11072 (params (org-prepare-dblock))
11073 (name (plist-get params :name))
11074 (indent (plist-get params :indentation-column))
11075 (cmd (intern (concat "org-dblock-write:" name))))
11076 (message "Updating dynamic block `%s' at line %d..." name line)
11077 (funcall cmd params)
11078 (message "Updating dynamic block `%s' at line %d...done" name line)
11079 (goto-char pos)
11080 (when (and indent (> indent 0))
11081 (setq indent (make-string indent ?\ ))
11082 (save-excursion
11083 (org-beginning-of-dblock)
11084 (forward-line 1)
11085 (while (not (looking-at org-dblock-end-re))
11086 (insert indent)
11087 (beginning-of-line 2))
11088 (when (looking-at org-dblock-end-re)
11089 (and (looking-at "[ \t]+")
11090 (replace-match ""))
11091 (insert indent)))))))
11093 (defun org-beginning-of-dblock ()
11094 "Find the beginning of the dynamic block at point.
11095 Error if there is no such block at point."
11096 (let ((pos (point))
11097 beg)
11098 (end-of-line 1)
11099 (if (and (re-search-backward org-dblock-start-re nil t)
11100 (setq beg (match-beginning 0))
11101 (re-search-forward org-dblock-end-re nil t)
11102 (> (match-end 0) pos))
11103 (goto-char beg)
11104 (goto-char pos)
11105 (error "Not in a dynamic block"))))
11107 ;;;###autoload
11108 (defun org-update-all-dblocks ()
11109 "Update all dynamic blocks in the buffer.
11110 This function can be used in a hook."
11111 (interactive)
11112 (when (derived-mode-p 'org-mode)
11113 (org-map-dblocks 'org-update-dblock)))
11116 ;;;; Completion
11118 (defconst org-additional-option-like-keywords
11119 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML:"
11120 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook:"
11121 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"
11122 "LATEX_CLASS:" "LATEX_CLASS_OPTIONS:" "ATTR_LaTeX:"
11123 "BEGIN:" "END:"
11124 "ORGTBL" "TBLFM:" "TBLNAME:"
11125 "BEGIN_EXAMPLE" "END_EXAMPLE"
11126 "BEGIN_QUOTE" "END_QUOTE"
11127 "BEGIN_VERSE" "END_VERSE"
11128 "BEGIN_CENTER" "END_CENTER"
11129 "BEGIN_SRC" "END_SRC"
11130 "BEGIN_RESULT" "END_RESULT"
11131 "NAME:" "RESULTS:"
11132 "HEADER:" "HEADERS:"
11133 "CATEGORY:" "COLUMNS:" "PROPERTY:"
11134 "CAPTION:" "LABEL:"
11135 "SETUPFILE:"
11136 "INCLUDE:"
11137 "BIND:"
11138 "MACRO:"))
11140 (defcustom org-structure-template-alist
11142 ("s" "#+BEGIN_SRC ?\n\n#+END_SRC"
11143 "<src lang=\"?\">\n\n</src>")
11144 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE"
11145 "<example>\n?\n</example>")
11146 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE"
11147 "<quote>\n?\n</quote>")
11148 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE"
11149 "<verse>\n?\n</verse>")
11150 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER"
11151 "<center>\n?\n</center>")
11152 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11153 "<literal style=\"latex\">\n?\n</literal>")
11154 ("L" "#+LaTeX: "
11155 "<literal style=\"latex\">?</literal>")
11156 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
11157 "<literal style=\"html\">\n?\n</literal>")
11158 ("H" "#+HTML: "
11159 "<literal style=\"html\">?</literal>")
11160 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
11161 ("A" "#+ASCII: ")
11162 ("i" "#+INDEX: ?"
11163 "#+INDEX: ?")
11164 ("I" "#+INCLUDE %file ?"
11165 "<include file=%file markup=\"?\">")
11167 "Structure completion elements.
11168 This is a list of abbreviation keys and values. The value gets inserted
11169 if you type `<' followed by the key and then press the completion key,
11170 usually `M-TAB'. %file will be replaced by a file name after prompting
11171 for the file using completion. The cursor will be placed at the position
11172 of the `?` in the template.
11173 There are two templates for each key, the first uses the original Org syntax,
11174 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11175 the default when the /org-mtags.el/ module has been loaded. See also the
11176 variable `org-mtags-prefer-muse-templates'."
11177 :group 'org-completion
11178 :type '(repeat
11179 (string :tag "Key")
11180 (string :tag "Template")
11181 (string :tag "Muse Template")))
11183 (defun org-try-structure-completion ()
11184 "Try to complete a structure template before point.
11185 This looks for strings like \"<e\" on an otherwise empty line and
11186 expands them."
11187 (let ((l (buffer-substring (point-at-bol) (point)))
11189 (when (and (looking-at "[ \t]*$")
11190 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
11191 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
11192 (org-complete-expand-structure-template (+ -1 (point-at-bol)
11193 (match-beginning 1)) a)
11194 t)))
11196 (defun org-complete-expand-structure-template (start cell)
11197 "Expand a structure template."
11198 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
11199 (rpl (nth (if musep 2 1) cell))
11200 (ind ""))
11201 (delete-region start (point))
11202 (when (string-match "\\`#\\+" rpl)
11203 (cond
11204 ((bolp))
11205 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
11206 (setq ind (buffer-substring (point-at-bol) (point))))
11207 (t (newline))))
11208 (setq start (point))
11209 (if (string-match "%file" rpl)
11210 (setq rpl (replace-match
11211 (concat
11212 "\""
11213 (save-match-data
11214 (abbreviate-file-name (read-file-name "Include file: ")))
11215 "\"")
11216 t t rpl)))
11217 (setq rpl (mapconcat 'identity (split-string rpl "\n")
11218 (concat "\n" ind)))
11219 (insert rpl)
11220 (if (re-search-backward "\\?" start t) (delete-char 1))))
11222 ;;;; TODO, DEADLINE, Comments
11224 (defun org-toggle-comment ()
11225 "Change the COMMENT state of an entry."
11226 (interactive)
11227 (save-excursion
11228 (org-back-to-heading)
11229 (let (case-fold-search)
11230 (cond
11231 ((looking-at (format org-heading-keyword-regexp-format
11232 org-comment-string))
11233 (goto-char (match-end 1))
11234 (looking-at (concat " +" org-comment-string))
11235 (replace-match "" t t)
11236 (when (eolp) (insert " ")))
11237 ((looking-at org-outline-regexp)
11238 (goto-char (match-end 0))
11239 (insert org-comment-string " "))))))
11241 (defvar org-last-todo-state-is-todo nil
11242 "This is non-nil when the last TODO state change led to a TODO state.
11243 If the last change removed the TODO tag or switched to DONE, then
11244 this is nil.")
11246 (defvar org-setting-tags nil) ; dynamically skipped
11248 (defvar org-todo-setup-filter-hook nil
11249 "Hook for functions that pre-filter todo specs.
11250 Each function takes a todo spec and returns either nil or the spec
11251 transformed into canonical form." )
11253 (defvar org-todo-get-default-hook nil
11254 "Hook for functions that get a default item for todo.
11255 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11256 nil or a string to be used for the todo mark." )
11258 (defvar org-agenda-headline-snapshot-before-repeat)
11260 (defun org-current-effective-time ()
11261 "Return current time adjusted for `org-extend-today-until' variable"
11262 (let* ((ct (org-current-time))
11263 (dct (decode-time ct))
11264 (ct1
11265 (if (and org-use-effective-time
11266 (< (nth 2 dct) org-extend-today-until))
11267 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct))
11268 ct)))
11269 ct1))
11271 (defun org-todo-yesterday (&optional arg)
11272 "Like `org-todo' but the time of change will be 23:59 of yesterday."
11273 (interactive "P")
11274 (if (eq major-mode 'org-agenda-mode)
11275 (apply 'org-agenda-todo-yesterday arg)
11276 (let* ((hour (third (decode-time
11277 (org-current-time))))
11278 (org-extend-today-until (1+ hour)))
11279 (org-todo arg))))
11281 (defun org-todo (&optional arg)
11282 "Change the TODO state of an item.
11283 The state of an item is given by a keyword at the start of the heading,
11284 like
11285 *** TODO Write paper
11286 *** DONE Call mom
11288 The different keywords are specified in the variable `org-todo-keywords'.
11289 By default the available states are \"TODO\" and \"DONE\".
11290 So for this example: when the item starts with TODO, it is changed to DONE.
11291 When it starts with DONE, the DONE is removed. And when neither TODO nor
11292 DONE are present, add TODO at the beginning of the heading.
11294 With \\[universal-argument] prefix arg, use completion to determine the new \
11295 state.
11296 With numeric prefix arg, switch to that state.
11297 With a double \\[universal-argument] prefix, switch to the next set of TODO \
11298 keywords (nextset).
11299 With a triple \\[universal-argument] prefix, circumvent any state blocking.
11300 With a numeric prefix arg of 0, inhibit note taking for the change.
11302 For calling through lisp, arg is also interpreted in the following way:
11303 'none -> empty state
11304 \"\"(empty string) -> switch to empty state
11305 'done -> switch to DONE
11306 'nextset -> switch to the next set of keywords
11307 'previousset -> switch to the previous set of keywords
11308 \"WAITING\" -> switch to the specified keyword, but only if it
11309 really is a member of `org-todo-keywords'."
11310 (interactive "P")
11311 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11312 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
11313 'region-start-level 'region))
11314 org-loop-over-headlines-in-active-region)
11315 (org-map-entries
11316 `(org-todo ,arg)
11317 org-loop-over-headlines-in-active-region
11318 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
11319 (if (equal arg '(16)) (setq arg 'nextset))
11320 (let ((org-blocker-hook org-blocker-hook)
11321 (case-fold-search nil))
11322 (when (equal arg '(64))
11323 (setq arg nil org-blocker-hook nil))
11324 (when (and org-blocker-hook
11325 (or org-inhibit-blocking
11326 (org-entry-get nil "NOBLOCKING")))
11327 (setq org-blocker-hook nil))
11328 (save-excursion
11329 (catch 'exit
11330 (org-back-to-heading t)
11331 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
11332 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
11333 (looking-at "\\(?: *\\|[ \t]*$\\)"))
11334 (let* ((match-data (match-data))
11335 (startpos (point-at-bol))
11336 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
11337 (org-log-done org-log-done)
11338 (org-log-repeat org-log-repeat)
11339 (org-todo-log-states org-todo-log-states)
11340 (org-inhibit-logging
11341 (if (equal arg 0)
11342 (progn (setq arg nil) 'note) org-inhibit-logging))
11343 (this (match-string 1))
11344 (hl-pos (match-beginning 0))
11345 (head (org-get-todo-sequence-head this))
11346 (ass (assoc head org-todo-kwd-alist))
11347 (interpret (nth 1 ass))
11348 (done-word (nth 3 ass))
11349 (final-done-word (nth 4 ass))
11350 (org-last-state (or this ""))
11351 (completion-ignore-case t)
11352 (member (member this org-todo-keywords-1))
11353 (tail (cdr member))
11354 (org-state (cond
11355 ((and org-todo-key-trigger
11356 (or (and (equal arg '(4))
11357 (eq org-use-fast-todo-selection 'prefix))
11358 (and (not arg) org-use-fast-todo-selection
11359 (not (eq org-use-fast-todo-selection
11360 'prefix)))))
11361 ;; Use fast selection
11362 (org-fast-todo-selection))
11363 ((and (equal arg '(4))
11364 (or (not org-use-fast-todo-selection)
11365 (not org-todo-key-trigger)))
11366 ;; Read a state with completion
11367 (org-icompleting-read
11368 "State: " (mapcar (lambda(x) (list x))
11369 org-todo-keywords-1)
11370 nil t))
11371 ((eq arg 'right)
11372 (if this
11373 (if tail (car tail) nil)
11374 (car org-todo-keywords-1)))
11375 ((eq arg 'left)
11376 (if (equal member org-todo-keywords-1)
11378 (if this
11379 (nth (- (length org-todo-keywords-1)
11380 (length tail) 2)
11381 org-todo-keywords-1)
11382 (org-last org-todo-keywords-1))))
11383 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
11384 (setq arg nil))) ; hack to fall back to cycling
11385 (arg
11386 ;; user or caller requests a specific state
11387 (cond
11388 ((equal arg "") nil)
11389 ((eq arg 'none) nil)
11390 ((eq arg 'done) (or done-word (car org-done-keywords)))
11391 ((eq arg 'nextset)
11392 (or (car (cdr (member head org-todo-heads)))
11393 (car org-todo-heads)))
11394 ((eq arg 'previousset)
11395 (let ((org-todo-heads (reverse org-todo-heads)))
11396 (or (car (cdr (member head org-todo-heads)))
11397 (car org-todo-heads))))
11398 ((car (member arg org-todo-keywords-1)))
11399 ((stringp arg)
11400 (error "State `%s' not valid in this file" arg))
11401 ((nth (1- (prefix-numeric-value arg))
11402 org-todo-keywords-1))))
11403 ((null member) (or head (car org-todo-keywords-1)))
11404 ((equal this final-done-word) nil) ;; -> make empty
11405 ((null tail) nil) ;; -> first entry
11406 ((memq interpret '(type priority))
11407 (if (eq this-command last-command)
11408 (car tail)
11409 (if (> (length tail) 0)
11410 (or done-word (car org-done-keywords))
11411 nil)))
11413 (car tail))))
11414 (org-state (or
11415 (run-hook-with-args-until-success
11416 'org-todo-get-default-hook org-state org-last-state)
11417 org-state))
11418 (next (if org-state (concat " " org-state " ") " "))
11419 (change-plist (list :type 'todo-state-change :from this :to org-state
11420 :position startpos))
11421 dolog now-done-p)
11422 (when org-blocker-hook
11423 (setq org-last-todo-state-is-todo
11424 (not (member this org-done-keywords)))
11425 (unless (save-excursion
11426 (save-match-data
11427 (org-with-wide-buffer
11428 (run-hook-with-args-until-failure
11429 'org-blocker-hook change-plist))))
11430 (if (org-called-interactively-p 'interactive)
11431 (error "TODO state change from %s to %s blocked" this org-state)
11432 ;; fail silently
11433 (message "TODO state change from %s to %s blocked" this org-state)
11434 (throw 'exit nil))))
11435 (store-match-data match-data)
11436 (replace-match next t t)
11437 (unless (pos-visible-in-window-p hl-pos)
11438 (message "TODO state changed to %s" (org-trim next)))
11439 (unless head
11440 (setq head (org-get-todo-sequence-head org-state)
11441 ass (assoc head org-todo-kwd-alist)
11442 interpret (nth 1 ass)
11443 done-word (nth 3 ass)
11444 final-done-word (nth 4 ass)))
11445 (when (memq arg '(nextset previousset))
11446 (message "Keyword-Set %d/%d: %s"
11447 (- (length org-todo-sets) -1
11448 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
11449 (length org-todo-sets)
11450 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
11451 (setq org-last-todo-state-is-todo
11452 (not (member org-state org-done-keywords)))
11453 (setq now-done-p (and (member org-state org-done-keywords)
11454 (not (member this org-done-keywords))))
11455 (and logging (org-local-logging logging))
11456 (when (and (or org-todo-log-states org-log-done)
11457 (not (eq org-inhibit-logging t))
11458 (not (memq arg '(nextset previousset))))
11459 ;; we need to look at recording a time and note
11460 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
11461 (nth 2 (assoc this org-todo-log-states))))
11462 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
11463 (setq dolog 'time))
11464 (when (and org-state
11465 (member org-state org-not-done-keywords)
11466 (not (member this org-not-done-keywords)))
11467 ;; This is now a todo state and was not one before
11468 ;; If there was a CLOSED time stamp, get rid of it.
11469 (org-add-planning-info nil nil 'closed))
11470 (when (and now-done-p org-log-done)
11471 ;; It is now done, and it was not done before
11472 (org-add-planning-info 'closed (org-current-effective-time))
11473 (if (and (not dolog) (eq 'note org-log-done))
11474 (org-add-log-setup 'done org-state this 'findpos 'note)))
11475 (when (and org-state dolog)
11476 ;; This is a non-nil state, and we need to log it
11477 (org-add-log-setup 'state org-state this 'findpos dolog)))
11478 ;; Fixup tag positioning
11479 (org-todo-trigger-tag-changes org-state)
11480 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
11481 (when org-provide-todo-statistics
11482 (org-update-parent-todo-statistics))
11483 (run-hooks 'org-after-todo-state-change-hook)
11484 (if (and arg (not (member org-state org-done-keywords)))
11485 (setq head (org-get-todo-sequence-head org-state)))
11486 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
11487 ;; Do we need to trigger a repeat?
11488 (when now-done-p
11489 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
11490 ;; This is for the agenda, take a snapshot of the headline.
11491 (save-match-data
11492 (setq org-agenda-headline-snapshot-before-repeat
11493 (org-get-heading))))
11494 (org-auto-repeat-maybe org-state))
11495 ;; Fixup cursor location if close to the keyword
11496 (if (and (outline-on-heading-p)
11497 (not (bolp))
11498 (save-excursion (beginning-of-line 1)
11499 (looking-at org-todo-line-regexp))
11500 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
11501 (progn
11502 (goto-char (or (match-end 2) (match-end 1)))
11503 (and (looking-at " ") (just-one-space))))
11504 (when org-trigger-hook
11505 (save-excursion
11506 (run-hook-with-args 'org-trigger-hook change-plist)))))))))
11508 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
11509 "Block turning an entry into a TODO, using the hierarchy.
11510 This checks whether the current task should be blocked from state
11511 changes. Such blocking occurs when:
11513 1. The task has children which are not all in a completed state.
11515 2. A task has a parent with the property :ORDERED:, and there
11516 are siblings prior to the current task with incomplete
11517 status.
11519 3. The parent of the task is blocked because it has siblings that should
11520 be done first, or is child of a block grandparent TODO entry."
11522 (if (not org-enforce-todo-dependencies)
11523 t ; if locally turned off don't block
11524 (catch 'dont-block
11525 ;; If this is not a todo state change, or if this entry is already DONE,
11526 ;; do not block
11527 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11528 (member (plist-get change-plist :from)
11529 (cons 'done org-done-keywords))
11530 (member (plist-get change-plist :to)
11531 (cons 'todo org-not-done-keywords))
11532 (not (plist-get change-plist :to)))
11533 (throw 'dont-block t))
11534 ;; If this task has children, and any are undone, it's blocked
11535 (save-excursion
11536 (org-back-to-heading t)
11537 (let ((this-level (funcall outline-level)))
11538 (outline-next-heading)
11539 (let ((child-level (funcall outline-level)))
11540 (while (and (not (eobp))
11541 (> child-level this-level))
11542 ;; this todo has children, check whether they are all
11543 ;; completed
11544 (if (and (not (org-entry-is-done-p))
11545 (org-entry-is-todo-p))
11546 (throw 'dont-block nil))
11547 (outline-next-heading)
11548 (setq child-level (funcall outline-level))))))
11549 ;; Otherwise, if the task's parent has the :ORDERED: property, and
11550 ;; any previous siblings are undone, it's blocked
11551 (save-excursion
11552 (org-back-to-heading t)
11553 (let* ((pos (point))
11554 (parent-pos (and (org-up-heading-safe) (point))))
11555 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11556 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11557 (forward-line 1)
11558 (re-search-forward org-not-done-heading-regexp pos t))
11559 (throw 'dont-block nil)) ; block, there is an older sibling not done.
11560 ;; Search further up the hierarchy, to see if an ancestor is blocked
11561 (while t
11562 (goto-char parent-pos)
11563 (if (not (looking-at org-not-done-heading-regexp))
11564 (throw 'dont-block t)) ; do not block, parent is not a TODO
11565 (setq pos (point))
11566 (setq parent-pos (and (org-up-heading-safe) (point)))
11567 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11568 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11569 (forward-line 1)
11570 (re-search-forward org-not-done-heading-regexp pos t))
11571 (throw 'dont-block nil)))))))) ; block, older sibling not done.
11573 (defcustom org-track-ordered-property-with-tag nil
11574 "Should the ORDERED property also be shown as a tag?
11575 The ORDERED property decides if an entry should require subtasks to be
11576 completed in sequence. Since a property is not very visible, setting
11577 this option means that toggling the ORDERED property with the command
11578 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
11579 not relevant for the behavior, but it makes things more visible.
11581 Note that toggling the tag with tags commands will not change the property
11582 and therefore not influence behavior!
11584 This can be t, meaning the tag ORDERED should be used, It can also be a
11585 string to select a different tag for this task."
11586 :group 'org-todo
11587 :type '(choice
11588 (const :tag "No tracking" nil)
11589 (const :tag "Track with ORDERED tag" t)
11590 (string :tag "Use other tag")))
11592 (defun org-toggle-ordered-property ()
11593 "Toggle the ORDERED property of the current entry.
11594 For better visibility, you can track the value of this property with a tag.
11595 See variable `org-track-ordered-property-with-tag'."
11596 (interactive)
11597 (let* ((t1 org-track-ordered-property-with-tag)
11598 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
11599 (save-excursion
11600 (org-back-to-heading)
11601 (if (org-entry-get nil "ORDERED")
11602 (progn
11603 (org-delete-property "ORDERED")
11604 (and tag (org-toggle-tag tag 'off))
11605 (message "Subtasks can be completed in arbitrary order"))
11606 (org-entry-put nil "ORDERED" "t")
11607 (and tag (org-toggle-tag tag 'on))
11608 (message "Subtasks must be completed in sequence")))))
11610 (defvar org-blocked-by-checkboxes) ; dynamically scoped
11611 (defun org-block-todo-from-checkboxes (change-plist)
11612 "Block turning an entry into a TODO, using checkboxes.
11613 This checks whether the current task should be blocked from state
11614 changes because there are unchecked boxes in this entry."
11615 (if (not org-enforce-todo-checkbox-dependencies)
11616 t ; if locally turned off don't block
11617 (catch 'dont-block
11618 ;; If this is not a todo state change, or if this entry is already DONE,
11619 ;; do not block
11620 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11621 (member (plist-get change-plist :from)
11622 (cons 'done org-done-keywords))
11623 (member (plist-get change-plist :to)
11624 (cons 'todo org-not-done-keywords))
11625 (not (plist-get change-plist :to)))
11626 (throw 'dont-block t))
11627 ;; If this task has checkboxes that are not checked, it's blocked
11628 (save-excursion
11629 (org-back-to-heading t)
11630 (let ((beg (point)) end)
11631 (outline-next-heading)
11632 (setq end (point))
11633 (goto-char beg)
11634 (if (org-list-search-forward
11635 (concat (org-item-beginning-re)
11636 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
11637 "\\[[- ]\\]")
11638 end t)
11639 (progn
11640 (if (boundp 'org-blocked-by-checkboxes)
11641 (setq org-blocked-by-checkboxes t))
11642 (throw 'dont-block nil)))))
11643 t))) ; do not block
11645 (defun org-entry-blocked-p ()
11646 "Is the current entry blocked?"
11647 (if (org-entry-get nil "NOBLOCKING")
11648 nil ;; Never block this entry
11649 (not
11650 (run-hook-with-args-until-failure
11651 'org-blocker-hook
11652 (list :type 'todo-state-change
11653 :position (point)
11654 :from 'todo
11655 :to 'done)))))
11657 (defun org-update-statistics-cookies (all)
11658 "Update the statistics cookie, either from TODO or from checkboxes.
11659 This should be called with the cursor in a line with a statistics cookie."
11660 (interactive "P")
11661 (if all
11662 (progn
11663 (org-update-checkbox-count 'all)
11664 (org-map-entries 'org-update-parent-todo-statistics))
11665 (if (not (org-at-heading-p))
11666 (org-update-checkbox-count)
11667 (let ((pos (move-marker (make-marker) (point)))
11668 end l1 l2)
11669 (ignore-errors (org-back-to-heading t))
11670 (if (not (org-at-heading-p))
11671 (org-update-checkbox-count)
11672 (setq l1 (org-outline-level))
11673 (setq end (save-excursion
11674 (outline-next-heading)
11675 (if (org-at-heading-p) (setq l2 (org-outline-level)))
11676 (point)))
11677 (if (and (save-excursion
11678 (re-search-forward
11679 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
11680 (not (save-excursion (re-search-forward
11681 ":COOKIE_DATA:.*\\<todo\\>" end t))))
11682 (org-update-checkbox-count)
11683 (if (and l2 (> l2 l1))
11684 (progn
11685 (goto-char end)
11686 (org-update-parent-todo-statistics))
11687 (goto-char pos)
11688 (beginning-of-line 1)
11689 (while (re-search-forward
11690 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
11691 (point-at-eol) t)
11692 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
11693 (goto-char pos)
11694 (move-marker pos nil)))))
11696 (defvar org-entry-property-inherited-from) ;; defined below
11697 (defun org-update-parent-todo-statistics ()
11698 "Update any statistics cookie in the parent of the current headline.
11699 When `org-hierarchical-todo-statistics' is nil, statistics will cover
11700 the entire subtree and this will travel up the hierarchy and update
11701 statistics everywhere."
11702 (let* ((prop (save-excursion (org-up-heading-safe)
11703 (org-entry-get nil "COOKIE_DATA" 'inherit)))
11704 (recursive (or (not org-hierarchical-todo-statistics)
11705 (and prop (string-match "\\<recursive\\>" prop))))
11706 (lim (or (and prop (marker-position org-entry-property-inherited-from))
11708 (first t)
11709 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
11710 level ltoggle l1 new ndel
11711 (cnt-all 0) (cnt-done 0) is-percent kwd
11712 checkbox-beg ov ovs ove cookie-present)
11713 (catch 'exit
11714 (save-excursion
11715 (beginning-of-line 1)
11716 (setq ltoggle (funcall outline-level))
11717 ;; Three situations are to consider:
11719 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
11720 ;; to the top-level ancestor on the headline;
11722 ;; 2. If parent has "recursive" property, repeat up to the
11723 ;; headline setting that property, taking inheritance into
11724 ;; account;
11726 ;; 3. Else, move up to direct parent and proceed only once.
11727 (while (and (setq level (org-up-heading-safe))
11728 (or recursive first)
11729 (>= (point) lim))
11730 (setq first nil cookie-present nil)
11731 (unless (and level
11732 (not (string-match
11733 "\\<checkbox\\>"
11734 (downcase (or (org-entry-get nil "COOKIE_DATA")
11735 "")))))
11736 (throw 'exit nil))
11737 (while (re-search-forward box-re (point-at-eol) t)
11738 (setq cnt-all 0 cnt-done 0 cookie-present t)
11739 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
11740 (save-match-data
11741 (unless (outline-next-heading) (throw 'exit nil))
11742 (while (and (looking-at org-complex-heading-regexp)
11743 (> (setq l1 (length (match-string 1))) level))
11744 (setq kwd (and (or recursive (= l1 ltoggle))
11745 (match-string 2)))
11746 (if (or (eq org-provide-todo-statistics 'all-headlines)
11747 (and (listp org-provide-todo-statistics)
11748 (or (member kwd org-provide-todo-statistics)
11749 (member kwd org-done-keywords))))
11750 (setq cnt-all (1+ cnt-all))
11751 (if (eq org-provide-todo-statistics t)
11752 (and kwd (setq cnt-all (1+ cnt-all)))))
11753 (and (member kwd org-done-keywords)
11754 (setq cnt-done (1+ cnt-done)))
11755 (outline-next-heading)))
11756 (setq new
11757 (if is-percent
11758 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
11759 (format "[%d/%d]" cnt-done cnt-all))
11760 ndel (- (match-end 0) checkbox-beg))
11761 ;; handle overlays when updating cookie from column view
11762 (when (setq ov (car (overlays-at checkbox-beg)))
11763 (setq ovs (overlay-start ov) ove (overlay-end ov))
11764 (delete-overlay ov))
11765 (goto-char checkbox-beg)
11766 (insert new)
11767 (delete-region (point) (+ (point) ndel))
11768 (when org-auto-align-tags (org-fix-tags-on-the-fly))
11769 (when ov (move-overlay ov ovs ove)))
11770 (when cookie-present
11771 (run-hook-with-args 'org-after-todo-statistics-hook
11772 cnt-done (- cnt-all cnt-done))))))
11773 (run-hooks 'org-todo-statistics-hook)))
11775 (defvar org-after-todo-statistics-hook nil
11776 "Hook that is called after a TODO statistics cookie has been updated.
11777 Each function is called with two arguments: the number of not-done entries
11778 and the number of done entries.
11780 For example, the following function, when added to this hook, will switch
11781 an entry to DONE when all children are done, and back to TODO when new
11782 entries are set to a TODO status. Note that this hook is only called
11783 when there is a statistics cookie in the headline!
11785 (defun org-summary-todo (n-done n-not-done)
11786 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
11787 (let (org-log-done org-log-states) ; turn off logging
11788 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
11791 (defvar org-todo-statistics-hook nil
11792 "Hook that is run whenever Org thinks TODO statistics should be updated.
11793 This hook runs even if there is no statistics cookie present, in which case
11794 `org-after-todo-statistics-hook' would not run.")
11796 (defun org-todo-trigger-tag-changes (state)
11797 "Apply the changes defined in `org-todo-state-tags-triggers'."
11798 (let ((l org-todo-state-tags-triggers)
11799 changes)
11800 (when (or (not state) (equal state ""))
11801 (setq changes (append changes (cdr (assoc "" l)))))
11802 (when (and (stringp state) (> (length state) 0))
11803 (setq changes (append changes (cdr (assoc state l)))))
11804 (when (member state org-not-done-keywords)
11805 (setq changes (append changes (cdr (assoc 'todo l)))))
11806 (when (member state org-done-keywords)
11807 (setq changes (append changes (cdr (assoc 'done l)))))
11808 (dolist (c changes)
11809 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
11811 (defun org-local-logging (value)
11812 "Get logging settings from a property VALUE."
11813 (let* (words w a)
11814 ;; directly set the variables, they are already local.
11815 (setq org-log-done nil
11816 org-log-repeat nil
11817 org-todo-log-states nil)
11818 (setq words (org-split-string value))
11819 (while (setq w (pop words))
11820 (cond
11821 ((setq a (assoc w org-startup-options))
11822 (and (member (nth 1 a) '(org-log-done org-log-repeat))
11823 (set (nth 1 a) (nth 2 a))))
11824 ((setq a (org-extract-log-state-settings w))
11825 (and (member (car a) org-todo-keywords-1)
11826 (push a org-todo-log-states)))))))
11828 (defun org-get-todo-sequence-head (kwd)
11829 "Return the head of the TODO sequence to which KWD belongs.
11830 If KWD is not set, check if there is a text property remembering the
11831 right sequence."
11832 (let (p)
11833 (cond
11834 ((not kwd)
11835 (or (get-text-property (point-at-bol) 'org-todo-head)
11836 (progn
11837 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
11838 nil (point-at-eol)))
11839 (get-text-property p 'org-todo-head))))
11840 ((not (member kwd org-todo-keywords-1))
11841 (car org-todo-keywords-1))
11842 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
11844 (defun org-fast-todo-selection ()
11845 "Fast TODO keyword selection with single keys.
11846 Returns the new TODO keyword, or nil if no state change should occur."
11847 (let* ((fulltable org-todo-key-alist)
11848 (done-keywords org-done-keywords) ;; needed for the faces.
11849 (maxlen (apply 'max (mapcar
11850 (lambda (x)
11851 (if (stringp (car x)) (string-width (car x)) 0))
11852 fulltable)))
11853 (expert nil)
11854 (fwidth (+ maxlen 3 1 3))
11855 (ncol (/ (- (window-width) 4) fwidth))
11856 tg cnt e c tbl
11857 groups ingroup)
11858 (save-excursion
11859 (save-window-excursion
11860 (if expert
11861 (set-buffer (get-buffer-create " *Org todo*"))
11862 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
11863 (erase-buffer)
11864 (org-set-local 'org-done-keywords done-keywords)
11865 (setq tbl fulltable cnt 0)
11866 (while (setq e (pop tbl))
11867 (cond
11868 ((equal e '(:startgroup))
11869 (push '() groups) (setq ingroup t)
11870 (when (not (= cnt 0))
11871 (setq cnt 0)
11872 (insert "\n"))
11873 (insert "{ "))
11874 ((equal e '(:endgroup))
11875 (setq ingroup nil cnt 0)
11876 (insert "}\n"))
11877 ((equal e '(:newline))
11878 (when (not (= cnt 0))
11879 (setq cnt 0)
11880 (insert "\n")
11881 (setq e (car tbl))
11882 (while (equal (car tbl) '(:newline))
11883 (insert "\n")
11884 (setq tbl (cdr tbl)))))
11886 (setq tg (car e) c (cdr e))
11887 (if ingroup (push tg (car groups)))
11888 (setq tg (org-add-props tg nil 'face
11889 (org-get-todo-face tg)))
11890 (if (and (= cnt 0) (not ingroup)) (insert " "))
11891 (insert "[" c "] " tg (make-string
11892 (- fwidth 4 (length tg)) ?\ ))
11893 (when (= (setq cnt (1+ cnt)) ncol)
11894 (insert "\n")
11895 (if ingroup (insert " "))
11896 (setq cnt 0)))))
11897 (insert "\n")
11898 (goto-char (point-min))
11899 (if (not expert) (org-fit-window-to-buffer))
11900 (message "[a-z..]:Set [SPC]:clear")
11901 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
11902 (cond
11903 ((or (= c ?\C-g)
11904 (and (= c ?q) (not (rassoc c fulltable))))
11905 (setq quit-flag t))
11906 ((= c ?\ ) nil)
11907 ((setq e (rassoc c fulltable) tg (car e))
11909 (t (setq quit-flag t)))))))
11911 (defun org-entry-is-todo-p ()
11912 (member (org-get-todo-state) org-not-done-keywords))
11914 (defun org-entry-is-done-p ()
11915 (member (org-get-todo-state) org-done-keywords))
11917 (defun org-get-todo-state ()
11918 (save-excursion
11919 (org-back-to-heading t)
11920 (and (looking-at org-todo-line-regexp)
11921 (match-end 2)
11922 (match-string 2))))
11924 (defun org-at-date-range-p (&optional inactive-ok)
11925 "Is the cursor inside a date range?"
11926 (interactive)
11927 (save-excursion
11928 (catch 'exit
11929 (let ((pos (point)))
11930 (skip-chars-backward "^[<\r\n")
11931 (skip-chars-backward "<[")
11932 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
11933 (>= (match-end 0) pos)
11934 (throw 'exit t))
11935 (skip-chars-backward "^<[\r\n")
11936 (skip-chars-backward "<[")
11937 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
11938 (>= (match-end 0) pos)
11939 (throw 'exit t)))
11940 nil)))
11942 (defun org-get-repeat (&optional tagline)
11943 "Check if there is a deadline/schedule with repeater in this entry."
11944 (save-match-data
11945 (save-excursion
11946 (org-back-to-heading t)
11947 (and (re-search-forward (if tagline
11948 (concat tagline "\\s-*" org-repeat-re)
11949 org-repeat-re)
11950 (org-entry-end-position) t)
11951 (match-string-no-properties 1)))))
11953 (defvar org-last-changed-timestamp)
11954 (defvar org-last-inserted-timestamp)
11955 (defvar org-log-post-message)
11956 (defvar org-log-note-purpose)
11957 (defvar org-log-note-how)
11958 (defvar org-log-note-extra)
11959 (defun org-auto-repeat-maybe (done-word)
11960 "Check if the current headline contains a repeated deadline/schedule.
11961 If yes, set TODO state back to what it was and change the base date
11962 of repeating deadline/scheduled time stamps to new date.
11963 This function is run automatically after each state change to a DONE state."
11964 ;; last-state is dynamically scoped into this function
11965 (let* ((repeat (org-get-repeat))
11966 (aa (assoc org-last-state org-todo-kwd-alist))
11967 (interpret (nth 1 aa))
11968 (head (nth 2 aa))
11969 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
11970 (msg "Entry repeats: ")
11971 (org-log-done nil)
11972 (org-todo-log-states nil)
11973 re type n what ts time to-state)
11974 (when repeat
11975 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
11976 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
11977 org-todo-repeat-to-state))
11978 (unless (and to-state (member to-state org-todo-keywords-1))
11979 (setq to-state (if (eq interpret 'type) org-last-state head)))
11980 (org-todo to-state)
11981 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
11982 (org-entry-put nil "LAST_REPEAT" (format-time-string
11983 (org-time-stamp-format t t))))
11984 (when org-log-repeat
11985 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
11986 (memq 'org-add-log-note post-command-hook))
11987 ;; OK, we are already setup for some record
11988 (if (eq org-log-repeat 'note)
11989 ;; make sure we take a note, not only a time stamp
11990 (setq org-log-note-how 'note))
11991 ;; Set up for taking a record
11992 (org-add-log-setup 'state (or done-word (car org-done-keywords))
11993 org-last-state
11994 'findpos org-log-repeat)))
11995 (org-back-to-heading t)
11996 (org-add-planning-info nil nil 'closed)
11997 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
11998 org-deadline-time-regexp "\\)\\|\\("
11999 org-ts-regexp "\\)"))
12000 (while (re-search-forward
12001 re (save-excursion (outline-next-heading) (point)) t)
12002 (setq type (if (match-end 1) org-scheduled-string
12003 (if (match-end 3) org-deadline-string "Plain:"))
12004 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12005 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12006 (setq n (string-to-number (match-string 2 ts))
12007 what (match-string 3 ts))
12008 (if (equal what "w") (setq n (* n 7) what "d"))
12009 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12010 (error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12011 ;; Preparation, see if we need to modify the start date for the change
12012 (when (match-end 1)
12013 (setq time (save-match-data (org-time-string-to-time ts)))
12014 (cond
12015 ((equal (match-string 1 ts) ".")
12016 ;; Shift starting date to today
12017 (org-timestamp-change
12018 (- (org-today) (time-to-days time))
12019 'day))
12020 ((equal (match-string 1 ts) "+")
12021 (let ((nshiftmax 10) (nshift 0))
12022 (while (or (= nshift 0)
12023 (<= (time-to-days time)
12024 (time-to-days (current-time))))
12025 (when (= (incf nshift) nshiftmax)
12026 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12027 (error "Abort")))
12028 (org-timestamp-change n (cdr (assoc what whata)))
12029 (org-at-timestamp-p t)
12030 (setq ts (match-string 1))
12031 (setq time (save-match-data (org-time-string-to-time ts)))))
12032 (org-timestamp-change (- n) (cdr (assoc what whata)))
12033 ;; rematch, so that we have everything in place for the real shift
12034 (org-at-timestamp-p t)
12035 (setq ts (match-string 1))
12036 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12037 (org-timestamp-change n (cdr (assoc what whata)))
12038 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12039 (setq org-log-post-message msg)
12040 (message "%s" msg))))
12042 (defun org-show-todo-tree (arg)
12043 "Make a compact tree which shows all headlines marked with TODO.
12044 The tree will show the lines where the regexp matches, and all higher
12045 headlines above the match.
12046 With a \\[universal-argument] prefix, prompt for a regexp to match.
12047 With a numeric prefix N, construct a sparse tree for the Nth element
12048 of `org-todo-keywords-1'."
12049 (interactive "P")
12050 (let ((case-fold-search nil)
12051 (kwd-re
12052 (cond ((null arg) org-not-done-regexp)
12053 ((equal arg '(4))
12054 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12055 (mapcar 'list org-todo-keywords-1))))
12056 (concat "\\("
12057 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12058 "\\)\\>")))
12059 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12060 (regexp-quote (nth (1- (prefix-numeric-value arg))
12061 org-todo-keywords-1)))
12062 (t (error "Invalid prefix argument: %s" arg)))))
12063 (message "%d TODO entries found"
12064 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12066 (defun org-deadline (&optional remove time)
12067 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12068 With argument REMOVE, remove any deadline from the item.
12069 With argument TIME, set the deadline at the corresponding date. TIME
12070 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12071 (interactive "P")
12072 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12073 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12074 'region-start-level 'region))
12075 org-loop-over-headlines-in-active-region)
12076 (org-map-entries
12077 `(org-deadline ',remove ,time)
12078 org-loop-over-headlines-in-active-region
12079 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12080 (let* ((old-date (org-entry-get nil "DEADLINE"))
12081 (repeater (and old-date
12082 (string-match
12083 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12084 old-date)
12085 (match-string 1 old-date))))
12086 (if remove
12087 (progn
12088 (when (and old-date org-log-redeadline)
12089 (org-add-log-setup 'deldeadline nil old-date 'findpos
12090 org-log-redeadline))
12091 (org-remove-timestamp-with-keyword org-deadline-string)
12092 (message "Item no longer has a deadline."))
12093 (org-add-planning-info 'deadline time 'closed)
12094 (when (and old-date org-log-redeadline
12095 (not (equal old-date
12096 (substring org-last-inserted-timestamp 1 -1))))
12097 (org-add-log-setup 'redeadline nil old-date 'findpos
12098 org-log-redeadline))
12099 (when repeater
12100 (save-excursion
12101 (org-back-to-heading t)
12102 (when (re-search-forward (concat org-deadline-string " "
12103 org-last-inserted-timestamp)
12104 (save-excursion
12105 (outline-next-heading) (point)) t)
12106 (goto-char (1- (match-end 0)))
12107 (insert " " repeater)
12108 (setq org-last-inserted-timestamp
12109 (concat (substring org-last-inserted-timestamp 0 -1)
12110 " " repeater
12111 (substring org-last-inserted-timestamp -1))))))
12112 (message "Deadline on %s" org-last-inserted-timestamp)))))
12114 (defun org-schedule (&optional remove time)
12115 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12116 With argument REMOVE, remove any scheduling date from the item.
12117 With argument TIME, scheduled at the corresponding date. TIME can
12118 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12119 (interactive "P")
12120 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12121 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12122 'region-start-level 'region))
12123 org-loop-over-headlines-in-active-region)
12124 (org-map-entries
12125 `(org-schedule ',remove ,time)
12126 org-loop-over-headlines-in-active-region
12127 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12128 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12129 (repeater (and old-date
12130 (string-match
12131 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12132 old-date)
12133 (match-string 1 old-date))))
12134 (if remove
12135 (progn
12136 (when (and old-date org-log-reschedule)
12137 (org-add-log-setup 'delschedule nil old-date 'findpos
12138 org-log-reschedule))
12139 (org-remove-timestamp-with-keyword org-scheduled-string)
12140 (message "Item is no longer scheduled."))
12141 (org-add-planning-info 'scheduled time 'closed)
12142 (when (and old-date org-log-reschedule
12143 (not (equal old-date
12144 (substring org-last-inserted-timestamp 1 -1))))
12145 (org-add-log-setup 'reschedule nil old-date 'findpos
12146 org-log-reschedule))
12147 (when repeater
12148 (save-excursion
12149 (org-back-to-heading t)
12150 (when (re-search-forward (concat org-scheduled-string " "
12151 org-last-inserted-timestamp)
12152 (save-excursion
12153 (outline-next-heading) (point)) t)
12154 (goto-char (1- (match-end 0)))
12155 (insert " " repeater)
12156 (setq org-last-inserted-timestamp
12157 (concat (substring org-last-inserted-timestamp 0 -1)
12158 " " repeater
12159 (substring org-last-inserted-timestamp -1))))))
12160 (message "Scheduled to %s" org-last-inserted-timestamp)))))
12162 (defun org-get-scheduled-time (pom &optional inherit)
12163 "Get the scheduled time as a time tuple, of a format suitable
12164 for calling org-schedule with, or if there is no scheduling,
12165 returns nil."
12166 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12167 (when time
12168 (apply 'encode-time (org-parse-time-string time)))))
12170 (defun org-get-deadline-time (pom &optional inherit)
12171 "Get the deadline as a time tuple, of a format suitable for
12172 calling org-deadline with, or if there is no scheduling, returns
12173 nil."
12174 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12175 (when time
12176 (apply 'encode-time (org-parse-time-string time)))))
12178 (defun org-remove-timestamp-with-keyword (keyword)
12179 "Remove all time stamps with KEYWORD in the current entry."
12180 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12181 beg)
12182 (save-excursion
12183 (org-back-to-heading t)
12184 (setq beg (point))
12185 (outline-next-heading)
12186 (while (re-search-backward re beg t)
12187 (replace-match "")
12188 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12189 (equal (char-before) ?\ ))
12190 (backward-delete-char 1)
12191 (if (string-match "^[ \t]*$" (buffer-substring
12192 (point-at-bol) (point-at-eol)))
12193 (delete-region (point-at-bol)
12194 (min (point-max) (1+ (point-at-eol))))))))))
12196 (defun org-add-planning-info (what &optional time &rest remove)
12197 "Insert new timestamp with keyword in the line directly after the headline.
12198 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
12199 If non is given, the user is prompted for a date.
12200 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
12201 be removed."
12202 (interactive)
12203 (let (org-time-was-given org-end-time-was-given ts
12204 end default-time default-input)
12206 (catch 'exit
12207 (when (and (memq what '(scheduled deadline))
12208 (or (not time)
12209 (and (stringp time)
12210 (string-match "^[-+]+[0-9]" time))))
12211 ;; Try to get a default date/time from existing timestamp
12212 (save-excursion
12213 (org-back-to-heading t)
12214 (setq end (save-excursion (outline-next-heading) (point)))
12215 (when (re-search-forward (if (eq what 'scheduled)
12216 org-scheduled-time-regexp
12217 org-deadline-time-regexp)
12218 end t)
12219 (setq ts (match-string 1)
12220 default-time
12221 (apply 'encode-time (org-parse-time-string ts))
12222 default-input (and ts (org-get-compact-tod ts))))))
12223 (when what
12224 (setq time
12225 (if (stringp time)
12226 ;; This is a string (relative or absolute), set proper date
12227 (apply 'encode-time
12228 (org-read-date-analyze
12229 time default-time (decode-time default-time)))
12230 ;; If necessary, get the time from the user
12231 (or time (org-read-date nil 'to-time nil nil
12232 default-time default-input)))))
12234 (when (and org-insert-labeled-timestamps-at-point
12235 (member what '(scheduled deadline)))
12236 (insert
12237 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
12238 (org-insert-time-stamp time org-time-was-given
12239 nil nil nil (list org-end-time-was-given))
12240 (setq what nil))
12241 (save-excursion
12242 (save-restriction
12243 (let (col list elt ts buffer-invisibility-spec)
12244 (org-back-to-heading t)
12245 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
12246 (goto-char (match-end 1))
12247 (setq col (current-column))
12248 (goto-char (match-end 0))
12249 (if (eobp) (insert "\n") (forward-char 1))
12250 (when (and (not what)
12251 (not (looking-at
12252 (concat "[ \t]*"
12253 org-keyword-time-not-clock-regexp))))
12254 ;; Nothing to add, nothing to remove...... :-)
12255 (throw 'exit nil))
12256 (if (and (not (looking-at org-outline-regexp))
12257 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
12258 "[^\r\n]*"))
12259 (not (equal (match-string 1) org-clock-string)))
12260 (narrow-to-region (match-beginning 0) (match-end 0))
12261 (insert-before-markers "\n")
12262 (backward-char 1)
12263 (narrow-to-region (point) (point))
12264 (and org-adapt-indentation (org-indent-to-column col)))
12265 ;; Check if we have to remove something.
12266 (setq list (cons what remove))
12267 (while list
12268 (setq elt (pop list))
12269 (when (or (and (eq elt 'scheduled)
12270 (re-search-forward org-scheduled-time-regexp nil t))
12271 (and (eq elt 'deadline)
12272 (re-search-forward org-deadline-time-regexp nil t))
12273 (and (eq elt 'closed)
12274 (re-search-forward org-closed-time-regexp nil t)))
12275 (replace-match "")
12276 (if (looking-at "--+<[^>]+>") (replace-match ""))))
12277 (and (looking-at "[ \t]+") (replace-match ""))
12278 (and org-adapt-indentation (bolp) (org-indent-to-column col))
12279 (when what
12280 (insert
12281 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
12282 (cond ((eq what 'scheduled) org-scheduled-string)
12283 ((eq what 'deadline) org-deadline-string)
12284 ((eq what 'closed) org-closed-string))
12285 " ")
12286 (setq ts (org-insert-time-stamp
12287 time
12288 (or org-time-was-given
12289 (and (eq what 'closed) org-log-done-with-time))
12290 (eq what 'closed)
12291 nil nil (list org-end-time-was-given)))
12292 (insert
12293 (if (not (or (bolp) (eq (char-before) ?\ )
12294 (memq (char-after) '(32 10))
12295 (eobp))) " " ""))
12296 (end-of-line 1))
12297 (goto-char (point-min))
12298 (widen)
12299 (if (and (looking-at "[ \t]*\n")
12300 (equal (char-before) ?\n))
12301 (delete-region (1- (point)) (point-at-eol)))
12302 ts))))))
12304 (defvar org-log-note-marker (make-marker))
12305 (defvar org-log-note-purpose nil)
12306 (defvar org-log-note-state nil)
12307 (defvar org-log-note-previous-state nil)
12308 (defvar org-log-note-how nil)
12309 (defvar org-log-note-extra nil)
12310 (defvar org-log-note-window-configuration nil)
12311 (defvar org-log-note-return-to (make-marker))
12312 (defvar org-log-note-effective-time nil
12313 "Remembered current time so that dynamically scoped
12314 `org-extend-today-until' affects tha timestamps in state change
12315 log")
12317 (defvar org-log-post-message nil
12318 "Message to be displayed after a log note has been stored.
12319 The auto-repeater uses this.")
12321 (defun org-add-note ()
12322 "Add a note to the current entry.
12323 This is done in the same way as adding a state change note."
12324 (interactive)
12325 (org-add-log-setup 'note nil nil 'findpos nil))
12327 (defvar org-property-end-re)
12328 (defun org-add-log-setup (&optional purpose state prev-state
12329 findpos how extra)
12330 "Set up the post command hook to take a note.
12331 If this is about to TODO state change, the new state is expected in STATE.
12332 When FINDPOS is non-nil, find the correct position for the note in
12333 the current entry. If not, assume that it can be inserted at point.
12334 HOW is an indicator what kind of note should be created.
12335 EXTRA is additional text that will be inserted into the notes buffer."
12336 (let* ((org-log-into-drawer (org-log-into-drawer))
12337 (drawer (cond ((stringp org-log-into-drawer)
12338 org-log-into-drawer)
12339 (org-log-into-drawer "LOGBOOK")
12340 (t nil))))
12341 (save-restriction
12342 (save-excursion
12343 (when findpos
12344 (org-back-to-heading t)
12345 (narrow-to-region (point) (save-excursion
12346 (outline-next-heading) (point)))
12347 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
12348 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
12349 "[^\r\n]*\\)?"))
12350 (goto-char (match-end 0))
12351 (cond
12352 (drawer
12353 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
12354 nil t)
12355 (progn
12356 (goto-char (match-end 0))
12357 (or org-log-states-order-reversed
12358 (and (re-search-forward org-property-end-re nil t)
12359 (goto-char (1- (match-beginning 0))))))
12360 (insert "\n:" drawer ":\n:END:")
12361 (beginning-of-line 0)
12362 (org-indent-line-function)
12363 (beginning-of-line 2)
12364 (org-indent-line-function)
12365 (end-of-line 0)))
12366 ((and org-log-state-notes-insert-after-drawers
12367 (save-excursion
12368 (forward-line) (looking-at org-drawer-regexp)))
12369 (forward-line)
12370 (while (looking-at org-drawer-regexp)
12371 (goto-char (match-end 0))
12372 (re-search-forward org-property-end-re (point-max) t)
12373 (forward-line))
12374 (forward-line -1)))
12375 (unless org-log-states-order-reversed
12376 (and (= (char-after) ?\n) (forward-char 1))
12377 (org-skip-over-state-notes)
12378 (skip-chars-backward " \t\n\r")))
12379 (move-marker org-log-note-marker (point))
12380 (setq org-log-note-purpose purpose
12381 org-log-note-state state
12382 org-log-note-previous-state prev-state
12383 org-log-note-how how
12384 org-log-note-extra extra
12385 org-log-note-effective-time (org-current-effective-time))
12386 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
12388 (defun org-skip-over-state-notes ()
12389 "Skip past the list of State notes in an entry."
12390 (if (looking-at "\n[ \t]*- State") (forward-char 1))
12391 (when (ignore-errors (goto-char (org-in-item-p)))
12392 (let* ((struct (org-list-struct))
12393 (prevs (org-list-prevs-alist struct)))
12394 (while (looking-at "[ \t]*- State")
12395 (goto-char (or (org-list-get-next-item (point) struct prevs)
12396 (org-list-get-item-end (point) struct)))))))
12398 (defun org-add-log-note (&optional purpose)
12399 "Pop up a window for taking a note, and add this note later at point."
12400 (remove-hook 'post-command-hook 'org-add-log-note)
12401 (setq org-log-note-window-configuration (current-window-configuration))
12402 (delete-other-windows)
12403 (move-marker org-log-note-return-to (point))
12404 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
12405 (goto-char org-log-note-marker)
12406 (org-switch-to-buffer-other-window "*Org Note*")
12407 (erase-buffer)
12408 (if (memq org-log-note-how '(time state))
12409 (let (current-prefix-arg) (org-store-log-note))
12410 (let ((org-inhibit-startup t)) (org-mode))
12411 (insert (format "# Insert note for %s.
12412 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
12413 (cond
12414 ((eq org-log-note-purpose 'clock-out) "stopped clock")
12415 ((eq org-log-note-purpose 'done) "closed todo item")
12416 ((eq org-log-note-purpose 'state)
12417 (format "state change from \"%s\" to \"%s\""
12418 (or org-log-note-previous-state "")
12419 (or org-log-note-state "")))
12420 ((eq org-log-note-purpose 'reschedule)
12421 "rescheduling")
12422 ((eq org-log-note-purpose 'delschedule)
12423 "no longer scheduled")
12424 ((eq org-log-note-purpose 'redeadline)
12425 "changing deadline")
12426 ((eq org-log-note-purpose 'deldeadline)
12427 "removing deadline")
12428 ((eq org-log-note-purpose 'refile)
12429 "refiling")
12430 ((eq org-log-note-purpose 'note)
12431 "this entry")
12432 (t (error "This should not happen")))))
12433 (if org-log-note-extra (insert org-log-note-extra))
12434 (org-set-local 'org-finish-function 'org-store-log-note)
12435 (run-hooks 'org-log-buffer-setup-hook)))
12437 (defvar org-note-abort nil) ; dynamically scoped
12438 (defun org-store-log-note ()
12439 "Finish taking a log note, and insert it to where it belongs."
12440 (let ((txt (buffer-string))
12441 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
12442 lines ind bul)
12443 (kill-buffer (current-buffer))
12444 (while (string-match "\\`#.*\n[ \t\n]*" txt)
12445 (setq txt (replace-match "" t t txt)))
12446 (if (string-match "\\s-+\\'" txt)
12447 (setq txt (replace-match "" t t txt)))
12448 (setq lines (org-split-string txt "\n"))
12449 (when (and note (string-match "\\S-" note))
12450 (setq note
12451 (org-replace-escapes
12452 note
12453 (list (cons "%u" (user-login-name))
12454 (cons "%U" user-full-name)
12455 (cons "%t" (format-time-string
12456 (org-time-stamp-format 'long 'inactive)
12457 org-log-note-effective-time))
12458 (cons "%T" (format-time-string
12459 (org-time-stamp-format 'long nil)
12460 org-log-note-effective-time))
12461 (cons "%d" (format-time-string
12462 (org-time-stamp-format nil 'inactive)
12463 org-log-note-effective-time))
12464 (cons "%D" (format-time-string
12465 (org-time-stamp-format nil nil)
12466 org-log-note-effective-time))
12467 (cons "%s" (if org-log-note-state
12468 (concat "\"" org-log-note-state "\"")
12469 ""))
12470 (cons "%S" (if org-log-note-previous-state
12471 (concat "\"" org-log-note-previous-state "\"")
12472 "\"\"")))))
12473 (if lines (setq note (concat note " \\\\")))
12474 (push note lines))
12475 (when (or current-prefix-arg org-note-abort)
12476 (when org-log-into-drawer
12477 (org-remove-empty-drawer-at
12478 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
12479 org-log-note-marker))
12480 (setq lines nil))
12481 (when lines
12482 (with-current-buffer (marker-buffer org-log-note-marker)
12483 (save-excursion
12484 (goto-char org-log-note-marker)
12485 (move-marker org-log-note-marker nil)
12486 (end-of-line 1)
12487 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
12488 (setq ind (save-excursion
12489 (if (ignore-errors (goto-char (org-in-item-p)))
12490 (let ((struct (org-list-struct)))
12491 (org-list-get-ind
12492 (org-list-get-top-point struct) struct))
12493 (skip-chars-backward " \r\t\n")
12494 (cond
12495 ((and (org-at-heading-p)
12496 org-adapt-indentation)
12497 (1+ (org-current-level)))
12498 ((org-at-heading-p) 0)
12499 (t (org-get-indentation))))))
12500 (setq bul (org-list-bullet-string "-"))
12501 (org-indent-line-to ind)
12502 (insert bul (pop lines))
12503 (let ((ind-body (+ (length bul) ind)))
12504 (while lines
12505 (insert "\n")
12506 (org-indent-line-to ind-body)
12507 (insert (pop lines))))
12508 (message "Note stored")
12509 (org-back-to-heading t)
12510 (org-cycle-hide-drawers 'children)))))
12511 (set-window-configuration org-log-note-window-configuration)
12512 (with-current-buffer (marker-buffer org-log-note-return-to)
12513 (goto-char org-log-note-return-to))
12514 (move-marker org-log-note-return-to nil)
12515 (and org-log-post-message (message "%s" org-log-post-message)))
12517 (defun org-remove-empty-drawer-at (drawer pos)
12518 "Remove an empty drawer DRAWER at position POS.
12519 POS may also be a marker."
12520 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
12521 (save-excursion
12522 (save-restriction
12523 (widen)
12524 (goto-char pos)
12525 (if (org-in-regexp
12526 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
12527 (replace-match ""))))))
12529 (defun org-sparse-tree (&optional arg)
12530 "Create a sparse tree, prompt for the details.
12531 This command can create sparse trees. You first need to select the type
12532 of match used to create the tree:
12534 t Show all TODO entries.
12535 T Show entries with a specific TODO keyword.
12536 m Show entries selected by a tags/property match.
12537 p Enter a property name and its value (both with completion on existing
12538 names/values) and show entries with that property.
12539 r Show entries matching a regular expression (`/' can be used as well)
12540 d Show deadlines due within `org-deadline-warning-days'.
12541 b Show deadlines and scheduled items before a date.
12542 a Show deadlines and scheduled items after a date."
12543 (interactive "P")
12544 (let (ans kwd value)
12545 (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")
12546 (setq ans (read-char-exclusive))
12547 (cond
12548 ((equal ans ?d)
12549 (call-interactively 'org-check-deadlines))
12550 ((equal ans ?b)
12551 (call-interactively 'org-check-before-date))
12552 ((equal ans ?a)
12553 (call-interactively 'org-check-after-date))
12554 ((equal ans ?D)
12555 (call-interactively 'org-check-dates-range))
12556 ((equal ans ?t)
12557 (org-show-todo-tree nil))
12558 ((equal ans ?T)
12559 (org-show-todo-tree '(4)))
12560 ((member ans '(?T ?m))
12561 (call-interactively 'org-match-sparse-tree))
12562 ((member ans '(?p ?P))
12563 (setq kwd (org-icompleting-read "Property: "
12564 (mapcar 'list (org-buffer-property-keys))))
12565 (setq value (org-icompleting-read "Value: "
12566 (mapcar 'list (org-property-values kwd))))
12567 (unless (string-match "\\`{.*}\\'" value)
12568 (setq value (concat "\"" value "\"")))
12569 (org-match-sparse-tree arg (concat kwd "=" value)))
12570 ((member ans '(?r ?R ?/))
12571 (call-interactively 'org-occur))
12572 (t (error "No such sparse tree command \"%c\"" ans)))))
12574 (defvar org-occur-highlights nil
12575 "List of overlays used for occur matches.")
12576 (make-variable-buffer-local 'org-occur-highlights)
12577 (defvar org-occur-parameters nil
12578 "Parameters of the active org-occur calls.
12579 This is a list, each call to org-occur pushes as cons cell,
12580 containing the regular expression and the callback, onto the list.
12581 The list can contain several entries if `org-occur' has been called
12582 several time with the KEEP-PREVIOUS argument. Otherwise, this list
12583 will only contain one set of parameters. When the highlights are
12584 removed (for example with `C-c C-c', or with the next edit (depending
12585 on `org-remove-highlights-with-change'), this variable is emptied
12586 as well.")
12587 (make-variable-buffer-local 'org-occur-parameters)
12589 (defun org-occur (regexp &optional keep-previous callback)
12590 "Make a compact tree which shows all matches of REGEXP.
12591 The tree will show the lines where the regexp matches, and all higher
12592 headlines above the match. It will also show the heading after the match,
12593 to make sure editing the matching entry is easy.
12594 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
12595 call to `org-occur' will be kept, to allow stacking of calls to this
12596 command.
12597 If CALLBACK is non-nil, it is a function which is called to confirm
12598 that the match should indeed be shown."
12599 (interactive "sRegexp: \nP")
12600 (when (equal regexp "")
12601 (error "Regexp cannot be empty"))
12602 (unless keep-previous
12603 (org-remove-occur-highlights nil nil t))
12604 (push (cons regexp callback) org-occur-parameters)
12605 (let ((cnt 0))
12606 (save-excursion
12607 (goto-char (point-min))
12608 (if (or (not keep-previous) ; do not want to keep
12609 (not org-occur-highlights)) ; no previous matches
12610 ;; hide everything
12611 (org-overview))
12612 (while (re-search-forward regexp nil t)
12613 (when (or (not callback)
12614 (save-match-data (funcall callback)))
12615 (setq cnt (1+ cnt))
12616 (when org-highlight-sparse-tree-matches
12617 (org-highlight-new-match (match-beginning 0) (match-end 0)))
12618 (org-show-context 'occur-tree))))
12619 (when org-remove-highlights-with-change
12620 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
12621 nil 'local))
12622 (unless org-sparse-tree-open-archived-trees
12623 (org-hide-archived-subtrees (point-min) (point-max)))
12624 (run-hooks 'org-occur-hook)
12625 (if (org-called-interactively-p 'interactive)
12626 (message "%d match(es) for regexp %s" cnt regexp))
12627 cnt))
12629 (defun org-occur-next-match (&optional n reset)
12630 "Function for `next-error-function' to find sparse tree matches.
12631 N is the number of matches to move, when negative move backwards.
12632 RESET is entirely ignored - this function always goes back to the
12633 starting point when no match is found."
12634 (let* ((limit (if (< n 0) (point-min) (point-max)))
12635 (search-func (if (< n 0)
12636 'previous-single-char-property-change
12637 'next-single-char-property-change))
12638 (n (abs n))
12639 (pos (point))
12641 (catch 'exit
12642 (while (setq p1 (funcall search-func (point) 'org-type))
12643 (when (equal p1 limit)
12644 (goto-char pos)
12645 (error "No more matches"))
12646 (when (equal (get-char-property p1 'org-type) 'org-occur)
12647 (setq n (1- n))
12648 (when (= n 0)
12649 (goto-char p1)
12650 (throw 'exit (point))))
12651 (goto-char p1))
12652 (goto-char p1)
12653 (error "No more matches"))))
12655 (defun org-show-context (&optional key)
12656 "Make sure point and context are visible.
12657 How much context is shown depends upon the variables
12658 `org-show-hierarchy-above', `org-show-following-heading',
12659 `org-show-entry-below' and `org-show-siblings'."
12660 (let ((heading-p (org-at-heading-p t))
12661 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
12662 (following-p (org-get-alist-option org-show-following-heading key))
12663 (entry-p (org-get-alist-option org-show-entry-below key))
12664 (siblings-p (org-get-alist-option org-show-siblings key)))
12665 (catch 'exit
12666 ;; Show heading or entry text
12667 (if (and heading-p (not entry-p))
12668 (org-flag-heading nil) ; only show the heading
12669 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
12670 (org-show-hidden-entry))) ; show entire entry
12671 (when following-p
12672 ;; Show next sibling, or heading below text
12673 (save-excursion
12674 (and (if heading-p (org-goto-sibling) (outline-next-heading))
12675 (org-flag-heading nil))))
12676 (when siblings-p (org-show-siblings))
12677 (when hierarchy-p
12678 ;; show all higher headings, possibly with siblings
12679 (save-excursion
12680 (while (and (condition-case nil
12681 (progn (org-up-heading-all 1) t)
12682 (error nil))
12683 (not (bobp)))
12684 (org-flag-heading nil)
12685 (when siblings-p (org-show-siblings))))))))
12687 (defvar org-reveal-start-hook nil
12688 "Hook run before revealing a location.")
12690 (defun org-reveal (&optional siblings)
12691 "Show current entry, hierarchy above it, and the following headline.
12692 This can be used to show a consistent set of context around locations
12693 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
12694 not t for the search context.
12696 With optional argument SIBLINGS, on each level of the hierarchy all
12697 siblings are shown. This repairs the tree structure to what it would
12698 look like when opened with hierarchical calls to `org-cycle'.
12699 With double optional argument \\[universal-argument] \\[universal-argument], \
12700 go to the parent and show the
12701 entire tree."
12702 (interactive "P")
12703 (run-hooks 'org-reveal-start-hook)
12704 (let ((org-show-hierarchy-above t)
12705 (org-show-following-heading t)
12706 (org-show-siblings (if siblings t org-show-siblings)))
12707 (org-show-context nil))
12708 (when (equal siblings '(16))
12709 (save-excursion
12710 (when (org-up-heading-safe)
12711 (org-show-subtree)
12712 (run-hook-with-args 'org-cycle-hook 'subtree)))))
12714 (defun org-highlight-new-match (beg end)
12715 "Highlight from BEG to END and mark the highlight is an occur headline."
12716 (let ((ov (make-overlay beg end)))
12717 (overlay-put ov 'face 'secondary-selection)
12718 (overlay-put ov 'org-type 'org-occur)
12719 (push ov org-occur-highlights)))
12721 (defun org-remove-occur-highlights (&optional beg end noremove)
12722 "Remove the occur highlights from the buffer.
12723 BEG and END are ignored. If NOREMOVE is nil, remove this function
12724 from the `before-change-functions' in the current buffer."
12725 (interactive)
12726 (unless org-inhibit-highlight-removal
12727 (mapc 'delete-overlay org-occur-highlights)
12728 (setq org-occur-highlights nil)
12729 (setq org-occur-parameters nil)
12730 (unless noremove
12731 (remove-hook 'before-change-functions
12732 'org-remove-occur-highlights 'local))))
12734 ;;;; Priorities
12736 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
12737 "Regular expression matching the priority indicator.")
12739 (defvar org-remove-priority-next-time nil)
12741 (defun org-priority-up ()
12742 "Increase the priority of the current item."
12743 (interactive)
12744 (org-priority 'up))
12746 (defun org-priority-down ()
12747 "Decrease the priority of the current item."
12748 (interactive)
12749 (org-priority 'down))
12751 (defun org-priority (&optional action)
12752 "Change the priority of an item by ARG.
12753 ACTION can be `set', `up', `down', or a character."
12754 (interactive)
12755 (unless org-enable-priority-commands
12756 (error "Priority commands are disabled"))
12757 (setq action (or action 'set))
12758 (let (current new news have remove)
12759 (save-excursion
12760 (org-back-to-heading t)
12761 (if (looking-at org-priority-regexp)
12762 (setq current (string-to-char (match-string 2))
12763 have t))
12764 (cond
12765 ((eq action 'remove)
12766 (setq remove t new ?\ ))
12767 ((or (eq action 'set)
12768 (if (featurep 'xemacs) (characterp action) (integerp action)))
12769 (if (not (eq action 'set))
12770 (setq new action)
12771 (message "Priority %c-%c, SPC to remove: "
12772 org-highest-priority org-lowest-priority)
12773 (save-match-data
12774 (setq new (read-char-exclusive))))
12775 (if (and (= (upcase org-highest-priority) org-highest-priority)
12776 (= (upcase org-lowest-priority) org-lowest-priority))
12777 (setq new (upcase new)))
12778 (cond ((equal new ?\ ) (setq remove t))
12779 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
12780 (error "Priority must be between `%c' and `%c'"
12781 org-highest-priority org-lowest-priority))))
12782 ((eq action 'up)
12783 (setq new (if have
12784 (1- current) ; normal cycling
12785 ;; last priority was empty
12786 (if (eq last-command this-command)
12787 org-lowest-priority ; wrap around empty to lowest
12788 ;; default
12789 (if org-priority-start-cycle-with-default
12790 org-default-priority
12791 (1- org-default-priority))))))
12792 ((eq action 'down)
12793 (setq new (if have
12794 (1+ current) ; normal cycling
12795 ;; last priority was empty
12796 (if (eq last-command this-command)
12797 org-highest-priority ; wrap around empty to highest
12798 ;; default
12799 (if org-priority-start-cycle-with-default
12800 org-default-priority
12801 (1+ org-default-priority))))))
12802 (t (error "Invalid action")))
12803 (if (or (< (upcase new) org-highest-priority)
12804 (> (upcase new) org-lowest-priority))
12805 (if (and (memq action '(up down))
12806 (not have) (not (eq last-command this-command)))
12807 ;; `new' is from default priority
12808 (error
12809 "The default can not be set, see `org-default-priority' why")
12810 ;; normal cycling: `new' is beyond highest/lowest priority
12811 ;; and is wrapped around to the empty priority
12812 (setq remove t)))
12813 (setq news (format "%c" new))
12814 (if have
12815 (if remove
12816 (replace-match "" t t nil 1)
12817 (replace-match news t t nil 2))
12818 (if remove
12819 (error "No priority cookie found in line")
12820 (let ((case-fold-search nil))
12821 (looking-at org-todo-line-regexp))
12822 (if (match-end 2)
12823 (progn
12824 (goto-char (match-end 2))
12825 (insert " [#" news "]"))
12826 (goto-char (match-beginning 3))
12827 (insert "[#" news "] "))))
12828 (org-preserve-lc (org-set-tags nil 'align)))
12829 (if remove
12830 (message "Priority removed")
12831 (message "Priority of current item set to %s" news))))
12833 (defun org-get-priority (s)
12834 "Find priority cookie and return priority."
12835 (if (functionp org-get-priority-function)
12836 (funcall org-get-priority-function)
12837 (save-match-data
12838 (if (not (string-match org-priority-regexp s))
12839 (* 1000 (- org-lowest-priority org-default-priority))
12840 (* 1000 (- org-lowest-priority
12841 (string-to-char (match-string 2 s))))))))
12843 ;;;; Tags
12845 (defvar org-agenda-archives-mode)
12846 (defvar org-map-continue-from nil
12847 "Position from where mapping should continue.
12848 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
12850 (defvar org-scanner-tags nil
12851 "The current tag list while the tags scanner is running.")
12852 (defvar org-trust-scanner-tags nil
12853 "Should `org-get-tags-at' use the tags for the scanner.
12854 This is for internal dynamical scoping only.
12855 When this is non-nil, the function `org-get-tags-at' will return the value
12856 of `org-scanner-tags' instead of building the list by itself. This
12857 can lead to large speed-ups when the tags scanner is used in a file with
12858 many entries, and when the list of tags is retrieved, for example to
12859 obtain a list of properties. Building the tags list for each entry in such
12860 a file becomes an N^2 operation - but with this variable set, it scales
12861 as N.")
12863 (defun org-scan-tags (action matcher todo-only &optional start-level)
12864 "Scan headline tags with inheritance and produce output ACTION.
12866 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
12867 or `agenda' to produce an entry list for an agenda view. It can also be
12868 a Lisp form or a function that should be called at each matched headline, in
12869 this case the return value is a list of all return values from these calls.
12871 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
12872 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
12873 only lines with a not-done TODO keyword are included in the output.
12874 This should be the same variable that was scoped into
12875 and set by `org-make-tags-matcher' when it constructed MATCHER.
12877 START-LEVEL can be a string with asterisks, reducing the scope to
12878 headlines matching this string."
12879 (require 'org-agenda)
12880 (let* ((re (concat "^"
12881 (if start-level
12882 ;; Get the correct level to match
12883 (concat "\\*\\{" (number-to-string start-level) "\\} ")
12884 org-outline-regexp)
12885 " *\\(\\<\\("
12886 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
12887 (org-re
12888 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
12889 (props (list 'face 'default
12890 'done-face 'org-agenda-done
12891 'undone-face 'default
12892 'mouse-face 'highlight
12893 'org-not-done-regexp org-not-done-regexp
12894 'org-todo-regexp org-todo-regexp
12895 'org-complex-heading-regexp org-complex-heading-regexp
12896 'help-echo
12897 (format "mouse-2 or RET jump to org file %s"
12898 (abbreviate-file-name
12899 (or (buffer-file-name (buffer-base-buffer))
12900 (buffer-name (buffer-base-buffer)))))))
12901 (case-fold-search nil)
12902 (org-map-continue-from nil)
12903 lspos tags tags-list
12904 (tags-alist (list (cons 0 org-file-tags)))
12905 (llast 0) rtn rtn1 level category i txt
12906 todo marker entry priority)
12907 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
12908 (setq action (list 'lambda nil action)))
12909 (save-excursion
12910 (goto-char (point-min))
12911 (when (eq action 'sparse-tree)
12912 (org-overview)
12913 (org-remove-occur-highlights))
12914 (while (re-search-forward re nil t)
12915 (setq org-map-continue-from nil)
12916 (catch :skip
12917 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
12918 tags (if (match-end 4) (org-match-string-no-properties 4)))
12919 (goto-char (setq lspos (match-beginning 0)))
12920 (setq level (org-reduced-level (funcall outline-level))
12921 category (org-get-category))
12922 (setq i llast llast level)
12923 ;; remove tag lists from same and sublevels
12924 (while (>= i level)
12925 (when (setq entry (assoc i tags-alist))
12926 (setq tags-alist (delete entry tags-alist)))
12927 (setq i (1- i)))
12928 ;; add the next tags
12929 (when tags
12930 (setq tags (org-split-string tags ":")
12931 tags-alist
12932 (cons (cons level tags) tags-alist)))
12933 ;; compile tags for current headline
12934 (setq tags-list
12935 (if org-use-tag-inheritance
12936 (apply 'append (mapcar 'cdr (reverse tags-alist)))
12937 tags)
12938 org-scanner-tags tags-list)
12939 (when org-use-tag-inheritance
12940 (setcdr (car tags-alist)
12941 (mapcar (lambda (x)
12942 (setq x (copy-sequence x))
12943 (org-add-prop-inherited x))
12944 (cdar tags-alist))))
12945 (when (and tags org-use-tag-inheritance
12946 (or (not (eq t org-use-tag-inheritance))
12947 org-tags-exclude-from-inheritance))
12948 ;; selective inheritance, remove uninherited ones
12949 (setcdr (car tags-alist)
12950 (org-remove-uninherited-tags (cdar tags-alist))))
12951 (when (and
12953 ;; eval matcher only when the todo condition is OK
12954 (and (or (not todo-only) (member todo org-not-done-keywords))
12955 (let ((case-fold-search t) (org-trust-scanner-tags t))
12956 (eval matcher)))
12958 ;; Call the skipper, but return t if it does not skip,
12959 ;; so that the `and' form continues evaluating
12960 (progn
12961 (unless (eq action 'sparse-tree) (org-agenda-skip))
12964 ;; Check if timestamps are deselecting this entry
12965 (or (not todo-only)
12966 (and (member todo org-not-done-keywords)
12967 (or (not org-agenda-tags-todo-honor-ignore-options)
12968 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
12970 ;; Extra check for the archive tag
12971 ;; FIXME: Does the skipper already do this????
12973 (not (member org-archive-tag tags-list))
12974 ;; we have an archive tag, should we use this anyway?
12975 (or (not org-agenda-skip-archived-trees)
12976 (and (eq action 'agenda) org-agenda-archives-mode))))
12978 ;; select this headline
12980 (cond
12981 ((eq action 'sparse-tree)
12982 (and org-highlight-sparse-tree-matches
12983 (org-get-heading) (match-end 0)
12984 (org-highlight-new-match
12985 (match-beginning 1) (match-end 1)))
12986 (org-show-context 'tags-tree))
12987 ((eq action 'agenda)
12988 (setq txt (org-agenda-format-item
12990 (concat
12991 (if (eq org-tags-match-list-sublevels 'indented)
12992 (make-string (1- level) ?.) "")
12993 (org-get-heading))
12994 category
12995 tags-list)
12996 priority (org-get-priority txt))
12997 (goto-char lspos)
12998 (setq marker (org-agenda-new-marker))
12999 (org-add-props txt props
13000 'org-marker marker 'org-hd-marker marker 'org-category category
13001 'todo-state todo
13002 'priority priority 'type "tagsmatch")
13003 (push txt rtn))
13004 ((functionp action)
13005 (setq org-map-continue-from nil)
13006 (save-excursion
13007 (setq rtn1 (funcall action))
13008 (push rtn1 rtn)))
13009 (t (error "Invalid action")))
13011 ;; if we are to skip sublevels, jump to end of subtree
13012 (unless org-tags-match-list-sublevels
13013 (org-end-of-subtree t)
13014 (backward-char 1))))
13015 ;; Get the correct position from where to continue
13016 (if org-map-continue-from
13017 (goto-char org-map-continue-from)
13018 (and (= (point) lspos) (end-of-line 1)))))
13019 (when (and (eq action 'sparse-tree)
13020 (not org-sparse-tree-open-archived-trees))
13021 (org-hide-archived-subtrees (point-min) (point-max)))
13022 (nreverse rtn)))
13024 (defun org-remove-uninherited-tags (tags)
13025 "Remove all tags that are not inherited from the list TAGS."
13026 (cond
13027 ((eq org-use-tag-inheritance t)
13028 (if org-tags-exclude-from-inheritance
13029 (org-delete-all org-tags-exclude-from-inheritance tags)
13030 tags))
13031 ((not org-use-tag-inheritance) nil)
13032 ((stringp org-use-tag-inheritance)
13033 (delq nil (mapcar
13034 (lambda (x)
13035 (if (and (string-match org-use-tag-inheritance x)
13036 (not (member x org-tags-exclude-from-inheritance)))
13037 x nil))
13038 tags)))
13039 ((listp org-use-tag-inheritance)
13040 (delq nil (mapcar
13041 (lambda (x)
13042 (if (member x org-use-tag-inheritance) x nil))
13043 tags)))))
13045 (defun org-match-sparse-tree (&optional todo-only match)
13046 "Create a sparse tree according to tags string MATCH.
13047 MATCH can contain positive and negative selection of tags, like
13048 \"+WORK+URGENT-WITHBOSS\".
13049 If optional argument TODO-ONLY is non-nil, only select lines that are
13050 also TODO lines."
13051 (interactive "P")
13052 (org-prepare-agenda-buffers (list (current-buffer)))
13053 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13055 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13057 (defvar org-cached-props nil)
13058 (defun org-cached-entry-get (pom property)
13059 (if (or (eq t org-use-property-inheritance)
13060 (and (stringp org-use-property-inheritance)
13061 (string-match org-use-property-inheritance property))
13062 (and (listp org-use-property-inheritance)
13063 (member property org-use-property-inheritance)))
13064 ;; Caching is not possible, check it directly
13065 (org-entry-get pom property 'inherit)
13066 ;; Get all properties, so that we can do complicated checks easily
13067 (cdr (assoc property (or org-cached-props
13068 (setq org-cached-props
13069 (org-entry-properties pom)))))))
13071 (defun org-global-tags-completion-table (&optional files)
13072 "Return the list of all tags in all agenda buffer/files.
13073 Optional FILES argument is a list of files to which can be used
13074 instead of the agenda files."
13075 (save-excursion
13076 (org-uniquify
13077 (delq nil
13078 (apply 'append
13079 (mapcar
13080 (lambda (file)
13081 (set-buffer (find-file-noselect file))
13082 (append (org-get-buffer-tags)
13083 (mapcar (lambda (x) (if (stringp (car-safe x))
13084 (list (car-safe x)) nil))
13085 org-tag-alist)))
13086 (if (and files (car files))
13087 files
13088 (org-agenda-files))))))))
13090 (defun org-make-tags-matcher (match)
13091 "Create the TAGS/TODO matcher form for the selection string MATCH.
13093 The variable `todo-only' is scoped dynamically into this function; it will be
13094 set to t if the matcher restricts matching to TODO entries,
13095 otherwise will not be touched.
13097 Returns a cons of the selection string MATCH and the constructed
13098 lisp form implementing the matcher. The matcher is to be
13099 evaluated at an Org entry, with point on the headline,
13100 and returns t if the entry matches the
13101 selection string MATCH. The returned lisp form references
13102 two variables with information about the entry, which must be
13103 bound around the form's evaluation: todo, the TODO keyword at the
13104 entry (or nil of none); and tags-list, the list of all tags at the
13105 entry including inherited ones. Additionally, the category
13106 of the entry (if any) must be specified as the text property
13107 'org-category on the headline.
13109 See also `org-scan-tags'.
13111 (declare (special todo-only))
13112 (unless (boundp 'todo-only)
13113 (error "org-make-tags-matcher expects todo-only to be scoped in"))
13114 (unless match
13115 ;; Get a new match request, with completion
13116 (let ((org-last-tags-completion-table
13117 (org-global-tags-completion-table)))
13118 (setq match (org-completing-read-no-i
13119 "Match: " 'org-tags-completion-function nil nil nil
13120 'org-tags-history))))
13122 ;; Parse the string and create a lisp form
13123 (let ((match0 match)
13124 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
13125 minus tag mm
13126 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
13127 orterms term orlist re-p str-p level-p level-op time-p
13128 prop-p pn pv po gv rest)
13129 (if (string-match "/+" match)
13130 ;; match contains also a todo-matching request
13131 (progn
13132 (setq tagsmatch (substring match 0 (match-beginning 0))
13133 todomatch (substring match (match-end 0)))
13134 (if (string-match "^!" todomatch)
13135 (setq todo-only t todomatch (substring todomatch 1)))
13136 (if (string-match "^\\s-*$" todomatch)
13137 (setq todomatch nil)))
13138 ;; only matching tags
13139 (setq tagsmatch match todomatch nil))
13141 ;; Make the tags matcher
13142 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
13143 (setq tagsmatcher t)
13144 (setq orterms (org-split-string tagsmatch "|") orlist nil)
13145 (while (setq term (pop orterms))
13146 (while (and (equal (substring term -1) "\\") orterms)
13147 (setq term (concat term "|" (pop orterms)))) ; repair bad split
13148 (while (string-match re term)
13149 (setq rest (substring term (match-end 0))
13150 minus (and (match-end 1)
13151 (equal (match-string 1 term) "-"))
13152 tag (save-match-data (replace-regexp-in-string
13153 "\\\\-" "-"
13154 (match-string 2 term)))
13155 re-p (equal (string-to-char tag) ?{)
13156 level-p (match-end 4)
13157 prop-p (match-end 5)
13158 mm (cond
13159 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
13160 (level-p
13161 (setq level-op (org-op-to-function (match-string 3 term)))
13162 `(,level-op level ,(string-to-number
13163 (match-string 4 term))))
13164 (prop-p
13165 (setq pn (match-string 5 term)
13166 po (match-string 6 term)
13167 pv (match-string 7 term)
13168 re-p (equal (string-to-char pv) ?{)
13169 str-p (equal (string-to-char pv) ?\")
13170 time-p (save-match-data
13171 (string-match "^\"[[<].*[]>]\"$" pv))
13172 pv (if (or re-p str-p) (substring pv 1 -1) pv))
13173 (if time-p (setq pv (org-matcher-time pv)))
13174 (setq po (org-op-to-function po (if time-p 'time str-p)))
13175 (cond
13176 ((equal pn "CATEGORY")
13177 (setq gv '(get-text-property (point) 'org-category)))
13178 ((equal pn "TODO")
13179 (setq gv 'todo))
13181 (setq gv `(org-cached-entry-get nil ,pn))))
13182 (if re-p
13183 (if (eq po 'org<>)
13184 `(not (string-match ,pv (or ,gv "")))
13185 `(string-match ,pv (or ,gv "")))
13186 (if str-p
13187 `(,po (or ,gv "") ,pv)
13188 `(,po (string-to-number (or ,gv ""))
13189 ,(string-to-number pv) ))))
13190 (t `(member ,tag tags-list)))
13191 mm (if minus (list 'not mm) mm)
13192 term rest)
13193 (push mm tagsmatcher))
13194 (push (if (> (length tagsmatcher) 1)
13195 (cons 'and tagsmatcher)
13196 (car tagsmatcher))
13197 orlist)
13198 (setq tagsmatcher nil))
13199 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
13200 (setq tagsmatcher
13201 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
13202 ;; Make the todo matcher
13203 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
13204 (setq todomatcher t)
13205 (setq orterms (org-split-string todomatch "|") orlist nil)
13206 (while (setq term (pop orterms))
13207 (while (string-match re term)
13208 (setq minus (and (match-end 1)
13209 (equal (match-string 1 term) "-"))
13210 kwd (match-string 2 term)
13211 re-p (equal (string-to-char kwd) ?{)
13212 term (substring term (match-end 0))
13213 mm (if re-p
13214 `(string-match ,(substring kwd 1 -1) todo)
13215 (list 'equal 'todo kwd))
13216 mm (if minus (list 'not mm) mm))
13217 (push mm todomatcher))
13218 (push (if (> (length todomatcher) 1)
13219 (cons 'and todomatcher)
13220 (car todomatcher))
13221 orlist)
13222 (setq todomatcher nil))
13223 (setq todomatcher (if (> (length orlist) 1)
13224 (cons 'or orlist) (car orlist))))
13226 ;; Return the string and lisp forms of the matcher
13227 (setq matcher (if todomatcher
13228 (list 'and tagsmatcher todomatcher)
13229 tagsmatcher))
13230 (when todo-only
13231 (setq matcher (list 'and '(member todo org-not-done-keywords)
13232 matcher)))
13233 (cons match0 matcher)))
13235 (defun org-op-to-function (op &optional stringp)
13236 "Turn an operator into the appropriate function."
13237 (setq op
13238 (cond
13239 ((equal op "<" ) '(< string< org-time<))
13240 ((equal op ">" ) '(> org-string> org-time>))
13241 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
13242 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
13243 ((member op '("=" "==")) '(= string= org-time=))
13244 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
13245 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
13247 (defun org<> (a b) (not (= a b)))
13248 (defun org-string<= (a b) (or (string= a b) (string< a b)))
13249 (defun org-string>= (a b) (not (string< a b)))
13250 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
13251 (defun org-string<> (a b) (not (string= a b)))
13252 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
13253 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< 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) (org<> a b)))
13258 (defun org-2ft (s)
13259 "Convert S to a floating point time.
13260 If S is already a number, just return it. If it is a string, parse
13261 it as a time string and apply `float-time' to it. If S is nil, just return 0."
13262 (cond
13263 ((numberp s) s)
13264 ((stringp s)
13265 (condition-case nil
13266 (float-time (apply 'encode-time (org-parse-time-string s)))
13267 (error 0.)))
13268 (t 0.)))
13270 (defun org-time-today ()
13271 "Time in seconds today at 0:00.
13272 Returns the float number of seconds since the beginning of the
13273 epoch to the beginning of today (00:00)."
13274 (float-time (apply 'encode-time
13275 (append '(0 0 0) (nthcdr 3 (decode-time))))))
13277 (defun org-matcher-time (s)
13278 "Interpret a time comparison value."
13279 (save-match-data
13280 (cond
13281 ((string= s "<now>") (float-time))
13282 ((string= s "<today>") (org-time-today))
13283 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
13284 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
13285 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
13286 (+ (org-time-today)
13287 (* (string-to-number (match-string 1 s))
13288 (cdr (assoc (match-string 2 s)
13289 '(("d" . 86400.0) ("w" . 604800.0)
13290 ("m" . 2678400.0) ("y" . 31557600.0)))))))
13291 (t (org-2ft s)))))
13293 (defun org-match-any-p (re list)
13294 "Does re match any element of list?"
13295 (setq list (mapcar (lambda (x) (string-match re x)) list))
13296 (delq nil list))
13298 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
13299 (defvar org-tags-overlay (make-overlay 1 1))
13300 (org-detach-overlay org-tags-overlay)
13302 (defun org-get-local-tags-at (&optional pos)
13303 "Get a list of tags defined in the current headline."
13304 (org-get-tags-at pos 'local))
13306 (defun org-get-local-tags ()
13307 "Get a list of tags defined in the current headline."
13308 (org-get-tags-at nil 'local))
13310 (defun org-get-tags-at (&optional pos local)
13311 "Get a list of all headline tags applicable at POS.
13312 POS defaults to point. If tags are inherited, the list contains
13313 the targets in the same sequence as the headlines appear, i.e.
13314 the tags of the current headline come last.
13315 When LOCAL is non-nil, only return tags from the current headline,
13316 ignore inherited ones."
13317 (interactive)
13318 (if (and org-trust-scanner-tags
13319 (or (not pos) (equal pos (point)))
13320 (not local))
13321 org-scanner-tags
13322 (let (tags ltags lastpos parent)
13323 (save-excursion
13324 (save-restriction
13325 (widen)
13326 (goto-char (or pos (point)))
13327 (save-match-data
13328 (catch 'done
13329 (condition-case nil
13330 (progn
13331 (org-back-to-heading t)
13332 (while (not (equal lastpos (point)))
13333 (setq lastpos (point))
13334 (when (looking-at
13335 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
13336 (setq ltags (org-split-string
13337 (org-match-string-no-properties 1) ":"))
13338 (when parent
13339 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
13340 (setq tags (append
13341 (if parent
13342 (org-remove-uninherited-tags ltags)
13343 ltags)
13344 tags)))
13345 (or org-use-tag-inheritance (throw 'done t))
13346 (if local (throw 'done t))
13347 (or (org-up-heading-safe) (error nil))
13348 (setq parent t)))
13349 (error nil)))))
13350 (if local
13351 tags
13352 (append (org-remove-uninherited-tags org-file-tags) tags))))))
13354 (defun org-add-prop-inherited (s)
13355 (add-text-properties 0 (length s) '(inherited t) s)
13358 (defun org-toggle-tag (tag &optional onoff)
13359 "Toggle the tag TAG for the current line.
13360 If ONOFF is `on' or `off', don't toggle but set to this state."
13361 (let (res current)
13362 (save-excursion
13363 (org-back-to-heading t)
13364 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
13365 (point-at-eol) t)
13366 (progn
13367 (setq current (match-string 1))
13368 (replace-match ""))
13369 (setq current ""))
13370 (setq current (nreverse (org-split-string current ":")))
13371 (cond
13372 ((eq onoff 'on)
13373 (setq res t)
13374 (or (member tag current) (push tag current)))
13375 ((eq onoff 'off)
13376 (or (not (member tag current)) (setq current (delete tag current))))
13377 (t (if (member tag current)
13378 (setq current (delete tag current))
13379 (setq res t)
13380 (push tag current))))
13381 (end-of-line 1)
13382 (if current
13383 (progn
13384 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
13385 (org-set-tags nil t))
13386 (delete-horizontal-space))
13387 (run-hooks 'org-after-tags-change-hook))
13388 res))
13390 (defun org-align-tags-here (to-col)
13391 ;; Assumes that this is a headline
13392 (let ((pos (point)) (col (current-column)) ncol tags-l p)
13393 (beginning-of-line 1)
13394 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13395 (< pos (match-beginning 2)))
13396 (progn
13397 (setq tags-l (- (match-end 2) (match-beginning 2)))
13398 (goto-char (match-beginning 1))
13399 (insert " ")
13400 (delete-region (point) (1+ (match-beginning 2)))
13401 (setq ncol (max (current-column)
13402 (1+ col)
13403 (if (> to-col 0)
13404 to-col
13405 (- (abs to-col) tags-l))))
13406 (setq p (point))
13407 (insert (make-string (- ncol (current-column)) ?\ ))
13408 (setq ncol (current-column))
13409 (when indent-tabs-mode (tabify p (point-at-eol)))
13410 (org-move-to-column (min ncol col) t))
13411 (goto-char pos))))
13413 (defun org-set-tags-command (&optional arg just-align)
13414 "Call the set-tags command for the current entry."
13415 (interactive "P")
13416 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
13417 (org-set-tags arg just-align)
13418 (save-excursion
13419 (org-back-to-heading t)
13420 (org-set-tags arg just-align))))
13422 (defun org-set-tags-to (data)
13423 "Set the tags of the current entry to DATA, replacing the current tags.
13424 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
13425 If DATA is nil or the empty string, any tags will be removed."
13426 (interactive "sTags: ")
13427 (setq data
13428 (cond
13429 ((eq data nil) "")
13430 ((equal data "") "")
13431 ((stringp data)
13432 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
13433 ":"))
13434 ((listp data)
13435 (concat ":" (mapconcat 'identity data ":") ":"))
13436 (t nil)))
13437 (when data
13438 (save-excursion
13439 (org-back-to-heading t)
13440 (when (looking-at org-complex-heading-regexp)
13441 (if (match-end 5)
13442 (progn
13443 (goto-char (match-beginning 5))
13444 (insert data)
13445 (delete-region (point) (point-at-eol))
13446 (org-set-tags nil 'align))
13447 (goto-char (point-at-eol))
13448 (insert " " data)
13449 (org-set-tags nil 'align)))
13450 (beginning-of-line 1)
13451 (if (looking-at ".*?\\([ \t]+\\)$")
13452 (delete-region (match-beginning 1) (match-end 1))))))
13454 (defun org-align-all-tags ()
13455 "Align the tags i all headings."
13456 (interactive)
13457 (save-excursion
13458 (or (ignore-errors (org-back-to-heading t))
13459 (outline-next-heading))
13460 (if (org-at-heading-p)
13461 (org-set-tags t)
13462 (message "No headings"))))
13464 (defvar org-indent-indentation-per-level)
13465 (defun org-set-tags (&optional arg just-align)
13466 "Set the tags for the current headline.
13467 With prefix ARG, realign all tags in headings in the current buffer."
13468 (interactive "P")
13469 (let* ((re org-outline-regexp-bol)
13470 (current (unless arg (org-get-tags-string)))
13471 (col (current-column))
13472 (org-setting-tags t)
13473 table current-tags inherited-tags ; computed below when needed
13474 tags p0 c0 c1 rpl di tc level)
13475 (if arg
13476 (save-excursion
13477 (goto-char (point-min))
13478 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
13479 (while (re-search-forward re nil t)
13480 (org-set-tags nil t)
13481 (end-of-line 1)))
13482 (message "All tags realigned to column %d" org-tags-column))
13483 (if just-align
13484 (setq tags current)
13485 ;; Get a new set of tags from the user
13486 (save-excursion
13487 (setq table (append org-tag-persistent-alist
13488 (or org-tag-alist (org-get-buffer-tags))
13489 (and
13490 org-complete-tags-always-offer-all-agenda-tags
13491 (org-global-tags-completion-table
13492 (org-agenda-files))))
13493 org-last-tags-completion-table table
13494 current-tags (org-split-string current ":")
13495 inherited-tags (nreverse
13496 (nthcdr (length current-tags)
13497 (nreverse (org-get-tags-at))))
13498 tags
13499 (if (or (eq t org-use-fast-tag-selection)
13500 (and org-use-fast-tag-selection
13501 (delq nil (mapcar 'cdr table))))
13502 (org-fast-tag-selection
13503 current-tags inherited-tags table
13504 (if org-fast-tag-selection-include-todo
13505 org-todo-key-alist))
13506 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
13507 (org-trim
13508 (org-icompleting-read "Tags: "
13509 'org-tags-completion-function
13510 nil nil current 'org-tags-history))))))
13511 (while (string-match "[-+&]+" tags)
13512 ;; No boolean logic, just a list
13513 (setq tags (replace-match ":" t t tags))))
13515 (setq tags (replace-regexp-in-string "[,]" ":" tags))
13517 (if org-tags-sort-function
13518 (setq tags (mapconcat 'identity
13519 (sort (org-split-string
13520 tags (org-re "[^[:alnum:]_@#%]+"))
13521 org-tags-sort-function) ":")))
13523 (if (string-match "\\`[\t ]*\\'" tags)
13524 (setq tags "")
13525 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
13526 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
13528 ;; Insert new tags at the correct column
13529 (beginning-of-line 1)
13530 (setq level (or (and (looking-at org-outline-regexp)
13531 (- (match-end 0) (point) 1))
13533 (cond
13534 ((and (equal current "") (equal tags "")))
13535 ((re-search-forward
13536 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
13537 (point-at-eol) t)
13538 (if (equal tags "")
13539 (setq rpl "")
13540 (goto-char (match-beginning 0))
13541 (setq c0 (current-column)
13542 ;; compute offset for the case of org-indent-mode active
13543 di (if org-indent-mode
13544 (* (1- org-indent-indentation-per-level) (1- level))
13546 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
13547 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
13548 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
13549 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
13550 (replace-match rpl t t)
13551 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
13552 tags)
13553 (t (error "Tags alignment failed")))
13554 (org-move-to-column col)
13555 (unless just-align
13556 (run-hooks 'org-after-tags-change-hook)))))
13558 (defun org-change-tag-in-region (beg end tag off)
13559 "Add or remove TAG for each entry in the region.
13560 This works in the agenda, and also in an org-mode buffer."
13561 (interactive
13562 (list (region-beginning) (region-end)
13563 (let ((org-last-tags-completion-table
13564 (if (derived-mode-p 'org-mode)
13565 (org-get-buffer-tags)
13566 (org-global-tags-completion-table))))
13567 (org-icompleting-read
13568 "Tag: " 'org-tags-completion-function nil nil nil
13569 'org-tags-history))
13570 (progn
13571 (message "[s]et or [r]emove? ")
13572 (equal (read-char-exclusive) ?r))))
13573 (if (fboundp 'deactivate-mark) (deactivate-mark))
13574 (let ((agendap (equal major-mode 'org-agenda-mode))
13575 l1 l2 m buf pos newhead (cnt 0))
13576 (goto-char end)
13577 (setq l2 (1- (org-current-line)))
13578 (goto-char beg)
13579 (setq l1 (org-current-line))
13580 (loop for l from l1 to l2 do
13581 (org-goto-line l)
13582 (setq m (get-text-property (point) 'org-hd-marker))
13583 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
13584 (and agendap m))
13585 (setq buf (if agendap (marker-buffer m) (current-buffer))
13586 pos (if agendap m (point)))
13587 (with-current-buffer buf
13588 (save-excursion
13589 (save-restriction
13590 (goto-char pos)
13591 (setq cnt (1+ cnt))
13592 (org-toggle-tag tag (if off 'off 'on))
13593 (setq newhead (org-get-heading)))))
13594 (and agendap (org-agenda-change-all-lines newhead m))))
13595 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
13597 (defun org-tags-completion-function (string predicate &optional flag)
13598 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
13599 (confirm (lambda (x) (stringp (car x)))))
13600 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
13601 (setq s1 (match-string 1 string)
13602 s2 (match-string 2 string))
13603 (setq s1 "" s2 string))
13604 (cond
13605 ((eq flag nil)
13606 ;; try completion
13607 (setq rtn (try-completion s2 ctable confirm))
13608 (if (stringp rtn)
13609 (setq rtn
13610 (concat s1 s2 (substring rtn (length s2))
13611 (if (and org-add-colon-after-tag-completion
13612 (assoc rtn ctable))
13613 ":" ""))))
13614 rtn)
13615 ((eq flag t)
13616 ;; all-completions
13617 (all-completions s2 ctable confirm)
13619 ((eq flag 'lambda)
13620 ;; exact match?
13621 (assoc s2 ctable)))
13624 (defun org-fast-tag-insert (kwd tags face &optional end)
13625 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
13626 (insert (format "%-12s" (concat kwd ":"))
13627 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
13628 (or end "")))
13630 (defun org-fast-tag-show-exit (flag)
13631 (save-excursion
13632 (org-goto-line 3)
13633 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
13634 (replace-match ""))
13635 (when flag
13636 (end-of-line 1)
13637 (org-move-to-column (- (window-width) 19) t)
13638 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
13640 (defun org-set-current-tags-overlay (current prefix)
13641 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
13642 (if (featurep 'xemacs)
13643 (org-overlay-display org-tags-overlay (concat prefix s)
13644 'secondary-selection)
13645 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
13646 (org-overlay-display org-tags-overlay (concat prefix s)))))
13648 (defvar org-last-tag-selection-key nil)
13649 (defun org-fast-tag-selection (current inherited table &optional todo-table)
13650 "Fast tag selection with single keys.
13651 CURRENT is the current list of tags in the headline, INHERITED is the
13652 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
13653 possibly with grouping information. TODO-TABLE is a similar table with
13654 TODO keywords, should these have keys assigned to them.
13655 If the keys are nil, a-z are automatically assigned.
13656 Returns the new tags string, or nil to not change the current settings."
13657 (let* ((fulltable (append table todo-table))
13658 (maxlen (apply 'max (mapcar
13659 (lambda (x)
13660 (if (stringp (car x)) (string-width (car x)) 0))
13661 fulltable)))
13662 (buf (current-buffer))
13663 (expert (eq org-fast-tag-selection-single-key 'expert))
13664 (buffer-tags nil)
13665 (fwidth (+ maxlen 3 1 3))
13666 (ncol (/ (- (window-width) 4) fwidth))
13667 (i-face 'org-done)
13668 (c-face 'org-todo)
13669 tg cnt e c char c1 c2 ntable tbl rtn
13670 ov-start ov-end ov-prefix
13671 (exit-after-next org-fast-tag-selection-single-key)
13672 (done-keywords org-done-keywords)
13673 groups ingroup)
13674 (save-excursion
13675 (beginning-of-line 1)
13676 (if (looking-at
13677 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13678 (setq ov-start (match-beginning 1)
13679 ov-end (match-end 1)
13680 ov-prefix "")
13681 (setq ov-start (1- (point-at-eol))
13682 ov-end (1+ ov-start))
13683 (skip-chars-forward "^\n\r")
13684 (setq ov-prefix
13685 (concat
13686 (buffer-substring (1- (point)) (point))
13687 (if (> (current-column) org-tags-column)
13689 (make-string (- org-tags-column (current-column)) ?\ ))))))
13690 (move-overlay org-tags-overlay ov-start ov-end)
13691 (save-window-excursion
13692 (if expert
13693 (set-buffer (get-buffer-create " *Org tags*"))
13694 (delete-other-windows)
13695 (split-window-vertically)
13696 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
13697 (erase-buffer)
13698 (org-set-local 'org-done-keywords done-keywords)
13699 (org-fast-tag-insert "Inherited" inherited i-face "\n")
13700 (org-fast-tag-insert "Current" current c-face "\n\n")
13701 (org-fast-tag-show-exit exit-after-next)
13702 (org-set-current-tags-overlay current ov-prefix)
13703 (setq tbl fulltable char ?a cnt 0)
13704 (while (setq e (pop tbl))
13705 (cond
13706 ((equal (car e) :startgroup)
13707 (push '() groups) (setq ingroup t)
13708 (when (not (= cnt 0))
13709 (setq cnt 0)
13710 (insert "\n"))
13711 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
13712 ((equal (car e) :endgroup)
13713 (setq ingroup nil cnt 0)
13714 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
13715 ((equal e '(:newline))
13716 (when (not (= cnt 0))
13717 (setq cnt 0)
13718 (insert "\n")
13719 (setq e (car tbl))
13720 (while (equal (car tbl) '(:newline))
13721 (insert "\n")
13722 (setq tbl (cdr tbl)))))
13724 (setq tg (copy-sequence (car e)) c2 nil)
13725 (if (cdr e)
13726 (setq c (cdr e))
13727 ;; automatically assign a character.
13728 (setq c1 (string-to-char
13729 (downcase (substring
13730 tg (if (= (string-to-char tg) ?@) 1 0)))))
13731 (if (or (rassoc c1 ntable) (rassoc c1 table))
13732 (while (or (rassoc char ntable) (rassoc char table))
13733 (setq char (1+ char)))
13734 (setq c2 c1))
13735 (setq c (or c2 char)))
13736 (if ingroup (push tg (car groups)))
13737 (setq tg (org-add-props tg nil 'face
13738 (cond
13739 ((not (assoc tg table))
13740 (org-get-todo-face tg))
13741 ((member tg current) c-face)
13742 ((member tg inherited) i-face)
13743 (t nil))))
13744 (if (and (= cnt 0) (not ingroup)) (insert " "))
13745 (insert "[" c "] " tg (make-string
13746 (- fwidth 4 (length tg)) ?\ ))
13747 (push (cons tg c) ntable)
13748 (when (= (setq cnt (1+ cnt)) ncol)
13749 (insert "\n")
13750 (if ingroup (insert " "))
13751 (setq cnt 0)))))
13752 (setq ntable (nreverse ntable))
13753 (insert "\n")
13754 (goto-char (point-min))
13755 (if (not expert) (org-fit-window-to-buffer))
13756 (setq rtn
13757 (catch 'exit
13758 (while t
13759 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
13760 (if (not groups) "no " "")
13761 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
13762 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13763 (setq org-last-tag-selection-key c)
13764 (cond
13765 ((= c ?\r) (throw 'exit t))
13766 ((= c ?!)
13767 (setq groups (not groups))
13768 (goto-char (point-min))
13769 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
13770 ((= c ?\C-c)
13771 (if (not expert)
13772 (org-fast-tag-show-exit
13773 (setq exit-after-next (not exit-after-next)))
13774 (setq expert nil)
13775 (delete-other-windows)
13776 (set-window-buffer (split-window-vertically) " *Org tags*")
13777 (org-switch-to-buffer-other-window " *Org tags*")
13778 (org-fit-window-to-buffer)))
13779 ((or (= c ?\C-g)
13780 (and (= c ?q) (not (rassoc c ntable))))
13781 (org-detach-overlay org-tags-overlay)
13782 (setq quit-flag t))
13783 ((= c ?\ )
13784 (setq current nil)
13785 (if exit-after-next (setq exit-after-next 'now)))
13786 ((= c ?\t)
13787 (condition-case nil
13788 (setq tg (org-icompleting-read
13789 "Tag: "
13790 (or buffer-tags
13791 (with-current-buffer buf
13792 (org-get-buffer-tags)))))
13793 (quit (setq tg "")))
13794 (when (string-match "\\S-" tg)
13795 (add-to-list 'buffer-tags (list tg))
13796 (if (member tg current)
13797 (setq current (delete tg current))
13798 (push tg current)))
13799 (if exit-after-next (setq exit-after-next 'now)))
13800 ((setq e (rassoc c todo-table) tg (car e))
13801 (with-current-buffer buf
13802 (save-excursion (org-todo tg)))
13803 (if exit-after-next (setq exit-after-next 'now)))
13804 ((setq e (rassoc c ntable) tg (car e))
13805 (if (member tg current)
13806 (setq current (delete tg current))
13807 (loop for g in groups do
13808 (if (member tg g)
13809 (mapc (lambda (x)
13810 (setq current (delete x current)))
13811 g)))
13812 (push tg current))
13813 (if exit-after-next (setq exit-after-next 'now))))
13815 ;; Create a sorted list
13816 (setq current
13817 (sort current
13818 (lambda (a b)
13819 (assoc b (cdr (memq (assoc a ntable) ntable))))))
13820 (if (eq exit-after-next 'now) (throw 'exit t))
13821 (goto-char (point-min))
13822 (beginning-of-line 2)
13823 (delete-region (point) (point-at-eol))
13824 (org-fast-tag-insert "Current" current c-face)
13825 (org-set-current-tags-overlay current ov-prefix)
13826 (while (re-search-forward
13827 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
13828 (setq tg (match-string 1))
13829 (add-text-properties
13830 (match-beginning 1) (match-end 1)
13831 (list 'face
13832 (cond
13833 ((member tg current) c-face)
13834 ((member tg inherited) i-face)
13835 (t (get-text-property (match-beginning 1) 'face))))))
13836 (goto-char (point-min)))))
13837 (org-detach-overlay org-tags-overlay)
13838 (if rtn
13839 (mapconcat 'identity current ":")
13840 nil))))
13842 (defun org-get-tags-string ()
13843 "Get the TAGS string in the current headline."
13844 (unless (org-at-heading-p t)
13845 (error "Not on a heading"))
13846 (save-excursion
13847 (beginning-of-line 1)
13848 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13849 (org-match-string-no-properties 1)
13850 "")))
13852 (defun org-get-tags ()
13853 "Get the list of tags specified in the current headline."
13854 (org-split-string (org-get-tags-string) ":"))
13856 (defun org-get-buffer-tags ()
13857 "Get a table of all tags used in the buffer, for completion."
13858 (let (tags)
13859 (save-excursion
13860 (goto-char (point-min))
13861 (while (re-search-forward
13862 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
13863 (when (equal (char-after (point-at-bol 0)) ?*)
13864 (mapc (lambda (x) (add-to-list 'tags x))
13865 (org-split-string (org-match-string-no-properties 1) ":")))))
13866 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
13867 (mapcar 'list tags)))
13869 ;;;; The mapping API
13871 ;;;###autoload
13872 (defun org-map-entries (func &optional match scope &rest skip)
13873 "Call FUNC at each headline selected by MATCH in SCOPE.
13875 FUNC is a function or a lisp form. The function will be called without
13876 arguments, with the cursor positioned at the beginning of the headline.
13877 The return values of all calls to the function will be collected and
13878 returned as a list.
13880 The call to FUNC will be wrapped into a save-excursion form, so FUNC
13881 does not need to preserve point. After evaluation, the cursor will be
13882 moved to the end of the line (presumably of the headline of the
13883 processed entry) and search continues from there. Under some
13884 circumstances, this may not produce the wanted results. For example,
13885 if you have removed (e.g. archived) the current (sub)tree it could
13886 mean that the next entry will be skipped entirely. In such cases, you
13887 can specify the position from where search should continue by making
13888 FUNC set the variable `org-map-continue-from' to the desired buffer
13889 position.
13891 MATCH is a tags/property/todo match as it is used in the agenda tags view.
13892 Only headlines that are matched by this query will be considered during
13893 the iteration. When MATCH is nil or t, all headlines will be
13894 visited by the iteration.
13896 SCOPE determines the scope of this command. It can be any of:
13898 nil The current buffer, respecting the restriction if any
13899 tree The subtree started with the entry at point
13900 region The entries within the active region, if any
13901 region-start-level
13902 The entries within the active region, but only those at
13903 the same level than the first one.
13904 file The current buffer, without restriction
13905 file-with-archives
13906 The current buffer, and any archives associated with it
13907 agenda All agenda files
13908 agenda-with-archives
13909 All agenda files with any archive files associated with them
13910 \(file1 file2 ...)
13911 If this is a list, all files in the list will be scanned
13913 The remaining args are treated as settings for the skipping facilities of
13914 the scanner. The following items can be given here:
13916 archive skip trees with the archive tag.
13917 comment skip trees with the COMMENT keyword
13918 function or Emacs Lisp form:
13919 will be used as value for `org-agenda-skip-function', so whenever
13920 the function returns t, FUNC will not be called for that
13921 entry and search will continue from the point where the
13922 function leaves it.
13924 If your function needs to retrieve the tags including inherited tags
13925 at the *current* entry, you can use the value of the variable
13926 `org-scanner-tags' which will be much faster than getting the value
13927 with `org-get-tags-at'. If your function gets properties with
13928 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
13929 to t around the call to `org-entry-properties' to get the same speedup.
13930 Note that if your function moves around to retrieve tags and properties at
13931 a *different* entry, you cannot use these techniques."
13932 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
13933 (not (org-region-active-p)))
13934 (let* ((org-agenda-archives-mode nil) ; just to make sure
13935 (org-agenda-skip-archived-trees (memq 'archive skip))
13936 (org-agenda-skip-comment-trees (memq 'comment skip))
13937 (org-agenda-skip-function
13938 (car (org-delete-all '(comment archive) skip)))
13939 (org-tags-match-list-sublevels t)
13940 (start-level (eq scope 'region-start-level))
13941 matcher file res
13942 org-todo-keywords-for-agenda
13943 org-done-keywords-for-agenda
13944 org-todo-keyword-alist-for-agenda
13945 org-drawers-for-agenda
13946 org-tag-alist-for-agenda
13947 todo-only)
13949 (cond
13950 ((eq match t) (setq matcher t))
13951 ((eq match nil) (setq matcher t))
13952 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
13954 (save-excursion
13955 (save-restriction
13956 (cond ((eq scope 'tree)
13957 (org-back-to-heading t)
13958 (org-narrow-to-subtree)
13959 (setq scope nil))
13960 ((and (or (eq scope 'region) (eq scope 'region-start-level))
13961 (org-region-active-p))
13962 ;; If needed, set start-level to a string like "2"
13963 (when start-level
13964 (save-excursion
13965 (goto-char (region-beginning))
13966 (unless (org-at-heading-p) (outline-next-heading))
13967 (setq start-level (org-current-level))))
13968 (narrow-to-region (region-beginning)
13969 (save-excursion
13970 (goto-char (region-end))
13971 (unless (and (bolp) (org-at-heading-p))
13972 (outline-next-heading))
13973 (point)))
13974 (setq scope nil)))
13976 (if (not scope)
13977 (progn
13978 (org-prepare-agenda-buffers
13979 (list (buffer-file-name (current-buffer))))
13980 (setq res (org-scan-tags func matcher todo-only start-level)))
13981 ;; Get the right scope
13982 (cond
13983 ((and scope (listp scope) (symbolp (car scope)))
13984 (setq scope (eval scope)))
13985 ((eq scope 'agenda)
13986 (setq scope (org-agenda-files t)))
13987 ((eq scope 'agenda-with-archives)
13988 (setq scope (org-agenda-files t))
13989 (setq scope (org-add-archive-files scope)))
13990 ((eq scope 'file)
13991 (setq scope (list (buffer-file-name))))
13992 ((eq scope 'file-with-archives)
13993 (setq scope (org-add-archive-files (list (buffer-file-name))))))
13994 (org-prepare-agenda-buffers scope)
13995 (while (setq file (pop scope))
13996 (with-current-buffer (org-find-base-buffer-visiting file)
13997 (save-excursion
13998 (save-restriction
13999 (widen)
14000 (goto-char (point-min))
14001 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
14002 res)))
14004 ;;;; Properties
14006 ;;; Setting and retrieving properties
14008 (defconst org-special-properties
14009 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
14010 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM")
14011 "The special properties valid in Org-mode.
14013 These are properties that are not defined in the property drawer,
14014 but in some other way.")
14016 (defconst org-default-properties
14017 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
14018 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
14019 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
14020 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
14021 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
14022 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
14023 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
14024 "Some properties that are used by Org-mode for various purposes.
14025 Being in this list makes sure that they are offered for completion.")
14027 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
14028 "Regular expression matching the first line of a property drawer.")
14030 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
14031 "Regular expression matching the last line of a property drawer.")
14033 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
14034 "Regular expression matching the first line of a property drawer.")
14036 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
14037 "Regular expression matching the first line of a property drawer.")
14039 (defconst org-property-drawer-re
14040 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
14041 org-property-end-re "\\)\n?")
14042 "Matches an entire property drawer.")
14044 (defconst org-clock-drawer-re
14045 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
14046 org-property-end-re "\\)\n?")
14047 "Matches an entire clock drawer.")
14049 (defsubst org-re-property (property)
14050 "Return a regexp matching PROPERTY.
14051 Match group 1 will be set to the value "
14052 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
14054 (defun org-property-action ()
14055 "Do an action on properties."
14056 (interactive)
14057 (let (c)
14058 (org-at-property-p)
14059 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14060 (setq c (read-char-exclusive))
14061 (cond
14062 ((equal c ?s)
14063 (call-interactively 'org-set-property))
14064 ((equal c ?d)
14065 (call-interactively 'org-delete-property))
14066 ((equal c ?D)
14067 (call-interactively 'org-delete-property-globally))
14068 ((equal c ?c)
14069 (call-interactively 'org-compute-property-at-point))
14070 (t (error "No such property action %c" c)))))
14072 (defun org-set-effort (&optional value)
14073 "Set the effort property of the current entry.
14074 With numerical prefix arg, use the nth allowed value, 0 stands for the 10th
14075 allowed value."
14076 (interactive "P")
14077 (if (equal value 0) (setq value 10))
14078 (let* ((completion-ignore-case t)
14079 (prop org-effort-property)
14080 (cur (org-entry-get nil prop))
14081 (allowed (org-property-get-allowed-values nil prop 'table))
14082 (existing (mapcar 'list (org-property-values prop)))
14084 (val (cond
14085 ((stringp value) value)
14086 ((and allowed (integerp value))
14087 (or (car (nth (1- value) allowed))
14088 (car (org-last allowed))))
14089 (allowed
14090 (message "Select 1-9,0, [RET%s]: %s"
14091 (if cur (concat "=" cur) "")
14092 (mapconcat 'car allowed " "))
14093 (setq rpl (read-char-exclusive))
14094 (if (equal rpl ?\r)
14096 (setq rpl (- rpl ?0))
14097 (if (equal rpl 0) (setq rpl 10))
14098 (if (and (> rpl 0) (<= rpl (length allowed)))
14099 (car (nth (1- rpl) allowed))
14100 (org-completing-read "Effort: " allowed nil))))
14102 (let (org-completion-use-ido org-completion-use-iswitchb)
14103 (org-completing-read
14104 (concat "Effort " (if (and cur (string-match "\\S-" cur))
14105 (concat "[" cur "]") "")
14106 ": ")
14107 existing nil nil "" nil cur))))))
14108 (unless (equal (org-entry-get nil prop) val)
14109 (org-entry-put nil prop val))
14110 (message "%s is now %s" prop val)))
14112 (defun org-at-property-p ()
14113 "Is cursor inside a property drawer?"
14114 (save-excursion
14115 (beginning-of-line 1)
14116 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
14117 (save-match-data ;; Used by calling procedures
14118 (let ((p (point))
14119 (range (unless (org-before-first-heading-p)
14120 (org-get-property-block))))
14121 (and range (<= (car range) p) (< p (cdr range))))))))
14123 (defun org-get-property-block (&optional beg end force)
14124 "Return the (beg . end) range of the body of the property drawer.
14125 BEG and END can be beginning and end of subtree, if not given
14126 they will be found.
14127 If the drawer does not exist and FORCE is non-nil, create the drawer."
14128 (catch 'exit
14129 (save-excursion
14130 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
14131 (end (or end (progn (outline-next-heading) (point)))))
14132 (goto-char beg)
14133 (if (re-search-forward org-property-start-re end t)
14134 (setq beg (1+ (match-end 0)))
14135 (if force
14136 (save-excursion
14137 (org-insert-property-drawer)
14138 (setq end (progn (outline-next-heading) (point))))
14139 (throw 'exit nil))
14140 (goto-char beg)
14141 (if (re-search-forward org-property-start-re end t)
14142 (setq beg (1+ (match-end 0)))))
14143 (if (re-search-forward org-property-end-re end t)
14144 (setq end (match-beginning 0))
14145 (or force (throw 'exit nil))
14146 (goto-char beg)
14147 (setq end beg)
14148 (org-indent-line-function)
14149 (insert ":END:\n"))
14150 (cons beg end)))))
14152 (defun org-entry-properties (&optional pom which specific)
14153 "Get all properties of the entry at point-or-marker POM.
14154 This includes the TODO keyword, the tags, time strings for deadline,
14155 scheduled, and clocking, and any additional properties defined in the
14156 entry. The return value is an alist, keys may occur multiple times
14157 if the property key was used several times.
14158 POM may also be nil, in which case the current entry is used.
14159 If WHICH is nil or `all', get all properties. If WHICH is
14160 `special' or `standard', only get that subclass. If WHICH
14161 is a string only get exactly this property. SPECIFIC can be a string, the
14162 specific property we are interested in. Specifying it can speed
14163 things up because then unnecessary parsing is avoided."
14164 (setq which (or which 'all))
14165 (org-with-point-at pom
14166 (let ((clockstr (substring org-clock-string 0 -1))
14167 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
14168 (case-fold-search nil)
14169 beg end range props sum-props key key1 value string clocksum)
14170 (save-excursion
14171 (when (condition-case nil
14172 (and (derived-mode-p 'org-mode) (org-back-to-heading t))
14173 (error nil))
14174 (setq beg (point))
14175 (setq sum-props (get-text-property (point) 'org-summaries))
14176 (setq clocksum (get-text-property (point) :org-clock-minutes))
14177 (outline-next-heading)
14178 (setq end (point))
14179 (when (memq which '(all special))
14180 ;; Get the special properties, like TODO and tags
14181 (goto-char beg)
14182 (when (and (or (not specific) (string= specific "TODO"))
14183 (looking-at org-todo-line-regexp) (match-end 2))
14184 (push (cons "TODO" (org-match-string-no-properties 2)) props))
14185 (when (and (or (not specific) (string= specific "PRIORITY"))
14186 (looking-at org-priority-regexp))
14187 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
14188 (when (or (not specific) (string= specific "FILE"))
14189 (push (cons "FILE" buffer-file-name) props))
14190 (when (and (or (not specific) (string= specific "TAGS"))
14191 (setq value (org-get-tags-string))
14192 (string-match "\\S-" value))
14193 (push (cons "TAGS" value) props))
14194 (when (and (or (not specific) (string= specific "ALLTAGS"))
14195 (setq value (org-get-tags-at)))
14196 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
14197 ":"))
14198 props))
14199 (when (or (not specific) (string= specific "BLOCKED"))
14200 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
14201 (when (or (not specific)
14202 (member specific
14203 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
14204 "TIMESTAMP" "TIMESTAMP_IA")))
14205 (catch 'match
14206 (while (re-search-forward org-maybe-keyword-time-regexp end t)
14207 (setq key (if (match-end 1)
14208 (substring (org-match-string-no-properties 1)
14209 0 -1))
14210 string (if (equal key clockstr)
14211 (org-no-properties
14212 (org-trim
14213 (buffer-substring
14214 (match-beginning 3) (goto-char
14215 (point-at-eol)))))
14216 (substring (org-match-string-no-properties 3)
14217 1 -1)))
14218 ;; Get the correct property name from the key. This is
14219 ;; necessary if the user has configured time keywords.
14220 (setq key1 (concat key ":"))
14221 (cond
14222 ((not key)
14223 (setq key
14224 (if (= (char-after (match-beginning 3)) ?\[)
14225 "TIMESTAMP_IA" "TIMESTAMP")))
14226 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
14227 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
14228 ((equal key1 org-closed-string) (setq key "CLOSED"))
14229 ((equal key1 org-clock-string) (setq key "CLOCK")))
14230 (if (and specific (equal key specific) (not (equal key "CLOCK")))
14231 (progn
14232 (push (cons key string) props)
14233 ;; no need to search further if match is found
14234 (throw 'match t))
14235 (when (or (equal key "CLOCK") (not (assoc key props)))
14236 (push (cons key string) props))))))
14239 (when (memq which '(all standard))
14240 ;; Get the standard properties, like :PROP: ...
14241 (setq range (org-get-property-block beg end))
14242 (when range
14243 (goto-char (car range))
14244 (while (re-search-forward
14245 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
14246 (cdr range) t)
14247 (setq key (org-match-string-no-properties 1)
14248 value (org-trim (or (org-match-string-no-properties 2) "")))
14249 (unless (member key excluded)
14250 (push (cons key (or value "")) props)))))
14251 (if clocksum
14252 (push (cons "CLOCKSUM"
14253 (org-columns-number-to-string (/ (float clocksum) 60.)
14254 'add_times))
14255 props))
14256 (unless (assoc "CATEGORY" props)
14257 (push (cons "CATEGORY" (org-get-category)) props))
14258 (append sum-props (nreverse props)))))))
14260 (defun org-entry-get (pom property &optional inherit literal-nil)
14261 "Get value of PROPERTY for entry at point-or-marker POM.
14262 If INHERIT is non-nil and the entry does not have the property,
14263 then also check higher levels of the hierarchy.
14264 If INHERIT is the symbol `selective', use inheritance only if the setting
14265 in `org-use-property-inheritance' selects PROPERTY for inheritance.
14266 If the property is present but empty, the return value is the empty string.
14267 If the property is not present at all, nil is returned.
14269 If LITERAL-NIL is set, return the string value \"nil\" as a string,
14270 do not interpret it as the list atom nil. This is used for inheritance
14271 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
14272 (org-with-point-at pom
14273 (if (and inherit (if (eq inherit 'selective)
14274 (org-property-inherit-p property)
14276 (org-entry-get-with-inheritance property literal-nil)
14277 (if (member property org-special-properties)
14278 ;; We need a special property. Use `org-entry-properties' to
14279 ;; retrieve it, but specify the wanted property
14280 (cdr (assoc property (org-entry-properties nil 'special property)))
14281 (let ((range (unless (org-before-first-heading-p)
14282 (org-get-property-block)))
14283 (props (list (or (assoc property org-file-properties)
14284 (assoc property org-global-properties)
14285 (assoc property org-global-properties-fixed))))
14286 val)
14287 (flet ((ap (key)
14288 (when (re-search-forward
14289 (org-re-property key) (cdr range) t)
14290 (setq props
14291 (org-update-property-plist
14293 (if (match-end 1)
14294 (org-match-string-no-properties 1) "")
14295 props)))))
14296 (when (and range (goto-char (car range)))
14297 (ap property)
14298 (goto-char (car range))
14299 (while (ap (concat property "+")))
14300 (setq val (cdr (assoc property props)))
14301 (when val (if literal-nil val (org-not-nil val))))))))))
14303 (defun org-property-or-variable-value (var &optional inherit)
14304 "Check if there is a property fixing the value of VAR.
14305 If yes, return this value. If not, return the current value of the variable."
14306 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14307 (if (and prop (stringp prop) (string-match "\\S-" prop))
14308 (read prop)
14309 (symbol-value var))))
14311 (defun org-entry-delete (pom property)
14312 "Delete the property PROPERTY from entry at point-or-marker POM."
14313 (org-with-point-at pom
14314 (if (member property org-special-properties)
14315 nil ; cannot delete these properties.
14316 (let ((range (org-get-property-block)))
14317 (if (and range
14318 (goto-char (car range))
14319 (re-search-forward
14320 (org-re-property property)
14321 (cdr range) t))
14322 (progn
14323 (delete-region (match-beginning 0) (1+ (point-at-eol)))
14325 nil)))))
14327 ;; Multi-values properties are properties that contain multiple values
14328 ;; These values are assumed to be single words, separated by whitespace.
14329 (defun org-entry-add-to-multivalued-property (pom property value)
14330 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
14331 (let* ((old (org-entry-get pom property))
14332 (values (and old (org-split-string old "[ \t]"))))
14333 (setq value (org-entry-protect-space value))
14334 (unless (member value values)
14335 (setq values (cons value values))
14336 (org-entry-put pom property
14337 (mapconcat 'identity values " ")))))
14339 (defun org-entry-remove-from-multivalued-property (pom property value)
14340 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
14341 (let* ((old (org-entry-get pom property))
14342 (values (and old (org-split-string old "[ \t]"))))
14343 (setq value (org-entry-protect-space value))
14344 (when (member value values)
14345 (setq values (delete value values))
14346 (org-entry-put pom property
14347 (mapconcat 'identity values " ")))))
14349 (defun org-entry-member-in-multivalued-property (pom property value)
14350 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
14351 (let* ((old (org-entry-get pom property))
14352 (values (and old (org-split-string old "[ \t]"))))
14353 (setq value (org-entry-protect-space value))
14354 (member value values)))
14356 (defun org-entry-get-multivalued-property (pom property)
14357 "Return a list of values in a multivalued property."
14358 (let* ((value (org-entry-get pom property))
14359 (values (and value (org-split-string value "[ \t]"))))
14360 (mapcar 'org-entry-restore-space values)))
14362 (defun org-entry-put-multivalued-property (pom property &rest values)
14363 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
14364 VALUES should be a list of strings. Spaces will be protected."
14365 (org-entry-put pom property
14366 (mapconcat 'org-entry-protect-space values " "))
14367 (let* ((value (org-entry-get pom property))
14368 (values (and value (org-split-string value "[ \t]"))))
14369 (mapcar 'org-entry-restore-space values)))
14371 (defun org-entry-protect-space (s)
14372 "Protect spaces and newline in string S."
14373 (while (string-match " " s)
14374 (setq s (replace-match "%20" t t s)))
14375 (while (string-match "\n" s)
14376 (setq s (replace-match "%0A" t t s)))
14379 (defun org-entry-restore-space (s)
14380 "Restore spaces and newline in string S."
14381 (while (string-match "%20" s)
14382 (setq s (replace-match " " t t s)))
14383 (while (string-match "%0A" s)
14384 (setq s (replace-match "\n" t t s)))
14387 (defvar org-entry-property-inherited-from (make-marker)
14388 "Marker pointing to the entry from where a property was inherited.
14389 Each call to `org-entry-get-with-inheritance' will set this marker to the
14390 location of the entry where the inheritance search matched. If there was
14391 no match, the marker will point nowhere.
14392 Note that also `org-entry-get' calls this function, if the INHERIT flag
14393 is set.")
14395 (defun org-entry-get-with-inheritance (property &optional literal-nil)
14396 "Get entry property, and search higher levels if not present.
14397 The search will stop at the first ancestor which has the property defined.
14398 If the value found is \"nil\", return nil to show that the property
14399 should be considered as undefined (this is the meaning of nil here).
14400 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
14401 (move-marker org-entry-property-inherited-from nil)
14402 (let (tmp)
14403 (unless (org-before-first-heading-p)
14404 (save-excursion
14405 (save-restriction
14406 (widen)
14407 (catch 'ex
14408 (while t
14409 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
14410 (org-back-to-heading t)
14411 (move-marker org-entry-property-inherited-from (point))
14412 (throw 'ex tmp))
14413 (or (org-up-heading-safe) (throw 'ex nil)))))))
14414 (setq tmp (or tmp
14415 (cdr (assoc property org-file-properties))
14416 (cdr (assoc property org-global-properties))
14417 (cdr (assoc property org-global-properties-fixed))))
14418 (if literal-nil tmp (org-not-nil tmp))))
14420 (defvar org-property-changed-functions nil
14421 "Hook called when the value of a property has changed.
14422 Each hook function should accept two arguments, the name of the property
14423 and the new value.")
14425 (defun org-entry-put (pom property value)
14426 "Set PROPERTY to VALUE for entry at point-or-marker POM."
14427 (org-with-point-at pom
14428 (org-back-to-heading t)
14429 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
14430 range)
14431 (cond
14432 ((equal property "TODO")
14433 (when (and (stringp value) (string-match "\\S-" value)
14434 (not (member value org-todo-keywords-1)))
14435 (error "\"%s\" is not a valid TODO state" value))
14436 (if (or (not value)
14437 (not (string-match "\\S-" value)))
14438 (setq value 'none))
14439 (org-todo value)
14440 (org-set-tags nil 'align))
14441 ((equal property "PRIORITY")
14442 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
14443 (string-to-char value) ?\ ))
14444 (org-set-tags nil 'align))
14445 ((equal property "SCHEDULED")
14446 (if (re-search-forward org-scheduled-time-regexp end t)
14447 (cond
14448 ((eq value 'earlier) (org-timestamp-change -1 'day))
14449 ((eq value 'later) (org-timestamp-change 1 'day))
14450 (t (call-interactively 'org-schedule)))
14451 (call-interactively 'org-schedule)))
14452 ((equal property "DEADLINE")
14453 (if (re-search-forward org-deadline-time-regexp end t)
14454 (cond
14455 ((eq value 'earlier) (org-timestamp-change -1 'day))
14456 ((eq value 'later) (org-timestamp-change 1 'day))
14457 (t (call-interactively 'org-deadline)))
14458 (call-interactively 'org-deadline)))
14459 ((member property org-special-properties)
14460 (error "The %s property can not yet be set with `org-entry-put'"
14461 property))
14462 (t ; a non-special property
14463 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
14464 (setq range (org-get-property-block beg end 'force))
14465 (goto-char (car range))
14466 (if (re-search-forward
14467 (org-re-property property) (cdr range) t)
14468 (progn
14469 (delete-region (match-beginning 0) (match-end 0))
14470 (goto-char (match-beginning 0)))
14471 (goto-char (cdr range))
14472 (insert "\n")
14473 (backward-char 1)
14474 (org-indent-line-function))
14475 (insert ":" property ":")
14476 (and value (insert " " value))
14477 (org-indent-line-function)))))
14478 (run-hook-with-args 'org-property-changed-functions property value)))
14480 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
14481 "Get all property keys in the current buffer.
14482 With INCLUDE-SPECIALS, also list the special properties that reflect things
14483 like tags and TODO state.
14484 With INCLUDE-DEFAULTS, also include properties that has special meaning
14485 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
14486 and others.
14487 With INCLUDE-COLUMNS, also include property names given in COLUMN
14488 formats in the current buffer."
14489 (let (rtn range cfmt s p)
14490 (save-excursion
14491 (save-restriction
14492 (widen)
14493 (goto-char (point-min))
14494 (while (re-search-forward org-property-start-re nil t)
14495 (setq range (org-get-property-block))
14496 (goto-char (car range))
14497 (while (re-search-forward
14498 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
14499 (cdr range) t)
14500 (add-to-list 'rtn (org-match-string-no-properties 1)))
14501 (outline-next-heading))))
14503 (when include-specials
14504 (setq rtn (append org-special-properties rtn)))
14506 (when include-defaults
14507 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
14508 (add-to-list 'rtn org-effort-property))
14510 (when include-columns
14511 (save-excursion
14512 (save-restriction
14513 (widen)
14514 (goto-char (point-min))
14515 (while (re-search-forward
14516 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
14517 nil t)
14518 (setq cfmt (match-string 2) s 0)
14519 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
14520 cfmt s)
14521 (setq s (match-end 0)
14522 p (match-string 1 cfmt))
14523 (unless (or (equal p "ITEM")
14524 (member p org-special-properties))
14525 (add-to-list 'rtn (match-string 1 cfmt))))))))
14527 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
14529 (defun org-property-values (key)
14530 "Return a list of all values of property KEY in the current buffer."
14531 (save-excursion
14532 (save-restriction
14533 (widen)
14534 (goto-char (point-min))
14535 (let ((re (org-re-property key))
14536 values)
14537 (while (re-search-forward re nil t)
14538 (add-to-list 'values (org-trim (match-string 1))))
14539 (delete "" values)))))
14541 (defun org-insert-property-drawer ()
14542 "Insert a property drawer into the current entry."
14543 (org-back-to-heading t)
14544 (looking-at org-outline-regexp)
14545 (let ((indent (if org-adapt-indentation
14546 (- (match-end 0) (match-beginning 0))
14548 (beg (point))
14549 (re (concat "^[ \t]*" org-keyword-time-regexp))
14550 end hiddenp)
14551 (outline-next-heading)
14552 (setq end (point))
14553 (goto-char beg)
14554 (while (re-search-forward re end t))
14555 (setq hiddenp (outline-invisible-p))
14556 (end-of-line 1)
14557 (and (equal (char-after) ?\n) (forward-char 1))
14558 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
14559 (if (member (match-string 1) '("CLOCK:" ":END:"))
14560 ;; just skip this line
14561 (beginning-of-line 2)
14562 ;; Drawer start, find the end
14563 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
14564 (beginning-of-line 1)))
14565 (org-skip-over-state-notes)
14566 (skip-chars-backward " \t\n\r")
14567 (if (eq (char-before) ?*) (forward-char 1))
14568 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
14569 (beginning-of-line 0)
14570 (org-indent-to-column indent)
14571 (beginning-of-line 2)
14572 (org-indent-to-column indent)
14573 (beginning-of-line 0)
14574 (if hiddenp
14575 (save-excursion
14576 (org-back-to-heading t)
14577 (hide-entry))
14578 (org-flag-drawer t))))
14580 (defun org-insert-drawer (&optional arg drawer)
14581 "Insert a drawer at point.
14583 Optional argument DRAWER, when non-nil, is a string representing
14584 drawer's name. Otherwise, the user is prompted for a name.
14586 If a region is active, insert the drawer around that region
14587 instead.
14589 Point is left between drawer's boundaries."
14590 (interactive "P")
14591 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
14592 "LOGBOOK"))
14593 ;; SYSTEM-DRAWERS is a list of drawer names that are used
14594 ;; internally by Org. They are meant to be inserted
14595 ;; automatically.
14596 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
14597 ;; Remove system drawers from list. Note: For some reason,
14598 ;; `org-completing-read' ignores the predicate while
14599 ;; `completing-read' handles it fine.
14600 (drawer (if arg "PROPERTIES"
14601 (or drawer
14602 (completing-read
14603 "Drawer: " org-drawers
14604 (lambda (d) (not (member d system-drawers))))))))
14605 (cond
14606 ;; With C-u, fall back on `org-insert-property-drawer'
14607 (arg (org-insert-property-drawer))
14608 ;; With an active region, insert a drawer at point.
14609 ((not (org-region-active-p))
14610 (progn
14611 (unless (bolp) (insert "\n"))
14612 (insert (format ":%s:\n\n:END:\n" drawer))
14613 (forward-line -2)))
14614 ;; Otherwise, insert the drawer at point
14616 (let ((rbeg (region-beginning))
14617 (rend (copy-marker (region-end))))
14618 (unwind-protect
14619 (progn
14620 (goto-char rbeg)
14621 (beginning-of-line)
14622 (when (save-excursion
14623 (re-search-forward org-outline-regexp-bol rend t))
14624 (error "Drawers cannot contain headlines"))
14625 ;; Position point at the beginning of the first
14626 ;; non-blank line in region. Insert drawer's opening
14627 ;; there, then indent it.
14628 (org-skip-whitespace)
14629 (beginning-of-line)
14630 (insert ":" drawer ":\n")
14631 (forward-line -1)
14632 (indent-for-tab-command)
14633 ;; Move point to the beginning of the first blank line
14634 ;; after the last non-blank line in region. Insert
14635 ;; drawer's closing, then indent it.
14636 (goto-char rend)
14637 (skip-chars-backward " \r\t\n")
14638 (insert "\n:END:")
14639 (indent-for-tab-command)
14640 (unless (eolp) (insert "\n")))
14641 ;; Clear marker, whatever the outcome of insertion is.
14642 (set-marker rend nil)))))))
14644 (defvar org-property-set-functions-alist nil
14645 "Property set function alist.
14646 Each entry should have the following format:
14648 (PROPERTY . READ-FUNCTION)
14650 The read function will be called with the same argument as
14651 `org-completing-read'.")
14653 (defun org-set-property-function (property)
14654 "Get the function that should be used to set PROPERTY.
14655 This is computed according to `org-property-set-functions-alist'."
14656 (or (cdr (assoc property org-property-set-functions-alist))
14657 'org-completing-read))
14659 (defun org-read-property-value (property)
14660 "Read PROPERTY value from user."
14661 (let* ((completion-ignore-case t)
14662 (allowed (org-property-get-allowed-values nil property 'table))
14663 (cur (org-entry-get nil property))
14664 (prompt (concat property " value"
14665 (if (and cur (string-match "\\S-" cur))
14666 (concat " [" cur "]") "") ": "))
14667 (set-function (org-set-property-function property))
14668 (val (if allowed
14669 (funcall set-function prompt allowed nil
14670 (not (get-text-property 0 'org-unrestricted
14671 (caar allowed))))
14672 (let (org-completion-use-ido org-completion-use-iswitchb)
14673 (funcall set-function prompt
14674 (mapcar 'list (org-property-values property))
14675 nil nil "" nil cur)))))
14676 (if (equal val "")
14678 val)))
14680 (defvar org-last-set-property nil)
14681 (defun org-read-property-name ()
14682 "Read a property name."
14683 (let* ((completion-ignore-case t)
14684 (keys (org-buffer-property-keys nil t t))
14685 (default-prop (or (save-excursion
14686 (save-match-data
14687 (beginning-of-line)
14688 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
14689 (null (string= (match-string 1) "END"))
14690 (match-string 1))))
14691 org-last-set-property))
14692 (property (org-icompleting-read
14693 (concat "Property"
14694 (if default-prop (concat " [" default-prop "]") "")
14695 ": ")
14696 (mapcar 'list keys)
14697 nil nil nil nil
14698 default-prop
14700 (if (member property keys)
14701 property
14702 (or (cdr (assoc (downcase property)
14703 (mapcar (lambda (x) (cons (downcase x) x))
14704 keys)))
14705 property))))
14707 (defun org-set-property (property value)
14708 "In the current entry, set PROPERTY to VALUE.
14709 When called interactively, this will prompt for a property name, offering
14710 completion on existing and default properties. And then it will prompt
14711 for a value, offering completion either on allowed values (via an inherited
14712 xxx_ALL property) or on existing values in other instances of this property
14713 in the current file."
14714 (interactive (list nil nil))
14715 (let* ((property (or property (org-read-property-name)))
14716 (value (or value (org-read-property-value property)))
14717 (fn (cadr (assoc property org-properties-postprocess-alist))))
14718 (setq org-last-set-property property)
14719 ;; Possibly postprocess the inserted value:
14720 (when fn (setq value (funcall fn value)))
14721 (unless (equal (org-entry-get nil property) value)
14722 (org-entry-put nil property value))))
14724 (defun org-delete-property (property)
14725 "In the current entry, delete PROPERTY."
14726 (interactive
14727 (let* ((completion-ignore-case t)
14728 (prop (org-icompleting-read "Property: "
14729 (org-entry-properties nil 'standard))))
14730 (list prop)))
14731 (message "Property %s %s" property
14732 (if (org-entry-delete nil property)
14733 "deleted"
14734 "was not present in the entry")))
14736 (defun org-delete-property-globally (property)
14737 "Remove PROPERTY globally, from all entries."
14738 (interactive
14739 (let* ((completion-ignore-case t)
14740 (prop (org-icompleting-read
14741 "Globally remove property: "
14742 (mapcar 'list (org-buffer-property-keys)))))
14743 (list prop)))
14744 (save-excursion
14745 (save-restriction
14746 (widen)
14747 (goto-char (point-min))
14748 (let ((cnt 0))
14749 (while (re-search-forward
14750 (org-re-property property)
14751 nil t)
14752 (setq cnt (1+ cnt))
14753 (delete-region (match-beginning 0) (1+ (point-at-eol))))
14754 (message "Property \"%s\" removed from %d entries" property cnt)))))
14756 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
14758 (defun org-compute-property-at-point ()
14759 "Compute the property at point.
14760 This looks for an enclosing column format, extracts the operator and
14761 then applies it to the property in the column format's scope."
14762 (interactive)
14763 (unless (org-at-property-p)
14764 (error "Not at a property"))
14765 (let ((prop (org-match-string-no-properties 2)))
14766 (org-columns-get-format-and-top-level)
14767 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
14768 (error "No operator defined for property %s" prop))
14769 (org-columns-compute prop)))
14771 (defvar org-property-allowed-value-functions nil
14772 "Hook for functions supplying allowed values for a specific property.
14773 The functions must take a single argument, the name of the property, and
14774 return a flat list of allowed values. If \":ETC\" is one of
14775 the values, this means that these values are intended as defaults for
14776 completion, but that other values should be allowed too.
14777 The functions must return nil if they are not responsible for this
14778 property.")
14780 (defun org-property-get-allowed-values (pom property &optional table)
14781 "Get allowed values for the property PROPERTY.
14782 When TABLE is non-nil, return an alist that can directly be used for
14783 completion."
14784 (let (vals)
14785 (cond
14786 ((equal property "TODO")
14787 (setq vals (org-with-point-at pom
14788 (append org-todo-keywords-1 '("")))))
14789 ((equal property "PRIORITY")
14790 (let ((n org-lowest-priority))
14791 (while (>= n org-highest-priority)
14792 (push (char-to-string n) vals)
14793 (setq n (1- n)))))
14794 ((member property org-special-properties))
14795 ((setq vals (run-hook-with-args-until-success
14796 'org-property-allowed-value-functions property)))
14798 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
14799 (when (and vals (string-match "\\S-" vals))
14800 (setq vals (car (read-from-string (concat "(" vals ")"))))
14801 (setq vals (mapcar (lambda (x)
14802 (cond ((stringp x) x)
14803 ((numberp x) (number-to-string x))
14804 ((symbolp x) (symbol-name x))
14805 (t "???")))
14806 vals)))))
14807 (when (member ":ETC" vals)
14808 (setq vals (remove ":ETC" vals))
14809 (org-add-props (car vals) '(org-unrestricted t)))
14810 (if table (mapcar 'list vals) vals)))
14812 (defun org-property-previous-allowed-value (&optional previous)
14813 "Switch to the next allowed value for this property."
14814 (interactive)
14815 (org-property-next-allowed-value t))
14817 (defun org-property-next-allowed-value (&optional previous)
14818 "Switch to the next allowed value for this property."
14819 (interactive)
14820 (unless (org-at-property-p)
14821 (error "Not at a property"))
14822 (let* ((key (match-string 2))
14823 (value (match-string 3))
14824 (allowed (or (org-property-get-allowed-values (point) key)
14825 (and (member value '("[ ]" "[-]" "[X]"))
14826 '("[ ]" "[X]"))))
14827 nval)
14828 (unless allowed
14829 (error "Allowed values for this property have not been defined"))
14830 (if previous (setq allowed (reverse allowed)))
14831 (if (member value allowed)
14832 (setq nval (car (cdr (member value allowed)))))
14833 (setq nval (or nval (car allowed)))
14834 (if (equal nval value)
14835 (error "Only one allowed value for this property"))
14836 (org-at-property-p)
14837 (replace-match (concat " :" key ": " nval) t t)
14838 (org-indent-line-function)
14839 (beginning-of-line 1)
14840 (skip-chars-forward " \t")
14841 (run-hook-with-args 'org-property-changed-functions key nval)))
14843 (defun org-find-olp (path &optional this-buffer)
14844 "Return a marker pointing to the entry at outline path OLP.
14845 If anything goes wrong, throw an error.
14846 You can wrap this call to catch the error like this:
14848 (condition-case msg
14849 (org-mobile-locate-entry (match-string 4))
14850 (error (nth 1 msg)))
14852 The return value will then be either a string with the error message,
14853 or a marker if everything is OK.
14855 If THIS-BUFFER is set, the outline path does not contain a file,
14856 only headings."
14857 (let* ((file (if this-buffer buffer-file-name (pop path)))
14858 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
14859 (level 1)
14860 (lmin 1)
14861 (lmax 1)
14862 limit re end found pos heading cnt flevel)
14863 (unless buffer (error "File not found :%s" file))
14864 (with-current-buffer buffer
14865 (save-excursion
14866 (save-restriction
14867 (widen)
14868 (setq limit (point-max))
14869 (goto-char (point-min))
14870 (while (setq heading (pop path))
14871 (setq re (format org-complex-heading-regexp-format
14872 (regexp-quote heading)))
14873 (setq cnt 0 pos (point))
14874 (while (re-search-forward re end t)
14875 (setq level (- (match-end 1) (match-beginning 1)))
14876 (if (and (>= level lmin) (<= level lmax))
14877 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
14878 (when (= cnt 0) (error "Heading not found on level %d: %s"
14879 lmax heading))
14880 (when (> cnt 1) (error "Heading not unique on level %d: %s"
14881 lmax heading))
14882 (goto-char found)
14883 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
14884 (setq end (save-excursion (org-end-of-subtree t t))))
14885 (when (org-at-heading-p)
14886 (move-marker (make-marker) (point))))))))
14888 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
14889 "Find node HEADING in BUFFER.
14890 Return a marker to the heading if it was found, or nil if not.
14891 If POS-ONLY is set, return just the position instead of a marker.
14893 The heading text must match exact, but it may have a TODO keyword,
14894 a priority cookie and tags in the standard locations."
14895 (with-current-buffer (or buffer (current-buffer))
14896 (save-excursion
14897 (save-restriction
14898 (widen)
14899 (goto-char (point-min))
14900 (let (case-fold-search)
14901 (if (re-search-forward
14902 (format org-complex-heading-regexp-format
14903 (regexp-quote heading)) nil t)
14904 (if pos-only
14905 (match-beginning 0)
14906 (move-marker (make-marker) (match-beginning 0)))))))))
14908 (defun org-find-exact-heading-in-directory (heading &optional dir)
14909 "Find Org node headline HEADING in all .org files in directory DIR.
14910 When the target headline is found, return a marker to this location."
14911 (let ((files (directory-files (or dir default-directory)
14912 nil "\\`[^.#].*\\.org\\'"))
14913 file visiting m buffer)
14914 (catch 'found
14915 (while (setq file (pop files))
14916 (message "trying %s" file)
14917 (setq visiting (org-find-base-buffer-visiting file))
14918 (setq buffer (or visiting (find-file-noselect file)))
14919 (setq m (org-find-exact-headline-in-buffer
14920 heading buffer))
14921 (when (and (not m) (not visiting)) (kill-buffer buffer))
14922 (and m (throw 'found m))))))
14924 (defun org-find-entry-with-id (ident)
14925 "Locate the entry that contains the ID property with exact value IDENT.
14926 IDENT can be a string, a symbol or a number, this function will search for
14927 the string representation of it.
14928 Return the position where this entry starts, or nil if there is no such entry."
14929 (interactive "sID: ")
14930 (let ((id (cond
14931 ((stringp ident) ident)
14932 ((symbol-name ident) (symbol-name ident))
14933 ((numberp ident) (number-to-string ident))
14934 (t (error "IDENT %s must be a string, symbol or number" ident))))
14935 (case-fold-search nil))
14936 (save-excursion
14937 (save-restriction
14938 (widen)
14939 (goto-char (point-min))
14940 (when (re-search-forward
14941 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
14942 nil t)
14943 (org-back-to-heading t)
14944 (point))))))
14946 ;;;; Timestamps
14948 (defvar org-last-changed-timestamp nil)
14949 (defvar org-last-inserted-timestamp nil
14950 "The last time stamp inserted with `org-insert-time-stamp'.")
14951 (defvar org-time-was-given) ; dynamically scoped parameter
14952 (defvar org-end-time-was-given) ; dynamically scoped parameter
14953 (defvar org-ts-what) ; dynamically scoped parameter
14955 (defun org-time-stamp (arg &optional inactive)
14956 "Prompt for a date/time and insert a time stamp.
14957 If the user specifies a time like HH:MM, or if this command is called
14958 with a prefix argument, the time stamp will contain date and time.
14959 Otherwise, only the date will be included. All parts of a date not
14960 specified by the user will be filled in from the current date/time.
14961 So if you press just return without typing anything, the time stamp
14962 will represent the current date/time. If there is already a timestamp
14963 at the cursor, it will be modified."
14964 (interactive "P")
14965 (let* ((ts nil)
14966 (default-time
14967 ;; Default time is either today, or, when entering a range,
14968 ;; the range start.
14969 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
14970 (save-excursion
14971 (re-search-backward
14972 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
14973 (- (point) 20) t)))
14974 (apply 'encode-time (org-parse-time-string (match-string 1)))
14975 (current-time)))
14976 (default-input (and ts (org-get-compact-tod ts)))
14977 (repeater (save-excursion
14978 (save-match-data
14979 (beginning-of-line)
14980 (when (re-search-forward
14981 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
14982 (save-excursion (progn (end-of-line) (point))) t)
14983 (match-string 0)))))
14984 org-time-was-given org-end-time-was-given time)
14985 (cond
14986 ((and (org-at-timestamp-p t)
14987 (memq last-command '(org-time-stamp org-time-stamp-inactive))
14988 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
14989 (insert "--")
14990 (setq time (let ((this-command this-command))
14991 (org-read-date arg 'totime nil nil
14992 default-time default-input inactive)))
14993 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
14994 ((org-at-timestamp-p t)
14995 (setq time (let ((this-command this-command))
14996 (org-read-date arg 'totime nil nil default-time default-input inactive)))
14997 (when (org-at-timestamp-p t) ; just to get the match data
14998 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
14999 (replace-match "")
15000 (setq org-last-changed-timestamp
15001 (org-insert-time-stamp
15002 time (or org-time-was-given arg)
15003 inactive nil nil (list org-end-time-was-given)))
15004 (when repeater (goto-char (1- (point))) (insert " " repeater)
15005 (setq org-last-changed-timestamp
15006 (concat (substring org-last-inserted-timestamp 0 -1)
15007 " " repeater ">"))))
15008 (message "Timestamp updated"))
15010 (setq time (let ((this-command this-command))
15011 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15012 (org-insert-time-stamp time (or org-time-was-given arg) inactive
15013 nil nil (list org-end-time-was-given))))))
15015 ;; FIXME: can we use this for something else, like computing time differences?
15016 (defun org-get-compact-tod (s)
15017 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
15018 (let* ((t1 (match-string 1 s))
15019 (h1 (string-to-number (match-string 2 s)))
15020 (m1 (string-to-number (match-string 3 s)))
15021 (t2 (and (match-end 4) (match-string 5 s)))
15022 (h2 (and t2 (string-to-number (match-string 6 s))))
15023 (m2 (and t2 (string-to-number (match-string 7 s))))
15024 dh dm)
15025 (if (not t2)
15027 (setq dh (- h2 h1) dm (- m2 m1))
15028 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
15029 (concat t1 "+" (number-to-string dh)
15030 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
15032 (defun org-time-stamp-inactive (&optional arg)
15033 "Insert an inactive time stamp.
15034 An inactive time stamp is enclosed in square brackets instead of angle
15035 brackets. It is inactive in the sense that it does not trigger agenda entries,
15036 does not link to the calendar and cannot be changed with the S-cursor keys.
15037 So these are more for recording a certain time/date."
15038 (interactive "P")
15039 (org-time-stamp arg 'inactive))
15041 (defvar org-date-ovl (make-overlay 1 1))
15042 (overlay-put org-date-ovl 'face 'org-date-selected)
15043 (org-detach-overlay org-date-ovl)
15045 (defvar org-ans1) ; dynamically scoped parameter
15046 (defvar org-ans2) ; dynamically scoped parameter
15048 (defvar org-plain-time-of-day-regexp) ; defined below
15050 (defvar org-overriding-default-time nil) ; dynamically scoped
15051 (defvar org-read-date-overlay nil)
15052 (defvar org-dcst nil) ; dynamically scoped
15053 (defvar org-read-date-history nil)
15054 (defvar org-read-date-final-answer nil)
15055 (defvar org-read-date-analyze-futurep nil)
15056 (defvar org-read-date-analyze-forced-year nil)
15057 (defvar org-read-date-inactive)
15059 (defun org-read-date (&optional org-with-time to-time from-string prompt
15060 default-time default-input inactive)
15061 "Read a date, possibly a time, and make things smooth for the user.
15062 The prompt will suggest to enter an ISO date, but you can also enter anything
15063 which will at least partially be understood by `parse-time-string'.
15064 Unrecognized parts of the date will default to the current day, month, year,
15065 hour and minute. If this command is called to replace a timestamp at point,
15066 or to enter the second timestamp of a range, the default time is taken
15067 from the existing stamp. Furthermore, the command prefers the future,
15068 so if you are giving a date where the year is not given, and the day-month
15069 combination is already past in the current year, it will assume you
15070 mean next year. For details, see the manual. A few examples:
15072 3-2-5 --> 2003-02-05
15073 feb 15 --> currentyear-02-15
15074 2/15 --> currentyear-02-15
15075 sep 12 9 --> 2009-09-12
15076 12:45 --> today 12:45
15077 22 sept 0:34 --> currentyear-09-22 0:34
15078 12 --> currentyear-currentmonth-12
15079 Fri --> nearest Friday (today or later)
15080 etc.
15082 Furthermore you can specify a relative date by giving, as the *first* thing
15083 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
15084 change in days weeks, months, years.
15085 With a single plus or minus, the date is relative to today. With a double
15086 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
15087 +4d --> four days from today
15088 +4 --> same as above
15089 +2w --> two weeks from today
15090 ++5 --> five days from default date
15092 The function understands only English month and weekday abbreviations.
15094 While prompting, a calendar is popped up - you can also select the
15095 date with the mouse (button 1). The calendar shows a period of three
15096 months. To scroll it to other months, use the keys `>' and `<'.
15097 If you don't like the calendar, turn it off with
15098 \(setq org-read-date-popup-calendar nil)
15100 With optional argument TO-TIME, the date will immediately be converted
15101 to an internal time.
15102 With an optional argument WITH-TIME, the prompt will suggest to also
15103 insert a time. Note that when WITH-TIME is not set, you can still
15104 enter a time, and this function will inform the calling routine about
15105 this change. The calling routine may then choose to change the format
15106 used to insert the time stamp into the buffer to include the time.
15107 With optional argument FROM-STRING, read from this string instead from
15108 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
15109 the time/date that is used for everything that is not specified by the
15110 user."
15111 (require 'parse-time)
15112 (let* ((org-time-stamp-rounding-minutes
15113 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
15114 (org-dcst org-display-custom-times)
15115 (ct (org-current-time))
15116 (org-def (or org-overriding-default-time default-time ct))
15117 (org-defdecode (decode-time org-def))
15118 (dummy (progn
15119 (when (< (nth 2 org-defdecode) org-extend-today-until)
15120 (setcar (nthcdr 2 org-defdecode) -1)
15121 (setcar (nthcdr 1 org-defdecode) 59)
15122 (setq org-def (apply 'encode-time org-defdecode)
15123 org-defdecode (decode-time org-def)))))
15124 (calendar-frame-setup nil)
15125 (calendar-setup nil)
15126 (calendar-move-hook nil)
15127 (calendar-view-diary-initially-flag nil)
15128 (calendar-view-holidays-initially-flag nil)
15129 (timestr (format-time-string
15130 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
15131 (prompt (concat (if prompt (concat prompt " ") "")
15132 (format "Date+time [%s]: " timestr)))
15133 ans (org-ans0 "") org-ans1 org-ans2 final)
15135 (cond
15136 (from-string (setq ans from-string))
15137 (org-read-date-popup-calendar
15138 (save-excursion
15139 (save-window-excursion
15140 (calendar)
15141 (org-eval-in-calendar '(setq cursor-type nil) t)
15142 (unwind-protect
15143 (progn
15144 (calendar-forward-day (- (time-to-days org-def)
15145 (calendar-absolute-from-gregorian
15146 (calendar-current-date))))
15147 (org-eval-in-calendar nil t)
15148 (let* ((old-map (current-local-map))
15149 (map (copy-keymap calendar-mode-map))
15150 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
15151 (org-defkey map (kbd "RET") 'org-calendar-select)
15152 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
15153 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
15154 (org-defkey minibuffer-local-map [(meta shift left)]
15155 (lambda () (interactive)
15156 (org-eval-in-calendar '(calendar-backward-month 1))))
15157 (org-defkey minibuffer-local-map [(meta shift right)]
15158 (lambda () (interactive)
15159 (org-eval-in-calendar '(calendar-forward-month 1))))
15160 (org-defkey minibuffer-local-map [(meta shift up)]
15161 (lambda () (interactive)
15162 (org-eval-in-calendar '(calendar-backward-year 1))))
15163 (org-defkey minibuffer-local-map [(meta shift down)]
15164 (lambda () (interactive)
15165 (org-eval-in-calendar '(calendar-forward-year 1))))
15166 (org-defkey minibuffer-local-map [?\e (shift left)]
15167 (lambda () (interactive)
15168 (org-eval-in-calendar '(calendar-backward-month 1))))
15169 (org-defkey minibuffer-local-map [?\e (shift right)]
15170 (lambda () (interactive)
15171 (org-eval-in-calendar '(calendar-forward-month 1))))
15172 (org-defkey minibuffer-local-map [?\e (shift up)]
15173 (lambda () (interactive)
15174 (org-eval-in-calendar '(calendar-backward-year 1))))
15175 (org-defkey minibuffer-local-map [?\e (shift down)]
15176 (lambda () (interactive)
15177 (org-eval-in-calendar '(calendar-forward-year 1))))
15178 (org-defkey minibuffer-local-map [(shift up)]
15179 (lambda () (interactive)
15180 (org-eval-in-calendar '(calendar-backward-week 1))))
15181 (org-defkey minibuffer-local-map [(shift down)]
15182 (lambda () (interactive)
15183 (org-eval-in-calendar '(calendar-forward-week 1))))
15184 (org-defkey minibuffer-local-map [(shift left)]
15185 (lambda () (interactive)
15186 (org-eval-in-calendar '(calendar-backward-day 1))))
15187 (org-defkey minibuffer-local-map [(shift right)]
15188 (lambda () (interactive)
15189 (org-eval-in-calendar '(calendar-forward-day 1))))
15190 (org-defkey minibuffer-local-map ">"
15191 (lambda () (interactive)
15192 (org-eval-in-calendar '(scroll-calendar-left 1))))
15193 (org-defkey minibuffer-local-map "<"
15194 (lambda () (interactive)
15195 (org-eval-in-calendar '(scroll-calendar-right 1))))
15196 (org-defkey minibuffer-local-map "\C-v"
15197 (lambda () (interactive)
15198 (org-eval-in-calendar
15199 '(calendar-scroll-left-three-months 1))))
15200 (org-defkey minibuffer-local-map "\M-v"
15201 (lambda () (interactive)
15202 (org-eval-in-calendar
15203 '(calendar-scroll-right-three-months 1))))
15204 (run-hooks 'org-read-date-minibuffer-setup-hook)
15205 (unwind-protect
15206 (progn
15207 (use-local-map map)
15208 (setq org-read-date-inactive inactive)
15209 (add-hook 'post-command-hook 'org-read-date-display)
15210 (setq org-ans0 (read-string prompt default-input
15211 'org-read-date-history nil))
15212 ;; org-ans0: from prompt
15213 ;; org-ans1: from mouse click
15214 ;; org-ans2: from calendar motion
15215 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
15216 (remove-hook 'post-command-hook 'org-read-date-display)
15217 (use-local-map old-map)
15218 (when org-read-date-overlay
15219 (delete-overlay org-read-date-overlay)
15220 (setq org-read-date-overlay nil)))))
15221 (bury-buffer "*Calendar*")))))
15223 (t ; Naked prompt only
15224 (unwind-protect
15225 (setq ans (read-string prompt default-input
15226 'org-read-date-history timestr))
15227 (when org-read-date-overlay
15228 (delete-overlay org-read-date-overlay)
15229 (setq org-read-date-overlay nil)))))
15231 (setq final (org-read-date-analyze ans org-def org-defdecode))
15233 (when org-read-date-analyze-forced-year
15234 (message "Year was forced into %s"
15235 (if org-read-date-force-compatible-dates
15236 "compatible range (1970-2037)"
15237 "range representable on this machine"))
15238 (ding))
15240 ;; One round trip to get rid of 34th of August and stuff like that....
15241 (setq final (decode-time (apply 'encode-time final)))
15243 (setq org-read-date-final-answer ans)
15245 (if to-time
15246 (apply 'encode-time final)
15247 (if (and (boundp 'org-time-was-given) org-time-was-given)
15248 (format "%04d-%02d-%02d %02d:%02d"
15249 (nth 5 final) (nth 4 final) (nth 3 final)
15250 (nth 2 final) (nth 1 final))
15251 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
15253 (defvar org-def)
15254 (defvar org-defdecode)
15255 (defvar org-with-time)
15256 (defun org-read-date-display ()
15257 "Display the current date prompt interpretation in the minibuffer."
15258 (when org-read-date-display-live
15259 (when org-read-date-overlay
15260 (delete-overlay org-read-date-overlay))
15261 (when (minibufferp (current-buffer))
15262 (save-excursion
15263 (end-of-line 1)
15264 (while (not (equal (buffer-substring
15265 (max (point-min) (- (point) 4)) (point))
15266 " "))
15267 (insert " ")))
15268 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
15269 " " (or org-ans1 org-ans2)))
15270 (org-end-time-was-given nil)
15271 (f (org-read-date-analyze ans org-def org-defdecode))
15272 (fmts (if org-dcst
15273 org-time-stamp-custom-formats
15274 org-time-stamp-formats))
15275 (fmt (if (or org-with-time
15276 (and (boundp 'org-time-was-given) org-time-was-given))
15277 (cdr fmts)
15278 (car fmts)))
15279 (txt (format-time-string fmt (apply 'encode-time f)))
15280 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
15281 (txt (concat "=> " txt)))
15282 (when (and org-end-time-was-given
15283 (string-match org-plain-time-of-day-regexp txt))
15284 (setq txt (concat (substring txt 0 (match-end 0)) "-"
15285 org-end-time-was-given
15286 (substring txt (match-end 0)))))
15287 (when org-read-date-analyze-futurep
15288 (setq txt (concat txt " (=>F)")))
15289 (setq org-read-date-overlay
15290 (make-overlay (1- (point-at-eol)) (point-at-eol)))
15291 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
15293 (defun org-read-date-analyze (ans org-def org-defdecode)
15294 "Analyze the combined answer of the date prompt."
15295 ;; FIXME: cleanup and comment
15296 (let ((nowdecode (decode-time (current-time)))
15297 delta deltan deltaw deltadef year month day
15298 hour minute second wday pm h2 m2 tl wday1
15299 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
15300 (setq org-read-date-analyze-futurep nil
15301 org-read-date-analyze-forced-year nil)
15302 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
15303 (setq ans "+0"))
15305 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
15306 (setq ans (replace-match "" t t ans)
15307 deltan (car delta)
15308 deltaw (nth 1 delta)
15309 deltadef (nth 2 delta)))
15311 ;; Check if there is an iso week date in there
15312 ;; If yes, store the info and postpone interpreting it until the rest
15313 ;; of the parsing is done
15314 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
15315 (setq iso-year (if (match-end 1)
15316 (org-small-year-to-year
15317 (string-to-number (match-string 1 ans))))
15318 iso-weekday (if (match-end 3)
15319 (string-to-number (match-string 3 ans)))
15320 iso-week (string-to-number (match-string 2 ans)))
15321 (setq ans (replace-match "" t t ans)))
15323 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
15324 (when (string-match
15325 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
15326 (setq year (if (match-end 2)
15327 (string-to-number (match-string 2 ans))
15328 (progn (setq kill-year t)
15329 (string-to-number (format-time-string "%Y"))))
15330 month (string-to-number (match-string 3 ans))
15331 day (string-to-number (match-string 4 ans)))
15332 (if (< year 100) (setq year (+ 2000 year)))
15333 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15334 t nil ans)))
15336 ;; Help matching dotted european dates
15337 (when (string-match
15338 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\. ?\\([1-9][0-9][0-9][0-9]\\)?" ans)
15339 (setq year (if (match-end 3)
15340 (string-to-number (match-string 3 ans))
15341 (progn (setq kill-year t)
15342 (string-to-number (format-time-string "%Y"))))
15343 day (string-to-number (match-string 1 ans))
15344 month (string-to-number (match-string 2 ans))
15345 ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15346 t nil ans)))
15348 ;; Help matching american dates, like 5/30 or 5/30/7
15349 (when (string-match
15350 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
15351 (setq year (if (match-end 4)
15352 (string-to-number (match-string 4 ans))
15353 (progn (setq kill-year t)
15354 (string-to-number (format-time-string "%Y"))))
15355 month (string-to-number (match-string 1 ans))
15356 day (string-to-number (match-string 2 ans)))
15357 (if (< year 100) (setq year (+ 2000 year)))
15358 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15359 t nil ans)))
15360 ;; Help matching am/pm times, because `parse-time-string' does not do that.
15361 ;; If there is a time with am/pm, and *no* time without it, we convert
15362 ;; so that matching will be successful.
15363 (loop for i from 1 to 2 do ; twice, for end time as well
15364 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
15365 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
15366 (setq hour (string-to-number (match-string 1 ans))
15367 minute (if (match-end 3)
15368 (string-to-number (match-string 3 ans))
15370 pm (equal ?p
15371 (string-to-char (downcase (match-string 4 ans)))))
15372 (if (and (= hour 12) (not pm))
15373 (setq hour 0)
15374 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
15375 (setq ans (replace-match (format "%02d:%02d" hour minute)
15376 t t ans))))
15378 ;; Check if a time range is given as a duration
15379 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
15380 (setq hour (string-to-number (match-string 1 ans))
15381 h2 (+ hour (string-to-number (match-string 3 ans)))
15382 minute (string-to-number (match-string 2 ans))
15383 m2 (+ minute (if (match-end 5) (string-to-number
15384 (match-string 5 ans))0)))
15385 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
15386 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
15387 t t ans)))
15389 ;; Check if there is a time range
15390 (when (boundp 'org-end-time-was-given)
15391 (setq org-time-was-given nil)
15392 (when (and (string-match org-plain-time-of-day-regexp ans)
15393 (match-end 8))
15394 (setq org-end-time-was-given (match-string 8 ans))
15395 (setq ans (concat (substring ans 0 (match-beginning 7))
15396 (substring ans (match-end 7))))))
15398 (setq tl (parse-time-string ans)
15399 day (or (nth 3 tl) (nth 3 org-defdecode))
15400 month (or (nth 4 tl)
15401 (if (and org-read-date-prefer-future
15402 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
15403 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
15404 (nth 4 org-defdecode)))
15405 year (or (and (not kill-year) (nth 5 tl))
15406 (if (and org-read-date-prefer-future
15407 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
15408 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
15409 (nth 5 org-defdecode)))
15410 hour (or (nth 2 tl) (nth 2 org-defdecode))
15411 minute (or (nth 1 tl) (nth 1 org-defdecode))
15412 second (or (nth 0 tl) 0)
15413 wday (nth 6 tl))
15415 (when (and (eq org-read-date-prefer-future 'time)
15416 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
15417 (equal day (nth 3 nowdecode))
15418 (equal month (nth 4 nowdecode))
15419 (equal year (nth 5 nowdecode))
15420 (nth 2 tl)
15421 (or (< (nth 2 tl) (nth 2 nowdecode))
15422 (and (= (nth 2 tl) (nth 2 nowdecode))
15423 (nth 1 tl)
15424 (< (nth 1 tl) (nth 1 nowdecode)))))
15425 (setq day (1+ day)
15426 futurep t))
15428 ;; Special date definitions below
15429 (cond
15430 (iso-week
15431 ;; There was an iso week
15432 (require 'cal-iso)
15433 (setq futurep nil)
15434 (setq year (or iso-year year)
15435 day (or iso-weekday wday 1)
15436 wday nil ; to make sure that the trigger below does not match
15437 iso-date (calendar-gregorian-from-absolute
15438 (calendar-absolute-from-iso
15439 (list iso-week day year))))
15440 ; FIXME: Should we also push ISO weeks into the future?
15441 ; (when (and org-read-date-prefer-future
15442 ; (not iso-year)
15443 ; (< (calendar-absolute-from-gregorian iso-date)
15444 ; (time-to-days (current-time))))
15445 ; (setq year (1+ year)
15446 ; iso-date (calendar-gregorian-from-absolute
15447 ; (calendar-absolute-from-iso
15448 ; (list iso-week day year)))))
15449 (setq month (car iso-date)
15450 year (nth 2 iso-date)
15451 day (nth 1 iso-date)))
15452 (deltan
15453 (setq futurep nil)
15454 (unless deltadef
15455 (let ((now (decode-time (current-time))))
15456 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
15457 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
15458 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
15459 ((equal deltaw "m") (setq month (+ month deltan)))
15460 ((equal deltaw "y") (setq year (+ year deltan)))))
15461 ((and wday (not (nth 3 tl)))
15462 (setq futurep nil)
15463 ;; Weekday was given, but no day, so pick that day in the week
15464 ;; on or after the derived date.
15465 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
15466 (unless (equal wday wday1)
15467 (setq day (+ day (% (- wday wday1 -7) 7))))))
15468 (if (and (boundp 'org-time-was-given)
15469 (nth 2 tl))
15470 (setq org-time-was-given t))
15471 (if (< year 100) (setq year (+ 2000 year)))
15472 ;; Check of the date is representable
15473 (if org-read-date-force-compatible-dates
15474 (progn
15475 (if (< year 1970)
15476 (setq year 1970 org-read-date-analyze-forced-year t))
15477 (if (> year 2037)
15478 (setq year 2037 org-read-date-analyze-forced-year t)))
15479 (condition-case nil
15480 (ignore (encode-time second minute hour day month year))
15481 (error
15482 (setq year (nth 5 org-defdecode))
15483 (setq org-read-date-analyze-forced-year t))))
15484 (setq org-read-date-analyze-futurep futurep)
15485 (list second minute hour day month year)))
15487 (defvar parse-time-weekdays)
15488 (defun org-read-date-get-relative (s today default)
15489 "Check string S for special relative date string.
15490 TODAY and DEFAULT are internal times, for today and for a default.
15491 Return shift list (N what def-flag)
15492 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
15493 N is the number of WHATs to shift.
15494 DEF-FLAG is t when a double ++ or -- indicates shift relative to
15495 the DEFAULT date rather than TODAY."
15496 (require 'parse-time)
15497 (when (and
15498 (string-match
15499 (concat
15500 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
15501 "\\([0-9]+\\)?"
15502 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
15503 "\\([ \t]\\|$\\)") s)
15504 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
15505 (let* ((dir (if (> (match-end 1) (match-beginning 1))
15506 (string-to-char (substring (match-string 1 s) -1))
15507 ?+))
15508 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
15509 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
15510 (what (if (match-end 3) (match-string 3 s) "d"))
15511 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
15512 (date (if rel default today))
15513 (wday (nth 6 (decode-time date)))
15514 delta)
15515 (if wday1
15516 (progn
15517 (setq delta (mod (+ 7 (- wday1 wday)) 7))
15518 (if (= dir ?-) (setq delta (- delta 7)))
15519 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
15520 (list delta "d" rel))
15521 (list (* n (if (= dir ?-) -1 1)) what rel)))))
15523 (defun org-order-calendar-date-args (arg1 arg2 arg3)
15524 "Turn a user-specified date into the internal representation.
15525 The internal representation needed by the calendar is (month day year).
15526 This is a wrapper to handle the brain-dead convention in calendar that
15527 user function argument order change dependent on argument order."
15528 (if (boundp 'calendar-date-style)
15529 (cond
15530 ((eq calendar-date-style 'american)
15531 (list arg1 arg2 arg3))
15532 ((eq calendar-date-style 'european)
15533 (list arg2 arg1 arg3))
15534 ((eq calendar-date-style 'iso)
15535 (list arg2 arg3 arg1)))
15536 (with-no-warnings ;; european-calendar-style is obsolete as of version 23.1
15537 (if (org-bound-and-true-p european-calendar-style)
15538 (list arg2 arg1 arg3)
15539 (list arg1 arg2 arg3)))))
15541 (defun org-eval-in-calendar (form &optional keepdate)
15542 "Eval FORM in the calendar window and return to current window.
15543 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
15544 otherwise stick to the current value of `org-ans2'."
15545 (let ((sf (selected-frame))
15546 (sw (selected-window)))
15547 (select-window (get-buffer-window "*Calendar*" t))
15548 (eval form)
15549 (when (and (not keepdate) (calendar-cursor-to-date))
15550 (let* ((date (calendar-cursor-to-date))
15551 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15552 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
15553 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
15554 (select-window sw)
15555 (org-select-frame-set-input-focus sf)))
15557 (defun org-calendar-select ()
15558 "Return to `org-read-date' with the date currently selected.
15559 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15560 (interactive)
15561 (when (calendar-cursor-to-date)
15562 (let* ((date (calendar-cursor-to-date))
15563 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15564 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15565 (if (active-minibuffer-window) (exit-minibuffer))))
15567 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
15568 "Insert a date stamp for the date given by the internal TIME.
15569 WITH-HM means use the stamp format that includes the time of the day.
15570 INACTIVE means use square brackets instead of angular ones, so that the
15571 stamp will not contribute to the agenda.
15572 PRE and POST are optional strings to be inserted before and after the
15573 stamp.
15574 The command returns the inserted time stamp."
15575 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
15576 stamp)
15577 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
15578 (insert-before-markers (or pre ""))
15579 (when (listp extra)
15580 (setq extra (car extra))
15581 (if (and (stringp extra)
15582 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
15583 (setq extra (format "-%02d:%02d"
15584 (string-to-number (match-string 1 extra))
15585 (string-to-number (match-string 2 extra))))
15586 (setq extra nil)))
15587 (when extra
15588 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
15589 (insert-before-markers (setq stamp (format-time-string fmt time)))
15590 (insert-before-markers (or post ""))
15591 (setq org-last-inserted-timestamp stamp)))
15593 (defun org-toggle-time-stamp-overlays ()
15594 "Toggle the use of custom time stamp formats."
15595 (interactive)
15596 (setq org-display-custom-times (not org-display-custom-times))
15597 (unless org-display-custom-times
15598 (let ((p (point-min)) (bmp (buffer-modified-p)))
15599 (while (setq p (next-single-property-change p 'display))
15600 (if (and (get-text-property p 'display)
15601 (eq (get-text-property p 'face) 'org-date))
15602 (remove-text-properties
15603 p (setq p (next-single-property-change p 'display))
15604 '(display t))))
15605 (set-buffer-modified-p bmp)))
15606 (if (featurep 'xemacs)
15607 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
15608 (org-restart-font-lock)
15609 (setq org-table-may-need-update t)
15610 (if org-display-custom-times
15611 (message "Time stamps are overlaid with custom format")
15612 (message "Time stamp overlays removed")))
15614 (defun org-display-custom-time (beg end)
15615 "Overlay modified time stamp format over timestamp between BEG and END."
15616 (let* ((ts (buffer-substring beg end))
15617 t1 w1 with-hm tf time str w2 (off 0))
15618 (save-match-data
15619 (setq t1 (org-parse-time-string ts t))
15620 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
15621 (setq off (- (match-end 0) (match-beginning 0)))))
15622 (setq end (- end off))
15623 (setq w1 (- end beg)
15624 with-hm (and (nth 1 t1) (nth 2 t1))
15625 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
15626 time (org-fix-decoded-time t1)
15627 str (org-add-props
15628 (format-time-string
15629 (substring tf 1 -1) (apply 'encode-time time))
15630 nil 'mouse-face 'highlight)
15631 w2 (length str))
15632 (if (not (= w2 w1))
15633 (add-text-properties (1+ beg) (+ 2 beg)
15634 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
15635 (if (featurep 'xemacs)
15636 (progn
15637 (put-text-property beg end 'invisible t)
15638 (put-text-property beg end 'end-glyph (make-glyph str)))
15639 (put-text-property beg end 'display str))))
15641 (defun org-translate-time (string)
15642 "Translate all timestamps in STRING to custom format.
15643 But do this only if the variable `org-display-custom-times' is set."
15644 (when org-display-custom-times
15645 (save-match-data
15646 (let* ((start 0)
15647 (re org-ts-regexp-both)
15648 t1 with-hm inactive tf time str beg end)
15649 (while (setq start (string-match re string start))
15650 (setq beg (match-beginning 0)
15651 end (match-end 0)
15652 t1 (save-match-data
15653 (org-parse-time-string (substring string beg end) t))
15654 with-hm (and (nth 1 t1) (nth 2 t1))
15655 inactive (equal (substring string beg (1+ beg)) "[")
15656 tf (funcall (if with-hm 'cdr 'car)
15657 org-time-stamp-custom-formats)
15658 time (org-fix-decoded-time t1)
15659 str (format-time-string
15660 (concat
15661 (if inactive "[" "<") (substring tf 1 -1)
15662 (if inactive "]" ">"))
15663 (apply 'encode-time time))
15664 string (replace-match str t t string)
15665 start (+ start (length str)))))))
15666 string)
15668 (defun org-fix-decoded-time (time)
15669 "Set 0 instead of nil for the first 6 elements of time.
15670 Don't touch the rest."
15671 (let ((n 0))
15672 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
15674 (defun org-days-to-time (timestamp-string)
15675 "Difference between TIMESTAMP-STRING and now in days."
15676 (- (time-to-days (org-time-string-to-time timestamp-string))
15677 (time-to-days (current-time))))
15679 (defun org-deadline-close (timestamp-string &optional ndays)
15680 "Is the time in TIMESTAMP-STRING close to the current date?"
15681 (setq ndays (or ndays (org-get-wdays timestamp-string)))
15682 (and (< (org-days-to-time timestamp-string) ndays)
15683 (not (org-entry-is-done-p))))
15685 (defun org-get-wdays (ts)
15686 "Get the deadline lead time appropriate for timestring TS."
15687 (cond
15688 ((<= org-deadline-warning-days 0)
15689 ;; 0 or negative, enforce this value no matter what
15690 (- org-deadline-warning-days))
15691 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
15692 ;; lead time is specified.
15693 (floor (* (string-to-number (match-string 1 ts))
15694 (cdr (assoc (match-string 2 ts)
15695 '(("d" . 1) ("w" . 7)
15696 ("m" . 30.4) ("y" . 365.25)))))))
15697 ;; go for the default.
15698 (t org-deadline-warning-days)))
15700 (defun org-calendar-select-mouse (ev)
15701 "Return to `org-read-date' with the date currently selected.
15702 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15703 (interactive "e")
15704 (mouse-set-point ev)
15705 (when (calendar-cursor-to-date)
15706 (let* ((date (calendar-cursor-to-date))
15707 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15708 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15709 (if (active-minibuffer-window) (exit-minibuffer))))
15711 (defun org-check-deadlines (ndays)
15712 "Check if there are any deadlines due or past due.
15713 A deadline is considered due if it happens within `org-deadline-warning-days'
15714 days from today's date. If the deadline appears in an entry marked DONE,
15715 it is not shown. The prefix arg NDAYS can be used to test that many
15716 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
15717 (interactive "P")
15718 (let* ((org-warn-days
15719 (cond
15720 ((equal ndays '(4)) 100000)
15721 (ndays (prefix-numeric-value ndays))
15722 (t (abs org-deadline-warning-days))))
15723 (case-fold-search nil)
15724 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
15725 (callback
15726 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
15728 (message "%d deadlines past-due or due within %d days"
15729 (org-occur regexp nil callback)
15730 org-warn-days)))
15732 (defun org-check-before-date (date)
15733 "Check if there are deadlines or scheduled entries before DATE."
15734 (interactive (list (org-read-date)))
15735 (let ((case-fold-search nil)
15736 (regexp (concat "\\<\\(" org-deadline-string
15737 "\\|" org-scheduled-string
15738 "\\) *<\\([^>]+\\)>"))
15739 (callback
15740 (lambda () (time-less-p
15741 (org-time-string-to-time (match-string 2))
15742 (org-time-string-to-time date)))))
15743 (message "%d entries before %s"
15744 (org-occur regexp nil callback) date)))
15746 (defun org-check-after-date (date)
15747 "Check if there are deadlines or scheduled entries after DATE."
15748 (interactive (list (org-read-date)))
15749 (let ((case-fold-search nil)
15750 (regexp (concat "\\<\\(" org-deadline-string
15751 "\\|" org-scheduled-string
15752 "\\) *<\\([^>]+\\)>"))
15753 (callback
15754 (lambda () (not
15755 (time-less-p
15756 (org-time-string-to-time (match-string 2))
15757 (org-time-string-to-time date))))))
15758 (message "%d entries after %s"
15759 (org-occur regexp nil callback) date)))
15761 (defun org-check-dates-range (start-date end-date)
15762 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
15763 (interactive (list (org-read-date nil nil nil "Range starts")
15764 (org-read-date nil nil nil "Range end")))
15765 (let ((case-fold-search nil)
15766 (regexp (concat "\\<\\(" org-deadline-string
15767 "\\|" org-scheduled-string
15768 "\\) *<\\([^>]+\\)>"))
15769 (callback
15770 (lambda ()
15771 (let ((match (match-string 2)))
15772 (and
15773 (not (time-less-p
15774 (org-time-string-to-time match)
15775 (org-time-string-to-time start-date)))
15776 (time-less-p
15777 (org-time-string-to-time match)
15778 (org-time-string-to-time end-date)))))))
15779 (message "%d entries between %s and %s"
15780 (org-occur regexp nil callback) start-date end-date)))
15782 (defun org-evaluate-time-range (&optional to-buffer)
15783 "Evaluate a time range by computing the difference between start and end.
15784 Normally the result is just printed in the echo area, but with prefix arg
15785 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
15786 If the time range is actually in a table, the result is inserted into the
15787 next column.
15788 For time difference computation, a year is assumed to be exactly 365
15789 days in order to avoid rounding problems."
15790 (interactive "P")
15792 (org-clock-update-time-maybe)
15793 (save-excursion
15794 (unless (org-at-date-range-p t)
15795 (goto-char (point-at-bol))
15796 (re-search-forward org-tr-regexp-both (point-at-eol) t))
15797 (if (not (org-at-date-range-p t))
15798 (error "Not at a time-stamp range, and none found in current line")))
15799 (let* ((ts1 (match-string 1))
15800 (ts2 (match-string 2))
15801 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
15802 (match-end (match-end 0))
15803 (time1 (org-time-string-to-time ts1))
15804 (time2 (org-time-string-to-time ts2))
15805 (t1 (org-float-time time1))
15806 (t2 (org-float-time time2))
15807 (diff (abs (- t2 t1)))
15808 (negative (< (- t2 t1) 0))
15809 ;; (ys (floor (* 365 24 60 60)))
15810 (ds (* 24 60 60))
15811 (hs (* 60 60))
15812 (fy "%dy %dd %02d:%02d")
15813 (fy1 "%dy %dd")
15814 (fd "%dd %02d:%02d")
15815 (fd1 "%dd")
15816 (fh "%02d:%02d")
15817 y d h m align)
15818 (if havetime
15819 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
15821 d (floor (/ diff ds)) diff (mod diff ds)
15822 h (floor (/ diff hs)) diff (mod diff hs)
15823 m (floor (/ diff 60)))
15824 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
15826 d (floor (+ (/ diff ds) 0.5))
15827 h 0 m 0))
15828 (if (not to-buffer)
15829 (message "%s" (org-make-tdiff-string y d h m))
15830 (if (org-at-table-p)
15831 (progn
15832 (goto-char match-end)
15833 (setq align t)
15834 (and (looking-at " *|") (goto-char (match-end 0))))
15835 (goto-char match-end))
15836 (if (looking-at
15837 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
15838 (replace-match ""))
15839 (if negative (insert " -"))
15840 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
15841 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
15842 (insert " " (format fh h m))))
15843 (if align (org-table-align))
15844 (message "Time difference inserted")))))
15846 (defun org-make-tdiff-string (y d h m)
15847 (let ((fmt "")
15848 (l nil))
15849 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
15850 l (push y l)))
15851 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
15852 l (push d l)))
15853 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
15854 l (push h l)))
15855 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
15856 l (push m l)))
15857 (apply 'format fmt (nreverse l))))
15859 (defun org-time-string-to-time (s &optional buffer pos)
15860 (condition-case errdata
15861 (apply 'encode-time (org-parse-time-string s))
15862 (error (error "Bad timestamp `%s'%s\nError was: %s"
15863 s (if (not (and buffer pos))
15865 (format " at %d in buffer `%s'" pos buffer))
15866 (cdr errdata)))))
15868 (defun org-time-string-to-seconds (s)
15869 (org-float-time (org-time-string-to-time s)))
15871 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
15872 "Convert a time stamp to an absolute day number.
15873 If there is a specifier for a cyclic time stamp, get the closest date to
15874 DAYNR.
15875 PREFER and SHOW-ALL are passed through to `org-closest-date'.
15876 The variable date is bound by the calendar when this is called."
15877 (cond
15878 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
15879 (if (org-diary-sexp-entry (match-string 1 s) "" date)
15880 daynr
15881 (+ daynr 1000)))
15882 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
15883 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
15884 (time-to-days (current-time))) (match-string 0 s)
15885 prefer show-all))
15886 (t (time-to-days
15887 (condition-case errdata
15888 (apply 'encode-time (org-parse-time-string s))
15889 (error (error "Bad timestamp `%s'%s\nError was: %s"
15890 s (if (not (and buffer pos))
15892 (format " at %d in buffer `%s'" pos buffer))
15893 (cdr errdata))))))))
15895 (defun org-days-to-iso-week (days)
15896 "Return the iso week number."
15897 (require 'cal-iso)
15898 (car (calendar-iso-from-absolute days)))
15900 (defun org-small-year-to-year (year)
15901 "Convert 2-digit years into 4-digit years.
15902 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
15903 The year 2000 cannot be abbreviated. Any year larger than 99
15904 is returned unchanged."
15905 (if (< year 38)
15906 (setq year (+ 2000 year))
15907 (if (< year 100)
15908 (setq year (+ 1900 year))))
15909 year)
15911 (defun org-time-from-absolute (d)
15912 "Return the time corresponding to date D.
15913 D may be an absolute day number, or a calendar-type list (month day year)."
15914 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
15915 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
15917 (defun org-calendar-holiday ()
15918 "List of holidays, for Diary display in Org-mode."
15919 (require 'holidays)
15920 (let ((hl (funcall
15921 (if (fboundp 'calendar-check-holidays)
15922 'calendar-check-holidays 'check-calendar-holidays) date)))
15923 (if hl (mapconcat 'identity hl "; "))))
15925 (defun org-diary-sexp-entry (sexp entry date)
15926 "Process a SEXP diary ENTRY for DATE."
15927 (require 'diary-lib)
15928 (let ((result (if calendar-debug-sexp
15929 (let ((stack-trace-on-error t))
15930 (eval (car (read-from-string sexp))))
15931 (condition-case nil
15932 (eval (car (read-from-string sexp)))
15933 (error
15934 (beep)
15935 (message "Bad sexp at line %d in %s: %s"
15936 (org-current-line)
15937 (buffer-file-name) sexp)
15938 (sleep-for 2))))))
15939 (cond ((stringp result) (split-string result "; "))
15940 ((and (consp result)
15941 (not (consp (cdr result)))
15942 (stringp (cdr result))) (cdr result))
15943 ((and (consp result)
15944 (stringp (car result))) result)
15945 (result entry)
15946 (t nil))))
15948 (defun org-diary-to-ical-string (frombuf)
15949 "Get iCalendar entries from diary entries in buffer FROMBUF.
15950 This uses the icalendar.el library."
15951 (let* ((tmpdir (if (featurep 'xemacs)
15952 (temp-directory)
15953 temporary-file-directory))
15954 (tmpfile (make-temp-name
15955 (expand-file-name "orgics" tmpdir)))
15956 buf rtn b e)
15957 (with-current-buffer frombuf
15958 (icalendar-export-region (point-min) (point-max) tmpfile)
15959 (setq buf (find-buffer-visiting tmpfile))
15960 (set-buffer buf)
15961 (goto-char (point-min))
15962 (if (re-search-forward "^BEGIN:VEVENT" nil t)
15963 (setq b (match-beginning 0)))
15964 (goto-char (point-max))
15965 (if (re-search-backward "^END:VEVENT" nil t)
15966 (setq e (match-end 0)))
15967 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
15968 (kill-buffer buf)
15969 (delete-file tmpfile)
15970 rtn))
15972 (defun org-closest-date (start current change prefer show-all)
15973 "Find the date closest to CURRENT that is consistent with START and CHANGE.
15974 When PREFER is `past', return a date that is either CURRENT or past.
15975 When PREFER is `future', return a date that is either CURRENT or future.
15976 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
15977 ;; Make the proper lists from the dates
15978 (catch 'exit
15979 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
15980 dn dw sday cday n1 n2 n0
15981 d m y y1 y2 date1 date2 nmonths nm ny m2)
15983 (setq start (org-date-to-gregorian start)
15984 current (org-date-to-gregorian
15985 (if show-all
15986 current
15987 (time-to-days (current-time))))
15988 sday (calendar-absolute-from-gregorian start)
15989 cday (calendar-absolute-from-gregorian current))
15991 (if (<= cday sday) (throw 'exit sday))
15993 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
15994 (setq dn (string-to-number (match-string 1 change))
15995 dw (cdr (assoc (match-string 2 change) a1)))
15996 (error "Invalid change specifier: %s" change))
15997 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
15998 (cond
15999 ((eq dw 'day)
16000 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
16001 n2 (+ n1 dn)))
16002 ((eq dw 'year)
16003 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
16004 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
16005 (setq date1 (list m d y1)
16006 n1 (calendar-absolute-from-gregorian date1)
16007 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
16008 n2 (calendar-absolute-from-gregorian date2)))
16009 ((eq dw 'month)
16010 ;; approx number of month between the two dates
16011 (setq nmonths (floor (/ (- cday sday) 30.436875)))
16012 ;; How often does dn fit in there?
16013 (setq d (nth 1 start) m (car start) y (nth 2 start)
16014 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
16015 m (+ m nm)
16016 ny (floor (/ m 12))
16017 y (+ y ny)
16018 m (- m (* ny 12)))
16019 (while (> m 12) (setq m (- m 12) y (1+ y)))
16020 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
16021 (setq m2 (+ m dn) y2 y)
16022 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16023 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
16024 (while (<= n2 cday)
16025 (setq n1 n2 m m2 y y2)
16026 (setq m2 (+ m dn) y2 y)
16027 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16028 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
16029 ;; Make sure n1 is the earlier date
16030 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
16031 (if show-all
16032 (cond
16033 ((eq prefer 'past) (if (= cday n2) n2 n1))
16034 ((eq prefer 'future) (if (= cday n1) n1 n2))
16035 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
16036 (cond
16037 ((eq prefer 'past) (if (= cday n2) n2 n1))
16038 ((eq prefer 'future) (if (= cday n1) n1 n2))
16039 (t (if (= cday n1) n1 n2)))))))
16041 (defun org-date-to-gregorian (date)
16042 "Turn any specification of DATE into a Gregorian date for the calendar."
16043 (cond ((integerp date) (calendar-gregorian-from-absolute date))
16044 ((and (listp date) (= (length date) 3)) date)
16045 ((stringp date)
16046 (setq date (org-parse-time-string date))
16047 (list (nth 4 date) (nth 3 date) (nth 5 date)))
16048 ((listp date)
16049 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
16051 (defun org-parse-time-string (s &optional nodefault)
16052 "Parse the standard Org-mode time string.
16053 This should be a lot faster than the normal `parse-time-string'.
16054 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
16055 hour and minute fields will be nil if not given."
16056 (if (string-match org-ts-regexp0 s)
16057 (list 0
16058 (if (or (match-beginning 8) (not nodefault))
16059 (string-to-number (or (match-string 8 s) "0")))
16060 (if (or (match-beginning 7) (not nodefault))
16061 (string-to-number (or (match-string 7 s) "0")))
16062 (string-to-number (match-string 4 s))
16063 (string-to-number (match-string 3 s))
16064 (string-to-number (match-string 2 s))
16065 nil nil nil)
16066 (error "Not a standard Org-mode time string: %s" s)))
16068 (defun org-timestamp-up (&optional arg)
16069 "Increase the date item at the cursor by one.
16070 If the cursor is on the year, change the year. If it is on the month,
16071 the day or the time, change that.
16072 With prefix ARG, change by that many units."
16073 (interactive "p")
16074 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
16076 (defun org-timestamp-down (&optional arg)
16077 "Decrease the date item at the cursor by one.
16078 If the cursor is on the year, change the year. If it is on the month,
16079 the day or the time, change that.
16080 With prefix ARG, change by that many units."
16081 (interactive "p")
16082 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
16084 (defun org-timestamp-up-day (&optional arg)
16085 "Increase the date in the time stamp by one day.
16086 With prefix ARG, change that many days."
16087 (interactive "p")
16088 (if (and (not (org-at-timestamp-p t))
16089 (org-at-heading-p))
16090 (org-todo 'up)
16091 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
16093 (defun org-timestamp-down-day (&optional arg)
16094 "Decrease the date in the time stamp by one day.
16095 With prefix ARG, change that many days."
16096 (interactive "p")
16097 (if (and (not (org-at-timestamp-p t))
16098 (org-at-heading-p))
16099 (org-todo 'down)
16100 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
16102 (defun org-at-timestamp-p (&optional inactive-ok)
16103 "Determine if the cursor is in or at a timestamp."
16104 (interactive)
16105 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
16106 (pos (point))
16107 (ans (or (looking-at tsr)
16108 (save-excursion
16109 (skip-chars-backward "^[<\n\r\t")
16110 (if (> (point) (point-min)) (backward-char 1))
16111 (and (looking-at tsr)
16112 (> (- (match-end 0) pos) -1))))))
16113 (and ans
16114 (boundp 'org-ts-what)
16115 (setq org-ts-what
16116 (cond
16117 ((= pos (match-beginning 0)) 'bracket)
16118 ;; Point is considered to be "on the bracket" whether
16119 ;; it's really on it or right after it.
16120 ((or (= pos (1- (match-end 0)))
16121 (= pos (match-end 0))) 'bracket)
16122 ((org-pos-in-match-range pos 2) 'year)
16123 ((org-pos-in-match-range pos 3) 'month)
16124 ((org-pos-in-match-range pos 7) 'hour)
16125 ((org-pos-in-match-range pos 8) 'minute)
16126 ((or (org-pos-in-match-range pos 4)
16127 (org-pos-in-match-range pos 5)) 'day)
16128 ((and (> pos (or (match-end 8) (match-end 5)))
16129 (< pos (match-end 0)))
16130 (- pos (or (match-end 8) (match-end 5))))
16131 (t 'day))))
16132 ans))
16134 (defun org-toggle-timestamp-type ()
16135 "Toggle the type (<active> or [inactive]) of a time stamp."
16136 (interactive)
16137 (when (org-at-timestamp-p t)
16138 (let ((beg (match-beginning 0)) (end (match-end 0))
16139 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
16140 (save-excursion
16141 (goto-char beg)
16142 (while (re-search-forward "[][<>]" end t)
16143 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
16144 t t)))
16145 (message "Timestamp is now %sactive"
16146 (if (equal (char-after beg) ?<) "" "in")))))
16148 (defun org-timestamp-change (n &optional what updown)
16149 "Change the date in the time stamp at point.
16150 The date will be changed by N times WHAT. WHAT can be `day', `month',
16151 `year', `minute', `second'. If WHAT is not given, the cursor position
16152 in the timestamp determines what will be changed."
16153 (let ((origin (point)) origin-cat
16154 with-hm inactive
16155 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
16156 org-ts-what
16157 extra rem
16158 ts time time0)
16159 (if (not (org-at-timestamp-p t))
16160 (error "Not at a timestamp"))
16161 (if (and (not what) (eq org-ts-what 'bracket))
16162 (org-toggle-timestamp-type)
16163 ;; Point isn't on brackets. Remember the part of the time-stamp
16164 ;; the point was in. Indeed, size of time-stamps may change,
16165 ;; but point must be kept in the same category nonetheless.
16166 (setq origin-cat org-ts-what)
16167 (if (and (not what) (not (eq org-ts-what 'day))
16168 org-display-custom-times
16169 (get-text-property (point) 'display)
16170 (not (get-text-property (1- (point)) 'display)))
16171 (setq org-ts-what 'day))
16172 (setq org-ts-what (or what org-ts-what)
16173 inactive (= (char-after (match-beginning 0)) ?\[)
16174 ts (match-string 0))
16175 (replace-match "")
16176 (if (string-match
16177 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
16179 (setq extra (match-string 1 ts)))
16180 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
16181 (setq with-hm t))
16182 (setq time0 (org-parse-time-string ts))
16183 (when (and updown
16184 (eq org-ts-what 'minute)
16185 (not current-prefix-arg))
16186 ;; This looks like s-up and s-down. Change by one rounding step.
16187 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
16188 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
16189 (setcar (cdr time0) (+ (nth 1 time0)
16190 (if (> n 0) (- rem) (- dm rem))))))
16191 (setq time
16192 (encode-time (or (car time0) 0)
16193 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
16194 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
16195 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
16196 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
16197 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
16198 (nthcdr 6 time0)))
16199 (when (and (member org-ts-what '(hour minute))
16200 extra
16201 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
16202 (setq extra (org-modify-ts-extra
16203 extra
16204 (if (eq org-ts-what 'hour) 2 5)
16205 n dm)))
16206 (when (integerp org-ts-what)
16207 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
16208 (if (eq what 'calendar)
16209 (let ((cal-date (org-get-date-from-calendar)))
16210 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
16211 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
16212 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
16213 (setcar time0 (or (car time0) 0))
16214 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
16215 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
16216 (setq time (apply 'encode-time time0))))
16217 ;; Insert the new time-stamp, and ensure point stays in the same
16218 ;; category as before (i.e. not after the last position in that
16219 ;; category).
16220 (let ((pos (point)))
16221 ;; Stay before inserted string. `save-excursion' is of no use.
16222 (setq org-last-changed-timestamp
16223 (org-insert-time-stamp time with-hm inactive nil nil extra))
16224 (goto-char pos))
16225 (save-match-data
16226 (looking-at org-ts-regexp3)
16227 (goto-char (cond
16228 ;; `day' category ends before `hour' if any, or at
16229 ;; the end of the day name.
16230 ((eq origin-cat 'day)
16231 (min (or (match-beginning 7) (1- (match-end 5))) origin))
16232 ((eq origin-cat 'hour) (min (match-end 7) origin))
16233 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
16234 ((integerp origin-cat) (min (1- (match-end 0)) origin))
16235 ;; `year' and `month' have both fixed size: point
16236 ;; couldn't have moved into another part.
16237 (t origin))))
16238 ;; Update clock if on a CLOCK line.
16239 (org-clock-update-time-maybe)
16240 ;; Try to recenter the calendar window, if any.
16241 (if (and org-calendar-follow-timestamp-change
16242 (get-buffer-window "*Calendar*" t)
16243 (memq org-ts-what '(day month year)))
16244 (org-recenter-calendar (time-to-days time))))))
16246 (defun org-modify-ts-extra (s pos n dm)
16247 "Change the different parts of the lead-time and repeat fields in timestamp."
16248 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
16249 ng h m new rem)
16250 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
16251 (cond
16252 ((or (org-pos-in-match-range pos 2)
16253 (org-pos-in-match-range pos 3))
16254 (setq m (string-to-number (match-string 3 s))
16255 h (string-to-number (match-string 2 s)))
16256 (if (org-pos-in-match-range pos 2)
16257 (setq h (+ h n))
16258 (setq n (* dm (org-no-warnings (signum n))))
16259 (when (not (= 0 (setq rem (% m dm))))
16260 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
16261 (setq m (+ m n)))
16262 (if (< m 0) (setq m (+ m 60) h (1- h)))
16263 (if (> m 59) (setq m (- m 60) h (1+ h)))
16264 (setq h (min 24 (max 0 h)))
16265 (setq ng 1 new (format "-%02d:%02d" h m)))
16266 ((org-pos-in-match-range pos 6)
16267 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
16268 ((org-pos-in-match-range pos 5)
16269 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
16271 ((org-pos-in-match-range pos 9)
16272 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
16273 ((org-pos-in-match-range pos 8)
16274 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
16276 (when ng
16277 (setq s (concat
16278 (substring s 0 (match-beginning ng))
16280 (substring s (match-end ng))))))
16283 (defun org-recenter-calendar (date)
16284 "If the calendar is visible, recenter it to DATE."
16285 (let ((cwin (get-buffer-window "*Calendar*" t)))
16286 (when cwin
16287 (let ((calendar-move-hook nil))
16288 (with-selected-window cwin
16289 (calendar-goto-date (if (listp date) date
16290 (calendar-gregorian-from-absolute date))))))))
16292 (defun org-goto-calendar (&optional arg)
16293 "Go to the Emacs calendar at the current date.
16294 If there is a time stamp in the current line, go to that date.
16295 A prefix ARG can be used to force the current date."
16296 (interactive "P")
16297 (let ((tsr org-ts-regexp) diff
16298 (calendar-move-hook nil)
16299 (calendar-view-holidays-initially-flag nil)
16300 (calendar-view-diary-initially-flag nil))
16301 (if (or (org-at-timestamp-p)
16302 (save-excursion
16303 (beginning-of-line 1)
16304 (looking-at (concat ".*" tsr))))
16305 (let ((d1 (time-to-days (current-time)))
16306 (d2 (time-to-days
16307 (org-time-string-to-time (match-string 1)))))
16308 (setq diff (- d2 d1))))
16309 (calendar)
16310 (calendar-goto-today)
16311 (if (and diff (not arg)) (calendar-forward-day diff))))
16313 (defun org-get-date-from-calendar ()
16314 "Return a list (month day year) of date at point in calendar."
16315 (with-current-buffer "*Calendar*"
16316 (save-match-data
16317 (calendar-cursor-to-date))))
16319 (defun org-date-from-calendar ()
16320 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
16321 If there is already a time stamp at the cursor position, update it."
16322 (interactive)
16323 (if (org-at-timestamp-p t)
16324 (org-timestamp-change 0 'calendar)
16325 (let ((cal-date (org-get-date-from-calendar)))
16326 (org-insert-time-stamp
16327 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
16329 (defun org-minutes-to-hh:mm-string (m)
16330 "Compute H:MM from a number of minutes."
16331 (let ((h (/ m 60)))
16332 (setq m (- m (* 60 h)))
16333 (format org-time-clocksum-format h m)))
16335 (defun org-hh:mm-string-to-minutes (s)
16336 "Convert a string H:MM to a number of minutes.
16337 If the string is just a number, interpret it as minutes.
16338 In fact, the first hh:mm or number in the string will be taken,
16339 there can be extra stuff in the string.
16340 If no number is found, the return value is 0."
16341 (cond
16342 ((integerp s) s)
16343 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
16344 (+ (* (string-to-number (match-string 1 s)) 60)
16345 (string-to-number (match-string 2 s))))
16346 ((string-match "\\([0-9]+\\)" s)
16347 (string-to-number (match-string 1 s)))
16348 (t 0)))
16350 (defcustom org-effort-durations
16351 `(("h" . 60)
16352 ("d" . ,(* 60 8))
16353 ("w" . ,(* 60 8 5))
16354 ("m" . ,(* 60 8 5 4))
16355 ("y" . ,(* 60 8 5 40)))
16356 "Conversion factor to minutes for an effort modifier.
16358 Each entry has the form (MODIFIER . MINUTES).
16360 In an effort string, a number followed by MODIFIER is multiplied
16361 by the specified number of MINUTES to obtain an effort in
16362 minutes.
16364 For example, if the value of this variable is ((\"hours\" . 60)), then an
16365 effort string \"2hours\" is equivalent to 120 minutes."
16366 :group 'org-agenda
16367 :version "24.1"
16368 :type '(alist :key-type (string :tag "Modifier")
16369 :value-type (number :tag "Minutes")))
16371 (defun org-duration-string-to-minutes (s &optional output-to-string)
16372 "Convert a duration string S to minutes.
16374 A bare number is interpreted as minutes, modifiers can be set by
16375 customizing `org-effort-durations' (which see).
16377 Entries containing a colon are interpreted as H:MM by
16378 `org-hh:mm-string-to-minutes'."
16379 (let ((result 0)
16380 (re (concat "\\([0-9.]+\\) *\\("
16381 (regexp-opt (mapcar 'car org-effort-durations))
16382 "\\)")))
16383 (while (string-match re s)
16384 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
16385 (string-to-number (match-string 1 s))))
16386 (setq s (replace-match "" nil t s)))
16387 (setq result (floor result))
16388 (incf result (org-hh:mm-string-to-minutes s))
16389 (if output-to-string (number-to-string result) result)))
16391 ;;;; Files
16393 (defun org-save-all-org-buffers ()
16394 "Save all Org-mode buffers without user confirmation."
16395 (interactive)
16396 (message "Saving all Org-mode buffers...")
16397 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
16398 (when (featurep 'org-id) (org-id-locations-save))
16399 (message "Saving all Org-mode buffers... done"))
16401 (defun org-revert-all-org-buffers ()
16402 "Revert all Org-mode buffers.
16403 Prompt for confirmation when there are unsaved changes.
16404 Be sure you know what you are doing before letting this function
16405 overwrite your changes.
16407 This function is useful in a setup where one tracks org files
16408 with a version control system, to revert on one machine after pulling
16409 changes from another. I believe the procedure must be like this:
16411 1. M-x org-save-all-org-buffers
16412 2. Pull changes from the other machine, resolve conflicts
16413 3. M-x org-revert-all-org-buffers"
16414 (interactive)
16415 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
16416 (error "Abort"))
16417 (save-excursion
16418 (save-window-excursion
16419 (mapc
16420 (lambda (b)
16421 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
16422 (with-current-buffer b buffer-file-name))
16423 (org-pop-to-buffer-same-window b)
16424 (revert-buffer t 'no-confirm)))
16425 (buffer-list))
16426 (when (and (featurep 'org-id) org-id-track-globally)
16427 (org-id-locations-load)))))
16429 ;;;; Agenda files
16431 ;;;###autoload
16432 (defun org-switchb (&optional arg)
16433 "Switch between Org buffers.
16434 With one prefix argument, restrict available buffers to files.
16435 With two prefix arguments, restrict available buffers to agenda files.
16437 Defaults to `iswitchb' for buffer name completion.
16438 Set `org-completion-use-ido' to make it use ido instead."
16439 (interactive "P")
16440 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
16441 ((equal arg '(16)) (org-buffer-list 'agenda))
16442 (t (org-buffer-list))))
16443 (org-completion-use-iswitchb org-completion-use-iswitchb)
16444 (org-completion-use-ido org-completion-use-ido))
16445 (unless (or org-completion-use-ido org-completion-use-iswitchb)
16446 (setq org-completion-use-iswitchb t))
16447 (org-pop-to-buffer-same-window
16448 (org-icompleting-read "Org buffer: "
16449 (mapcar 'list (mapcar 'buffer-name blist))
16450 nil t))))
16452 ;;; Define some older names previously used for this functionality
16453 ;;;###autoload
16454 (defalias 'org-ido-switchb 'org-switchb)
16455 ;;;###autoload
16456 (defalias 'org-iswitchb 'org-switchb)
16458 (defun org-buffer-list (&optional predicate exclude-tmp)
16459 "Return a list of Org buffers.
16460 PREDICATE can be `export', `files' or `agenda'.
16462 export restrict the list to Export buffers.
16463 files restrict the list to buffers visiting Org files.
16464 agenda restrict the list to buffers visiting agenda files.
16466 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
16467 (let* ((bfn nil)
16468 (agenda-files (and (eq predicate 'agenda)
16469 (mapcar 'file-truename (org-agenda-files t))))
16470 (filter
16471 (cond
16472 ((eq predicate 'files)
16473 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
16474 ((eq predicate 'export)
16475 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
16476 ((eq predicate 'agenda)
16477 (lambda (b)
16478 (with-current-buffer b
16479 (and (derived-mode-p 'org-mode)
16480 (setq bfn (buffer-file-name b))
16481 (member (file-truename bfn) agenda-files)))))
16482 (t (lambda (b) (with-current-buffer b
16483 (or (derived-mode-p 'org-mode)
16484 (string-match "\*Org .*Export"
16485 (buffer-name b)))))))))
16486 (delq nil
16487 (mapcar
16488 (lambda(b)
16489 (if (and (funcall filter b)
16490 (or (not exclude-tmp)
16491 (not (string-match "tmp" (buffer-name b)))))
16493 nil))
16494 (buffer-list)))))
16496 (defun org-agenda-files (&optional unrestricted archives)
16497 "Get the list of agenda files.
16498 Optional UNRESTRICTED means return the full list even if a restriction
16499 is currently in place.
16500 When ARCHIVES is t, include all archive files that are really being
16501 used by the agenda files. If ARCHIVE is `ifmode', do this only if
16502 `org-agenda-archives-mode' is t."
16503 (let ((files
16504 (cond
16505 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
16506 ((stringp org-agenda-files) (org-read-agenda-file-list))
16507 ((listp org-agenda-files) org-agenda-files)
16508 (t (error "Invalid value of `org-agenda-files'")))))
16509 (setq files (apply 'append
16510 (mapcar (lambda (f)
16511 (if (file-directory-p f)
16512 (directory-files
16513 f t org-agenda-file-regexp)
16514 (list f)))
16515 files)))
16516 (when org-agenda-skip-unavailable-files
16517 (setq files (delq nil
16518 (mapcar (function
16519 (lambda (file)
16520 (and (file-readable-p file) file)))
16521 files))))
16522 (when (or (eq archives t)
16523 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
16524 (setq files (org-add-archive-files files)))
16525 files))
16527 (defun org-agenda-file-p (&optional file)
16528 "Return non-nil, if FILE is an agenda file.
16529 If FILE is omitted, use the file associated with the current
16530 buffer."
16531 (member (or file (buffer-file-name))
16532 (org-agenda-files t)))
16534 (defun org-edit-agenda-file-list ()
16535 "Edit the list of agenda files.
16536 Depending on setup, this either uses customize to edit the variable
16537 `org-agenda-files', or it visits the file that is holding the list. In the
16538 latter case, the buffer is set up in a way that saving it automatically kills
16539 the buffer and restores the previous window configuration."
16540 (interactive)
16541 (if (stringp org-agenda-files)
16542 (let ((cw (current-window-configuration)))
16543 (find-file org-agenda-files)
16544 (org-set-local 'org-window-configuration cw)
16545 (org-add-hook 'after-save-hook
16546 (lambda ()
16547 (set-window-configuration
16548 (prog1 org-window-configuration
16549 (kill-buffer (current-buffer))))
16550 (org-install-agenda-files-menu)
16551 (message "New agenda file list installed"))
16552 nil 'local)
16553 (message "%s" (substitute-command-keys
16554 "Edit list and finish with \\[save-buffer]")))
16555 (customize-variable 'org-agenda-files)))
16557 (defun org-store-new-agenda-file-list (list)
16558 "Set new value for the agenda file list and save it correctly."
16559 (if (stringp org-agenda-files)
16560 (let ((fe (org-read-agenda-file-list t)) b u)
16561 (while (setq b (find-buffer-visiting org-agenda-files))
16562 (kill-buffer b))
16563 (with-temp-file org-agenda-files
16564 (insert
16565 (mapconcat
16566 (lambda (f) ;; Keep un-expanded entries.
16567 (if (setq u (assoc f fe))
16568 (cdr u)
16570 list "\n")
16571 "\n")))
16572 (let ((org-mode-hook nil) (org-inhibit-startup t)
16573 (org-insert-mode-line-in-empty-file nil))
16574 (setq org-agenda-files list)
16575 (customize-save-variable 'org-agenda-files org-agenda-files))))
16577 (defun org-read-agenda-file-list (&optional pair-with-expansion)
16578 "Read the list of agenda files from a file.
16579 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
16580 filenames, used by `org-store-new-agenda-file-list' to write back
16581 un-expanded file names."
16582 (when (file-directory-p org-agenda-files)
16583 (error "`org-agenda-files' cannot be a single directory"))
16584 (when (stringp org-agenda-files)
16585 (with-temp-buffer
16586 (insert-file-contents org-agenda-files)
16587 (mapcar
16588 (lambda (f)
16589 (let ((e (expand-file-name (substitute-in-file-name f)
16590 org-directory)))
16591 (if pair-with-expansion
16592 (cons e f)
16593 e)))
16594 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
16596 ;;;###autoload
16597 (defun org-cycle-agenda-files ()
16598 "Cycle through the files in `org-agenda-files'.
16599 If the current buffer visits an agenda file, find the next one in the list.
16600 If the current buffer does not, find the first agenda file."
16601 (interactive)
16602 (let* ((fs (org-agenda-files t))
16603 (files (append fs (list (car fs))))
16604 (tcf (if buffer-file-name (file-truename buffer-file-name)))
16605 file)
16606 (unless files (error "No agenda files"))
16607 (catch 'exit
16608 (while (setq file (pop files))
16609 (if (equal (file-truename file) tcf)
16610 (when (car files)
16611 (find-file (car files))
16612 (throw 'exit t))))
16613 (find-file (car fs)))
16614 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
16616 (defun org-agenda-file-to-front (&optional to-end)
16617 "Move/add the current file to the top of the agenda file list.
16618 If the file is not present in the list, it is added to the front. If it is
16619 present, it is moved there. With optional argument TO-END, add/move to the
16620 end of the list."
16621 (interactive "P")
16622 (let ((org-agenda-skip-unavailable-files nil)
16623 (file-alist (mapcar (lambda (x)
16624 (cons (file-truename x) x))
16625 (org-agenda-files t)))
16626 (ctf (file-truename buffer-file-name))
16627 x had)
16628 (setq x (assoc ctf file-alist) had x)
16630 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
16631 (if to-end
16632 (setq file-alist (append (delq x file-alist) (list x)))
16633 (setq file-alist (cons x (delq x file-alist))))
16634 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
16635 (org-install-agenda-files-menu)
16636 (message "File %s to %s of agenda file list"
16637 (if had "moved" "added") (if to-end "end" "front"))))
16639 (defun org-remove-file (&optional file)
16640 "Remove current file from the list of files in variable `org-agenda-files'.
16641 These are the files which are being checked for agenda entries.
16642 Optional argument FILE means use this file instead of the current."
16643 (interactive)
16644 (let* ((org-agenda-skip-unavailable-files nil)
16645 (file (or file buffer-file-name))
16646 (true-file (file-truename file))
16647 (afile (abbreviate-file-name file))
16648 (files (delq nil (mapcar
16649 (lambda (x)
16650 (if (equal true-file
16651 (file-truename x))
16652 nil x))
16653 (org-agenda-files t)))))
16654 (if (not (= (length files) (length (org-agenda-files t))))
16655 (progn
16656 (org-store-new-agenda-file-list files)
16657 (org-install-agenda-files-menu)
16658 (message "Removed file: %s" afile))
16659 (message "File was not in list: %s (not removed)" afile))))
16661 (defun org-file-menu-entry (file)
16662 (vector file (list 'find-file file) t))
16664 (defun org-check-agenda-file (file)
16665 "Make sure FILE exists. If not, ask user what to do."
16666 (when (not (file-exists-p file))
16667 (message "non-existent agenda file %s. [R]emove from list or [A]bort?"
16668 (abbreviate-file-name file))
16669 (let ((r (downcase (read-char-exclusive))))
16670 (cond
16671 ((equal r ?r)
16672 (org-remove-file file)
16673 (throw 'nextfile t))
16674 (t (error "Abort"))))))
16676 (defun org-get-agenda-file-buffer (file)
16677 "Get a buffer visiting FILE. If the buffer needs to be created, add
16678 it to the list of buffers which might be released later."
16679 (let ((buf (org-find-base-buffer-visiting file)))
16680 (if buf
16681 buf ; just return it
16682 ;; Make a new buffer and remember it
16683 (setq buf (find-file-noselect file))
16684 (if buf (push buf org-agenda-new-buffers))
16685 buf)))
16687 (defun org-release-buffers (blist)
16688 "Release all buffers in list, asking the user for confirmation when needed.
16689 When a buffer is unmodified, it is just killed. When modified, it is saved
16690 \(if the user agrees) and then killed."
16691 (let (buf file)
16692 (while (setq buf (pop blist))
16693 (setq file (buffer-file-name buf))
16694 (when (and (buffer-modified-p buf)
16695 file
16696 (y-or-n-p (format "Save file %s? " file)))
16697 (with-current-buffer buf (save-buffer)))
16698 (kill-buffer buf))))
16700 (defun org-prepare-agenda-buffers (files)
16701 "Create buffers for all agenda files, protect archived trees and comments."
16702 (interactive)
16703 (let ((pa '(:org-archived t))
16704 (pc '(:org-comment t))
16705 (pall '(:org-archived t :org-comment t))
16706 (inhibit-read-only t)
16707 (rea (concat ":" org-archive-tag ":"))
16708 bmp file re)
16709 (save-excursion
16710 (save-restriction
16711 (while (setq file (pop files))
16712 (catch 'nextfile
16713 (if (bufferp file)
16714 (set-buffer file)
16715 (org-check-agenda-file file)
16716 (set-buffer (org-get-agenda-file-buffer file)))
16717 (widen)
16718 (setq bmp (buffer-modified-p))
16719 (org-refresh-category-properties)
16720 (setq org-todo-keywords-for-agenda
16721 (append org-todo-keywords-for-agenda org-todo-keywords-1))
16722 (setq org-done-keywords-for-agenda
16723 (append org-done-keywords-for-agenda org-done-keywords))
16724 (setq org-todo-keyword-alist-for-agenda
16725 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
16726 (setq org-drawers-for-agenda
16727 (append org-drawers-for-agenda org-drawers))
16728 (setq org-tag-alist-for-agenda
16729 (append org-tag-alist-for-agenda org-tag-alist))
16731 (save-excursion
16732 (remove-text-properties (point-min) (point-max) pall)
16733 (when org-agenda-skip-archived-trees
16734 (goto-char (point-min))
16735 (while (re-search-forward rea nil t)
16736 (if (org-at-heading-p t)
16737 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
16738 (goto-char (point-min))
16739 (setq re (format org-heading-keyword-regexp-format
16740 org-comment-string))
16741 (while (re-search-forward re nil t)
16742 (add-text-properties
16743 (match-beginning 0) (org-end-of-subtree t) pc)))
16744 (set-buffer-modified-p bmp)))))
16745 (setq org-todo-keywords-for-agenda
16746 (org-uniquify org-todo-keywords-for-agenda))
16747 (setq org-todo-keyword-alist-for-agenda
16748 (org-uniquify org-todo-keyword-alist-for-agenda)
16749 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
16751 ;;;; Embedded LaTeX
16753 (defvar org-cdlatex-mode-map (make-sparse-keymap)
16754 "Keymap for the minor `org-cdlatex-mode'.")
16756 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
16757 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
16758 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
16759 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
16760 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
16762 (defvar org-cdlatex-texmathp-advice-is-done nil
16763 "Flag remembering if we have applied the advice to texmathp already.")
16765 (define-minor-mode org-cdlatex-mode
16766 "Toggle the minor `org-cdlatex-mode'.
16767 This mode supports entering LaTeX environment and math in LaTeX fragments
16768 in Org-mode.
16769 \\{org-cdlatex-mode-map}"
16770 nil " OCDL" nil
16771 (when org-cdlatex-mode
16772 (require 'cdlatex)
16773 (run-hooks 'cdlatex-mode-hook)
16774 (cdlatex-compute-tables))
16775 (unless org-cdlatex-texmathp-advice-is-done
16776 (setq org-cdlatex-texmathp-advice-is-done t)
16777 (defadvice texmathp (around org-math-always-on activate)
16778 "Always return t in org-mode buffers.
16779 This is because we want to insert math symbols without dollars even outside
16780 the LaTeX math segments. If Orgmode thinks that point is actually inside
16781 an embedded LaTeX fragment, let texmathp do its job.
16782 \\[org-cdlatex-mode-map]"
16783 (interactive)
16784 (let (p)
16785 (cond
16786 ((not (derived-mode-p 'org-mode)) ad-do-it)
16787 ((eq this-command 'cdlatex-math-symbol)
16788 (setq ad-return-value t
16789 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
16791 (let ((p (org-inside-LaTeX-fragment-p)))
16792 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
16793 (setq ad-return-value t
16794 texmathp-why '("Org-mode embedded math" . 0))
16795 (if p ad-do-it)))))))))
16797 (defun turn-on-org-cdlatex ()
16798 "Unconditionally turn on `org-cdlatex-mode'."
16799 (org-cdlatex-mode 1))
16801 (defun org-inside-LaTeX-fragment-p ()
16802 "Test if point is inside a LaTeX fragment.
16803 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
16804 sequence appearing also before point.
16805 Even though the matchers for math are configurable, this function assumes
16806 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
16807 delimiters are skipped when they have been removed by customization.
16808 The return value is nil, or a cons cell with the delimiter and the
16809 position of this delimiter.
16811 This function does a reasonably good job, but can locally be fooled by
16812 for example currency specifications. For example it will assume being in
16813 inline math after \"$22.34\". The LaTeX fragment formatter will only format
16814 fragments that are properly closed, but during editing, we have to live
16815 with the uncertainty caused by missing closing delimiters. This function
16816 looks only before point, not after."
16817 (catch 'exit
16818 (let ((pos (point))
16819 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
16820 (lim (progn
16821 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
16822 (point)))
16823 dd-on str (start 0) m re)
16824 (goto-char pos)
16825 (when dodollar
16826 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
16827 re (nth 1 (assoc "$" org-latex-regexps)))
16828 (while (string-match re str start)
16829 (cond
16830 ((= (match-end 0) (length str))
16831 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
16832 ((= (match-end 0) (- (length str) 5))
16833 (throw 'exit nil))
16834 (t (setq start (match-end 0))))))
16835 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
16836 (goto-char pos)
16837 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
16838 (and (match-beginning 2) (throw 'exit nil))
16839 ;; count $$
16840 (while (re-search-backward "\\$\\$" lim t)
16841 (setq dd-on (not dd-on)))
16842 (goto-char pos)
16843 (if dd-on (cons "$$" m))))))
16845 (defun org-inside-latex-macro-p ()
16846 "Is point inside a LaTeX macro or its arguments?"
16847 (save-match-data
16848 (org-in-regexp
16849 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
16851 (defun org-try-cdlatex-tab ()
16852 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
16853 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
16854 - inside a LaTeX fragment, or
16855 - after the first word in a line, where an abbreviation expansion could
16856 insert a LaTeX environment."
16857 (when org-cdlatex-mode
16858 (cond
16859 ;; Before any word on the line: No expansion possible.
16860 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
16861 ;; Just after first word on the line: Expand it. Make sure it
16862 ;; cannot happen on headlines, though.
16863 ((save-excursion
16864 (skip-chars-backward "a-zA-Z0-9*")
16865 (skip-chars-backward " \t")
16866 (and (bolp) (not (org-at-heading-p))))
16867 (cdlatex-tab) t)
16868 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
16870 (defun org-cdlatex-underscore-caret (&optional arg)
16871 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
16872 Revert to the normal definition outside of these fragments."
16873 (interactive "P")
16874 (if (org-inside-LaTeX-fragment-p)
16875 (call-interactively 'cdlatex-sub-superscript)
16876 (let (org-cdlatex-mode)
16877 (call-interactively (key-binding (vector last-input-event))))))
16879 (defun org-cdlatex-math-modify (&optional arg)
16880 "Execute `cdlatex-math-modify' in LaTeX fragments.
16881 Revert to the normal definition outside of these fragments."
16882 (interactive "P")
16883 (if (org-inside-LaTeX-fragment-p)
16884 (call-interactively 'cdlatex-math-modify)
16885 (let (org-cdlatex-mode)
16886 (call-interactively (key-binding (vector last-input-event))))))
16888 (defvar org-latex-fragment-image-overlays nil
16889 "List of overlays carrying the images of latex fragments.")
16890 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
16892 (defun org-remove-latex-fragment-image-overlays ()
16893 "Remove all overlays with LaTeX fragment images in current buffer."
16894 (mapc 'delete-overlay org-latex-fragment-image-overlays)
16895 (setq org-latex-fragment-image-overlays nil))
16897 (defun org-preview-latex-fragment (&optional subtree)
16898 "Preview the LaTeX fragment at point, or all locally or globally.
16899 If the cursor is in a LaTeX fragment, create the image and overlay
16900 it over the source code. If there is no fragment at point, display
16901 all fragments in the current text, from one headline to the next. With
16902 prefix SUBTREE, display all fragments in the current subtree. With a
16903 double prefix arg \\[universal-argument] \\[universal-argument], or when \
16904 the cursor is before the first headline,
16905 display all fragments in the buffer.
16906 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
16907 (interactive "P")
16908 (unless buffer-file-name
16909 (error "Can't preview LaTeX fragment in a non-file buffer"))
16910 (org-remove-latex-fragment-image-overlays)
16911 (save-excursion
16912 (save-restriction
16913 (let (beg end at msg)
16914 (cond
16915 ((or (equal subtree '(16))
16916 (not (save-excursion
16917 (re-search-backward org-outline-regexp-bol nil t))))
16918 (setq beg (point-min) end (point-max)
16919 msg "Creating images for buffer...%s"))
16920 ((equal subtree '(4))
16921 (org-back-to-heading)
16922 (setq beg (point) end (org-end-of-subtree t)
16923 msg "Creating images for subtree...%s"))
16925 (if (setq at (org-inside-LaTeX-fragment-p))
16926 (goto-char (max (point-min) (- (cdr at) 2)))
16927 (org-back-to-heading))
16928 (setq beg (point) end (progn (outline-next-heading) (point))
16929 msg (if at "Creating image...%s"
16930 "Creating images for entry...%s"))))
16931 (message msg "")
16932 (narrow-to-region beg end)
16933 (goto-char beg)
16934 (org-format-latex
16935 (concat "ltxpng/" (file-name-sans-extension
16936 (file-name-nondirectory
16937 buffer-file-name)))
16938 default-directory 'overlays msg at 'forbuffer
16939 org-latex-create-formula-image-program)
16940 (message msg "done. Use `C-c C-c' to remove images.")))))
16942 (defvar org-latex-regexps
16943 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
16944 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
16945 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
16946 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
16947 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
16948 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
16949 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
16950 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
16951 "Regular expressions for matching embedded LaTeX.")
16953 (defvar org-export-have-math nil) ;; dynamic scoping
16954 (defun org-format-latex (prefix &optional dir overlays msg at
16955 forbuffer processing-type)
16956 "Replace LaTeX fragments with links to an image, and produce images.
16957 Some of the options can be changed using the variable
16958 `org-format-latex-options'."
16959 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
16960 (let* ((prefixnodir (file-name-nondirectory prefix))
16961 (absprefix (expand-file-name prefix dir))
16962 (todir (file-name-directory absprefix))
16963 (opt org-format-latex-options)
16964 (matchers (plist-get opt :matchers))
16965 (re-list org-latex-regexps)
16966 (org-format-latex-header-extra
16967 (plist-get (org-infile-export-plist) :latex-header-extra))
16968 (cnt 0) txt hash link beg end re e checkdir
16969 executables-checked string
16970 m n block-type block linkfile movefile ov)
16971 ;; Check the different regular expressions
16972 (while (setq e (pop re-list))
16973 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
16974 block (if block-type "\n\n" ""))
16975 (when (member m matchers)
16976 (goto-char (point-min))
16977 (while (re-search-forward re nil t)
16978 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
16979 (not (get-text-property (match-beginning n)
16980 'org-protected))
16981 (or (not overlays)
16982 (not (eq (get-char-property (match-beginning n)
16983 'org-overlay-type)
16984 'org-latex-overlay))))
16985 (setq org-export-have-math t)
16986 (cond
16987 ((eq processing-type 'verbatim)
16988 ;; Leave the text verbatim, just protect it
16989 (add-text-properties (match-beginning n) (match-end n)
16990 '(org-protected t)))
16991 ((eq processing-type 'mathjax)
16992 ;; Prepare for MathJax processing
16993 (setq string (match-string n))
16994 (if (member m '("$" "$1"))
16995 (save-excursion
16996 (delete-region (match-beginning n) (match-end n))
16997 (goto-char (match-beginning n))
16998 (insert (org-add-props (concat "\\(" (substring string 1 -1)
16999 "\\)")
17000 '(org-protected t))))
17001 (add-text-properties (match-beginning n) (match-end n)
17002 '(org-protected t))))
17003 ((or (eq processing-type 'dvipng)
17004 (eq processing-type 'imagemagick))
17005 ;; Process to an image
17006 (setq txt (match-string n)
17007 beg (match-beginning n) end (match-end n)
17008 cnt (1+ cnt))
17009 (let (print-length print-level) ; make sure full list is printed
17010 (setq hash (sha1 (prin1-to-string
17011 (list org-format-latex-header
17012 org-format-latex-header-extra
17013 org-export-latex-default-packages-alist
17014 org-export-latex-packages-alist
17015 org-format-latex-options
17016 forbuffer txt)))
17017 linkfile (format "%s_%s.png" prefix hash)
17018 movefile (format "%s_%s.png" absprefix hash)))
17019 (setq link (concat block "[[file:" linkfile "]]" block))
17020 (if msg (message msg cnt))
17021 (goto-char beg)
17022 (unless checkdir ; make sure the directory exists
17023 (setq checkdir t)
17024 (or (file-directory-p todir) (make-directory todir t)))
17025 (cond
17026 ((eq processing-type 'dvipng)
17027 (unless executables-checked
17028 (org-check-external-command
17029 "latex" "needed to convert LaTeX fragments to images")
17030 (org-check-external-command
17031 "dvipng" "needed to convert LaTeX fragments to images")
17032 (setq executables-checked t))
17033 (unless (file-exists-p movefile)
17034 (org-create-formula-image-with-dvipng
17035 txt movefile opt forbuffer)))
17036 ((eq processing-type 'imagemagick)
17037 (unless executables-checked
17038 (org-check-external-command
17039 "convert" "you need to install imagemagick")
17040 (setq executables-checked t))
17041 (unless (file-exists-p movefile)
17042 (org-create-formula-image-with-imagemagick
17043 txt movefile opt forbuffer))))
17044 (if overlays
17045 (progn
17046 (mapc (lambda (o)
17047 (if (eq (overlay-get o 'org-overlay-type)
17048 'org-latex-overlay)
17049 (delete-overlay o)))
17050 (overlays-in beg end))
17051 (setq ov (make-overlay beg end))
17052 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
17053 (if (featurep 'xemacs)
17054 (progn
17055 (overlay-put ov 'invisible t)
17056 (overlay-put
17057 ov 'end-glyph
17058 (make-glyph (vector 'png :file movefile))))
17059 (overlay-put
17060 ov 'display
17061 (list 'image :type 'png :file movefile :ascent 'center)))
17062 (push ov org-latex-fragment-image-overlays)
17063 (goto-char end))
17064 (delete-region beg end)
17065 (insert (org-add-props link
17066 (list 'org-latex-src
17067 (replace-regexp-in-string
17068 "\"" "" txt)
17069 'org-latex-src-embed-type
17070 (if block-type 'paragraph 'character))))))
17071 ((eq processing-type 'mathml)
17072 ;; Process to MathML
17073 (unless executables-checked
17074 (unless (save-match-data (org-format-latex-mathml-available-p))
17075 (error "LaTeX to MathML converter not configured"))
17076 (setq executables-checked t))
17077 (setq txt (match-string n)
17078 beg (match-beginning n) end (match-end n)
17079 cnt (1+ cnt))
17080 (if msg (message msg cnt))
17081 (goto-char beg)
17082 (delete-region beg end)
17083 (insert (org-format-latex-as-mathml
17084 txt block-type prefix dir)))
17086 (error "Unknown conversion type %s for latex fragments"
17087 processing-type)))))))))
17089 (defun org-create-math-formula (latex-frag &optional mathml-file)
17090 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
17091 Use `org-latex-to-mathml-convert-command'. If the conversion is
17092 sucessful, return the portion between \"<math...> </math>\"
17093 elements otherwise return nil. When MATHML-FILE is specified,
17094 write the results in to that file. When invoked as an
17095 interactive command, prompt for LATEX-FRAG, with initial value
17096 set to the current active region and echo the results for user
17097 inspection."
17098 (interactive (list (let ((frag (when (region-active-p)
17099 (buffer-substring-no-properties
17100 (region-beginning) (region-end)))))
17101 (read-string "LaTeX Fragment: " frag nil frag))))
17102 (unless latex-frag (error "Invalid latex-frag"))
17103 (let* ((tmp-in-file (file-relative-name
17104 (make-temp-name (expand-file-name "ltxmathml-in"))))
17105 (ignore (write-region latex-frag nil tmp-in-file))
17106 (tmp-out-file (file-relative-name
17107 (make-temp-name (expand-file-name "ltxmathml-out"))))
17108 (cmd (format-spec
17109 org-latex-to-mathml-convert-command
17110 `((?j . ,(shell-quote-argument
17111 (expand-file-name org-latex-to-mathml-jar-file)))
17112 (?I . ,(shell-quote-argument tmp-in-file))
17113 (?o . ,(shell-quote-argument tmp-out-file)))))
17114 mathml shell-command-output)
17115 (when (org-called-interactively-p 'any)
17116 (unless (org-format-latex-mathml-available-p)
17117 (error "LaTeX to MathML converter not configured")))
17118 (message "Running %s" cmd)
17119 (setq shell-command-output (shell-command-to-string cmd))
17120 (setq mathml
17121 (when (file-readable-p tmp-out-file)
17122 (with-current-buffer (find-file-noselect tmp-out-file t)
17123 (goto-char (point-min))
17124 (when (re-search-forward
17125 (concat
17126 (regexp-quote
17127 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
17128 "\\(.\\|\n\\)*"
17129 (regexp-quote "</math>")) nil t)
17130 (prog1 (match-string 0) (kill-buffer))))))
17131 (cond
17132 (mathml
17133 (setq mathml
17134 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
17135 (when mathml-file
17136 (write-region mathml nil mathml-file))
17137 (when (org-called-interactively-p 'any)
17138 (message mathml)))
17139 ((message "LaTeX to MathML conversion failed")
17140 (message shell-command-output)))
17141 (delete-file tmp-in-file)
17142 (when (file-exists-p tmp-out-file)
17143 (delete-file tmp-out-file))
17144 mathml))
17146 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
17147 prefix &optional dir)
17148 "Use `org-create-math-formula' but check local cache first."
17149 (let* ((absprefix (expand-file-name prefix dir))
17150 (print-length nil) (print-level nil)
17151 (formula-id (concat
17152 "formula-"
17153 (sha1
17154 (prin1-to-string
17155 (list latex-frag
17156 org-latex-to-mathml-convert-command)))))
17157 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
17158 (formula-cache-dir (file-name-directory formula-cache)))
17160 (unless (file-directory-p formula-cache-dir)
17161 (make-directory formula-cache-dir t))
17163 (unless (file-exists-p formula-cache)
17164 (org-create-math-formula latex-frag formula-cache))
17166 (if (file-exists-p formula-cache)
17167 ;; Successful conversion. Return the link to MathML file.
17168 (org-add-props
17169 (format "[[file:%s]]" (file-relative-name formula-cache dir))
17170 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
17171 'org-latex-src-embed-type (if latex-frag-type
17172 'paragraph 'character)))
17173 ;; Failed conversion. Return the LaTeX fragment verbatim
17174 (add-text-properties
17175 0 (1- (length latex-frag)) '(org-protected t) latex-frag)
17176 latex-frag)))
17178 ;; This function borrows from Ganesh Swami's latex2png.el
17179 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
17180 "This calls dvipng."
17181 (require 'org-latex)
17182 (let* ((tmpdir (if (featurep 'xemacs)
17183 (temp-directory)
17184 temporary-file-directory))
17185 (texfilebase (make-temp-name
17186 (expand-file-name "orgtex" tmpdir)))
17187 (texfile (concat texfilebase ".tex"))
17188 (dvifile (concat texfilebase ".dvi"))
17189 (pngfile (concat texfilebase ".png"))
17190 (fnh (if (featurep 'xemacs)
17191 (font-height (face-font 'default))
17192 (face-attribute 'default :height nil)))
17193 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17194 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17195 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17196 "Black"))
17197 (bg (or (plist-get options (if buffer :background :html-background))
17198 "Transparent")))
17199 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
17200 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
17201 (with-temp-file texfile
17202 (insert (org-splice-latex-header
17203 org-format-latex-header
17204 org-export-latex-default-packages-alist
17205 org-export-latex-packages-alist t
17206 org-format-latex-header-extra))
17207 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")
17208 (require 'org-latex)
17209 (org-export-latex-fix-inputenc))
17210 (let ((dir default-directory))
17211 (condition-case nil
17212 (progn
17213 (cd tmpdir)
17214 (call-process "latex" nil nil nil texfile))
17215 (error nil))
17216 (cd dir))
17217 (if (not (file-exists-p dvifile))
17218 (progn (message "Failed to create dvi file from %s" texfile) nil)
17219 (condition-case nil
17220 (if (featurep 'xemacs)
17221 (call-process "dvipng" nil nil nil
17222 "-fg" fg "-bg" bg
17223 "-T" "tight"
17224 "-o" pngfile
17225 dvifile)
17226 (call-process "dvipng" nil nil nil
17227 "-fg" fg "-bg" bg
17228 "-D" dpi
17229 ;;"-x" scale "-y" scale
17230 "-T" "tight"
17231 "-o" pngfile
17232 dvifile))
17233 (error nil))
17234 (if (not (file-exists-p pngfile))
17235 (if org-format-latex-signal-error
17236 (error "Failed to create png file from %s" texfile)
17237 (message "Failed to create png file from %s" texfile)
17238 nil)
17239 ;; Use the requested file name and clean up
17240 (copy-file pngfile tofile 'replace)
17241 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
17242 (delete-file (concat texfilebase e)))
17243 pngfile))))
17245 (defvar org-latex-to-pdf-process) ;; Defined in org-latex.el
17246 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
17247 "This calls convert, which is included into imagemagick."
17248 (require 'org-latex)
17249 (let* ((tmpdir (if (featurep 'xemacs)
17250 (temp-directory)
17251 temporary-file-directory))
17252 (texfilebase (make-temp-name
17253 (expand-file-name "orgtex" tmpdir)))
17254 (texfile (concat texfilebase ".tex"))
17255 (pdffile (concat texfilebase ".pdf"))
17256 (pngfile (concat texfilebase ".png"))
17257 (fnh (if (featurep 'xemacs)
17258 (font-height (face-font 'default))
17259 (face-attribute 'default :height nil)))
17260 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17261 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17262 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17263 "black"))
17264 (bg (or (plist-get options (if buffer :background :html-background))
17265 "white")))
17266 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
17267 (setq fg (org-latex-color-format fg)))
17268 (if (eq bg 'default) (setq bg (org-latex-color :background))
17269 (setq bg (org-latex-color-format
17270 (if (string= bg "Transparent")(setq bg "white")))))
17271 (with-temp-file texfile
17272 (insert (org-splice-latex-header
17273 org-format-latex-header
17274 org-export-latex-default-packages-alist
17275 org-export-latex-packages-alist t
17276 org-format-latex-header-extra))
17277 (insert "\n\\begin{document}\n"
17278 "\\definecolor{fg}{rgb}{" fg "}\n"
17279 "\\definecolor{bg}{rgb}{" bg "}\n"
17280 "\n\\pagecolor{bg}\n"
17281 "\n{\\color{fg}\n"
17282 string
17283 "\n}\n"
17284 "\n\\end{document}\n" )
17285 (require 'org-latex)
17286 (org-export-latex-fix-inputenc))
17287 (let ((dir default-directory) cmd cmds latex-frags-cmds)
17288 (condition-case nil
17289 (progn
17290 (cd tmpdir)
17291 (setq cmds org-latex-to-pdf-process)
17292 (while cmds
17293 (setq latex-frags-cmds (pop cmds))
17294 (if (listp latex-frags-cmds)
17295 (setq cmds nil)
17296 (setq latex-frags-cmds (list (car org-latex-to-pdf-process)))))
17297 (while latex-frags-cmds
17298 (setq cmd (pop latex-frags-cmds))
17299 (while (string-match "%b" cmd)
17300 (setq cmd (replace-match
17301 (save-match-data
17302 (shell-quote-argument texfile))
17303 t t cmd)))
17304 (while (string-match "%f" cmd)
17305 (setq cmd (replace-match
17306 (save-match-data
17307 (shell-quote-argument (file-name-nondirectory texfile)))
17308 t t cmd)))
17309 (while (string-match "%o" cmd)
17310 (setq cmd (replace-match
17311 (save-match-data
17312 (shell-quote-argument (file-name-directory texfile)))
17313 t t cmd)))
17314 (setq cmd (split-string cmd))
17315 (eval (append (list 'call-process (pop cmd) nil nil nil) 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 (declare-function orgstruct++-ignore-org-filling "org-macs.el" (&rest body))
20405 (defun org-indent-line-function ()
20406 "Indent line depending on context."
20407 (interactive)
20408 (if orgstruct-is-++
20409 (orgstruct++-ignore-org-filling
20410 (funcall indent-line-function))
20411 (let* ((pos (point))
20412 (itemp (org-at-item-p))
20413 (case-fold-search t)
20414 (org-drawer-regexp (or org-drawer-regexp "\000"))
20415 (inline-task-p (and (featurep 'org-inlinetask)
20416 (org-inlinetask-in-task-p)))
20417 (inline-re (and inline-task-p
20418 (org-inlinetask-outline-regexp)))
20419 column)
20420 (beginning-of-line 1)
20421 (cond
20422 ;; Comments
20423 ((looking-at "# ") (setq column 0))
20424 ;; Headings
20425 ((looking-at org-outline-regexp) (setq column 0))
20426 ;; Included files
20427 ((looking-at "#\\+include:") (setq column 0))
20428 ;; Footnote definition
20429 ((looking-at org-footnote-definition-re) (setq column 0))
20430 ;; Literal examples
20431 ((looking-at "[ \t]*:\\( \\|$\\)")
20432 (setq column (org-get-indentation))) ; do nothing
20433 ;; Lists
20434 ((ignore-errors (goto-char (org-in-item-p)))
20435 (setq column (if itemp
20436 (org-get-indentation)
20437 (org-list-item-body-column (point))))
20438 (goto-char pos))
20439 ;; Drawers
20440 ((and (looking-at "[ \t]*:END:")
20441 (save-excursion (re-search-backward org-drawer-regexp nil t)))
20442 (save-excursion
20443 (goto-char (1- (match-beginning 1)))
20444 (setq column (current-column))))
20445 ;; Special blocks
20446 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
20447 (save-excursion
20448 (re-search-backward
20449 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
20450 (setq column (org-get-indentation (match-string 0))))
20451 ((and (not (looking-at "[ \t]*#\\+begin_"))
20452 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
20453 (save-excursion
20454 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
20455 (setq column
20456 (cond ((equal (downcase (match-string 1)) "src")
20457 ;; src blocks: let `org-edit-src-exit' handle them
20458 (org-get-indentation))
20459 ((equal (downcase (match-string 1)) "example")
20460 (max (org-get-indentation)
20461 (org-get-indentation (match-string 0))))
20463 (org-get-indentation (match-string 0))))))
20464 ;; This line has nothing special, look at the previous relevant
20465 ;; line to compute indentation
20467 (beginning-of-line 0)
20468 (while (and (not (bobp))
20469 (not (looking-at org-drawer-regexp))
20470 ;; When point started in an inline task, do not move
20471 ;; above task starting line.
20472 (not (and inline-task-p (looking-at inline-re)))
20473 ;; Skip drawers, blocks, empty lines, verbatim,
20474 ;; comments, tables, footnotes definitions, lists,
20475 ;; inline tasks.
20476 (or (and (looking-at "[ \t]*:END:")
20477 (re-search-backward org-drawer-regexp nil t))
20478 (and (looking-at "[ \t]*#\\+end_")
20479 (re-search-backward "[ \t]*#\\+begin_"nil t))
20480 (looking-at "[ \t]*[\n:#|]")
20481 (looking-at org-footnote-definition-re)
20482 (and (ignore-errors (goto-char (org-in-item-p)))
20483 (goto-char
20484 (org-list-get-top-point (org-list-struct))))
20485 (and (not inline-task-p)
20486 (featurep 'org-inlinetask)
20487 (org-inlinetask-in-task-p)
20488 (or (org-inlinetask-goto-beginning) t))))
20489 (beginning-of-line 0))
20490 (cond
20491 ;; There was an heading above.
20492 ((looking-at "\\*+[ \t]+")
20493 (if (not org-adapt-indentation)
20494 (setq column 0)
20495 (goto-char (match-end 0))
20496 (setq column (current-column))))
20497 ;; A drawer had started and is unfinished
20498 ((looking-at org-drawer-regexp)
20499 (goto-char (1- (match-beginning 1)))
20500 (setq column (current-column)))
20501 ;; Else, nothing noticeable found: get indentation and go on.
20502 (t (setq column (org-get-indentation))))))
20503 ;; Now apply indentation and move cursor accordingly
20504 (goto-char pos)
20505 (if (<= (current-column) (current-indentation))
20506 (org-indent-line-to column)
20507 (save-excursion (org-indent-line-to column)))
20508 ;; Special polishing for properties, see `org-property-format'
20509 (setq column (current-column))
20510 (beginning-of-line 1)
20511 (if (looking-at
20512 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
20513 (replace-match (concat (match-string 1)
20514 (format org-property-format
20515 (match-string 2) (match-string 3)))
20516 t t))
20517 (org-move-to-column column))))
20519 (defun org-indent-drawer ()
20520 "Indent the drawer at point."
20521 (interactive)
20522 (let ((p (point))
20523 (e (and (save-excursion (re-search-forward ":END:" nil t))
20524 (match-end 0)))
20525 (folded
20526 (save-excursion
20527 (end-of-line)
20528 (when (overlays-at (point))
20529 (member 'invisible (overlay-properties
20530 (car (overlays-at (point)))))))))
20531 (when folded (org-cycle))
20532 (indent-for-tab-command)
20533 (while (and (move-beginning-of-line 2) (< (point) e))
20534 (indent-for-tab-command))
20535 (goto-char p)
20536 (when folded (org-cycle)))
20537 (message "Drawer at point indented"))
20539 (defun org-indent-block ()
20540 "Indent the block at point."
20541 (interactive)
20542 (let ((p (point))
20543 (case-fold-search t)
20544 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
20545 (match-end 0)))
20546 (folded
20547 (save-excursion
20548 (end-of-line)
20549 (when (overlays-at (point))
20550 (member 'invisible (overlay-properties
20551 (car (overlays-at (point)))))))))
20552 (when folded (org-cycle))
20553 (indent-for-tab-command)
20554 (while (and (move-beginning-of-line 2) (< (point) e))
20555 (indent-for-tab-command))
20556 (goto-char p)
20557 (when folded (org-cycle)))
20558 (message "Block at point indented"))
20560 (defvar org-adaptive-fill-regexp-backup adaptive-fill-regexp
20561 "Variable to store copy of `adaptive-fill-regexp'.
20562 Since `adaptive-fill-regexp' is set to never match, we need to
20563 store a backup of its value before entering `org-mode' so that
20564 the functionality can be provided as a fall-back.")
20566 (defun org-set-autofill-regexps ()
20567 (interactive)
20568 ;; In the paragraph separator we include headlines, because filling
20569 ;; text in a line directly attached to a headline would otherwise
20570 ;; fill the headline as well.
20571 (org-set-local 'comment-start-skip "^#+[ \t]*")
20572 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|#]")
20573 ;; The paragraph starter includes hand-formatted lists.
20574 (org-set-local
20575 'paragraph-start
20576 (concat
20577 "\f" "\\|"
20578 "[ ]*$" "\\|"
20579 org-outline-regexp "\\|"
20580 "[ \t]*#" "\\|"
20581 (org-item-re) "\\|"
20582 "[ \t]*[:|]" "\\|"
20583 "\\$\\$" "\\|"
20584 "\\\\\\(begin\\|end\\|[][]\\)"))
20585 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
20586 ;; But only if the user has not turned off tables or fixed-width regions
20587 (org-set-local
20588 'auto-fill-inhibit-regexp
20589 (concat org-outline-regexp
20590 "\\|#\\+"
20591 "\\|[ \t]*" org-keyword-time-regexp
20592 (if (or org-enable-table-editor org-enable-fixed-width-editor)
20593 (concat
20594 "\\|[ \t]*["
20595 (if org-enable-table-editor "|" "")
20596 (if org-enable-fixed-width-editor ":" "")
20597 "]"))))
20598 ;; We use our own fill-paragraph function, to make sure that tables
20599 ;; and fixed-width regions are not wrapped. That function will pass
20600 ;; through to `fill-paragraph' when appropriate.
20601 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
20602 ;; Prevent auto-fill from inserting unwanted new items.
20603 (if (boundp 'fill-nobreak-predicate)
20604 (org-set-local
20605 'fill-nobreak-predicate
20606 (org-uniquify
20607 (append fill-nobreak-predicate
20608 '(org-fill-item-nobreak-p org-fill-line-break-nobreak-p)))))
20609 ;; Adaptive filling: To get full control, first make sure that
20610 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
20611 (unless (local-variable-p 'adaptive-fill-regexp (current-buffer))
20612 (org-set-local 'org-adaptive-fill-regexp-backup
20613 adaptive-fill-regexp))
20614 (org-set-local 'adaptive-fill-regexp "\000")
20615 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
20616 (org-set-local 'adaptive-fill-function
20617 'org-adaptive-fill-function)
20618 (org-set-local
20619 'align-mode-rules-list
20620 '((org-in-buffer-settings
20621 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
20622 (modes . '(org-mode))))))
20624 (defun org-fill-item-nobreak-p ()
20625 "Non-nil when a line break at point would insert a new item."
20626 (and (looking-at (org-item-re)) (org-list-in-valid-context-p)))
20628 (defun org-fill-line-break-nobreak-p ()
20629 "Non-nil when a line break at point would create an Org line break."
20630 (save-excursion
20631 (skip-chars-backward "[ \t]")
20632 (skip-chars-backward "\\\\")
20633 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
20635 (defun org-fill-paragraph (&optional justify)
20636 "Re-align a table, pass through to fill-paragraph if no table."
20637 (let ((table-p (org-at-table-p))
20638 (table.el-p (org-at-table.el-p))
20639 (itemp (org-in-item-p)))
20640 (cond ((and (equal (char-after (point-at-bol)) ?*)
20641 (save-excursion (goto-char (point-at-bol))
20642 (looking-at org-outline-regexp)))
20643 t) ; skip headlines
20644 (table.el-p t) ; skip table.el tables
20645 (table-p (org-table-align) t) ; align Org tables
20646 (itemp ; align text in items
20647 (let* ((struct (save-excursion (goto-char itemp)
20648 (org-list-struct)))
20649 (parents (org-list-parents-alist struct))
20650 (children (org-list-get-children itemp struct parents))
20651 beg end prev next prefix)
20652 ;; Determine in which part of item point is: before
20653 ;; first child, after last child, between two
20654 ;; sub-lists, or simply in item if there's no child.
20655 (cond
20656 ((not children)
20657 (setq prefix (make-string (org-list-item-body-column itemp) ?\ )
20658 beg itemp
20659 end (org-list-get-item-end itemp struct)))
20660 ((< (point) (setq next (car children)))
20661 (setq prefix (make-string (org-list-item-body-column itemp) ?\ )
20662 beg itemp
20663 end next))
20664 ((> (point) (setq prev (car (last children))))
20665 (setq beg (org-list-get-item-end prev struct)
20666 end (org-list-get-item-end itemp struct)
20667 prefix (save-excursion
20668 (goto-char beg)
20669 (skip-chars-forward " \t")
20670 (make-string (current-column) ?\ ))))
20671 (t (catch 'exit
20672 (while (setq next (pop children))
20673 (if (> (point) next)
20674 (setq prev next)
20675 (setq beg (org-list-get-item-end prev struct)
20676 end next
20677 prefix (save-excursion
20678 (goto-char beg)
20679 (skip-chars-forward " \t")
20680 (make-string (current-column) ?\ )))
20681 (throw 'exit nil))))))
20682 ;; Use `fill-paragraph' with buffer narrowed to item
20683 ;; without any child, and with our computed PREFIX.
20684 (flet ((fill-context-prefix (from to &optional flr) prefix))
20685 (save-restriction
20686 (narrow-to-region beg end)
20687 (save-excursion (fill-paragraph justify)))) t))
20688 ;; Special case where point is not in a list but is on
20689 ;; a paragraph adjacent to a list: make sure this paragraph
20690 ;; doesn't get merged with the end of the list by narrowing
20691 ;; buffer first.
20692 ((and (derived-mode-p 'org-mode)
20693 (save-excursion (forward-paragraph -1)
20694 (setq itemp (org-in-item-p))))
20695 (let ((struct (save-excursion (goto-char itemp)
20696 (org-list-struct))))
20697 (save-restriction
20698 (narrow-to-region (org-list-get-bottom-point struct)
20699 (save-excursion (forward-paragraph 1)
20700 (point)))
20701 (fill-paragraph justify) t)))
20702 ;; Don't fill schedule/deadline line before a paragraph
20703 ;; This only makes sense in real org-mode buffers
20704 ((and (eq major-mode 'org-mode)
20705 (save-excursion (forward-paragraph -1)
20706 (or (looking-at (concat "^[^\n]*" org-scheduled-regexp ".*$"))
20707 (looking-at (concat "^[^\n]*" org-deadline-regexp ".*$")))))
20708 (save-restriction
20709 (narrow-to-region (1+ (match-end 0))
20710 (save-excursion (forward-paragraph 1) (point)))
20711 (fill-paragraph justify) t))
20712 ;; Else falls back on `org-fill-paragraph-fallback-function'
20713 (orgstruct-is-++
20714 (orgstruct++-ignore-org-filling
20715 (fill-paragraph)))
20716 ;; (org-fill-paragraph-fallback-function
20717 ;; (funcall org-fill-paragraph-fallback-function justify))
20718 ;; Else simply call `fill-paragraph'.
20719 (t nil))))
20721 ;; For reference, this is the default value of adaptive-fill-regexp
20722 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
20724 (defun org-adaptive-fill-function ()
20725 "Return a fill prefix for org-mode files."
20726 (let (itemp)
20727 (save-excursion
20728 (cond
20729 ;; Comment line
20730 ((looking-at "#[ \t]+")
20731 (match-string-no-properties 0))
20732 ;; Plain list item
20733 ((org-at-item-p)
20734 (make-string (org-list-item-body-column (point-at-bol)) ?\ ))
20735 ;; Point is in a list after `backward-paragraph': original
20736 ;; point wasn't in the list, or filling would have been taken
20737 ;; care of by `org-auto-fill-function', but the list and the
20738 ;; real paragraph are not separated by a blank line. Thus, move
20739 ;; point after the list to go back to real paragraph and
20740 ;; determine fill-prefix.
20741 ((setq itemp (org-in-item-p))
20742 (goto-char itemp)
20743 (let* ((struct (org-list-struct))
20744 (bottom (org-list-get-bottom-point struct)))
20745 (goto-char bottom)
20746 (make-string (org-get-indentation) ?\ )))
20747 ;; Other text
20748 ((looking-at org-adaptive-fill-regexp-backup)
20749 (match-string-no-properties 0))))))
20751 (defun org-auto-fill-function ()
20752 "Auto-fill function."
20753 (let (itemp prefix)
20754 ;; When in a list, compute an appropriate fill-prefix and make
20755 ;; sure it will be used by `do-auto-fill'.
20756 (cond ((setq itemp (org-in-item-p))
20757 (progn
20758 (setq prefix (make-string (org-list-item-body-column itemp) ?\ ))
20759 (flet ((fill-context-prefix (from to &optional flr) prefix))
20760 (do-auto-fill))))
20761 (orgstruct-is-++
20762 (orgstruct++-ignore-org-filling
20763 (do-auto-fill)))
20764 (t (do-auto-fill)))))
20766 ;;; Other stuff.
20768 (defun org-toggle-fixed-width-section (arg)
20769 "Toggle the fixed-width export.
20770 If there is no active region, the QUOTE keyword at the current headline is
20771 inserted or removed. When present, it causes the text between this headline
20772 and the next to be exported as fixed-width text, and unmodified.
20773 If there is an active region, this command adds or removes a colon as the
20774 first character of this line. If the first character of a line is a colon,
20775 this line is also exported in fixed-width font."
20776 (interactive "P")
20777 (let* ((cc 0)
20778 (regionp (org-region-active-p))
20779 (beg (if regionp (region-beginning) (point)))
20780 (end (if regionp (region-end)))
20781 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
20782 (case-fold-search nil)
20783 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
20784 off)
20785 (if regionp
20786 (save-excursion
20787 (goto-char beg)
20788 (setq cc (current-column))
20789 (beginning-of-line 1)
20790 (setq off (looking-at re))
20791 (while (> nlines 0)
20792 (setq nlines (1- nlines))
20793 (beginning-of-line 1)
20794 (cond
20795 (arg
20796 (org-move-to-column cc t)
20797 (insert ": \n")
20798 (forward-line -1))
20799 ((and off (looking-at re))
20800 (replace-match "" t t nil 1))
20801 ((not off) (org-move-to-column cc t) (insert ": ")))
20802 (forward-line 1)))
20803 (save-excursion
20804 (org-back-to-heading)
20805 (cond
20806 ((looking-at (format org-heading-keyword-regexp-format
20807 org-quote-string))
20808 (goto-char (match-end 1))
20809 (looking-at (concat " +" org-quote-string))
20810 (replace-match "" t t)
20811 (when (eolp) (insert " ")))
20812 ((looking-at org-outline-regexp)
20813 (goto-char (match-end 0))
20814 (insert org-quote-string " ")))))))
20816 (defun org-reftex-citation ()
20817 "Use reftex-citation to insert a citation into the buffer.
20818 This looks for a line like
20820 #+BIBLIOGRAPHY: foo plain option:-d
20822 and derives from it that foo.bib is the bibliography file relevant
20823 for this document. It then installs the necessary environment for RefTeX
20824 to work in this buffer and calls `reftex-citation' to insert a citation
20825 into the buffer.
20827 Export of such citations to both LaTeX and HTML is handled by the contributed
20828 package org-exp-bibtex by Taru Karttunen."
20829 (interactive)
20830 (let ((reftex-docstruct-symbol 'rds)
20831 (reftex-cite-format "\\cite{%l}")
20832 rds bib)
20833 (save-excursion
20834 (save-restriction
20835 (widen)
20836 (let ((case-fold-search t)
20837 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
20838 (if (not (save-excursion
20839 (or (re-search-forward re nil t)
20840 (re-search-backward re nil t))))
20841 (error "No bibliography defined in file")
20842 (setq bib (concat (match-string 1) ".bib")
20843 rds (list (list 'bib bib)))))))
20844 (call-interactively 'reftex-citation)))
20846 ;;;; Functions extending outline functionality
20848 (defun org-beginning-of-line (&optional arg)
20849 "Go to the beginning of the current line. If that is invisible, continue
20850 to a visible line beginning. This makes the function of C-a more intuitive.
20851 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
20852 first attempt, and only move to after the tags when the cursor is already
20853 beyond the end of the headline."
20854 (interactive "P")
20855 (let ((pos (point))
20856 (special (if (consp org-special-ctrl-a/e)
20857 (car org-special-ctrl-a/e)
20858 org-special-ctrl-a/e))
20859 refpos)
20860 (if (org-bound-and-true-p line-move-visual)
20861 (beginning-of-visual-line 1)
20862 (beginning-of-line 1))
20863 (if (and arg (fboundp 'move-beginning-of-line))
20864 (call-interactively 'move-beginning-of-line)
20865 (if (bobp)
20867 (backward-char 1)
20868 (if (org-truely-invisible-p)
20869 (while (and (not (bobp)) (org-truely-invisible-p))
20870 (backward-char 1)
20871 (beginning-of-line 1))
20872 (forward-char 1))))
20873 (when special
20874 (cond
20875 ((and (looking-at org-complex-heading-regexp)
20876 (= (char-after (match-end 1)) ?\ ))
20877 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
20878 (point-at-eol)))
20879 (goto-char
20880 (if (eq special t)
20881 (cond ((> pos refpos) refpos)
20882 ((= pos (point)) refpos)
20883 (t (point)))
20884 (cond ((> pos (point)) (point))
20885 ((not (eq last-command this-command)) (point))
20886 (t refpos)))))
20887 ((org-at-item-p)
20888 ;; Being at an item and not looking at an the item means point
20889 ;; was previously moved to beginning of a visual line, which
20890 ;; doesn't contain the item. Therefore, do nothing special,
20891 ;; just stay here.
20892 (when (looking-at org-list-full-item-re)
20893 ;; Set special position at first white space character after
20894 ;; bullet, and check-box, if any.
20895 (let ((after-bullet
20896 (let ((box (match-end 3)))
20897 (if (not box) (match-end 1)
20898 (let ((after (char-after box)))
20899 (if (and after (= after ? )) (1+ box) box))))))
20900 ;; Special case: Move point to special position when
20901 ;; currently after it or at beginning of line.
20902 (if (eq special t)
20903 (when (or (> pos after-bullet) (= (point) pos))
20904 (goto-char after-bullet))
20905 ;; Reversed case: Move point to special position when
20906 ;; point was already at beginning of line and command is
20907 ;; repeated.
20908 (when (and (= (point) pos) (eq last-command this-command))
20909 (goto-char after-bullet))))))))
20910 (org-no-warnings
20911 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
20913 (defun org-end-of-line (&optional arg)
20914 "Go to the end of the line.
20915 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
20916 first attempt, and only move to after the tags when the cursor is already
20917 beyond the end of the headline."
20918 (interactive "P")
20919 (let ((special (if (consp org-special-ctrl-a/e)
20920 (cdr org-special-ctrl-a/e)
20921 org-special-ctrl-a/e)))
20922 (cond
20923 ((or (not special) arg
20924 (not (or (org-at-heading-p) (org-at-item-p) (org-at-drawer-p))))
20925 (call-interactively
20926 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
20927 ((fboundp 'move-end-of-line) 'move-end-of-line)
20928 (t 'end-of-line))))
20929 ((org-at-heading-p)
20930 (let ((pos (point)))
20931 (beginning-of-line 1)
20932 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
20933 (if (eq special t)
20934 (if (or (< pos (match-beginning 1))
20935 (= pos (match-end 0)))
20936 (goto-char (match-beginning 1))
20937 (goto-char (match-end 0)))
20938 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
20939 (goto-char (match-end 0))
20940 (goto-char (match-beginning 1))))
20941 (call-interactively (if (fboundp 'move-end-of-line)
20942 'move-end-of-line
20943 'end-of-line)))))
20944 ((org-at-drawer-p)
20945 (move-end-of-line 1)
20946 (when (overlays-at (1- (point))) (backward-char 1)))
20947 ;; At an item: Move before any hidden text.
20948 (t (call-interactively
20949 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
20950 ((fboundp 'move-end-of-line) 'move-end-of-line)
20951 (t 'end-of-line)))))
20952 (org-no-warnings
20953 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
20955 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
20956 (define-key org-mode-map "\C-e" 'org-end-of-line)
20958 (defun org-backward-sentence (&optional arg)
20959 "Go to beginning of sentence, or beginning of table field.
20960 This will call `backward-sentence' or `org-table-beginning-of-field',
20961 depending on context."
20962 (interactive "P")
20963 (cond
20964 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
20965 (t (call-interactively 'backward-sentence))))
20967 (defun org-forward-sentence (&optional arg)
20968 "Go to end of sentence, or end of table field.
20969 This will call `forward-sentence' or `org-table-end-of-field',
20970 depending on context."
20971 (interactive "P")
20972 (cond
20973 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
20974 (t (call-interactively 'forward-sentence))))
20976 (define-key org-mode-map "\M-a" 'org-backward-sentence)
20977 (define-key org-mode-map "\M-e" 'org-forward-sentence)
20979 (defun org-kill-line (&optional arg)
20980 "Kill line, to tags or end of line."
20981 (interactive "P")
20982 (cond
20983 ((or (not org-special-ctrl-k)
20984 (bolp)
20985 (not (org-at-heading-p)))
20986 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
20987 org-ctrl-k-protect-subtree)
20988 (if (or (eq org-ctrl-k-protect-subtree 'error)
20989 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
20990 (error "C-k aborted - would kill hidden subtree")))
20991 (call-interactively
20992 (if (and (boundp 'visual-line-mode) visual-line-mode) 'kill-visual-line 'kill-line)))
20993 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
20994 (kill-region (point) (match-beginning 1))
20995 (org-set-tags nil t))
20996 (t (kill-region (point) (point-at-eol)))))
20998 (define-key org-mode-map "\C-k" 'org-kill-line)
21000 (defun org-yank (&optional arg)
21001 "Yank. If the kill is a subtree, treat it specially.
21002 This command will look at the current kill and check if is a single
21003 subtree, or a series of subtrees[1]. If it passes the test, and if the
21004 cursor is at the beginning of a line or after the stars of a currently
21005 empty headline, then the yank is handled specially. How exactly depends
21006 on the value of the following variables, both set by default.
21008 org-yank-folded-subtrees
21009 When set, the subtree(s) will be folded after insertion, but only
21010 if doing so would now swallow text after the yanked text.
21012 org-yank-adjusted-subtrees
21013 When set, the subtree will be promoted or demoted in order to
21014 fit into the local outline tree structure, which means that the level
21015 will be adjusted so that it becomes the smaller one of the two
21016 *visible* surrounding headings.
21018 Any prefix to this command will cause `yank' to be called directly with
21019 no special treatment. In particular, a simple \\[universal-argument] prefix \
21020 will just
21021 plainly yank the text as it is.
21023 \[1] The test checks if the first non-white line is a heading
21024 and if there are no other headings with fewer stars."
21025 (interactive "P")
21026 (org-yank-generic 'yank arg))
21028 (defun org-yank-generic (command arg)
21029 "Perform some yank-like command.
21031 This function implements the behavior described in the `org-yank'
21032 documentation. However, it has been generalized to work for any
21033 interactive command with similar behavior."
21035 ;; pretend to be command COMMAND
21036 (setq this-command command)
21038 (if arg
21039 (call-interactively command)
21041 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
21042 (and (org-kill-is-subtree-p)
21043 (or (bolp)
21044 (and (looking-at "[ \t]*$")
21045 (string-match
21046 "\\`\\*+\\'"
21047 (buffer-substring (point-at-bol) (point)))))))
21048 swallowp)
21049 (cond
21050 ((and subtreep org-yank-folded-subtrees)
21051 (let ((beg (point))
21052 end)
21053 (if (and subtreep org-yank-adjusted-subtrees)
21054 (org-paste-subtree nil nil 'for-yank)
21055 (call-interactively command))
21057 (setq end (point))
21058 (goto-char beg)
21059 (when (and (bolp) subtreep
21060 (not (setq swallowp
21061 (org-yank-folding-would-swallow-text beg end))))
21062 (org-with-limited-levels
21063 (or (looking-at org-outline-regexp)
21064 (re-search-forward org-outline-regexp-bol end t))
21065 (while (and (< (point) end) (looking-at org-outline-regexp))
21066 (hide-subtree)
21067 (org-cycle-show-empty-lines 'folded)
21068 (condition-case nil
21069 (outline-forward-same-level 1)
21070 (error (goto-char end))))))
21071 (when swallowp
21072 (message
21073 "Inserted text not folded because that would swallow text"))
21075 (goto-char end)
21076 (skip-chars-forward " \t\n\r")
21077 (beginning-of-line 1)
21078 (push-mark beg 'nomsg)))
21079 ((and subtreep org-yank-adjusted-subtrees)
21080 (let ((beg (point-at-bol)))
21081 (org-paste-subtree nil nil 'for-yank)
21082 (push-mark beg 'nomsg)))
21084 (call-interactively command))))))
21086 (defun org-yank-folding-would-swallow-text (beg end)
21087 "Would hide-subtree at BEG swallow any text after END?"
21088 (let (level)
21089 (org-with-limited-levels
21090 (save-excursion
21091 (goto-char beg)
21092 (when (or (looking-at org-outline-regexp)
21093 (re-search-forward org-outline-regexp-bol end t))
21094 (setq level (org-outline-level)))
21095 (goto-char end)
21096 (skip-chars-forward " \t\r\n\v\f")
21097 (if (or (eobp)
21098 (and (bolp) (looking-at org-outline-regexp)
21099 (<= (org-outline-level) level)))
21100 nil ; Nothing would be swallowed
21101 t))))) ; something would swallow
21103 (define-key org-mode-map "\C-y" 'org-yank)
21105 (defun org-truely-invisible-p ()
21106 "Check if point is at a character currently not visible.
21107 This version does not only check the character property, but also
21108 `visible-mode'."
21109 ;; Early versions of noutline don't have `outline-invisible-p'.
21110 (if (org-bound-and-true-p visible-mode)
21112 (outline-invisible-p)))
21114 (defun org-invisible-p2 ()
21115 "Check if point is at a character currently not visible."
21116 (save-excursion
21117 (if (and (eolp) (not (bobp))) (backward-char 1))
21118 ;; Early versions of noutline don't have `outline-invisible-p'.
21119 (outline-invisible-p)))
21121 (defun org-back-to-heading (&optional invisible-ok)
21122 "Call `outline-back-to-heading', but provide a better error message."
21123 (condition-case nil
21124 (outline-back-to-heading invisible-ok)
21125 (error (error "Before first headline at position %d in buffer %s"
21126 (point) (current-buffer)))))
21128 (defun org-beginning-of-defun ()
21129 "Go to the beginning of the subtree, i.e. back to the heading."
21130 (org-back-to-heading))
21131 (defun org-end-of-defun ()
21132 "Go to the end of the subtree."
21133 (org-end-of-subtree nil t))
21135 (defun org-before-first-heading-p ()
21136 "Before first heading?"
21137 (save-excursion
21138 (end-of-line)
21139 (null (re-search-backward org-outline-regexp-bol nil t))))
21141 (defun org-at-heading-p (&optional ignored)
21142 (outline-on-heading-p t))
21143 ;; Compatibility alias with Org versions < 7.8.03
21144 (defalias 'org-on-heading-p 'org-at-heading-p)
21146 (defun org-at-drawer-p nil
21147 "Is cursor at a drawer keyword?"
21148 (save-excursion
21149 (move-beginning-of-line 1)
21150 (looking-at org-drawer-regexp)))
21152 (defun org-at-block-p nil
21153 "Is cursor at a block keyword?"
21154 (save-excursion
21155 (move-beginning-of-line 1)
21156 (looking-at org-block-regexp)))
21158 (defun org-point-at-end-of-empty-headline ()
21159 "If point is at the end of an empty headline, return t, else nil.
21160 If the heading only contains a TODO keyword, it is still still considered
21161 empty."
21162 (and (looking-at "[ \t]*$")
21163 (when org-todo-line-regexp
21164 (save-excursion
21165 (beginning-of-line 1)
21166 (let ((case-fold-search nil))
21167 (looking-at org-todo-line-regexp)
21168 (string= (match-string 3) ""))))))
21170 (defun org-at-heading-or-item-p ()
21171 (or (org-at-heading-p) (org-at-item-p)))
21173 (defun org-at-target-p ()
21174 (or (org-in-regexp org-radio-target-regexp)
21175 (org-in-regexp org-target-regexp)))
21176 ;; Compatibility alias with Org versions < 7.8.03
21177 (defalias 'org-on-target-p 'org-at-target-p)
21179 (defun org-up-heading-all (arg)
21180 "Move to the heading line of which the present line is a subheading.
21181 This function considers both visible and invisible heading lines.
21182 With argument, move up ARG levels."
21183 (if (fboundp 'outline-up-heading-all)
21184 (outline-up-heading-all arg) ; emacs 21 version of outline.el
21185 (outline-up-heading arg t))) ; emacs 22 version of outline.el
21187 (defun org-up-heading-safe ()
21188 "Move to the heading line of which the present line is a subheading.
21189 This version will not throw an error. It will return the level of the
21190 headline found, or nil if no higher level is found.
21192 Also, this function will be a lot faster than `outline-up-heading',
21193 because it relies on stars being the outline starters. This can really
21194 make a significant difference in outlines with very many siblings."
21195 (let (start-level re)
21196 (org-back-to-heading t)
21197 (setq start-level (funcall outline-level))
21198 (if (equal start-level 1)
21200 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
21201 (if (re-search-backward re nil t)
21202 (funcall outline-level)))))
21204 (defun org-first-sibling-p ()
21205 "Is this heading the first child of its parents?"
21206 (interactive)
21207 (let ((re org-outline-regexp-bol)
21208 level l)
21209 (unless (org-at-heading-p t)
21210 (error "Not at a heading"))
21211 (setq level (funcall outline-level))
21212 (save-excursion
21213 (if (not (re-search-backward re nil t))
21215 (setq l (funcall outline-level))
21216 (< l level)))))
21218 (defun org-goto-sibling (&optional previous)
21219 "Goto the next sibling, even if it is invisible.
21220 When PREVIOUS is set, go to the previous sibling instead. Returns t
21221 when a sibling was found. When none is found, return nil and don't
21222 move point."
21223 (let ((fun (if previous 're-search-backward 're-search-forward))
21224 (pos (point))
21225 (re org-outline-regexp-bol)
21226 level l)
21227 (when (condition-case nil (org-back-to-heading t) (error nil))
21228 (setq level (funcall outline-level))
21229 (catch 'exit
21230 (or previous (forward-char 1))
21231 (while (funcall fun re nil t)
21232 (setq l (funcall outline-level))
21233 (when (< l level) (goto-char pos) (throw 'exit nil))
21234 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
21235 (goto-char pos)
21236 nil))))
21238 (defun org-show-siblings ()
21239 "Show all siblings of the current headline."
21240 (save-excursion
21241 (while (org-goto-sibling) (org-flag-heading nil)))
21242 (save-excursion
21243 (while (org-goto-sibling 'previous)
21244 (org-flag-heading nil))))
21246 (defun org-goto-first-child ()
21247 "Goto the first child, even if it is invisible.
21248 Return t when a child was found. Otherwise don't move point and
21249 return nil."
21250 (let (level (pos (point)) (re org-outline-regexp-bol))
21251 (when (condition-case nil (org-back-to-heading t) (error nil))
21252 (setq level (outline-level))
21253 (forward-char 1)
21254 (if (and (re-search-forward re nil t) (> (outline-level) level))
21255 (progn (goto-char (match-beginning 0)) t)
21256 (goto-char pos) nil))))
21258 (defun org-show-hidden-entry ()
21259 "Show an entry where even the heading is hidden."
21260 (save-excursion
21261 (org-show-entry)))
21263 (defun org-flag-heading (flag &optional entry)
21264 "Flag the current heading. FLAG non-nil means make invisible.
21265 When ENTRY is non-nil, show the entire entry."
21266 (save-excursion
21267 (org-back-to-heading t)
21268 ;; Check if we should show the entire entry
21269 (if entry
21270 (progn
21271 (org-show-entry)
21272 (save-excursion
21273 (and (outline-next-heading)
21274 (org-flag-heading nil))))
21275 (outline-flag-region (max (point-min) (1- (point)))
21276 (save-excursion (outline-end-of-heading) (point))
21277 flag))))
21279 (defun org-get-next-sibling ()
21280 "Move to next heading of the same level, and return point.
21281 If there is no such heading, return nil.
21282 This is like outline-next-sibling, but invisible headings are ok."
21283 (let ((level (funcall outline-level)))
21284 (outline-next-heading)
21285 (while (and (not (eobp)) (> (funcall outline-level) level))
21286 (outline-next-heading))
21287 (if (or (eobp) (< (funcall outline-level) level))
21289 (point))))
21291 (defun org-get-last-sibling ()
21292 "Move to previous heading of the same level, and return point.
21293 If there is no such heading, return nil."
21294 (let ((opoint (point))
21295 (level (funcall outline-level)))
21296 (outline-previous-heading)
21297 (when (and (/= (point) opoint) (outline-on-heading-p t))
21298 (while (and (> (funcall outline-level) level)
21299 (not (bobp)))
21300 (outline-previous-heading))
21301 (if (< (funcall outline-level) level)
21303 (point)))))
21305 (defun org-end-of-subtree (&optional invisible-OK to-heading)
21306 ;; This contains an exact copy of the original function, but it uses
21307 ;; `org-back-to-heading', to make it work also in invisible
21308 ;; trees. And is uses an invisible-OK argument.
21309 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
21310 ;; Furthermore, when used inside Org, finding the end of a large subtree
21311 ;; with many children and grandchildren etc, this can be much faster
21312 ;; than the outline version.
21313 (org-back-to-heading invisible-OK)
21314 (let ((first t)
21315 (level (funcall outline-level)))
21316 (if (and (derived-mode-p 'org-mode) (< level 1000))
21317 ;; A true heading (not a plain list item), in Org-mode
21318 ;; This means we can easily find the end by looking
21319 ;; only for the right number of stars. Using a regexp to do
21320 ;; this is so much faster than using a Lisp loop.
21321 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
21322 (forward-char 1)
21323 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
21324 ;; something else, do it the slow way
21325 (while (and (not (eobp))
21326 (or first (> (funcall outline-level) level)))
21327 (setq first nil)
21328 (outline-next-heading)))
21329 (unless to-heading
21330 (if (memq (preceding-char) '(?\n ?\^M))
21331 (progn
21332 ;; Go to end of line before heading
21333 (forward-char -1)
21334 (if (memq (preceding-char) '(?\n ?\^M))
21335 ;; leave blank line before heading
21336 (forward-char -1))))))
21337 (point))
21339 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
21340 "Use Org version in org-mode, for dramatic speed-up."
21341 (if (derived-mode-p 'org-mode)
21342 (progn
21343 (org-end-of-subtree nil t)
21344 (unless (eobp) (backward-char 1)))
21345 ad-do-it))
21347 (defun org-end-of-meta-data-and-drawers ()
21348 "Jump to the first text after meta data and drawers in the current entry.
21349 This will move over empty lines, lines with planning time stamps,
21350 clocking lines, and drawers."
21351 (org-back-to-heading t)
21352 (let ((end (save-excursion (outline-next-heading) (point)))
21353 (re (concat "\\(" org-drawer-regexp "\\)"
21354 "\\|" "[ \t]*" org-keyword-time-regexp)))
21355 (forward-line 1)
21356 (while (re-search-forward re end t)
21357 (if (not (match-end 1))
21358 ;; empty or planning line
21359 (forward-line 1)
21360 ;; a drawer, find the end
21361 (re-search-forward "^[ \t]*:END:" end 'move)
21362 (forward-line 1)))
21363 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
21364 (point)))
21366 (defun org-forward-same-level (arg &optional invisible-ok)
21367 "Move forward to the arg'th subheading at same level as this one.
21368 Stop at the first and last subheadings of a superior heading.
21369 Normally this only looks at visible headings, but when INVISIBLE-OK is non-nil
21370 it wil also look at invisible ones."
21371 (interactive "p")
21372 (org-back-to-heading invisible-ok)
21373 (org-at-heading-p)
21374 (let* ((level (- (match-end 0) (match-beginning 0) 1))
21375 (re (format "^\\*\\{1,%d\\} " level))
21377 (forward-char 1)
21378 (while (> arg 0)
21379 (while (and (re-search-forward re nil 'move)
21380 (setq l (- (match-end 0) (match-beginning 0) 1))
21381 (= l level)
21382 (not invisible-ok)
21383 (progn (backward-char 1) (outline-invisible-p)))
21384 (if (< l level) (setq arg 1)))
21385 (setq arg (1- arg)))
21386 (beginning-of-line 1)))
21388 (defun org-backward-same-level (arg &optional invisible-ok)
21389 "Move backward to the arg'th subheading at same level as this one.
21390 Stop at the first and last subheadings of a superior heading."
21391 (interactive "p")
21392 (org-back-to-heading)
21393 (org-at-heading-p)
21394 (let* ((level (- (match-end 0) (match-beginning 0) 1))
21395 (re (format "^\\*\\{1,%d\\} " level))
21397 (while (> arg 0)
21398 (while (and (re-search-backward re nil 'move)
21399 (setq l (- (match-end 0) (match-beginning 0) 1))
21400 (= l level)
21401 (not invisible-ok)
21402 (outline-invisible-p))
21403 (if (< l level) (setq arg 1)))
21404 (setq arg (1- arg)))))
21406 (defun org-show-subtree ()
21407 "Show everything after this heading at deeper levels."
21408 (interactive)
21409 (outline-flag-region
21410 (point)
21411 (save-excursion
21412 (org-end-of-subtree t t))
21413 nil))
21415 (defun org-show-entry ()
21416 "Show the body directly following this heading.
21417 Show the heading too, if it is currently invisible."
21418 (interactive)
21419 (save-excursion
21420 (condition-case nil
21421 (progn
21422 (org-back-to-heading t)
21423 (outline-flag-region
21424 (max (point-min) (1- (point)))
21425 (save-excursion
21426 (if (re-search-forward
21427 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
21428 (match-beginning 1)
21429 (point-max)))
21430 nil)
21431 (org-cycle-hide-drawers 'children))
21432 (error nil))))
21434 (defun org-make-options-regexp (kwds &optional extra)
21435 "Make a regular expression for keyword lines."
21436 (concat
21438 "#?[ \t]*\\+\\("
21439 (mapconcat 'regexp-quote kwds "\\|")
21440 (if extra (concat "\\|" extra))
21441 "\\):[ \t]*"
21442 "\\(.*\\)"))
21444 ;; Make isearch reveal the necessary context
21445 (defun org-isearch-end ()
21446 "Reveal context after isearch exits."
21447 (when isearch-success ; only if search was successful
21448 (if (featurep 'xemacs)
21449 ;; Under XEmacs, the hook is run in the correct place,
21450 ;; we directly show the context.
21451 (org-show-context 'isearch)
21452 ;; In Emacs the hook runs *before* restoring the overlays.
21453 ;; So we have to use a one-time post-command-hook to do this.
21454 ;; (Emacs 22 has a special variable, see function `org-mode')
21455 (unless (and (boundp 'isearch-mode-end-hook-quit)
21456 isearch-mode-end-hook-quit)
21457 ;; Only when the isearch was not quitted.
21458 (org-add-hook 'post-command-hook 'org-isearch-post-command
21459 'append 'local)))))
21461 (defun org-isearch-post-command ()
21462 "Remove self from hook, and show context."
21463 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
21464 (org-show-context 'isearch))
21467 ;;;; Integration with and fixes for other packages
21469 ;;; Imenu support
21471 (defvar org-imenu-markers nil
21472 "All markers currently used by Imenu.")
21473 (make-variable-buffer-local 'org-imenu-markers)
21475 (defun org-imenu-new-marker (&optional pos)
21476 "Return a new marker for use by Imenu, and remember the marker."
21477 (let ((m (make-marker)))
21478 (move-marker m (or pos (point)))
21479 (push m org-imenu-markers)
21482 (defun org-imenu-get-tree ()
21483 "Produce the index for Imenu."
21484 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
21485 (setq org-imenu-markers nil)
21486 (let* ((n org-imenu-depth)
21487 (re (concat "^" (org-get-limited-outline-regexp)))
21488 (subs (make-vector (1+ n) nil))
21489 (last-level 0)
21490 m level head)
21491 (save-excursion
21492 (save-restriction
21493 (widen)
21494 (goto-char (point-max))
21495 (while (re-search-backward re nil t)
21496 (setq level (org-reduced-level (funcall outline-level)))
21497 (when (and (<= level n)
21498 (looking-at org-complex-heading-regexp))
21499 (setq head (org-link-display-format
21500 (org-match-string-no-properties 4))
21501 m (org-imenu-new-marker))
21502 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
21503 (if (>= level last-level)
21504 (push (cons head m) (aref subs level))
21505 (push (cons head (aref subs (1+ level))) (aref subs level))
21506 (loop for i from (1+ level) to n do (aset subs i nil)))
21507 (setq last-level level)))))
21508 (aref subs 1)))
21510 (eval-after-load "imenu"
21511 '(progn
21512 (add-hook 'imenu-after-jump-hook
21513 (lambda ()
21514 (if (derived-mode-p 'org-mode)
21515 (org-show-context 'org-goto))))))
21517 (defun org-link-display-format (link)
21518 "Replace a link with either the description, or the link target
21519 if no description is present"
21520 (save-match-data
21521 (if (string-match org-bracket-link-analytic-regexp link)
21522 (replace-match (if (match-end 5)
21523 (match-string 5 link)
21524 (concat (match-string 1 link)
21525 (match-string 3 link)))
21526 nil t link)
21527 link)))
21529 (defun org-toggle-link-display ()
21530 "Toggle the literal or descriptive display of links."
21531 (interactive)
21532 (if org-descriptive-links
21533 (progn (org-remove-from-invisibility-spec '(org-link))
21534 (org-restart-font-lock)
21535 (setq org-descriptive-links nil))
21536 (progn (add-to-invisibility-spec '(org-link))
21537 (org-restart-font-lock)
21538 (setq org-descriptive-links t))))
21540 ;; Speedbar support
21542 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
21543 "Overlay marking the agenda restriction line in speedbar.")
21544 (overlay-put org-speedbar-restriction-lock-overlay
21545 'face 'org-agenda-restriction-lock)
21546 (overlay-put org-speedbar-restriction-lock-overlay
21547 'help-echo "Agendas are currently limited to this item.")
21548 (org-detach-overlay org-speedbar-restriction-lock-overlay)
21550 (defun org-speedbar-set-agenda-restriction ()
21551 "Restrict future agenda commands to the location at point in speedbar.
21552 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
21553 (interactive)
21554 (require 'org-agenda)
21555 (let (p m tp np dir txt)
21556 (cond
21557 ((setq p (text-property-any (point-at-bol) (point-at-eol)
21558 'org-imenu t))
21559 (setq m (get-text-property p 'org-imenu-marker))
21560 (with-current-buffer (marker-buffer m)
21561 (goto-char m)
21562 (org-agenda-set-restriction-lock 'subtree)))
21563 ((setq p (text-property-any (point-at-bol) (point-at-eol)
21564 'speedbar-function 'speedbar-find-file))
21565 (setq tp (previous-single-property-change
21566 (1+ p) 'speedbar-function)
21567 np (next-single-property-change
21568 tp 'speedbar-function)
21569 dir (speedbar-line-directory)
21570 txt (buffer-substring-no-properties (or tp (point-min))
21571 (or np (point-max))))
21572 (with-current-buffer (find-file-noselect
21573 (let ((default-directory dir))
21574 (expand-file-name txt)))
21575 (unless (derived-mode-p 'org-mode)
21576 (error "Cannot restrict to non-Org-mode file"))
21577 (org-agenda-set-restriction-lock 'file)))
21578 (t (error "Don't know how to restrict Org-mode's agenda")))
21579 (move-overlay org-speedbar-restriction-lock-overlay
21580 (point-at-bol) (point-at-eol))
21581 (setq current-prefix-arg nil)
21582 (org-agenda-maybe-redo)))
21584 (eval-after-load "speedbar"
21585 '(progn
21586 (speedbar-add-supported-extension ".org")
21587 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
21588 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
21589 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
21590 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
21591 (add-hook 'speedbar-visiting-tag-hook
21592 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
21594 ;;; Fixes and Hacks for problems with other packages
21596 ;; Make flyspell not check words in links, to not mess up our keymap
21597 (defun org-mode-flyspell-verify ()
21598 "Don't let flyspell put overlays at active buttons, or on
21599 {todo,all-time,additional-option-like}-keywords."
21600 (let ((pos (max (1- (point)) (point-min)))
21601 (word (thing-at-point 'word)))
21602 (and (not (get-text-property pos 'keymap))
21603 (not (get-text-property pos 'org-no-flyspell))
21604 (not (member word org-todo-keywords-1))
21605 (not (member word org-all-time-keywords))
21606 (not (member word org-additional-option-like-keywords)))))
21608 (defun org-remove-flyspell-overlays-in (beg end)
21609 "Remove flyspell overlays in region."
21610 (and (org-bound-and-true-p flyspell-mode)
21611 (fboundp 'flyspell-delete-region-overlays)
21612 (flyspell-delete-region-overlays beg end))
21613 (add-text-properties beg end '(org-no-flyspell t)))
21615 ;; Make `bookmark-jump' shows the jump location if it was hidden.
21616 (eval-after-load "bookmark"
21617 '(if (boundp 'bookmark-after-jump-hook)
21618 ;; We can use the hook
21619 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
21620 ;; Hook not available, use advice
21621 (defadvice bookmark-jump (after org-make-visible activate)
21622 "Make the position visible."
21623 (org-bookmark-jump-unhide))))
21625 ;; Make sure saveplace shows the location if it was hidden
21626 (eval-after-load "saveplace"
21627 '(defadvice save-place-find-file-hook (after org-make-visible activate)
21628 "Make the position visible."
21629 (org-bookmark-jump-unhide)))
21631 ;; Make sure ecb shows the location if it was hidden
21632 (eval-after-load "ecb"
21633 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
21634 "Make hierarchy visible when jumping into location from ECB tree buffer."
21635 (if (derived-mode-p 'org-mode)
21636 (org-show-context))))
21638 (defun org-bookmark-jump-unhide ()
21639 "Unhide the current position, to show the bookmark location."
21640 (and (derived-mode-p 'org-mode)
21641 (or (outline-invisible-p)
21642 (save-excursion (goto-char (max (point-min) (1- (point))))
21643 (outline-invisible-p)))
21644 (org-show-context 'bookmark-jump)))
21646 ;; Make session.el ignore our circular variable
21647 (eval-after-load "session"
21648 '(add-to-list 'session-globals-exclude 'org-mark-ring))
21650 ;;;; Experimental code
21652 (defun org-closed-in-range ()
21653 "Sparse tree of items closed in a certain time range.
21654 Still experimental, may disappear in the future."
21655 (interactive)
21656 ;; Get the time interval from the user.
21657 (let* ((time1 (org-float-time
21658 (org-read-date nil 'to-time nil "Starting date: ")))
21659 (time2 (org-float-time
21660 (org-read-date nil 'to-time nil "End date:")))
21661 ;; callback function
21662 (callback (lambda ()
21663 (let ((time
21664 (org-float-time
21665 (apply 'encode-time
21666 (org-parse-time-string
21667 (match-string 1))))))
21668 ;; check if time in interval
21669 (and (>= time time1) (<= time time2))))))
21670 ;; make tree, check each match with the callback
21671 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
21673 ;;;; Finish up
21675 (provide 'org)
21677 (run-hooks 'org-load-hook)
21679 ;;; org.el ends here