org.el: Fix bug in `org-fill-paragraph'.
[org-mode/org-mode-NeilSmithlineMods.git] / lisp / org.el
blob3fb2a96b4f73c97b23425d333f0c7e9e61d44781
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 (setq 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 here (insert version))
227 (message version)))
229 ;;; Compatibility constants
231 ;;; The custom variables
233 (defgroup org nil
234 "Outline-based notes management and organizer."
235 :tag "Org"
236 :group 'outlines
237 :group 'calendar)
239 (defcustom org-mode-hook nil
240 "Mode hook for Org-mode, run after the mode was turned on."
241 :group 'org
242 :type 'hook)
244 (defcustom org-load-hook nil
245 "Hook that is run after org.el has been loaded."
246 :group 'org
247 :type 'hook)
249 (defcustom org-log-buffer-setup-hook nil
250 "Hook that is run after an Org log buffer is created."
251 :group 'org
252 :version "24.1"
253 :type 'hook)
255 (defvar org-modules) ; defined below
256 (defvar org-modules-loaded nil
257 "Have the modules been loaded already?")
259 (defun org-load-modules-maybe (&optional force)
260 "Load all extensions listed in `org-modules'."
261 (when (or force (not org-modules-loaded))
262 (mapc (lambda (ext)
263 (condition-case nil (require ext)
264 (error (message "Problems while trying to load feature `%s'" ext))))
265 org-modules)
266 (setq org-modules-loaded t)))
268 (defun org-set-modules (var value)
269 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
270 (set var value)
271 (when (featurep 'org)
272 (org-load-modules-maybe 'force)))
274 (when (org-bound-and-true-p org-modules)
275 (let ((a (member 'org-infojs org-modules)))
276 (and a (setcar a 'org-jsinfo))))
278 (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)
279 "Modules that should always be loaded together with org.el.
280 If a description starts with <C>, the file is not part of Emacs
281 and loading it will require that you have downloaded and properly installed
282 the org-mode distribution.
284 You can also use this system to load external packages (i.e. neither Org
285 core modules, nor modules from the CONTRIB directory). Just add symbols
286 to the end of the list. If the package is called org-xyz.el, then you need
287 to add the symbol `xyz', and the package must have a call to
289 (provide 'org-xyz)"
290 :group 'org
291 :set 'org-set-modules
292 :type
293 '(set :greedy t
294 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
295 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
296 (const :tag " crypt: Encryption of subtrees" org-crypt)
297 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
298 (const :tag " docview: Links to doc-view buffers" org-docview)
299 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
300 (const :tag " id: Global IDs for identifying entries" org-id)
301 (const :tag " info: Links to Info nodes" org-info)
302 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
303 (const :tag " habit: Track your consistency with habits" org-habit)
304 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
305 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
306 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
307 (const :tag " mew Links to Mew folders/messages" org-mew)
308 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
309 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
310 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
311 (const :tag " special-blocks: Turn blocks into LaTeX envs and HTML divs" org-special-blocks)
312 (const :tag " vm: Links to VM folders/messages" org-vm)
313 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
314 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
315 (const :tag " mouse: Additional mouse support" org-mouse)
316 (const :tag " TaskJuggler: Export tasks to a TaskJuggler project" org-taskjuggler)
318 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
319 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
320 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
321 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
322 (const :tag "C collector: Collect properties into tables" org-collector)
323 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
324 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
325 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
326 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
327 (const :tag "C eval: Include command output as text" org-eval)
328 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
329 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
330 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
331 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
332 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
334 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
336 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
337 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
338 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
339 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
340 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
341 (const :tag "C mac-link-grabber Grab links and URLs from various Mac applications" org-mac-link-grabber)
342 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
343 (const :tag "C mtags: Support for muse-like tags" org-mtags)
344 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
345 (const :tag "C registry: A registry for Org-mode links" org-registry)
346 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
347 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
348 (const :tag "C secretary: Team management with org-mode" org-secretary)
349 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
350 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
351 (const :tag "C track: Keep up with Org-mode development" org-track)
352 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
353 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
354 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
356 (defcustom org-support-shift-select nil
357 "Non-nil means make shift-cursor commands select text when possible.
359 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
360 start selecting a region, or enlarge regions started in this way.
361 In Org-mode, in special contexts, these same keys are used for
362 other purposes, important enough to compete with shift selection.
363 Org tries to balance these needs by supporting `shift-select-mode'
364 outside these special contexts, under control of this variable.
366 The default of this variable is nil, to avoid confusing behavior. Shifted
367 cursor keys will then execute Org commands in the following contexts:
368 - on a headline, changing TODO state (left/right) and priority (up/down)
369 - on a time stamp, changing the time
370 - in a plain list item, changing the bullet type
371 - in a property definition line, switching between allowed values
372 - in the BEGIN line of a clock table (changing the time block).
373 Outside these contexts, the commands will throw an error.
375 When this variable is t and the cursor is not in a special
376 context, Org-mode will support shift-selection for making and
377 enlarging regions. To make this more effective, the bullet
378 cycling will no longer happen anywhere in an item line, but only
379 if the cursor is exactly on the bullet.
381 If you set this variable to the symbol `always', then the keys
382 will not be special in headlines, property lines, and item lines,
383 to make shift selection work there as well. If this is what you
384 want, you can use the following alternative commands: `C-c C-t'
385 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
386 can be used to switch TODO sets, `C-c -' to cycle item bullet
387 types, and properties can be edited by hand or in column view.
389 However, when the cursor is on a timestamp, shift-cursor commands
390 will still edit the time stamp - this is just too good to give up.
392 XEmacs user should have this variable set to nil, because
393 `shift-select-mode' is in Emacs 23 or later only."
394 :group 'org
395 :type '(choice
396 (const :tag "Never" nil)
397 (const :tag "When outside special context" t)
398 (const :tag "Everywhere except timestamps" always)))
400 (defcustom org-loop-over-headlines-in-active-region nil
401 "Shall some commands act upon headlines in the active region?
403 When set to `t', some commands will be performed in all headlines
404 within the active region.
406 When set to `start-level', some commands will be performed in all
407 headlines within the active region, provided that these headlines
408 are of the same level than the first one.
410 When set to a string, those commands will be performed on the
411 matching headlines within the active region. Such string must be
412 a tags/property/todo match as it is used in the agenda tags view.
414 The list of commands is: `org-schedule', `org-deadline',
415 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
416 `org-archive-to-archive-sibling'. The archiving commands skip
417 already archived entries."
418 :type '(choice (const :tag "Don't loop" nil)
419 (const :tag "All headlines in active region" t)
420 (const :tag "In active region, headlines at the same level than the first one" 'start-level)
421 (string :tag "Tags/Property/Todo matcher"))
422 :version "24.1"
423 :group 'org-todo
424 :group 'org-archive)
426 (defgroup org-startup nil
427 "Options concerning startup of Org-mode."
428 :tag "Org Startup"
429 :group 'org)
431 (defcustom org-startup-folded t
432 "Non-nil means entering Org-mode will switch to OVERVIEW.
433 This can also be configured on a per-file basis by adding one of
434 the following lines anywhere in the buffer:
436 #+STARTUP: fold (or `overview', this is equivalent)
437 #+STARTUP: nofold (or `showall', this is equivalent)
438 #+STARTUP: content
439 #+STARTUP: showeverything"
440 :group 'org-startup
441 :type '(choice
442 (const :tag "nofold: show all" nil)
443 (const :tag "fold: overview" t)
444 (const :tag "content: all headlines" content)
445 (const :tag "show everything, even drawers" showeverything)))
447 (defcustom org-startup-truncated t
448 "Non-nil means entering Org-mode will set `truncate-lines'.
449 This is useful since some lines containing links can be very long and
450 uninteresting. Also tables look terrible when wrapped."
451 :group 'org-startup
452 :type 'boolean)
454 (defcustom org-startup-indented nil
455 "Non-nil means turn on `org-indent-mode' on startup.
456 This can also be configured on a per-file basis by adding one of
457 the following lines anywhere in the buffer:
459 #+STARTUP: indent
460 #+STARTUP: noindent"
461 :group 'org-structure
462 :type '(choice
463 (const :tag "Not" nil)
464 (const :tag "Globally (slow on startup in large files)" t)))
466 (defcustom org-use-sub-superscripts t
467 "Non-nil means interpret \"_\" and \"^\" for export.
468 When this option is turned on, you can use TeX-like syntax for sub- and
469 superscripts. Several characters after \"_\" or \"^\" will be
470 considered as a single item - so grouping with {} is normally not
471 needed. For example, the following things will be parsed as single
472 sub- or superscripts.
474 10^24 or 10^tau several digits will be considered 1 item.
475 10^-12 or 10^-tau a leading sign with digits or a word
476 x^2-y^3 will be read as x^2 - y^3, because items are
477 terminated by almost any nonword/nondigit char.
478 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
480 Still, ambiguity is possible - so when in doubt use {} to enclose the
481 sub/superscript. If you set this variable to the symbol `{}',
482 the braces are *required* in order to trigger interpretations as
483 sub/superscript. This can be helpful in documents that need \"_\"
484 frequently in plain text.
486 Not all export backends support this, but HTML does.
488 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
489 :group 'org-startup
490 :group 'org-export-translation
491 :version "24.1"
492 :type '(choice
493 (const :tag "Always interpret" t)
494 (const :tag "Only with braces" {})
495 (const :tag "Never interpret" nil)))
497 (if (fboundp 'defvaralias)
498 (defvaralias 'org-export-with-sub-superscripts 'org-use-sub-superscripts))
501 (defcustom org-startup-with-beamer-mode nil
502 "Non-nil means turn on `org-beamer-mode' on startup.
503 This can also be configured on a per-file basis by adding one of
504 the following lines anywhere in the buffer:
506 #+STARTUP: beamer"
507 :group 'org-startup
508 :version "24.1"
509 :type 'boolean)
511 (defcustom org-startup-align-all-tables nil
512 "Non-nil means align all tables when visiting a file.
513 This is useful when the column width in tables is forced with <N> cookies
514 in table fields. Such tables will look correct only after the first re-align.
515 This can also be configured on a per-file basis by adding one of
516 the following lines anywhere in the buffer:
517 #+STARTUP: align
518 #+STARTUP: noalign"
519 :group 'org-startup
520 :type 'boolean)
522 (defcustom org-startup-with-inline-images nil
523 "Non-nil means show inline images when loading a new Org file.
524 This can also be configured on a per-file basis by adding one of
525 the following lines anywhere in the buffer:
526 #+STARTUP: inlineimages
527 #+STARTUP: noinlineimages"
528 :group 'org-startup
529 :version "24.1"
530 :type 'boolean)
532 (defcustom org-insert-mode-line-in-empty-file nil
533 "Non-nil means insert the first line setting Org-mode in empty files.
534 When the function `org-mode' is called interactively in an empty file, this
535 normally means that the file name does not automatically trigger Org-mode.
536 To ensure that the file will always be in Org-mode in the future, a
537 line enforcing Org-mode will be inserted into the buffer, if this option
538 has been set."
539 :group 'org-startup
540 :type 'boolean)
542 (defcustom org-replace-disputed-keys nil
543 "Non-nil means use alternative key bindings for some keys.
544 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
545 These keys are also used by other packages like shift-selection-mode'
546 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
547 If you want to use Org-mode together with one of these other modes,
548 or more generally if you would like to move some Org-mode commands to
549 other keys, set this variable and configure the keys with the variable
550 `org-disputed-keys'.
552 This option is only relevant at load-time of Org-mode, and must be set
553 *before* org.el is loaded. Changing it requires a restart of Emacs to
554 become effective."
555 :group 'org-startup
556 :type 'boolean)
558 (defcustom org-use-extra-keys nil
559 "Non-nil means use extra key sequence definitions for certain commands.
560 This happens automatically if you run XEmacs or if `window-system'
561 is nil. This variable lets you do the same manually. You must
562 set it before loading org.
564 Example: on Carbon Emacs 22 running graphically, with an external
565 keyboard on a Powerbook, the default way of setting M-left might
566 not work for either Alt or ESC. Setting this variable will make
567 it work for ESC."
568 :group 'org-startup
569 :type 'boolean)
571 (if (fboundp 'defvaralias)
572 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
574 (defcustom org-disputed-keys
575 '(([(shift up)] . [(meta p)])
576 ([(shift down)] . [(meta n)])
577 ([(shift left)] . [(meta -)])
578 ([(shift right)] . [(meta +)])
579 ([(control shift right)] . [(meta shift +)])
580 ([(control shift left)] . [(meta shift -)]))
581 "Keys for which Org-mode and other modes compete.
582 This is an alist, cars are the default keys, second element specifies
583 the alternative to use when `org-replace-disputed-keys' is t.
585 Keys can be specified in any syntax supported by `define-key'.
586 The value of this option takes effect only at Org-mode's startup,
587 therefore you'll have to restart Emacs to apply it after changing."
588 :group 'org-startup
589 :type 'alist)
591 (defun org-key (key)
592 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
593 Or return the original if not disputed.
594 Also apply the translations defined in `org-xemacs-key-equivalents'."
595 (when org-replace-disputed-keys
596 (let* ((nkey (key-description key))
597 (x (org-find-if (lambda (x)
598 (equal (key-description (car x)) nkey))
599 org-disputed-keys)))
600 (setq key (if x (cdr x) key))))
601 (when (featurep 'xemacs)
602 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
603 key)
605 (defun org-find-if (predicate seq)
606 (catch 'exit
607 (while seq
608 (if (funcall predicate (car seq))
609 (throw 'exit (car seq))
610 (pop seq)))))
612 (defun org-defkey (keymap key def)
613 "Define a key, possibly translated, as returned by `org-key'."
614 (define-key keymap (org-key key) def))
616 (defcustom org-ellipsis nil
617 "The ellipsis to use in the Org-mode outline.
618 When nil, just use the standard three dots. When a string, use that instead,
619 When a face, use the standard 3 dots, but with the specified face.
620 The change affects only Org-mode (which will then use its own display table).
621 Changing this requires executing `M-x org-mode' in a buffer to become
622 effective."
623 :group 'org-startup
624 :type '(choice (const :tag "Default" nil)
625 (face :tag "Face" :value org-warning)
626 (string :tag "String" :value "...#")))
628 (defvar org-display-table nil
629 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
631 (defgroup org-keywords nil
632 "Keywords in Org-mode."
633 :tag "Org Keywords"
634 :group 'org)
636 (defcustom org-deadline-string "DEADLINE:"
637 "String to mark deadline entries.
638 A deadline is this string, followed by a time stamp. Should be a word,
639 terminated by a colon. You can insert a schedule keyword and
640 a timestamp with \\[org-deadline].
641 Changes become only effective after restarting Emacs."
642 :group 'org-keywords
643 :type 'string)
645 (defcustom org-scheduled-string "SCHEDULED:"
646 "String to mark scheduled TODO entries.
647 A schedule is this string, followed by a time stamp. Should be a word,
648 terminated by a colon. You can insert a schedule keyword and
649 a timestamp with \\[org-schedule].
650 Changes become only effective after restarting Emacs."
651 :group 'org-keywords
652 :type 'string)
654 (defcustom org-closed-string "CLOSED:"
655 "String used as the prefix for timestamps logging closing a TODO entry."
656 :group 'org-keywords
657 :type 'string)
659 (defcustom org-clock-string "CLOCK:"
660 "String used as prefix for timestamps clocking work hours on an item."
661 :group 'org-keywords
662 :type 'string)
664 (defcustom org-comment-string "COMMENT"
665 "Entries starting with this keyword will never be exported.
666 An entry can be toggled between COMMENT and normal with
667 \\[org-toggle-comment].
668 Changes become only effective after restarting Emacs."
669 :group 'org-keywords
670 :type 'string)
672 (defcustom org-quote-string "QUOTE"
673 "Entries starting with this keyword will be exported in fixed-width font.
674 Quoting applies only to the text in the entry following the headline, and does
675 not extend beyond the next headline, even if that is lower level.
676 An entry can be toggled between QUOTE and normal with
677 \\[org-toggle-fixed-width-section]."
678 :group 'org-keywords
679 :type 'string)
681 (defconst org-repeat-re
682 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
683 "Regular expression for specifying repeated events.
684 After a match, group 1 contains the repeat expression.")
686 (defgroup org-structure nil
687 "Options concerning the general structure of Org-mode files."
688 :tag "Org Structure"
689 :group 'org)
691 (defgroup org-reveal-location nil
692 "Options about how to make context of a location visible."
693 :tag "Org Reveal Location"
694 :group 'org-structure)
696 (defconst org-context-choice
697 '(choice
698 (const :tag "Always" t)
699 (const :tag "Never" nil)
700 (repeat :greedy t :tag "Individual contexts"
701 (cons
702 (choice :tag "Context"
703 (const agenda)
704 (const org-goto)
705 (const occur-tree)
706 (const tags-tree)
707 (const link-search)
708 (const mark-goto)
709 (const bookmark-jump)
710 (const isearch)
711 (const default))
712 (boolean))))
713 "Contexts for the reveal options.")
715 (defcustom org-show-hierarchy-above '((default . t))
716 "Non-nil means show full hierarchy when revealing a location.
717 Org-mode often shows locations in an org-mode file which might have
718 been invisible before. When this is set, the hierarchy of headings
719 above the exposed location is shown.
720 Turning this off for example for sparse trees makes them very compact.
721 Instead of t, this can also be an alist specifying this option for different
722 contexts. Valid contexts are
723 agenda when exposing an entry from the agenda
724 org-goto when using the command `org-goto' on key C-c C-j
725 occur-tree when using the command `org-occur' on key C-c /
726 tags-tree when constructing a sparse tree based on tags matches
727 link-search when exposing search matches associated with a link
728 mark-goto when exposing the jump goal of a mark
729 bookmark-jump when exposing a bookmark location
730 isearch when exiting from an incremental search
731 default default for all contexts not set explicitly"
732 :group 'org-reveal-location
733 :type org-context-choice)
735 (defcustom org-show-following-heading '((default . nil))
736 "Non-nil means show following heading when revealing a location.
737 Org-mode often shows locations in an org-mode file which might have
738 been invisible before. When this is set, the heading following the
739 match is shown.
740 Turning this off for example for sparse trees makes them very compact,
741 but makes it harder to edit the location of the match. In such a case,
742 use the command \\[org-reveal] to show more context.
743 Instead of t, this can also be an alist specifying this option for different
744 contexts. See `org-show-hierarchy-above' for valid contexts."
745 :group 'org-reveal-location
746 :type org-context-choice)
748 (defcustom org-show-siblings '((default . nil) (isearch t))
749 "Non-nil means show all sibling heading when revealing a location.
750 Org-mode often shows locations in an org-mode file which might have
751 been invisible before. When this is set, the sibling of the current entry
752 heading are all made visible. If `org-show-hierarchy-above' is t,
753 the same happens on each level of the hierarchy above the current entry.
755 By default this is on for the isearch context, off for all other contexts.
756 Turning this off for example for sparse trees makes them very compact,
757 but makes it harder to edit the location of the match. In such a case,
758 use the command \\[org-reveal] to show more context.
759 Instead of t, this can also be an alist specifying this option for different
760 contexts. See `org-show-hierarchy-above' for valid contexts."
761 :group 'org-reveal-location
762 :type org-context-choice)
764 (defcustom org-show-entry-below '((default . nil))
765 "Non-nil means show the entry below a headline when revealing a location.
766 Org-mode often shows locations in an org-mode file which might have
767 been invisible before. When this is set, the text below the headline that is
768 exposed is also shown.
770 By default this is off for all contexts.
771 Instead of t, this can also be an alist specifying this option for different
772 contexts. See `org-show-hierarchy-above' for valid contexts."
773 :group 'org-reveal-location
774 :type org-context-choice)
776 (defcustom org-indirect-buffer-display 'other-window
777 "How should indirect tree buffers be displayed?
778 This applies to indirect buffers created with the commands
779 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
780 Valid values are:
781 current-window Display in the current window
782 other-window Just display in another window.
783 dedicated-frame Create one new frame, and re-use it each time.
784 new-frame Make a new frame each time. Note that in this case
785 previously-made indirect buffers are kept, and you need to
786 kill these buffers yourself."
787 :group 'org-structure
788 :group 'org-agenda-windows
789 :type '(choice
790 (const :tag "In current window" current-window)
791 (const :tag "In current frame, other window" other-window)
792 (const :tag "Each time a new frame" new-frame)
793 (const :tag "One dedicated frame" dedicated-frame)))
795 (defcustom org-use-speed-commands nil
796 "Non-nil means activate single letter commands at beginning of a headline.
797 This may also be a function to test for appropriate locations where speed
798 commands should be active."
799 :group 'org-structure
800 :type '(choice
801 (const :tag "Never" nil)
802 (const :tag "At beginning of headline stars" t)
803 (function)))
805 (defcustom org-speed-commands-user nil
806 "Alist of additional speed commands.
807 This list will be checked before `org-speed-commands-default'
808 when the variable `org-use-speed-commands' is non-nil
809 and when the cursor is at the beginning of a headline.
810 The car if each entry is a string with a single letter, which must
811 be assigned to `self-insert-command' in the global map.
812 The cdr is either a command to be called interactively, a function
813 to be called, or a form to be evaluated.
814 An entry that is just a list with a single string will be interpreted
815 as a descriptive headline that will be added when listing the speed
816 commands in the Help buffer using the `?' speed command."
817 :group 'org-structure
818 :type '(repeat :value ("k" . ignore)
819 (choice :value ("k" . ignore)
820 (list :tag "Descriptive Headline" (string :tag "Headline"))
821 (cons :tag "Letter and Command"
822 (string :tag "Command letter")
823 (choice
824 (function)
825 (sexp))))))
827 (defgroup org-cycle nil
828 "Options concerning visibility cycling in Org-mode."
829 :tag "Org Cycle"
830 :group 'org-structure)
832 (defcustom org-cycle-skip-children-state-if-no-children t
833 "Non-nil means skip CHILDREN state in entries that don't have any."
834 :group 'org-cycle
835 :type 'boolean)
837 (defcustom org-cycle-max-level nil
838 "Maximum level which should still be subject to visibility cycling.
839 Levels higher than this will, for cycling, be treated as text, not a headline.
840 When `org-odd-levels-only' is set, a value of N in this variable actually
841 means 2N-1 stars as the limiting headline.
842 When nil, cycle all levels.
843 Note that the limiting level of cycling is also influenced by
844 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
845 `org-inlinetask-min-level' is, cycling will be limited to levels one less
846 than its value."
847 :group 'org-cycle
848 :type '(choice
849 (const :tag "No limit" nil)
850 (integer :tag "Maximum level")))
852 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK" "RESULTS")
853 "Names of drawers. Drawers are not opened by cycling on the headline above.
854 Drawers only open with a TAB on the drawer line itself. A drawer looks like
855 this:
856 :DRAWERNAME:
857 .....
858 :END:
859 The drawer \"PROPERTIES\" is special for capturing properties through
860 the property API.
862 Drawers can be defined on the per-file basis with a line like:
864 #+DRAWERS: HIDDEN STATE PROPERTIES"
865 :group 'org-structure
866 :group 'org-cycle
867 :type '(repeat (string :tag "Drawer Name")))
869 (defcustom org-hide-block-startup nil
870 "Non-nil means entering Org-mode will fold all blocks.
871 This can also be set in on a per-file basis with
873 #+STARTUP: hideblocks
874 #+STARTUP: showblocks"
875 :group 'org-startup
876 :group 'org-cycle
877 :type 'boolean)
879 (defcustom org-cycle-global-at-bob nil
880 "Cycle globally if cursor is at beginning of buffer and not at a headline.
881 This makes it possible to do global cycling without having to use S-TAB or
882 \\[universal-argument] TAB. For this special case to work, the first line \
883 of the buffer
884 must not be a headline - it may be empty or some other text. When used in
885 this way, `org-cycle-hook' is disables temporarily, to make sure the
886 cursor stays at the beginning of the buffer.
887 When this option is nil, don't do anything special at the beginning
888 of the buffer."
889 :group 'org-cycle
890 :type 'boolean)
892 (defcustom org-cycle-level-after-item/entry-creation t
893 "Non-nil means cycle entry level or item indentation in new empty entries.
895 When the cursor is at the end of an empty headline, i.e with only stars
896 and maybe a TODO keyword, TAB will then switch the entry to become a child,
897 and then all possible ancestor states, before returning to the original state.
898 This makes data entry extremely fast: M-RET to create a new headline,
899 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
901 When the cursor is at the end of an empty plain list item, one TAB will
902 make it a subitem, two or more tabs will back up to make this an item
903 higher up in the item hierarchy."
904 :group 'org-cycle
905 :type 'boolean)
907 (defcustom org-cycle-emulate-tab t
908 "Where should `org-cycle' emulate TAB.
909 nil Never
910 white Only in completely white lines
911 whitestart Only at the beginning of lines, before the first non-white char
912 t Everywhere except in headlines
913 exc-hl-bol Everywhere except at the start of a headline
914 If TAB is used in a place where it does not emulate TAB, the current subtree
915 visibility is cycled."
916 :group 'org-cycle
917 :type '(choice (const :tag "Never" nil)
918 (const :tag "Only in completely white lines" white)
919 (const :tag "Before first char in a line" whitestart)
920 (const :tag "Everywhere except in headlines" t)
921 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
924 (defcustom org-cycle-separator-lines 2
925 "Number of empty lines needed to keep an empty line between collapsed trees.
926 If you leave an empty line between the end of a subtree and the following
927 headline, this empty line is hidden when the subtree is folded.
928 Org-mode will leave (exactly) one empty line visible if the number of
929 empty lines is equal or larger to the number given in this variable.
930 So the default 2 means at least 2 empty lines after the end of a subtree
931 are needed to produce free space between a collapsed subtree and the
932 following headline.
934 If the number is negative, and the number of empty lines is at least -N,
935 all empty lines are shown.
937 Special case: when 0, never leave empty lines in collapsed view."
938 :group 'org-cycle
939 :type 'integer)
940 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
942 (defcustom org-pre-cycle-hook nil
943 "Hook that is run before visibility cycling is happening.
944 The function(s) in this hook must accept a single argument which indicates
945 the new state that will be set right after running this hook. The
946 argument is a symbol. Before a global state change, it can have the values
947 `overview', `content', or `all'. Before a local state change, it can have
948 the values `folded', `children', or `subtree'."
949 :group 'org-cycle
950 :type 'hook)
952 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
953 org-cycle-hide-drawers
954 org-cycle-show-empty-lines
955 org-optimize-window-after-visibility-change)
956 "Hook that is run after `org-cycle' has changed the buffer visibility.
957 The function(s) in this hook must accept a single argument which indicates
958 the new state that was set by the most recent `org-cycle' command. The
959 argument is a symbol. After a global state change, it can have the values
960 `overview', `content', or `all'. After a local state change, it can have
961 the values `folded', `children', or `subtree'."
962 :group 'org-cycle
963 :type 'hook)
965 (defgroup org-edit-structure nil
966 "Options concerning structure editing in Org-mode."
967 :tag "Org Edit Structure"
968 :group 'org-structure)
970 (defcustom org-odd-levels-only nil
971 "Non-nil means skip even levels and only use odd levels for the outline.
972 This has the effect that two stars are being added/taken away in
973 promotion/demotion commands. It also influences how levels are
974 handled by the exporters.
975 Changing it requires restart of `font-lock-mode' to become effective
976 for fontification also in regions already fontified.
977 You may also set this on a per-file basis by adding one of the following
978 lines to the buffer:
980 #+STARTUP: odd
981 #+STARTUP: oddeven"
982 :group 'org-edit-structure
983 :group 'org-appearance
984 :type 'boolean)
986 (defcustom org-adapt-indentation t
987 "Non-nil means adapt indentation to outline node level.
989 When this variable is set, Org assumes that you write outlines by
990 indenting text in each node to align with the headline (after the stars).
991 The following issues are influenced by this variable:
993 - When this is set and the *entire* text in an entry is indented, the
994 indentation is increased by one space in a demotion command, and
995 decreased by one in a promotion command. If any line in the entry
996 body starts with text at column 0, indentation is not changed at all.
998 - Property drawers and planning information is inserted indented when
999 this variable s set. When nil, they will not be indented.
1001 - TAB indents a line relative to context. The lines below a headline
1002 will be indented when this variable is set.
1004 Note that this is all about true indentation, by adding and removing
1005 space characters. See also `org-indent.el' which does level-dependent
1006 indentation in a virtual way, i.e. at display time in Emacs."
1007 :group 'org-edit-structure
1008 :type 'boolean)
1010 (defcustom org-special-ctrl-a/e nil
1011 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1013 When t, `C-a' will bring back the cursor to the beginning of the
1014 headline text, i.e. after the stars and after a possible TODO
1015 keyword. In an item, this will be the position after bullet and
1016 check-box, if any. When the cursor is already at that position,
1017 another `C-a' will bring it to the beginning of the line.
1019 `C-e' will jump to the end of the headline, ignoring the presence
1020 of tags in the headline. A second `C-e' will then jump to the
1021 true end of the line, after any tags. This also means that, when
1022 this variable is non-nil, `C-e' also will never jump beyond the
1023 end of the heading of a folded section, i.e. not after the
1024 ellipses.
1026 When set to the symbol `reversed', the first `C-a' or `C-e' works
1027 normally, going to the true line boundary first. Only a directly
1028 following, identical keypress will bring the cursor to the
1029 special positions.
1031 This may also be a cons cell where the behavior for `C-a' and
1032 `C-e' is set separately."
1033 :group 'org-edit-structure
1034 :type '(choice
1035 (const :tag "off" nil)
1036 (const :tag "on: after stars/bullet and before tags first" t)
1037 (const :tag "reversed: true line boundary first" reversed)
1038 (cons :tag "Set C-a and C-e separately"
1039 (choice :tag "Special C-a"
1040 (const :tag "off" nil)
1041 (const :tag "on: after stars/bullet first" t)
1042 (const :tag "reversed: before stars/bullet first" reversed))
1043 (choice :tag "Special C-e"
1044 (const :tag "off" nil)
1045 (const :tag "on: before tags first" t)
1046 (const :tag "reversed: after tags first" reversed)))))
1047 (if (fboundp 'defvaralias)
1048 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
1050 (defcustom org-special-ctrl-k nil
1051 "Non-nil means `C-k' will behave specially in headlines.
1052 When nil, `C-k' will call the default `kill-line' command.
1053 When t, the following will happen while the cursor is in the headline:
1055 - When the cursor is at the beginning of a headline, kill the entire
1056 line and possible the folded subtree below the line.
1057 - When in the middle of the headline text, kill the headline up to the tags.
1058 - When after the headline text, kill the tags."
1059 :group 'org-edit-structure
1060 :type 'boolean)
1062 (defcustom org-ctrl-k-protect-subtree nil
1063 "Non-nil means, do not delete a hidden subtree with C-k.
1064 When set to the symbol `error', simply throw an error when C-k is
1065 used to kill (part-of) a headline that has hidden text behind it.
1066 Any other non-nil value will result in a query to the user, if it is
1067 OK to kill that hidden subtree. When nil, kill without remorse."
1068 :group 'org-edit-structure
1069 :version "24.1"
1070 :type '(choice
1071 (const :tag "Do not protect hidden subtrees" nil)
1072 (const :tag "Protect hidden subtrees with a security query" t)
1073 (const :tag "Never kill a hidden subtree with C-k" error)))
1075 (defcustom org-catch-invisible-edits nil
1076 "Check if in invisible region before inserting or deleting a character.
1077 Valid values are:
1079 nil Do not check, so just do invisible edits.
1080 error Throw an error and do nothing.
1081 show Make point visible, and do the requested edit.
1082 show-and-error Make point visible, then throw an error and abort the edit.
1083 smart Make point visible, and do insertion/deletion if it is
1084 adjacent to visible text and the change feels predictable.
1085 Never delete a previously invisible character or add in the
1086 middle or right after an invisible region. Basically, this
1087 allows insertion and backward-delete right before ellipses.
1088 FIXME: maybe in this case we should not even show?"
1089 :group 'org-edit-structure
1090 :version "24.1"
1091 :type '(choice
1092 (const :tag "Do not check" nil)
1093 (const :tag "Throw error when trying to edit" error)
1094 (const :tag "Unhide, but do not do the edit" show-and-error)
1095 (const :tag "Show invisible part and do the edit" show)
1096 (const :tag "Be smart and do the right thing" smart)))
1098 (defcustom org-yank-folded-subtrees t
1099 "Non-nil means when yanking subtrees, fold them.
1100 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1101 it starts with a heading and all other headings in it are either children
1102 or siblings, then fold all the subtrees. However, do this only if no
1103 text after the yank would be swallowed into a folded tree by this action."
1104 :group 'org-edit-structure
1105 :type 'boolean)
1107 (defcustom org-yank-adjusted-subtrees nil
1108 "Non-nil means when yanking subtrees, adjust the level.
1109 With this setting, `org-paste-subtree' is used to insert the subtree, see
1110 this function for details."
1111 :group 'org-edit-structure
1112 :type 'boolean)
1114 (defcustom org-M-RET-may-split-line '((default . t))
1115 "Non-nil means M-RET will split the line at the cursor position.
1116 When nil, it will go to the end of the line before making a
1117 new line.
1118 You may also set this option in a different way for different
1119 contexts. Valid contexts are:
1121 headline when creating a new headline
1122 item when creating a new item
1123 table in a table field
1124 default the value to be used for all contexts not explicitly
1125 customized"
1126 :group 'org-structure
1127 :group 'org-table
1128 :type '(choice
1129 (const :tag "Always" t)
1130 (const :tag "Never" nil)
1131 (repeat :greedy t :tag "Individual contexts"
1132 (cons
1133 (choice :tag "Context"
1134 (const headline)
1135 (const item)
1136 (const table)
1137 (const default))
1138 (boolean)))))
1141 (defcustom org-insert-heading-respect-content nil
1142 "Non-nil means insert new headings after the current subtree.
1143 When nil, the new heading is created directly after the current line.
1144 The commands \\[org-insert-heading-respect-content] and
1145 \\[org-insert-todo-heading-respect-content] turn this variable on
1146 for the duration of the command."
1147 :group 'org-structure
1148 :type 'boolean)
1150 (defcustom org-blank-before-new-entry '((heading . auto)
1151 (plain-list-item . auto))
1152 "Should `org-insert-heading' leave a blank line before new heading/item?
1153 The value is an alist, with `heading' and `plain-list-item' as CAR,
1154 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1155 which case Org will look at the surrounding headings/items and try to
1156 make an intelligent decision whether to insert a blank line or not.
1158 For plain lists, if the variable `org-empty-line-terminates-plain-lists' is
1159 set, the setting here is ignored and no empty line is inserted, to avoid
1160 breaking the list structure."
1161 :group 'org-edit-structure
1162 :type '(list
1163 (cons (const heading)
1164 (choice (const :tag "Never" nil)
1165 (const :tag "Always" t)
1166 (const :tag "Auto" auto)))
1167 (cons (const plain-list-item)
1168 (choice (const :tag "Never" nil)
1169 (const :tag "Always" t)
1170 (const :tag "Auto" auto)))))
1172 (defcustom org-insert-heading-hook nil
1173 "Hook being run after inserting a new heading."
1174 :group 'org-edit-structure
1175 :type 'hook)
1177 (defcustom org-enable-fixed-width-editor t
1178 "Non-nil means lines starting with \":\" are treated as fixed-width.
1179 This currently only means they are never auto-wrapped.
1180 When nil, such lines will be treated like ordinary lines.
1181 See also the QUOTE keyword."
1182 :group 'org-edit-structure
1183 :type 'boolean)
1185 (defcustom org-goto-auto-isearch t
1186 "Non-nil means typing characters in `org-goto' starts incremental search."
1187 :group 'org-edit-structure
1188 :type 'boolean)
1190 (defgroup org-sparse-trees nil
1191 "Options concerning sparse trees in Org-mode."
1192 :tag "Org Sparse Trees"
1193 :group 'org-structure)
1195 (defcustom org-highlight-sparse-tree-matches t
1196 "Non-nil means highlight all matches that define a sparse tree.
1197 The highlights will automatically disappear the next time the buffer is
1198 changed by an edit command."
1199 :group 'org-sparse-trees
1200 :type 'boolean)
1202 (defcustom org-remove-highlights-with-change t
1203 "Non-nil means any change to the buffer will remove temporary highlights.
1204 Such highlights are created by `org-occur' and `org-clock-display'.
1205 When nil, `C-c C-c needs to be used to get rid of the highlights.
1206 The highlights created by `org-preview-latex-fragment' always need
1207 `C-c C-c' to be removed."
1208 :group 'org-sparse-trees
1209 :group 'org-time
1210 :type 'boolean)
1213 (defcustom org-occur-hook '(org-first-headline-recenter)
1214 "Hook that is run after `org-occur' has constructed a sparse tree.
1215 This can be used to recenter the window to show as much of the structure
1216 as possible."
1217 :group 'org-sparse-trees
1218 :type 'hook)
1220 (defgroup org-imenu-and-speedbar nil
1221 "Options concerning imenu and speedbar in Org-mode."
1222 :tag "Org Imenu and Speedbar"
1223 :group 'org-structure)
1225 (defcustom org-imenu-depth 2
1226 "The maximum level for Imenu access to Org-mode headlines.
1227 This also applied for speedbar access."
1228 :group 'org-imenu-and-speedbar
1229 :type 'integer)
1231 (defgroup org-table nil
1232 "Options concerning tables in Org-mode."
1233 :tag "Org Table"
1234 :group 'org)
1236 (defcustom org-enable-table-editor 'optimized
1237 "Non-nil means lines starting with \"|\" are handled by the table editor.
1238 When nil, such lines will be treated like ordinary lines.
1240 When equal to the symbol `optimized', the table editor will be optimized to
1241 do the following:
1242 - Automatic overwrite mode in front of whitespace in table fields.
1243 This makes the structure of the table stay in tact as long as the edited
1244 field does not exceed the column width.
1245 - Minimize the number of realigns. Normally, the table is aligned each time
1246 TAB or RET are pressed to move to another field. With optimization this
1247 happens only if changes to a field might have changed the column width.
1248 Optimization requires replacing the functions `self-insert-command',
1249 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1250 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1251 very good at guessing when a re-align will be necessary, but you can always
1252 force one with \\[org-ctrl-c-ctrl-c].
1254 If you would like to use the optimized version in Org-mode, but the
1255 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1257 This variable can be used to turn on and off the table editor during a session,
1258 but in order to toggle optimization, a restart is required.
1260 See also the variable `org-table-auto-blank-field'."
1261 :group 'org-table
1262 :type '(choice
1263 (const :tag "off" nil)
1264 (const :tag "on" t)
1265 (const :tag "on, optimized" optimized)))
1267 (defcustom org-self-insert-cluster-for-undo t
1268 "Non-nil means cluster self-insert commands for undo when possible.
1269 If this is set, then, like in the Emacs command loop, 20 consecutive
1270 characters will be undone together.
1271 This is configurable, because there is some impact on typing performance."
1272 :group 'org-table
1273 :type 'boolean)
1275 (defcustom org-table-tab-recognizes-table.el t
1276 "Non-nil means TAB will automatically notice a table.el table.
1277 When it sees such a table, it moves point into it and - if necessary -
1278 calls `table-recognize-table'."
1279 :group 'org-table-editing
1280 :type 'boolean)
1282 (defgroup org-link nil
1283 "Options concerning links in Org-mode."
1284 :tag "Org Link"
1285 :group 'org)
1287 (defvar org-link-abbrev-alist-local nil
1288 "Buffer-local version of `org-link-abbrev-alist', which see.
1289 The value of this is taken from the #+LINK lines.")
1290 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1292 (defcustom org-link-abbrev-alist nil
1293 "Alist of link abbreviations.
1294 The car of each element is a string, to be replaced at the start of a link.
1295 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1296 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1298 [[linkkey:tag][description]]
1300 The 'linkkey' must be a word word, starting with a letter, followed
1301 by letters, numbers, '-' or '_'.
1303 If REPLACE is a string, the tag will simply be appended to create the link.
1304 If the string contains \"%s\", the tag will be inserted there. Alternatively,
1305 the placeholder \"%h\" will cause a url-encoded version of the tag to
1306 be inserted at that point (see the function `url-hexify-string').
1308 REPLACE may also be a function that will be called with the tag as the
1309 only argument to create the link, which should be returned as a string.
1311 See the manual for examples."
1312 :group 'org-link
1313 :type '(repeat
1314 (cons
1315 (string :tag "Protocol")
1316 (choice
1317 (string :tag "Format")
1318 (function)))))
1320 (defcustom org-descriptive-links t
1321 "Non-nil means Org will display descriptive links.
1322 E.g. [[http://orgmode.org][Org website]] will be displayed as
1323 \"Org Website\", hiding the link itself and just displaying its
1324 description. When set to `nil', Org will display the full links
1325 literally.
1327 You can interactively set the value of this variable by calling
1328 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1329 :group 'org-link
1330 :type 'boolean)
1332 (defcustom org-link-file-path-type 'adaptive
1333 "How the path name in file links should be stored.
1334 Valid values are:
1336 relative Relative to the current directory, i.e. the directory of the file
1337 into which the link is being inserted.
1338 absolute Absolute path, if possible with ~ for home directory.
1339 noabbrev Absolute path, no abbreviation of home directory.
1340 adaptive Use relative path for files in the current directory and sub-
1341 directories of it. For other files, use an absolute path."
1342 :group 'org-link
1343 :type '(choice
1344 (const relative)
1345 (const absolute)
1346 (const noabbrev)
1347 (const adaptive)))
1349 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1350 "Types of links that should be activated in Org-mode files.
1351 This is a list of symbols, each leading to the activation of a certain link
1352 type. In principle, it does not hurt to turn on most link types - there may
1353 be a small gain when turning off unused link types. The types are:
1355 bracket The recommended [[link][description]] or [[link]] links with hiding.
1356 angle Links in angular brackets that may contain whitespace like
1357 <bbdb:Carsten Dominik>.
1358 plain Plain links in normal text, no whitespace, like http://google.com.
1359 radio Text that is matched by a radio target, see manual for details.
1360 tag Tag settings in a headline (link to tag search).
1361 date Time stamps (link to calendar).
1362 footnote Footnote labels.
1364 Changing this variable requires a restart of Emacs to become effective."
1365 :group 'org-link
1366 :type '(set :greedy t
1367 (const :tag "Double bracket links" bracket)
1368 (const :tag "Angular bracket links" angle)
1369 (const :tag "Plain text links" plain)
1370 (const :tag "Radio target matches" radio)
1371 (const :tag "Tags" tag)
1372 (const :tag "Timestamps" date)
1373 (const :tag "Footnotes" footnote)))
1375 (defcustom org-make-link-description-function nil
1376 "Function to use to generate link descriptions from links.
1377 If nil the link location will be used. This function must take
1378 two parameters; the first is the link and the second the
1379 description `org-insert-link' has generated, and should return the
1380 description to use."
1381 :group 'org-link
1382 :type 'function)
1384 (defgroup org-link-store nil
1385 "Options concerning storing links in Org-mode."
1386 :tag "Org Store Link"
1387 :group 'org-link)
1389 (defcustom org-email-link-description-format "Email %c: %.30s"
1390 "Format of the description part of a link to an email or usenet message.
1391 The following %-escapes will be replaced by corresponding information:
1393 %F full \"From\" field
1394 %f name, taken from \"From\" field, address if no name
1395 %T full \"To\" field
1396 %t first name in \"To\" field, address if no name
1397 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1398 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1399 %s subject
1400 %d date
1401 %m message-id.
1403 You may use normal field width specification between the % and the letter.
1404 This is for example useful to limit the length of the subject.
1406 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1407 :group 'org-link-store
1408 :type 'string)
1410 (defcustom org-from-is-user-regexp
1411 (let (r1 r2)
1412 (when (and user-mail-address (not (string= user-mail-address "")))
1413 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1414 (when (and user-full-name (not (string= user-full-name "")))
1415 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1416 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1417 "Regexp matched against the \"From:\" header of an email or usenet message.
1418 It should match if the message is from the user him/herself."
1419 :group 'org-link-store
1420 :type 'regexp)
1422 (defcustom org-link-to-org-use-id 'create-if-interactive-and-no-custom-id
1423 "Non-nil means storing a link to an Org file will use entry IDs.
1425 Note that before this variable is even considered, org-id must be loaded,
1426 so please customize `org-modules' and turn it on.
1428 The variable can have the following values:
1430 t Create an ID if needed to make a link to the current entry.
1432 create-if-interactive
1433 If `org-store-link' is called directly (interactively, as a user
1434 command), do create an ID to support the link. But when doing the
1435 job for remember, only use the ID if it already exists. The
1436 purpose of this setting is to avoid proliferation of unwanted
1437 IDs, just because you happen to be in an Org file when you
1438 call `org-remember' that automatically and preemptively
1439 creates a link. If you do want to get an ID link in a remember
1440 template to an entry not having an ID, create it first by
1441 explicitly creating a link to it, using `C-c C-l' first.
1443 create-if-interactive-and-no-custom-id
1444 Like create-if-interactive, but do not create an ID if there is
1445 a CUSTOM_ID property defined in the entry. This is the default.
1447 use-existing
1448 Use existing ID, do not create one.
1450 nil Never use an ID to make a link, instead link using a text search for
1451 the headline text."
1452 :group 'org-link-store
1453 :type '(choice
1454 (const :tag "Create ID to make link" t)
1455 (const :tag "Create if storing link interactively"
1456 create-if-interactive)
1457 (const :tag "Create if storing link interactively and no CUSTOM_ID is present"
1458 create-if-interactive-and-no-custom-id)
1459 (const :tag "Only use existing" use-existing)
1460 (const :tag "Do not use ID to create link" nil)))
1462 (defcustom org-context-in-file-links t
1463 "Non-nil means file links from `org-store-link' contain context.
1464 A search string will be added to the file name with :: as separator and
1465 used to find the context when the link is activated by the command
1466 `org-open-at-point'. When this option is t, the entire active region
1467 will be placed in the search string of the file link. If set to a
1468 positive integer, only the first n lines of context will be stored.
1470 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1471 negates this setting for the duration of the command."
1472 :group 'org-link-store
1473 :type '(choice boolean integer))
1475 (defcustom org-keep-stored-link-after-insertion nil
1476 "Non-nil means keep link in list for entire session.
1478 The command `org-store-link' adds a link pointing to the current
1479 location to an internal list. These links accumulate during a session.
1480 The command `org-insert-link' can be used to insert links into any
1481 Org-mode file (offering completion for all stored links). When this
1482 option is nil, every link which has been inserted once using \\[org-insert-link]
1483 will be removed from the list, to make completing the unused links
1484 more efficient."
1485 :group 'org-link-store
1486 :type 'boolean)
1488 (defgroup org-link-follow nil
1489 "Options concerning following links in Org-mode."
1490 :tag "Org Follow Link"
1491 :group 'org-link)
1493 (defcustom org-link-translation-function nil
1494 "Function to translate links with different syntax to Org syntax.
1495 This can be used to translate links created for example by the Planner
1496 or emacs-wiki packages to Org syntax.
1497 The function must accept two parameters, a TYPE containing the link
1498 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1499 which is everything after the link protocol. It should return a cons
1500 with possibly modified values of type and path.
1501 Org contains a function for this, so if you set this variable to
1502 `org-translate-link-from-planner', you should be able follow many
1503 links created by planner."
1504 :group 'org-link-follow
1505 :type 'function)
1507 (defcustom org-follow-link-hook nil
1508 "Hook that is run after a link has been followed."
1509 :group 'org-link-follow
1510 :type 'hook)
1512 (defcustom org-tab-follows-link nil
1513 "Non-nil means on links TAB will follow the link.
1514 Needs to be set before org.el is loaded.
1515 This really should not be used, it does not make sense, and the
1516 implementation is bad."
1517 :group 'org-link-follow
1518 :type 'boolean)
1520 (defcustom org-return-follows-link nil
1521 "Non-nil means on links RET will follow the link."
1522 :group 'org-link-follow
1523 :type 'boolean)
1525 (defcustom org-mouse-1-follows-link
1526 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1527 "Non-nil means mouse-1 on a link will follow the link.
1528 A longer mouse click will still set point. Does not work on XEmacs.
1529 Needs to be set before org.el is loaded."
1530 :group 'org-link-follow
1531 :type 'boolean)
1533 (defcustom org-mark-ring-length 4
1534 "Number of different positions to be recorded in the ring.
1535 Changing this requires a restart of Emacs to work correctly."
1536 :group 'org-link-follow
1537 :type 'integer)
1539 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1540 "Non-nil means internal links in Org files must exactly match a headline.
1541 When nil, the link search tries to match a phrase with all words
1542 in the search text."
1543 :group 'org-link-follow
1544 :version "24.1"
1545 :type '(choice
1546 (const :tag "Use fuzzy text search" nil)
1547 (const :tag "Match only exact headline" t)
1548 (const :tag "Match exact headline or query to create it"
1549 query-to-create)))
1551 (defcustom org-link-frame-setup
1552 '((vm . vm-visit-folder-other-frame)
1553 (vm-imap . vm-visit-imap-folder-other-frame)
1554 (gnus . org-gnus-no-new-news)
1555 (file . find-file-other-window)
1556 (wl . wl-other-frame))
1557 "Setup the frame configuration for following links.
1558 When following a link with Emacs, it may often be useful to display
1559 this link in another window or frame. This variable can be used to
1560 set this up for the different types of links.
1561 For VM, use any of
1562 `vm-visit-folder'
1563 `vm-visit-folder-other-window'
1564 `vm-visit-folder-other-frame'
1565 For Gnus, use any of
1566 `gnus'
1567 `gnus-other-frame'
1568 `org-gnus-no-new-news'
1569 For FILE, use any of
1570 `find-file'
1571 `find-file-other-window'
1572 `find-file-other-frame'
1573 For Wanderlust use any of
1574 `wl'
1575 `wl-other-frame'
1576 For the calendar, use the variable `calendar-setup'.
1577 For BBDB, it is currently only possible to display the matches in
1578 another window."
1579 :group 'org-link-follow
1580 :type '(list
1581 (cons (const vm)
1582 (choice
1583 (const vm-visit-folder)
1584 (const vm-visit-folder-other-window)
1585 (const vm-visit-folder-other-frame)))
1586 (cons (const gnus)
1587 (choice
1588 (const gnus)
1589 (const gnus-other-frame)
1590 (const org-gnus-no-new-news)))
1591 (cons (const file)
1592 (choice
1593 (const find-file)
1594 (const find-file-other-window)
1595 (const find-file-other-frame)))
1596 (cons (const wl)
1597 (choice
1598 (const wl)
1599 (const wl-other-frame)))))
1601 (defcustom org-display-internal-link-with-indirect-buffer nil
1602 "Non-nil means use indirect buffer to display infile links.
1603 Activating internal links (from one location in a file to another location
1604 in the same file) normally just jumps to the location. When the link is
1605 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1606 is displayed in
1607 another window. When this option is set, the other window actually displays
1608 an indirect buffer clone of the current buffer, to avoid any visibility
1609 changes to the current buffer."
1610 :group 'org-link-follow
1611 :type 'boolean)
1613 (defcustom org-open-non-existing-files nil
1614 "Non-nil means `org-open-file' will open non-existing files.
1615 When nil, an error will be generated.
1616 This variable applies only to external applications because they
1617 might choke on non-existing files. If the link is to a file that
1618 will be opened in Emacs, the variable is ignored."
1619 :group 'org-link-follow
1620 :type 'boolean)
1622 (defcustom org-open-directory-means-index-dot-org nil
1623 "Non-nil means a link to a directory really means to index.org.
1624 When nil, following a directory link will run dired or open a finder/explorer
1625 window on that directory."
1626 :group 'org-link-follow
1627 :type 'boolean)
1629 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1630 "Function and arguments to call for following mailto links.
1631 This is a list with the first element being a Lisp function, and the
1632 remaining elements being arguments to the function. In string arguments,
1633 %a will be replaced by the address, and %s will be replaced by the subject
1634 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1635 :group 'org-link-follow
1636 :type '(choice
1637 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1638 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1639 (const :tag "message-mail" (message-mail "%a" "%s"))
1640 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1642 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1643 "Non-nil means ask for confirmation before executing shell links.
1644 Shell links can be dangerous: just think about a link
1646 [[shell:rm -rf ~/*][Google Search]]
1648 This link would show up in your Org-mode document as \"Google Search\",
1649 but really it would remove your entire home directory.
1650 Therefore we advise against setting this variable to nil.
1651 Just change it to `y-or-n-p' if you want to confirm with a
1652 single keystroke rather than having to type \"yes\"."
1653 :group 'org-link-follow
1654 :type '(choice
1655 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1656 (const :tag "with y-or-n (faster)" y-or-n-p)
1657 (const :tag "no confirmation (dangerous)" nil)))
1658 (put 'org-confirm-shell-link-function
1659 'safe-local-variable
1660 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1662 (defcustom org-confirm-shell-link-not-regexp ""
1663 "A regexp to skip confirmation for shell links."
1664 :group 'org-link-follow
1665 :version "24.1"
1666 :type 'regexp)
1668 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1669 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1670 Elisp links can be dangerous: just think about a link
1672 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1674 This link would show up in your Org-mode document as \"Google Search\",
1675 but really it would remove your entire home directory.
1676 Therefore we advise against setting this variable to nil.
1677 Just change it to `y-or-n-p' if you want to confirm with a
1678 single keystroke rather than having to type \"yes\"."
1679 :group 'org-link-follow
1680 :type '(choice
1681 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1682 (const :tag "with y-or-n (faster)" y-or-n-p)
1683 (const :tag "no confirmation (dangerous)" nil)))
1684 (put 'org-confirm-shell-link-function
1685 'safe-local-variable
1686 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1688 (defcustom org-confirm-elisp-link-not-regexp ""
1689 "A regexp to skip confirmation for Elisp links."
1690 :group 'org-link-follow
1691 :version "24.1"
1692 :type 'regexp)
1694 (defconst org-file-apps-defaults-gnu
1695 '((remote . emacs)
1696 (system . mailcap)
1697 (t . mailcap))
1698 "Default file applications on a UNIX or GNU/Linux system.
1699 See `org-file-apps'.")
1701 (defconst org-file-apps-defaults-macosx
1702 '((remote . emacs)
1703 (t . "open %s")
1704 (system . "open %s")
1705 ("ps.gz" . "gv %s")
1706 ("eps.gz" . "gv %s")
1707 ("dvi" . "xdvi %s")
1708 ("fig" . "xfig %s"))
1709 "Default file applications on a MacOS X system.
1710 The system \"open\" is known as a default, but we use X11 applications
1711 for some files for which the OS does not have a good default.
1712 See `org-file-apps'.")
1714 (defconst org-file-apps-defaults-windowsnt
1715 (list
1716 '(remote . emacs)
1717 (cons t
1718 (list (if (featurep 'xemacs)
1719 'mswindows-shell-execute
1720 'w32-shell-execute)
1721 "open" 'file))
1722 (cons 'system
1723 (list (if (featurep 'xemacs)
1724 'mswindows-shell-execute
1725 'w32-shell-execute)
1726 "open" 'file)))
1727 "Default file applications on a Windows NT system.
1728 The system \"open\" is used for most files.
1729 See `org-file-apps'.")
1731 (defcustom org-file-apps
1733 (auto-mode . emacs)
1734 ("\\.mm\\'" . default)
1735 ("\\.x?html?\\'" . default)
1736 ("\\.pdf\\'" . default)
1738 "External applications for opening `file:path' items in a document.
1739 Org-mode uses system defaults for different file types, but
1740 you can use this variable to set the application for a given file
1741 extension. The entries in this list are cons cells where the car identifies
1742 files and the cdr the corresponding command. Possible values for the
1743 file identifier are
1744 \"string\" A string as a file identifier can be interpreted in different
1745 ways, depending on its contents:
1747 - Alphanumeric characters only:
1748 Match links with this file extension.
1749 Example: (\"pdf\" . \"evince %s\")
1750 to open PDFs with evince.
1752 - Regular expression: Match links where the
1753 filename matches the regexp. If you want to
1754 use groups here, use shy groups.
1756 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1757 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1758 to open *.html and *.xhtml with firefox.
1760 - Regular expression which contains (non-shy) groups:
1761 Match links where the whole link, including \"::\", and
1762 anything after that, matches the regexp.
1763 In a custom command string, %1, %2, etc. are replaced with
1764 the parts of the link that were matched by the groups.
1765 For backwards compatibility, if a command string is given
1766 that does not use any of the group matches, this case is
1767 handled identically to the second one (i.e. match against
1768 file name only).
1769 In a custom lisp form, you can access the group matches with
1770 (match-string n link).
1772 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1773 to open [[file:document.pdf::5]] with evince at page 5.
1775 `directory' Matches a directory
1776 `remote' Matches a remote file, accessible through tramp or efs.
1777 Remote files most likely should be visited through Emacs
1778 because external applications cannot handle such paths.
1779 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1780 so all files Emacs knows how to handle. Using this with
1781 command `emacs' will open most files in Emacs. Beware that this
1782 will also open html files inside Emacs, unless you add
1783 (\"html\" . default) to the list as well.
1784 t Default for files not matched by any of the other options.
1785 `system' The system command to open files, like `open' on Windows
1786 and Mac OS X, and mailcap under GNU/Linux. This is the command
1787 that will be selected if you call `C-c C-o' with a double
1788 \\[universal-argument] \\[universal-argument] prefix.
1790 Possible values for the command are:
1791 `emacs' The file will be visited by the current Emacs process.
1792 `default' Use the default application for this file type, which is the
1793 association for t in the list, most likely in the system-specific
1794 part.
1795 This can be used to overrule an unwanted setting in the
1796 system-specific variable.
1797 `system' Use the system command for opening files, like \"open\".
1798 This command is specified by the entry whose car is `system'.
1799 Most likely, the system-specific version of this variable
1800 does define this command, but you can overrule/replace it
1801 here.
1802 string A command to be executed by a shell; %s will be replaced
1803 by the path to the file.
1804 sexp A Lisp form which will be evaluated. The file path will
1805 be available in the Lisp variable `file'.
1806 For more examples, see the system specific constants
1807 `org-file-apps-defaults-macosx'
1808 `org-file-apps-defaults-windowsnt'
1809 `org-file-apps-defaults-gnu'."
1810 :group 'org-link-follow
1811 :type '(repeat
1812 (cons (choice :value ""
1813 (string :tag "Extension")
1814 (const :tag "System command to open files" system)
1815 (const :tag "Default for unrecognized files" t)
1816 (const :tag "Remote file" remote)
1817 (const :tag "Links to a directory" directory)
1818 (const :tag "Any files that have Emacs modes"
1819 auto-mode))
1820 (choice :value ""
1821 (const :tag "Visit with Emacs" emacs)
1822 (const :tag "Use default" default)
1823 (const :tag "Use the system command" system)
1824 (string :tag "Command")
1825 (sexp :tag "Lisp form")))))
1829 (defgroup org-refile nil
1830 "Options concerning refiling entries in Org-mode."
1831 :tag "Org Refile"
1832 :group 'org)
1834 (defcustom org-directory "~/org"
1835 "Directory with org files.
1836 This is just a default location to look for Org files. There is no need
1837 at all to put your files into this directory. It is only used in the
1838 following situations:
1840 1. When a remember template specifies a target file that is not an
1841 absolute path. The path will then be interpreted relative to
1842 `org-directory'
1843 2. When a remember note is filed away in an interactive way (when exiting the
1844 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1845 with `org-directory' as the default path."
1846 :group 'org-refile
1847 :group 'org-remember
1848 :type 'directory)
1850 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1851 "Default target for storing notes.
1852 Used as a fall back file for org-remember.el and org-capture.el, for
1853 templates that do not specify a target file."
1854 :group 'org-refile
1855 :group 'org-remember
1856 :type '(choice
1857 (const :tag "Default from remember-data-file" nil)
1858 file))
1860 (defcustom org-goto-interface 'outline
1861 "The default interface to be used for `org-goto'.
1862 Allowed values are:
1863 outline The interface shows an outline of the relevant file
1864 and the correct heading is found by moving through
1865 the outline or by searching with incremental search.
1866 outline-path-completion Headlines in the current buffer are offered via
1867 completion. This is the interface also used by
1868 the refile command."
1869 :group 'org-refile
1870 :type '(choice
1871 (const :tag "Outline" outline)
1872 (const :tag "Outline-path-completion" outline-path-completion)))
1874 (defcustom org-goto-max-level 5
1875 "Maximum target level when running `org-goto' with refile interface."
1876 :group 'org-refile
1877 :type 'integer)
1879 (defcustom org-reverse-note-order nil
1880 "Non-nil means store new notes at the beginning of a file or entry.
1881 When nil, new notes will be filed to the end of a file or entry.
1882 This can also be a list with cons cells of regular expressions that
1883 are matched against file names, and values."
1884 :group 'org-remember
1885 :group 'org-refile
1886 :type '(choice
1887 (const :tag "Reverse always" t)
1888 (const :tag "Reverse never" nil)
1889 (repeat :tag "By file name regexp"
1890 (cons regexp boolean))))
1892 (defcustom org-log-refile nil
1893 "Information to record when a task is refiled.
1895 Possible values are:
1897 nil Don't add anything
1898 time Add a time stamp to the task
1899 note Prompt for a note and add it with template `org-log-note-headings'
1901 This option can also be set with on a per-file-basis with
1903 #+STARTUP: nologrefile
1904 #+STARTUP: logrefile
1905 #+STARTUP: lognoterefile
1907 You can have local logging settings for a subtree by setting the LOGGING
1908 property to one or more of these keywords.
1910 When bulk-refiling from the agenda, the value `note' is forbidden and
1911 will temporarily be changed to `time'."
1912 :group 'org-refile
1913 :group 'org-progress
1914 :version "24.1"
1915 :type '(choice
1916 (const :tag "No logging" nil)
1917 (const :tag "Record timestamp" time)
1918 (const :tag "Record timestamp with note." note)))
1920 (defcustom org-refile-targets nil
1921 "Targets for refiling entries with \\[org-refile].
1922 This is a list of cons cells. Each cell contains:
1923 - a specification of the files to be considered, either a list of files,
1924 or a symbol whose function or variable value will be used to retrieve
1925 a file name or a list of file names. If you use `org-agenda-files' for
1926 that, all agenda files will be scanned for targets. Nil means consider
1927 headings in the current buffer.
1928 - A specification of how to find candidate refile targets. This may be
1929 any of:
1930 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1931 This tag has to be present in all target headlines, inheritance will
1932 not be considered.
1933 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1934 todo keyword.
1935 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1936 headlines that are refiling targets.
1937 - a cons cell (:level . N). Any headline of level N is considered a target.
1938 Note that, when `org-odd-levels-only' is set, level corresponds to
1939 order in hierarchy, not to the number of stars.
1940 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1941 Note that, when `org-odd-levels-only' is set, level corresponds to
1942 order in hierarchy, not to the number of stars.
1944 Each element of this list generates a set of possible targets.
1945 The union of these sets is presented (with completion) to
1946 the user by `org-refile'.
1948 You can set the variable `org-refile-target-verify-function' to a function
1949 to verify each headline found by the simple criteria above.
1951 When this variable is nil, all top-level headlines in the current buffer
1952 are used, equivalent to the value `((nil . (:level . 1))'."
1953 :group 'org-refile
1954 :type '(repeat
1955 (cons
1956 (choice :value org-agenda-files
1957 (const :tag "All agenda files" org-agenda-files)
1958 (const :tag "Current buffer" nil)
1959 (function) (variable) (file))
1960 (choice :tag "Identify target headline by"
1961 (cons :tag "Specific tag" (const :value :tag) (string))
1962 (cons :tag "TODO keyword" (const :value :todo) (string))
1963 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1964 (cons :tag "Level number" (const :value :level) (integer))
1965 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1967 (defcustom org-refile-target-verify-function nil
1968 "Function to verify if the headline at point should be a refile target.
1969 The function will be called without arguments, with point at the
1970 beginning of the headline. It should return t and leave point
1971 where it is if the headline is a valid target for refiling.
1973 If the target should not be selected, the function must return nil.
1974 In addition to this, it may move point to a place from where the search
1975 should be continued. For example, the function may decide that the entire
1976 subtree of the current entry should be excluded and move point to the end
1977 of the subtree."
1978 :group 'org-refile
1979 :type 'function)
1981 (defcustom org-refile-use-cache nil
1982 "Non-nil means cache refile targets to speed up the process.
1983 The cache for a particular file will be updated automatically when
1984 the buffer has been killed, or when any of the marker used for flagging
1985 refile targets no longer points at a live buffer.
1986 If you have added new entries to a buffer that might themselves be targets,
1987 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
1988 find that easier, `C-u C-u C-u C-c C-w'."
1989 :group 'org-refile
1990 :version "24.1"
1991 :type 'boolean)
1993 (defcustom org-refile-use-outline-path nil
1994 "Non-nil means provide refile targets as paths.
1995 So a level 3 headline will be available as level1/level2/level3.
1997 When the value is `file', also include the file name (without directory)
1998 into the path. In this case, you can also stop the completion after
1999 the file name, to get entries inserted as top level in the file.
2001 When `full-file-path', include the full file path."
2002 :group 'org-refile
2003 :type '(choice
2004 (const :tag "Not" nil)
2005 (const :tag "Yes" t)
2006 (const :tag "Start with file name" file)
2007 (const :tag "Start with full file path" full-file-path)))
2009 (defcustom org-outline-path-complete-in-steps t
2010 "Non-nil means complete the outline path in hierarchical steps.
2011 When Org-mode uses the refile interface to select an outline path
2012 \(see variable `org-refile-use-outline-path'), the completion of
2013 the path can be done is a single go, or if can be done in steps down
2014 the headline hierarchy. Going in steps is probably the best if you
2015 do not use a special completion package like `ido' or `icicles'.
2016 However, when using these packages, going in one step can be very
2017 fast, while still showing the whole path to the entry."
2018 :group 'org-refile
2019 :type 'boolean)
2021 (defcustom org-refile-allow-creating-parent-nodes nil
2022 "Non-nil means allow to create new nodes as refile targets.
2023 New nodes are then created by adding \"/new node name\" to the completion
2024 of an existing node. When the value of this variable is `confirm',
2025 new node creation must be confirmed by the user (recommended)
2026 When nil, the completion must match an existing entry.
2028 Note that, if the new heading is not seen by the criteria
2029 listed in `org-refile-targets', multiple instances of the same
2030 heading would be created by trying again to file under the new
2031 heading."
2032 :group 'org-refile
2033 :type '(choice
2034 (const :tag "Never" nil)
2035 (const :tag "Always" t)
2036 (const :tag "Prompt for confirmation" confirm)))
2038 (defcustom org-refile-active-region-within-subtree nil
2039 "Non-nil means also refile active region within a subtree.
2041 By default `org-refile' doesn't allow refiling regions if they
2042 don't contain a set of subtrees, but it might be convenient to
2043 do so sometimes: in that case, the first line of the region is
2044 converted to a headline before refiling."
2045 :group 'org-refile
2046 :version "24.1"
2047 :type 'boolean)
2049 (defgroup org-todo nil
2050 "Options concerning TODO items in Org-mode."
2051 :tag "Org TODO"
2052 :group 'org)
2054 (defgroup org-progress nil
2055 "Options concerning Progress logging in Org-mode."
2056 :tag "Org Progress"
2057 :group 'org-time)
2059 (defvar org-todo-interpretation-widgets
2060 '((:tag "Sequence (cycling hits every state)" sequence)
2061 (:tag "Type (cycling directly to DONE)" type))
2062 "The available interpretation symbols for customizing `org-todo-keywords'.
2063 Interested libraries should add to this list.")
2065 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2066 "List of TODO entry keyword sequences and their interpretation.
2067 \\<org-mode-map>This is a list of sequences.
2069 Each sequence starts with a symbol, either `sequence' or `type',
2070 indicating if the keywords should be interpreted as a sequence of
2071 action steps, or as different types of TODO items. The first
2072 keywords are states requiring action - these states will select a headline
2073 for inclusion into the global TODO list Org-mode produces. If one of
2074 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2075 signify that no further action is necessary. If \"|\" is not found,
2076 the last keyword is treated as the only DONE state of the sequence.
2078 The command \\[org-todo] cycles an entry through these states, and one
2079 additional state where no keyword is present. For details about this
2080 cycling, see the manual.
2082 TODO keywords and interpretation can also be set on a per-file basis with
2083 the special #+SEQ_TODO and #+TYP_TODO lines.
2085 Each keyword can optionally specify a character for fast state selection
2086 \(in combination with the variable `org-use-fast-todo-selection')
2087 and specifiers for state change logging, using the same syntax
2088 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
2089 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2090 indicates to record a time stamp each time this state is selected.
2092 Each keyword may also specify if a timestamp or a note should be
2093 recorded when entering or leaving the state, by adding additional
2094 characters in the parenthesis after the keyword. This looks like this:
2095 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2096 record only the time of the state change. With X and Y being either
2097 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2098 Y when leaving the state if and only if the *target* state does not
2099 define X. You may omit any of the fast-selection key or X or /Y,
2100 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2102 For backward compatibility, this variable may also be just a list
2103 of keywords - in this case the interpretation (sequence or type) will be
2104 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2105 :group 'org-todo
2106 :group 'org-keywords
2107 :type '(choice
2108 (repeat :tag "Old syntax, just keywords"
2109 (string :tag "Keyword"))
2110 (repeat :tag "New syntax"
2111 (cons
2112 (choice
2113 :tag "Interpretation"
2114 ;;Quick and dirty way to see
2115 ;;`org-todo-interpretations'. This takes the
2116 ;;place of item arguments
2117 :convert-widget
2118 (lambda (widget)
2119 (widget-put widget
2120 :args (mapcar
2121 #'(lambda (x)
2122 (widget-convert
2123 (cons 'const x)))
2124 org-todo-interpretation-widgets))
2125 widget))
2126 (repeat
2127 (string :tag "Keyword"))))))
2129 (defvar org-todo-keywords-1 nil
2130 "All TODO and DONE keywords active in a buffer.")
2131 (make-variable-buffer-local 'org-todo-keywords-1)
2132 (defvar org-todo-keywords-for-agenda nil)
2133 (defvar org-done-keywords-for-agenda nil)
2134 (defvar org-drawers-for-agenda nil)
2135 (defvar org-todo-keyword-alist-for-agenda nil)
2136 (defvar org-tag-alist-for-agenda nil)
2137 (defvar org-agenda-contributing-files nil)
2138 (defvar org-not-done-keywords nil)
2139 (make-variable-buffer-local 'org-not-done-keywords)
2140 (defvar org-done-keywords nil)
2141 (make-variable-buffer-local 'org-done-keywords)
2142 (defvar org-todo-heads nil)
2143 (make-variable-buffer-local 'org-todo-heads)
2144 (defvar org-todo-sets nil)
2145 (make-variable-buffer-local 'org-todo-sets)
2146 (defvar org-todo-log-states nil)
2147 (make-variable-buffer-local 'org-todo-log-states)
2148 (defvar org-todo-kwd-alist nil)
2149 (make-variable-buffer-local 'org-todo-kwd-alist)
2150 (defvar org-todo-key-alist nil)
2151 (make-variable-buffer-local 'org-todo-key-alist)
2152 (defvar org-todo-key-trigger nil)
2153 (make-variable-buffer-local 'org-todo-key-trigger)
2155 (defcustom org-todo-interpretation 'sequence
2156 "Controls how TODO keywords are interpreted.
2157 This variable is in principle obsolete and is only used for
2158 backward compatibility, if the interpretation of todo keywords is
2159 not given already in `org-todo-keywords'. See that variable for
2160 more information."
2161 :group 'org-todo
2162 :group 'org-keywords
2163 :type '(choice (const sequence)
2164 (const type)))
2166 (defcustom org-use-fast-todo-selection t
2167 "Non-nil means use the fast todo selection scheme with C-c C-t.
2168 This variable describes if and under what circumstances the cycling
2169 mechanism for TODO keywords will be replaced by a single-key, direct
2170 selection scheme.
2172 When nil, fast selection is never used.
2174 When the symbol `prefix', it will be used when `org-todo' is called with
2175 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
2176 in an agenda buffer.
2178 When t, fast selection is used by default. In this case, the prefix
2179 argument forces cycling instead.
2181 In all cases, the special interface is only used if access keys have actually
2182 been assigned by the user, i.e. if keywords in the configuration are followed
2183 by a letter in parenthesis, like TODO(t)."
2184 :group 'org-todo
2185 :type '(choice
2186 (const :tag "Never" nil)
2187 (const :tag "By default" t)
2188 (const :tag "Only with C-u C-c C-t" prefix)))
2190 (defcustom org-provide-todo-statistics t
2191 "Non-nil means update todo statistics after insert and toggle.
2192 ALL-HEADLINES means update todo statistics by including headlines
2193 with no TODO keyword as well, counting them as not done.
2194 A list of TODO keywords means the same, but skip keywords that are
2195 not in this list.
2197 When this is set, todo statistics is updated in the parent of the
2198 current entry each time a todo state is changed."
2199 :group 'org-todo
2200 :type '(choice
2201 (const :tag "Yes, only for TODO entries" t)
2202 (const :tag "Yes, including all entries" 'all-headlines)
2203 (repeat :tag "Yes, for TODOs in this list"
2204 (string :tag "TODO keyword"))
2205 (other :tag "No TODO statistics" nil)))
2207 (defcustom org-hierarchical-todo-statistics t
2208 "Non-nil means TODO statistics covers just direct children.
2209 When nil, all entries in the subtree are considered.
2210 This has only an effect if `org-provide-todo-statistics' is set.
2211 To set this to nil for only a single subtree, use a COOKIE_DATA
2212 property and include the word \"recursive\" into the value."
2213 :group 'org-todo
2214 :type 'boolean)
2216 (defcustom org-after-todo-state-change-hook nil
2217 "Hook which is run after the state of a TODO item was changed.
2218 The new state (a string with a TODO keyword, or nil) is available in the
2219 Lisp variable `org-state'."
2220 :group 'org-todo
2221 :type 'hook)
2223 (defvar org-blocker-hook nil
2224 "Hook for functions that are allowed to block a state change.
2226 Each function gets as its single argument a property list, see
2227 `org-trigger-hook' for more information about this list.
2229 If any of the functions in this hook returns nil, the state change
2230 is blocked.")
2232 (defvar org-trigger-hook nil
2233 "Hook for functions that are triggered by a state change.
2235 Each function gets as its single argument a property list with at least
2236 the following elements:
2238 (:type type-of-change :position pos-at-entry-start
2239 :from old-state :to new-state)
2241 Depending on the type, more properties may be present.
2243 This mechanism is currently implemented for:
2245 TODO state changes
2246 ------------------
2247 :type todo-state-change
2248 :from previous state (keyword as a string), or nil, or a symbol
2249 'todo' or 'done', to indicate the general type of state.
2250 :to new state, like in :from")
2252 (defcustom org-enforce-todo-dependencies nil
2253 "Non-nil means undone TODO entries will block switching the parent to DONE.
2254 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2255 be blocked if any prior sibling is not yet done.
2256 Finally, if the parent is blocked because of ordered siblings of its own,
2257 the child will also be blocked."
2258 :set (lambda (var val)
2259 (set var val)
2260 (if val
2261 (add-hook 'org-blocker-hook
2262 'org-block-todo-from-children-or-siblings-or-parent)
2263 (remove-hook 'org-blocker-hook
2264 'org-block-todo-from-children-or-siblings-or-parent)))
2265 :group 'org-todo
2266 :type 'boolean)
2268 (defcustom org-enforce-todo-checkbox-dependencies nil
2269 "Non-nil means unchecked boxes will block switching the parent to DONE.
2270 When this is nil, checkboxes have no influence on switching TODO states.
2271 When non-nil, you first need to check off all check boxes before the TODO
2272 entry can be switched to DONE.
2273 This variable needs to be set before org.el is loaded, and you need to
2274 restart Emacs after a change to make the change effective. The only way
2275 to change is while Emacs is running is through the customize interface."
2276 :set (lambda (var val)
2277 (set var val)
2278 (if val
2279 (add-hook 'org-blocker-hook
2280 'org-block-todo-from-checkboxes)
2281 (remove-hook 'org-blocker-hook
2282 'org-block-todo-from-checkboxes)))
2283 :group 'org-todo
2284 :type 'boolean)
2286 (defcustom org-treat-insert-todo-heading-as-state-change nil
2287 "Non-nil means inserting a TODO heading is treated as state change.
2288 So when the command \\[org-insert-todo-heading] is used, state change
2289 logging will apply if appropriate. When nil, the new TODO item will
2290 be inserted directly, and no logging will take place."
2291 :group 'org-todo
2292 :type 'boolean)
2294 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2295 "Non-nil means switching TODO states with S-cursor counts as state change.
2296 This is the default behavior. However, setting this to nil allows a
2297 convenient way to select a TODO state and bypass any logging associated
2298 with that."
2299 :group 'org-todo
2300 :type 'boolean)
2302 (defcustom org-todo-state-tags-triggers nil
2303 "Tag changes that should be triggered by TODO state changes.
2304 This is a list. Each entry is
2306 (state-change (tag . flag) .......)
2308 State-change can be a string with a state, and empty string to indicate the
2309 state that has no TODO keyword, or it can be one of the symbols `todo'
2310 or `done', meaning any not-done or done state, respectively."
2311 :group 'org-todo
2312 :group 'org-tags
2313 :type '(repeat
2314 (cons (choice :tag "When changing to"
2315 (const :tag "Not-done state" todo)
2316 (const :tag "Done state" done)
2317 (string :tag "State"))
2318 (repeat
2319 (cons :tag "Tag action"
2320 (string :tag "Tag")
2321 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2323 (defcustom org-log-done nil
2324 "Information to record when a task moves to the DONE state.
2326 Possible values are:
2328 nil Don't add anything, just change the keyword
2329 time Add a time stamp to the task
2330 note Prompt for a note and add it with template `org-log-note-headings'
2332 This option can also be set with on a per-file-basis with
2334 #+STARTUP: nologdone
2335 #+STARTUP: logdone
2336 #+STARTUP: lognotedone
2338 You can have local logging settings for a subtree by setting the LOGGING
2339 property to one or more of these keywords."
2340 :group 'org-todo
2341 :group 'org-progress
2342 :type '(choice
2343 (const :tag "No logging" nil)
2344 (const :tag "Record CLOSED timestamp" time)
2345 (const :tag "Record CLOSED timestamp with note." note)))
2347 ;; Normalize old uses of org-log-done.
2348 (cond
2349 ((eq org-log-done t) (setq org-log-done 'time))
2350 ((and (listp org-log-done) (memq 'done org-log-done))
2351 (setq org-log-done 'note)))
2353 (defcustom org-log-reschedule nil
2354 "Information to record when the scheduling date of a tasks is modified.
2356 Possible values are:
2358 nil Don't add anything, just change the date
2359 time Add a time stamp to the task
2360 note Prompt for a note and add it with template `org-log-note-headings'
2362 This option can also be set with on a per-file-basis with
2364 #+STARTUP: nologreschedule
2365 #+STARTUP: logreschedule
2366 #+STARTUP: lognotereschedule"
2367 :group 'org-todo
2368 :group 'org-progress
2369 :type '(choice
2370 (const :tag "No logging" nil)
2371 (const :tag "Record timestamp" time)
2372 (const :tag "Record timestamp with note." note)))
2374 (defcustom org-log-redeadline nil
2375 "Information to record when the deadline date of a tasks is modified.
2377 Possible values are:
2379 nil Don't add anything, just change the date
2380 time Add a time stamp to the task
2381 note Prompt for a note and add it with template `org-log-note-headings'
2383 This option can also be set with on a per-file-basis with
2385 #+STARTUP: nologredeadline
2386 #+STARTUP: logredeadline
2387 #+STARTUP: lognoteredeadline
2389 You can have local logging settings for a subtree by setting the LOGGING
2390 property to one or more of these keywords."
2391 :group 'org-todo
2392 :group 'org-progress
2393 :type '(choice
2394 (const :tag "No logging" nil)
2395 (const :tag "Record timestamp" time)
2396 (const :tag "Record timestamp with note." note)))
2398 (defcustom org-log-note-clock-out nil
2399 "Non-nil means record a note when clocking out of an item.
2400 This can also be configured on a per-file basis by adding one of
2401 the following lines anywhere in the buffer:
2403 #+STARTUP: lognoteclock-out
2404 #+STARTUP: nolognoteclock-out"
2405 :group 'org-todo
2406 :group 'org-progress
2407 :type 'boolean)
2409 (defcustom org-log-done-with-time t
2410 "Non-nil means the CLOSED time stamp will contain date and time.
2411 When nil, only the date will be recorded."
2412 :group 'org-progress
2413 :type 'boolean)
2415 (defcustom org-log-note-headings
2416 '((done . "CLOSING NOTE %t")
2417 (state . "State %-12s from %-12S %t")
2418 (note . "Note taken on %t")
2419 (reschedule . "Rescheduled from %S on %t")
2420 (delschedule . "Not scheduled, was %S on %t")
2421 (redeadline . "New deadline from %S on %t")
2422 (deldeadline . "Removed deadline, was %S on %t")
2423 (refile . "Refiled on %t")
2424 (clock-out . ""))
2425 "Headings for notes added to entries.
2426 The value is an alist, with the car being a symbol indicating the note
2427 context, and the cdr is the heading to be used. The heading may also be the
2428 empty string.
2429 %t in the heading will be replaced by a time stamp.
2430 %T will be an active time stamp instead the default inactive one
2431 %d will be replaced by a short-format time stamp.
2432 %D will be replaced by an active short-format time stamp.
2433 %s will be replaced by the new TODO state, in double quotes.
2434 %S will be replaced by the old TODO state, in double quotes.
2435 %u will be replaced by the user name.
2436 %U will be replaced by the full user name.
2438 In fact, it is not a good idea to change the `state' entry, because
2439 agenda log mode depends on the format of these entries."
2440 :group 'org-todo
2441 :group 'org-progress
2442 :type '(list :greedy t
2443 (cons (const :tag "Heading when closing an item" done) string)
2444 (cons (const :tag
2445 "Heading when changing todo state (todo sequence only)"
2446 state) string)
2447 (cons (const :tag "Heading when just taking a note" note) string)
2448 (cons (const :tag "Heading when clocking out" clock-out) string)
2449 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2450 (cons (const :tag "Heading when rescheduling" reschedule) string)
2451 (cons (const :tag "Heading when changing deadline" redeadline) string)
2452 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2453 (cons (const :tag "Heading when refiling" refile) string)))
2455 (unless (assq 'note org-log-note-headings)
2456 (push '(note . "%t") org-log-note-headings))
2458 (defcustom org-log-into-drawer nil
2459 "Non-nil means insert state change notes and time stamps into a drawer.
2460 When nil, state changes notes will be inserted after the headline and
2461 any scheduling and clock lines, but not inside a drawer.
2463 The value of this variable should be the name of the drawer to use.
2464 LOGBOOK is proposed as the default drawer for this purpose, you can
2465 also set this to a string to define the drawer of your choice.
2467 A value of t is also allowed, representing \"LOGBOOK\".
2469 If this variable is set, `org-log-state-notes-insert-after-drawers'
2470 will be ignored.
2472 You can set the property LOG_INTO_DRAWER to overrule this setting for
2473 a subtree."
2474 :group 'org-todo
2475 :group 'org-progress
2476 :type '(choice
2477 (const :tag "Not into a drawer" nil)
2478 (const :tag "LOGBOOK" t)
2479 (string :tag "Other")))
2481 (if (fboundp 'defvaralias)
2482 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2484 (defun org-log-into-drawer ()
2485 "Return the value of `org-log-into-drawer', but let properties overrule.
2486 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2487 used instead of the default value."
2488 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit)))
2489 (cond
2490 ((or (not p) (equal p "nil")) org-log-into-drawer)
2491 ((equal p "t") "LOGBOOK")
2492 (t p))))
2494 (defcustom org-log-state-notes-insert-after-drawers nil
2495 "Non-nil means insert state change notes after any drawers in entry.
2496 Only the drawers that *immediately* follow the headline and the
2497 deadline/scheduled line are skipped.
2498 When nil, insert notes right after the heading and perhaps the line
2499 with deadline/scheduling if present.
2501 This variable will have no effect if `org-log-into-drawer' is
2502 set."
2503 :group 'org-todo
2504 :group 'org-progress
2505 :type 'boolean)
2507 (defcustom org-log-states-order-reversed t
2508 "Non-nil means the latest state note will be directly after heading.
2509 When nil, the state change notes will be ordered according to time."
2510 :group 'org-todo
2511 :group 'org-progress
2512 :type 'boolean)
2514 (defcustom org-todo-repeat-to-state nil
2515 "The TODO state to which a repeater should return the repeating task.
2516 By default this is the first task in a TODO sequence, or the previous state
2517 in a TODO_TYP set. But you can specify another task here.
2518 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2519 :group 'org-todo
2520 :version "24.1"
2521 :type '(choice (const :tag "Head of sequence" nil)
2522 (string :tag "Specific state")))
2524 (defcustom org-log-repeat 'time
2525 "Non-nil means record moving through the DONE state when triggering repeat.
2526 An auto-repeating task is immediately switched back to TODO when
2527 marked DONE. If you are not logging state changes (by adding \"@\"
2528 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2529 record a closing note, there will be no record of the task moving
2530 through DONE. This variable forces taking a note anyway.
2532 nil Don't force a record
2533 time Record a time stamp
2534 note Record a note
2536 This option can also be set with on a per-file-basis with
2538 #+STARTUP: logrepeat
2539 #+STARTUP: lognoterepeat
2540 #+STARTUP: nologrepeat
2542 You can have local logging settings for a subtree by setting the LOGGING
2543 property to one or more of these keywords."
2544 :group 'org-todo
2545 :group 'org-progress
2546 :type '(choice
2547 (const :tag "Don't force a record" nil)
2548 (const :tag "Force recording the DONE state" time)
2549 (const :tag "Force recording a note with the DONE state" note)))
2552 (defgroup org-priorities nil
2553 "Priorities in Org-mode."
2554 :tag "Org Priorities"
2555 :group 'org-todo)
2557 (defcustom org-enable-priority-commands t
2558 "Non-nil means priority commands are active.
2559 When nil, these commands will be disabled, so that you never accidentally
2560 set a priority."
2561 :group 'org-priorities
2562 :type 'boolean)
2564 (defcustom org-highest-priority ?A
2565 "The highest priority of TODO items. A character like ?A, ?B etc.
2566 Must have a smaller ASCII number than `org-lowest-priority'."
2567 :group 'org-priorities
2568 :type 'character)
2570 (defcustom org-lowest-priority ?C
2571 "The lowest priority of TODO items. A character like ?A, ?B etc.
2572 Must have a larger ASCII number than `org-highest-priority'."
2573 :group 'org-priorities
2574 :type 'character)
2576 (defcustom org-default-priority ?B
2577 "The default priority of TODO items.
2578 This is the priority an item gets if no explicit priority is given.
2579 When starting to cycle on an empty priority the first step in the cycle
2580 depends on `org-priority-start-cycle-with-default'. The resulting first
2581 step priority must not exceed the range from `org-highest-priority' to
2582 `org-lowest-priority' which means that `org-default-priority' has to be
2583 in this range exclusive or inclusive the range boundaries. Else the
2584 first step refuses to set the default and the second will fall back
2585 to (depending on the command used) the highest or lowest priority."
2586 :group 'org-priorities
2587 :type 'character)
2589 (defcustom org-priority-start-cycle-with-default t
2590 "Non-nil means start with default priority when starting to cycle.
2591 When this is nil, the first step in the cycle will be (depending on the
2592 command used) one higher or lower than the default priority.
2593 See also `org-default-priority'."
2594 :group 'org-priorities
2595 :type 'boolean)
2597 (defcustom org-get-priority-function nil
2598 "Function to extract the priority from a string.
2599 The string is normally the headline. If this is nil Org computes the
2600 priority from the priority cookie like [#A] in the headline. It returns
2601 an integer, increasing by 1000 for each priority level.
2602 The user can set a different function here, which should take a string
2603 as an argument and return the numeric priority."
2604 :group 'org-priorities
2605 :version "24.1"
2606 :type 'function)
2608 (defgroup org-time nil
2609 "Options concerning time stamps and deadlines in Org-mode."
2610 :tag "Org Time"
2611 :group 'org)
2613 (defcustom org-insert-labeled-timestamps-at-point nil
2614 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2615 When nil, these labeled time stamps are forces into the second line of an
2616 entry, just after the headline. When scheduling from the global TODO list,
2617 the time stamp will always be forced into the second line."
2618 :group 'org-time
2619 :type 'boolean)
2621 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2622 "Formats for `format-time-string' which are used for time stamps.
2623 It is not recommended to change this constant.")
2625 (defcustom org-time-stamp-rounding-minutes '(0 5)
2626 "Number of minutes to round time stamps to.
2627 These are two values, the first applies when first creating a time stamp.
2628 The second applies when changing it with the commands `S-up' and `S-down'.
2629 When changing the time stamp, this means that it will change in steps
2630 of N minutes, as given by the second value.
2632 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2633 numbers should be factors of 60, so for example 5, 10, 15.
2635 When this is larger than 1, you can still force an exact time stamp by using
2636 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2637 and by using a prefix arg to `S-up/down' to specify the exact number
2638 of minutes to shift."
2639 :group 'org-time
2640 :get #'(lambda (var) ; Make sure both elements are there
2641 (if (integerp (default-value var))
2642 (list (default-value var) 5)
2643 (default-value var)))
2644 :type '(list
2645 (integer :tag "when inserting times")
2646 (integer :tag "when modifying times")))
2648 ;; Normalize old customizations of this variable.
2649 (when (integerp org-time-stamp-rounding-minutes)
2650 (setq org-time-stamp-rounding-minutes
2651 (list org-time-stamp-rounding-minutes
2652 org-time-stamp-rounding-minutes)))
2654 (defcustom org-display-custom-times nil
2655 "Non-nil means overlay custom formats over all time stamps.
2656 The formats are defined through the variable `org-time-stamp-custom-formats'.
2657 To turn this on on a per-file basis, insert anywhere in the file:
2658 #+STARTUP: customtime"
2659 :group 'org-time
2660 :set 'set-default
2661 :type 'sexp)
2662 (make-variable-buffer-local 'org-display-custom-times)
2664 (defcustom org-time-stamp-custom-formats
2665 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2666 "Custom formats for time stamps. See `format-time-string' for the syntax.
2667 These are overlaid over the default ISO format if the variable
2668 `org-display-custom-times' is set. Time like %H:%M should be at the
2669 end of the second format. The custom formats are also honored by export
2670 commands, if custom time display is turned on at the time of export."
2671 :group 'org-time
2672 :type 'sexp)
2674 (defun org-time-stamp-format (&optional long inactive)
2675 "Get the right format for a time string."
2676 (let ((f (if long (cdr org-time-stamp-formats)
2677 (car org-time-stamp-formats))))
2678 (if inactive
2679 (concat "[" (substring f 1 -1) "]")
2680 f)))
2682 (defcustom org-time-clocksum-format "%d:%02d"
2683 "The format string used when creating CLOCKSUM lines.
2684 This is also used when org-mode generates a time duration."
2685 :group 'org-time
2686 :type 'string)
2688 (defcustom org-time-clocksum-use-fractional nil
2689 "If non-nil, \\[org-clock-display] uses fractional times.
2690 org-mode generates a time duration."
2691 :group 'org-time
2692 :type 'boolean)
2694 (defcustom org-time-clocksum-fractional-format "%.2f"
2695 "The format string used when creating CLOCKSUM lines, or when
2696 org-mode generates a time duration."
2697 :group 'org-time
2698 :type 'string)
2700 (defcustom org-deadline-warning-days 14
2701 "No. of days before expiration during which a deadline becomes active.
2702 This variable governs the display in sparse trees and in the agenda.
2703 When 0 or negative, it means use this number (the absolute value of it)
2704 even if a deadline has a different individual lead time specified.
2706 Custom commands can set this variable in the options section."
2707 :group 'org-time
2708 :group 'org-agenda-daily/weekly
2709 :type 'integer)
2711 (defcustom org-read-date-prefer-future t
2712 "Non-nil means assume future for incomplete date input from user.
2713 This affects the following situations:
2714 1. The user gives a month but not a year.
2715 For example, if it is April and you enter \"feb 2\", this will be read
2716 as Feb 2, *next* year. \"May 5\", however, will be this year.
2717 2. The user gives a day, but no month.
2718 For example, if today is the 15th, and you enter \"3\", Org-mode will
2719 read this as the third of *next* month. However, if you enter \"17\",
2720 it will be considered as *this* month.
2722 If you set this variable to the symbol `time', then also the following
2723 will work:
2725 3. If the user gives a time, but no day. If the time is before now,
2726 to will be interpreted as tomorrow.
2728 Currently none of this works for ISO week specifications.
2730 When this option is nil, the current day, month and year will always be
2731 used as defaults.
2733 See also `org-agenda-jump-prefer-future'."
2734 :group 'org-time
2735 :type '(choice
2736 (const :tag "Never" nil)
2737 (const :tag "Check month and day" t)
2738 (const :tag "Check month, day, and time" time)))
2740 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
2741 "Should the agenda jump command prefer the future for incomplete dates?
2742 The default is to do the same as configured in `org-read-date-prefer-future'.
2743 But you can also set a deviating value here.
2744 This may t or nil, or the symbol `org-read-date-prefer-future'."
2745 :group 'org-agenda
2746 :group 'org-time
2747 :version "24.1"
2748 :type '(choice
2749 (const :tag "Use org-read-date-prefer-future"
2750 org-read-date-prefer-future)
2751 (const :tag "Never" nil)
2752 (const :tag "Always" t)))
2754 (defcustom org-read-date-force-compatible-dates t
2755 "Should date/time prompt force dates that are guaranteed to work in Emacs?
2757 Depending on the system Emacs is running on, certain dates cannot
2758 be represented with the type used internally to represent time.
2759 Dates between 1970-1-1 and 2038-1-1 can always be represented
2760 correctly. Some systems allow for earlier dates, some for later,
2761 some for both. One way to find out it to insert any date into an
2762 Org buffer, putting the cursor on the year and hitting S-up and
2763 S-down to test the range.
2765 When this variable is set to t, the date/time prompt will not let
2766 you specify dates outside the 1970-2037 range, so it is certain that
2767 these dates will work in whatever version of Emacs you are
2768 running, and also that you can move a file from one Emacs implementation
2769 to another. WHenever Org is forcing the year for you, it will display
2770 a message and beep.
2772 When this variable is nil, Org will check if the date is
2773 representable in the specific Emacs implementation you are using.
2774 If not, it will force a year, usually the current year, and beep
2775 to remind you. Currently this setting is not recommended because
2776 the likelihood that you will open your Org files in an Emacs that
2777 has limited date range is not negligible.
2779 A workaround for this problem is to use diary sexp dates for time
2780 stamps outside of this range."
2781 :group 'org-time
2782 :version "24.1"
2783 :type 'boolean)
2785 (defcustom org-read-date-display-live t
2786 "Non-nil means display current interpretation of date prompt live.
2787 This display will be in an overlay, in the minibuffer."
2788 :group 'org-time
2789 :type 'boolean)
2791 (defcustom org-read-date-popup-calendar t
2792 "Non-nil means pop up a calendar when prompting for a date.
2793 In the calendar, the date can be selected with mouse-1. However, the
2794 minibuffer will also be active, and you can simply enter the date as well.
2795 When nil, only the minibuffer will be available."
2796 :group 'org-time
2797 :type 'boolean)
2798 (if (fboundp 'defvaralias)
2799 (defvaralias 'org-popup-calendar-for-date-prompt
2800 'org-read-date-popup-calendar))
2802 (defcustom org-read-date-minibuffer-setup-hook nil
2803 "Hook to be used to set up keys for the date/time interface.
2804 Add key definitions to `minibuffer-local-map', which will be a temporary
2805 copy."
2806 :group 'org-time
2807 :type 'hook)
2809 (defcustom org-extend-today-until 0
2810 "The hour when your day really ends. Must be an integer.
2811 This has influence for the following applications:
2812 - When switching the agenda to \"today\". It it is still earlier than
2813 the time given here, the day recognized as TODAY is actually yesterday.
2814 - When a date is read from the user and it is still before the time given
2815 here, the current date and time will be assumed to be yesterday, 23:59.
2816 Also, timestamps inserted in remember templates follow this rule.
2818 IMPORTANT: This is a feature whose implementation is and likely will
2819 remain incomplete. Really, it is only here because past midnight seems to
2820 be the favorite working time of John Wiegley :-)"
2821 :group 'org-time
2822 :type 'integer)
2824 (defcustom org-use-effective-time nil
2825 "If non-nil, consider `org-extend-today-until' when creating timestamps.
2826 For example, if `org-extend-today-until' is 8, and it's 4am, then the
2827 \"effective time\" of any timestamps between midnight and 8am will be
2828 23:59 of the previous day."
2829 :group 'org-time
2830 :version "24.1"
2831 :type 'boolean)
2833 (defcustom org-edit-timestamp-down-means-later nil
2834 "Non-nil means S-down will increase the time in a time stamp.
2835 When nil, S-up will increase."
2836 :group 'org-time
2837 :type 'boolean)
2839 (defcustom org-calendar-follow-timestamp-change t
2840 "Non-nil means make the calendar window follow timestamp changes.
2841 When a timestamp is modified and the calendar window is visible, it will be
2842 moved to the new date."
2843 :group 'org-time
2844 :type 'boolean)
2846 (defgroup org-tags nil
2847 "Options concerning tags in Org-mode."
2848 :tag "Org Tags"
2849 :group 'org)
2851 (defcustom org-tag-alist nil
2852 "List of tags allowed in Org-mode files.
2853 When this list is nil, Org-mode will base TAG input on what is already in the
2854 buffer.
2855 The value of this variable is an alist, the car of each entry must be a
2856 keyword as a string, the cdr may be a character that is used to select
2857 that tag through the fast-tag-selection interface.
2858 See the manual for details."
2859 :group 'org-tags
2860 :type '(repeat
2861 (choice
2862 (cons (string :tag "Tag name")
2863 (character :tag "Access char"))
2864 (list :tag "Start radio group"
2865 (const :startgroup)
2866 (option (string :tag "Group description")))
2867 (list :tag "End radio group"
2868 (const :endgroup)
2869 (option (string :tag "Group description")))
2870 (const :tag "New line" (:newline)))))
2872 (defcustom org-tag-persistent-alist nil
2873 "List of tags that will always appear in all Org-mode files.
2874 This is in addition to any in buffer settings or customizations
2875 of `org-tag-alist'.
2876 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2877 The value of this variable is an alist, the car of each entry must be a
2878 keyword as a string, the cdr may be a character that is used to select
2879 that tag through the fast-tag-selection interface.
2880 See the manual for details.
2881 To disable these tags on a per-file basis, insert anywhere in the file:
2882 #+STARTUP: noptag"
2883 :group 'org-tags
2884 :type '(repeat
2885 (choice
2886 (cons (string :tag "Tag name")
2887 (character :tag "Access char"))
2888 (const :tag "Start radio group" (:startgroup))
2889 (const :tag "End radio group" (:endgroup))
2890 (const :tag "New line" (:newline)))))
2892 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
2893 "If non-nil, always offer completion for all tags of all agenda files.
2894 Instead of customizing this variable directly, you might want to
2895 set it locally for capture buffers, because there no list of
2896 tags in that file can be created dynamically (there are none).
2898 (add-hook 'org-capture-mode-hook
2899 (lambda ()
2900 (set (make-local-variable
2901 'org-complete-tags-always-offer-all-agenda-tags)
2902 t)))"
2903 :group 'org-tags
2904 :version "24.1"
2905 :type 'boolean)
2907 (defvar org-file-tags nil
2908 "List of tags that can be inherited by all entries in the file.
2909 The tags will be inherited if the variable `org-use-tag-inheritance'
2910 says they should be.
2911 This variable is populated from #+FILETAGS lines.")
2913 (defcustom org-use-fast-tag-selection 'auto
2914 "Non-nil means use fast tag selection scheme.
2915 This is a special interface to select and deselect tags with single keys.
2916 When nil, fast selection is never used.
2917 When the symbol `auto', fast selection is used if and only if selection
2918 characters for tags have been configured, either through the variable
2919 `org-tag-alist' or through a #+TAGS line in the buffer.
2920 When t, fast selection is always used and selection keys are assigned
2921 automatically if necessary."
2922 :group 'org-tags
2923 :type '(choice
2924 (const :tag "Always" t)
2925 (const :tag "Never" nil)
2926 (const :tag "When selection characters are configured" 'auto)))
2928 (defcustom org-fast-tag-selection-single-key nil
2929 "Non-nil means fast tag selection exits after first change.
2930 When nil, you have to press RET to exit it.
2931 During fast tag selection, you can toggle this flag with `C-c'.
2932 This variable can also have the value `expert'. In this case, the window
2933 displaying the tags menu is not even shown, until you press C-c again."
2934 :group 'org-tags
2935 :type '(choice
2936 (const :tag "No" nil)
2937 (const :tag "Yes" t)
2938 (const :tag "Expert" expert)))
2940 (defvar org-fast-tag-selection-include-todo nil
2941 "Non-nil means fast tags selection interface will also offer TODO states.
2942 This is an undocumented feature, you should not rely on it.")
2944 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2945 "The column to which tags should be indented in a headline.
2946 If this number is positive, it specifies the column. If it is negative,
2947 it means that the tags should be flushright to that column. For example,
2948 -80 works well for a normal 80 character screen.
2949 When 0, place tags directly after headline text, with only one space in
2950 between."
2951 :group 'org-tags
2952 :type 'integer)
2954 (defcustom org-auto-align-tags t
2955 "Non-nil keeps tags aligned when modifying headlines.
2956 Some operations (i.e. demoting) change the length of a headline and
2957 therefore shift the tags around. With this option turned on, after
2958 each such operation the tags are again aligned to `org-tags-column'."
2959 :group 'org-tags
2960 :type 'boolean)
2962 (defcustom org-use-tag-inheritance t
2963 "Non-nil means tags in levels apply also for sublevels.
2964 When nil, only the tags directly given in a specific line apply there.
2965 This may also be a list of tags that should be inherited, or a regexp that
2966 matches tags that should be inherited. Additional control is possible
2967 with the variable `org-tags-exclude-from-inheritance' which gives an
2968 explicit list of tags to be excluded from inheritance., even if the value of
2969 `org-use-tag-inheritance' would select it for inheritance.
2971 If this option is t, a match early-on in a tree can lead to a large
2972 number of matches in the subtree when constructing the agenda or creating
2973 a sparse tree. If you only want to see the first match in a tree during
2974 a search, check out the variable `org-tags-match-list-sublevels'."
2975 :group 'org-tags
2976 :type '(choice
2977 (const :tag "Not" nil)
2978 (const :tag "Always" t)
2979 (repeat :tag "Specific tags" (string :tag "Tag"))
2980 (regexp :tag "Tags matched by regexp")))
2982 (defcustom org-tags-exclude-from-inheritance nil
2983 "List of tags that should never be inherited.
2984 This is a way to exclude a few tags from inheritance. For way to do
2985 the opposite, to actively allow inheritance for selected tags,
2986 see the variable `org-use-tag-inheritance'."
2987 :group 'org-tags
2988 :type '(repeat (string :tag "Tag")))
2990 (defun org-tag-inherit-p (tag)
2991 "Check if TAG is one that should be inherited."
2992 (cond
2993 ((member tag org-tags-exclude-from-inheritance) nil)
2994 ((eq org-use-tag-inheritance t) t)
2995 ((not org-use-tag-inheritance) nil)
2996 ((stringp org-use-tag-inheritance)
2997 (string-match org-use-tag-inheritance tag))
2998 ((listp org-use-tag-inheritance)
2999 (member tag org-use-tag-inheritance))
3000 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3002 (defcustom org-tags-match-list-sublevels t
3003 "Non-nil means list also sublevels of headlines matching a search.
3004 This variable applies to tags/property searches, and also to stuck
3005 projects because this search is based on a tags match as well.
3007 When set to the symbol `indented', sublevels are indented with
3008 leading dots.
3010 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3011 the sublevels of a headline matching a tag search often also match
3012 the same search. Listing all of them can create very long lists.
3013 Setting this variable to nil causes subtrees of a match to be skipped.
3015 This variable is semi-obsolete and probably should always be true. It
3016 is better to limit inheritance to certain tags using the variables
3017 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3018 :group 'org-tags
3019 :type '(choice
3020 (const :tag "No, don't list them" nil)
3021 (const :tag "Yes, do list them" t)
3022 (const :tag "List them, indented with leading dots" indented)))
3024 (defcustom org-tags-sort-function nil
3025 "When set, tags are sorted using this function as a comparator."
3026 :group 'org-tags
3027 :type '(choice
3028 (const :tag "No sorting" nil)
3029 (const :tag "Alphabetical" string<)
3030 (const :tag "Reverse alphabetical" string>)
3031 (function :tag "Custom function" nil)))
3033 (defvar org-tags-history nil
3034 "History of minibuffer reads for tags.")
3035 (defvar org-last-tags-completion-table nil
3036 "The last used completion table for tags.")
3037 (defvar org-after-tags-change-hook nil
3038 "Hook that is run after the tags in a line have changed.")
3040 (defgroup org-properties nil
3041 "Options concerning properties in Org-mode."
3042 :tag "Org Properties"
3043 :group 'org)
3045 (defcustom org-property-format "%-10s %s"
3046 "How property key/value pairs should be formatted by `indent-line'.
3047 When `indent-line' hits a property definition, it will format the line
3048 according to this format, mainly to make sure that the values are
3049 lined-up with respect to each other."
3050 :group 'org-properties
3051 :type 'string)
3053 (defcustom org-properties-postprocess-alist nil
3054 "Alist of properties and functions to adjust inserted values.
3055 Elements of this alist must be of the form
3057 ([string] [function])
3059 where [string] must be a property name and [function] must be a
3060 lambda expression: this lambda expression must take one argument,
3061 the value to adjust, and return the new value as a string.
3063 For example, this element will allow the property \"Remaining\"
3064 to be updated wrt the relation between the \"Effort\" property
3065 and the clock summary:
3067 ((\"Remaining\" (lambda(value)
3068 (let ((clocksum (org-clock-sum-current-item))
3069 (effort (org-duration-string-to-minutes
3070 (org-entry-get (point) \"Effort\"))))
3071 (org-minutes-to-hh:mm-string (- effort clocksum))))))"
3072 :group 'org-properties
3073 :version "24.1"
3074 :type 'alist)
3076 (defcustom org-use-property-inheritance nil
3077 "Non-nil means properties apply also for sublevels.
3079 This setting is chiefly used during property searches. Turning it on can
3080 cause significant overhead when doing a search, which is why it is not
3081 on by default.
3083 When nil, only the properties directly given in the current entry count.
3084 When t, every property is inherited. The value may also be a list of
3085 properties that should have inheritance, or a regular expression matching
3086 properties that should be inherited.
3088 However, note that some special properties use inheritance under special
3089 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3090 and the properties ending in \"_ALL\" when they are used as descriptor
3091 for valid values of a property.
3093 Note for programmers:
3094 When querying an entry with `org-entry-get', you can control if inheritance
3095 should be used. By default, `org-entry-get' looks only at the local
3096 properties. You can request inheritance by setting the inherit argument
3097 to t (to force inheritance) or to `selective' (to respect the setting
3098 in this variable)."
3099 :group 'org-properties
3100 :type '(choice
3101 (const :tag "Not" nil)
3102 (const :tag "Always" t)
3103 (repeat :tag "Specific properties" (string :tag "Property"))
3104 (regexp :tag "Properties matched by regexp")))
3106 (defun org-property-inherit-p (property)
3107 "Check if PROPERTY is one that should be inherited."
3108 (cond
3109 ((eq org-use-property-inheritance t) t)
3110 ((not org-use-property-inheritance) nil)
3111 ((stringp org-use-property-inheritance)
3112 (string-match org-use-property-inheritance property))
3113 ((listp org-use-property-inheritance)
3114 (member property org-use-property-inheritance))
3115 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3117 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3118 "The default column format, if no other format has been defined.
3119 This variable can be set on the per-file basis by inserting a line
3121 #+COLUMNS: %25ITEM ....."
3122 :group 'org-properties
3123 :type 'string)
3125 (defcustom org-columns-ellipses ".."
3126 "The ellipses to be used when a field in column view is truncated.
3127 When this is the empty string, as many characters as possible are shown,
3128 but then there will be no visual indication that the field has been truncated.
3129 When this is a string of length N, the last N characters of a truncated
3130 field are replaced by this string. If the column is narrower than the
3131 ellipses string, only part of the ellipses string will be shown."
3132 :group 'org-properties
3133 :type 'string)
3135 (defcustom org-columns-modify-value-for-display-function nil
3136 "Function that modifies values for display in column view.
3137 For example, it can be used to cut out a certain part from a time stamp.
3138 The function must take 2 arguments:
3140 column-title The title of the column (*not* the property name)
3141 value The value that should be modified.
3143 The function should return the value that should be displayed,
3144 or nil if the normal value should be used."
3145 :group 'org-properties
3146 :type 'function)
3148 (defcustom org-effort-property "Effort"
3149 "The property that is being used to keep track of effort estimates.
3150 Effort estimates given in this property need to have the format H:MM."
3151 :group 'org-properties
3152 :group 'org-progress
3153 :type '(string :tag "Property"))
3155 (defconst org-global-properties-fixed
3156 '(("VISIBILITY_ALL" . "folded children content all")
3157 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3158 "List of property/value pairs that can be inherited by any entry.
3160 These are fixed values, for the preset properties. The user variable
3161 that can be used to add to this list is `org-global-properties'.
3163 The entries in this list are cons cells where the car is a property
3164 name and cdr is a string with the value. If the value represents
3165 multiple items like an \"_ALL\" property, separate the items by
3166 spaces.")
3168 (defcustom org-global-properties nil
3169 "List of property/value pairs that can be inherited by any entry.
3171 This list will be combined with the constant `org-global-properties-fixed'.
3173 The entries in this list are cons cells where the car is a property
3174 name and cdr is a string with the value.
3176 You can set buffer-local values for the same purpose in the variable
3177 `org-file-properties' this by adding lines like
3179 #+PROPERTY: NAME VALUE"
3180 :group 'org-properties
3181 :type '(repeat
3182 (cons (string :tag "Property")
3183 (string :tag "Value"))))
3185 (defvar org-file-properties nil
3186 "List of property/value pairs that can be inherited by any entry.
3187 Valid for the current buffer.
3188 This variable is populated from #+PROPERTY lines.")
3189 (make-variable-buffer-local 'org-file-properties)
3191 (defgroup org-agenda nil
3192 "Options concerning agenda views in Org-mode."
3193 :tag "Org Agenda"
3194 :group 'org)
3196 (defvar org-category nil
3197 "Variable used by org files to set a category for agenda display.
3198 Such files should use a file variable to set it, for example
3200 # -*- mode: org; org-category: \"ELisp\"
3202 or contain a special line
3204 #+CATEGORY: ELisp
3206 If the file does not specify a category, then file's base name
3207 is used instead.")
3208 (make-variable-buffer-local 'org-category)
3209 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3211 (defcustom org-agenda-files nil
3212 "The files to be used for agenda display.
3213 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3214 \\[org-remove-file]. You can also use customize to edit the list.
3216 If an entry is a directory, all files in that directory that are matched by
3217 `org-agenda-file-regexp' will be part of the file list.
3219 If the value of the variable is not a list but a single file name, then
3220 the list of agenda files is actually stored and maintained in that file, one
3221 agenda file per line. In this file paths can be given relative to
3222 `org-directory'. Tilde expansion and environment variable substitution
3223 are also made."
3224 :group 'org-agenda
3225 :type '(choice
3226 (repeat :tag "List of files and directories" file)
3227 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3229 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3230 "Regular expression to match files for `org-agenda-files'.
3231 If any element in the list in that variable contains a directory instead
3232 of a normal file, all files in that directory that are matched by this
3233 regular expression will be included."
3234 :group 'org-agenda
3235 :type 'regexp)
3237 (defcustom org-agenda-text-search-extra-files nil
3238 "List of extra files to be searched by text search commands.
3239 These files will be search in addition to the agenda files by the
3240 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3241 Note that these files will only be searched for text search commands,
3242 not for the other agenda views like todo lists, tag searches or the weekly
3243 agenda. This variable is intended to list notes and possibly archive files
3244 that should also be searched by these two commands.
3245 In fact, if the first element in the list is the symbol `agenda-archives',
3246 than all archive files of all agenda files will be added to the search
3247 scope."
3248 :group 'org-agenda
3249 :type '(set :greedy t
3250 (const :tag "Agenda Archives" agenda-archives)
3251 (repeat :inline t (file))))
3253 (if (fboundp 'defvaralias)
3254 (defvaralias 'org-agenda-multi-occur-extra-files
3255 'org-agenda-text-search-extra-files))
3257 (defcustom org-agenda-skip-unavailable-files nil
3258 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3259 A nil value means to remove them, after a query, from the list."
3260 :group 'org-agenda
3261 :type 'boolean)
3263 (defcustom org-calendar-to-agenda-key [?c]
3264 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3265 The command `org-calendar-goto-agenda' will be bound to this key. The
3266 default is the character `c' because then `c' can be used to switch back and
3267 forth between agenda and calendar."
3268 :group 'org-agenda
3269 :type 'sexp)
3271 (defcustom org-calendar-agenda-action-key [?k]
3272 "The key to be installed in `calendar-mode-map' for agenda-action.
3273 The command `org-agenda-action' will be bound to this key. The
3274 default is the character `k' because we use the same key in the agenda."
3275 :group 'org-agenda
3276 :type 'sexp)
3278 (defcustom org-calendar-insert-diary-entry-key [?i]
3279 "The key to be installed in `calendar-mode-map' for adding diary entries.
3280 This option is irrelevant until `org-agenda-diary-file' has been configured
3281 to point to an Org-mode file. When that is the case, the command
3282 `org-agenda-diary-entry' will be bound to the key given here, by default
3283 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3284 if you want to continue doing this, you need to change this to a different
3285 key."
3286 :group 'org-agenda
3287 :type 'sexp)
3289 (defcustom org-agenda-diary-file 'diary-file
3290 "File to which to add new entries with the `i' key in agenda and calendar.
3291 When this is the symbol `diary-file', the functionality in the Emacs
3292 calendar will be used to add entries to the `diary-file'. But when this
3293 points to a file, `org-agenda-diary-entry' will be used instead."
3294 :group 'org-agenda
3295 :type '(choice
3296 (const :tag "The standard Emacs diary file" diary-file)
3297 (file :tag "Special Org file diary entries")))
3299 (eval-after-load "calendar"
3300 '(progn
3301 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3302 'org-calendar-goto-agenda)
3303 (org-defkey calendar-mode-map org-calendar-agenda-action-key
3304 'org-agenda-action)
3305 (add-hook 'calendar-mode-hook
3306 (lambda ()
3307 (unless (eq org-agenda-diary-file 'diary-file)
3308 (define-key calendar-mode-map
3309 org-calendar-insert-diary-entry-key
3310 'org-agenda-diary-entry))))))
3312 (defgroup org-latex nil
3313 "Options for embedding LaTeX code into Org-mode."
3314 :tag "Org LaTeX"
3315 :group 'org)
3317 (defcustom org-format-latex-options
3318 '(:foreground default :background default :scale 1.0
3319 :html-foreground "Black" :html-background "Transparent"
3320 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3321 "Options for creating images from LaTeX fragments.
3322 This is a property list with the following properties:
3323 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3324 `default' means use the foreground of the default face.
3325 :background the background color, or \"Transparent\".
3326 `default' means use the background of the default face.
3327 :scale a scaling factor for the size of the images, to get more pixels
3328 :html-foreground, :html-background, :html-scale
3329 the same numbers for HTML export.
3330 :matchers a list indicating which matchers should be used to
3331 find LaTeX fragments. Valid members of this list are:
3332 \"begin\" find environments
3333 \"$1\" find single characters surrounded by $.$
3334 \"$\" find math expressions surrounded by $...$
3335 \"$$\" find math expressions surrounded by $$....$$
3336 \"\\(\" find math expressions surrounded by \\(...\\)
3337 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3338 :group 'org-latex
3339 :type 'plist)
3341 (defcustom org-format-latex-signal-error t
3342 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3343 When nil, just push out a message."
3344 :group 'org-latex
3345 :version "24.1"
3346 :type 'boolean)
3348 (defcustom org-latex-to-mathml-jar-file nil
3349 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3350 Use this to specify additional executable file say a jar file.
3352 When using MathToWeb as the converter, specify the full-path to
3353 your mathtoweb.jar file."
3354 :group 'org-latex
3355 :version "24.1"
3356 :type '(choice
3357 (const :tag "None" nil)
3358 (file :tag "JAR file" :must-match t)))
3360 (defcustom org-latex-to-mathml-convert-command nil
3361 "Command to convert LaTeX fragments to MathML.
3362 Replace format-specifiers in the command as noted below and use
3363 `shell-command' to convert LaTeX to MathML.
3364 %j: Executable file in fully expanded form as specified by
3365 `org-latex-to-mathml-jar-file'.
3366 %I: Input LaTeX file in fully expanded form
3367 %o: Output MathML file
3368 This command is used by `org-create-math-formula'.
3370 When using MathToWeb as the converter, set this to
3371 \"java -jar %j -unicode -force -df %o %I\"."
3372 :group 'org-latex
3373 :version "24.1"
3374 :type '(choice
3375 (const :tag "None" nil)
3376 (string :tag "\nShell command")))
3378 (defcustom org-latex-create-formula-image-program 'dvipng
3379 "Program to convert LaTeX fragments with.
3381 dvipng Process the LaTeX fragments to dvi file, then convert
3382 dvi files to png files using dvipng.
3383 This will also include processing of non-math environments.
3384 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3385 to convert pdf files to png files"
3386 :group 'org-latex
3387 :version "24.1"
3388 :type '(choice
3389 (const :tag "dvipng" dvipng)
3390 (const :tag "imagemagick" imagemagick)))
3392 (defun org-format-latex-mathml-available-p ()
3393 "Return t if `org-latex-to-mathml-convert-command' is usable."
3394 (save-match-data
3395 (when (and (boundp 'org-latex-to-mathml-convert-command)
3396 org-latex-to-mathml-convert-command)
3397 (let ((executable (car (split-string
3398 org-latex-to-mathml-convert-command))))
3399 (when (executable-find executable)
3400 (if (string-match
3401 "%j" org-latex-to-mathml-convert-command)
3402 (file-readable-p org-latex-to-mathml-jar-file)
3403 t))))))
3405 (defcustom org-format-latex-header "\\documentclass{article}
3406 \\usepackage[usenames]{color}
3407 \\usepackage{amsmath}
3408 \\usepackage[mathscr]{eucal}
3409 \\pagestyle{empty} % do not remove
3410 \[PACKAGES]
3411 \[DEFAULT-PACKAGES]
3412 % The settings below are copied from fullpage.sty
3413 \\setlength{\\textwidth}{\\paperwidth}
3414 \\addtolength{\\textwidth}{-3cm}
3415 \\setlength{\\oddsidemargin}{1.5cm}
3416 \\addtolength{\\oddsidemargin}{-2.54cm}
3417 \\setlength{\\evensidemargin}{\\oddsidemargin}
3418 \\setlength{\\textheight}{\\paperheight}
3419 \\addtolength{\\textheight}{-\\headheight}
3420 \\addtolength{\\textheight}{-\\headsep}
3421 \\addtolength{\\textheight}{-\\footskip}
3422 \\addtolength{\\textheight}{-3cm}
3423 \\setlength{\\topmargin}{1.5cm}
3424 \\addtolength{\\topmargin}{-2.54cm}"
3425 "The document header used for processing LaTeX fragments.
3426 It is imperative that this header make sure that no page number
3427 appears on the page. The package defined in the variables
3428 `org-export-latex-default-packages-alist' and `org-export-latex-packages-alist'
3429 will either replace the placeholder \"[PACKAGES]\" in this header, or they
3430 will be appended."
3431 :group 'org-latex
3432 :type 'string)
3434 (defvar org-format-latex-header-extra nil)
3436 (defun org-set-packages-alist (var val)
3437 "Set the packages alist and make sure it has 3 elements per entry."
3438 (set var (mapcar (lambda (x)
3439 (if (and (consp x) (= (length x) 2))
3440 (list (car x) (nth 1 x) t)
3442 val)))
3444 (defun org-get-packages-alist (var)
3446 "Get the packages alist and make sure it has 3 elements per entry."
3447 (mapcar (lambda (x)
3448 (if (and (consp x) (= (length x) 2))
3449 (list (car x) (nth 1 x) t)
3451 (default-value var)))
3453 ;; The following variables are defined here because is it also used
3454 ;; when formatting latex fragments. Originally it was part of the
3455 ;; LaTeX exporter, which is why the name includes "export".
3456 (defcustom org-export-latex-default-packages-alist
3457 '(("AUTO" "inputenc" t)
3458 ("T1" "fontenc" t)
3459 ("" "fixltx2e" nil)
3460 ("" "graphicx" t)
3461 ("" "longtable" nil)
3462 ("" "float" nil)
3463 ("" "wrapfig" nil)
3464 ("" "soul" t)
3465 ("" "textcomp" t)
3466 ("" "marvosym" t)
3467 ("" "wasysym" t)
3468 ("" "latexsym" t)
3469 ("" "amssymb" t)
3470 ("" "hyperref" nil)
3471 "\\tolerance=1000"
3473 "Alist of default packages to be inserted in the header.
3474 Change this only if one of the packages here causes an incompatibility
3475 with another package you are using.
3476 The packages in this list are needed by one part or another of Org-mode
3477 to function properly.
3479 - inputenc, fontenc: for basic font and character selection
3480 - textcomp, marvosymb, wasysym, latexsym, amssym: for various symbols used
3481 for interpreting the entities in `org-entities'. You can skip some of these
3482 packages if you don't use any of the symbols in it.
3483 - graphicx: for including images
3484 - float, wrapfig: for figure placement
3485 - longtable: for long tables
3486 - hyperref: for cross references
3488 Therefore you should not modify this variable unless you know what you
3489 are doing. The one reason to change it anyway is that you might be loading
3490 some other package that conflicts with one of the default packages.
3491 Each cell is of the format \( \"options\" \"package\" snippet-flag\).
3492 If SNIPPET-FLAG is t, the package also needs to be included when
3493 compiling LaTeX snippets into images for inclusion into HTML."
3494 :group 'org-export-latex
3495 :set 'org-set-packages-alist
3496 :get 'org-get-packages-alist
3497 :version "24.1"
3498 :type '(repeat
3499 (choice
3500 (list :tag "options/package pair"
3501 (string :tag "options")
3502 (string :tag "package")
3503 (boolean :tag "Snippet"))
3504 (string :tag "A line of LaTeX"))))
3506 (defcustom org-export-latex-packages-alist nil
3507 "Alist of packages to be inserted in every LaTeX header.
3508 These will be inserted after `org-export-latex-default-packages-alist'.
3509 Each cell is of the format \( \"options\" \"package\" snippet-flag \).
3510 SNIPPET-FLAG, when t, indicates that this package is also needed when
3511 turning LaTeX snippets into images for inclusion into HTML.
3512 Make sure that you only list packages here which:
3513 - you want in every file
3514 - do not conflict with the default packages in
3515 `org-export-latex-default-packages-alist'
3516 - do not conflict with the setup in `org-format-latex-header'."
3517 :group 'org-export-latex
3518 :set 'org-set-packages-alist
3519 :get 'org-get-packages-alist
3520 :type '(repeat
3521 (choice
3522 (list :tag "options/package pair"
3523 (string :tag "options")
3524 (string :tag "package")
3525 (boolean :tag "Snippet"))
3526 (string :tag "A line of LaTeX"))))
3529 (defgroup org-appearance nil
3530 "Settings for Org-mode appearance."
3531 :tag "Org Appearance"
3532 :group 'org)
3534 (defcustom org-level-color-stars-only nil
3535 "Non-nil means fontify only the stars in each headline.
3536 When nil, the entire headline is fontified.
3537 Changing it requires restart of `font-lock-mode' to become effective
3538 also in regions already fontified."
3539 :group 'org-appearance
3540 :type 'boolean)
3542 (defcustom org-hide-leading-stars nil
3543 "Non-nil means hide the first N-1 stars in a headline.
3544 This works by using the face `org-hide' for these stars. This
3545 face is white for a light background, and black for a dark
3546 background. You may have to customize the face `org-hide' to
3547 make this work.
3548 Changing it requires restart of `font-lock-mode' to become effective
3549 also in regions already fontified.
3550 You may also set this on a per-file basis by adding one of the following
3551 lines to the buffer:
3553 #+STARTUP: hidestars
3554 #+STARTUP: showstars"
3555 :group 'org-appearance
3556 :type 'boolean)
3558 (defcustom org-hidden-keywords nil
3559 "List of symbols corresponding to keywords to be hidden the org buffer.
3560 For example, a value '(title) for this list will make the document's title
3561 appear in the buffer without the initial #+TITLE: keyword."
3562 :group 'org-appearance
3563 :version "24.1"
3564 :type '(set (const :tag "#+AUTHOR" author)
3565 (const :tag "#+DATE" date)
3566 (const :tag "#+EMAIL" email)
3567 (const :tag "#+TITLE" title)))
3569 (defcustom org-fontify-done-headline nil
3570 "Non-nil means change the face of a headline if it is marked DONE.
3571 Normally, only the TODO/DONE keyword indicates the state of a headline.
3572 When this is non-nil, the headline after the keyword is set to the
3573 `org-headline-done' as an additional indication."
3574 :group 'org-appearance
3575 :type 'boolean)
3577 (defcustom org-fontify-emphasized-text t
3578 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3579 Changing this variable requires a restart of Emacs to take effect."
3580 :group 'org-appearance
3581 :type 'boolean)
3583 (defcustom org-fontify-whole-heading-line nil
3584 "Non-nil means fontify the whole line for headings.
3585 This is useful when setting a background color for the
3586 org-level-* faces."
3587 :group 'org-appearance
3588 :type 'boolean)
3590 (defcustom org-highlight-latex-fragments-and-specials nil
3591 "Non-nil means fontify what is treated specially by the exporters."
3592 :group 'org-appearance
3593 :type 'boolean)
3595 (defcustom org-hide-emphasis-markers nil
3596 "Non-nil mean font-lock should hide the emphasis marker characters."
3597 :group 'org-appearance
3598 :type 'boolean)
3600 (defcustom org-pretty-entities nil
3601 "Non-nil means show entities as UTF8 characters.
3602 When nil, the \\name form remains in the buffer."
3603 :group 'org-appearance
3604 :version "24.1"
3605 :type 'boolean)
3607 (defcustom org-pretty-entities-include-sub-superscripts t
3608 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3609 :group 'org-appearance
3610 :version "24.1"
3611 :type 'boolean)
3613 (defvar org-emph-re nil
3614 "Regular expression for matching emphasis.
3615 After a match, the match groups contain these elements:
3616 0 The match of the full regular expression, including the characters
3617 before and after the proper match
3618 1 The character before the proper match, or empty at beginning of line
3619 2 The proper match, including the leading and trailing markers
3620 3 The leading marker like * or /, indicating the type of highlighting
3621 4 The text between the emphasis markers, not including the markers
3622 5 The character after the match, empty at the end of a line")
3623 (defvar org-verbatim-re nil
3624 "Regular expression for matching verbatim text.")
3625 (defvar org-emphasis-regexp-components) ; defined just below
3626 (defvar org-emphasis-alist) ; defined just below
3627 (defun org-set-emph-re (var val)
3628 "Set variable and compute the emphasis regular expression."
3629 (set var val)
3630 (when (and (boundp 'org-emphasis-alist)
3631 (boundp 'org-emphasis-regexp-components)
3632 org-emphasis-alist org-emphasis-regexp-components)
3633 (let* ((e org-emphasis-regexp-components)
3634 (pre (car e))
3635 (post (nth 1 e))
3636 (border (nth 2 e))
3637 (body (nth 3 e))
3638 (nl (nth 4 e))
3639 (body1 (concat body "*?"))
3640 (markers (mapconcat 'car org-emphasis-alist ""))
3641 (vmarkers (mapconcat
3642 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3643 org-emphasis-alist "")))
3644 ;; make sure special characters appear at the right position in the class
3645 (if (string-match "\\^" markers)
3646 (setq markers (concat (replace-match "" t t markers) "^")))
3647 (if (string-match "-" markers)
3648 (setq markers (concat (replace-match "" t t markers) "-")))
3649 (if (string-match "\\^" vmarkers)
3650 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3651 (if (string-match "-" vmarkers)
3652 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3653 (if (> nl 0)
3654 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3655 (int-to-string nl) "\\}")))
3656 ;; Make the regexp
3657 (setq org-emph-re
3658 (concat "\\([" pre "]\\|^\\)"
3659 "\\("
3660 "\\([" markers "]\\)"
3661 "\\("
3662 "[^" border "]\\|"
3663 "[^" border "]"
3664 body1
3665 "[^" border "]"
3666 "\\)"
3667 "\\3\\)"
3668 "\\([" post "]\\|$\\)"))
3669 (setq org-verbatim-re
3670 (concat "\\([" pre "]\\|^\\)"
3671 "\\("
3672 "\\([" vmarkers "]\\)"
3673 "\\("
3674 "[^" border "]\\|"
3675 "[^" border "]"
3676 body1
3677 "[^" border "]"
3678 "\\)"
3679 "\\3\\)"
3680 "\\([" post "]\\|$\\)")))))
3682 (defcustom org-emphasis-regexp-components
3683 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
3684 "Components used to build the regular expression for emphasis.
3685 This is a list with five entries. Terminology: In an emphasis string
3686 like \" *strong word* \", we call the initial space PREMATCH, the final
3687 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3688 and \"trong wor\" is the body. The different components in this variable
3689 specify what is allowed/forbidden in each part:
3691 pre Chars allowed as prematch. Beginning of line will be allowed too.
3692 post Chars allowed as postmatch. End of line will be allowed too.
3693 border The chars *forbidden* as border characters.
3694 body-regexp A regexp like \".\" to match a body character. Don't use
3695 non-shy groups here, and don't allow newline here.
3696 newline The maximum number of newlines allowed in an emphasis exp.
3698 Use customize to modify this, or restart Emacs after changing it."
3699 :group 'org-appearance
3700 :set 'org-set-emph-re
3701 :type '(list
3702 (sexp :tag "Allowed chars in pre ")
3703 (sexp :tag "Allowed chars in post ")
3704 (sexp :tag "Forbidden chars in border ")
3705 (sexp :tag "Regexp for body ")
3706 (integer :tag "number of newlines allowed")
3707 (option (boolean :tag "Please ignore this button"))))
3709 (defcustom org-emphasis-alist
3710 `(("*" bold "<b>" "</b>")
3711 ("/" italic "<i>" "</i>")
3712 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
3713 ("=" org-code "<code>" "</code>" verbatim)
3714 ("~" org-verbatim "<code>" "</code>" verbatim)
3715 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
3716 "<del>" "</del>")
3718 "Special syntax for emphasized text.
3719 Text starting and ending with a special character will be emphasized, for
3720 example *bold*, _underlined_ and /italic/. This variable sets the marker
3721 characters, the face to be used by font-lock for highlighting in Org-mode
3722 Emacs buffers, and the HTML tags to be used for this.
3723 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
3724 For DocBook export, see the variable `org-export-docbook-emphasis-alist'.
3725 Use customize to modify this, or restart Emacs after changing it."
3726 :group 'org-appearance
3727 :set 'org-set-emph-re
3728 :type '(repeat
3729 (list
3730 (string :tag "Marker character")
3731 (choice
3732 (face :tag "Font-lock-face")
3733 (plist :tag "Face property list"))
3734 (string :tag "HTML start tag")
3735 (string :tag "HTML end tag")
3736 (option (const verbatim)))))
3738 (defvar org-protecting-blocks
3739 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
3740 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
3741 This is needed for font-lock setup.")
3743 ;;; Miscellaneous options
3745 (defgroup org-completion nil
3746 "Completion in Org-mode."
3747 :tag "Org Completion"
3748 :group 'org)
3750 (defcustom org-completion-use-ido nil
3751 "Non-nil means use ido completion wherever possible.
3752 Note that `ido-mode' must be active for this variable to be relevant.
3753 If you decide to turn this variable on, you might well want to turn off
3754 `org-outline-path-complete-in-steps'.
3755 See also `org-completion-use-iswitchb'."
3756 :group 'org-completion
3757 :type 'boolean)
3759 (defcustom org-completion-use-iswitchb nil
3760 "Non-nil means use iswitchb completion wherever possible.
3761 Note that `iswitchb-mode' must be active for this variable to be relevant.
3762 If you decide to turn this variable on, you might well want to turn off
3763 `org-outline-path-complete-in-steps'.
3764 Note that this variable has only an effect if `org-completion-use-ido' is nil."
3765 :group 'org-completion
3766 :type 'boolean)
3768 (defcustom org-completion-fallback-command 'hippie-expand
3769 "The expansion command called by \\[pcomplete] in normal context.
3770 Normal means, no org-mode-specific context."
3771 :group 'org-completion
3772 :type 'function)
3774 ;;; Functions and variables from their packages
3775 ;; Declared here to avoid compiler warnings
3777 ;; XEmacs only
3778 (defvar outline-mode-menu-heading)
3779 (defvar outline-mode-menu-show)
3780 (defvar outline-mode-menu-hide)
3781 (defvar zmacs-regions) ; XEmacs regions
3783 ;; Emacs only
3784 (defvar mark-active)
3786 ;; Various packages
3787 (declare-function calendar-absolute-from-iso "cal-iso" (date))
3788 (declare-function calendar-forward-day "cal-move" (arg))
3789 (declare-function calendar-goto-date "cal-move" (date))
3790 (declare-function calendar-goto-today "cal-move" ())
3791 (declare-function calendar-iso-from-absolute "cal-iso" (date))
3792 (defvar calc-embedded-close-formula)
3793 (defvar calc-embedded-open-formula)
3794 (declare-function cdlatex-tab "ext:cdlatex" ())
3795 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
3796 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3797 (defvar font-lock-unfontify-region-function)
3798 (declare-function iswitchb-read-buffer "iswitchb"
3799 (prompt &optional default require-match start matches-set))
3800 (defvar iswitchb-temp-buflist)
3801 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
3802 (defvar org-agenda-tags-todo-honor-ignore-options)
3803 (declare-function org-agenda-skip "org-agenda" ())
3804 (declare-function
3805 org-agenda-format-item "org-agenda"
3806 (extra txt &optional category tags dotime noprefix remove-re habitp))
3807 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
3808 (declare-function org-agenda-change-all-lines "org-agenda"
3809 (newhead hdmarker &optional fixface just-this))
3810 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
3811 (declare-function org-agenda-maybe-redo "org-agenda" ())
3812 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
3813 (beg end))
3814 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
3815 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
3816 "org-agenda" (&optional end))
3817 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
3818 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
3819 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
3820 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
3821 (declare-function org-indent-mode "org-indent" (&optional arg))
3822 (declare-function parse-time-string "parse-time" (string))
3823 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
3824 (declare-function org-export-latex-fix-inputenc "org-latex" ())
3825 (declare-function orgtbl-send-table "org-table" (&optional maybe))
3826 (defvar remember-data-file)
3827 (defvar texmathp-why)
3828 (declare-function speedbar-line-directory "speedbar" (&optional depth))
3829 (declare-function table--at-cell-p "table" (position &optional object at-column))
3831 (defvar w3m-current-url)
3832 (defvar w3m-current-title)
3834 (defvar org-latex-regexps)
3836 ;;; Autoload and prepare some org modules
3838 ;; Some table stuff that needs to be defined here, because it is used
3839 ;; by the functions setting up org-mode or checking for table context.
3841 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
3842 "Detect an org-type or table-type table.")
3843 (defconst org-table-line-regexp "^[ \t]*|"
3844 "Detect an org-type table line.")
3845 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
3846 "Detect an org-type table line.")
3847 (defconst org-table-hline-regexp "^[ \t]*|-"
3848 "Detect an org-type table hline.")
3849 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
3850 "Detect a table-type table hline.")
3851 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
3852 "Detect the first line outside a table when searching from within it.
3853 This works for both table types.")
3855 ;; Autoload the functions in org-table.el that are needed by functions here.
3857 (eval-and-compile
3858 (org-autoload "org-table"
3859 '(org-table-align org-table-begin org-table-blank-field
3860 org-table-convert org-table-convert-region org-table-copy-down
3861 org-table-copy-region org-table-create
3862 org-table-create-or-convert-from-region
3863 org-table-create-with-table.el org-table-current-dline
3864 org-table-cut-region org-table-delete-column org-table-edit-field
3865 org-table-edit-formulas org-table-end org-table-eval-formula
3866 org-table-export org-table-field-info
3867 org-table-get-stored-formulas org-table-goto-column
3868 org-table-hline-and-move org-table-import org-table-insert-column
3869 org-table-insert-hline org-table-insert-row org-table-iterate
3870 org-table-justify-field-maybe org-table-kill-row
3871 org-table-maybe-eval-formula org-table-maybe-recalculate-line
3872 org-table-move-column org-table-move-column-left
3873 org-table-move-column-right org-table-move-row
3874 org-table-move-row-down org-table-move-row-up
3875 org-table-next-field org-table-next-row org-table-paste-rectangle
3876 org-table-previous-field org-table-recalculate
3877 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
3878 org-table-toggle-coordinate-overlays
3879 org-table-toggle-formula-debugger org-table-wrap-region
3880 orgtbl-mode turn-on-orgtbl org-table-to-lisp
3881 orgtbl-to-generic orgtbl-to-tsv orgtbl-to-csv orgtbl-to-latex
3882 orgtbl-to-orgtbl orgtbl-to-html orgtbl-to-texinfo)))
3884 (defun org-at-table-p (&optional table-type)
3885 "Return t if the cursor is inside an org-type table.
3886 If TABLE-TYPE is non-nil, also check for table.el-type tables."
3887 (if org-enable-table-editor
3888 (save-excursion
3889 (beginning-of-line 1)
3890 (looking-at (if table-type org-table-any-line-regexp
3891 org-table-line-regexp)))
3892 nil))
3893 (defsubst org-table-p () (org-at-table-p))
3895 (defun org-at-table.el-p ()
3896 "Return t if and only if we are at a table.el table."
3897 (and (org-at-table-p 'any)
3898 (save-excursion
3899 (goto-char (org-table-begin 'any))
3900 (looking-at org-table1-hline-regexp))))
3901 (defun org-table-recognize-table.el ()
3902 "If there is a table.el table nearby, recognize it and move into it."
3903 (if org-table-tab-recognizes-table.el
3904 (if (org-at-table.el-p)
3905 (progn
3906 (beginning-of-line 1)
3907 (if (looking-at org-table-dataline-regexp)
3909 (if (looking-at org-table1-hline-regexp)
3910 (progn
3911 (beginning-of-line 2)
3912 (if (looking-at org-table-any-border-regexp)
3913 (beginning-of-line -1)))))
3914 (if (re-search-forward "|" (org-table-end t) t)
3915 (progn
3916 (require 'table)
3917 (if (table--at-cell-p (point))
3919 (message "recognizing table.el table...")
3920 (table-recognize-table)
3921 (message "recognizing table.el table...done")))
3922 (error "This should not happen"))
3924 nil)
3925 nil))
3927 (defun org-at-table-hline-p ()
3928 "Return t if the cursor is inside a hline in a table."
3929 (if org-enable-table-editor
3930 (save-excursion
3931 (beginning-of-line 1)
3932 (looking-at org-table-hline-regexp))
3933 nil))
3935 (defvar org-table-clean-did-remove-column nil)
3937 (defun org-table-map-tables (function &optional quietly)
3938 "Apply FUNCTION to the start of all tables in the buffer."
3939 (save-excursion
3940 (save-restriction
3941 (widen)
3942 (goto-char (point-min))
3943 (while (re-search-forward org-table-any-line-regexp nil t)
3944 (unless quietly
3945 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
3946 (beginning-of-line 1)
3947 (when (and (looking-at org-table-line-regexp)
3948 ;; Exclude tables in src/example/verbatim/clocktable blocks
3949 (not (org-in-block-p '("src" "example"))))
3950 (save-excursion (funcall function))
3951 (or (looking-at org-table-line-regexp)
3952 (forward-char 1)))
3953 (re-search-forward org-table-any-border-regexp nil 1))))
3954 (unless quietly (message "Mapping tables: done")))
3956 ;; Declare and autoload functions from org-exp.el & Co
3958 (declare-function org-default-export-plist "org-exp")
3959 (declare-function org-infile-export-plist "org-exp")
3960 (declare-function org-get-current-options "org-exp")
3961 (eval-and-compile
3962 (org-autoload "org-exp"
3963 '(org-export org-export-visible
3964 org-insert-export-options-template
3965 org-table-clean-before-export))
3966 (org-autoload "org-ascii"
3967 '(org-export-as-ascii org-export-ascii-preprocess
3968 org-export-as-ascii-to-buffer org-replace-region-by-ascii
3969 org-export-region-as-ascii))
3970 (org-autoload "org-latex"
3971 '(org-export-as-latex-batch org-export-as-latex-to-buffer
3972 org-replace-region-by-latex org-export-region-as-latex
3973 org-export-as-latex org-export-as-pdf
3974 org-export-as-pdf-and-open))
3975 (org-autoload "org-html"
3976 '(org-export-as-html-and-open
3977 org-export-as-html-batch org-export-as-html-to-buffer
3978 org-replace-region-by-html org-export-region-as-html
3979 org-export-as-html))
3980 (org-autoload "org-docbook"
3981 '(org-export-as-docbook-batch org-export-as-docbook-to-buffer
3982 org-replace-region-by-docbook org-export-region-as-docbook
3983 org-export-as-docbook-pdf org-export-as-docbook-pdf-and-open
3984 org-export-as-docbook))
3985 (org-autoload "org-icalendar"
3986 '(org-export-icalendar-this-file
3987 org-export-icalendar-all-agenda-files
3988 org-export-icalendar-combine-agenda-files))
3989 (org-autoload "org-xoxo" '(org-export-as-xoxo))
3990 (org-autoload "org-beamer" '(org-beamer-mode org-beamer-sectioning)))
3992 ;; Declare and autoload functions from org-agenda.el
3994 (eval-and-compile
3995 (org-autoload "org-agenda"
3996 '(org-agenda org-agenda-list org-search-view
3997 org-todo-list org-tags-view org-agenda-list-stuck-projects
3998 org-diary org-agenda-to-appt
3999 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
4001 ;; Autoload org-remember
4003 (eval-and-compile
4004 (org-autoload "org-remember"
4005 '(org-remember-insinuate org-remember-annotation
4006 org-remember-apply-template org-remember org-remember-handler)))
4008 (eval-and-compile
4009 (org-autoload "org-capture"
4010 '(org-capture org-capture-insert-template-here
4011 org-capture-import-remember-templates)))
4013 ;; Autoload org-clock.el
4015 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
4016 (beg end))
4017 (declare-function org-clock-update-mode-line "org-clock" ())
4018 (declare-function org-resolve-clocks "org-clock"
4019 (&optional also-non-dangling-p prompt last-valid))
4020 (defvar org-clock-start-time)
4021 (defvar org-clock-marker (make-marker)
4022 "Marker recording the last clock-in.")
4023 (defvar org-clock-hd-marker (make-marker)
4024 "Marker recording the last clock-in, but the headline position.")
4025 (defvar org-clock-heading ""
4026 "The heading of the current clock entry.")
4027 (defun org-clock-is-active ()
4028 "Return non-nil if clock is currently running.
4029 The return value is actually the clock marker."
4030 (marker-buffer org-clock-marker))
4032 (eval-and-compile
4033 (org-autoload
4034 "org-clock"
4035 '(org-clock-in org-clock-out org-clock-cancel
4036 org-clock-goto org-clock-sum org-clock-display
4037 org-clock-remove-overlays org-clock-report
4038 org-clocktable-shift org-dblock-write:clocktable
4039 org-get-clocktable org-resolve-clocks)))
4041 (defun org-clock-update-time-maybe ()
4042 "If this is a CLOCK line, update it and return t.
4043 Otherwise, return nil."
4044 (interactive)
4045 (save-excursion
4046 (beginning-of-line 1)
4047 (skip-chars-forward " \t")
4048 (when (looking-at org-clock-string)
4049 (let ((re (concat "[ \t]*" org-clock-string
4050 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
4051 "\\([ \t]*=>.*\\)?\\)?"))
4052 ts te h m s neg)
4053 (cond
4054 ((not (looking-at re))
4055 nil)
4056 ((not (match-end 2))
4057 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4058 (> org-clock-marker (point))
4059 (<= org-clock-marker (point-at-eol)))
4060 ;; The clock is running here
4061 (setq org-clock-start-time
4062 (apply 'encode-time
4063 (org-parse-time-string (match-string 1))))
4064 (org-clock-update-mode-line)))
4066 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
4067 (end-of-line 1)
4068 (setq ts (match-string 1)
4069 te (match-string 3))
4070 (setq s (- (org-float-time
4071 (apply 'encode-time (org-parse-time-string te)))
4072 (org-float-time
4073 (apply 'encode-time (org-parse-time-string ts))))
4074 neg (< s 0)
4075 s (abs s)
4076 h (floor (/ s 3600))
4077 s (- s (* 3600 h))
4078 m (floor (/ s 60))
4079 s (- s (* 60 s)))
4080 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
4081 t))))))
4083 (defun org-check-running-clock ()
4084 "Check if the current buffer contains the running clock.
4085 If yes, offer to stop it and to save the buffer with the changes."
4086 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4087 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4088 (buffer-name))))
4089 (org-clock-out)
4090 (when (y-or-n-p "Save changed buffer?")
4091 (save-buffer))))
4093 (defun org-clocktable-try-shift (dir n)
4094 "Check if this line starts a clock table, if yes, shift the time block."
4095 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4096 (org-clocktable-shift dir n)))
4098 ;; Autoload org-timer.el
4100 (eval-and-compile
4101 (org-autoload
4102 "org-timer"
4103 '(org-timer-start org-timer org-timer-item
4104 org-timer-change-times-in-region
4105 org-timer-set-timer
4106 org-timer-reset-timers
4107 org-timer-show-remaining-time)))
4109 ;; Autoload org-feed.el
4111 (eval-and-compile
4112 (org-autoload
4113 "org-feed"
4114 '(org-feed-update org-feed-update-all org-feed-goto-inbox)))
4117 ;; Autoload org-indent.el
4119 ;; Define the variable already here, to make sure we have it.
4120 (defvar org-indent-mode nil
4121 "Non-nil if Org-Indent mode is enabled.
4122 Use the command `org-indent-mode' to change this variable.")
4124 (eval-and-compile
4125 (org-autoload
4126 "org-indent"
4127 '(org-indent-mode)))
4129 ;; Autoload org-mobile.el
4131 (eval-and-compile
4132 (org-autoload
4133 "org-mobile"
4134 '(org-mobile-push org-mobile-pull org-mobile-create-sumo-agenda)))
4136 ;; Autoload archiving code
4137 ;; The stuff that is needed for cycling and tags has to be defined here.
4139 (defgroup org-archive nil
4140 "Options concerning archiving in Org-mode."
4141 :tag "Org Archive"
4142 :group 'org-structure)
4144 (defcustom org-archive-location "%s_archive::"
4145 "The location where subtrees should be archived.
4147 The value of this variable is a string, consisting of two parts,
4148 separated by a double-colon. The first part is a filename and
4149 the second part is a headline.
4151 When the filename is omitted, archiving happens in the same file.
4152 %s in the filename will be replaced by the current file
4153 name (without the directory part). Archiving to a different file
4154 is useful to keep archived entries from contributing to the
4155 Org-mode Agenda.
4157 The archived entries will be filed as subtrees of the specified
4158 headline. When the headline is omitted, the subtrees are simply
4159 filed away at the end of the file, as top-level entries. Also in
4160 the heading you can use %s to represent the file name, this can be
4161 useful when using the same archive for a number of different files.
4163 Here are a few examples:
4164 \"%s_archive::\"
4165 If the current file is Projects.org, archive in file
4166 Projects.org_archive, as top-level trees. This is the default.
4168 \"::* Archived Tasks\"
4169 Archive in the current file, under the top-level headline
4170 \"* Archived Tasks\".
4172 \"~/org/archive.org::\"
4173 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4175 \"~/org/archive.org::* From %s\"
4176 Archive in file ~/org/archive.org (absolute path), under headlines
4177 \"From FILENAME\" where file name is the current file name.
4179 \"~/org/datetree.org::datetree/* Finished Tasks\"
4180 The \"datetree/\" string is special, signifying to archive
4181 items to the datetree. Items are placed in either the CLOSED
4182 date of the item, or the current date if there is no CLOSED date.
4183 The heading will be a subentry to the current date. There doesn't
4184 need to be a heading, but there always needs to be a slash after
4185 datetree. For example, to store archived items directly in the
4186 datetree, use \"~/org/datetree.org::datetree/\".
4188 \"basement::** Finished Tasks\"
4189 Archive in file ./basement (relative path), as level 3 trees
4190 below the level 2 heading \"** Finished Tasks\".
4192 You may set this option on a per-file basis by adding to the buffer a
4193 line like
4195 #+ARCHIVE: basement::** Finished Tasks
4197 You may also define it locally for a subtree by setting an ARCHIVE property
4198 in the entry. If such a property is found in an entry, or anywhere up
4199 the hierarchy, it will be used."
4200 :group 'org-archive
4201 :type 'string)
4203 (defcustom org-archive-tag "ARCHIVE"
4204 "The tag that marks a subtree as archived.
4205 An archived subtree does not open during visibility cycling, and does
4206 not contribute to the agenda listings.
4207 After changing this, font-lock must be restarted in the relevant buffers to
4208 get the proper fontification."
4209 :group 'org-archive
4210 :group 'org-keywords
4211 :type 'string)
4213 (defcustom org-agenda-skip-archived-trees t
4214 "Non-nil means the agenda will skip any items located in archived trees.
4215 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4216 variable is no longer recommended, you should leave it at the value t.
4217 Instead, use the key `v' to cycle the archives-mode in the agenda."
4218 :group 'org-archive
4219 :group 'org-agenda-skip
4220 :type 'boolean)
4222 (defcustom org-columns-skip-archived-trees t
4223 "Non-nil means ignore archived trees when creating column view."
4224 :group 'org-archive
4225 :group 'org-properties
4226 :type 'boolean)
4228 (defcustom org-cycle-open-archived-trees nil
4229 "Non-nil means `org-cycle' will open archived trees.
4230 An archived tree is a tree marked with the tag ARCHIVE.
4231 When nil, archived trees will stay folded. You can still open them with
4232 normal outline commands like `show-all', but not with the cycling commands."
4233 :group 'org-archive
4234 :group 'org-cycle
4235 :type 'boolean)
4237 (defcustom org-sparse-tree-open-archived-trees nil
4238 "Non-nil means sparse tree construction shows matches in archived trees.
4239 When nil, matches in these trees are highlighted, but the trees are kept in
4240 collapsed state."
4241 :group 'org-archive
4242 :group 'org-sparse-trees
4243 :type 'boolean)
4245 (defun org-cycle-hide-archived-subtrees (state)
4246 "Re-hide all archived subtrees after a visibility state change."
4247 (when (and (not org-cycle-open-archived-trees)
4248 (not (memq state '(overview folded))))
4249 (save-excursion
4250 (let* ((globalp (memq state '(contents all)))
4251 (beg (if globalp (point-min) (point)))
4252 (end (if globalp (point-max) (org-end-of-subtree t))))
4253 (org-hide-archived-subtrees beg end)
4254 (goto-char beg)
4255 (if (looking-at (concat ".*:" org-archive-tag ":"))
4256 (message "%s" (substitute-command-keys
4257 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4259 (defun org-force-cycle-archived ()
4260 "Cycle subtree even if it is archived."
4261 (interactive)
4262 (setq this-command 'org-cycle)
4263 (let ((org-cycle-open-archived-trees t))
4264 (call-interactively 'org-cycle)))
4266 (defun org-hide-archived-subtrees (beg end)
4267 "Re-hide all archived subtrees after a visibility state change."
4268 (save-excursion
4269 (let* ((re (concat ":" org-archive-tag ":")))
4270 (goto-char beg)
4271 (while (re-search-forward re end t)
4272 (when (org-at-heading-p)
4273 (org-flag-subtree t)
4274 (org-end-of-subtree t))))))
4276 (defun org-flag-subtree (flag)
4277 (save-excursion
4278 (org-back-to-heading t)
4279 (outline-end-of-heading)
4280 (outline-flag-region (point)
4281 (progn (org-end-of-subtree t) (point))
4282 flag)))
4284 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4286 (eval-and-compile
4287 (org-autoload "org-archive"
4288 '(org-add-archive-files org-archive-subtree
4289 org-archive-to-archive-sibling org-toggle-archive-tag
4290 org-archive-subtree-default
4291 org-archive-subtree-default-with-confirmation)))
4293 ;; Autoload Column View Code
4295 (declare-function org-columns-number-to-string "org-colview")
4296 (declare-function org-columns-get-format-and-top-level "org-colview")
4297 (declare-function org-columns-compute "org-colview")
4299 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4300 '(org-columns-number-to-string org-columns-get-format-and-top-level
4301 org-columns-compute org-agenda-columns org-columns-remove-overlays
4302 org-columns org-insert-columns-dblock org-dblock-write:columnview))
4304 ;; Autoload ID code
4306 (declare-function org-id-store-link "org-id")
4307 (declare-function org-id-locations-load "org-id")
4308 (declare-function org-id-locations-save "org-id")
4309 (defvar org-id-track-globally)
4310 (org-autoload "org-id"
4311 '(org-id-get-create org-id-new org-id-copy org-id-get
4312 org-id-get-with-outline-path-completion
4313 org-id-get-with-outline-drilling org-id-store-link
4314 org-id-goto org-id-find org-id-store-link))
4316 ;; Autoload Plotting Code
4318 (org-autoload "org-plot"
4319 '(org-plot/gnuplot))
4321 ;;; Variables for pre-computed regular expressions, all buffer local
4323 (defvar org-drawer-regexp nil
4324 "Matches first line of a hidden block.")
4325 (make-variable-buffer-local 'org-drawer-regexp)
4326 (defvar org-todo-regexp nil
4327 "Matches any of the TODO state keywords.")
4328 (make-variable-buffer-local 'org-todo-regexp)
4329 (defvar org-not-done-regexp nil
4330 "Matches any of the TODO state keywords except the last one.")
4331 (make-variable-buffer-local 'org-not-done-regexp)
4332 (defvar org-not-done-heading-regexp nil
4333 "Matches a TODO headline that is not done.")
4334 (make-variable-buffer-local 'org-not-done-regexp)
4335 (defvar org-todo-line-regexp nil
4336 "Matches a headline and puts TODO state into group 2 if present.")
4337 (make-variable-buffer-local 'org-todo-line-regexp)
4338 (defvar org-complex-heading-regexp nil
4339 "Matches a headline and puts everything into groups:
4340 group 1: the stars
4341 group 2: The todo keyword, maybe
4342 group 3: Priority cookie
4343 group 4: True headline
4344 group 5: Tags")
4345 (make-variable-buffer-local 'org-complex-heading-regexp)
4346 (defvar org-complex-heading-regexp-format nil
4347 "Printf format to make regexp to match an exact headline.
4348 This regexp will match the headline of any node which has the
4349 exact headline text that is put into the format, but may have any
4350 TODO state, priority and tags.")
4351 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4352 (defvar org-todo-line-tags-regexp nil
4353 "Matches a headline and puts TODO state into group 2 if present.
4354 Also put tags into group 4 if tags are present.")
4355 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4356 (defvar org-ds-keyword-length 12
4357 "Maximum length of the Deadline and SCHEDULED keywords.")
4358 (make-variable-buffer-local 'org-ds-keyword-length)
4359 (defvar org-deadline-regexp nil
4360 "Matches the DEADLINE keyword.")
4361 (make-variable-buffer-local 'org-deadline-regexp)
4362 (defvar org-deadline-time-regexp nil
4363 "Matches the DEADLINE keyword together with a time stamp.")
4364 (make-variable-buffer-local 'org-deadline-time-regexp)
4365 (defvar org-deadline-line-regexp nil
4366 "Matches the DEADLINE keyword and the rest of the line.")
4367 (make-variable-buffer-local 'org-deadline-line-regexp)
4368 (defvar org-scheduled-regexp nil
4369 "Matches the SCHEDULED keyword.")
4370 (make-variable-buffer-local 'org-scheduled-regexp)
4371 (defvar org-scheduled-time-regexp nil
4372 "Matches the SCHEDULED keyword together with a time stamp.")
4373 (make-variable-buffer-local 'org-scheduled-time-regexp)
4374 (defvar org-closed-time-regexp nil
4375 "Matches the CLOSED keyword together with a time stamp.")
4376 (make-variable-buffer-local 'org-closed-time-regexp)
4378 (defvar org-keyword-time-regexp nil
4379 "Matches any of the 4 keywords, together with the time stamp.")
4380 (make-variable-buffer-local 'org-keyword-time-regexp)
4381 (defvar org-keyword-time-not-clock-regexp nil
4382 "Matches any of the 3 keywords, together with the time stamp.")
4383 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4384 (defvar org-maybe-keyword-time-regexp nil
4385 "Matches a timestamp, possibly preceded by a keyword.")
4386 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4387 (defvar org-planning-or-clock-line-re nil
4388 "Matches a line with planning or clock info.")
4389 (make-variable-buffer-local 'org-planning-or-clock-line-re)
4390 (defvar org-all-time-keywords nil
4391 "List of time keywords.")
4392 (make-variable-buffer-local 'org-all-time-keywords)
4394 (defconst org-plain-time-of-day-regexp
4395 (concat
4396 "\\(\\<[012]?[0-9]"
4397 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4398 "\\(--?"
4399 "\\(\\<[012]?[0-9]"
4400 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4401 "\\)?")
4402 "Regular expression to match a plain time or time range.
4403 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4404 groups carry important information:
4405 0 the full match
4406 1 the first time, range or not
4407 8 the second time, if it is a range.")
4409 (defconst org-plain-time-extension-regexp
4410 (concat
4411 "\\(\\<[012]?[0-9]"
4412 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4413 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4414 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4415 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4416 groups carry important information:
4417 0 the full match
4418 7 hours of duration
4419 9 minutes of duration")
4421 (defconst org-stamp-time-of-day-regexp
4422 (concat
4423 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4424 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4425 "\\(--?"
4426 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4427 "Regular expression to match a timestamp time or time range.
4428 After a match, the following groups carry important information:
4429 0 the full match
4430 1 date plus weekday, for back referencing to make sure both times are on the same day
4431 2 the first time, range or not
4432 4 the second time, if it is a range.")
4434 (defconst org-startup-options
4435 '(("fold" org-startup-folded t)
4436 ("overview" org-startup-folded t)
4437 ("nofold" org-startup-folded nil)
4438 ("showall" org-startup-folded nil)
4439 ("showeverything" org-startup-folded showeverything)
4440 ("content" org-startup-folded content)
4441 ("indent" org-startup-indented t)
4442 ("noindent" org-startup-indented nil)
4443 ("hidestars" org-hide-leading-stars t)
4444 ("showstars" org-hide-leading-stars nil)
4445 ("odd" org-odd-levels-only t)
4446 ("oddeven" org-odd-levels-only nil)
4447 ("align" org-startup-align-all-tables t)
4448 ("noalign" org-startup-align-all-tables nil)
4449 ("inlineimages" org-startup-with-inline-images t)
4450 ("noinlineimages" org-startup-with-inline-images nil)
4451 ("customtime" org-display-custom-times t)
4452 ("logdone" org-log-done time)
4453 ("lognotedone" org-log-done note)
4454 ("nologdone" org-log-done nil)
4455 ("lognoteclock-out" org-log-note-clock-out t)
4456 ("nolognoteclock-out" org-log-note-clock-out nil)
4457 ("logrepeat" org-log-repeat state)
4458 ("lognoterepeat" org-log-repeat note)
4459 ("nologrepeat" org-log-repeat nil)
4460 ("logreschedule" org-log-reschedule time)
4461 ("lognotereschedule" org-log-reschedule note)
4462 ("nologreschedule" org-log-reschedule nil)
4463 ("logredeadline" org-log-redeadline time)
4464 ("lognoteredeadline" org-log-redeadline note)
4465 ("nologredeadline" org-log-redeadline nil)
4466 ("logrefile" org-log-refile time)
4467 ("lognoterefile" org-log-refile note)
4468 ("nologrefile" org-log-refile nil)
4469 ("fninline" org-footnote-define-inline t)
4470 ("nofninline" org-footnote-define-inline nil)
4471 ("fnlocal" org-footnote-section nil)
4472 ("fnauto" org-footnote-auto-label t)
4473 ("fnprompt" org-footnote-auto-label nil)
4474 ("fnconfirm" org-footnote-auto-label confirm)
4475 ("fnplain" org-footnote-auto-label plain)
4476 ("fnadjust" org-footnote-auto-adjust t)
4477 ("nofnadjust" org-footnote-auto-adjust nil)
4478 ("constcgs" constants-unit-system cgs)
4479 ("constSI" constants-unit-system SI)
4480 ("noptag" org-tag-persistent-alist nil)
4481 ("hideblocks" org-hide-block-startup t)
4482 ("nohideblocks" org-hide-block-startup nil)
4483 ("beamer" org-startup-with-beamer-mode t)
4484 ("entitiespretty" org-pretty-entities t)
4485 ("entitiesplain" org-pretty-entities nil))
4486 "Variable associated with STARTUP options for org-mode.
4487 Each element is a list of three items: The startup options as written
4488 in the #+STARTUP line, the corresponding variable, and the value to
4489 set this variable to if the option is found. An optional forth element PUSH
4490 means to push this value onto the list in the variable.")
4492 (defun org-update-property-plist (key val props)
4493 "Update PROPS with KEY and VAL."
4494 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4495 (key (if appending (substring key 0 (- (length key) 1)) key))
4496 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4497 (previous (cdr (assoc key props))))
4498 (if appending
4499 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4500 (cons (cons key val) remainder))))
4502 (defconst org-block-regexp
4503 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4504 "Regular expression for hiding blocks.")
4505 (defconst org-heading-keyword-regexp-format
4506 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4507 "Printf format for a regexp matching an headline with some keyword.
4508 This regexp will match the headline of any node which has the
4509 exact keyword that is put into the format. The keyword isn't in
4510 any group by default, but the stars and the body are.")
4511 (defconst org-heading-keyword-maybe-regexp-format
4512 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4513 "Printf format for a regexp matching an headline, possibly with some keyword.
4514 This regexp can match any headline with the specified keyword, or
4515 without a keyword. The keyword isn't in any group by default,
4516 but the stars and the body are.")
4518 (defun org-set-regexps-and-options ()
4519 "Precompute regular expressions for current buffer."
4520 (when (derived-mode-p 'org-mode)
4521 (org-set-local 'org-todo-kwd-alist nil)
4522 (org-set-local 'org-todo-key-alist nil)
4523 (org-set-local 'org-todo-key-trigger nil)
4524 (org-set-local 'org-todo-keywords-1 nil)
4525 (org-set-local 'org-done-keywords nil)
4526 (org-set-local 'org-todo-heads nil)
4527 (org-set-local 'org-todo-sets nil)
4528 (org-set-local 'org-todo-log-states nil)
4529 (org-set-local 'org-file-properties nil)
4530 (org-set-local 'org-file-tags nil)
4531 (let ((re (org-make-options-regexp
4532 '("CATEGORY" "TODO" "COLUMNS"
4533 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
4534 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE" "LATEX_CLASS"
4535 "OPTIONS")
4536 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4537 (splitre "[ \t]+")
4538 (scripts org-use-sub-superscripts)
4539 kwds kws0 kwsa key log value cat arch tags const links hw dws
4540 tail sep kws1 prio props ftags drawers beamer-p
4541 ext-setup-or-nil setup-contents (start 0))
4542 (save-excursion
4543 (save-restriction
4544 (widen)
4545 (goto-char (point-min))
4546 (while (or (and ext-setup-or-nil
4547 (string-match re ext-setup-or-nil start)
4548 (setq start (match-end 0)))
4549 (and (setq ext-setup-or-nil nil start 0)
4550 (re-search-forward re nil t)))
4551 (setq key (upcase (match-string 1 ext-setup-or-nil))
4552 value (org-match-string-no-properties 2 ext-setup-or-nil))
4553 (if (stringp value) (setq value (org-trim value)))
4554 (cond
4555 ((equal key "CATEGORY")
4556 (setq cat value))
4557 ((member key '("SEQ_TODO" "TODO"))
4558 (push (cons 'sequence (org-split-string value splitre)) kwds))
4559 ((equal key "TYP_TODO")
4560 (push (cons 'type (org-split-string value splitre)) kwds))
4561 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4562 ;; general TODO-like setup
4563 (push (cons (intern (downcase (match-string 1 key)))
4564 (org-split-string value splitre)) kwds))
4565 ((equal key "TAGS")
4566 (setq tags (append tags (if tags '("\\n") nil)
4567 (org-split-string value splitre))))
4568 ((equal key "COLUMNS")
4569 (org-set-local 'org-columns-default-format value))
4570 ((equal key "LINK")
4571 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4572 (push (cons (match-string 1 value)
4573 (org-trim (match-string 2 value)))
4574 links)))
4575 ((equal key "PRIORITIES")
4576 (setq prio (org-split-string value " +")))
4577 ((equal key "PROPERTY")
4578 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4579 (setq props (org-update-property-plist (match-string 1 value)
4580 (match-string 2 value)
4581 props))))
4582 ((equal key "FILETAGS")
4583 (when (string-match "\\S-" value)
4584 (setq ftags
4585 (append
4586 ftags
4587 (apply 'append
4588 (mapcar (lambda (x) (org-split-string x ":"))
4589 (org-split-string value)))))))
4590 ((equal key "DRAWERS")
4591 (setq drawers (delete-dups (append org-drawers (org-split-string value splitre)))))
4592 ((equal key "CONSTANTS")
4593 (setq const (append const (org-split-string value splitre))))
4594 ((equal key "STARTUP")
4595 (let ((opts (org-split-string value splitre))
4596 l var val)
4597 (while (setq l (pop opts))
4598 (when (setq l (assoc l org-startup-options))
4599 (setq var (nth 1 l) val (nth 2 l))
4600 (if (not (nth 3 l))
4601 (set (make-local-variable var) val)
4602 (if (not (listp (symbol-value var)))
4603 (set (make-local-variable var) nil))
4604 (set (make-local-variable var) (symbol-value var))
4605 (add-to-list var val))))))
4606 ((equal key "ARCHIVE")
4607 (setq arch value)
4608 (remove-text-properties 0 (length arch)
4609 '(face t fontified t) arch))
4610 ((equal key "LATEX_CLASS")
4611 (setq beamer-p (equal value "beamer")))
4612 ((equal key "OPTIONS")
4613 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4614 (setq scripts (read (match-string 2 value)))))
4615 ((equal key "SETUPFILE")
4616 (setq setup-contents (org-file-contents
4617 (expand-file-name
4618 (org-remove-double-quotes value))
4619 'noerror))
4620 (if (not ext-setup-or-nil)
4621 (setq ext-setup-or-nil setup-contents start 0)
4622 (setq ext-setup-or-nil
4623 (concat (substring ext-setup-or-nil 0 start)
4624 "\n" setup-contents "\n"
4625 (substring ext-setup-or-nil start)))))))
4626 ;; search for property blocks
4627 (goto-char (point-min))
4628 (while (re-search-forward org-block-regexp nil t)
4629 (when (equal "PROPERTY" (upcase (match-string 1)))
4630 (setq value (replace-regexp-in-string
4631 "[\n\r]" " " (match-string 4)))
4632 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4633 (setq props (org-update-property-plist (match-string 1 value)
4634 (match-string 2 value)
4635 props)))))))
4636 (org-set-local 'org-use-sub-superscripts scripts)
4637 (when cat
4638 (org-set-local 'org-category (intern cat))
4639 (push (cons "CATEGORY" cat) props))
4640 (when prio
4641 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4642 (setq prio (mapcar 'string-to-char prio))
4643 (org-set-local 'org-highest-priority (nth 0 prio))
4644 (org-set-local 'org-lowest-priority (nth 1 prio))
4645 (org-set-local 'org-default-priority (nth 2 prio)))
4646 (and props (org-set-local 'org-file-properties (nreverse props)))
4647 (and ftags (org-set-local 'org-file-tags
4648 (mapcar 'org-add-prop-inherited ftags)))
4649 (and drawers (org-set-local 'org-drawers drawers))
4650 (and arch (org-set-local 'org-archive-location arch))
4651 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4652 ;; Process the TODO keywords
4653 (unless kwds
4654 ;; Use the global values as if they had been given locally.
4655 (setq kwds (default-value 'org-todo-keywords))
4656 (if (stringp (car kwds))
4657 (setq kwds (list (cons org-todo-interpretation
4658 (default-value 'org-todo-keywords)))))
4659 (setq kwds (reverse kwds)))
4660 (setq kwds (nreverse kwds))
4661 (let (inter kws kw)
4662 (while (setq kws (pop kwds))
4663 (let ((kws (or
4664 (run-hook-with-args-until-success
4665 'org-todo-setup-filter-hook kws)
4666 kws)))
4667 (setq inter (pop kws) sep (member "|" kws)
4668 kws0 (delete "|" (copy-sequence kws))
4669 kwsa nil
4670 kws1 (mapcar
4671 (lambda (x)
4672 ;; 1 2
4673 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4674 (progn
4675 (setq kw (match-string 1 x)
4676 key (and (match-end 2) (match-string 2 x))
4677 log (org-extract-log-state-settings x))
4678 (push (cons kw (and key (string-to-char key))) kwsa)
4679 (and log (push log org-todo-log-states))
4681 (error "Invalid TODO keyword %s" x)))
4682 kws0)
4683 kwsa (if kwsa (append '((:startgroup))
4684 (nreverse kwsa)
4685 '((:endgroup))))
4686 hw (car kws1)
4687 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4688 tail (list inter hw (car dws) (org-last dws))))
4689 (add-to-list 'org-todo-heads hw 'append)
4690 (push kws1 org-todo-sets)
4691 (setq org-done-keywords (append org-done-keywords dws nil))
4692 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4693 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4694 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4695 (setq org-todo-sets (nreverse org-todo-sets)
4696 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4697 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4698 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4699 ;; Process the constants
4700 (when const
4701 (let (e cst)
4702 (while (setq e (pop const))
4703 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4704 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4705 (setq org-table-formula-constants-local cst)))
4707 ;; Process the tags.
4708 (when tags
4709 (let (e tgs)
4710 (while (setq e (pop tags))
4711 (cond
4712 ((equal e "{") (push '(:startgroup) tgs))
4713 ((equal e "}") (push '(:endgroup) tgs))
4714 ((equal e "\\n") (push '(:newline) tgs))
4715 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4716 (push (cons (match-string 1 e)
4717 (string-to-char (match-string 2 e)))
4718 tgs))
4719 (t (push (list e) tgs))))
4720 (org-set-local 'org-tag-alist nil)
4721 (while (setq e (pop tgs))
4722 (or (and (stringp (car e))
4723 (assoc (car e) org-tag-alist))
4724 (push e org-tag-alist)))))
4726 ;; Compute the regular expressions and other local variables.
4727 ;; Using `org-outline-regexp-bol' would complicate them much,
4728 ;; because of the fixed white space at the end of that string.
4729 (if (not org-done-keywords)
4730 (setq org-done-keywords (and org-todo-keywords-1
4731 (list (org-last org-todo-keywords-1)))))
4732 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4733 (length org-scheduled-string)
4734 (length org-clock-string)
4735 (length org-closed-string)))
4736 org-drawer-regexp
4737 (concat "^[ \t]*:\\("
4738 (mapconcat 'regexp-quote org-drawers "\\|")
4739 "\\):[ \t]*$")
4740 org-not-done-keywords
4741 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4742 org-todo-regexp
4743 (concat "\\("
4744 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4745 "\\)")
4746 org-not-done-regexp
4747 (concat "\\("
4748 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4749 "\\)")
4750 org-not-done-heading-regexp
4751 (format org-heading-keyword-regexp-format org-not-done-regexp)
4752 org-todo-line-regexp
4753 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
4754 org-complex-heading-regexp
4755 (concat "^\\(\\*+\\)"
4756 "\\(?: +" org-todo-regexp "\\)?"
4757 "\\(?: +\\(\\[#.\\]\\)\\)?"
4758 "\\(?: +\\(.*?\\)\\)?"
4759 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
4760 "[ \t]*$")
4761 org-complex-heading-regexp-format
4762 (concat "^\\(\\*+\\)"
4763 "\\(?: +" org-todo-regexp "\\)?"
4764 "\\(?: +\\(\\[#.\\]\\)\\)?"
4765 "\\(?: +"
4766 ;; Stats cookies can be stuck to body.
4767 "\\(?:\\[[0-9%%/]+\\] *\\)?"
4768 "\\(%s\\)"
4769 "\\(?: *\\[[0-9%%/]+\\]\\)?"
4770 "\\)"
4771 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
4772 "[ \t]*$")
4773 org-todo-line-tags-regexp
4774 (concat "^\\(\\*+\\)"
4775 "\\(?: +" org-todo-regexp "\\)?"
4776 "\\(?: +\\(.*?\\)\\)?"
4777 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
4778 "[ \t]*$")
4779 org-deadline-regexp (concat "\\<" org-deadline-string)
4780 org-deadline-time-regexp
4781 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4782 org-deadline-line-regexp
4783 (concat "\\<\\(" org-deadline-string "\\).*")
4784 org-scheduled-regexp
4785 (concat "\\<" org-scheduled-string)
4786 org-scheduled-time-regexp
4787 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4788 org-closed-time-regexp
4789 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4790 org-keyword-time-regexp
4791 (concat "\\<\\(" org-scheduled-string
4792 "\\|" org-deadline-string
4793 "\\|" org-closed-string
4794 "\\|" org-clock-string "\\)"
4795 " *[[<]\\([^]>]+\\)[]>]")
4796 org-keyword-time-not-clock-regexp
4797 (concat "\\<\\(" org-scheduled-string
4798 "\\|" org-deadline-string
4799 "\\|" org-closed-string
4800 "\\)"
4801 " *[[<]\\([^]>]+\\)[]>]")
4802 org-maybe-keyword-time-regexp
4803 (concat "\\(\\<\\(" org-scheduled-string
4804 "\\|" org-deadline-string
4805 "\\|" org-closed-string
4806 "\\|" org-clock-string "\\)\\)?"
4807 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4808 org-planning-or-clock-line-re
4809 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
4810 "\\|" org-deadline-string
4811 "\\|" org-closed-string "\\|" org-clock-string
4812 "\\)\\>\\)")
4813 org-all-time-keywords
4814 (mapcar (lambda (w) (substring w 0 -1))
4815 (list org-scheduled-string org-deadline-string
4816 org-clock-string org-closed-string))
4818 (org-compute-latex-and-specials-regexp)
4819 (org-set-font-lock-defaults))))
4821 (defun org-file-contents (file &optional noerror)
4822 "Return the contents of FILE, as a string."
4823 (if (or (not file)
4824 (not (file-readable-p file)))
4825 (if noerror
4826 (progn
4827 (message "Cannot read file \"%s\"" file)
4828 (ding) (sit-for 2)
4830 (error "Cannot read file \"%s\"" file))
4831 (with-temp-buffer
4832 (insert-file-contents file)
4833 (buffer-string))))
4835 (defun org-extract-log-state-settings (x)
4836 "Extract the log state setting from a TODO keyword string.
4837 This will extract info from a string like \"WAIT(w@/!)\"."
4838 (let (kw key log1 log2)
4839 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4840 (setq kw (match-string 1 x)
4841 key (and (match-end 2) (match-string 2 x))
4842 log1 (and (match-end 3) (match-string 3 x))
4843 log2 (and (match-end 4) (match-string 4 x)))
4844 (and (or log1 log2)
4845 (list kw
4846 (and log1 (if (equal log1 "!") 'time 'note))
4847 (and log2 (if (equal log2 "!") 'time 'note)))))))
4849 (defun org-remove-keyword-keys (list)
4850 "Remove a pair of parenthesis at the end of each string in LIST."
4851 (mapcar (lambda (x)
4852 (if (string-match "(.*)$" x)
4853 (substring x 0 (match-beginning 0))
4855 list))
4857 (defun org-assign-fast-keys (alist)
4858 "Assign fast keys to a keyword-key alist.
4859 Respect keys that are already there."
4860 (let (new e (alt ?0))
4861 (while (setq e (pop alist))
4862 (if (or (memq (car e) '(:newline :endgroup :startgroup))
4863 (cdr e)) ;; Key already assigned.
4864 (push e new)
4865 (let ((clist (string-to-list (downcase (car e))))
4866 (used (append new alist)))
4867 (when (= (car clist) ?@)
4868 (pop clist))
4869 (while (and clist (rassoc (car clist) used))
4870 (pop clist))
4871 (unless clist
4872 (while (rassoc alt used)
4873 (incf alt)))
4874 (push (cons (car e) (or (car clist) alt)) new))))
4875 (nreverse new)))
4877 ;;; Some variables used in various places
4879 (defvar org-window-configuration nil
4880 "Used in various places to store a window configuration.")
4881 (defvar org-selected-window nil
4882 "Used in various places to store a window configuration.")
4883 (defvar org-finish-function nil
4884 "Function to be called when `C-c C-c' is used.
4885 This is for getting out of special buffers like remember.")
4888 ;; FIXME: Occasionally check by commenting these, to make sure
4889 ;; no other functions uses these, forgetting to let-bind them.
4890 (defvar entry)
4891 (defvar org-last-state)
4892 (defvar date)
4894 ;; Defined somewhere in this file, but used before definition.
4895 (defvar org-entities) ;; defined in org-entities.el
4896 (defvar org-struct-menu)
4897 (defvar org-org-menu)
4898 (defvar org-tbl-menu)
4900 ;;;; Define the Org-mode
4902 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4903 (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"))
4906 ;; We use a before-change function to check if a table might need
4907 ;; an update.
4908 (defvar org-table-may-need-update t
4909 "Indicates that a table might need an update.
4910 This variable is set by `org-before-change-function'.
4911 `org-table-align' sets it back to nil.")
4912 (defun org-before-change-function (beg end)
4913 "Every change indicates that a table might need an update."
4914 (setq org-table-may-need-update t))
4915 (defvar org-mode-map)
4916 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4917 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
4918 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4919 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
4920 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
4921 (defvar org-table-buffer-is-an nil)
4923 ;; `org-outline-regexp' ought to be a defconst but is let-binding in
4924 ;; some places -- e.g. see the macro org-with-limited-levels.
4926 ;; In Org buffers, the value of `outline-regexp' is that of
4927 ;; `org-outline-regexp'. The only function still directly relying on
4928 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
4929 ;; job when `orgstruct-mode' is active.
4930 (defvar org-outline-regexp "\\*+ "
4931 "Regexp to match Org headlines.")
4932 (defconst org-outline-regexp-bol "^\\*+ "
4933 "Regexp to match Org headlines.
4934 This is similar to `org-outline-regexp' but additionally makes
4935 sure that we are at the beginning of the line.")
4937 (defconst org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4938 "Matches an headline, putting stars and text into groups.
4939 Stars are put in group 1 and the trimmed body in group 2.")
4941 (defvar bidi-paragraph-direction)
4942 (defvar buffer-face-mode-face)
4943 (defvar org-auto-fill-fallback-function nil)
4944 (defvar org-indent-line-fallback-function nil)
4945 (defvar org-fill-paragraph-fallback-function nil)
4946 (make-variable-buffer-local 'org-auto-fill-fallback-function)
4947 (make-variable-buffer-local 'org-indent-line-fallback-function)
4948 (make-variable-buffer-local 'org-fill-paragraph-fallback-function)
4950 ;;;###autoload
4951 (define-derived-mode org-mode outline-mode "Org"
4952 "Outline-based notes management and organizer, alias
4953 \"Carsten's outline-mode for keeping track of everything.\"
4955 Org-mode develops organizational tasks around a NOTES file which
4956 contains information about projects as plain text. Org-mode is
4957 implemented on top of outline-mode, which is ideal to keep the content
4958 of large files well structured. It supports ToDo items, deadlines and
4959 time stamps, which magically appear in the diary listing of the Emacs
4960 calendar. Tables are easily created with a built-in table editor.
4961 Plain text URL-like links connect to websites, emails (VM), Usenet
4962 messages (Gnus), BBDB entries, and any files related to the project.
4963 For printing and sharing of notes, an Org-mode file (or a part of it)
4964 can be exported as a structured ASCII or HTML file.
4966 The following commands are available:
4968 \\{org-mode-map}"
4970 ;; Get rid of Outline menus, they are not needed
4971 ;; Need to do this here because define-derived-mode sets up
4972 ;; the keymap so late. Still, it is a waste to call this each time
4973 ;; we switch another buffer into org-mode.
4974 (if (featurep 'xemacs)
4975 (when (boundp 'outline-mode-menu-heading)
4976 ;; Assume this is Greg's port, it uses easymenu
4977 (easy-menu-remove outline-mode-menu-heading)
4978 (easy-menu-remove outline-mode-menu-show)
4979 (easy-menu-remove outline-mode-menu-hide))
4980 (define-key org-mode-map [menu-bar headings] 'undefined)
4981 (define-key org-mode-map [menu-bar hide] 'undefined)
4982 (define-key org-mode-map [menu-bar show] 'undefined))
4984 (org-load-modules-maybe)
4985 (easy-menu-add org-org-menu)
4986 (easy-menu-add org-tbl-menu)
4987 (org-install-agenda-files-menu)
4988 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
4989 (add-to-invisibility-spec '(org-cwidth))
4990 (add-to-invisibility-spec '(org-hide-block . t))
4991 (when (featurep 'xemacs)
4992 (org-set-local 'line-move-ignore-invisible t))
4993 (org-set-local 'outline-regexp org-outline-regexp)
4994 (org-set-local 'outline-level 'org-outline-level)
4995 (setq bidi-paragraph-direction 'left-to-right)
4996 (when (and org-ellipsis
4997 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
4998 (fboundp 'make-glyph-code))
4999 (unless org-display-table
5000 (setq org-display-table (make-display-table)))
5001 (set-display-table-slot
5002 org-display-table 4
5003 (vconcat (mapcar
5004 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5005 org-ellipsis)))
5006 (if (stringp org-ellipsis) org-ellipsis "..."))))
5007 (setq buffer-display-table org-display-table))
5008 (org-set-regexps-and-options)
5009 (when (and org-tag-faces (not org-tags-special-faces-re))
5010 ;; tag faces set outside customize.... force initialization.
5011 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5012 ;; Calc embedded
5013 (org-set-local 'calc-embedded-open-mode "# ")
5014 (modify-syntax-entry ?@ "w")
5015 (if org-startup-truncated (setq truncate-lines t))
5016 (org-set-local 'font-lock-unfontify-region-function
5017 'org-unfontify-region)
5018 ;; Activate before-change-function
5019 (org-set-local 'org-table-may-need-update t)
5020 (org-add-hook 'before-change-functions 'org-before-change-function nil
5021 'local)
5022 ;; Check for running clock before killing a buffer
5023 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5024 ;; Paragraphs and auto-filling
5025 (org-set-autofill-regexps)
5026 (setq indent-line-function 'org-indent-line-function)
5027 (org-update-radio-target-regexp)
5028 ;; Beginning/end of defun
5029 (org-set-local 'beginning-of-defun-function 'org-beginning-of-defun)
5030 (org-set-local 'end-of-defun-function 'org-end-of-defun)
5031 ;; Next error for sparse trees
5032 (org-set-local 'next-error-function 'org-occur-next-match)
5033 ;; Make sure dependence stuff works reliably, even for users who set it
5034 ;; too late :-(
5035 (if org-enforce-todo-dependencies
5036 (add-hook 'org-blocker-hook
5037 'org-block-todo-from-children-or-siblings-or-parent)
5038 (remove-hook 'org-blocker-hook
5039 'org-block-todo-from-children-or-siblings-or-parent))
5040 (if org-enforce-todo-checkbox-dependencies
5041 (add-hook 'org-blocker-hook
5042 'org-block-todo-from-checkboxes)
5043 (remove-hook 'org-blocker-hook
5044 'org-block-todo-from-checkboxes))
5046 ;; Comment characters
5047 (org-set-local 'comment-start "#")
5048 (org-set-local 'comment-padding " ")
5050 ;; Align options lines
5051 (org-set-local
5052 'align-mode-rules-list
5053 '((org-in-buffer-settings
5054 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5055 (modes . '(org-mode)))))
5057 ;; Imenu
5058 (org-set-local 'imenu-create-index-function
5059 'org-imenu-get-tree)
5061 ;; Make isearch reveal context
5062 (if (or (featurep 'xemacs)
5063 (not (boundp 'outline-isearch-open-invisible-function)))
5064 ;; Emacs 21 and XEmacs make use of the hook
5065 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5066 ;; Emacs 22 deals with this through a special variable
5067 (org-set-local 'outline-isearch-open-invisible-function
5068 (lambda (&rest ignore) (org-show-context 'isearch))))
5070 ;; Turn on org-beamer-mode?
5071 (and org-startup-with-beamer-mode (org-beamer-mode 1))
5073 ;; Setup the pcomplete hooks
5074 (set (make-local-variable 'pcomplete-command-completion-function)
5075 'org-pcomplete-initial)
5076 (set (make-local-variable 'pcomplete-command-name-function)
5077 'org-command-at-point)
5078 (set (make-local-variable 'pcomplete-default-completion-function)
5079 'ignore)
5080 (set (make-local-variable 'pcomplete-parse-arguments-function)
5081 'org-parse-arguments)
5082 (set (make-local-variable 'pcomplete-termination-string) "")
5083 (when (>= emacs-major-version 23)
5084 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5086 ;; If empty file that did not turn on org-mode automatically, make it to.
5087 (if (and org-insert-mode-line-in-empty-file
5088 (org-called-interactively-p 'any)
5089 (= (point-min) (point-max)))
5090 (insert "# -*- mode: org -*-\n\n"))
5091 (unless org-inhibit-startup
5092 (when org-startup-align-all-tables
5093 (let ((bmp (buffer-modified-p)))
5094 (org-table-map-tables 'org-table-align 'quietly)
5095 (set-buffer-modified-p bmp)))
5096 (when org-startup-with-inline-images
5097 (org-display-inline-images))
5098 (when org-startup-indented
5099 (require 'org-indent)
5100 (org-indent-mode 1))
5101 (unless org-inhibit-startup-visibility-stuff
5102 (org-set-startup-visibility))))
5104 (when (fboundp 'abbrev-table-put)
5105 (abbrev-table-put org-mode-abbrev-table
5106 :parents (list text-mode-abbrev-table)))
5108 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5110 (defun org-current-time ()
5111 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
5112 (if (> (car org-time-stamp-rounding-minutes) 1)
5113 (let ((r (car org-time-stamp-rounding-minutes))
5114 (time (decode-time)))
5115 (apply 'encode-time
5116 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5117 (nthcdr 2 time))))
5118 (current-time)))
5120 (defun org-today ()
5121 "Return today date, considering `org-extend-today-until'."
5122 (time-to-days
5123 (time-subtract (current-time)
5124 (list 0 (* 3600 org-extend-today-until) 0))))
5126 ;;;; Font-Lock stuff, including the activators
5128 (defvar org-mouse-map (make-sparse-keymap))
5129 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5130 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5131 (when org-mouse-1-follows-link
5132 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5133 (when org-tab-follows-link
5134 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5135 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5137 (require 'font-lock)
5139 (defconst org-non-link-chars "]\t\n\r<>")
5140 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5141 "shell" "elisp" "doi" "message"))
5142 (defvar org-link-types-re nil
5143 "Matches a link that has a url-like prefix like \"http:\"")
5144 (defvar org-link-re-with-space nil
5145 "Matches a link with spaces, optional angular brackets around it.")
5146 (defvar org-link-re-with-space2 nil
5147 "Matches a link with spaces, optional angular brackets around it.")
5148 (defvar org-link-re-with-space3 nil
5149 "Matches a link with spaces, only for internal part in bracket links.")
5150 (defvar org-angle-link-re nil
5151 "Matches link with angular brackets, spaces are allowed.")
5152 (defvar org-plain-link-re nil
5153 "Matches plain link, without spaces.")
5154 (defvar org-bracket-link-regexp nil
5155 "Matches a link in double brackets.")
5156 (defvar org-bracket-link-analytic-regexp nil
5157 "Regular expression used to analyze links.
5158 Here is what the match groups contain after a match:
5159 1: http:
5160 2: http
5161 3: path
5162 4: [desc]
5163 5: desc")
5164 (defvar org-bracket-link-analytic-regexp++ nil
5165 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5166 (defvar org-any-link-re nil
5167 "Regular expression matching any link.")
5169 (defcustom org-match-sexp-depth 3
5170 "Number of stacked braces for sub/superscript matching.
5171 This has to be set before loading org.el to be effective."
5172 :group 'org-export-translation ; ??????????????????????????/
5173 :type 'integer)
5175 (defun org-create-multibrace-regexp (left right n)
5176 "Create a regular expression which will match a balanced sexp.
5177 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5178 as single character strings.
5179 The regexp returned will match the entire expression including the
5180 delimiters. It will also define a single group which contains the
5181 match except for the outermost delimiters. The maximum depth of
5182 stacked delimiters is N. Escaping delimiters is not possible."
5183 (let* ((nothing (concat "[^" left right "]*?"))
5184 (or "\\|")
5185 (re nothing)
5186 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5187 (while (> n 1)
5188 (setq n (1- n)
5189 re (concat re or next)
5190 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5191 (concat left "\\(" re "\\)" right)))
5193 (defvar org-match-substring-regexp
5194 (concat
5195 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5196 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5197 "\\|"
5198 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5199 "\\|"
5200 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5201 "The regular expression matching a sub- or superscript.")
5203 (defvar org-match-substring-with-braces-regexp
5204 (concat
5205 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5206 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5207 "\\)")
5208 "The regular expression matching a sub- or superscript, forcing braces.")
5210 (defun org-make-link-regexps ()
5211 "Update the link regular expressions.
5212 This should be called after the variable `org-link-types' has changed."
5213 (setq org-link-types-re
5214 (concat
5215 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5216 org-link-re-with-space
5217 (concat
5218 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5219 "\\([^" org-non-link-chars " ]"
5220 "[^" org-non-link-chars "]*"
5221 "[^" org-non-link-chars " ]\\)>?")
5222 org-link-re-with-space2
5223 (concat
5224 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5225 "\\([^" org-non-link-chars " ]"
5226 "[^\t\n\r]*"
5227 "[^" org-non-link-chars " ]\\)>?")
5228 org-link-re-with-space3
5229 (concat
5230 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5231 "\\([^" org-non-link-chars " ]"
5232 "[^\t\n\r]*\\)")
5233 org-angle-link-re
5234 (concat
5235 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5236 "\\([^" org-non-link-chars " ]"
5237 "[^" org-non-link-chars "]*"
5238 "\\)>")
5239 org-plain-link-re
5240 (concat
5241 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5242 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5243 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5244 org-bracket-link-regexp
5245 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5246 org-bracket-link-analytic-regexp
5247 (concat
5248 "\\[\\["
5249 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5250 "\\([^]]+\\)"
5251 "\\]"
5252 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5253 "\\]")
5254 org-bracket-link-analytic-regexp++
5255 (concat
5256 "\\[\\["
5257 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5258 "\\([^]]+\\)"
5259 "\\]"
5260 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5261 "\\]")
5262 org-any-link-re
5263 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5264 org-angle-link-re "\\)\\|\\("
5265 org-plain-link-re "\\)")))
5267 (org-make-link-regexps)
5269 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5270 "Regular expression for fast time stamp matching.")
5271 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5272 "Regular expression for fast time stamp matching.")
5273 (defconst org-ts-regexp0
5274 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5275 "Regular expression matching time strings for analysis.
5276 This one does not require the space after the date, so it can be used
5277 on a string that terminates immediately after the date.")
5278 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5279 "Regular expression matching time strings for analysis.")
5280 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5281 "Regular expression matching time stamps, with groups.")
5282 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5283 "Regular expression matching time stamps (also [..]), with groups.")
5284 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5285 "Regular expression matching a time stamp range.")
5286 (defconst org-tr-regexp-both
5287 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5288 "Regular expression matching a time stamp range.")
5289 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5290 org-ts-regexp "\\)?")
5291 "Regular expression matching a time stamp or time stamp range.")
5292 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5293 org-ts-regexp-both "\\)?")
5294 "Regular expression matching a time stamp or time stamp range.
5295 The time stamps may be either active or inactive.")
5297 (defvar org-emph-face nil)
5299 (defun org-do-emphasis-faces (limit)
5300 "Run through the buffer and add overlays to emphasized strings."
5301 (let (rtn a)
5302 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5303 (if (not (= (char-after (match-beginning 3))
5304 (char-after (match-beginning 4))))
5305 (progn
5306 (setq rtn t)
5307 (setq a (assoc (match-string 3) org-emphasis-alist))
5308 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5309 'face
5310 (nth 1 a))
5311 (and (nth 4 a)
5312 (org-remove-flyspell-overlays-in
5313 (match-beginning 0) (match-end 0)))
5314 (add-text-properties (match-beginning 2) (match-end 2)
5315 '(font-lock-multiline t org-emphasis t))
5316 (when org-hide-emphasis-markers
5317 (add-text-properties (match-end 4) (match-beginning 5)
5318 '(invisible org-link))
5319 (add-text-properties (match-beginning 3) (match-end 3)
5320 '(invisible org-link)))))
5321 (backward-char 1))
5322 rtn))
5324 (defun org-emphasize (&optional char)
5325 "Insert or change an emphasis, i.e. a font like bold or italic.
5326 If there is an active region, change that region to a new emphasis.
5327 If there is no region, just insert the marker characters and position
5328 the cursor between them.
5329 CHAR should be either the marker character, or the first character of the
5330 HTML tag associated with that emphasis. If CHAR is a space, the means
5331 to remove the emphasis of the selected region.
5332 If char is not given (for example in an interactive call) it
5333 will be prompted for."
5334 (interactive)
5335 (let ((eal org-emphasis-alist) e det
5336 (erc org-emphasis-regexp-components)
5337 (prompt "")
5338 (string "") beg end move tag c s)
5339 (if (org-region-active-p)
5340 (setq beg (region-beginning) end (region-end)
5341 string (buffer-substring beg end))
5342 (setq move t))
5344 (while (setq e (pop eal))
5345 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5346 c (aref tag 0))
5347 (push (cons c (string-to-char (car e))) det)
5348 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5349 (substring tag 1)))))
5350 (setq det (nreverse det))
5351 (unless char
5352 (message "%s" (concat "Emphasis marker or tag:" prompt))
5353 (setq char (read-char-exclusive)))
5354 (setq char (or (cdr (assoc char det)) char))
5355 (if (equal char ?\ )
5356 (setq s "" move nil)
5357 (unless (assoc (char-to-string char) org-emphasis-alist)
5358 (error "No such emphasis marker: \"%c\"" char))
5359 (setq s (char-to-string char)))
5360 (while (and (> (length string) 1)
5361 (equal (substring string 0 1) (substring string -1))
5362 (assoc (substring string 0 1) org-emphasis-alist))
5363 (setq string (substring string 1 -1)))
5364 (setq string (concat s string s))
5365 (if beg (delete-region beg end))
5366 (unless (or (bolp)
5367 (string-match (concat "[" (nth 0 erc) "\n]")
5368 (char-to-string (char-before (point)))))
5369 (insert " "))
5370 (unless (or (eobp)
5371 (string-match (concat "[" (nth 1 erc) "\n]")
5372 (char-to-string (char-after (point)))))
5373 (insert " ") (backward-char 1))
5374 (insert string)
5375 (and move (backward-char 1))))
5377 (defconst org-nonsticky-props
5378 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
5380 (defsubst org-rear-nonsticky-at (pos)
5381 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5383 (defun org-activate-plain-links (limit)
5384 "Run through the buffer and add overlays to links."
5385 (catch 'exit
5386 (let (f)
5387 (if (re-search-forward org-plain-link-re limit t)
5388 (progn
5389 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5390 (setq f (get-text-property (match-beginning 0) 'face))
5391 (if (or (eq f 'org-tag)
5392 (and (listp f) (memq 'org-tag f)))
5394 (add-text-properties (match-beginning 0) (match-end 0)
5395 (list 'mouse-face 'highlight
5396 'face 'org-link
5397 'keymap org-mouse-map))
5398 (org-rear-nonsticky-at (match-end 0)))
5399 t)))))
5401 (defun org-activate-code (limit)
5402 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5403 (progn
5404 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5405 (remove-text-properties (match-beginning 0) (match-end 0)
5406 '(display t invisible t intangible t))
5407 t)))
5409 (defcustom org-src-fontify-natively nil
5410 "When non-nil, fontify code in code blocks."
5411 :type 'boolean
5412 :version "24.1"
5413 :group 'org-appearance
5414 :group 'org-babel)
5416 (defun org-fontify-meta-lines-and-blocks (limit)
5417 (condition-case nil
5418 (org-fontify-meta-lines-and-blocks-1 limit)
5419 (error (message "org-mode fontification error"))))
5421 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5422 "Fontify #+ lines and blocks, in the correct ways."
5423 (let ((case-fold-search t))
5424 (if (re-search-forward
5425 "^\\([ \t]*#\\+\\(\\([a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5426 limit t)
5427 (let ((beg (match-beginning 0))
5428 (block-start (match-end 0))
5429 (block-end nil)
5430 (lang (match-string 7))
5431 (beg1 (line-beginning-position 2))
5432 (dc1 (downcase (match-string 2)))
5433 (dc3 (downcase (match-string 3)))
5434 end end1 quoting block-type ovl)
5435 (cond
5436 ((member dc1 '("html:" "ascii:" "latex:" "docbook:"))
5437 ;; a single line of backend-specific content
5438 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5439 (remove-text-properties (match-beginning 0) (match-end 0)
5440 '(display t invisible t intangible t))
5441 (add-text-properties (match-beginning 1) (match-end 3)
5442 '(font-lock-fontified t face org-meta-line))
5443 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5444 '(font-lock-fontified t face org-block))
5445 ; for backend-specific code
5447 ((and (match-end 4) (equal dc3 "begin"))
5448 ;; Truly a block
5449 (setq block-type (downcase (match-string 5))
5450 quoting (member block-type org-protecting-blocks))
5451 (when (re-search-forward
5452 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5453 nil t) ;; on purpose, we look further than LIMIT
5454 (setq end (min (point-max) (match-end 0))
5455 end1 (min (point-max) (1- (match-beginning 0))))
5456 (setq block-end (match-beginning 0))
5457 (when quoting
5458 (remove-text-properties beg end
5459 '(display t invisible t intangible t)))
5460 (add-text-properties
5461 beg end
5462 '(font-lock-fontified t font-lock-multiline t))
5463 (add-text-properties beg beg1 '(face org-meta-line))
5464 (add-text-properties end1 (min (point-max) (1+ end))
5465 '(face org-meta-line)) ; for end_src
5466 (cond
5467 ((and lang (not (string= lang "")) org-src-fontify-natively)
5468 (org-src-font-lock-fontify-block lang block-start block-end)
5469 ;; remove old background overlays
5470 (mapc (lambda (ov)
5471 (if (eq (overlay-get ov 'face) 'org-block-background)
5472 (delete-overlay ov)))
5473 (overlays-at (/ (+ beg1 block-end) 2)))
5474 ;; add a background overlay
5475 (setq ovl (make-overlay beg1 block-end))
5476 (overlay-put ovl 'face 'org-block-background)
5477 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5478 (quoting
5479 (add-text-properties beg1 (min (point-max) (1+ end1))
5480 '(face org-block))) ; end of source block
5481 ((not org-fontify-quote-and-verse-blocks))
5482 ((string= block-type "quote")
5483 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5484 ((string= block-type "verse")
5485 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5486 (add-text-properties beg beg1 '(face org-block-begin-line))
5487 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5488 '(face org-block-end-line))
5490 ((member dc1 '("title:" "author:" "email:" "date:"))
5491 (add-text-properties
5492 beg (match-end 3)
5493 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5494 '(font-lock-fontified t invisible t)
5495 '(font-lock-fontified t face org-document-info-keyword)))
5496 (add-text-properties
5497 (match-beginning 6) (match-end 6)
5498 (if (string-equal dc1 "title:")
5499 '(font-lock-fontified t face org-document-title)
5500 '(font-lock-fontified t face org-document-info))))
5501 ((not (member (char-after beg) '(?\ ?\t)))
5502 ;; just any other in-buffer setting, but not indented
5503 (add-text-properties
5504 beg (match-end 0)
5505 '(font-lock-fontified t face org-meta-line))
5507 ((or (member dc1 '("begin:" "end:" "caption:" "label:"
5508 "orgtbl:" "tblfm:" "tblname:" "results:"
5509 "call:" "header:" "headers:" "name:"))
5510 (and (match-end 4) (equal dc3 "attr")))
5511 (add-text-properties
5512 beg (match-end 0)
5513 '(font-lock-fontified t face org-meta-line))
5515 ((member dc3 '(" " ""))
5516 (add-text-properties
5517 beg (match-end 0)
5518 '(font-lock-fontified t face font-lock-comment-face)))
5519 (t nil))))))
5521 (defun org-strip-protective-commas (beg end)
5522 "Strip protective commas between BEG and END in the current buffer."
5523 (interactive "r")
5524 (save-excursion
5525 (save-match-data
5526 (goto-char beg)
5527 (let ((front-line (save-excursion
5528 (re-search-forward
5529 "[^[:space:]]" end t)
5530 (goto-char (match-beginning 0))
5531 (current-column))))
5532 (while (re-search-forward "^[ \t]*\\(,\\)\\([*]\\|#\\+\\)" end t)
5533 (goto-char (match-beginning 1))
5534 (when (= (current-column) front-line)
5535 (replace-match "" nil nil nil 1)))))))
5537 (defun org-activate-angle-links (limit)
5538 "Run through the buffer and add overlays to links."
5539 (if (re-search-forward org-angle-link-re limit t)
5540 (progn
5541 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5542 (add-text-properties (match-beginning 0) (match-end 0)
5543 (list 'mouse-face 'highlight
5544 'keymap org-mouse-map))
5545 (org-rear-nonsticky-at (match-end 0))
5546 t)))
5548 (defun org-activate-footnote-links (limit)
5549 "Run through the buffer and add overlays to footnotes."
5550 (let ((fn (org-footnote-next-reference-or-definition limit)))
5551 (when fn
5552 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5553 (org-remove-flyspell-overlays-in beg end)
5554 (add-text-properties beg end
5555 (list 'mouse-face 'highlight
5556 'keymap org-mouse-map
5557 'help-echo
5558 (if (= (point-at-bol) beg)
5559 "Footnote definition"
5560 "Footnote reference")
5561 'font-lock-fontified t
5562 'font-lock-multiline t
5563 'face 'org-footnote))))))
5565 (defun org-activate-bracket-links (limit)
5566 "Run through the buffer and add overlays to bracketed links."
5567 (if (re-search-forward org-bracket-link-regexp limit t)
5568 (let* ((help (concat "LINK: "
5569 (org-match-string-no-properties 1)))
5570 ;; FIXME: above we should remove the escapes.
5571 ;; but that requires another match, protecting match data,
5572 ;; a lot of overhead for font-lock.
5573 (ip (org-maybe-intangible
5574 (list 'invisible 'org-link
5575 'keymap org-mouse-map 'mouse-face 'highlight
5576 'font-lock-multiline t 'help-echo help)))
5577 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5578 'font-lock-multiline t 'help-echo help)))
5579 ;; We need to remove the invisible property here. Table narrowing
5580 ;; may have made some of this invisible.
5581 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5582 (remove-text-properties (match-beginning 0) (match-end 0)
5583 '(invisible nil))
5584 (if (match-end 3)
5585 (progn
5586 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5587 (org-rear-nonsticky-at (match-beginning 3))
5588 (add-text-properties (match-beginning 3) (match-end 3) vp)
5589 (org-rear-nonsticky-at (match-end 3))
5590 (add-text-properties (match-end 3) (match-end 0) ip)
5591 (org-rear-nonsticky-at (match-end 0)))
5592 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5593 (org-rear-nonsticky-at (match-beginning 1))
5594 (add-text-properties (match-beginning 1) (match-end 1) vp)
5595 (org-rear-nonsticky-at (match-end 1))
5596 (add-text-properties (match-end 1) (match-end 0) ip)
5597 (org-rear-nonsticky-at (match-end 0)))
5598 t)))
5600 (defun org-activate-dates (limit)
5601 "Run through the buffer and add overlays to dates."
5602 (if (re-search-forward org-tsr-regexp-both limit t)
5603 (progn
5604 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5605 (add-text-properties (match-beginning 0) (match-end 0)
5606 (list 'mouse-face 'highlight
5607 'keymap org-mouse-map))
5608 (org-rear-nonsticky-at (match-end 0))
5609 (when org-display-custom-times
5610 (if (match-end 3)
5611 (org-display-custom-time (match-beginning 3) (match-end 3)))
5612 (org-display-custom-time (match-beginning 1) (match-end 1)))
5613 t)))
5615 (defvar org-target-link-regexp nil
5616 "Regular expression matching radio targets in plain text.")
5617 (make-variable-buffer-local 'org-target-link-regexp)
5618 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5619 "Regular expression matching a link target.")
5620 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5621 "Regular expression matching a radio target.")
5622 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5623 "Regular expression matching any target.")
5625 (defun org-activate-target-links (limit)
5626 "Run through the buffer and add overlays to target matches."
5627 (when org-target-link-regexp
5628 (let ((case-fold-search t))
5629 (if (re-search-forward org-target-link-regexp limit t)
5630 (progn
5631 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5632 (add-text-properties (match-beginning 0) (match-end 0)
5633 (list 'mouse-face 'highlight
5634 'keymap org-mouse-map
5635 'help-echo "Radio target link"
5636 'org-linked-text t))
5637 (org-rear-nonsticky-at (match-end 0))
5638 t)))))
5640 (defun org-update-radio-target-regexp ()
5641 "Find all radio targets in this file and update the regular expression."
5642 (interactive)
5643 (when (memq 'radio org-activate-links)
5644 (setq org-target-link-regexp
5645 (org-make-target-link-regexp (org-all-targets 'radio)))
5646 (org-restart-font-lock)))
5648 (defun org-hide-wide-columns (limit)
5649 (let (s e)
5650 (setq s (text-property-any (point) (or limit (point-max))
5651 'org-cwidth t))
5652 (when s
5653 (setq e (next-single-property-change s 'org-cwidth))
5654 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5655 (goto-char e)
5656 t)))
5658 (defvar org-latex-and-specials-regexp nil
5659 "Regular expression for highlighting export special stuff.")
5660 (defvar org-match-substring-regexp)
5661 (defvar org-match-substring-with-braces-regexp)
5663 ;; This should be with the exporter code, but we also use if for font-locking
5664 (defconst org-export-html-special-string-regexps
5665 '(("\\\\-" . "&shy;")
5666 ("---\\([^-]\\)" . "&mdash;\\1")
5667 ("--\\([^-]\\)" . "&ndash;\\1")
5668 ("\\.\\.\\." . "&hellip;"))
5669 "Regular expressions for special string conversion.")
5672 (defun org-compute-latex-and-specials-regexp ()
5673 "Compute regular expression for stuff treated specially by exporters."
5674 (if (not org-highlight-latex-fragments-and-specials)
5675 (org-set-local 'org-latex-and-specials-regexp nil)
5676 (require 'org-exp)
5677 (let*
5678 ((matchers (plist-get org-format-latex-options :matchers))
5679 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5680 org-latex-regexps)))
5681 (org-export-allow-BIND nil)
5682 (options (org-combine-plists (org-default-export-plist)
5683 (org-infile-export-plist)))
5684 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5685 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5686 (org-export-with-TeX-macros (plist-get options :TeX-macros))
5687 (org-export-html-expand (plist-get options :expand-quoted-html))
5688 (org-export-with-special-strings (plist-get options :special-strings))
5689 (re-sub
5690 (cond
5691 ((equal org-export-with-sub-superscripts '{})
5692 (list org-match-substring-with-braces-regexp))
5693 (org-export-with-sub-superscripts
5694 (list org-match-substring-regexp))
5695 (t nil)))
5696 (re-latex
5697 (if org-export-with-LaTeX-fragments
5698 (mapcar (lambda (x) (nth 1 x)) latexs)))
5699 (re-macros
5700 (if org-export-with-TeX-macros
5701 (list (concat "\\\\"
5702 (regexp-opt
5703 (append
5705 (delq nil
5706 (mapcar 'car-safe
5707 (append org-entities-user
5708 org-entities)))
5709 (if (boundp 'org-latex-entities)
5710 (mapcar (lambda (x)
5711 (or (car-safe x) x))
5712 org-latex-entities)
5713 nil))
5714 'words))) ; FIXME
5716 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5717 (re-special (if org-export-with-special-strings
5718 (mapcar (lambda (x) (car x))
5719 org-export-html-special-string-regexps)))
5720 (re-rest
5721 (delq nil
5722 (list
5723 (if org-export-html-expand "@<[^>\n]+>")
5724 ))))
5725 (org-set-local
5726 'org-latex-and-specials-regexp
5727 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5728 re-rest) "\\|")))))
5730 (defun org-do-latex-and-special-faces (limit)
5731 "Run through the buffer and add overlays to links."
5732 (when org-latex-and-specials-regexp
5733 (let (rtn d)
5734 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5735 limit t))
5736 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5737 'face))
5738 '(org-code org-verbatim underline)))
5739 (progn
5740 (setq rtn t
5741 d (cond ((member (char-after (1+ (match-beginning 0)))
5742 '(?_ ?^)) 1)
5743 (t 0)))
5744 (font-lock-prepend-text-property
5745 (+ d (match-beginning 0)) (match-end 0)
5746 'face 'org-latex-and-export-specials)
5747 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5748 '(font-lock-multiline t)))))
5749 rtn)))
5751 (defun org-restart-font-lock ()
5752 "Restart `font-lock-mode', to force refontification."
5753 (when (and (boundp 'font-lock-mode) font-lock-mode)
5754 (font-lock-mode -1)
5755 (font-lock-mode 1)))
5757 (defun org-all-targets (&optional radio)
5758 "Return a list of all targets in this file.
5759 With optional argument RADIO, only find radio targets."
5760 (let ((re (if radio org-radio-target-regexp org-target-regexp))
5761 rtn)
5762 (save-excursion
5763 (goto-char (point-min))
5764 (while (re-search-forward re nil t)
5765 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
5766 rtn)))
5768 (defun org-make-target-link-regexp (targets)
5769 "Make regular expression matching all strings in TARGETS.
5770 The regular expression finds the targets also if there is a line break
5771 between words."
5772 (and targets
5773 (concat
5774 "\\<\\("
5775 (mapconcat
5776 (lambda (x)
5777 (setq x (regexp-quote x))
5778 (while (string-match " +" x)
5779 (setq x (replace-match "\\s-+" t t x)))
5781 targets
5782 "\\|")
5783 "\\)\\>")))
5785 (defun org-activate-tags (limit)
5786 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
5787 (progn
5788 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5789 (add-text-properties (match-beginning 1) (match-end 1)
5790 (list 'mouse-face 'highlight
5791 'keymap org-mouse-map))
5792 (org-rear-nonsticky-at (match-end 1))
5793 t)))
5795 (defun org-outline-level ()
5796 "Compute the outline level of the heading at point.
5797 This function assumes that the cursor is at the beginning of a line matched
5798 by `outline-regexp'. Otherwise it returns garbage.
5799 If this is called at a normal headline, the level is the number of stars.
5800 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
5801 (save-excursion
5802 (looking-at org-outline-regexp)
5803 (1- (- (match-end 0) (match-beginning 0)))))
5805 (defvar org-font-lock-keywords nil)
5807 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\+?\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
5808 "Regular expression matching a property line.")
5810 (defvar org-font-lock-hook nil
5811 "Functions to be called for special font lock stuff.")
5813 (defvar org-font-lock-set-keywords-hook nil
5814 "Functions that can manipulate `org-font-lock-extra-keywords'.
5815 This is called after `org-font-lock-extra-keywords' is defined, but before
5816 it is installed to be used by font lock. This can be useful if something
5817 needs to be inserted at a specific position in the font-lock sequence.")
5819 (defun org-font-lock-hook (limit)
5820 (run-hook-with-args 'org-font-lock-hook limit))
5822 (defun org-set-font-lock-defaults ()
5823 (let* ((em org-fontify-emphasized-text)
5824 (lk org-activate-links)
5825 (org-font-lock-extra-keywords
5826 (list
5827 ;; Call the hook
5828 '(org-font-lock-hook)
5829 ;; Headlines
5830 `(,(if org-fontify-whole-heading-line
5831 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
5832 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
5833 (1 (org-get-level-face 1))
5834 (2 (org-get-level-face 2))
5835 (3 (org-get-level-face 3)))
5836 ;; Table lines
5837 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5838 (1 'org-table t))
5839 ;; Table internals
5840 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5841 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5842 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5843 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
5844 ;; Drawers
5845 (list org-drawer-regexp '(0 'org-special-keyword t))
5846 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5847 ;; Properties
5848 (list org-property-re
5849 '(1 'org-special-keyword t)
5850 '(3 'org-property-value t))
5851 ;; Links
5852 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5853 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5854 (if (memq 'plain lk) '(org-activate-plain-links))
5855 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5856 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5857 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5858 (if (memq 'footnote lk) '(org-activate-footnote-links))
5859 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5860 '(org-hide-wide-columns (0 nil append))
5861 ;; TODO keyword
5862 (list (format org-heading-keyword-regexp-format
5863 org-todo-regexp)
5864 '(2 (org-get-todo-face 2) t))
5865 ;; DONE
5866 (if org-fontify-done-headline
5867 (list (format org-heading-keyword-regexp-format
5868 (concat
5869 "\\(?:"
5870 (mapconcat 'regexp-quote org-done-keywords "\\|")
5871 "\\)"))
5872 '(2 'org-headline-done t))
5873 nil)
5874 ;; Priorities
5875 '(org-font-lock-add-priority-faces)
5876 ;; Tags
5877 '(org-font-lock-add-tag-faces)
5878 ;; Special keywords
5879 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5880 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5881 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5882 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5883 ;; Emphasis
5884 (if em
5885 (if (featurep 'xemacs)
5886 '(org-do-emphasis-faces (0 nil append))
5887 '(org-do-emphasis-faces)))
5888 ;; Checkboxes
5889 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
5890 1 'org-checkbox prepend)
5891 (if (cdr (assq 'checkbox org-list-automatic-rules))
5892 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5893 (0 (org-get-checkbox-statistics-face) t)))
5894 ;; Description list items
5895 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
5896 1 'bold prepend)
5897 ;; ARCHIVEd headings
5898 (list (concat
5899 org-outline-regexp-bol
5900 "\\(.*:" org-archive-tag ":.*\\)")
5901 '(1 'org-archived prepend))
5902 ;; Specials
5903 '(org-do-latex-and-special-faces)
5904 '(org-fontify-entities)
5905 '(org-raise-scripts)
5906 ;; Code
5907 '(org-activate-code (1 'org-code t))
5908 ;; COMMENT
5909 (list (format org-heading-keyword-regexp-format
5910 (concat "\\("
5911 org-comment-string "\\|" org-quote-string
5912 "\\)"))
5913 '(2 'org-special-keyword t))
5914 '("^#.*" (0 'font-lock-comment-face t))
5915 ;; Blocks and meta lines
5916 '(org-fontify-meta-lines-and-blocks)
5918 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5919 (run-hooks 'org-font-lock-set-keywords-hook)
5920 ;; Now set the full font-lock-keywords
5921 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5922 (org-set-local 'font-lock-defaults
5923 '(org-font-lock-keywords t nil nil backward-paragraph))
5924 (kill-local-variable 'font-lock-keywords) nil))
5926 (defun org-toggle-pretty-entities ()
5927 "Toggle the composition display of entities as UTF8 characters."
5928 (interactive)
5929 (org-set-local 'org-pretty-entities (not org-pretty-entities))
5930 (org-restart-font-lock)
5931 (if org-pretty-entities
5932 (message "Entities are displayed as UTF8 characters")
5933 (save-restriction
5934 (widen)
5935 (org-decompose-region (point-min) (point-max))
5936 (message "Entities are displayed plain"))))
5938 (defun org-fontify-entities (limit)
5939 "Find an entity to fontify."
5940 (let (ee)
5941 (when org-pretty-entities
5942 (catch 'match
5943 (while (re-search-forward
5944 "\\\\\\(frac[13][24]\\|[a-zA-Z]+\\)\\($\\|[^[:alpha:]\n]\\)"
5945 limit t)
5946 (if (and (not (org-in-indented-comment-line))
5947 (setq ee (org-entity-get (match-string 1)))
5948 (= (length (nth 6 ee)) 1))
5949 (progn
5950 (add-text-properties
5951 (match-beginning 0) (match-end 1)
5952 (list 'font-lock-fontified t))
5953 (compose-region (match-beginning 0) (match-end 1)
5954 (nth 6 ee) nil)
5955 (backward-char 1)
5956 (throw 'match t))))
5957 nil))))
5959 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
5960 "Fontify string S like in Org-mode."
5961 (with-temp-buffer
5962 (insert s)
5963 (let ((org-odd-levels-only odd-levels))
5964 (org-mode)
5965 (font-lock-fontify-buffer)
5966 (buffer-string))))
5968 (defvar org-m nil)
5969 (defvar org-l nil)
5970 (defvar org-f nil)
5971 (defun org-get-level-face (n)
5972 "Get the right face for match N in font-lock matching of headlines."
5973 (setq org-l (- (match-end 2) (match-beginning 1) 1))
5974 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
5975 (if org-cycle-level-faces
5976 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
5977 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
5978 (cond
5979 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
5980 ((eq n 2) org-f)
5981 (t (if org-level-color-stars-only nil org-f))))
5984 (defun org-get-todo-face (kwd)
5985 "Get the right face for a TODO keyword KWD.
5986 If KWD is a number, get the corresponding match group."
5987 (if (numberp kwd) (setq kwd (match-string kwd)))
5988 (or (org-face-from-face-or-color
5989 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
5990 (and (member kwd org-done-keywords) 'org-done)
5991 'org-todo))
5993 (defun org-face-from-face-or-color (context inherit face-or-color)
5994 "Create a face list that inherits INHERIT, but sets the foreground color.
5995 When FACE-OR-COLOR is not a string, just return it."
5996 (if (stringp face-or-color)
5997 (list :inherit inherit
5998 (cdr (assoc context org-faces-easy-properties))
5999 face-or-color)
6000 face-or-color))
6002 (defun org-font-lock-add-tag-faces (limit)
6003 "Add the special tag faces."
6004 (when (and org-tag-faces org-tags-special-faces-re)
6005 (while (re-search-forward org-tags-special-faces-re limit t)
6006 (add-text-properties (match-beginning 1) (match-end 1)
6007 (list 'face (org-get-tag-face 1)
6008 'font-lock-fontified t))
6009 (backward-char 1))))
6011 (defun org-font-lock-add-priority-faces (limit)
6012 "Add the special priority faces."
6013 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6014 (add-text-properties
6015 (match-beginning 0) (match-end 0)
6016 (list 'face (or (org-face-from-face-or-color
6017 'priority 'org-special-keyword
6018 (cdr (assoc (char-after (match-beginning 1))
6019 org-priority-faces)))
6020 'org-special-keyword)
6021 'font-lock-fontified t))))
6023 (defun org-get-tag-face (kwd)
6024 "Get the right face for a TODO keyword KWD.
6025 If KWD is a number, get the corresponding match group."
6026 (if (numberp kwd) (setq kwd (match-string kwd)))
6027 (or (org-face-from-face-or-color
6028 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6029 'org-tag))
6031 (defun org-unfontify-region (beg end &optional maybe_loudly)
6032 "Remove fontification and activation overlays from links."
6033 (font-lock-default-unfontify-region beg end)
6034 (let* ((buffer-undo-list t)
6035 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6036 (inhibit-modification-hooks t)
6037 deactivate-mark buffer-file-name buffer-file-truename)
6038 (org-decompose-region beg end)
6039 (remove-text-properties beg end
6040 '(mouse-face t keymap t org-linked-text t
6041 invisible t intangible t
6042 org-no-flyspell t org-emphasis t))
6043 (org-remove-font-lock-display-properties beg end)))
6045 (defconst org-script-display '(((raise -0.3) (height 0.7))
6046 ((raise 0.3) (height 0.7))
6047 ((raise -0.5))
6048 ((raise 0.5)))
6049 "Display properties for showing superscripts and subscripts.")
6051 (defun org-remove-font-lock-display-properties (beg end)
6052 "Remove specific display properties that have been added by font lock.
6053 The will remove the raise properties that are used to show superscripts
6054 and subscripts."
6055 (let (next prop)
6056 (while (< beg end)
6057 (setq next (next-single-property-change beg 'display nil end)
6058 prop (get-text-property beg 'display))
6059 (if (member prop org-script-display)
6060 (put-text-property beg next 'display nil))
6061 (setq beg next))))
6063 (defun org-raise-scripts (limit)
6064 "Add raise properties to sub/superscripts."
6065 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6066 (if (re-search-forward
6067 (if (eq org-use-sub-superscripts t)
6068 org-match-substring-regexp
6069 org-match-substring-with-braces-regexp)
6070 limit t)
6071 (let* ((pos (point)) table-p comment-p
6072 (mpos (match-beginning 3))
6073 (emph-p (get-text-property mpos 'org-emphasis))
6074 (link-p (get-text-property mpos 'mouse-face))
6075 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6076 (goto-char (point-at-bol))
6077 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6078 comment-p (org-looking-at-p "[ \t]*#"))
6079 (goto-char pos)
6080 ;; FIXME: Should we go back one character here, for a_b^c
6081 ;; (goto-char (1- pos)) ;????????????????????
6082 (if (or comment-p emph-p link-p keyw-p)
6084 (put-text-property (match-beginning 3) (match-end 0)
6085 'display
6086 (if (equal (char-after (match-beginning 2)) ?^)
6087 (nth (if table-p 3 1) org-script-display)
6088 (nth (if table-p 2 0) org-script-display)))
6089 (add-text-properties (match-beginning 2) (match-end 2)
6090 (list 'invisible t
6091 'org-dwidth t 'org-dwidth-n 1))
6092 (if (and (eq (char-after (match-beginning 3)) ?{)
6093 (eq (char-before (match-end 3)) ?}))
6094 (progn
6095 (add-text-properties
6096 (match-beginning 3) (1+ (match-beginning 3))
6097 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6098 (add-text-properties
6099 (1- (match-end 3)) (match-end 3)
6100 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6101 t)))))
6103 ;;;; Visibility cycling, including org-goto and indirect buffer
6105 ;;; Cycling
6107 (defvar org-cycle-global-status nil)
6108 (make-variable-buffer-local 'org-cycle-global-status)
6109 (defvar org-cycle-subtree-status nil)
6110 (make-variable-buffer-local 'org-cycle-subtree-status)
6112 ;;;###autoload
6114 (defvar org-inlinetask-min-level)
6116 (defun org-cycle (&optional arg)
6117 "TAB-action and visibility cycling for Org-mode.
6119 This is the command invoked in Org-mode by the TAB key. Its main purpose
6120 is outline visibility cycling, but it also invokes other actions
6121 in special contexts.
6123 - When this function is called with a prefix argument, rotate the entire
6124 buffer through 3 states (global cycling)
6125 1. OVERVIEW: Show only top-level headlines.
6126 2. CONTENTS: Show all headlines of all levels, but no body text.
6127 3. SHOW ALL: Show everything.
6128 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6129 determined by the variable `org-startup-folded', and by any VISIBILITY
6130 properties in the buffer.
6131 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6132 including any drawers.
6134 - When inside a table, re-align the table and move to the next field.
6136 - When point is at the beginning of a headline, rotate the subtree started
6137 by this line through 3 different states (local cycling)
6138 1. FOLDED: Only the main headline is shown.
6139 2. CHILDREN: The main headline and the direct children are shown.
6140 From this state, you can move to one of the children
6141 and zoom in further.
6142 3. SUBTREE: Show the entire subtree, including body text.
6143 If there is no subtree, switch directly from CHILDREN to FOLDED.
6145 - When point is at the beginning of an empty headline and the variable
6146 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6147 of the headline by demoting and promoting it to likely levels. This
6148 speeds up creation document structure by pressing TAB once or several
6149 times right after creating a new headline.
6151 - When there is a numeric prefix, go up to a heading with level ARG, do
6152 a `show-subtree' and return to the previous cursor position. If ARG
6153 is negative, go up that many levels.
6155 - When point is not at the beginning of a headline, execute the global
6156 binding for TAB, which is re-indenting the line. See the option
6157 `org-cycle-emulate-tab' for details.
6159 - Special case: if point is at the beginning of the buffer and there is
6160 no headline in line 1, this function will act as if called with prefix arg
6161 (C-u TAB, same as S-TAB) also when called without prefix arg.
6162 But only if also the variable `org-cycle-global-at-bob' is t."
6163 (interactive "P")
6164 (org-load-modules-maybe)
6165 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6166 (and org-cycle-level-after-item/entry-creation
6167 (or (org-cycle-level)
6168 (org-cycle-item-indentation))))
6169 (let* ((limit-level
6170 (or org-cycle-max-level
6171 (and (boundp 'org-inlinetask-min-level)
6172 org-inlinetask-min-level
6173 (1- org-inlinetask-min-level))))
6174 (nstars (and limit-level
6175 (if org-odd-levels-only
6176 (and limit-level (1- (* limit-level 2)))
6177 limit-level)))
6178 (org-outline-regexp
6179 (if (not (derived-mode-p 'org-mode))
6180 outline-regexp
6181 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6182 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6183 (not (looking-at org-outline-regexp))))
6184 (org-cycle-hook
6185 (if bob-special
6186 (delq 'org-optimize-window-after-visibility-change
6187 (copy-sequence org-cycle-hook))
6188 org-cycle-hook))
6189 (pos (point)))
6191 (if (or bob-special (equal arg '(4)))
6192 ;; special case: use global cycling
6193 (setq arg t))
6195 (cond
6197 ((equal arg '(16))
6198 (setq last-command 'dummy)
6199 (org-set-startup-visibility)
6200 (message "Startup visibility, plus VISIBILITY properties"))
6202 ((equal arg '(64))
6203 (show-all)
6204 (message "Entire buffer visible, including drawers"))
6206 ;; Table: enter it or move to the next field.
6207 ((org-at-table-p 'any)
6208 (if (org-at-table.el-p)
6209 (message "Use C-c ' to edit table.el tables")
6210 (if arg (org-table-edit-field t)
6211 (org-table-justify-field-maybe)
6212 (call-interactively 'org-table-next-field))))
6214 ((run-hook-with-args-until-success
6215 'org-tab-after-check-for-table-hook))
6217 ;; Global cycling: delegate to `org-cycle-internal-global'.
6218 ((eq arg t) (org-cycle-internal-global))
6220 ;; Drawers: delegate to `org-flag-drawer'.
6221 ((and org-drawers org-drawer-regexp
6222 (save-excursion
6223 (beginning-of-line 1)
6224 (looking-at org-drawer-regexp)))
6225 (org-flag-drawer ; toggle block visibility
6226 (not (get-char-property (match-end 0) 'invisible))))
6228 ;; Show-subtree, ARG levels up from here.
6229 ((integerp arg)
6230 (save-excursion
6231 (org-back-to-heading)
6232 (outline-up-heading (if (< arg 0) (- arg)
6233 (- (funcall outline-level) arg)))
6234 (org-show-subtree)))
6236 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6237 ((and (featurep 'org-inlinetask)
6238 (org-inlinetask-at-task-p)
6239 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6240 (org-inlinetask-toggle-visibility))
6242 ((org-try-cdlatex-tab))
6244 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6245 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6246 (save-excursion (beginning-of-line 1)
6247 (looking-at org-outline-regexp)))
6248 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6249 (org-cycle-internal-local))
6251 ;; From there: TAB emulation and template completion.
6252 (buffer-read-only (org-back-to-heading))
6254 ((run-hook-with-args-until-success
6255 'org-tab-after-check-for-cycling-hook))
6257 ((org-try-structure-completion))
6259 ((run-hook-with-args-until-success
6260 'org-tab-before-tab-emulation-hook))
6262 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6263 (or (not (bolp))
6264 (not (looking-at org-outline-regexp))))
6265 (call-interactively (global-key-binding "\t")))
6267 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6268 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6269 (or (and (eq org-cycle-emulate-tab 'white)
6270 (= (match-end 0) (point-at-eol)))
6271 (and (eq org-cycle-emulate-tab 'whitestart)
6272 (>= (match-end 0) pos))))
6274 (eq org-cycle-emulate-tab t))
6275 (call-interactively (global-key-binding "\t")))
6277 (t (save-excursion
6278 (org-back-to-heading)
6279 (org-cycle)))))))
6281 (defun org-cycle-internal-global ()
6282 "Do the global cycling action."
6283 ;; Hack to avoid display of messages for .org attachments in Gnus
6284 (let ((ga (string-match "\\*fontification" (buffer-name))))
6285 (cond
6286 ((and (eq last-command this-command)
6287 (eq org-cycle-global-status 'overview))
6288 ;; We just created the overview - now do table of contents
6289 ;; This can be slow in very large buffers, so indicate action
6290 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6291 (unless ga (message "CONTENTS..."))
6292 (org-content)
6293 (unless ga (message "CONTENTS...done"))
6294 (setq org-cycle-global-status 'contents)
6295 (run-hook-with-args 'org-cycle-hook 'contents))
6297 ((and (eq last-command this-command)
6298 (eq org-cycle-global-status 'contents))
6299 ;; We just showed the table of contents - now show everything
6300 (run-hook-with-args 'org-pre-cycle-hook 'all)
6301 (show-all)
6302 (unless ga (message "SHOW ALL"))
6303 (setq org-cycle-global-status 'all)
6304 (run-hook-with-args 'org-cycle-hook 'all))
6307 ;; Default action: go to overview
6308 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6309 (org-overview)
6310 (unless ga (message "OVERVIEW"))
6311 (setq org-cycle-global-status 'overview)
6312 (run-hook-with-args 'org-cycle-hook 'overview)))))
6314 (defun org-cycle-internal-local ()
6315 "Do the local cycling action."
6316 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6317 ;; First, determine end of headline (EOH), end of subtree or item
6318 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6319 (save-excursion
6320 (if (org-at-item-p)
6321 (progn
6322 (beginning-of-line)
6323 (setq struct (org-list-struct))
6324 (setq eoh (point-at-eol))
6325 (setq eos (org-list-get-item-end-before-blank (point) struct))
6326 (setq has-children (org-list-has-child-p (point) struct)))
6327 (org-back-to-heading)
6328 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6329 (setq eos (save-excursion
6330 (org-end-of-subtree t)
6331 (unless (eobp)
6332 (skip-chars-forward " \t\n"))
6333 (if (eobp) (point) (1- (point)))))
6334 (setq has-children
6335 (or (save-excursion
6336 (let ((level (funcall outline-level)))
6337 (outline-next-heading)
6338 (and (org-at-heading-p t)
6339 (> (funcall outline-level) level))))
6340 (save-excursion
6341 (org-list-search-forward (org-item-beginning-re) eos t)))))
6342 ;; Determine end invisible part of buffer (EOL)
6343 (beginning-of-line 2)
6344 ;; XEmacs doesn't have `next-single-char-property-change'
6345 (if (featurep 'xemacs)
6346 (while (and (not (eobp)) ;; this is like `next-line'
6347 (get-char-property (1- (point)) 'invisible))
6348 (beginning-of-line 2))
6349 (while (and (not (eobp)) ;; this is like `next-line'
6350 (get-char-property (1- (point)) 'invisible))
6351 (goto-char (next-single-char-property-change (point) 'invisible))
6352 (and (eolp) (beginning-of-line 2))))
6353 (setq eol (point)))
6354 ;; Find out what to do next and set `this-command'
6355 (cond
6356 ((= eos eoh)
6357 ;; Nothing is hidden behind this heading
6358 (run-hook-with-args 'org-pre-cycle-hook 'empty)
6359 (message "EMPTY ENTRY")
6360 (setq org-cycle-subtree-status nil)
6361 (save-excursion
6362 (goto-char eos)
6363 (outline-next-heading)
6364 (if (outline-invisible-p) (org-flag-heading nil))))
6365 ((and (or (>= eol eos)
6366 (not (string-match "\\S-" (buffer-substring eol eos))))
6367 (or has-children
6368 (not (setq children-skipped
6369 org-cycle-skip-children-state-if-no-children))))
6370 ;; Entire subtree is hidden in one line: children view
6371 (run-hook-with-args 'org-pre-cycle-hook 'children)
6372 (if (org-at-item-p)
6373 (org-list-set-item-visibility (point-at-bol) struct 'children)
6374 (org-show-entry)
6375 (org-with-limited-levels (show-children))
6376 ;; FIXME: This slows down the func way too much.
6377 ;; How keep drawers hidden in subtree anyway?
6378 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6379 ;; (org-cycle-hide-drawers 'subtree))
6381 ;; Fold every list in subtree to top-level items.
6382 (when (eq org-cycle-include-plain-lists 'integrate)
6383 (save-excursion
6384 (org-back-to-heading)
6385 (while (org-list-search-forward (org-item-beginning-re) eos t)
6386 (beginning-of-line 1)
6387 (let* ((struct (org-list-struct))
6388 (prevs (org-list-prevs-alist struct))
6389 (end (org-list-get-bottom-point struct)))
6390 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6391 (org-list-get-all-items (point) struct prevs))
6392 (goto-char end))))))
6393 (message "CHILDREN")
6394 (save-excursion
6395 (goto-char eos)
6396 (outline-next-heading)
6397 (if (outline-invisible-p) (org-flag-heading nil)))
6398 (setq org-cycle-subtree-status 'children)
6399 (run-hook-with-args 'org-cycle-hook 'children))
6400 ((or children-skipped
6401 (and (eq last-command this-command)
6402 (eq org-cycle-subtree-status 'children)))
6403 ;; We just showed the children, or no children are there,
6404 ;; now show everything.
6405 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
6406 (outline-flag-region eoh eos nil)
6407 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6408 (setq org-cycle-subtree-status 'subtree)
6409 (run-hook-with-args 'org-cycle-hook 'subtree))
6411 ;; Default action: hide the subtree.
6412 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6413 (outline-flag-region eoh eos t)
6414 (message "FOLDED")
6415 (setq org-cycle-subtree-status 'folded)
6416 (run-hook-with-args 'org-cycle-hook 'folded)))))
6418 ;;;###autoload
6419 (defun org-global-cycle (&optional arg)
6420 "Cycle the global visibility. For details see `org-cycle'.
6421 With \\[universal-argument] prefix arg, switch to startup visibility.
6422 With a numeric prefix, show all headlines up to that level."
6423 (interactive "P")
6424 (let ((org-cycle-include-plain-lists
6425 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6426 (cond
6427 ((integerp arg)
6428 (show-all)
6429 (hide-sublevels arg)
6430 (setq org-cycle-global-status 'contents))
6431 ((equal arg '(4))
6432 (org-set-startup-visibility)
6433 (message "Startup visibility, plus VISIBILITY properties."))
6435 (org-cycle '(4))))))
6437 (defun org-set-startup-visibility ()
6438 "Set the visibility required by startup options and properties."
6439 (cond
6440 ((eq org-startup-folded t)
6441 (org-cycle '(4)))
6442 ((eq org-startup-folded 'content)
6443 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6444 (org-cycle '(4)) (org-cycle '(4)))))
6445 (unless (eq org-startup-folded 'showeverything)
6446 (if org-hide-block-startup (org-hide-block-all))
6447 (org-set-visibility-according-to-property 'no-cleanup)
6448 (org-cycle-hide-archived-subtrees 'all)
6449 (org-cycle-hide-drawers 'all)
6450 (org-cycle-show-empty-lines t)))
6452 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6453 "Switch subtree visibilities according to :VISIBILITY: property."
6454 (interactive)
6455 (let (org-show-entry-below state)
6456 (save-excursion
6457 (goto-char (point-min))
6458 (while (re-search-forward
6459 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6460 nil t)
6461 (setq state (match-string 1))
6462 (save-excursion
6463 (org-back-to-heading t)
6464 (hide-subtree)
6465 (org-reveal)
6466 (cond
6467 ((equal state '("fold" "folded"))
6468 (hide-subtree))
6469 ((equal state "children")
6470 (org-show-hidden-entry)
6471 (show-children))
6472 ((equal state "content")
6473 (save-excursion
6474 (save-restriction
6475 (org-narrow-to-subtree)
6476 (org-content))))
6477 ((member state '("all" "showall"))
6478 (show-subtree)))))
6479 (unless no-cleanup
6480 (org-cycle-hide-archived-subtrees 'all)
6481 (org-cycle-hide-drawers 'all)
6482 (org-cycle-show-empty-lines 'all)))))
6484 ;; This function uses outline-regexp instead of the more fundamental
6485 ;; org-outline-regexp so that org-cycle-global works outside of Org
6486 ;; buffers, where outline-regexp is needed.
6487 (defun org-overview ()
6488 "Switch to overview mode, showing only top-level headlines.
6489 Really, this shows all headlines with level equal or greater than the level
6490 of the first headline in the buffer. This is important, because if the
6491 first headline is not level one, then (hide-sublevels 1) gives confusing
6492 results."
6493 (interactive)
6494 (let ((level (save-excursion
6495 (goto-char (point-min))
6496 (if (re-search-forward (concat "^" outline-regexp) nil t)
6497 (progn
6498 (goto-char (match-beginning 0))
6499 (funcall outline-level))))))
6500 (and level (hide-sublevels level))))
6502 (defun org-content (&optional arg)
6503 "Show all headlines in the buffer, like a table of contents.
6504 With numerical argument N, show content up to level N."
6505 (interactive "P")
6506 (save-excursion
6507 ;; Visit all headings and show their offspring
6508 (and (integerp arg) (org-overview))
6509 (goto-char (point-max))
6510 (catch 'exit
6511 (while (and (progn (condition-case nil
6512 (outline-previous-visible-heading 1)
6513 (error (goto-char (point-min))))
6515 (looking-at org-outline-regexp))
6516 (if (integerp arg)
6517 (show-children (1- arg))
6518 (show-branches))
6519 (if (bobp) (throw 'exit nil))))))
6522 (defun org-optimize-window-after-visibility-change (state)
6523 "Adjust the window after a change in outline visibility.
6524 This function is the default value of the hook `org-cycle-hook'."
6525 (when (get-buffer-window (current-buffer))
6526 (cond
6527 ((eq state 'content) nil)
6528 ((eq state 'all) nil)
6529 ((eq state 'folded) nil)
6530 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6531 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6533 (defun org-remove-empty-overlays-at (pos)
6534 "Remove outline overlays that do not contain non-white stuff."
6535 (mapc
6536 (lambda (o)
6537 (and (eq 'outline (overlay-get o 'invisible))
6538 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6539 (overlay-end o))))
6540 (delete-overlay o)))
6541 (overlays-at pos)))
6543 (defun org-clean-visibility-after-subtree-move ()
6544 "Fix visibility issues after moving a subtree."
6545 ;; First, find a reasonable region to look at:
6546 ;; Start two siblings above, end three below
6547 (let* ((beg (save-excursion
6548 (and (org-get-last-sibling)
6549 (org-get-last-sibling))
6550 (point)))
6551 (end (save-excursion
6552 (and (org-get-next-sibling)
6553 (org-get-next-sibling)
6554 (org-get-next-sibling))
6555 (if (org-at-heading-p)
6556 (point-at-eol)
6557 (point))))
6558 (level (looking-at "\\*+"))
6559 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6560 (save-excursion
6561 (save-restriction
6562 (narrow-to-region beg end)
6563 (when re
6564 ;; Properly fold already folded siblings
6565 (goto-char (point-min))
6566 (while (re-search-forward re nil t)
6567 (if (and (not (outline-invisible-p))
6568 (save-excursion
6569 (goto-char (point-at-eol)) (outline-invisible-p)))
6570 (hide-entry))))
6571 (org-cycle-show-empty-lines 'overview)
6572 (org-cycle-hide-drawers 'overview)))))
6574 (defun org-cycle-show-empty-lines (state)
6575 "Show empty lines above all visible headlines.
6576 The region to be covered depends on STATE when called through
6577 `org-cycle-hook'. Lisp program can use t for STATE to get the
6578 entire buffer covered. Note that an empty line is only shown if there
6579 are at least `org-cycle-separator-lines' empty lines before the headline."
6580 (when (not (= org-cycle-separator-lines 0))
6581 (save-excursion
6582 (let* ((n (abs org-cycle-separator-lines))
6583 (re (cond
6584 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6585 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6586 (t (let ((ns (number-to-string (- n 2))))
6587 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6588 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6589 beg end b e)
6590 (cond
6591 ((memq state '(overview contents t))
6592 (setq beg (point-min) end (point-max)))
6593 ((memq state '(children folded))
6594 (setq beg (point) end (progn (org-end-of-subtree t t)
6595 (beginning-of-line 2)
6596 (point)))))
6597 (when beg
6598 (goto-char beg)
6599 (while (re-search-forward re end t)
6600 (unless (get-char-property (match-end 1) 'invisible)
6601 (setq e (match-end 1))
6602 (if (< org-cycle-separator-lines 0)
6603 (setq b (save-excursion
6604 (goto-char (match-beginning 0))
6605 (org-back-over-empty-lines)
6606 (if (save-excursion
6607 (goto-char (max (point-min) (1- (point))))
6608 (org-at-heading-p))
6609 (1- (point))
6610 (point))))
6611 (setq b (match-beginning 1)))
6612 (outline-flag-region b e nil)))))))
6613 ;; Never hide empty lines at the end of the file.
6614 (save-excursion
6615 (goto-char (point-max))
6616 (outline-previous-heading)
6617 (outline-end-of-heading)
6618 (if (and (looking-at "[ \t\n]+")
6619 (= (match-end 0) (point-max)))
6620 (outline-flag-region (point) (match-end 0) nil))))
6622 (defun org-show-empty-lines-in-parent ()
6623 "Move to the parent and re-show empty lines before visible headlines."
6624 (save-excursion
6625 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6626 (org-cycle-show-empty-lines context))))
6628 (defun org-files-list ()
6629 "Return `org-agenda-files' list, plus all open org-mode files.
6630 This is useful for operations that need to scan all of a user's
6631 open and agenda-wise Org files."
6632 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6633 (dolist (buf (buffer-list))
6634 (with-current-buffer buf
6635 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
6636 (let ((file (expand-file-name (buffer-file-name))))
6637 (unless (member file files)
6638 (push file files))))))
6639 files))
6641 (defsubst org-entry-beginning-position ()
6642 "Return the beginning position of the current entry."
6643 (save-excursion (outline-back-to-heading t) (point)))
6645 (defsubst org-entry-end-position ()
6646 "Return the end position of the current entry."
6647 (save-excursion (outline-next-heading) (point)))
6649 (defun org-cycle-hide-drawers (state)
6650 "Re-hide all drawers after a visibility state change."
6651 (when (and (derived-mode-p 'org-mode)
6652 (not (memq state '(overview folded contents))))
6653 (save-excursion
6654 (let* ((globalp (memq state '(contents all)))
6655 (beg (if globalp (point-min) (point)))
6656 (end (if globalp (point-max)
6657 (if (eq state 'children)
6658 (save-excursion (outline-next-heading) (point))
6659 (org-end-of-subtree t)))))
6660 (goto-char beg)
6661 (while (re-search-forward org-drawer-regexp end t)
6662 (org-flag-drawer t))))))
6664 (defun org-flag-drawer (flag)
6665 (save-excursion
6666 (beginning-of-line 1)
6667 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6668 (let ((b (match-end 0)))
6669 (if (re-search-forward
6670 "^[ \t]*:END:"
6671 (save-excursion (outline-next-heading) (point)) t)
6672 (outline-flag-region b (point-at-eol) flag)
6673 (error ":END: line missing at position %s" b))))))
6675 (defun org-subtree-end-visible-p ()
6676 "Is the end of the current subtree visible?"
6677 (pos-visible-in-window-p
6678 (save-excursion (org-end-of-subtree t) (point))))
6680 (defun org-first-headline-recenter (&optional N)
6681 "Move cursor to the first headline and recenter the headline.
6682 Optional argument N means put the headline into the Nth line of the window."
6683 (goto-char (point-min))
6684 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
6685 (beginning-of-line)
6686 (recenter (prefix-numeric-value N))))
6688 ;;; Saving and restoring visibility
6690 (defun org-outline-overlay-data (&optional use-markers)
6691 "Return a list of the locations of all outline overlays.
6692 These are overlays with the `invisible' property value `outline'.
6693 The return value is a list of cons cells, with start and stop
6694 positions for each overlay.
6695 If USE-MARKERS is set, return the positions as markers."
6696 (let (beg end)
6697 (save-excursion
6698 (save-restriction
6699 (widen)
6700 (delq nil
6701 (mapcar (lambda (o)
6702 (when (eq (overlay-get o 'invisible) 'outline)
6703 (setq beg (overlay-start o)
6704 end (overlay-end o))
6705 (and beg end (> end beg)
6706 (if use-markers
6707 (cons (move-marker (make-marker) beg)
6708 (move-marker (make-marker) end))
6709 (cons beg end)))))
6710 (overlays-in (point-min) (point-max))))))))
6712 (defun org-set-outline-overlay-data (data)
6713 "Create visibility overlays for all positions in DATA.
6714 DATA should have been made by `org-outline-overlay-data'."
6715 (let (o)
6716 (save-excursion
6717 (save-restriction
6718 (widen)
6719 (show-all)
6720 (mapc (lambda (c)
6721 (outline-flag-region (car c) (cdr c) t))
6722 data)))))
6724 ;;; Folding of blocks
6726 (defvar org-hide-block-overlays nil
6727 "Overlays hiding blocks.")
6728 (make-variable-buffer-local 'org-hide-block-overlays)
6730 (defun org-block-map (function &optional start end)
6731 "Call FUNCTION at the head of all source blocks in the current buffer.
6732 Optional arguments START and END can be used to limit the range."
6733 (let ((start (or start (point-min)))
6734 (end (or end (point-max))))
6735 (save-excursion
6736 (goto-char start)
6737 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
6738 (save-excursion
6739 (save-match-data
6740 (goto-char (match-beginning 0))
6741 (funcall function)))))))
6743 (defun org-hide-block-toggle-all ()
6744 "Toggle the visibility of all blocks in the current buffer."
6745 (org-block-map #'org-hide-block-toggle))
6747 (defun org-hide-block-all ()
6748 "Fold all blocks in the current buffer."
6749 (interactive)
6750 (org-show-block-all)
6751 (org-block-map #'org-hide-block-toggle-maybe))
6753 (defun org-show-block-all ()
6754 "Unfold all blocks in the current buffer."
6755 (interactive)
6756 (mapc 'delete-overlay org-hide-block-overlays)
6757 (setq org-hide-block-overlays nil))
6759 (defun org-hide-block-toggle-maybe ()
6760 "Toggle visibility of block at point."
6761 (interactive)
6762 (let ((case-fold-search t))
6763 (if (save-excursion
6764 (beginning-of-line 1)
6765 (looking-at org-block-regexp))
6766 (progn (org-hide-block-toggle)
6767 t) ;; to signal that we took action
6768 nil))) ;; to signal that we did not
6770 (defun org-hide-block-toggle (&optional force)
6771 "Toggle the visibility of the current block."
6772 (interactive)
6773 (save-excursion
6774 (beginning-of-line)
6775 (if (re-search-forward org-block-regexp nil t)
6776 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
6777 (end (match-end 0)) ;; end of entire body
6779 (if (memq t (mapcar (lambda (overlay)
6780 (eq (overlay-get overlay 'invisible)
6781 'org-hide-block))
6782 (overlays-at start)))
6783 (if (or (not force) (eq force 'off))
6784 (mapc (lambda (ov)
6785 (when (member ov org-hide-block-overlays)
6786 (setq org-hide-block-overlays
6787 (delq ov org-hide-block-overlays)))
6788 (when (eq (overlay-get ov 'invisible)
6789 'org-hide-block)
6790 (delete-overlay ov)))
6791 (overlays-at start)))
6792 (setq ov (make-overlay start end))
6793 (overlay-put ov 'invisible 'org-hide-block)
6794 ;; make the block accessible to isearch
6795 (overlay-put
6796 ov 'isearch-open-invisible
6797 (lambda (ov)
6798 (when (member ov org-hide-block-overlays)
6799 (setq org-hide-block-overlays
6800 (delq ov org-hide-block-overlays)))
6801 (when (eq (overlay-get ov 'invisible)
6802 'org-hide-block)
6803 (delete-overlay ov))))
6804 (push ov org-hide-block-overlays)))
6805 (error "Not looking at a source block"))))
6807 ;; org-tab-after-check-for-cycling-hook
6808 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
6809 ;; Remove overlays when changing major mode
6810 (add-hook 'org-mode-hook
6811 (lambda () (org-add-hook 'change-major-mode-hook
6812 'org-show-block-all 'append 'local)))
6814 ;;; Org-goto
6816 (defvar org-goto-window-configuration nil)
6817 (defvar org-goto-marker nil)
6818 (defvar org-goto-map
6819 (let ((map (make-sparse-keymap)))
6820 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
6821 (while (setq cmd (pop cmds))
6822 (substitute-key-definition cmd cmd map global-map)))
6823 (suppress-keymap map)
6824 (org-defkey map "\C-m" 'org-goto-ret)
6825 (org-defkey map [(return)] 'org-goto-ret)
6826 (org-defkey map [(left)] 'org-goto-left)
6827 (org-defkey map [(right)] 'org-goto-right)
6828 (org-defkey map [(control ?g)] 'org-goto-quit)
6829 (org-defkey map "\C-i" 'org-cycle)
6830 (org-defkey map [(tab)] 'org-cycle)
6831 (org-defkey map [(down)] 'outline-next-visible-heading)
6832 (org-defkey map [(up)] 'outline-previous-visible-heading)
6833 (if org-goto-auto-isearch
6834 (if (fboundp 'define-key-after)
6835 (define-key-after map [t] 'org-goto-local-auto-isearch)
6836 nil)
6837 (org-defkey map "q" 'org-goto-quit)
6838 (org-defkey map "n" 'outline-next-visible-heading)
6839 (org-defkey map "p" 'outline-previous-visible-heading)
6840 (org-defkey map "f" 'outline-forward-same-level)
6841 (org-defkey map "b" 'outline-backward-same-level)
6842 (org-defkey map "u" 'outline-up-heading))
6843 (org-defkey map "/" 'org-occur)
6844 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
6845 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
6846 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
6847 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
6848 (org-defkey map "\C-c\C-u" 'outline-up-heading)
6849 map))
6851 (defconst org-goto-help
6852 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
6853 RET=jump to location [Q]uit and return to previous location
6854 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
6856 (defvar org-goto-start-pos) ; dynamically scoped parameter
6858 ;; FIXME: Docstring does not mention both interfaces
6859 (defun org-goto (&optional alternative-interface)
6860 "Look up a different location in the current file, keeping current visibility.
6862 When you want look-up or go to a different location in a
6863 document, the fastest way is often to fold the entire buffer and
6864 then dive into the tree. This method has the disadvantage, that
6865 the previous location will be folded, which may not be what you
6866 want.
6868 This command works around this by showing a copy of the current
6869 buffer in an indirect buffer, in overview mode. You can dive
6870 into the tree in that copy, use org-occur and incremental search
6871 to find a location. When pressing RET or `Q', the command
6872 returns to the original buffer in which the visibility is still
6873 unchanged. After RET it will also jump to the location selected
6874 in the indirect buffer and expose the headline hierarchy above.
6876 With a prefix argument, use the alternative interface: e.g. if
6877 `org-goto-interface' is 'outline use 'outline-path-completion."
6878 (interactive "P")
6879 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
6880 (org-refile-use-outline-path t)
6881 (org-refile-target-verify-function nil)
6882 (interface
6883 (if (not alternative-interface)
6884 org-goto-interface
6885 (if (eq org-goto-interface 'outline)
6886 'outline-path-completion
6887 'outline)))
6888 (org-goto-start-pos (point))
6889 (selected-point
6890 (if (eq interface 'outline)
6891 (car (org-get-location (current-buffer) org-goto-help))
6892 (let ((pa (org-refile-get-location "Goto" nil nil t)))
6893 (org-refile-check-position pa)
6894 (nth 3 pa)))))
6895 (if selected-point
6896 (progn
6897 (org-mark-ring-push org-goto-start-pos)
6898 (goto-char selected-point)
6899 (if (or (outline-invisible-p) (org-invisible-p2))
6900 (org-show-context 'org-goto)))
6901 (message "Quit"))))
6903 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
6904 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
6905 (defvar org-goto-local-auto-isearch-map) ; defined below
6907 (defun org-get-location (buf help)
6908 "Let the user select a location in the Org-mode buffer BUF.
6909 This function uses a recursive edit. It returns the selected position
6910 or nil."
6911 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
6912 (isearch-hide-immediately nil)
6913 (isearch-search-fun-function
6914 (lambda () 'org-goto-local-search-headings))
6915 (org-goto-selected-point org-goto-exit-command)
6916 (pop-up-frames nil)
6917 (special-display-buffer-names nil)
6918 (special-display-regexps nil)
6919 (special-display-function nil))
6920 (save-excursion
6921 (save-window-excursion
6922 (delete-other-windows)
6923 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
6924 (org-pop-to-buffer-same-window
6925 (condition-case nil
6926 (make-indirect-buffer (current-buffer) "*org-goto*")
6927 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
6928 (with-output-to-temp-buffer "*Help*"
6929 (princ help))
6930 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
6931 (setq buffer-read-only nil)
6932 (let ((org-startup-truncated t)
6933 (org-startup-folded nil)
6934 (org-startup-align-all-tables nil))
6935 (org-mode)
6936 (org-overview))
6937 (setq buffer-read-only t)
6938 (if (and (boundp 'org-goto-start-pos)
6939 (integer-or-marker-p org-goto-start-pos))
6940 (let ((org-show-hierarchy-above t)
6941 (org-show-siblings t)
6942 (org-show-following-heading t))
6943 (goto-char org-goto-start-pos)
6944 (and (outline-invisible-p) (org-show-context)))
6945 (goto-char (point-min)))
6946 (let (org-special-ctrl-a/e) (org-beginning-of-line))
6947 (message "Select location and press RET")
6948 (use-local-map org-goto-map)
6949 (recursive-edit)
6951 (kill-buffer "*org-goto*")
6952 (cons org-goto-selected-point org-goto-exit-command)))
6954 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
6955 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
6956 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
6957 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
6959 (defun org-goto-local-search-headings (string bound noerror)
6960 "Search and make sure that any matches are in headlines."
6961 (catch 'return
6962 (while (if isearch-forward
6963 (search-forward string bound noerror)
6964 (search-backward string bound noerror))
6965 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
6966 (and (member :headline context)
6967 (not (member :tags context))))
6968 (throw 'return (point))))))
6970 (defun org-goto-local-auto-isearch ()
6971 "Start isearch."
6972 (interactive)
6973 (goto-char (point-min))
6974 (let ((keys (this-command-keys)))
6975 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
6976 (isearch-mode t)
6977 (isearch-process-search-char (string-to-char keys)))))
6979 (defun org-goto-ret (&optional arg)
6980 "Finish `org-goto' by going to the new location."
6981 (interactive "P")
6982 (setq org-goto-selected-point (point)
6983 org-goto-exit-command 'return)
6984 (throw 'exit nil))
6986 (defun org-goto-left ()
6987 "Finish `org-goto' by going to the new location."
6988 (interactive)
6989 (if (org-at-heading-p)
6990 (progn
6991 (beginning-of-line 1)
6992 (setq org-goto-selected-point (point)
6993 org-goto-exit-command 'left)
6994 (throw 'exit nil))
6995 (error "Not on a heading")))
6997 (defun org-goto-right ()
6998 "Finish `org-goto' by going to the new location."
6999 (interactive)
7000 (if (org-at-heading-p)
7001 (progn
7002 (setq org-goto-selected-point (point)
7003 org-goto-exit-command 'right)
7004 (throw 'exit nil))
7005 (error "Not on a heading")))
7007 (defun org-goto-quit ()
7008 "Finish `org-goto' without cursor motion."
7009 (interactive)
7010 (setq org-goto-selected-point nil)
7011 (setq org-goto-exit-command 'quit)
7012 (throw 'exit nil))
7014 ;;; Indirect buffer display of subtrees
7016 (defvar org-indirect-dedicated-frame nil
7017 "This is the frame being used for indirect tree display.")
7018 (defvar org-last-indirect-buffer nil)
7020 (defun org-tree-to-indirect-buffer (&optional arg)
7021 "Create indirect buffer and narrow it to current subtree.
7022 With numerical prefix ARG, go up to this level and then take that tree.
7023 If ARG is negative, go up that many levels.
7024 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7025 indirect buffer previously made with this command, to avoid proliferation of
7026 indirect buffers. However, when you call the command with a \
7027 \\[universal-argument] prefix, or
7028 when `org-indirect-buffer-display' is `new-frame', the last buffer
7029 is kept so that you can work with several indirect buffers at the same time.
7030 If `org-indirect-buffer-display' is `dedicated-frame', the \
7031 \\[universal-argument] prefix also
7032 requests that a new frame be made for the new buffer, so that the dedicated
7033 frame is not changed."
7034 (interactive "P")
7035 (let ((cbuf (current-buffer))
7036 (cwin (selected-window))
7037 (pos (point))
7038 beg end level heading ibuf)
7039 (save-excursion
7040 (org-back-to-heading t)
7041 (when (numberp arg)
7042 (setq level (org-outline-level))
7043 (if (< arg 0) (setq arg (+ level arg)))
7044 (while (> (setq level (org-outline-level)) arg)
7045 (outline-up-heading 1 t)))
7046 (setq beg (point)
7047 heading (org-get-heading))
7048 (org-end-of-subtree t t)
7049 (if (org-at-heading-p) (backward-char 1))
7050 (setq end (point)))
7051 (if (and (buffer-live-p org-last-indirect-buffer)
7052 (not (eq org-indirect-buffer-display 'new-frame))
7053 (not arg))
7054 (kill-buffer org-last-indirect-buffer))
7055 (setq ibuf (org-get-indirect-buffer cbuf)
7056 org-last-indirect-buffer ibuf)
7057 (cond
7058 ((or (eq org-indirect-buffer-display 'new-frame)
7059 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7060 (select-frame (make-frame))
7061 (delete-other-windows)
7062 (org-pop-to-buffer-same-window ibuf)
7063 (org-set-frame-title heading))
7064 ((eq org-indirect-buffer-display 'dedicated-frame)
7065 (raise-frame
7066 (select-frame (or (and org-indirect-dedicated-frame
7067 (frame-live-p org-indirect-dedicated-frame)
7068 org-indirect-dedicated-frame)
7069 (setq org-indirect-dedicated-frame (make-frame)))))
7070 (delete-other-windows)
7071 (org-pop-to-buffer-same-window ibuf)
7072 (org-set-frame-title (concat "Indirect: " heading)))
7073 ((eq org-indirect-buffer-display 'current-window)
7074 (org-pop-to-buffer-same-window ibuf))
7075 ((eq org-indirect-buffer-display 'other-window)
7076 (pop-to-buffer ibuf))
7077 (t (error "Invalid value")))
7078 (if (featurep 'xemacs)
7079 (save-excursion (org-mode) (turn-on-font-lock)))
7080 (narrow-to-region beg end)
7081 (show-all)
7082 (goto-char pos)
7083 (run-hook-with-args 'org-cycle-hook 'all)
7084 (and (window-live-p cwin) (select-window cwin))))
7086 (defun org-get-indirect-buffer (&optional buffer)
7087 (setq buffer (or buffer (current-buffer)))
7088 (let ((n 1) (base (buffer-name buffer)) bname)
7089 (while (buffer-live-p
7090 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7091 (setq n (1+ n)))
7092 (condition-case nil
7093 (make-indirect-buffer buffer bname 'clone)
7094 (error (make-indirect-buffer buffer bname)))))
7096 (defun org-set-frame-title (title)
7097 "Set the title of the current frame to the string TITLE."
7098 ;; FIXME: how to name a single frame in XEmacs???
7099 (unless (featurep 'xemacs)
7100 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7102 ;;;; Structure editing
7104 ;;; Inserting headlines
7106 (defun org-previous-line-empty-p ()
7107 (save-excursion
7108 (and (not (bobp))
7109 (or (beginning-of-line 0) t)
7110 (save-match-data
7111 (looking-at "[ \t]*$")))))
7113 (defun org-insert-heading (&optional force-heading invisible-ok)
7114 "Insert a new heading or item with same depth at point.
7115 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
7116 If point is at the beginning of a headline, insert a sibling before the
7117 current headline. If point is not at the beginning, split the line,
7118 create the new headline with the text in the current line after point
7119 \(but see also the variable `org-M-RET-may-split-line').
7121 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7122 This is important for non-interactive uses of the command."
7123 (interactive "P")
7124 (if (or (= (buffer-size) 0)
7125 (and (not (save-excursion
7126 (and (ignore-errors (org-back-to-heading invisible-ok))
7127 (org-at-heading-p))))
7128 (or force-heading (not (org-in-item-p)))))
7129 (progn
7130 (insert "\n* ")
7131 (run-hooks 'org-insert-heading-hook))
7132 (when (or force-heading (not (org-insert-item)))
7133 (let* ((empty-line-p nil)
7134 (level nil)
7135 (on-heading (org-at-heading-p))
7136 (head (save-excursion
7137 (condition-case nil
7138 (progn
7139 (org-back-to-heading invisible-ok)
7140 (when (and (not on-heading)
7141 (featurep 'org-inlinetask)
7142 (integerp org-inlinetask-min-level)
7143 (>= (length (match-string 0))
7144 org-inlinetask-min-level))
7145 ;; Find a heading level before the inline task
7146 (while (and (setq level (org-up-heading-safe))
7147 (>= level org-inlinetask-min-level)))
7148 (if (org-at-heading-p)
7149 (org-back-to-heading invisible-ok)
7150 (error "This should not happen")))
7151 (setq empty-line-p (org-previous-line-empty-p))
7152 (match-string 0))
7153 (error "*"))))
7154 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7155 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7156 pos hide-previous previous-pos)
7157 (cond
7158 ((and (org-at-heading-p) (bolp)
7159 (or (bobp)
7160 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
7161 ;; insert before the current line
7162 (open-line (if blank 2 1)))
7163 ((and (bolp)
7164 (not org-insert-heading-respect-content)
7165 (or (bobp)
7166 (save-excursion
7167 (backward-char 1) (not (outline-invisible-p)))))
7168 ;; insert right here
7169 nil)
7171 ;; somewhere in the line
7172 (save-excursion
7173 (setq previous-pos (point-at-bol))
7174 (end-of-line)
7175 (setq hide-previous (outline-invisible-p)))
7176 (and org-insert-heading-respect-content (org-show-subtree))
7177 (let ((split
7178 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
7179 (save-excursion
7180 (let ((p (point)))
7181 (goto-char (point-at-bol))
7182 (and (looking-at org-complex-heading-regexp)
7183 (match-beginning 4)
7184 (> p (match-beginning 4)))))))
7185 tags pos)
7186 (cond
7187 (org-insert-heading-respect-content
7188 (org-end-of-subtree nil t)
7189 (when (featurep 'org-inlinetask)
7190 (while (and (not (eobp))
7191 (looking-at "\\(\\*+\\)[ \t]+")
7192 (>= (length (match-string 1))
7193 org-inlinetask-min-level))
7194 (org-end-of-subtree nil t)))
7195 (or (bolp) (newline))
7196 (or (org-previous-line-empty-p)
7197 (and blank (newline)))
7198 (open-line 1))
7199 ((org-at-heading-p)
7200 (when hide-previous
7201 (show-children)
7202 (org-show-entry))
7203 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7204 (setq tags (and (match-end 2) (match-string 2)))
7205 (and (match-end 1)
7206 (delete-region (match-beginning 1) (match-end 1)))
7207 (setq pos (point-at-bol))
7208 (or split (end-of-line 1))
7209 (delete-horizontal-space)
7210 (if (string-match "\\`\\*+\\'"
7211 (buffer-substring (point-at-bol) (point)))
7212 (insert " "))
7213 (newline (if blank 2 1))
7214 (when tags
7215 (save-excursion
7216 (goto-char pos)
7217 (end-of-line 1)
7218 (insert " " tags)
7219 (org-set-tags nil 'align))))
7221 (or split (end-of-line 1))
7222 (newline (if blank 2 1)))))))
7223 (insert head) (just-one-space)
7224 (setq pos (point))
7225 (end-of-line 1)
7226 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7227 (when (and org-insert-heading-respect-content hide-previous)
7228 (save-excursion
7229 (goto-char previous-pos)
7230 (hide-subtree)))
7231 (run-hooks 'org-insert-heading-hook)))))
7233 (defun org-get-heading (&optional no-tags no-todo)
7234 "Return the heading of the current entry, without the stars.
7235 When NO-TAGS is non-nil, don't include tags.
7236 When NO-TODO is non-nil, don't include TODO keywords."
7237 (save-excursion
7238 (org-back-to-heading t)
7239 (cond
7240 ((and no-tags no-todo)
7241 (looking-at org-complex-heading-regexp)
7242 (match-string 4))
7243 (no-tags
7244 (looking-at (concat org-outline-regexp
7245 "\\(.*?\\)"
7246 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7247 (match-string 1))
7248 (no-todo
7249 (looking-at org-todo-line-regexp)
7250 (match-string 3))
7251 (t (looking-at org-heading-regexp)
7252 (match-string 2)))))
7254 (defun org-heading-components ()
7255 "Return the components of the current heading.
7256 This is a list with the following elements:
7257 - the level as an integer
7258 - the reduced level, different if `org-odd-levels-only' is set.
7259 - the TODO keyword, or nil
7260 - the priority character, like ?A, or nil if no priority is given
7261 - the headline text itself, or the tags string if no headline text
7262 - the tags string, or nil."
7263 (save-excursion
7264 (org-back-to-heading t)
7265 (if (let (case-fold-search) (looking-at org-complex-heading-regexp))
7266 (list (length (match-string 1))
7267 (org-reduced-level (length (match-string 1)))
7268 (org-match-string-no-properties 2)
7269 (and (match-end 3) (aref (match-string 3) 2))
7270 (org-match-string-no-properties 4)
7271 (org-match-string-no-properties 5)))))
7273 (defun org-get-entry ()
7274 "Get the entry text, after heading, entire subtree."
7275 (save-excursion
7276 (org-back-to-heading t)
7277 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7279 (defun org-insert-heading-after-current ()
7280 "Insert a new heading with same level as current, after current subtree."
7281 (interactive)
7282 (org-back-to-heading)
7283 (org-insert-heading)
7284 (org-move-subtree-down)
7285 (end-of-line 1))
7287 (defun org-insert-heading-respect-content ()
7288 (interactive)
7289 (let ((org-insert-heading-respect-content t))
7290 (org-insert-heading t)))
7292 (defun org-insert-todo-heading-respect-content (&optional force-state)
7293 (interactive "P")
7294 (let ((org-insert-heading-respect-content t))
7295 (org-insert-todo-heading force-state t)))
7297 (defun org-insert-todo-heading (arg &optional force-heading)
7298 "Insert a new heading with the same level and TODO state as current heading.
7299 If the heading has no TODO state, or if the state is DONE, use the first
7300 state (TODO by default). Also with prefix arg, force first state."
7301 (interactive "P")
7302 (when (or force-heading (not (org-insert-item 'checkbox)))
7303 (org-insert-heading force-heading)
7304 (save-excursion
7305 (org-back-to-heading)
7306 (outline-previous-heading)
7307 (looking-at org-todo-line-regexp))
7308 (let*
7309 ((new-mark-x
7310 (if (or arg
7311 (not (match-beginning 2))
7312 (member (match-string 2) org-done-keywords))
7313 (car org-todo-keywords-1)
7314 (match-string 2)))
7315 (new-mark
7317 (run-hook-with-args-until-success
7318 'org-todo-get-default-hook new-mark-x nil)
7319 new-mark-x)))
7320 (beginning-of-line 1)
7321 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7322 (if org-treat-insert-todo-heading-as-state-change
7323 (org-todo new-mark)
7324 (insert new-mark " "))))
7325 (when org-provide-todo-statistics
7326 (org-update-parent-todo-statistics))))
7328 (defun org-insert-subheading (arg)
7329 "Insert a new subheading and demote it.
7330 Works for outline headings and for plain lists alike."
7331 (interactive "P")
7332 (org-insert-heading arg)
7333 (cond
7334 ((org-at-heading-p) (org-do-demote))
7335 ((org-at-item-p) (org-indent-item))))
7337 (defun org-insert-todo-subheading (arg)
7338 "Insert a new subheading with TODO keyword or checkbox and demote it.
7339 Works for outline headings and for plain lists alike."
7340 (interactive "P")
7341 (org-insert-todo-heading arg)
7342 (cond
7343 ((org-at-heading-p) (org-do-demote))
7344 ((org-at-item-p) (org-indent-item))))
7346 ;;; Promotion and Demotion
7348 (defvar org-after-demote-entry-hook nil
7349 "Hook run after an entry has been demoted.
7350 The cursor will be at the beginning of the entry.
7351 When a subtree is being demoted, the hook will be called for each node.")
7353 (defvar org-after-promote-entry-hook nil
7354 "Hook run after an entry has been promoted.
7355 The cursor will be at the beginning of the entry.
7356 When a subtree is being promoted, the hook will be called for each node.")
7358 (defun org-promote-subtree ()
7359 "Promote the entire subtree.
7360 See also `org-promote'."
7361 (interactive)
7362 (save-excursion
7363 (org-with-limited-levels (org-map-tree 'org-promote)))
7364 (org-fix-position-after-promote))
7366 (defun org-demote-subtree ()
7367 "Demote the entire subtree. See `org-demote'.
7368 See also `org-promote'."
7369 (interactive)
7370 (save-excursion
7371 (org-with-limited-levels (org-map-tree 'org-demote)))
7372 (org-fix-position-after-promote))
7375 (defun org-do-promote ()
7376 "Promote the current heading higher up the tree.
7377 If the region is active in `transient-mark-mode', promote all headings
7378 in the region."
7379 (interactive)
7380 (save-excursion
7381 (if (org-region-active-p)
7382 (org-map-region 'org-promote (region-beginning) (region-end))
7383 (org-promote)))
7384 (org-fix-position-after-promote))
7386 (defun org-do-demote ()
7387 "Demote the current heading lower down the tree.
7388 If the region is active in `transient-mark-mode', demote all headings
7389 in the region."
7390 (interactive)
7391 (save-excursion
7392 (if (org-region-active-p)
7393 (org-map-region 'org-demote (region-beginning) (region-end))
7394 (org-demote)))
7395 (org-fix-position-after-promote))
7397 (defun org-fix-position-after-promote ()
7398 "Make sure that after pro/demotion cursor position is right."
7399 (let ((pos (point)))
7400 (when (save-excursion
7401 (beginning-of-line 1)
7402 (looking-at org-todo-line-regexp)
7403 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7404 (cond ((eobp) (insert " "))
7405 ((eolp) (insert " "))
7406 ((equal (char-after) ?\ ) (forward-char 1))))))
7408 (defun org-current-level ()
7409 "Return the level of the current entry, or nil if before the first headline.
7410 The level is the number of stars at the beginning of the headline."
7411 (save-excursion
7412 (org-with-limited-levels
7413 (if (ignore-errors (org-back-to-heading t))
7414 (funcall outline-level)))))
7416 (defun org-get-previous-line-level ()
7417 "Return the outline depth of the last headline before the current line.
7418 Returns 0 for the first headline in the buffer, and nil if before the
7419 first headline."
7420 (let ((current-level (org-current-level))
7421 (prev-level (when (> (line-number-at-pos) 1)
7422 (save-excursion
7423 (beginning-of-line 0)
7424 (org-current-level)))))
7425 (cond ((null current-level) nil) ; Before first headline
7426 ((null prev-level) 0) ; At first headline
7427 (prev-level))))
7429 (defun org-reduced-level (l)
7430 "Compute the effective level of a heading.
7431 This takes into account the setting of `org-odd-levels-only'."
7432 (cond
7433 ((zerop l) 0)
7434 (org-odd-levels-only (1+ (floor (/ l 2))))
7435 (t l)))
7437 (defun org-level-increment ()
7438 "Return the number of stars that will be added or removed at a
7439 time to headlines when structure editing, based on the value of
7440 `org-odd-levels-only'."
7441 (if org-odd-levels-only 2 1))
7443 (defun org-get-valid-level (level &optional change)
7444 "Rectify a level change under the influence of `org-odd-levels-only'
7445 LEVEL is a current level, CHANGE is by how much the level should be
7446 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7447 even level numbers will become the next higher odd number."
7448 (if org-odd-levels-only
7449 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7450 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7451 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7452 (max 1 (+ level (or change 0)))))
7454 (if (boundp 'define-obsolete-function-alias)
7455 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7456 (define-obsolete-function-alias 'org-get-legal-level
7457 'org-get-valid-level)
7458 (define-obsolete-function-alias 'org-get-legal-level
7459 'org-get-valid-level "23.1")))
7461 (defun org-promote ()
7462 "Promote the current heading higher up the tree.
7463 If the region is active in `transient-mark-mode', promote all headings
7464 in the region."
7465 (org-back-to-heading t)
7466 (let* ((level (save-match-data (funcall outline-level)))
7467 (after-change-functions (remove 'flyspell-after-change-function
7468 after-change-functions))
7469 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7470 (diff (abs (- level (length up-head) -1))))
7471 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
7472 (replace-match up-head nil t)
7473 ;; Fixup tag positioning
7474 (and org-auto-align-tags (org-set-tags nil t))
7475 (if org-adapt-indentation (org-fixup-indentation (- diff)))
7476 (run-hooks 'org-after-promote-entry-hook)))
7478 (defun org-demote ()
7479 "Demote the current heading lower down the tree.
7480 If the region is active in `transient-mark-mode', demote all headings
7481 in the region."
7482 (org-back-to-heading t)
7483 (let* ((level (save-match-data (funcall outline-level)))
7484 (after-change-functions (remove 'flyspell-after-change-function
7485 after-change-functions))
7486 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7487 (diff (abs (- level (length down-head) -1))))
7488 (replace-match down-head nil t)
7489 ;; Fixup tag positioning
7490 (and org-auto-align-tags (org-set-tags nil t))
7491 (if org-adapt-indentation (org-fixup-indentation diff))
7492 (run-hooks 'org-after-demote-entry-hook)))
7494 (defun org-cycle-level ()
7495 "Cycle the level of an empty headline through possible states.
7496 This goes first to child, then to parent, level, then up the hierarchy.
7497 After top level, it switches back to sibling level."
7498 (interactive)
7499 (let ((org-adapt-indentation nil))
7500 (when (org-point-at-end-of-empty-headline)
7501 (setq this-command 'org-cycle-level) ; Only needed for caching
7502 (let ((cur-level (org-current-level))
7503 (prev-level (org-get-previous-line-level)))
7504 (cond
7505 ;; If first headline in file, promote to top-level.
7506 ((= prev-level 0)
7507 (loop repeat (/ (- cur-level 1) (org-level-increment))
7508 do (org-do-promote)))
7509 ;; If same level as prev, demote one.
7510 ((= prev-level cur-level)
7511 (org-do-demote))
7512 ;; If parent is top-level, promote to top level if not already.
7513 ((= prev-level 1)
7514 (loop repeat (/ (- cur-level 1) (org-level-increment))
7515 do (org-do-promote)))
7516 ;; If top-level, return to prev-level.
7517 ((= cur-level 1)
7518 (loop repeat (/ (- prev-level 1) (org-level-increment))
7519 do (org-do-demote)))
7520 ;; If less than prev-level, promote one.
7521 ((< cur-level prev-level)
7522 (org-do-promote))
7523 ;; If deeper than prev-level, promote until higher than
7524 ;; prev-level.
7525 ((> cur-level prev-level)
7526 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7527 do (org-do-promote))))
7528 t))))
7530 (defun org-map-tree (fun)
7531 "Call FUN for every heading underneath the current one."
7532 (org-back-to-heading)
7533 (let ((level (funcall outline-level)))
7534 (save-excursion
7535 (funcall fun)
7536 (while (and (progn
7537 (outline-next-heading)
7538 (> (funcall outline-level) level))
7539 (not (eobp)))
7540 (funcall fun)))))
7542 (defun org-map-region (fun beg end)
7543 "Call FUN for every heading between BEG and END."
7544 (let ((org-ignore-region t))
7545 (save-excursion
7546 (setq end (copy-marker end))
7547 (goto-char beg)
7548 (if (and (re-search-forward org-outline-regexp-bol nil t)
7549 (< (point) end))
7550 (funcall fun))
7551 (while (and (progn
7552 (outline-next-heading)
7553 (< (point) end))
7554 (not (eobp)))
7555 (funcall fun)))))
7557 (defvar org-property-end-re) ; silence byte-compiler
7558 (defun org-fixup-indentation (diff)
7559 "Change the indentation in the current entry by DIFF.
7560 However, if any line in the current entry has no indentation, or if it
7561 would end up with no indentation after the change, nothing at all is done."
7562 (save-excursion
7563 (let ((end (save-excursion (outline-next-heading)
7564 (point-marker)))
7565 (prohibit (if (> diff 0)
7566 "^\\S-"
7567 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7568 col)
7569 (unless (save-excursion (end-of-line 1)
7570 (re-search-forward prohibit end t))
7571 (while (and (< (point) end)
7572 (re-search-forward "^[ \t]+" end t))
7573 (goto-char (match-end 0))
7574 (setq col (current-column))
7575 (if (< diff 0) (replace-match ""))
7576 (org-indent-to-column (+ diff col))))
7577 (move-marker end nil))))
7579 (defun org-convert-to-odd-levels ()
7580 "Convert an org-mode file with all levels allowed to one with odd levels.
7581 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7582 level 5 etc."
7583 (interactive)
7584 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7585 (let ((outline-level 'org-outline-level)
7586 (org-odd-levels-only nil) n)
7587 (save-excursion
7588 (goto-char (point-min))
7589 (while (re-search-forward "^\\*\\*+ " nil t)
7590 (setq n (- (length (match-string 0)) 2))
7591 (while (>= (setq n (1- n)) 0)
7592 (org-demote))
7593 (end-of-line 1))))))
7595 (defun org-convert-to-oddeven-levels ()
7596 "Convert an org-mode file with only odd levels to one with odd/even levels.
7597 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7598 file contains a section with an even level, conversion would
7599 destroy the structure of the file. An error is signaled in this
7600 case."
7601 (interactive)
7602 (goto-char (point-min))
7603 ;; First check if there are no even levels
7604 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7605 (org-show-context t)
7606 (error "Not all levels are odd in this file. Conversion not possible"))
7607 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
7608 (let ((outline-regexp org-outline-regexp)
7609 (outline-level 'org-outline-level)
7610 (org-odd-levels-only nil) n)
7611 (save-excursion
7612 (goto-char (point-min))
7613 (while (re-search-forward "^\\*\\*+ " nil t)
7614 (setq n (/ (1- (length (match-string 0))) 2))
7615 (while (>= (setq n (1- n)) 0)
7616 (org-promote))
7617 (end-of-line 1))))))
7619 (defun org-tr-level (n)
7620 "Make N odd if required."
7621 (if org-odd-levels-only (1+ (/ n 2)) n))
7623 ;;; Vertical tree motion, cutting and pasting of subtrees
7625 (defun org-move-subtree-up (&optional arg)
7626 "Move the current subtree up past ARG headlines of the same level."
7627 (interactive "p")
7628 (org-move-subtree-down (- (prefix-numeric-value arg))))
7630 (defun org-move-subtree-down (&optional arg)
7631 "Move the current subtree down past ARG headlines of the same level."
7632 (interactive "p")
7633 (setq arg (prefix-numeric-value arg))
7634 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
7635 'org-get-last-sibling))
7636 (ins-point (make-marker))
7637 (cnt (abs arg))
7638 (col (current-column))
7639 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
7640 ;; Select the tree
7641 (org-back-to-heading)
7642 (setq beg0 (point))
7643 (save-excursion
7644 (setq ne-beg (org-back-over-empty-lines))
7645 (setq beg (point)))
7646 (save-match-data
7647 (save-excursion (outline-end-of-heading)
7648 (setq folded (outline-invisible-p)))
7649 (outline-end-of-subtree))
7650 (outline-next-heading)
7651 (setq ne-end (org-back-over-empty-lines))
7652 (setq end (point))
7653 (goto-char beg0)
7654 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
7655 ;; include less whitespace
7656 (save-excursion
7657 (goto-char beg)
7658 (forward-line (- ne-beg ne-end))
7659 (setq beg (point))))
7660 ;; Find insertion point, with error handling
7661 (while (> cnt 0)
7662 (or (and (funcall movfunc) (looking-at org-outline-regexp))
7663 (progn (goto-char beg0)
7664 (error "Cannot move past superior level or buffer limit")))
7665 (setq cnt (1- cnt)))
7666 (if (> arg 0)
7667 ;; Moving forward - still need to move over subtree
7668 (progn (org-end-of-subtree t t)
7669 (save-excursion
7670 (org-back-over-empty-lines)
7671 (or (bolp) (newline)))))
7672 (setq ne-ins (org-back-over-empty-lines))
7673 (move-marker ins-point (point))
7674 (setq txt (buffer-substring beg end))
7675 (org-save-markers-in-region beg end)
7676 (delete-region beg end)
7677 (org-remove-empty-overlays-at beg)
7678 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
7679 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
7680 (and (not (bolp)) (looking-at "\n") (forward-char 1))
7681 (let ((bbb (point)))
7682 (insert-before-markers txt)
7683 (org-reinstall-markers-in-region bbb)
7684 (move-marker ins-point bbb))
7685 (or (bolp) (insert "\n"))
7686 (setq ins-end (point))
7687 (goto-char ins-point)
7688 (org-skip-whitespace)
7689 (when (and (< arg 0)
7690 (org-first-sibling-p)
7691 (> ne-ins ne-beg))
7692 ;; Move whitespace back to beginning
7693 (save-excursion
7694 (goto-char ins-end)
7695 (let ((kill-whole-line t))
7696 (kill-line (- ne-ins ne-beg)) (point)))
7697 (insert (make-string (- ne-ins ne-beg) ?\n)))
7698 (move-marker ins-point nil)
7699 (if folded
7700 (hide-subtree)
7701 (org-show-entry)
7702 (show-children)
7703 (org-cycle-hide-drawers 'children))
7704 (org-clean-visibility-after-subtree-move)
7705 ;; move back to the initial column we were at
7706 (move-to-column col)))
7708 (defvar org-subtree-clip ""
7709 "Clipboard for cut and paste of subtrees.
7710 This is actually only a copy of the kill, because we use the normal kill
7711 ring. We need it to check if the kill was created by `org-copy-subtree'.")
7713 (defvar org-subtree-clip-folded nil
7714 "Was the last copied subtree folded?
7715 This is used to fold the tree back after pasting.")
7717 (defun org-cut-subtree (&optional n)
7718 "Cut the current subtree into the clipboard.
7719 With prefix arg N, cut this many sequential subtrees.
7720 This is a short-hand for marking the subtree and then cutting it."
7721 (interactive "p")
7722 (org-copy-subtree n 'cut))
7724 (defun org-copy-subtree (&optional n cut force-store-markers)
7725 "Cut the current subtree into the clipboard.
7726 With prefix arg N, cut this many sequential subtrees.
7727 This is a short-hand for marking the subtree and then copying it.
7728 If CUT is non-nil, actually cut the subtree.
7729 If FORCE-STORE-MARKERS is non-nil, store the relative locations
7730 of some markers in the region, even if CUT is non-nil. This is
7731 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
7732 (interactive "p")
7733 (let (beg end folded (beg0 (point)))
7734 (if (org-called-interactively-p 'any)
7735 (org-back-to-heading nil) ; take what looks like a subtree
7736 (org-back-to-heading t)) ; take what is really there
7737 (org-back-over-empty-lines)
7738 (setq beg (point))
7739 (skip-chars-forward " \t\r\n")
7740 (save-match-data
7741 (save-excursion (outline-end-of-heading)
7742 (setq folded (outline-invisible-p)))
7743 (condition-case nil
7744 (org-forward-same-level (1- n) t)
7745 (error nil))
7746 (org-end-of-subtree t t))
7747 (org-back-over-empty-lines)
7748 (setq end (point))
7749 (goto-char beg0)
7750 (when (> end beg)
7751 (setq org-subtree-clip-folded folded)
7752 (when (or cut force-store-markers)
7753 (org-save-markers-in-region beg end))
7754 (if cut (kill-region beg end) (copy-region-as-kill beg end))
7755 (setq org-subtree-clip (current-kill 0))
7756 (message "%s: Subtree(s) with %d characters"
7757 (if cut "Cut" "Copied")
7758 (length org-subtree-clip)))))
7760 (defun org-paste-subtree (&optional level tree for-yank)
7761 "Paste the clipboard as a subtree, with modification of headline level.
7762 The entire subtree is promoted or demoted in order to match a new headline
7763 level.
7765 If the cursor is at the beginning of a headline, the same level as
7766 that headline is used to paste the tree
7768 If not, the new level is derived from the *visible* headings
7769 before and after the insertion point, and taken to be the inferior headline
7770 level of the two. So if the previous visible heading is level 3 and the
7771 next is level 4 (or vice versa), level 4 will be used for insertion.
7772 This makes sure that the subtree remains an independent subtree and does
7773 not swallow low level entries.
7775 You can also force a different level, either by using a numeric prefix
7776 argument, or by inserting the heading marker by hand. For example, if the
7777 cursor is after \"*****\", then the tree will be shifted to level 5.
7779 If optional TREE is given, use this text instead of the kill ring.
7781 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
7782 move back over whitespace before inserting, and move point to the end of
7783 the inserted text when done."
7784 (interactive "P")
7785 (setq tree (or tree (and kill-ring (current-kill 0))))
7786 (unless (org-kill-is-subtree-p tree)
7787 (error "%s"
7788 (substitute-command-keys
7789 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
7790 (org-with-limited-levels
7791 (let* ((visp (not (outline-invisible-p)))
7792 (txt tree)
7793 (^re_ "\\(\\*+\\)[ \t]*")
7794 (old-level (if (string-match org-outline-regexp-bol txt)
7795 (- (match-end 0) (match-beginning 0) 1)
7796 -1))
7797 (force-level (cond (level (prefix-numeric-value level))
7798 ((and (looking-at "[ \t]*$")
7799 (string-match
7800 "^\\*+$" (buffer-substring
7801 (point-at-bol) (point))))
7802 (- (match-end 1) (match-beginning 1)))
7803 ((and (bolp)
7804 (looking-at org-outline-regexp))
7805 (- (match-end 0) (point) 1))
7806 (t nil)))
7807 (previous-level (save-excursion
7808 (condition-case nil
7809 (progn
7810 (outline-previous-visible-heading 1)
7811 (if (looking-at ^re_)
7812 (- (match-end 0) (match-beginning 0) 1)
7814 (error 1))))
7815 (next-level (save-excursion
7816 (condition-case nil
7817 (progn
7818 (or (looking-at org-outline-regexp)
7819 (outline-next-visible-heading 1))
7820 (if (looking-at ^re_)
7821 (- (match-end 0) (match-beginning 0) 1)
7823 (error 1))))
7824 (new-level (or force-level (max previous-level next-level)))
7825 (shift (if (or (= old-level -1)
7826 (= new-level -1)
7827 (= old-level new-level))
7829 (- new-level old-level)))
7830 (delta (if (> shift 0) -1 1))
7831 (func (if (> shift 0) 'org-demote 'org-promote))
7832 (org-odd-levels-only nil)
7833 beg end newend)
7834 ;; Remove the forced level indicator
7835 (if force-level
7836 (delete-region (point-at-bol) (point)))
7837 ;; Paste
7838 (beginning-of-line (if (bolp) 1 2))
7839 (unless for-yank (org-back-over-empty-lines))
7840 (setq beg (point))
7841 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
7842 (insert-before-markers txt)
7843 (unless (string-match "\n\\'" txt) (insert "\n"))
7844 (setq newend (point))
7845 (org-reinstall-markers-in-region beg)
7846 (setq end (point))
7847 (goto-char beg)
7848 (skip-chars-forward " \t\n\r")
7849 (setq beg (point))
7850 (if (and (outline-invisible-p) visp)
7851 (save-excursion (outline-show-heading)))
7852 ;; Shift if necessary
7853 (unless (= shift 0)
7854 (save-restriction
7855 (narrow-to-region beg end)
7856 (while (not (= shift 0))
7857 (org-map-region func (point-min) (point-max))
7858 (setq shift (+ delta shift)))
7859 (goto-char (point-min))
7860 (setq newend (point-max))))
7861 (when (or (org-called-interactively-p 'interactive) for-yank)
7862 (message "Clipboard pasted as level %d subtree" new-level))
7863 (if (and (not for-yank) ; in this case, org-yank will decide about folding
7864 kill-ring
7865 (eq org-subtree-clip (current-kill 0))
7866 org-subtree-clip-folded)
7867 ;; The tree was folded before it was killed/copied
7868 (hide-subtree))
7869 (and for-yank (goto-char newend)))))
7871 (defun org-kill-is-subtree-p (&optional txt)
7872 "Check if the current kill is an outline subtree, or a set of trees.
7873 Returns nil if kill does not start with a headline, or if the first
7874 headline level is not the largest headline level in the tree.
7875 So this will actually accept several entries of equal levels as well,
7876 which is OK for `org-paste-subtree'.
7877 If optional TXT is given, check this string instead of the current kill."
7878 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
7879 (re (org-get-limited-outline-regexp))
7880 (^re (concat "^" re))
7881 (start-level (and kill
7882 (string-match
7883 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
7884 kill)
7885 (- (match-end 2) (match-beginning 2) 1)))
7886 (start (1+ (or (match-beginning 2) -1))))
7887 (if (not start-level)
7888 (progn
7889 nil) ;; does not even start with a heading
7890 (catch 'exit
7891 (while (setq start (string-match ^re kill (1+ start)))
7892 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
7893 (throw 'exit nil)))
7894 t))))
7896 (defvar org-markers-to-move nil
7897 "Markers that should be moved with a cut-and-paste operation.
7898 Those markers are stored together with their positions relative to
7899 the start of the region.")
7901 (defun org-save-markers-in-region (beg end)
7902 "Check markers in region.
7903 If these markers are between BEG and END, record their position relative
7904 to BEG, so that after moving the block of text, we can put the markers back
7905 into place.
7906 This function gets called just before an entry or tree gets cut from the
7907 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
7908 called immediately, to move the markers with the entries."
7909 (setq org-markers-to-move nil)
7910 (when (featurep 'org-clock)
7911 (org-clock-save-markers-for-cut-and-paste beg end))
7912 (when (featurep 'org-agenda)
7913 (org-agenda-save-markers-for-cut-and-paste beg end)))
7915 (defun org-check-and-save-marker (marker beg end)
7916 "Check if MARKER is between BEG and END.
7917 If yes, remember the marker and the distance to BEG."
7918 (when (and (marker-buffer marker)
7919 (equal (marker-buffer marker) (current-buffer)))
7920 (if (and (>= marker beg) (< marker end))
7921 (push (cons marker (- marker beg)) org-markers-to-move))))
7923 (defun org-reinstall-markers-in-region (beg)
7924 "Move all remembered markers to their position relative to BEG."
7925 (mapc (lambda (x)
7926 (move-marker (car x) (+ beg (cdr x))))
7927 org-markers-to-move)
7928 (setq org-markers-to-move nil))
7930 (defun org-narrow-to-subtree ()
7931 "Narrow buffer to the current subtree."
7932 (interactive)
7933 (save-excursion
7934 (save-match-data
7935 (org-with-limited-levels
7936 (narrow-to-region
7937 (progn (org-back-to-heading t) (point))
7938 (progn (org-end-of-subtree t t)
7939 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
7940 (point)))))))
7942 (defun org-narrow-to-block ()
7943 "Narrow buffer to the current block."
7944 (interactive)
7945 (let* ((case-fold-search t)
7946 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
7947 "^[ \t]*#\\+end_.*")))
7948 (if blockp
7949 (narrow-to-region (car blockp) (cdr blockp))
7950 (error "Not in a block"))))
7952 (eval-when-compile
7953 (defvar org-property-drawer-re))
7955 (defvar org-property-start-re) ;; defined below
7956 (defun org-clone-subtree-with-time-shift (n &optional shift)
7957 "Clone the task (subtree) at point N times.
7958 The clones will be inserted as siblings.
7960 In interactive use, the user will be prompted for the number of
7961 clones to be produced, and for a time SHIFT, which may be a
7962 repeater as used in time stamps, for example `+3d'.
7964 When a valid repeater is given and the entry contains any time
7965 stamps, the clones will become a sequence in time, with time
7966 stamps in the subtree shifted for each clone produced. If SHIFT
7967 is nil or the empty string, time stamps will be left alone. The
7968 ID property of the original subtree is removed.
7970 If the original subtree did contain time stamps with a repeater,
7971 the following will happen:
7972 - the repeater will be removed in each clone
7973 - an additional clone will be produced, with the current, unshifted
7974 date(s) in the entry.
7975 - the original entry will be placed *after* all the clones, with
7976 repeater intact.
7977 - the start days in the repeater in the original entry will be shifted
7978 to past the last clone.
7979 In this way you can spell out a number of instances of a repeating task,
7980 and still retain the repeater to cover future instances of the task."
7981 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
7982 (let (beg end template task idprop
7983 shift-n shift-what doshift nmin nmax (n-no-remove -1)
7984 (drawer-re org-drawer-regexp))
7985 (if (not (and (integerp n) (> n 0)))
7986 (error "Invalid number of replications %s" n))
7987 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
7988 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
7989 shift)))
7990 (error "Invalid shift specification %s" shift))
7991 (when doshift
7992 (setq shift-n (string-to-number (match-string 1 shift))
7993 shift-what (cdr (assoc (match-string 2 shift)
7994 '(("d" . day) ("w" . week)
7995 ("m" . month) ("y" . year))))))
7996 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
7997 (setq nmin 1 nmax n)
7998 (org-back-to-heading t)
7999 (setq beg (point))
8000 (setq idprop (org-entry-get nil "ID"))
8001 (org-end-of-subtree t t)
8002 (or (bolp) (insert "\n"))
8003 (setq end (point))
8004 (setq template (buffer-substring beg end))
8005 (when (and doshift
8006 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8007 (delete-region beg end)
8008 (setq end beg)
8009 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8010 (goto-char end)
8011 (loop for n from nmin to nmax do
8012 ;; prepare clone
8013 (with-temp-buffer
8014 (insert template)
8015 (org-mode)
8016 (goto-char (point-min))
8017 (org-show-subtree)
8018 (and idprop (if org-clone-delete-id
8019 (org-entry-delete nil "ID")
8020 (org-id-get-create t)))
8021 (unless (= n 0)
8022 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8023 (kill-whole-line))
8024 (goto-char (point-min))
8025 (while (re-search-forward drawer-re nil t)
8026 (mapc (lambda (d)
8027 (org-remove-empty-drawer-at d (point))) org-drawers)))
8028 (goto-char (point-min))
8029 (when doshift
8030 (while (re-search-forward org-ts-regexp-both nil t)
8031 (org-timestamp-change (* n shift-n) shift-what))
8032 (unless (= n n-no-remove)
8033 (goto-char (point-min))
8034 (while (re-search-forward org-ts-regexp nil t)
8035 (save-excursion
8036 (goto-char (match-beginning 0))
8037 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8038 (delete-region (match-beginning 1) (match-end 1)))))))
8039 (setq task (buffer-string)))
8040 (insert task))
8041 (goto-char beg)))
8043 ;;; Outline Sorting
8045 (defun org-sort (with-case)
8046 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8047 Optional argument WITH-CASE means sort case-sensitively."
8048 (interactive "P")
8049 (cond
8050 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8051 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8053 (org-call-with-arg 'org-sort-entries with-case))))
8055 (defun org-sort-remove-invisible (s)
8056 (remove-text-properties 0 (length s) org-rm-props s)
8057 (while (string-match org-bracket-link-regexp s)
8058 (setq s (replace-match (if (match-end 2)
8059 (match-string 3 s)
8060 (match-string 1 s)) t t s)))
8063 (defvar org-priority-regexp) ; defined later in the file
8065 (defvar org-after-sorting-entries-or-items-hook nil
8066 "Hook that is run after a bunch of entries or items have been sorted.
8067 When children are sorted, the cursor is in the parent line when this
8068 hook gets called. When a region or a plain list is sorted, the cursor
8069 will be in the first entry of the sorted region/list.")
8071 (defun org-sort-entries
8072 (&optional with-case sorting-type getkey-func compare-func property)
8073 "Sort entries on a certain level of an outline tree.
8074 If there is an active region, the entries in the region are sorted.
8075 Else, if the cursor is before the first entry, sort the top-level items.
8076 Else, the children of the entry at point are sorted.
8078 Sorting can be alphabetically, numerically, by date/time as given by
8079 a time stamp, by a property or by priority.
8081 The command prompts for the sorting type unless it has been given to the
8082 function through the SORTING-TYPE argument, which needs to be a character,
8083 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F). Here is the
8084 precise meaning of each character:
8086 n Numerically, by converting the beginning of the entry/item to a number.
8087 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8088 t By date/time, either the first active time stamp in the entry, or, if
8089 none exist, by the first inactive one.
8090 s By the scheduled date/time.
8091 d By deadline date/time.
8092 c By creation time, which is assumed to be the first inactive time stamp
8093 at the beginning of a line.
8094 p By priority according to the cookie.
8095 r By the value of a property.
8097 Capital letters will reverse the sort order.
8099 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8100 called with point at the beginning of the record. It must return either
8101 a string or a number that should serve as the sorting key for that record.
8103 Comparing entries ignores case by default. However, with an optional argument
8104 WITH-CASE, the sorting considers case as well."
8105 (interactive "P")
8106 (let ((case-func (if with-case 'identity 'downcase))
8107 start beg end stars re re2
8108 txt what tmp)
8109 ;; Find beginning and end of region to sort
8110 (cond
8111 ((org-region-active-p)
8112 ;; we will sort the region
8113 (setq end (region-end)
8114 what "region")
8115 (goto-char (region-beginning))
8116 (if (not (org-at-heading-p)) (outline-next-heading))
8117 (setq start (point)))
8118 ((or (org-at-heading-p)
8119 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8120 ;; we will sort the children of the current headline
8121 (org-back-to-heading)
8122 (setq start (point)
8123 end (progn (org-end-of-subtree t t)
8124 (or (bolp) (insert "\n"))
8125 (org-back-over-empty-lines)
8126 (point))
8127 what "children")
8128 (goto-char start)
8129 (show-subtree)
8130 (outline-next-heading))
8132 ;; we will sort the top-level entries in this file
8133 (goto-char (point-min))
8134 (or (org-at-heading-p) (outline-next-heading))
8135 (setq start (point))
8136 (goto-char (point-max))
8137 (beginning-of-line 1)
8138 (when (looking-at ".*?\\S-")
8139 ;; File ends in a non-white line
8140 (end-of-line 1)
8141 (insert "\n"))
8142 (setq end (point-max))
8143 (setq what "top-level")
8144 (goto-char start)
8145 (show-all)))
8147 (setq beg (point))
8148 (if (>= beg end) (error "Nothing to sort"))
8150 (looking-at "\\(\\*+\\)")
8151 (setq stars (match-string 1)
8152 re (concat "^" (regexp-quote stars) " +")
8153 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8154 txt (buffer-substring beg end))
8155 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8156 (if (and (not (equal stars "*")) (string-match re2 txt))
8157 (error "Region to sort contains a level above the first entry"))
8159 (unless sorting-type
8160 (message
8161 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8162 [t]ime [s]cheduled [d]eadline [c]reated
8163 A/N/T/S/D/C/P/O/F means reversed:"
8164 what)
8165 (setq sorting-type (read-char-exclusive))
8167 (and (= (downcase sorting-type) ?f)
8168 (setq getkey-func
8169 (org-icompleting-read "Sort using function: "
8170 obarray 'fboundp t nil nil))
8171 (setq getkey-func (intern getkey-func)))
8173 (and (= (downcase sorting-type) ?r)
8174 (setq property
8175 (org-icompleting-read "Property: "
8176 (mapcar 'list (org-buffer-property-keys t))
8177 nil t))))
8179 (message "Sorting entries...")
8181 (save-restriction
8182 (narrow-to-region start end)
8183 (let ((dcst (downcase sorting-type))
8184 (case-fold-search nil)
8185 (now (current-time)))
8186 (sort-subr
8187 (/= dcst sorting-type)
8188 ;; This function moves to the beginning character of the "record" to
8189 ;; be sorted.
8190 (lambda nil
8191 (if (re-search-forward re nil t)
8192 (goto-char (match-beginning 0))
8193 (goto-char (point-max))))
8194 ;; This function moves to the last character of the "record" being
8195 ;; sorted.
8196 (lambda nil
8197 (save-match-data
8198 (condition-case nil
8199 (outline-forward-same-level 1)
8200 (error
8201 (goto-char (point-max))))))
8202 ;; This function returns the value that gets sorted against.
8203 (lambda nil
8204 (cond
8205 ((= dcst ?n)
8206 (if (looking-at org-complex-heading-regexp)
8207 (string-to-number (match-string 4))
8208 nil))
8209 ((= dcst ?a)
8210 (if (looking-at org-complex-heading-regexp)
8211 (funcall case-func (match-string 4))
8212 nil))
8213 ((= dcst ?t)
8214 (let ((end (save-excursion (outline-next-heading) (point))))
8215 (if (or (re-search-forward org-ts-regexp end t)
8216 (re-search-forward org-ts-regexp-both end t))
8217 (org-time-string-to-seconds (match-string 0))
8218 (org-float-time now))))
8219 ((= dcst ?c)
8220 (let ((end (save-excursion (outline-next-heading) (point))))
8221 (if (re-search-forward
8222 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8223 end t)
8224 (org-time-string-to-seconds (match-string 0))
8225 (org-float-time now))))
8226 ((= dcst ?s)
8227 (let ((end (save-excursion (outline-next-heading) (point))))
8228 (if (re-search-forward org-scheduled-time-regexp end t)
8229 (org-time-string-to-seconds (match-string 1))
8230 (org-float-time now))))
8231 ((= dcst ?d)
8232 (let ((end (save-excursion (outline-next-heading) (point))))
8233 (if (re-search-forward org-deadline-time-regexp end t)
8234 (org-time-string-to-seconds (match-string 1))
8235 (org-float-time now))))
8236 ((= dcst ?p)
8237 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8238 (string-to-char (match-string 2))
8239 org-default-priority))
8240 ((= dcst ?r)
8241 (or (org-entry-get nil property) ""))
8242 ((= dcst ?o)
8243 (if (looking-at org-complex-heading-regexp)
8244 (- 9999 (length (member (match-string 2)
8245 org-todo-keywords-1)))))
8246 ((= dcst ?f)
8247 (if getkey-func
8248 (progn
8249 (setq tmp (funcall getkey-func))
8250 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8251 tmp)
8252 (error "Invalid key function `%s'" getkey-func)))
8253 (t (error "Invalid sorting type `%c'" sorting-type))))
8255 (cond
8256 ((= dcst ?a) 'string<)
8257 ((= dcst ?f) compare-func)
8258 ((member dcst '(?p ?t ?s ?d ?c)) '<)
8259 (t nil)))))
8260 (run-hooks 'org-after-sorting-entries-or-items-hook)
8261 (message "Sorting entries...done")))
8263 (defun org-do-sort (table what &optional with-case sorting-type)
8264 "Sort TABLE of WHAT according to SORTING-TYPE.
8265 The user will be prompted for the SORTING-TYPE if the call to this
8266 function does not specify it. WHAT is only for the prompt, to indicate
8267 what is being sorted. The sorting key will be extracted from
8268 the car of the elements of the table.
8269 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8270 (unless sorting-type
8271 (message
8272 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
8273 what)
8274 (setq sorting-type (read-char-exclusive)))
8275 (let ((dcst (downcase sorting-type))
8276 extractfun comparefun)
8277 ;; Define the appropriate functions
8278 (cond
8279 ((= dcst ?n)
8280 (setq extractfun 'string-to-number
8281 comparefun (if (= dcst sorting-type) '< '>)))
8282 ((= dcst ?a)
8283 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8284 (lambda(x) (downcase (org-sort-remove-invisible x))))
8285 comparefun (if (= dcst sorting-type)
8286 'string<
8287 (lambda (a b) (and (not (string< a b))
8288 (not (string= a b)))))))
8289 ((= dcst ?t)
8290 (setq extractfun
8291 (lambda (x)
8292 (if (or (string-match org-ts-regexp x)
8293 (string-match org-ts-regexp-both x))
8294 (org-float-time
8295 (org-time-string-to-time (match-string 0 x)))
8297 comparefun (if (= dcst sorting-type) '< '>)))
8298 (t (error "Invalid sorting type `%c'" sorting-type)))
8300 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8301 table)
8302 (lambda (a b) (funcall comparefun (car a) (car b))))))
8305 ;;; The orgstruct minor mode
8307 ;; Define a minor mode which can be used in other modes in order to
8308 ;; integrate the org-mode structure editing commands.
8310 ;; This is really a hack, because the org-mode structure commands use
8311 ;; keys which normally belong to the major mode. Here is how it
8312 ;; works: The minor mode defines all the keys necessary to operate the
8313 ;; structure commands, but wraps the commands into a function which
8314 ;; tests if the cursor is currently at a headline or a plain list
8315 ;; item. If that is the case, the structure command is used,
8316 ;; temporarily setting many Org-mode variables like regular
8317 ;; expressions for filling etc. However, when any of those keys is
8318 ;; used at a different location, function uses `key-binding' to look
8319 ;; up if the key has an associated command in another currently active
8320 ;; keymap (minor modes, major mode, global), and executes that
8321 ;; command. There might be problems if any of the keys is otherwise
8322 ;; used as a prefix key.
8324 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
8325 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
8326 ;; addresses this by checking explicitly for both bindings.
8328 (defvar orgstruct-mode-map (make-sparse-keymap)
8329 "Keymap for the minor `orgstruct-mode'.")
8331 (defvar org-local-vars nil
8332 "List of local variables, for use by `orgstruct-mode'.")
8334 ;;;###autoload
8335 (define-minor-mode orgstruct-mode
8336 "Toggle the minor mode `orgstruct-mode'.
8337 This mode is for using Org-mode structure commands in other
8338 modes. The following keys behave as if Org-mode were active, if
8339 the cursor is on a headline, or on a plain list item (both as
8340 defined by Org-mode).
8342 M-up Move entry/item up
8343 M-down Move entry/item down
8344 M-left Promote
8345 M-right Demote
8346 M-S-up Move entry/item up
8347 M-S-down Move entry/item down
8348 M-S-left Promote subtree
8349 M-S-right Demote subtree
8350 M-q Fill paragraph and items like in Org-mode
8351 C-c ^ Sort entries
8352 C-c - Cycle list bullet
8353 TAB Cycle item visibility
8354 M-RET Insert new heading/item
8355 S-M-RET Insert new TODO heading / Checkbox item
8356 C-c C-c Set tags / toggle checkbox"
8357 nil " OrgStruct" nil
8358 (org-load-modules-maybe)
8359 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
8361 ;;;###autoload
8362 (defun turn-on-orgstruct ()
8363 "Unconditionally turn on `orgstruct-mode'."
8364 (orgstruct-mode 1))
8366 (defun orgstruct++-mode (&optional arg)
8367 "Toggle `orgstruct-mode', the enhanced version of it.
8368 In addition to setting orgstruct-mode, this also exports all indentation
8369 and autofilling variables from org-mode into the buffer. It will also
8370 recognize item context in multiline items.
8371 Note that turning off orgstruct-mode will *not* remove the
8372 indentation/paragraph settings. This can only be done by refreshing the
8373 major mode, for example with \\[normal-mode]."
8374 (interactive "P")
8375 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1)))
8376 ;; Set fallback functions
8377 org-auto-fill-fallback-function auto-fill-function
8378 org-indent-line-fallback-function indent-line-function
8379 org-fill-paragraph-fallback-function fill-paragraph-function)
8380 (if (< arg 1)
8381 (orgstruct-mode -1)
8382 (orgstruct-mode 1)
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 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8391 org-local-vars)
8392 (org-set-local 'orgstruct-is-++ t))))
8394 (defvar orgstruct-is-++ nil
8395 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8396 (make-variable-buffer-local 'orgstruct-is-++)
8398 ;;;###autoload
8399 (defun turn-on-orgstruct++ ()
8400 "Unconditionally turn on `orgstruct++-mode'."
8401 (orgstruct++-mode 1))
8403 (defun orgstruct-error ()
8404 "Error when there is no default binding for a structure key."
8405 (interactive)
8406 (error "This key has no function outside structure elements"))
8408 (defun orgstruct-setup ()
8409 "Setup orgstruct keymaps."
8410 (let ((nfunc 0)
8411 (bindings
8412 (list
8413 '([(meta up)] org-metaup)
8414 '([(meta down)] org-metadown)
8415 '([(meta left)] org-metaleft)
8416 '([(meta right)] org-metaright)
8417 '([(meta shift up)] org-shiftmetaup)
8418 '([(meta shift down)] org-shiftmetadown)
8419 '([(meta shift left)] org-shiftmetaleft)
8420 '([(meta shift right)] org-shiftmetaright)
8421 '([?\e (up)] org-metaup)
8422 '([?\e (down)] org-metadown)
8423 '([?\e (left)] org-metaleft)
8424 '([?\e (right)] org-metaright)
8425 '([?\e (shift up)] org-shiftmetaup)
8426 '([?\e (shift down)] org-shiftmetadown)
8427 '([?\e (shift left)] org-shiftmetaleft)
8428 '([?\e (shift right)] org-shiftmetaright)
8429 '([(shift up)] org-shiftup)
8430 '([(shift down)] org-shiftdown)
8431 '([(shift left)] org-shiftleft)
8432 '([(shift right)] org-shiftright)
8433 '("\C-c\C-c" org-ctrl-c-ctrl-c)
8434 '("\M-q" fill-paragraph)
8435 '("\C-c^" org-sort)
8436 '("\C-c-" org-cycle-list-bullet)))
8437 elt key fun cmd)
8438 (while (setq elt (pop bindings))
8439 (setq nfunc (1+ nfunc))
8440 (setq key (org-key (car elt))
8441 fun (nth 1 elt)
8442 cmd (orgstruct-make-binding fun nfunc key))
8443 (org-defkey orgstruct-mode-map key cmd))
8445 ;; Special treatment needed for TAB and RET
8446 (org-defkey orgstruct-mode-map [(tab)]
8447 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
8448 (org-defkey orgstruct-mode-map "\C-i"
8449 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
8451 (org-defkey orgstruct-mode-map "\M-\C-m"
8452 (orgstruct-make-binding 'org-insert-heading 105
8453 "\M-\C-m" [(meta return)]))
8454 (org-defkey orgstruct-mode-map [(meta return)]
8455 (orgstruct-make-binding 'org-insert-heading 106
8456 [(meta return)] "\M-\C-m"))
8458 (org-defkey orgstruct-mode-map [(shift meta return)]
8459 (orgstruct-make-binding 'org-insert-todo-heading 107
8460 [(meta return)] "\M-\C-m"))
8462 (org-defkey orgstruct-mode-map "\e\C-m"
8463 (orgstruct-make-binding 'org-insert-heading 108
8464 "\e\C-m" [?\e (return)]))
8465 (org-defkey orgstruct-mode-map [?\e (return)]
8466 (orgstruct-make-binding 'org-insert-heading 109
8467 [?\e (return)] "\e\C-m"))
8468 (org-defkey orgstruct-mode-map [?\e (shift return)]
8469 (orgstruct-make-binding 'org-insert-todo-heading 110
8470 [?\e (return)] "\e\C-m"))
8472 (unless org-local-vars
8473 (setq org-local-vars (org-get-local-variables)))
8477 (defun orgstruct-make-binding (fun n &rest keys)
8478 "Create a function for binding in the structure minor mode.
8479 FUN is the command to call inside a table. N is used to create a unique
8480 command name. KEYS are keys that should be checked in for a command
8481 to execute outside of tables."
8482 (eval
8483 (list 'defun
8484 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
8485 '(arg)
8486 (concat "In Structure, run `" (symbol-name fun) "'.\n"
8487 "Outside of structure, run the binding of `"
8488 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
8489 "'.")
8490 '(interactive "p")
8491 (list 'if
8492 `(org-context-p 'headline 'item
8493 (and orgstruct-is-++
8494 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
8495 'item-body))
8496 (list 'org-run-like-in-org-mode (list 'quote fun))
8497 (list 'let '(orgstruct-mode)
8498 (list 'call-interactively
8499 (append '(or)
8500 (mapcar (lambda (k)
8501 (list 'key-binding k))
8502 keys)
8503 '('orgstruct-error))))))))
8505 (defun org-context-p (&rest contexts)
8506 "Check if local context is any of CONTEXTS.
8507 Possible values in the list of contexts are `table', `headline', and `item'."
8508 (let ((pos (point)))
8509 (goto-char (point-at-bol))
8510 (prog1 (or (and (memq 'table contexts)
8511 (looking-at "[ \t]*|"))
8512 (and (memq 'headline contexts)
8513 (looking-at org-outline-regexp))
8514 (and (memq 'item contexts)
8515 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
8516 (and (memq 'item-body contexts)
8517 (org-in-item-p)))
8518 (goto-char pos))))
8520 (defun org-get-local-variables ()
8521 "Return a list of all local variables in an org-mode buffer."
8522 (let (varlist)
8523 (with-current-buffer (get-buffer-create "*Org tmp*")
8524 (erase-buffer)
8525 (org-mode)
8526 (setq varlist (buffer-local-variables)))
8527 (kill-buffer "*Org tmp*")
8528 (delq nil
8529 (mapcar
8530 (lambda (x)
8531 (setq x
8532 (if (symbolp x)
8533 (list x)
8534 (list (car x) (list 'quote (cdr x)))))
8535 (if (string-match
8536 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
8537 (symbol-name (car x)))
8538 x nil))
8539 varlist))))
8541 (defun org-clone-local-variables (from-buffer &optional regexp)
8542 "Clone local variables from FROM-BUFFER.
8543 Optional argument REGEXP selects variables to clone."
8544 (mapc
8545 (lambda (pair)
8546 (and (symbolp (car pair))
8547 (or (null regexp)
8548 (string-match regexp (symbol-name (car pair))))
8549 (set (make-local-variable (car pair))
8550 (cdr pair))))
8551 (buffer-local-variables from-buffer)))
8553 ;;;###autoload
8554 (defun org-run-like-in-org-mode (cmd)
8555 "Run a command, pretending that the current buffer is in Org-mode.
8556 This will temporarily bind local variables that are typically bound in
8557 Org-mode to the values they have in Org-mode, and then interactively
8558 call CMD."
8559 (org-load-modules-maybe)
8560 (unless org-local-vars
8561 (setq org-local-vars (org-get-local-variables)))
8562 (eval (list 'let org-local-vars
8563 (list 'call-interactively (list 'quote cmd)))))
8565 ;;;; Archiving
8567 (defun org-get-category (&optional pos force-refresh)
8568 "Get the category applying to position POS."
8569 (save-match-data
8570 (if force-refresh (org-refresh-category-properties))
8571 (let ((pos (or pos (point))))
8572 (or (get-text-property pos 'org-category)
8573 (progn (org-refresh-category-properties)
8574 (get-text-property pos 'org-category))))))
8576 (defun org-refresh-category-properties ()
8577 "Refresh category text properties in the buffer."
8578 (let ((inhibit-read-only t)
8579 (def-cat (cond
8580 ((null org-category)
8581 (if buffer-file-name
8582 (file-name-sans-extension
8583 (file-name-nondirectory buffer-file-name))
8584 "???"))
8585 ((symbolp org-category) (symbol-name org-category))
8586 (t org-category)))
8587 beg end cat pos optionp)
8588 (org-unmodified
8589 (save-excursion
8590 (save-restriction
8591 (widen)
8592 (goto-char (point-min))
8593 (put-text-property (point) (point-max) 'org-category def-cat)
8594 (while (re-search-forward
8595 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8596 (setq pos (match-end 0)
8597 optionp (equal (char-after (match-beginning 0)) ?#)
8598 cat (org-trim (match-string 2)))
8599 (if optionp
8600 (setq beg (point-at-bol) end (point-max))
8601 (org-back-to-heading t)
8602 (setq beg (point) end (org-end-of-subtree t t)))
8603 (put-text-property beg end 'org-category cat)
8604 (put-text-property beg end 'org-category-position beg)
8605 (goto-char pos)))))))
8608 ;;;; Link Stuff
8610 ;;; Link abbreviations
8612 (defun org-link-expand-abbrev (link)
8613 "Apply replacements as defined in `org-link-abbrev-alist."
8614 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
8615 (let* ((key (match-string 1 link))
8616 (as (or (assoc key org-link-abbrev-alist-local)
8617 (assoc key org-link-abbrev-alist)))
8618 (tag (and (match-end 2) (match-string 3 link)))
8619 rpl)
8620 (if (not as)
8621 link
8622 (setq rpl (cdr as))
8623 (cond
8624 ((symbolp rpl) (funcall rpl tag))
8625 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
8626 ((string-match "%h" rpl)
8627 (replace-match (url-hexify-string (or tag "")) t t rpl))
8628 (t (concat rpl tag)))))
8629 link))
8631 ;;; Storing and inserting links
8633 (defvar org-insert-link-history nil
8634 "Minibuffer history for links inserted with `org-insert-link'.")
8636 (defvar org-stored-links nil
8637 "Contains the links stored with `org-store-link'.")
8639 (defvar org-store-link-plist nil
8640 "Plist with info about the most recently link created with `org-store-link'.")
8642 (defvar org-link-protocols nil
8643 "Link protocols added to Org-mode using `org-add-link-type'.")
8645 (defvar org-store-link-functions nil
8646 "List of functions that are called to create and store a link.
8647 Each function will be called in turn until one returns a non-nil
8648 value. Each function should check if it is responsible for creating
8649 this link (for example by looking at the major mode).
8650 If not, it must exit and return nil.
8651 If yes, it should return a non-nil value after a calling
8652 `org-store-link-props' with a list of properties and values.
8653 Special properties are:
8655 :type The link prefix, like \"http\". This must be given.
8656 :link The link, like \"http://www.astro.uva.nl/~dominik\".
8657 This is obligatory as well.
8658 :description Optional default description for the second pair
8659 of brackets in an Org-mode link. The user can still change
8660 this when inserting this link into an Org-mode buffer.
8662 In addition to these, any additional properties can be specified
8663 and then used in remember templates.")
8665 (defun org-add-link-type (type &optional follow export)
8666 "Add TYPE to the list of `org-link-types'.
8667 Re-compute all regular expressions depending on `org-link-types'
8669 FOLLOW and EXPORT are two functions.
8671 FOLLOW should take the link path as the single argument and do whatever
8672 is necessary to follow the link, for example find a file or display
8673 a mail message.
8675 EXPORT should format the link path for export to one of the export formats.
8676 It should be a function accepting three arguments:
8678 path the path of the link, the text after the prefix (like \"http:\")
8679 desc the description of the link, if any, or a description added by
8680 org-export-normalize-links if there is none
8681 format the export format, a symbol like `html' or `latex' or `ascii'..
8683 The function may use the FORMAT information to return different values
8684 depending on the format. The return value will be put literally into
8685 the exported file. If the return value is nil, this means Org should
8686 do what it normally does with links which do not have EXPORT defined.
8688 Org-mode has a built-in default for exporting links. If you are happy with
8689 this default, there is no need to define an export function for the link
8690 type. For a simple example of an export function, see `org-bbdb.el'."
8691 (add-to-list 'org-link-types type t)
8692 (org-make-link-regexps)
8693 (if (assoc type org-link-protocols)
8694 (setcdr (assoc type org-link-protocols) (list follow export))
8695 (push (list type follow export) org-link-protocols)))
8697 (defvar org-agenda-buffer-name)
8699 ;;;###autoload
8700 (defun org-store-link (arg)
8701 "\\<org-mode-map>Store an org-link to the current location.
8702 This link is added to `org-stored-links' and can later be inserted
8703 into an org-buffer with \\[org-insert-link].
8705 For some link types, a prefix arg is interpreted:
8706 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
8707 For file links, arg negates `org-context-in-file-links'."
8708 (interactive "P")
8709 (org-load-modules-maybe)
8710 (setq org-store-link-plist nil) ; reset
8711 (org-with-limited-levels
8712 (let (link cpltxt desc description search txt custom-id agenda-link)
8713 (cond
8715 ((run-hook-with-args-until-success 'org-store-link-functions)
8716 (setq link (plist-get org-store-link-plist :link)
8717 desc (or (plist-get org-store-link-plist :description) link)))
8719 ((org-src-edit-buffer-p)
8720 (let (label gc)
8721 (while (or (not label)
8722 (save-excursion
8723 (save-restriction
8724 (widen)
8725 (goto-char (point-min))
8726 (re-search-forward
8727 (regexp-quote (format org-coderef-label-format label))
8728 nil t))))
8729 (when label (message "Label exists already") (sit-for 2))
8730 (setq label (read-string "Code line label: " label)))
8731 (end-of-line 1)
8732 (setq link (format org-coderef-label-format label))
8733 (setq gc (- 79 (length link)))
8734 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
8735 (insert link)
8736 (setq link (concat "(" label ")") desc nil)))
8738 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
8739 ;; We are in the agenda, link to referenced location
8740 (let ((m (or (get-text-property (point) 'org-hd-marker)
8741 (get-text-property (point) 'org-marker))))
8742 (when m
8743 (org-with-point-at m
8744 (setq agenda-link
8745 (if (org-called-interactively-p 'any)
8746 (call-interactively 'org-store-link)
8747 (org-store-link nil)))))))
8749 ((eq major-mode 'calendar-mode)
8750 (let ((cd (calendar-cursor-to-date)))
8751 (setq link
8752 (format-time-string
8753 (car org-time-stamp-formats)
8754 (apply 'encode-time
8755 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
8756 nil nil nil))))
8757 (org-store-link-props :type "calendar" :date cd)))
8759 ((eq major-mode 'w3-mode)
8760 (setq cpltxt (if (and (buffer-name)
8761 (not (string-match "Untitled" (buffer-name))))
8762 (buffer-name)
8763 (url-view-url t))
8764 link (org-make-link (url-view-url t)))
8765 (org-store-link-props :type "w3" :url (url-view-url t)))
8767 ((eq major-mode 'w3m-mode)
8768 (setq cpltxt (or w3m-current-title w3m-current-url)
8769 link (org-make-link w3m-current-url))
8770 (org-store-link-props :type "w3m" :url (url-view-url t)))
8772 ((setq search (run-hook-with-args-until-success
8773 'org-create-file-search-functions))
8774 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
8775 "::" search))
8776 (setq cpltxt (or description link)))
8778 ((eq major-mode 'image-mode)
8779 (setq cpltxt (concat "file:"
8780 (abbreviate-file-name buffer-file-name))
8781 link (org-make-link cpltxt))
8782 (org-store-link-props :type "image" :file buffer-file-name))
8784 ((eq major-mode 'dired-mode)
8785 ;; link to the file in the current line
8786 (let ((file (dired-get-filename nil t)))
8787 (setq file (if file
8788 (abbreviate-file-name
8789 (expand-file-name (dired-get-filename nil t)))
8790 ;; otherwise, no file so use current directory.
8791 default-directory))
8792 (setq cpltxt (concat "file:" file)
8793 link (org-make-link cpltxt))))
8795 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
8796 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
8797 (cond
8798 ((org-in-regexp "<<\\(.*?\\)>>")
8799 (setq cpltxt
8800 (concat "file:"
8801 (abbreviate-file-name
8802 (buffer-file-name (buffer-base-buffer)))
8803 "::" (match-string 1))
8804 link (org-make-link cpltxt)))
8805 ((and (featurep 'org-id)
8806 (or (eq org-link-to-org-use-id t)
8807 (and (eq org-link-to-org-use-id 'create-if-interactive)
8808 (org-called-interactively-p 'any))
8809 (and (eq org-link-to-org-use-id
8810 'create-if-interactive-and-no-custom-id)
8811 (org-called-interactively-p 'any)
8812 (not custom-id))
8813 (and org-link-to-org-use-id
8814 (org-entry-get nil "ID"))))
8815 ;; We can make a link using the ID.
8816 (setq link (condition-case nil
8817 (prog1 (org-id-store-link)
8818 (setq desc (plist-get org-store-link-plist
8819 :description)))
8820 (error
8821 ;; probably before first headline, link to file only
8822 (concat "file:"
8823 (abbreviate-file-name
8824 (buffer-file-name (buffer-base-buffer))))))))
8826 ;; Just link to current headline
8827 (setq cpltxt (concat "file:"
8828 (abbreviate-file-name
8829 (buffer-file-name (buffer-base-buffer)))))
8830 ;; Add a context search string
8831 (when (org-xor org-context-in-file-links arg)
8832 (setq txt (cond
8833 ((org-at-heading-p) nil)
8834 ((org-region-active-p)
8835 (buffer-substring (region-beginning) (region-end)))
8836 (t nil)))
8837 (when (or (null txt) (string-match "\\S-" txt))
8838 (setq cpltxt
8839 (concat cpltxt "::"
8840 (condition-case nil
8841 (org-make-org-heading-search-string txt)
8842 (error "")))
8843 desc (or (nth 4 (ignore-errors
8844 (org-heading-components))) "NONE"))))
8845 (if (string-match "::\\'" cpltxt)
8846 (setq cpltxt (substring cpltxt 0 -2)))
8847 (setq link (org-make-link cpltxt)))))
8849 ((buffer-file-name (buffer-base-buffer))
8850 ;; Just link to this file here.
8851 (setq cpltxt (concat "file:"
8852 (abbreviate-file-name
8853 (buffer-file-name (buffer-base-buffer)))))
8854 ;; Add a context string
8855 (when (org-xor org-context-in-file-links arg)
8856 (setq txt (if (org-region-active-p)
8857 (buffer-substring (region-beginning) (region-end))
8858 (buffer-substring (point-at-bol) (point-at-eol))))
8859 ;; Only use search option if there is some text.
8860 (when (string-match "\\S-" txt)
8861 (setq cpltxt
8862 (concat cpltxt "::" (org-make-org-heading-search-string txt))
8863 desc "NONE")))
8864 (setq link (org-make-link cpltxt)))
8866 ((org-called-interactively-p 'interactive)
8867 (error "Cannot link to a buffer which is not visiting a file"))
8869 (t (setq link nil)))
8871 (if (consp link) (setq cpltxt (car link) link (cdr link)))
8872 (setq link (or link cpltxt)
8873 desc (or desc cpltxt))
8874 (if (equal desc "NONE") (setq desc nil))
8876 (if (and (or (org-called-interactively-p 'any) executing-kbd-macro) link)
8877 (progn
8878 (setq org-stored-links
8879 (cons (list link desc) org-stored-links))
8880 (message "Stored: %s" (or desc link))
8881 (when custom-id
8882 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
8883 "::#" custom-id))
8884 (setq org-stored-links
8885 (cons (list link desc) org-stored-links))))
8886 (or agenda-link (and link (org-make-link-string link desc)))))))
8888 (defun org-store-link-props (&rest plist)
8889 "Store link properties, extract names and addresses."
8890 (let (x adr)
8891 (when (setq x (plist-get plist :from))
8892 (setq adr (mail-extract-address-components x))
8893 (setq plist (plist-put plist :fromname (car adr)))
8894 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
8895 (when (setq x (plist-get plist :to))
8896 (setq adr (mail-extract-address-components x))
8897 (setq plist (plist-put plist :toname (car adr)))
8898 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
8899 (let ((from (plist-get plist :from))
8900 (to (plist-get plist :to)))
8901 (when (and from to org-from-is-user-regexp)
8902 (setq plist
8903 (plist-put plist :fromto
8904 (if (string-match org-from-is-user-regexp from)
8905 (concat "to %t")
8906 (concat "from %f"))))))
8907 (setq org-store-link-plist plist))
8909 (defun org-add-link-props (&rest plist)
8910 "Add these properties to the link property list."
8911 (let (key value)
8912 (while plist
8913 (setq key (pop plist) value (pop plist))
8914 (setq org-store-link-plist
8915 (plist-put org-store-link-plist key value)))))
8917 (defun org-email-link-description (&optional fmt)
8918 "Return the description part of an email link.
8919 This takes information from `org-store-link-plist' and formats it
8920 according to FMT (default from `org-email-link-description-format')."
8921 (setq fmt (or fmt org-email-link-description-format))
8922 (let* ((p org-store-link-plist)
8923 (to (plist-get p :toaddress))
8924 (from (plist-get p :fromaddress))
8925 (table
8926 (list
8927 (cons "%c" (plist-get p :fromto))
8928 (cons "%F" (plist-get p :from))
8929 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
8930 (cons "%T" (plist-get p :to))
8931 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
8932 (cons "%s" (plist-get p :subject))
8933 (cons "%d" (plist-get p :date))
8934 (cons "%m" (plist-get p :message-id)))))
8935 (when (string-match "%c" fmt)
8936 ;; Check if the user wrote this message
8937 (if (and org-from-is-user-regexp from to
8938 (save-match-data (string-match org-from-is-user-regexp from)))
8939 (setq fmt (replace-match "to %t" t t fmt))
8940 (setq fmt (replace-match "from %f" t t fmt))))
8941 (org-replace-escapes fmt table)))
8943 (defun org-make-org-heading-search-string (&optional string heading)
8944 "Make search string for STRING or current headline."
8945 (interactive)
8946 (let ((s (or string (org-get-heading)))
8947 (lines org-context-in-file-links))
8948 (unless (and string (not heading))
8949 ;; We are using a headline, clean up garbage in there.
8950 (if (string-match org-todo-regexp s)
8951 (setq s (replace-match "" t t s)))
8952 (if (string-match (org-re ":[[:alnum:]_@#%:]+:[ \t]*$") s)
8953 (setq s (replace-match "" t t s)))
8954 (setq s (org-trim s))
8955 (if (string-match (concat "^\\(" org-quote-string "\\|"
8956 org-comment-string "\\)") s)
8957 (setq s (replace-match "" t t s)))
8958 (while (string-match org-ts-regexp s)
8959 (setq s (replace-match "" t t s))))
8960 (or string (setq s (concat "*" s))) ; Add * for headlines
8961 (when (and string (integerp lines) (> lines 0))
8962 (let ((slines (org-split-string s "\n")))
8963 (when (< lines (length slines))
8964 (setq s (mapconcat
8965 'identity
8966 (reverse (nthcdr (- (length slines) lines)
8967 (reverse slines))) "\n")))))
8968 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
8970 (defun org-make-link (&rest strings)
8971 "Concatenate STRINGS."
8972 (apply 'concat strings))
8974 (defun org-make-link-string (link &optional description)
8975 "Make a link with brackets, consisting of LINK and DESCRIPTION."
8976 (unless (string-match "\\S-" link)
8977 (error "Empty link"))
8978 (when (and description
8979 (stringp description)
8980 (not (string-match "\\S-" description)))
8981 (setq description nil))
8982 (when (stringp description)
8983 ;; Remove brackets from the description, they are fatal.
8984 (while (string-match "\\[" description)
8985 (setq description (replace-match "{" t t description)))
8986 (while (string-match "\\]" description)
8987 (setq description (replace-match "}" t t description))))
8988 (when (equal link description)
8989 ;; No description needed, it is identical
8990 (setq description nil))
8991 (when (and (not description)
8992 (not (string-match (org-image-file-name-regexp) link))
8993 (not (equal link (org-link-escape link))))
8994 (setq description (org-extract-attributes link)))
8995 (setq link
8996 (cond ((string-match (org-image-file-name-regexp) link) link)
8997 ((string-match org-link-types-re link)
8998 (concat (match-string 1 link)
8999 (org-link-escape (substring link (match-end 1)))))
9000 (t (org-link-escape link))))
9001 (concat "[[" link "]"
9002 (if description (concat "[" description "]") "")
9003 "]"))
9005 (defconst org-link-escape-chars
9006 '(?\ ?\[ ?\] ?\; ?\= ?\+)
9007 "List of characters that should be escaped in link.
9008 This is the list that is used for internal purposes.")
9010 (defvar org-url-encoding-use-url-hexify nil)
9012 (defconst org-link-escape-chars-browser
9013 '(?\ )
9014 "List of escapes for characters that are problematic in links.
9015 This is the list that is used before handing over to the browser.")
9017 (defun org-link-escape (text &optional table merge)
9018 "Return percent escaped representation of TEXT.
9019 TEXT is a string with the text to escape.
9020 Optional argument TABLE is a list with characters that should be
9021 escaped. When nil, `org-link-escape-chars' is used.
9022 If optional argument MERGE is set, merge TABLE into
9023 `org-link-escape-chars'."
9024 (if (and org-url-encoding-use-url-hexify (not table))
9025 (url-hexify-string text)
9026 (cond
9027 ((and table merge)
9028 (mapc (lambda (defchr)
9029 (unless (member defchr table)
9030 (setq table (cons defchr table)))) org-link-escape-chars))
9031 ((null table)
9032 (setq table org-link-escape-chars)))
9033 (mapconcat
9034 (lambda (char)
9035 (if (or (member char table)
9036 (< char 32) (= char 37) (> char 126))
9037 (mapconcat (lambda (sequence-element)
9038 (format "%%%.2X" sequence-element))
9039 (or (encode-coding-char char 'utf-8)
9040 (error "Unable to percent escape character: %s"
9041 (char-to-string char))) "")
9042 (char-to-string char))) text "")))
9044 (defun org-link-unescape (str)
9045 "Unhex hexified Unicode strings as returned from the JavaScript function
9046 encodeURIComponent. E.g. `%C3%B6' is the german Umlaut `ö'."
9047 (unless (and (null str) (string= "" str))
9048 (let ((pos 0) (case-fold-search t) unhexed)
9049 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9050 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9051 (setq str (replace-match unhexed t t str))
9052 (setq pos (+ pos (length unhexed))))))
9053 str)
9055 (defun org-link-unescape-compound (hex)
9056 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German Umlaut `ö'.
9057 Note: this function also decodes single byte encodings like
9058 `%E1' (\"á\") if not followed by another `%[A-F0-9]{2}' group."
9059 (save-match-data
9060 (let* ((bytes (cdr (split-string hex "%")))
9061 (ret "")
9062 (eat 0)
9063 (sum 0))
9064 (while bytes
9065 (let* ((val (string-to-number (pop bytes) 16))
9066 (shift-xor
9067 (if (= 0 eat)
9068 (cond
9069 ((>= val 252) (cons 6 252))
9070 ((>= val 248) (cons 5 248))
9071 ((>= val 240) (cons 4 240))
9072 ((>= val 224) (cons 3 224))
9073 ((>= val 192) (cons 2 192))
9074 (t (cons 0 0)))
9075 (cons 6 128))))
9076 (if (>= val 192) (setq eat (car shift-xor)))
9077 (setq val (logxor val (cdr shift-xor)))
9078 (setq sum (+ (lsh sum (car shift-xor)) val))
9079 (if (> eat 0) (setq eat (- eat 1)))
9080 (cond
9081 ((= 0 eat) ;multi byte
9082 (setq ret (concat ret (org-char-to-string sum)))
9083 (setq sum 0))
9084 ((not bytes) ; single byte(s)
9085 (setq ret (org-link-unescape-single-byte-sequence hex))))
9086 )) ;; end (while bytes
9087 ret )))
9089 (defun org-link-unescape-single-byte-sequence (hex)
9090 "Unhexify hex-encoded single byte character sequences."
9091 (mapconcat (lambda (byte)
9092 (char-to-string (string-to-number byte 16)))
9093 (cdr (split-string hex "%")) ""))
9095 (defun org-xor (a b)
9096 "Exclusive or."
9097 (if a (not b) b))
9099 (defun org-fixup-message-id-for-http (s)
9100 "Replace special characters in a message id, so it can be used in an http query."
9101 (when (string-match "%" s)
9102 (setq s (mapconcat (lambda (c)
9103 (if (eq c ?%)
9104 "%25"
9105 (char-to-string c)))
9106 s "")))
9107 (while (string-match "<" s)
9108 (setq s (replace-match "%3C" t t s)))
9109 (while (string-match ">" s)
9110 (setq s (replace-match "%3E" t t s)))
9111 (while (string-match "@" s)
9112 (setq s (replace-match "%40" t t s)))
9115 (defun org-link-prettify (link)
9116 "Return a human-readable representation of LINK.
9117 The car of LINK must be a raw link the cdr of LINK must be either
9118 a link description or nil."
9119 (let ((desc (or (cadr link) "<no description>")))
9120 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9121 "[[" (car link) "]]")))
9123 ;;;###autoload
9124 (defun org-insert-link-global ()
9125 "Insert a link like Org-mode does.
9126 This command can be called in any mode to insert a link in Org-mode syntax."
9127 (interactive)
9128 (org-load-modules-maybe)
9129 (org-run-like-in-org-mode 'org-insert-link))
9131 (defun org-insert-link (&optional complete-file link-location default-description)
9132 "Insert a link. At the prompt, enter the link.
9134 Completion can be used to insert any of the link protocol prefixes like
9135 http or ftp in use.
9137 The history can be used to select a link previously stored with
9138 `org-store-link'. When the empty string is entered (i.e. if you just
9139 press RET at the prompt), the link defaults to the most recently
9140 stored link. As SPC triggers completion in the minibuffer, you need to
9141 use M-SPC or C-q SPC to force the insertion of a space character.
9143 You will also be prompted for a description, and if one is given, it will
9144 be displayed in the buffer instead of the link.
9146 If there is already a link at point, this command will allow you to edit link
9147 and description parts.
9149 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9150 be selected using completion. The path to the file will be relative to the
9151 current directory if the file is in the current directory or a subdirectory.
9152 Otherwise, the link will be the absolute path as completed in the minibuffer
9153 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9154 option `org-link-file-path-type'.
9156 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9157 the current directory or below.
9159 With three \\[universal-argument] prefixes, negate the meaning of
9160 `org-keep-stored-link-after-insertion'.
9162 If `org-make-link-description-function' is non-nil, this function will be
9163 called with the link target, and the result will be the default
9164 link description.
9166 If the LINK-LOCATION parameter is non-nil, this value will be
9167 used as the link location instead of reading one interactively.
9169 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9170 be used as the default description."
9171 (interactive "P")
9172 (let* ((wcf (current-window-configuration))
9173 (region (if (org-region-active-p)
9174 (buffer-substring (region-beginning) (region-end))))
9175 (remove (and region (list (region-beginning) (region-end))))
9176 (desc region)
9177 tmphist ; byte-compile incorrectly complains about this
9178 (link link-location)
9179 entry file all-prefixes)
9180 (cond
9181 (link-location) ; specified by arg, just use it.
9182 ((org-in-regexp org-bracket-link-regexp 1)
9183 ;; We do have a link at point, and we are going to edit it.
9184 (setq remove (list (match-beginning 0) (match-end 0)))
9185 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9186 (setq link (read-string "Link: "
9187 (org-link-unescape
9188 (org-match-string-no-properties 1)))))
9189 ((or (org-in-regexp org-angle-link-re)
9190 (org-in-regexp org-plain-link-re))
9191 ;; Convert to bracket link
9192 (setq remove (list (match-beginning 0) (match-end 0))
9193 link (read-string "Link: "
9194 (org-remove-angle-brackets (match-string 0)))))
9195 ((member complete-file '((4) (16)))
9196 ;; Completing read for file names.
9197 (setq link (org-file-complete-link complete-file)))
9199 ;; Read link, with completion for stored links.
9200 (with-output-to-temp-buffer "*Org Links*"
9201 (princ "Insert a link.
9202 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9203 (when org-stored-links
9204 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9205 (princ (mapconcat 'org-link-prettify
9206 (reverse org-stored-links) "\n"))))
9207 (let ((cw (selected-window)))
9208 (select-window (get-buffer-window "*Org Links*" 'visible))
9209 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9210 (unless (pos-visible-in-window-p (point-max))
9211 (org-fit-window-to-buffer))
9212 (and (window-live-p cw) (select-window cw)))
9213 ;; Fake a link history, containing the stored links.
9214 (setq tmphist (append (mapcar 'car org-stored-links)
9215 org-insert-link-history))
9216 (setq all-prefixes (append (mapcar 'car org-link-abbrev-alist-local)
9217 (mapcar 'car org-link-abbrev-alist)
9218 org-link-types))
9219 (unwind-protect
9220 (progn
9221 (setq link
9222 (let ((org-completion-use-ido nil)
9223 (org-completion-use-iswitchb nil))
9224 (org-completing-read
9225 "Link: "
9226 (append
9227 (mapcar (lambda (x) (list (concat x ":")))
9228 all-prefixes)
9229 (mapcar 'car org-stored-links))
9230 nil nil nil
9231 'tmphist
9232 (car (car org-stored-links)))))
9233 (if (not (string-match "\\S-" link))
9234 (error "No link selected"))
9235 (if (or (member link all-prefixes)
9236 (and (equal ":" (substring link -1))
9237 (member (substring link 0 -1) all-prefixes)
9238 (setq link (substring link 0 -1))))
9239 (setq link (org-link-try-special-completion link))))
9240 (set-window-configuration wcf)
9241 (kill-buffer "*Org Links*"))
9242 (setq entry (assoc link org-stored-links))
9243 (or entry (push link org-insert-link-history))
9244 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9245 (not org-keep-stored-link-after-insertion))
9246 (setq org-stored-links (delq (assoc link org-stored-links)
9247 org-stored-links)))
9248 (setq desc (or desc (nth 1 entry)))))
9250 (if (string-match org-plain-link-re link)
9251 ;; URL-like link, normalize the use of angular brackets.
9252 (setq link (org-make-link (org-remove-angle-brackets link))))
9254 ;; Check if we are linking to the current file with a search option
9255 ;; If yes, simplify the link by using only the search option.
9256 (when (and buffer-file-name
9257 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
9258 (let* ((path (match-string 1 link))
9259 (case-fold-search nil)
9260 (search (match-string 2 link)))
9261 (save-match-data
9262 (if (equal (file-truename buffer-file-name) (file-truename path))
9263 ;; We are linking to this same file, with a search option
9264 (setq link search)))))
9266 ;; Check if we can/should use a relative path. If yes, simplify the link
9267 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
9268 (let* ((type (match-string 1 link))
9269 (path (match-string 2 link))
9270 (origpath path)
9271 (case-fold-search nil))
9272 (cond
9273 ((or (eq org-link-file-path-type 'absolute)
9274 (equal complete-file '(16)))
9275 (setq path (abbreviate-file-name (expand-file-name path))))
9276 ((eq org-link-file-path-type 'noabbrev)
9277 (setq path (expand-file-name path)))
9278 ((eq org-link-file-path-type 'relative)
9279 (setq path (file-relative-name path)))
9281 (save-match-data
9282 (if (string-match (concat "^" (regexp-quote
9283 (expand-file-name
9284 (file-name-as-directory
9285 default-directory))))
9286 (expand-file-name path))
9287 ;; We are linking a file with relative path name.
9288 (setq path (substring (expand-file-name path)
9289 (match-end 0)))
9290 (setq path (abbreviate-file-name (expand-file-name path)))))))
9291 (setq link (concat type path))
9292 (if (equal desc origpath)
9293 (setq desc path))))
9295 (if org-make-link-description-function
9296 (setq desc (funcall org-make-link-description-function link desc))
9297 (if default-description (setq desc default-description)))
9299 (setq desc (read-string "Description: " desc))
9300 (unless (string-match "\\S-" desc) (setq desc nil))
9301 (if remove (apply 'delete-region remove))
9302 (insert (org-make-link-string link desc))))
9304 (defun org-link-try-special-completion (type)
9305 "If there is completion support for link type TYPE, offer it."
9306 (let ((fun (intern (concat "org-" type "-complete-link"))))
9307 (if (functionp fun)
9308 (funcall fun)
9309 (read-string "Link (no completion support): " (concat type ":")))))
9311 (defun org-file-complete-link (&optional arg)
9312 "Create a file link using completion."
9313 (let (file link)
9314 (setq file (read-file-name "File: "))
9315 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9316 (pwd1 (file-name-as-directory (abbreviate-file-name
9317 (expand-file-name ".")))))
9318 (cond
9319 ((equal arg '(16))
9320 (setq link (org-make-link
9321 "file:"
9322 (abbreviate-file-name (expand-file-name file)))))
9323 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9324 (setq link (org-make-link "file:" (match-string 1 file))))
9325 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9326 (expand-file-name file))
9327 (setq link (org-make-link
9328 "file:" (match-string 1 (expand-file-name file)))))
9329 (t (setq link (org-make-link "file:" file)))))
9330 link))
9332 (defun org-completing-read (&rest args)
9333 "Completing-read with SPACE being a normal character."
9334 (let ((enable-recursive-minibuffers t)
9335 (minibuffer-local-completion-map
9336 (copy-keymap minibuffer-local-completion-map)))
9337 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
9338 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
9339 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
9340 (apply 'org-icompleting-read args)))
9342 (defun org-completing-read-no-i (&rest args)
9343 (let (org-completion-use-ido org-completion-use-iswitchb)
9344 (apply 'org-completing-read args)))
9346 (defun org-iswitchb-completing-read (prompt choices &rest args)
9347 "Use iswitch as a completing-read replacement to choose from choices.
9348 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
9349 from."
9350 (let* ((iswitchb-use-virtual-buffers nil)
9351 (iswitchb-make-buflist-hook
9352 (lambda ()
9353 (setq iswitchb-temp-buflist choices))))
9354 (iswitchb-read-buffer prompt)))
9356 (defun org-icompleting-read (&rest args)
9357 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
9358 (org-without-partial-completion
9359 (if (and org-completion-use-ido
9360 (fboundp 'ido-completing-read)
9361 (boundp 'ido-mode) ido-mode
9362 (listp (second args)))
9363 (let ((ido-enter-matching-directory nil))
9364 (apply 'ido-completing-read (concat (car args))
9365 (if (consp (car (nth 1 args)))
9366 (mapcar 'car (nth 1 args))
9367 (nth 1 args))
9368 (cddr args)))
9369 (if (and org-completion-use-iswitchb
9370 (boundp 'iswitchb-mode) iswitchb-mode
9371 (listp (second args)))
9372 (apply 'org-iswitchb-completing-read (concat (car args))
9373 (if (consp (car (nth 1 args)))
9374 (mapcar 'car (nth 1 args))
9375 (nth 1 args))
9376 (cddr args))
9377 (apply 'completing-read args)))))
9379 (defun org-extract-attributes (s)
9380 "Extract the attributes cookie from a string and set as text property."
9381 (let (a attr (start 0) key value)
9382 (save-match-data
9383 (when (string-match "{{\\([^}]+\\)}}$" s)
9384 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
9385 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
9386 (setq key (match-string 1 a) value (match-string 2 a)
9387 start (match-end 0)
9388 attr (plist-put attr (intern key) value))))
9389 (org-add-props s nil 'org-attr attr))
9392 (defun org-extract-attributes-from-string (tag)
9393 (let (key value attr)
9394 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
9395 (setq key (match-string 1 tag) value (match-string 2 tag)
9396 tag (replace-match "" t t tag)
9397 attr (plist-put attr (intern key) value)))
9398 (cons tag attr)))
9400 (defun org-attributes-to-string (plist)
9401 "Format a property list into an HTML attribute list."
9402 (let ((s "") key value)
9403 (while plist
9404 (setq key (pop plist) value (pop plist))
9405 (and value
9406 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
9409 ;;; Opening/following a link
9411 (defvar org-link-search-failed nil)
9413 (defvar org-open-link-functions nil
9414 "Hook for functions finding a plain text link.
9415 These functions must take a single argument, the link content.
9416 They will be called for links that look like [[link text][description]]
9417 when LINK TEXT does not have a protocol like \"http:\" and does not look
9418 like a filename (e.g. \"./blue.png\").
9420 These functions will be called *before* Org attempts to resolve the
9421 link by doing text searches in the current buffer - so if you want a
9422 link \"[[target]]\" to still find \"<<target>>\", your function should
9423 handle this as a special case.
9425 When the function does handle the link, it must return a non-nil value.
9426 If it decides that it is not responsible for this link, it must return
9427 nil to indicate that that Org-mode can continue with other options
9428 like exact and fuzzy text search.")
9430 (defun org-next-link ()
9431 "Move forward to the next link.
9432 If the link is in hidden text, expose it."
9433 (interactive)
9434 (when (and org-link-search-failed (eq this-command last-command))
9435 (goto-char (point-min))
9436 (message "Link search wrapped back to beginning of buffer"))
9437 (setq org-link-search-failed nil)
9438 (let* ((pos (point))
9439 (ct (org-context))
9440 (a (assoc :link ct)))
9441 (if a (goto-char (nth 2 a)))
9442 (if (re-search-forward org-any-link-re nil t)
9443 (progn
9444 (goto-char (match-beginning 0))
9445 (if (outline-invisible-p) (org-show-context)))
9446 (goto-char pos)
9447 (setq org-link-search-failed t)
9448 (error "No further link found"))))
9450 (defun org-previous-link ()
9451 "Move backward to the previous link.
9452 If the link is in hidden text, expose it."
9453 (interactive)
9454 (when (and org-link-search-failed (eq this-command last-command))
9455 (goto-char (point-max))
9456 (message "Link search wrapped back to end of buffer"))
9457 (setq org-link-search-failed nil)
9458 (let* ((pos (point))
9459 (ct (org-context))
9460 (a (assoc :link ct)))
9461 (if a (goto-char (nth 1 a)))
9462 (if (re-search-backward org-any-link-re nil t)
9463 (progn
9464 (goto-char (match-beginning 0))
9465 (if (outline-invisible-p) (org-show-context)))
9466 (goto-char pos)
9467 (setq org-link-search-failed t)
9468 (error "No further link found"))))
9470 (defun org-translate-link (s)
9471 "Translate a link string if a translation function has been defined."
9472 (if (and org-link-translation-function
9473 (fboundp org-link-translation-function)
9474 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
9475 (progn
9476 (setq s (funcall org-link-translation-function
9477 (match-string 1) (match-string 2)))
9478 (concat (car s) ":" (cdr s)))
9481 (defun org-translate-link-from-planner (type path)
9482 "Translate a link from Emacs Planner syntax so that Org can follow it.
9483 This is still an experimental function, your mileage may vary."
9484 (cond
9485 ((member type '("http" "https" "news" "ftp"))
9486 ;; standard Internet links are the same.
9487 nil)
9488 ((and (equal type "irc") (string-match "^//" path))
9489 ;; Planner has two / at the beginning of an irc link, we have 1.
9490 ;; We should have zero, actually....
9491 (setq path (substring path 1)))
9492 ((and (equal type "lisp") (string-match "^/" path))
9493 ;; Planner has a slash, we do not.
9494 (setq type "elisp" path (substring path 1)))
9495 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9496 ;; A typical message link. Planner has the id after the final slash,
9497 ;; we separate it with a hash mark
9498 (setq path (concat (match-string 1 path) "#"
9499 (org-remove-angle-brackets (match-string 2 path)))))
9501 (cons type path))
9503 (defun org-find-file-at-mouse (ev)
9504 "Open file link or URL at mouse."
9505 (interactive "e")
9506 (mouse-set-point ev)
9507 (org-open-at-point 'in-emacs))
9509 (defun org-open-at-mouse (ev)
9510 "Open file link or URL at mouse.
9511 See the docstring of `org-open-file' for details."
9512 (interactive "e")
9513 (mouse-set-point ev)
9514 (if (eq major-mode 'org-agenda-mode)
9515 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
9516 (org-open-at-point))
9518 (defvar org-window-config-before-follow-link nil
9519 "The window configuration before following a link.
9520 This is saved in case the need arises to restore it.")
9522 (defvar org-open-link-marker (make-marker)
9523 "Marker pointing to the location where `org-open-at-point; was called.")
9525 ;;;###autoload
9526 (defun org-open-at-point-global ()
9527 "Follow a link like Org-mode does.
9528 This command can be called in any mode to follow a link that has
9529 Org-mode syntax."
9530 (interactive)
9531 (org-run-like-in-org-mode 'org-open-at-point))
9533 ;;;###autoload
9534 (defun org-open-link-from-string (s &optional arg reference-buffer)
9535 "Open a link in the string S, as if it was in Org-mode."
9536 (interactive "sLink: \nP")
9537 (let ((reference-buffer (or reference-buffer (current-buffer))))
9538 (with-temp-buffer
9539 (let ((org-inhibit-startup (not reference-buffer)))
9540 (org-mode)
9541 (insert s)
9542 (goto-char (point-min))
9543 (when reference-buffer
9544 (setq org-link-abbrev-alist-local
9545 (with-current-buffer reference-buffer
9546 org-link-abbrev-alist-local)))
9547 (org-open-at-point arg reference-buffer)))))
9549 (defvar org-open-at-point-functions nil
9550 "Hook that is run when following a link at point.
9552 Functions in this hook must return t if they identify and follow
9553 a link at point. If they don't find anything interesting at point,
9554 they must return nil.")
9556 (defun org-open-at-point (&optional arg reference-buffer)
9557 "Open link at or after point.
9558 If there is no link at point, this function will search forward up to
9559 the end of the current line.
9560 Normally, files will be opened by an appropriate application. If the
9561 optional prefix argument ARG is non-nil, Emacs will visit the file.
9562 With a double prefix argument, try to open outside of Emacs, in the
9563 application the system uses for this file type."
9564 (interactive "P")
9565 ;; if in a code block, then open the block's results
9566 (unless (call-interactively #'org-babel-open-src-block-result)
9567 (org-load-modules-maybe)
9568 (move-marker org-open-link-marker (point))
9569 (setq org-window-config-before-follow-link (current-window-configuration))
9570 (org-remove-occur-highlights nil nil t)
9571 (cond
9572 ((and (org-at-heading-p)
9573 (not (org-in-regexp
9574 (concat org-plain-link-re "\\|"
9575 org-bracket-link-regexp "\\|"
9576 org-angle-link-re "\\|"
9577 "[ \t]:[^ \t\n]+:[ \t]*$")))
9578 (not (get-text-property (point) 'org-linked-text)))
9579 (or (org-offer-links-in-entry arg)
9580 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
9581 ((run-hook-with-args-until-success 'org-open-at-point-functions))
9582 ((org-at-timestamp-p t) (org-follow-timestamp-link))
9583 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
9584 (not (org-in-regexp org-bracket-link-regexp)))
9585 (org-footnote-action))
9587 (let (type path link line search (pos (point)))
9588 (catch 'match
9589 (save-excursion
9590 (skip-chars-forward "^]\n\r")
9591 (when (org-in-regexp org-bracket-link-regexp 1)
9592 (setq link (org-extract-attributes
9593 (org-link-unescape (org-match-string-no-properties 1))))
9594 (while (string-match " *\n *" link)
9595 (setq link (replace-match " " t t link)))
9596 (setq link (org-link-expand-abbrev link))
9597 (cond
9598 ((or (file-name-absolute-p link)
9599 (string-match "^\\.\\.?/" link))
9600 (setq type "file" path link))
9601 ((string-match org-link-re-with-space3 link)
9602 (setq type (match-string 1 link) path (match-string 2 link)))
9603 (t (setq type "thisfile" path link)))
9604 (throw 'match t)))
9606 (when (get-text-property (point) 'org-linked-text)
9607 (setq type "thisfile"
9608 pos (if (get-text-property (1+ (point)) 'org-linked-text)
9609 (1+ (point)) (point))
9610 path (buffer-substring
9611 (or (previous-single-property-change pos 'org-linked-text)
9612 (point-min))
9613 (or (next-single-property-change pos 'org-linked-text)
9614 (point-max))))
9615 (throw 'match t))
9617 (save-excursion
9618 (when (or (org-in-regexp org-angle-link-re)
9619 (org-in-regexp org-plain-link-re))
9620 (setq type (match-string 1)
9621 path (org-link-unescape (match-string 2)))
9622 (throw 'match t)))
9623 (save-excursion
9624 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
9625 (setq type "tags"
9626 path (match-string 1))
9627 (while (string-match ":" path)
9628 (setq path (replace-match "+" t t path)))
9629 (throw 'match t)))
9630 (when (org-in-regexp "<\\([^><\n]+\\)>")
9631 (setq type "tree-match"
9632 path (match-string 1))
9633 (throw 'match t)))
9634 (unless path
9635 (error "No link found"))
9637 ;; switch back to reference buffer
9638 ;; needed when if called in a temporary buffer through
9639 ;; org-open-link-from-string
9640 (with-current-buffer (or reference-buffer (current-buffer))
9642 ;; Remove any trailing spaces in path
9643 (if (string-match " +\\'" path)
9644 (setq path (replace-match "" t t path)))
9645 (if (and org-link-translation-function
9646 (fboundp org-link-translation-function))
9647 ;; Check if we need to translate the link
9648 (let ((tmp (funcall org-link-translation-function type path)))
9649 (setq type (car tmp) path (cdr tmp))))
9651 (cond
9653 ((assoc type org-link-protocols)
9654 (funcall (nth 1 (assoc type org-link-protocols)) path))
9656 ((equal type "mailto")
9657 (let ((cmd (car org-link-mailto-program))
9658 (args (cdr org-link-mailto-program)) args1
9659 (address path) (subject "") a)
9660 (if (string-match "\\(.*\\)::\\(.*\\)" path)
9661 (setq address (match-string 1 path)
9662 subject (org-link-escape (match-string 2 path))))
9663 (while args
9664 (cond
9665 ((not (stringp (car args))) (push (pop args) args1))
9666 (t (setq a (pop args))
9667 (if (string-match "%a" a)
9668 (setq a (replace-match address t t a)))
9669 (if (string-match "%s" a)
9670 (setq a (replace-match subject t t a)))
9671 (push a args1))))
9672 (apply cmd (nreverse args1))))
9674 ((member type '("http" "https" "ftp" "news"))
9675 (browse-url (concat type ":" (if (org-string-match-p "[[:nonascii:] ]" path)
9676 (org-link-escape
9677 path org-link-escape-chars-browser)
9678 path))))
9680 ((string= type "doi")
9681 (browse-url (concat "http://dx.doi.org/" (if (org-string-match-p "[[:nonascii:] ]" path)
9682 (org-link-escape
9683 path org-link-escape-chars-browser)
9684 path))))
9686 ((member type '("message"))
9687 (browse-url (concat type ":" path)))
9689 ((string= type "tags")
9690 (org-tags-view arg path))
9692 ((string= type "tree-match")
9693 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
9695 ((string= type "file")
9696 (if (string-match "::\\([0-9]+\\)\\'" path)
9697 (setq line (string-to-number (match-string 1 path))
9698 path (substring path 0 (match-beginning 0)))
9699 (if (string-match "::\\(.+\\)\\'" path)
9700 (setq search (match-string 1 path)
9701 path (substring path 0 (match-beginning 0)))))
9702 (if (string-match "[*?{]" (file-name-nondirectory path))
9703 (dired path)
9704 (org-open-file path arg line search)))
9706 ((string= type "shell")
9707 (let ((cmd path))
9708 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
9709 (string-match org-confirm-shell-link-not-regexp cmd))
9710 (not org-confirm-shell-link-function)
9711 (funcall org-confirm-shell-link-function
9712 (format "Execute \"%s\" in shell? "
9713 (org-add-props cmd nil
9714 'face 'org-warning))))
9715 (progn
9716 (message "Executing %s" cmd)
9717 (shell-command cmd))
9718 (error "Abort"))))
9720 ((string= type "elisp")
9721 (let ((cmd path))
9722 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
9723 (string-match org-confirm-elisp-link-not-regexp cmd))
9724 (not org-confirm-elisp-link-function)
9725 (funcall org-confirm-elisp-link-function
9726 (format "Execute \"%s\" as elisp? "
9727 (org-add-props cmd nil
9728 'face 'org-warning))))
9729 (message "%s => %s" cmd
9730 (if (equal (string-to-char cmd) ?\()
9731 (eval (read cmd))
9732 (call-interactively (read cmd))))
9733 (error "Abort"))))
9735 ((and (string= type "thisfile")
9736 (run-hook-with-args-until-success
9737 'org-open-link-functions path)))
9739 ((string= type "thisfile")
9740 (if arg
9741 (switch-to-buffer-other-window
9742 (org-get-buffer-for-internal-link (current-buffer)))
9743 (org-mark-ring-push))
9744 (let ((cmd `(org-link-search
9745 ,path
9746 ,(cond ((equal arg '(4)) ''occur)
9747 ((equal arg '(16)) ''org-occur)
9748 (t nil))
9749 ,pos)))
9750 (condition-case nil (let ((org-link-search-inhibit-query t))
9751 (eval cmd))
9752 (error (progn (widen) (eval cmd))))))
9755 (browse-url-at-point)))))))
9756 (move-marker org-open-link-marker nil)
9757 (run-hook-with-args 'org-follow-link-hook)))
9759 (defun org-offer-links-in-entry (&optional nth zero)
9760 "Offer links in the current entry and follow the selected link.
9761 If there is only one link, follow it immediately as well.
9762 If NTH is an integer, immediately pick the NTH link found.
9763 If ZERO is a string, check also this string for a link, and if
9764 there is one, offer it as link number zero."
9765 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
9766 "\\(" org-angle-link-re "\\)\\|"
9767 "\\(" org-plain-link-re "\\)"))
9768 (cnt ?0)
9769 (in-emacs (if (integerp nth) nil nth))
9770 have-zero end links link c)
9771 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
9772 (push (match-string 0 zero) links)
9773 (setq cnt (1- cnt) have-zero t))
9774 (save-excursion
9775 (org-back-to-heading t)
9776 (setq end (save-excursion (outline-next-heading) (point)))
9777 (while (re-search-forward re end t)
9778 (push (match-string 0) links))
9779 (setq links (org-uniquify (reverse links))))
9781 (cond
9782 ((null links)
9783 (message "No links"))
9784 ((equal (length links) 1)
9785 (setq link (list (car links))))
9786 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
9787 (setq link (list (nth (if have-zero nth (1- nth)) links))))
9788 (t ; we have to select a link
9789 (save-excursion
9790 (save-window-excursion
9791 (delete-other-windows)
9792 (with-output-to-temp-buffer "*Select Link*"
9793 (mapc (lambda (l)
9794 (if (not (string-match org-bracket-link-regexp l))
9795 (princ (format "[%c] %s\n" (incf cnt)
9796 (org-remove-angle-brackets l)))
9797 (if (match-end 3)
9798 (princ (format "[%c] %s (%s)\n" (incf cnt)
9799 (match-string 3 l) (match-string 1 l)))
9800 (princ (format "[%c] %s\n" (incf cnt)
9801 (match-string 1 l))))))
9802 links))
9803 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
9804 (message "Select link to open, RET to open all:")
9805 (setq c (read-char-exclusive))
9806 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
9807 (when (equal c ?q) (error "Abort"))
9808 (if (equal c ?\C-m)
9809 (setq link links)
9810 (setq nth (- c ?0))
9811 (if have-zero (setq nth (1+ nth)))
9812 (unless (and (integerp nth) (>= (length links) nth))
9813 (error "Invalid link selection"))
9814 (setq link (list (nth (1- nth) links))))))
9815 (if link
9816 (let ((buf (current-buffer)))
9817 (dolist (l link)
9818 (org-open-link-from-string l in-emacs buf))
9820 nil)))
9822 ;; Add special file links that specify the way of opening
9824 (org-add-link-type "file+sys" 'org-open-file-with-system)
9825 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
9826 (defun org-open-file-with-system (path)
9827 "Open file at PATH using the system way of opening it."
9828 (org-open-file path 'system))
9829 (defun org-open-file-with-emacs (path)
9830 "Open file at PATH in Emacs."
9831 (org-open-file path 'emacs))
9832 (defun org-remove-file-link-modifiers ()
9833 "Remove the file link modifiers in `file+sys:' and `file+emacs:' links."
9834 (goto-char (point-min))
9835 (while (re-search-forward "\\<file\\+\\(sys\\|emacs\\):" nil t)
9836 (org-if-unprotected
9837 (replace-match "file:" t t))))
9838 (eval-after-load "org-exp"
9839 '(add-hook 'org-export-preprocess-before-normalizing-links-hook
9840 'org-remove-file-link-modifiers))
9842 ;;;; Time estimates
9844 (defun org-get-effort (&optional pom)
9845 "Get the effort estimate for the current entry."
9846 (org-entry-get pom org-effort-property))
9848 ;;; File search
9850 (defvar org-create-file-search-functions nil
9851 "List of functions to construct the right search string for a file link.
9852 These functions are called in turn with point at the location to
9853 which the link should point.
9855 A function in the hook should first test if it would like to
9856 handle this file type, for example by checking the `major-mode'
9857 or the file extension. If it decides not to handle this file, it
9858 should just return nil to give other functions a chance. If it
9859 does handle the file, it must return the search string to be used
9860 when following the link. The search string will be part of the
9861 file link, given after a double colon, and `org-open-at-point'
9862 will automatically search for it. If special measures must be
9863 taken to make the search successful, another function should be
9864 added to the companion hook `org-execute-file-search-functions',
9865 which see.
9867 A function in this hook may also use `setq' to set the variable
9868 `description' to provide a suggestion for the descriptive text to
9869 be used for this link when it gets inserted into an Org-mode
9870 buffer with \\[org-insert-link].")
9872 (defvar org-execute-file-search-functions nil
9873 "List of functions to execute a file search triggered by a link.
9875 Functions added to this hook must accept a single argument, the
9876 search string that was part of the file link, the part after the
9877 double colon. The function must first check if it would like to
9878 handle this search, for example by checking the `major-mode' or
9879 the file extension. If it decides not to handle this search, it
9880 should just return nil to give other functions a chance. If it
9881 does handle the search, it must return a non-nil value to keep
9882 other functions from trying.
9884 Each function can access the current prefix argument through the
9885 variable `current-prefix-argument'. Note that a single prefix is
9886 used to force opening a link in Emacs, so it may be good to only
9887 use a numeric or double prefix to guide the search function.
9889 In case this is needed, a function in this hook can also restore
9890 the window configuration before `org-open-at-point' was called using:
9892 (set-window-configuration org-window-config-before-follow-link)")
9894 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
9895 (defun org-link-search (s &optional type avoid-pos stealth)
9896 "Search for a link search option.
9897 If S is surrounded by forward slashes, it is interpreted as a
9898 regular expression. In org-mode files, this will create an `org-occur'
9899 sparse tree. In ordinary files, `occur' will be used to list matches.
9900 If the current buffer is in `dired-mode', grep will be used to search
9901 in all files. If AVOID-POS is given, ignore matches near that position.
9903 When optional argument STEALTH is non-nil, do not modify
9904 visibility around point, thus ignoring
9905 `org-show-hierarchy-above', `org-show-following-heading' and
9906 `org-show-siblings' variables."
9907 (let ((case-fold-search t)
9908 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
9909 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
9910 (append '(("") (" ") ("\t") ("\n"))
9911 org-emphasis-alist)
9912 "\\|") "\\)"))
9913 (pos (point))
9914 (pre nil) (post nil)
9915 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
9916 (cond
9917 ;; First check if there are any special search functions
9918 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
9919 ;; Now try the builtin stuff
9920 ((and (equal (string-to-char s0) ?#)
9921 (> (length s0) 1)
9922 (save-excursion
9923 (goto-char (point-min))
9924 (and
9925 (re-search-forward
9926 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
9927 (setq type 'dedicated
9928 pos (match-beginning 0))))
9929 ;; There is an exact target for this
9930 (goto-char pos)
9931 (org-back-to-heading t)))
9932 ((save-excursion
9933 (goto-char (point-min))
9934 (and
9935 (re-search-forward
9936 (concat "<<" (regexp-quote s0) ">>") nil t)
9937 (setq type 'dedicated
9938 pos (match-beginning 0))))
9939 ;; There is an exact target for this
9940 (goto-char pos))
9941 ((save-excursion
9942 (goto-char (point-min))
9943 (and
9944 (re-search-forward
9945 (format "^[ \t]*#\\+TARGET: %s" (regexp-quote s0)) nil t)
9946 (setq type 'dedicated pos (match-beginning 0))))
9947 ;; Found an invisible target.
9948 (goto-char pos))
9949 ((save-excursion
9950 (goto-char (point-min))
9951 (and
9952 (re-search-forward
9953 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
9954 (setq type 'dedicated pos (match-beginning 0))))
9955 ;; Found an element with a matching #+name affiliated keyword.
9956 (goto-char pos))
9957 ((and (string-match "^(\\(.*\\))$" s0)
9958 (save-excursion
9959 (goto-char (point-min))
9960 (and
9961 (re-search-forward
9962 (concat "[^[]" (regexp-quote
9963 (format org-coderef-label-format
9964 (match-string 1 s0))))
9965 nil t)
9966 (setq type 'dedicated
9967 pos (1+ (match-beginning 0))))))
9968 ;; There is a coderef target for this
9969 (goto-char pos))
9970 ((string-match "^/\\(.*\\)/$" s)
9971 ;; A regular expression
9972 (cond
9973 ((derived-mode-p 'org-mode)
9974 (org-occur (match-string 1 s)))
9975 ;;((eq major-mode 'dired-mode)
9976 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
9977 (t (org-do-occur (match-string 1 s)))))
9978 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
9979 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
9980 (goto-char (point-min))
9981 (cond
9982 ((let (case-fold-search)
9983 (re-search-forward (format org-complex-heading-regexp-format
9984 (regexp-quote s))
9985 nil t))
9986 ;; OK, found a match
9987 (setq type 'dedicated)
9988 (goto-char (match-beginning 0)))
9989 ((and (not org-link-search-inhibit-query)
9990 (eq org-link-search-must-match-exact-headline 'query-to-create)
9991 (y-or-n-p "No match - create this as a new heading? "))
9992 (goto-char (point-max))
9993 (or (bolp) (newline))
9994 (insert "* " s "\n")
9995 (beginning-of-line 0))
9997 (goto-char pos)
9998 (error "No match"))))
10000 ;; A normal search string
10001 (when (equal (string-to-char s) ?*)
10002 ;; Anchor on headlines, post may include tags.
10003 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10004 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10005 s (substring s 1)))
10006 (remove-text-properties
10007 0 (length s)
10008 '(face nil mouse-face nil keymap nil fontified nil) s)
10009 ;; Make a series of regular expressions to find a match
10010 (setq words (org-split-string s "[ \n\r\t]+")
10012 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10013 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10014 "\\)" markers)
10015 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
10016 re2a (concat "[ \t\r\n]" re2a_)
10017 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10018 re4 (concat "[^a-zA-Z_]" re4_)
10020 re1 (concat pre re2 post)
10021 re3 (concat pre (if pre re4_ re4) post)
10022 re5 (concat pre ".*" re4)
10023 re2 (concat pre re2)
10024 re2a (concat pre (if pre re2a_ re2a))
10025 re4 (concat pre (if pre re4_ re4))
10026 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10027 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10028 re5 "\\)"
10030 (cond
10031 ((eq type 'org-occur) (org-occur reall))
10032 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10033 (t (goto-char (point-min))
10034 (setq type 'fuzzy)
10035 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
10036 (org-search-not-self 1 re1 nil t)
10037 (org-search-not-self 1 re2 nil t)
10038 (org-search-not-self 1 re2a nil t)
10039 (org-search-not-self 1 re3 nil t)
10040 (org-search-not-self 1 re4 nil t)
10041 (org-search-not-self 1 re5 nil t)
10043 (goto-char (match-beginning 1))
10044 (goto-char pos)
10045 (error "No match"))))))
10046 (and (derived-mode-p 'org-mode)
10047 (not stealth)
10048 (org-show-context 'link-search))
10049 type))
10051 (defun org-search-not-self (group &rest args)
10052 "Execute `re-search-forward', but only accept matches that do not
10053 enclose the position of `org-open-link-marker'."
10054 (let ((m org-open-link-marker))
10055 (catch 'exit
10056 (while (apply 're-search-forward args)
10057 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10058 (goto-char (match-end group))
10059 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10060 (> (match-beginning 0) (marker-position m))
10061 (< (match-end 0) (marker-position m)))
10062 (save-match-data
10063 (or (not (org-in-regexp
10064 org-bracket-link-analytic-regexp 1))
10065 (not (match-end 4)) ; no description
10066 (and (<= (match-beginning 4) (point))
10067 (>= (match-end 4) (point))))))
10068 (throw 'exit (point))))))))
10070 (defun org-get-buffer-for-internal-link (buffer)
10071 "Return a buffer to be used for displaying the link target of internal links."
10072 (cond
10073 ((not org-display-internal-link-with-indirect-buffer)
10074 buffer)
10075 ((string-match "(Clone)$" (buffer-name buffer))
10076 (message "Buffer is already a clone, not making another one")
10077 ;; we also do not modify visibility in this case
10078 buffer)
10079 (t ; make a new indirect buffer for displaying the link
10080 (let* ((bn (buffer-name buffer))
10081 (ibn (concat bn "(Clone)"))
10082 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10083 (with-current-buffer ib (org-overview))
10084 ib))))
10086 (defun org-do-occur (regexp &optional cleanup)
10087 "Call the Emacs command `occur'.
10088 If CLEANUP is non-nil, remove the printout of the regular expression
10089 in the *Occur* buffer. This is useful if the regex is long and not useful
10090 to read."
10091 (occur regexp)
10092 (when cleanup
10093 (let ((cwin (selected-window)) win beg end)
10094 (when (setq win (get-buffer-window "*Occur*"))
10095 (select-window win))
10096 (goto-char (point-min))
10097 (when (re-search-forward "match[a-z]+" nil t)
10098 (setq beg (match-end 0))
10099 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10100 (setq end (1- (match-beginning 0)))))
10101 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10102 (goto-char (point-min))
10103 (select-window cwin))))
10105 ;;; The mark ring for links jumps
10107 (defvar org-mark-ring nil
10108 "Mark ring for positions before jumps in Org-mode.")
10109 (defvar org-mark-ring-last-goto nil
10110 "Last position in the mark ring used to go back.")
10111 ;; Fill and close the ring
10112 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10113 (loop for i from 1 to org-mark-ring-length do
10114 (push (make-marker) org-mark-ring))
10115 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10116 org-mark-ring)
10118 (defun org-mark-ring-push (&optional pos buffer)
10119 "Put the current position or POS into the mark ring and rotate it."
10120 (interactive)
10121 (setq pos (or pos (point)))
10122 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10123 (move-marker (car org-mark-ring)
10124 (or pos (point))
10125 (or buffer (current-buffer)))
10126 (message "%s"
10127 (substitute-command-keys
10128 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10130 (defun org-mark-ring-goto (&optional n)
10131 "Jump to the previous position in the mark ring.
10132 With prefix arg N, jump back that many stored positions. When
10133 called several times in succession, walk through the entire ring.
10134 Org-mode commands jumping to a different position in the current file,
10135 or to another Org-mode file, automatically push the old position
10136 onto the ring."
10137 (interactive "p")
10138 (let (p m)
10139 (if (eq last-command this-command)
10140 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10141 (setq p org-mark-ring))
10142 (setq org-mark-ring-last-goto p)
10143 (setq m (car p))
10144 (org-pop-to-buffer-same-window (marker-buffer m))
10145 (goto-char m)
10146 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10148 (defun org-remove-angle-brackets (s)
10149 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10150 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10152 (defun org-add-angle-brackets (s)
10153 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10154 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10156 (defun org-remove-double-quotes (s)
10157 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10158 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10161 ;;; Following specific links
10163 (defun org-follow-timestamp-link ()
10164 (cond
10165 ((org-at-date-range-p t)
10166 (let ((org-agenda-start-on-weekday)
10167 (t1 (match-string 1))
10168 (t2 (match-string 2)))
10169 (setq t1 (time-to-days (org-time-string-to-time t1))
10170 t2 (time-to-days (org-time-string-to-time t2)))
10171 (org-agenda-list nil t1 (1+ (- t2 t1)))))
10172 ((org-at-timestamp-p t)
10173 (org-agenda-list nil (time-to-days (org-time-string-to-time
10174 (substring (match-string 1) 0 10)))
10176 (t (error "This should not happen"))))
10179 ;;; Following file links
10180 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10181 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10182 (declare-function mailcap-mime-info
10183 "mailcap" (string &optional request no-decode))
10184 (defvar org-wait nil)
10185 (defun org-open-file (path &optional in-emacs line search)
10186 "Open the file at PATH.
10187 First, this expands any special file name abbreviations. Then the
10188 configuration variable `org-file-apps' is checked if it contains an
10189 entry for this file type, and if yes, the corresponding command is launched.
10191 If no application is found, Emacs simply visits the file.
10193 With optional prefix argument IN-EMACS, Emacs will visit the file.
10194 With a double \\[universal-argument] \\[universal-argument] \
10195 prefix arg, Org tries to avoid opening in Emacs
10196 and to use an external application to visit the file.
10198 Optional LINE specifies a line to go to, optional SEARCH a string
10199 to search for. If LINE or SEARCH is given, the file will be
10200 opened in Emacs, unless an entry from org-file-apps that makes
10201 use of groups in a regexp matches.
10203 If you want to change the way frames are used when following a
10204 link, please customize `org-link-frame-setup'.
10206 If the file does not exist, an error is thrown."
10207 (let* ((file (if (equal path "")
10208 buffer-file-name
10209 (substitute-in-file-name (expand-file-name path))))
10210 (file-apps (append org-file-apps (org-default-apps)))
10211 (apps (org-remove-if
10212 'org-file-apps-entry-match-against-dlink-p file-apps))
10213 (apps-dlink (org-remove-if-not
10214 'org-file-apps-entry-match-against-dlink-p file-apps))
10215 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10216 (dirp (if remp nil (file-directory-p file)))
10217 (file (if (and dirp org-open-directory-means-index-dot-org)
10218 (concat (file-name-as-directory file) "index.org")
10219 file))
10220 (a-m-a-p (assq 'auto-mode apps))
10221 (dfile (downcase file))
10222 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10223 (link (cond ((and (eq line nil)
10224 (eq search nil))
10225 file)
10226 (line
10227 (concat file "::" (number-to-string line)))
10228 (search
10229 (concat file "::" search))))
10230 (dlink (downcase link))
10231 (old-buffer (current-buffer))
10232 (old-pos (point))
10233 (old-mode major-mode)
10234 ext cmd link-match-data)
10235 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10236 (setq ext (match-string 1 dfile))
10237 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10238 (setq ext (match-string 1 dfile))))
10239 (cond
10240 ((member in-emacs '((16) system))
10241 (setq cmd (cdr (assoc 'system apps))))
10242 (in-emacs (setq cmd 'emacs))
10244 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10245 (and dirp (cdr (assoc 'directory apps)))
10246 ; first, try matching against apps-dlink
10247 ; if we get a match here, store the match data for later
10248 (let ((match (assoc-default dlink apps-dlink
10249 'string-match)))
10250 (if match
10251 (progn (setq link-match-data (match-data))
10252 match)
10253 (progn (setq in-emacs (or in-emacs line search))
10254 nil))) ; if we have no match in apps-dlink,
10255 ; always open the file in emacs if line or search
10256 ; is given (for backwards compatibility)
10257 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10258 'string-match)
10259 (cdr (assoc ext apps))
10260 (cdr (assoc t apps))))))
10261 (when (eq cmd 'system)
10262 (setq cmd (cdr (assoc 'system apps))))
10263 (when (eq cmd 'default)
10264 (setq cmd (cdr (assoc t apps))))
10265 (when (eq cmd 'mailcap)
10266 (require 'mailcap)
10267 (mailcap-parse-mailcaps)
10268 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10269 (command (mailcap-mime-info mime-type)))
10270 (if (stringp command)
10271 (setq cmd command)
10272 (setq cmd 'emacs))))
10273 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10274 (not (file-exists-p file))
10275 (not org-open-non-existing-files))
10276 (error "No such file: %s" file))
10277 (cond
10278 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10279 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10280 (while (string-match "['\"]%s['\"]" cmd)
10281 (setq cmd (replace-match "%s" t t cmd)))
10282 (while (string-match "%s" cmd)
10283 (setq cmd (replace-match
10284 (save-match-data
10285 (shell-quote-argument
10286 (convert-standard-filename file)))
10287 t t cmd)))
10289 ;; Replace "%1", "%2" etc. in command with group matches from regex
10290 (save-match-data
10291 (let ((match-index 1)
10292 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10293 (set-match-data link-match-data)
10294 (while (<= match-index number-of-groups)
10295 (let ((regex (concat "%" (number-to-string match-index)))
10296 (replace-with (match-string match-index dlink)))
10297 (while (string-match regex cmd)
10298 (setq cmd (replace-match replace-with t t cmd))))
10299 (setq match-index (+ match-index 1)))))
10301 (save-window-excursion
10302 (start-process-shell-command cmd nil cmd)
10303 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
10305 ((or (stringp cmd)
10306 (eq cmd 'emacs))
10307 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10308 (widen)
10309 (if line (org-goto-line line)
10310 (if search (org-link-search search))))
10311 ((consp cmd)
10312 (let ((file (convert-standard-filename file)))
10313 (save-match-data
10314 (set-match-data link-match-data)
10315 (eval cmd))))
10316 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10317 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
10318 (or (not (equal old-buffer (current-buffer)))
10319 (not (equal old-pos (point))))
10320 (org-mark-ring-push old-pos old-buffer))))
10322 (defun org-file-apps-entry-match-against-dlink-p (entry)
10323 "This function returns non-nil if `entry' uses a regular
10324 expression which should be matched against the whole link by
10325 org-open-file.
10327 It assumes that is the case when the entry uses a regular
10328 expression which has at least one grouping construct and the
10329 action is either a lisp form or a command string containing
10330 '%1', i.e. using at least one subexpression match as a
10331 parameter."
10332 (let ((selector (car entry))
10333 (action (cdr entry)))
10334 (if (stringp selector)
10335 (and (> (regexp-opt-depth selector) 0)
10336 (or (and (stringp action)
10337 (string-match "%[0-9]" action))
10338 (consp action)))
10339 nil)))
10341 (defun org-default-apps ()
10342 "Return the default applications for this operating system."
10343 (cond
10344 ((eq system-type 'darwin)
10345 org-file-apps-defaults-macosx)
10346 ((eq system-type 'windows-nt)
10347 org-file-apps-defaults-windowsnt)
10348 (t org-file-apps-defaults-gnu)))
10350 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10351 "Convert extensions to regular expressions in the cars of LIST.
10352 Also, weed out any non-string entries, because the return value is used
10353 only for regexp matching.
10354 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10355 point to the symbol `emacs', indicating that the file should
10356 be opened in Emacs."
10357 (append
10358 (delq nil
10359 (mapcar (lambda (x)
10360 (if (not (stringp (car x)))
10362 (if (string-match "\\W" (car x))
10364 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10365 list))
10366 (if add-auto-mode
10367 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10369 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10370 (defun org-file-remote-p (file)
10371 "Test whether FILE specifies a location on a remote system.
10372 Return non-nil if the location is indeed remote.
10374 For example, the filename \"/user@host:/foo\" specifies a location
10375 on the system \"/user@host:\"."
10376 (cond ((fboundp 'file-remote-p)
10377 (file-remote-p file))
10378 ((fboundp 'tramp-handle-file-remote-p)
10379 (tramp-handle-file-remote-p file))
10380 ((and (boundp 'ange-ftp-name-format)
10381 (string-match (car ange-ftp-name-format) file))
10383 (t nil)))
10386 ;;;; Refiling
10388 (defun org-get-org-file ()
10389 "Read a filename, with default directory `org-directory'."
10390 (let ((default (or org-default-notes-file remember-data-file)))
10391 (read-file-name (format "File name [%s]: " default)
10392 (file-name-as-directory org-directory)
10393 default)))
10395 (defun org-notes-order-reversed-p ()
10396 "Check if the current file should receive notes in reversed order."
10397 (cond
10398 ((not org-reverse-note-order) nil)
10399 ((eq t org-reverse-note-order) t)
10400 ((not (listp org-reverse-note-order)) nil)
10401 (t (catch 'exit
10402 (let ((all org-reverse-note-order)
10403 entry)
10404 (while (setq entry (pop all))
10405 (if (string-match (car entry) buffer-file-name)
10406 (throw 'exit (cdr entry))))
10407 nil)))))
10409 (defvar org-refile-target-table nil
10410 "The list of refile targets, created by `org-refile'.")
10412 (defvar org-agenda-new-buffers nil
10413 "Buffers created to visit agenda files.")
10415 (defvar org-refile-cache nil
10416 "Cache for refile targets.")
10418 (defvar org-refile-markers nil
10419 "All the markers used for caching refile locations.")
10421 (defun org-refile-marker (pos)
10422 "Get a new refile marker, but only if caching is in use."
10423 (if (not org-refile-use-cache)
10425 (let ((m (make-marker)))
10426 (move-marker m pos)
10427 (push m org-refile-markers)
10428 m)))
10430 (defun org-refile-cache-clear ()
10431 "Clear the refile cache and disable all the markers."
10432 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
10433 (setq org-refile-markers nil)
10434 (setq org-refile-cache nil)
10435 (message "Refile cache has been cleared"))
10437 (defun org-refile-cache-check-set (set)
10438 "Check if all the markers in the cache still have live buffers."
10439 (let (marker)
10440 (catch 'exit
10441 (while (and set (setq marker (nth 3 (pop set))))
10442 ;; if org-refile-use-outline-path is 'file, marker may be nil
10443 (when (and marker (null (marker-buffer marker)))
10444 (message "not found") (sit-for 3)
10445 (throw 'exit nil)))
10446 t)))
10448 (defun org-refile-cache-put (set &rest identifiers)
10449 "Push the refile targets SET into the cache, under IDENTIFIERS."
10450 (let* ((key (sha1 (prin1-to-string identifiers)))
10451 (entry (assoc key org-refile-cache)))
10452 (if entry
10453 (setcdr entry set)
10454 (push (cons key set) org-refile-cache))))
10456 (defun org-refile-cache-get (&rest identifiers)
10457 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10458 (cond
10459 ((not org-refile-cache) nil)
10460 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10462 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10463 org-refile-cache))))
10464 (and set (org-refile-cache-check-set set) set)))))
10466 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
10467 "Produce a table with refile targets."
10468 (let ((case-fold-search nil)
10469 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10470 (entries (or org-refile-targets '((nil . (:level . 1)))))
10471 targets tgs txt re files f desc descre fast-path-p level pos0)
10472 (message "Getting targets...")
10473 (with-current-buffer (or default-buffer (current-buffer))
10474 (while (setq entry (pop entries))
10475 (setq files (car entry) desc (cdr entry))
10476 (setq fast-path-p nil)
10477 (cond
10478 ((null files) (setq files (list (current-buffer))))
10479 ((eq files 'org-agenda-files)
10480 (setq files (org-agenda-files 'unrestricted)))
10481 ((and (symbolp files) (fboundp files))
10482 (setq files (funcall files)))
10483 ((and (symbolp files) (boundp files))
10484 (setq files (symbol-value files))))
10485 (if (stringp files) (setq files (list files)))
10486 (cond
10487 ((eq (car desc) :tag)
10488 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
10489 ((eq (car desc) :todo)
10490 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
10491 ((eq (car desc) :regexp)
10492 (setq descre (cdr desc)))
10493 ((eq (car desc) :level)
10494 (setq descre (concat "^\\*\\{" (number-to-string
10495 (if org-odd-levels-only
10496 (1- (* 2 (cdr desc)))
10497 (cdr desc)))
10498 "\\}[ \t]")))
10499 ((eq (car desc) :maxlevel)
10500 (setq fast-path-p t)
10501 (setq descre (concat "^\\*\\{1," (number-to-string
10502 (if org-odd-levels-only
10503 (1- (* 2 (cdr desc)))
10504 (cdr desc)))
10505 "\\}[ \t]")))
10506 (t (error "Bad refiling target description %s" desc)))
10507 (while (setq f (pop files))
10508 (with-current-buffer
10509 (if (bufferp f) f (org-get-agenda-file-buffer f))
10511 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
10512 (progn
10513 (if (bufferp f) (setq f (buffer-file-name
10514 (buffer-base-buffer f))))
10515 (setq f (and f (expand-file-name f)))
10516 (if (eq org-refile-use-outline-path 'file)
10517 (push (list (file-name-nondirectory f) f nil nil) tgs))
10518 (save-excursion
10519 (save-restriction
10520 (widen)
10521 (goto-char (point-min))
10522 (while (re-search-forward descre nil t)
10523 (goto-char (setq pos0 (point-at-bol)))
10524 (catch 'next
10525 (when org-refile-target-verify-function
10526 (save-match-data
10527 (or (funcall org-refile-target-verify-function)
10528 (throw 'next t))))
10529 (when (and (looking-at org-complex-heading-regexp)
10530 (not (member (match-string 4) excluded-entries))
10531 (match-string 4))
10532 (setq level (org-reduced-level
10533 (- (match-end 1) (match-beginning 1)))
10534 txt (org-link-display-format (match-string 4))
10535 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
10536 re (format org-complex-heading-regexp-format
10537 (regexp-quote (match-string 4))))
10538 (when org-refile-use-outline-path
10539 (setq txt (mapconcat
10540 'org-protect-slash
10541 (append
10542 (if (eq org-refile-use-outline-path
10543 'file)
10544 (list (file-name-nondirectory
10545 (buffer-file-name
10546 (buffer-base-buffer))))
10547 (if (eq org-refile-use-outline-path
10548 'full-file-path)
10549 (list (buffer-file-name
10550 (buffer-base-buffer)))))
10551 (org-get-outline-path fast-path-p
10552 level txt)
10553 (list txt))
10554 "/")))
10555 (push (list txt f re (org-refile-marker (point)))
10556 tgs)))
10557 (when (= (point) pos0)
10558 ;; verification function has not moved point
10559 (goto-char (point-at-eol))))))))
10560 (when org-refile-use-cache
10561 (org-refile-cache-put tgs (buffer-file-name) descre))
10562 (setq targets (append tgs targets))
10563 ))))
10564 (message "Getting targets...done")
10565 (nreverse targets)))
10567 (defun org-protect-slash (s)
10568 (while (string-match "/" s)
10569 (setq s (replace-match "\\" t t s)))
10572 (defvar org-olpa (make-vector 20 nil))
10574 (defun org-get-outline-path (&optional fastp level heading)
10575 "Return the outline path to the current entry, as a list.
10577 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
10578 routine which makes outline path derivations for an entire file,
10579 avoiding backtracing. Refile target collection makes use of that."
10580 (if fastp
10581 (progn
10582 (if (> level 19)
10583 (error "Outline path failure, more than 19 levels"))
10584 (loop for i from level upto 19 do
10585 (aset org-olpa i nil))
10586 (prog1
10587 (delq nil (append org-olpa nil))
10588 (aset org-olpa level heading)))
10589 (let (rtn case-fold-search)
10590 (save-excursion
10591 (save-restriction
10592 (widen)
10593 (while (org-up-heading-safe)
10594 (when (looking-at org-complex-heading-regexp)
10595 (push (org-match-string-no-properties 4) rtn)))
10596 rtn)))))
10598 (defun org-format-outline-path (path &optional width prefix)
10599 "Format the outline path PATH for display.
10600 Width is the maximum number of characters that is available.
10601 Prefix is a prefix to be included in the returned string,
10602 such as the file name."
10603 (setq width (or width 79))
10604 (if prefix (setq width (- width (length prefix))))
10605 (if (not path)
10606 (or prefix "")
10607 (let* ((nsteps (length path))
10608 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
10609 (maxwidth (if (<= total-width width)
10610 10000 ;; everything fits
10611 ;; we need to shorten the level headings
10612 (/ (- width nsteps) nsteps)))
10613 (org-odd-levels-only nil)
10614 (n 0)
10615 (total (1+ (length prefix))))
10616 (setq maxwidth (max maxwidth 10))
10617 (concat prefix
10618 (mapconcat
10619 (lambda (h)
10620 (setq n (1+ n))
10621 (if (and (= n nsteps) (< maxwidth 10000))
10622 (setq maxwidth (- total-width total)))
10623 (if (< (length h) maxwidth)
10624 (progn (setq total (+ total (length h) 1)) h)
10625 (setq h (substring h 0 (- maxwidth 2))
10626 total (+ total maxwidth 1))
10627 (if (string-match "[ \t]+\\'" h)
10628 (setq h (substring h 0 (match-beginning 0))))
10629 (setq h (concat h "..")))
10630 (org-add-props h nil 'face
10631 (nth (% (1- n) org-n-level-faces)
10632 org-level-faces))
10634 path "/")))))
10636 (defun org-display-outline-path (&optional file current)
10637 "Display the current outline path in the echo area."
10638 (interactive "P")
10639 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
10640 (case-fold-search nil)
10641 (path (and (derived-mode-p 'org-mode) (org-get-outline-path))))
10642 (if current (setq path (append path
10643 (save-excursion
10644 (org-back-to-heading t)
10645 (if (looking-at org-complex-heading-regexp)
10646 (list (match-string 4)))))))
10647 (message "%s"
10648 (org-format-outline-path
10649 path
10650 (1- (frame-width))
10651 (and file bfn (concat (file-name-nondirectory bfn) "/"))))))
10653 (defvar org-refile-history nil
10654 "History for refiling operations.")
10656 (defvar org-after-refile-insert-hook nil
10657 "Hook run after `org-refile' has inserted its stuff at the new location.
10658 Note that this is still *before* the stuff will be removed from
10659 the *old* location.")
10661 (defvar org-capture-last-stored-marker)
10662 (defun org-refile (&optional goto default-buffer rfloc)
10663 "Move the entry or entries at point to another heading.
10664 The list of target headings is compiled using the information in
10665 `org-refile-targets', which see.
10667 At the target location, the entry is filed as a subitem of the target
10668 heading. Depending on `org-reverse-note-order', the new subitem will
10669 either be the first or the last subitem.
10671 If there is an active region, all entries in that region will be moved.
10672 However, the region must fulfill the requirement that the first heading
10673 is the first one sets the top-level of the moved text - at most siblings
10674 below it are allowed.
10676 With prefix arg GOTO, the command will only visit the target location
10677 and not actually move anything.
10679 With a double prefix arg \\[universal-argument] \\[universal-argument], \
10680 go to the location where the last refiling operation has put the subtree.
10681 With a prefix argument of `2', refile to the running clock.
10683 RFLOC can be a refile location obtained in a different way.
10685 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
10687 If you are using target caching (see `org-refile-use-cache'),
10688 You have to clear the target cache in order to find new targets.
10689 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
10690 prefix argument (`C-u C-u C-u C-c C-w')."
10692 (interactive "P")
10693 (if (member goto '(0 (64)))
10694 (org-refile-cache-clear)
10695 (let* ((cbuf (current-buffer))
10696 (regionp (org-region-active-p))
10697 (region-start (and regionp (region-beginning)))
10698 (region-end (and regionp (region-end)))
10699 (region-length (and regionp (- region-end region-start)))
10700 (filename (buffer-file-name (buffer-base-buffer cbuf)))
10701 pos it nbuf file re level reversed)
10702 (setq last-command nil)
10703 (when regionp
10704 (goto-char region-start)
10705 (or (bolp) (goto-char (point-at-bol)))
10706 (setq region-start (point))
10707 (unless (or (org-kill-is-subtree-p
10708 (buffer-substring region-start region-end))
10709 (prog1 org-refile-active-region-within-subtree
10710 (org-toggle-heading)))
10711 (error "The region is not a (sequence of) subtree(s)")))
10712 (if (equal goto '(16))
10713 (org-refile-goto-last-stored)
10714 (when (or
10715 (and (equal goto 2)
10716 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
10717 (prog1
10718 (setq it (list (or org-clock-heading "running clock")
10719 (buffer-file-name
10720 (marker-buffer org-clock-hd-marker))
10722 (marker-position org-clock-hd-marker)))
10723 (setq goto nil)))
10724 (setq it (or rfloc
10725 (let (heading-text)
10726 (save-excursion
10727 (unless goto
10728 (org-back-to-heading t)
10729 (setq heading-text
10730 (nth 4 (org-heading-components))))
10731 (org-refile-get-location
10732 (cond (goto "Goto")
10733 (regionp "Refile region to")
10734 (t (concat "Refile subtree \""
10735 heading-text "\" to")))
10736 default-buffer
10737 (and (not (equal '(4) goto))
10738 org-refile-allow-creating-parent-nodes)
10739 goto))))))
10740 (setq file (nth 1 it)
10741 re (nth 2 it)
10742 pos (nth 3 it))
10743 (if (and (not goto)
10745 (equal (buffer-file-name) file)
10746 (if regionp
10747 (and (>= pos region-start)
10748 (<= pos region-end))
10749 (and (>= pos (point))
10750 (< pos (save-excursion
10751 (org-end-of-subtree t t))))))
10752 (error "Cannot refile to position inside the tree or region"))
10754 (setq nbuf (or (find-buffer-visiting file)
10755 (find-file-noselect file)))
10756 (if goto
10757 (progn
10758 (org-pop-to-buffer-same-window nbuf)
10759 (goto-char pos)
10760 (org-show-context 'org-goto))
10761 (if regionp
10762 (progn
10763 (org-kill-new (buffer-substring region-start region-end))
10764 (org-save-markers-in-region region-start region-end))
10765 (org-copy-subtree 1 nil t))
10766 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
10767 (find-file-noselect file)))
10768 (setq reversed (org-notes-order-reversed-p))
10769 (save-excursion
10770 (save-restriction
10771 (widen)
10772 (if pos
10773 (progn
10774 (goto-char pos)
10775 (looking-at org-outline-regexp)
10776 (setq level (org-get-valid-level (funcall outline-level) 1))
10777 (goto-char
10778 (if reversed
10779 (or (outline-next-heading) (point-max))
10780 (or (save-excursion (org-get-next-sibling))
10781 (org-end-of-subtree t t)
10782 (point-max)))))
10783 (setq level 1)
10784 (if (not reversed)
10785 (goto-char (point-max))
10786 (goto-char (point-min))
10787 (or (outline-next-heading) (goto-char (point-max)))))
10788 (if (not (bolp)) (newline))
10789 (org-paste-subtree level)
10790 (when org-log-refile
10791 (org-add-log-setup 'refile nil nil 'findpos
10792 org-log-refile)
10793 (unless (eq org-log-refile 'note)
10794 (save-excursion (org-add-log-note))))
10795 (and org-auto-align-tags (org-set-tags nil t))
10796 (bookmark-set "org-refile-last-stored")
10797 ;; If we are refiling for capture, make sure that the
10798 ;; last-capture pointers point here
10799 (when (org-bound-and-true-p org-refile-for-capture)
10800 (bookmark-set "org-capture-last-stored-marker")
10801 (move-marker org-capture-last-stored-marker (point)))
10802 (if (fboundp 'deactivate-mark) (deactivate-mark))
10803 (run-hooks 'org-after-refile-insert-hook))))
10804 (if regionp
10805 (delete-region (point) (+ (point) region-length))
10806 (org-cut-subtree))
10807 (when (featurep 'org-inlinetask)
10808 (org-inlinetask-remove-END-maybe))
10809 (setq org-markers-to-move nil)
10810 (message "Refiled to \"%s\" in file %s" (car it) file)))))))
10812 (defun org-refile-goto-last-stored ()
10813 "Go to the location where the last refile was stored."
10814 (interactive)
10815 (bookmark-jump "org-refile-last-stored")
10816 (message "This is the location of the last refile"))
10818 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
10819 no-exclude)
10820 "Prompt the user for a refile location, using PROMPT.
10821 PROMPT should not be suffixed with a colon and a space, because
10822 this function appends the default value from
10823 `org-refile-history' automatically, if that is not empty.
10824 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
10825 this is used for the GOTO interface."
10826 (let ((org-refile-targets org-refile-targets)
10827 (org-refile-use-outline-path org-refile-use-outline-path)
10828 excluded-entries)
10829 (when (and (derived-mode-p 'org-mode)
10830 (not org-refile-use-cache)
10831 (not no-exclude))
10832 (org-map-tree
10833 (lambda()
10834 (setq excluded-entries
10835 (append excluded-entries (list (org-get-heading t t)))))))
10836 (setq org-refile-target-table
10837 (org-refile-get-targets default-buffer excluded-entries)))
10838 (unless org-refile-target-table
10839 (error "No refile targets"))
10840 (let* ((prompt (concat prompt
10841 (and (car org-refile-history)
10842 (concat " (default " (car org-refile-history) ")"))
10843 ": "))
10844 (cbuf (current-buffer))
10845 (partial-completion-mode nil)
10846 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
10847 (cfunc (if (and org-refile-use-outline-path
10848 org-outline-path-complete-in-steps)
10849 'org-olpath-completing-read
10850 'org-icompleting-read))
10851 (extra (if org-refile-use-outline-path "/" ""))
10852 (filename (and cfn (expand-file-name cfn)))
10853 (tbl (mapcar
10854 (lambda (x)
10855 (if (and (not (member org-refile-use-outline-path
10856 '(file full-file-path)))
10857 (not (equal filename (nth 1 x))))
10858 (cons (concat (car x) extra " ("
10859 (file-name-nondirectory (nth 1 x)) ")")
10860 (cdr x))
10861 (cons (concat (car x) extra) (cdr x))))
10862 org-refile-target-table))
10863 (completion-ignore-case t)
10864 pa answ parent-target child parent old-hist)
10865 (setq old-hist org-refile-history)
10866 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
10867 nil 'org-refile-history (car org-refile-history)))
10868 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
10869 (org-refile-check-position pa)
10870 (if pa
10871 (progn
10872 (when (or (not org-refile-history)
10873 (not (eq old-hist org-refile-history))
10874 (not (equal (car pa) (car org-refile-history))))
10875 (setq org-refile-history
10876 (cons (car pa) (if (assoc (car org-refile-history) tbl)
10877 org-refile-history
10878 (cdr org-refile-history))))
10879 (if (equal (car org-refile-history) (nth 1 org-refile-history))
10880 (pop org-refile-history)))
10882 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
10883 (progn
10884 (setq parent (match-string 1 answ)
10885 child (match-string 2 answ))
10886 (setq parent-target (or (assoc parent tbl)
10887 (assoc (concat parent "/") tbl)))
10888 (when (and parent-target
10889 (or (eq new-nodes t)
10890 (and (eq new-nodes 'confirm)
10891 (y-or-n-p (format "Create new node \"%s\"? "
10892 child)))))
10893 (org-refile-new-child parent-target child)))
10894 (error "Invalid target location")))))
10896 (declare-function org-string-nw-p "org-macs.el" (s))
10897 (defun org-refile-check-position (refile-pointer)
10898 "Check if the refile pointer matches the readline to which it points."
10899 (let* ((file (nth 1 refile-pointer))
10900 (re (nth 2 refile-pointer))
10901 (pos (nth 3 refile-pointer))
10902 buffer)
10903 (when (org-string-nw-p re)
10904 (setq buffer (if (markerp pos)
10905 (marker-buffer pos)
10906 (or (find-buffer-visiting file)
10907 (find-file-noselect file))))
10908 (with-current-buffer buffer
10909 (save-excursion
10910 (save-restriction
10911 (widen)
10912 (goto-char pos)
10913 (beginning-of-line 1)
10914 (unless (org-looking-at-p re)
10915 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
10917 (defun org-refile-new-child (parent-target child)
10918 "Use refile target PARENT-TARGET to add new CHILD below it."
10919 (unless parent-target
10920 (error "Cannot find parent for new node"))
10921 (let ((file (nth 1 parent-target))
10922 (pos (nth 3 parent-target))
10923 level)
10924 (with-current-buffer (or (find-buffer-visiting file)
10925 (find-file-noselect file))
10926 (save-excursion
10927 (save-restriction
10928 (widen)
10929 (if pos
10930 (goto-char pos)
10931 (goto-char (point-max))
10932 (if (not (bolp)) (newline)))
10933 (when (looking-at org-outline-regexp)
10934 (setq level (funcall outline-level))
10935 (org-end-of-subtree t t))
10936 (org-back-over-empty-lines)
10937 (insert "\n" (make-string
10938 (if pos (org-get-valid-level level 1) 1) ?*)
10939 " " child "\n")
10940 (beginning-of-line 0)
10941 (list (concat (car parent-target) "/" child) file "" (point)))))))
10943 (defun org-olpath-completing-read (prompt collection &rest args)
10944 "Read an outline path like a file name."
10945 (let ((thetable collection)
10946 (org-completion-use-ido nil) ; does not work with ido.
10947 (org-completion-use-iswitchb nil)) ; or iswitchb
10948 (apply
10949 'org-icompleting-read prompt
10950 (lambda (string predicate &optional flag)
10951 (let (rtn r f (l (length string)))
10952 (cond
10953 ((eq flag nil)
10954 ;; try completion
10955 (try-completion string thetable))
10956 ((eq flag t)
10957 ;; all-completions
10958 (setq rtn (all-completions string thetable predicate))
10959 (mapcar
10960 (lambda (x)
10961 (setq r (substring x l))
10962 (if (string-match " ([^)]*)$" x)
10963 (setq f (match-string 0 x))
10964 (setq f ""))
10965 (if (string-match "/" r)
10966 (concat string (substring r 0 (match-end 0)) f)
10968 rtn))
10969 ((eq flag 'lambda)
10970 ;; exact match?
10971 (assoc string thetable)))
10973 args)))
10975 ;;;; Dynamic blocks
10977 (defun org-find-dblock (name)
10978 "Find the first dynamic block with name NAME in the buffer.
10979 If not found, stay at current position and return nil."
10980 (let (pos)
10981 (save-excursion
10982 (goto-char (point-min))
10983 (setq pos (and (re-search-forward (concat "^[ \t]*#\\+BEGIN:[ \t]+" name "\\>")
10984 nil t)
10985 (match-beginning 0))))
10986 (if pos (goto-char pos))
10987 pos))
10989 (defconst org-dblock-start-re
10990 "^[ \t]*#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
10991 "Matches the start line of a dynamic block, with parameters.")
10993 (defconst org-dblock-end-re "^[ \t]*#\\+END\\([: \t\r\n]\\|$\\)"
10994 "Matches the end of a dynamic block.")
10996 (defun org-create-dblock (plist)
10997 "Create a dynamic block section, with parameters taken from PLIST.
10998 PLIST must contain a :name entry which is used as name of the block."
10999 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11000 (end-of-line 1)
11001 (newline))
11002 (let ((col (current-column))
11003 (name (plist-get plist :name)))
11004 (insert "#+BEGIN: " name)
11005 (while plist
11006 (if (eq (car plist) :name)
11007 (setq plist (cddr plist))
11008 (insert " " (prin1-to-string (pop plist)))))
11009 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11010 (beginning-of-line -2)))
11012 (defun org-prepare-dblock ()
11013 "Prepare dynamic block for refresh.
11014 This empties the block, puts the cursor at the insert position and returns
11015 the property list including an extra property :name with the block name."
11016 (unless (looking-at org-dblock-start-re)
11017 (error "Not at a dynamic block"))
11018 (let* ((begdel (1+ (match-end 0)))
11019 (name (org-no-properties (match-string 1)))
11020 (params (append (list :name name)
11021 (read (concat "(" (match-string 3) ")")))))
11022 (save-excursion
11023 (beginning-of-line 1)
11024 (skip-chars-forward " \t")
11025 (setq params (plist-put params :indentation-column (current-column))))
11026 (unless (re-search-forward org-dblock-end-re nil t)
11027 (error "Dynamic block not terminated"))
11028 (setq params
11029 (append params
11030 (list :content (buffer-substring
11031 begdel (match-beginning 0)))))
11032 (delete-region begdel (match-beginning 0))
11033 (goto-char begdel)
11034 (open-line 1)
11035 params))
11037 (defun org-map-dblocks (&optional command)
11038 "Apply COMMAND to all dynamic blocks in the current buffer.
11039 If COMMAND is not given, use `org-update-dblock'."
11040 (let ((cmd (or command 'org-update-dblock)))
11041 (save-excursion
11042 (goto-char (point-min))
11043 (while (re-search-forward org-dblock-start-re nil t)
11044 (goto-char (match-beginning 0))
11045 (save-excursion
11046 (condition-case nil
11047 (funcall cmd)
11048 (error (message "Error during update of dynamic block"))))
11049 (unless (re-search-forward org-dblock-end-re nil t)
11050 (error "Dynamic block not terminated"))))))
11052 (defun org-dblock-update (&optional arg)
11053 "User command for updating dynamic blocks.
11054 Update the dynamic block at point. With prefix ARG, update all dynamic
11055 blocks in the buffer."
11056 (interactive "P")
11057 (if arg
11058 (org-update-all-dblocks)
11059 (or (looking-at org-dblock-start-re)
11060 (org-beginning-of-dblock))
11061 (org-update-dblock)))
11063 (defun org-update-dblock ()
11064 "Update the dynamic block at point.
11065 This means to empty the block, parse for parameters and then call
11066 the correct writing function."
11067 (interactive)
11068 (save-window-excursion
11069 (let* ((pos (point))
11070 (line (org-current-line))
11071 (params (org-prepare-dblock))
11072 (name (plist-get params :name))
11073 (indent (plist-get params :indentation-column))
11074 (cmd (intern (concat "org-dblock-write:" name))))
11075 (message "Updating dynamic block `%s' at line %d..." name line)
11076 (funcall cmd params)
11077 (message "Updating dynamic block `%s' at line %d...done" name line)
11078 (goto-char pos)
11079 (when (and indent (> indent 0))
11080 (setq indent (make-string indent ?\ ))
11081 (save-excursion
11082 (org-beginning-of-dblock)
11083 (forward-line 1)
11084 (while (not (looking-at org-dblock-end-re))
11085 (insert indent)
11086 (beginning-of-line 2))
11087 (when (looking-at org-dblock-end-re)
11088 (and (looking-at "[ \t]+")
11089 (replace-match ""))
11090 (insert indent)))))))
11092 (defun org-beginning-of-dblock ()
11093 "Find the beginning of the dynamic block at point.
11094 Error if there is no such block at point."
11095 (let ((pos (point))
11096 beg)
11097 (end-of-line 1)
11098 (if (and (re-search-backward org-dblock-start-re nil t)
11099 (setq beg (match-beginning 0))
11100 (re-search-forward org-dblock-end-re nil t)
11101 (> (match-end 0) pos))
11102 (goto-char beg)
11103 (goto-char pos)
11104 (error "Not in a dynamic block"))))
11106 ;;;###autoload
11107 (defun org-update-all-dblocks ()
11108 "Update all dynamic blocks in the buffer.
11109 This function can be used in a hook."
11110 (interactive)
11111 (when (derived-mode-p 'org-mode)
11112 (org-map-dblocks 'org-update-dblock)))
11115 ;;;; Completion
11117 (defconst org-additional-option-like-keywords
11118 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML:"
11119 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook:"
11120 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"
11121 "LATEX_CLASS:" "LATEX_CLASS_OPTIONS:" "ATTR_LaTeX:"
11122 "BEGIN:" "END:"
11123 "ORGTBL" "TBLFM:" "TBLNAME:"
11124 "BEGIN_EXAMPLE" "END_EXAMPLE"
11125 "BEGIN_QUOTE" "END_QUOTE"
11126 "BEGIN_VERSE" "END_VERSE"
11127 "BEGIN_CENTER" "END_CENTER"
11128 "BEGIN_SRC" "END_SRC"
11129 "BEGIN_RESULT" "END_RESULT"
11130 "NAME:" "RESULTS:"
11131 "HEADER:" "HEADERS:"
11132 "CATEGORY:" "COLUMNS:" "PROPERTY:"
11133 "CAPTION:" "LABEL:"
11134 "SETUPFILE:"
11135 "INCLUDE:"
11136 "BIND:"
11137 "MACRO:"))
11139 (defcustom org-structure-template-alist
11141 ("s" "#+BEGIN_SRC ?\n\n#+END_SRC"
11142 "<src lang=\"?\">\n\n</src>")
11143 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE"
11144 "<example>\n?\n</example>")
11145 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE"
11146 "<quote>\n?\n</quote>")
11147 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE"
11148 "<verse>\n?\n</verse>")
11149 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER"
11150 "<center>\n?\n</center>")
11151 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11152 "<literal style=\"latex\">\n?\n</literal>")
11153 ("L" "#+LaTeX: "
11154 "<literal style=\"latex\">?</literal>")
11155 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
11156 "<literal style=\"html\">\n?\n</literal>")
11157 ("H" "#+HTML: "
11158 "<literal style=\"html\">?</literal>")
11159 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
11160 ("A" "#+ASCII: ")
11161 ("i" "#+INDEX: ?"
11162 "#+INDEX: ?")
11163 ("I" "#+INCLUDE %file ?"
11164 "<include file=%file markup=\"?\">")
11166 "Structure completion elements.
11167 This is a list of abbreviation keys and values. The value gets inserted
11168 if you type `<' followed by the key and then press the completion key,
11169 usually `M-TAB'. %file will be replaced by a file name after prompting
11170 for the file using completion. The cursor will be placed at the position
11171 of the `?` in the template.
11172 There are two templates for each key, the first uses the original Org syntax,
11173 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11174 the default when the /org-mtags.el/ module has been loaded. See also the
11175 variable `org-mtags-prefer-muse-templates'."
11176 :group 'org-completion
11177 :type '(repeat
11178 (string :tag "Key")
11179 (string :tag "Template")
11180 (string :tag "Muse Template")))
11182 (defun org-try-structure-completion ()
11183 "Try to complete a structure template before point.
11184 This looks for strings like \"<e\" on an otherwise empty line and
11185 expands them."
11186 (let ((l (buffer-substring (point-at-bol) (point)))
11188 (when (and (looking-at "[ \t]*$")
11189 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
11190 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
11191 (org-complete-expand-structure-template (+ -1 (point-at-bol)
11192 (match-beginning 1)) a)
11193 t)))
11195 (defun org-complete-expand-structure-template (start cell)
11196 "Expand a structure template."
11197 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
11198 (rpl (nth (if musep 2 1) cell))
11199 (ind ""))
11200 (delete-region start (point))
11201 (when (string-match "\\`#\\+" rpl)
11202 (cond
11203 ((bolp))
11204 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
11205 (setq ind (buffer-substring (point-at-bol) (point))))
11206 (t (newline))))
11207 (setq start (point))
11208 (if (string-match "%file" rpl)
11209 (setq rpl (replace-match
11210 (concat
11211 "\""
11212 (save-match-data
11213 (abbreviate-file-name (read-file-name "Include file: ")))
11214 "\"")
11215 t t rpl)))
11216 (setq rpl (mapconcat 'identity (split-string rpl "\n")
11217 (concat "\n" ind)))
11218 (insert rpl)
11219 (if (re-search-backward "\\?" start t) (delete-char 1))))
11221 ;;;; TODO, DEADLINE, Comments
11223 (defun org-toggle-comment ()
11224 "Change the COMMENT state of an entry."
11225 (interactive)
11226 (save-excursion
11227 (org-back-to-heading)
11228 (let (case-fold-search)
11229 (cond
11230 ((looking-at (format org-heading-keyword-regexp-format
11231 org-comment-string))
11232 (goto-char (match-end 1))
11233 (looking-at (concat " +" org-comment-string))
11234 (replace-match "" t t)
11235 (when (eolp) (insert " ")))
11236 ((looking-at org-outline-regexp)
11237 (goto-char (match-end 0))
11238 (insert org-comment-string " "))))))
11240 (defvar org-last-todo-state-is-todo nil
11241 "This is non-nil when the last TODO state change led to a TODO state.
11242 If the last change removed the TODO tag or switched to DONE, then
11243 this is nil.")
11245 (defvar org-setting-tags nil) ; dynamically skipped
11247 (defvar org-todo-setup-filter-hook nil
11248 "Hook for functions that pre-filter todo specs.
11249 Each function takes a todo spec and returns either nil or the spec
11250 transformed into canonical form." )
11252 (defvar org-todo-get-default-hook nil
11253 "Hook for functions that get a default item for todo.
11254 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11255 nil or a string to be used for the todo mark." )
11257 (defvar org-agenda-headline-snapshot-before-repeat)
11259 (defun org-current-effective-time ()
11260 "Return current time adjusted for `org-extend-today-until' variable"
11261 (let* ((ct (org-current-time))
11262 (dct (decode-time ct))
11263 (ct1
11264 (if (and org-use-effective-time
11265 (< (nth 2 dct) org-extend-today-until))
11266 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct))
11267 ct)))
11268 ct1))
11270 (defun org-todo-yesterday (&optional arg)
11271 "Like `org-todo' but the time of change will be 23:59 of yesterday."
11272 (interactive "P")
11273 (if (eq major-mode 'org-agenda-mode)
11274 (apply 'org-agenda-todo-yesterday arg)
11275 (let* ((hour (third (decode-time
11276 (org-current-time))))
11277 (org-extend-today-until (1+ hour)))
11278 (org-todo arg))))
11280 (defun org-todo (&optional arg)
11281 "Change the TODO state of an item.
11282 The state of an item is given by a keyword at the start of the heading,
11283 like
11284 *** TODO Write paper
11285 *** DONE Call mom
11287 The different keywords are specified in the variable `org-todo-keywords'.
11288 By default the available states are \"TODO\" and \"DONE\".
11289 So for this example: when the item starts with TODO, it is changed to DONE.
11290 When it starts with DONE, the DONE is removed. And when neither TODO nor
11291 DONE are present, add TODO at the beginning of the heading.
11293 With \\[universal-argument] prefix arg, use completion to determine the new \
11294 state.
11295 With numeric prefix arg, switch to that state.
11296 With a double \\[universal-argument] prefix, switch to the next set of TODO \
11297 keywords (nextset).
11298 With a triple \\[universal-argument] prefix, circumvent any state blocking.
11299 With a numeric prefix arg of 0, inhibit note taking for the change.
11301 For calling through lisp, arg is also interpreted in the following way:
11302 'none -> empty state
11303 \"\"(empty string) -> switch to empty state
11304 'done -> switch to DONE
11305 'nextset -> switch to the next set of keywords
11306 'previousset -> switch to the previous set of keywords
11307 \"WAITING\" -> switch to the specified keyword, but only if it
11308 really is a member of `org-todo-keywords'."
11309 (interactive "P")
11310 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11311 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
11312 'region-start-level 'region))
11313 org-loop-over-headlines-in-active-region)
11314 (org-map-entries
11315 `(org-todo ,arg)
11316 org-loop-over-headlines-in-active-region
11317 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
11318 (if (equal arg '(16)) (setq arg 'nextset))
11319 (let ((org-blocker-hook org-blocker-hook)
11320 (case-fold-search nil))
11321 (when (equal arg '(64))
11322 (setq arg nil org-blocker-hook nil))
11323 (when (and org-blocker-hook
11324 (or org-inhibit-blocking
11325 (org-entry-get nil "NOBLOCKING")))
11326 (setq org-blocker-hook nil))
11327 (save-excursion
11328 (catch 'exit
11329 (org-back-to-heading t)
11330 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
11331 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
11332 (looking-at "\\(?: *\\|[ \t]*$\\)"))
11333 (let* ((match-data (match-data))
11334 (startpos (point-at-bol))
11335 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
11336 (org-log-done org-log-done)
11337 (org-log-repeat org-log-repeat)
11338 (org-todo-log-states org-todo-log-states)
11339 (org-inhibit-logging
11340 (if (equal arg 0)
11341 (progn (setq arg nil) 'note) org-inhibit-logging))
11342 (this (match-string 1))
11343 (hl-pos (match-beginning 0))
11344 (head (org-get-todo-sequence-head this))
11345 (ass (assoc head org-todo-kwd-alist))
11346 (interpret (nth 1 ass))
11347 (done-word (nth 3 ass))
11348 (final-done-word (nth 4 ass))
11349 (org-last-state (or this ""))
11350 (completion-ignore-case t)
11351 (member (member this org-todo-keywords-1))
11352 (tail (cdr member))
11353 (org-state (cond
11354 ((and org-todo-key-trigger
11355 (or (and (equal arg '(4))
11356 (eq org-use-fast-todo-selection 'prefix))
11357 (and (not arg) org-use-fast-todo-selection
11358 (not (eq org-use-fast-todo-selection
11359 'prefix)))))
11360 ;; Use fast selection
11361 (org-fast-todo-selection))
11362 ((and (equal arg '(4))
11363 (or (not org-use-fast-todo-selection)
11364 (not org-todo-key-trigger)))
11365 ;; Read a state with completion
11366 (org-icompleting-read
11367 "State: " (mapcar (lambda(x) (list x))
11368 org-todo-keywords-1)
11369 nil t))
11370 ((eq arg 'right)
11371 (if this
11372 (if tail (car tail) nil)
11373 (car org-todo-keywords-1)))
11374 ((eq arg 'left)
11375 (if (equal member org-todo-keywords-1)
11377 (if this
11378 (nth (- (length org-todo-keywords-1)
11379 (length tail) 2)
11380 org-todo-keywords-1)
11381 (org-last org-todo-keywords-1))))
11382 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
11383 (setq arg nil))) ; hack to fall back to cycling
11384 (arg
11385 ;; user or caller requests a specific state
11386 (cond
11387 ((equal arg "") nil)
11388 ((eq arg 'none) nil)
11389 ((eq arg 'done) (or done-word (car org-done-keywords)))
11390 ((eq arg 'nextset)
11391 (or (car (cdr (member head org-todo-heads)))
11392 (car org-todo-heads)))
11393 ((eq arg 'previousset)
11394 (let ((org-todo-heads (reverse org-todo-heads)))
11395 (or (car (cdr (member head org-todo-heads)))
11396 (car org-todo-heads))))
11397 ((car (member arg org-todo-keywords-1)))
11398 ((stringp arg)
11399 (error "State `%s' not valid in this file" arg))
11400 ((nth (1- (prefix-numeric-value arg))
11401 org-todo-keywords-1))))
11402 ((null member) (or head (car org-todo-keywords-1)))
11403 ((equal this final-done-word) nil) ;; -> make empty
11404 ((null tail) nil) ;; -> first entry
11405 ((memq interpret '(type priority))
11406 (if (eq this-command last-command)
11407 (car tail)
11408 (if (> (length tail) 0)
11409 (or done-word (car org-done-keywords))
11410 nil)))
11412 (car tail))))
11413 (org-state (or
11414 (run-hook-with-args-until-success
11415 'org-todo-get-default-hook org-state org-last-state)
11416 org-state))
11417 (next (if org-state (concat " " org-state " ") " "))
11418 (change-plist (list :type 'todo-state-change :from this :to org-state
11419 :position startpos))
11420 dolog now-done-p)
11421 (when org-blocker-hook
11422 (setq org-last-todo-state-is-todo
11423 (not (member this org-done-keywords)))
11424 (unless (save-excursion
11425 (save-match-data
11426 (org-with-wide-buffer
11427 (run-hook-with-args-until-failure
11428 'org-blocker-hook change-plist))))
11429 (if (org-called-interactively-p 'interactive)
11430 (error "TODO state change from %s to %s blocked" this org-state)
11431 ;; fail silently
11432 (message "TODO state change from %s to %s blocked" this org-state)
11433 (throw 'exit nil))))
11434 (store-match-data match-data)
11435 (replace-match next t t)
11436 (unless (pos-visible-in-window-p hl-pos)
11437 (message "TODO state changed to %s" (org-trim next)))
11438 (unless head
11439 (setq head (org-get-todo-sequence-head org-state)
11440 ass (assoc head org-todo-kwd-alist)
11441 interpret (nth 1 ass)
11442 done-word (nth 3 ass)
11443 final-done-word (nth 4 ass)))
11444 (when (memq arg '(nextset previousset))
11445 (message "Keyword-Set %d/%d: %s"
11446 (- (length org-todo-sets) -1
11447 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
11448 (length org-todo-sets)
11449 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
11450 (setq org-last-todo-state-is-todo
11451 (not (member org-state org-done-keywords)))
11452 (setq now-done-p (and (member org-state org-done-keywords)
11453 (not (member this org-done-keywords))))
11454 (and logging (org-local-logging logging))
11455 (when (and (or org-todo-log-states org-log-done)
11456 (not (eq org-inhibit-logging t))
11457 (not (memq arg '(nextset previousset))))
11458 ;; we need to look at recording a time and note
11459 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
11460 (nth 2 (assoc this org-todo-log-states))))
11461 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
11462 (setq dolog 'time))
11463 (when (and org-state
11464 (member org-state org-not-done-keywords)
11465 (not (member this org-not-done-keywords)))
11466 ;; This is now a todo state and was not one before
11467 ;; If there was a CLOSED time stamp, get rid of it.
11468 (org-add-planning-info nil nil 'closed))
11469 (when (and now-done-p org-log-done)
11470 ;; It is now done, and it was not done before
11471 (org-add-planning-info 'closed (org-current-effective-time))
11472 (if (and (not dolog) (eq 'note org-log-done))
11473 (org-add-log-setup 'done org-state this 'findpos 'note)))
11474 (when (and org-state dolog)
11475 ;; This is a non-nil state, and we need to log it
11476 (org-add-log-setup 'state org-state this 'findpos dolog)))
11477 ;; Fixup tag positioning
11478 (org-todo-trigger-tag-changes org-state)
11479 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
11480 (when org-provide-todo-statistics
11481 (org-update-parent-todo-statistics))
11482 (run-hooks 'org-after-todo-state-change-hook)
11483 (if (and arg (not (member org-state org-done-keywords)))
11484 (setq head (org-get-todo-sequence-head org-state)))
11485 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
11486 ;; Do we need to trigger a repeat?
11487 (when now-done-p
11488 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
11489 ;; This is for the agenda, take a snapshot of the headline.
11490 (save-match-data
11491 (setq org-agenda-headline-snapshot-before-repeat
11492 (org-get-heading))))
11493 (org-auto-repeat-maybe org-state))
11494 ;; Fixup cursor location if close to the keyword
11495 (if (and (outline-on-heading-p)
11496 (not (bolp))
11497 (save-excursion (beginning-of-line 1)
11498 (looking-at org-todo-line-regexp))
11499 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
11500 (progn
11501 (goto-char (or (match-end 2) (match-end 1)))
11502 (and (looking-at " ") (just-one-space))))
11503 (when org-trigger-hook
11504 (save-excursion
11505 (run-hook-with-args 'org-trigger-hook change-plist)))))))))
11507 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
11508 "Block turning an entry into a TODO, using the hierarchy.
11509 This checks whether the current task should be blocked from state
11510 changes. Such blocking occurs when:
11512 1. The task has children which are not all in a completed state.
11514 2. A task has a parent with the property :ORDERED:, and there
11515 are siblings prior to the current task with incomplete
11516 status.
11518 3. The parent of the task is blocked because it has siblings that should
11519 be done first, or is child of a block grandparent TODO entry."
11521 (if (not org-enforce-todo-dependencies)
11522 t ; if locally turned off don't block
11523 (catch 'dont-block
11524 ;; If this is not a todo state change, or if this entry is already DONE,
11525 ;; do not block
11526 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11527 (member (plist-get change-plist :from)
11528 (cons 'done org-done-keywords))
11529 (member (plist-get change-plist :to)
11530 (cons 'todo org-not-done-keywords))
11531 (not (plist-get change-plist :to)))
11532 (throw 'dont-block t))
11533 ;; If this task has children, and any are undone, it's blocked
11534 (save-excursion
11535 (org-back-to-heading t)
11536 (let ((this-level (funcall outline-level)))
11537 (outline-next-heading)
11538 (let ((child-level (funcall outline-level)))
11539 (while (and (not (eobp))
11540 (> child-level this-level))
11541 ;; this todo has children, check whether they are all
11542 ;; completed
11543 (if (and (not (org-entry-is-done-p))
11544 (org-entry-is-todo-p))
11545 (throw 'dont-block nil))
11546 (outline-next-heading)
11547 (setq child-level (funcall outline-level))))))
11548 ;; Otherwise, if the task's parent has the :ORDERED: property, and
11549 ;; any previous siblings are undone, it's blocked
11550 (save-excursion
11551 (org-back-to-heading t)
11552 (let* ((pos (point))
11553 (parent-pos (and (org-up-heading-safe) (point))))
11554 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11555 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11556 (forward-line 1)
11557 (re-search-forward org-not-done-heading-regexp pos t))
11558 (throw 'dont-block nil)) ; block, there is an older sibling not done.
11559 ;; Search further up the hierarchy, to see if an ancestor is blocked
11560 (while t
11561 (goto-char parent-pos)
11562 (if (not (looking-at org-not-done-heading-regexp))
11563 (throw 'dont-block t)) ; do not block, parent is not a TODO
11564 (setq pos (point))
11565 (setq parent-pos (and (org-up-heading-safe) (point)))
11566 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11567 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11568 (forward-line 1)
11569 (re-search-forward org-not-done-heading-regexp pos t))
11570 (throw 'dont-block nil)))))))) ; block, older sibling not done.
11572 (defcustom org-track-ordered-property-with-tag nil
11573 "Should the ORDERED property also be shown as a tag?
11574 The ORDERED property decides if an entry should require subtasks to be
11575 completed in sequence. Since a property is not very visible, setting
11576 this option means that toggling the ORDERED property with the command
11577 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
11578 not relevant for the behavior, but it makes things more visible.
11580 Note that toggling the tag with tags commands will not change the property
11581 and therefore not influence behavior!
11583 This can be t, meaning the tag ORDERED should be used, It can also be a
11584 string to select a different tag for this task."
11585 :group 'org-todo
11586 :type '(choice
11587 (const :tag "No tracking" nil)
11588 (const :tag "Track with ORDERED tag" t)
11589 (string :tag "Use other tag")))
11591 (defun org-toggle-ordered-property ()
11592 "Toggle the ORDERED property of the current entry.
11593 For better visibility, you can track the value of this property with a tag.
11594 See variable `org-track-ordered-property-with-tag'."
11595 (interactive)
11596 (let* ((t1 org-track-ordered-property-with-tag)
11597 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
11598 (save-excursion
11599 (org-back-to-heading)
11600 (if (org-entry-get nil "ORDERED")
11601 (progn
11602 (org-delete-property "ORDERED")
11603 (and tag (org-toggle-tag tag 'off))
11604 (message "Subtasks can be completed in arbitrary order"))
11605 (org-entry-put nil "ORDERED" "t")
11606 (and tag (org-toggle-tag tag 'on))
11607 (message "Subtasks must be completed in sequence")))))
11609 (defvar org-blocked-by-checkboxes) ; dynamically scoped
11610 (defun org-block-todo-from-checkboxes (change-plist)
11611 "Block turning an entry into a TODO, using checkboxes.
11612 This checks whether the current task should be blocked from state
11613 changes because there are unchecked boxes in this entry."
11614 (if (not org-enforce-todo-checkbox-dependencies)
11615 t ; if locally turned off don't block
11616 (catch 'dont-block
11617 ;; If this is not a todo state change, or if this entry is already DONE,
11618 ;; do not block
11619 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11620 (member (plist-get change-plist :from)
11621 (cons 'done org-done-keywords))
11622 (member (plist-get change-plist :to)
11623 (cons 'todo org-not-done-keywords))
11624 (not (plist-get change-plist :to)))
11625 (throw 'dont-block t))
11626 ;; If this task has checkboxes that are not checked, it's blocked
11627 (save-excursion
11628 (org-back-to-heading t)
11629 (let ((beg (point)) end)
11630 (outline-next-heading)
11631 (setq end (point))
11632 (goto-char beg)
11633 (if (org-list-search-forward
11634 (concat (org-item-beginning-re)
11635 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
11636 "\\[[- ]\\]")
11637 end t)
11638 (progn
11639 (if (boundp 'org-blocked-by-checkboxes)
11640 (setq org-blocked-by-checkboxes t))
11641 (throw 'dont-block nil)))))
11642 t))) ; do not block
11644 (defun org-entry-blocked-p ()
11645 "Is the current entry blocked?"
11646 (if (org-entry-get nil "NOBLOCKING")
11647 nil ;; Never block this entry
11648 (not
11649 (run-hook-with-args-until-failure
11650 'org-blocker-hook
11651 (list :type 'todo-state-change
11652 :position (point)
11653 :from 'todo
11654 :to 'done)))))
11656 (defun org-update-statistics-cookies (all)
11657 "Update the statistics cookie, either from TODO or from checkboxes.
11658 This should be called with the cursor in a line with a statistics cookie."
11659 (interactive "P")
11660 (if all
11661 (progn
11662 (org-update-checkbox-count 'all)
11663 (org-map-entries 'org-update-parent-todo-statistics))
11664 (if (not (org-at-heading-p))
11665 (org-update-checkbox-count)
11666 (let ((pos (move-marker (make-marker) (point)))
11667 end l1 l2)
11668 (ignore-errors (org-back-to-heading t))
11669 (if (not (org-at-heading-p))
11670 (org-update-checkbox-count)
11671 (setq l1 (org-outline-level))
11672 (setq end (save-excursion
11673 (outline-next-heading)
11674 (if (org-at-heading-p) (setq l2 (org-outline-level)))
11675 (point)))
11676 (if (and (save-excursion
11677 (re-search-forward
11678 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
11679 (not (save-excursion (re-search-forward
11680 ":COOKIE_DATA:.*\\<todo\\>" end t))))
11681 (org-update-checkbox-count)
11682 (if (and l2 (> l2 l1))
11683 (progn
11684 (goto-char end)
11685 (org-update-parent-todo-statistics))
11686 (goto-char pos)
11687 (beginning-of-line 1)
11688 (while (re-search-forward
11689 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
11690 (point-at-eol) t)
11691 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
11692 (goto-char pos)
11693 (move-marker pos nil)))))
11695 (defvar org-entry-property-inherited-from) ;; defined below
11696 (defun org-update-parent-todo-statistics ()
11697 "Update any statistics cookie in the parent of the current headline.
11698 When `org-hierarchical-todo-statistics' is nil, statistics will cover
11699 the entire subtree and this will travel up the hierarchy and update
11700 statistics everywhere."
11701 (let* ((prop (save-excursion (org-up-heading-safe)
11702 (org-entry-get nil "COOKIE_DATA" 'inherit)))
11703 (recursive (or (not org-hierarchical-todo-statistics)
11704 (and prop (string-match "\\<recursive\\>" prop))))
11705 (lim (or (and prop (marker-position org-entry-property-inherited-from))
11707 (first t)
11708 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
11709 level ltoggle l1 new ndel
11710 (cnt-all 0) (cnt-done 0) is-percent kwd
11711 checkbox-beg ov ovs ove cookie-present)
11712 (catch 'exit
11713 (save-excursion
11714 (beginning-of-line 1)
11715 (setq ltoggle (funcall outline-level))
11716 ;; Three situations are to consider:
11718 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
11719 ;; to the top-level ancestor on the headline;
11721 ;; 2. If parent has "recursive" property, repeat up to the
11722 ;; headline setting that property, taking inheritance into
11723 ;; account;
11725 ;; 3. Else, move up to direct parent and proceed only once.
11726 (while (and (setq level (org-up-heading-safe))
11727 (or recursive first)
11728 (>= (point) lim))
11729 (setq first nil cookie-present nil)
11730 (unless (and level
11731 (not (string-match
11732 "\\<checkbox\\>"
11733 (downcase (or (org-entry-get nil "COOKIE_DATA")
11734 "")))))
11735 (throw 'exit nil))
11736 (while (re-search-forward box-re (point-at-eol) t)
11737 (setq cnt-all 0 cnt-done 0 cookie-present t)
11738 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
11739 (save-match-data
11740 (unless (outline-next-heading) (throw 'exit nil))
11741 (while (and (looking-at org-complex-heading-regexp)
11742 (> (setq l1 (length (match-string 1))) level))
11743 (setq kwd (and (or recursive (= l1 ltoggle))
11744 (match-string 2)))
11745 (if (or (eq org-provide-todo-statistics 'all-headlines)
11746 (and (listp org-provide-todo-statistics)
11747 (or (member kwd org-provide-todo-statistics)
11748 (member kwd org-done-keywords))))
11749 (setq cnt-all (1+ cnt-all))
11750 (if (eq org-provide-todo-statistics t)
11751 (and kwd (setq cnt-all (1+ cnt-all)))))
11752 (and (member kwd org-done-keywords)
11753 (setq cnt-done (1+ cnt-done)))
11754 (outline-next-heading)))
11755 (setq new
11756 (if is-percent
11757 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
11758 (format "[%d/%d]" cnt-done cnt-all))
11759 ndel (- (match-end 0) checkbox-beg))
11760 ;; handle overlays when updating cookie from column view
11761 (when (setq ov (car (overlays-at checkbox-beg)))
11762 (setq ovs (overlay-start ov) ove (overlay-end ov))
11763 (delete-overlay ov))
11764 (goto-char checkbox-beg)
11765 (insert new)
11766 (delete-region (point) (+ (point) ndel))
11767 (when org-auto-align-tags (org-fix-tags-on-the-fly))
11768 (when ov (move-overlay ov ovs ove)))
11769 (when cookie-present
11770 (run-hook-with-args 'org-after-todo-statistics-hook
11771 cnt-done (- cnt-all cnt-done))))))
11772 (run-hooks 'org-todo-statistics-hook)))
11774 (defvar org-after-todo-statistics-hook nil
11775 "Hook that is called after a TODO statistics cookie has been updated.
11776 Each function is called with two arguments: the number of not-done entries
11777 and the number of done entries.
11779 For example, the following function, when added to this hook, will switch
11780 an entry to DONE when all children are done, and back to TODO when new
11781 entries are set to a TODO status. Note that this hook is only called
11782 when there is a statistics cookie in the headline!
11784 (defun org-summary-todo (n-done n-not-done)
11785 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
11786 (let (org-log-done org-log-states) ; turn off logging
11787 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
11790 (defvar org-todo-statistics-hook nil
11791 "Hook that is run whenever Org thinks TODO statistics should be updated.
11792 This hook runs even if there is no statistics cookie present, in which case
11793 `org-after-todo-statistics-hook' would not run.")
11795 (defun org-todo-trigger-tag-changes (state)
11796 "Apply the changes defined in `org-todo-state-tags-triggers'."
11797 (let ((l org-todo-state-tags-triggers)
11798 changes)
11799 (when (or (not state) (equal state ""))
11800 (setq changes (append changes (cdr (assoc "" l)))))
11801 (when (and (stringp state) (> (length state) 0))
11802 (setq changes (append changes (cdr (assoc state l)))))
11803 (when (member state org-not-done-keywords)
11804 (setq changes (append changes (cdr (assoc 'todo l)))))
11805 (when (member state org-done-keywords)
11806 (setq changes (append changes (cdr (assoc 'done l)))))
11807 (dolist (c changes)
11808 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
11810 (defun org-local-logging (value)
11811 "Get logging settings from a property VALUE."
11812 (let* (words w a)
11813 ;; directly set the variables, they are already local.
11814 (setq org-log-done nil
11815 org-log-repeat nil
11816 org-todo-log-states nil)
11817 (setq words (org-split-string value))
11818 (while (setq w (pop words))
11819 (cond
11820 ((setq a (assoc w org-startup-options))
11821 (and (member (nth 1 a) '(org-log-done org-log-repeat))
11822 (set (nth 1 a) (nth 2 a))))
11823 ((setq a (org-extract-log-state-settings w))
11824 (and (member (car a) org-todo-keywords-1)
11825 (push a org-todo-log-states)))))))
11827 (defun org-get-todo-sequence-head (kwd)
11828 "Return the head of the TODO sequence to which KWD belongs.
11829 If KWD is not set, check if there is a text property remembering the
11830 right sequence."
11831 (let (p)
11832 (cond
11833 ((not kwd)
11834 (or (get-text-property (point-at-bol) 'org-todo-head)
11835 (progn
11836 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
11837 nil (point-at-eol)))
11838 (get-text-property p 'org-todo-head))))
11839 ((not (member kwd org-todo-keywords-1))
11840 (car org-todo-keywords-1))
11841 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
11843 (defun org-fast-todo-selection ()
11844 "Fast TODO keyword selection with single keys.
11845 Returns the new TODO keyword, or nil if no state change should occur."
11846 (let* ((fulltable org-todo-key-alist)
11847 (done-keywords org-done-keywords) ;; needed for the faces.
11848 (maxlen (apply 'max (mapcar
11849 (lambda (x)
11850 (if (stringp (car x)) (string-width (car x)) 0))
11851 fulltable)))
11852 (expert nil)
11853 (fwidth (+ maxlen 3 1 3))
11854 (ncol (/ (- (window-width) 4) fwidth))
11855 tg cnt e c tbl
11856 groups ingroup)
11857 (save-excursion
11858 (save-window-excursion
11859 (if expert
11860 (set-buffer (get-buffer-create " *Org todo*"))
11861 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
11862 (erase-buffer)
11863 (org-set-local 'org-done-keywords done-keywords)
11864 (setq tbl fulltable cnt 0)
11865 (while (setq e (pop tbl))
11866 (cond
11867 ((equal e '(:startgroup))
11868 (push '() groups) (setq ingroup t)
11869 (when (not (= cnt 0))
11870 (setq cnt 0)
11871 (insert "\n"))
11872 (insert "{ "))
11873 ((equal e '(:endgroup))
11874 (setq ingroup nil cnt 0)
11875 (insert "}\n"))
11876 ((equal e '(:newline))
11877 (when (not (= cnt 0))
11878 (setq cnt 0)
11879 (insert "\n")
11880 (setq e (car tbl))
11881 (while (equal (car tbl) '(:newline))
11882 (insert "\n")
11883 (setq tbl (cdr tbl)))))
11885 (setq tg (car e) c (cdr e))
11886 (if ingroup (push tg (car groups)))
11887 (setq tg (org-add-props tg nil 'face
11888 (org-get-todo-face tg)))
11889 (if (and (= cnt 0) (not ingroup)) (insert " "))
11890 (insert "[" c "] " tg (make-string
11891 (- fwidth 4 (length tg)) ?\ ))
11892 (when (= (setq cnt (1+ cnt)) ncol)
11893 (insert "\n")
11894 (if ingroup (insert " "))
11895 (setq cnt 0)))))
11896 (insert "\n")
11897 (goto-char (point-min))
11898 (if (not expert) (org-fit-window-to-buffer))
11899 (message "[a-z..]:Set [SPC]:clear")
11900 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
11901 (cond
11902 ((or (= c ?\C-g)
11903 (and (= c ?q) (not (rassoc c fulltable))))
11904 (setq quit-flag t))
11905 ((= c ?\ ) nil)
11906 ((setq e (rassoc c fulltable) tg (car e))
11908 (t (setq quit-flag t)))))))
11910 (defun org-entry-is-todo-p ()
11911 (member (org-get-todo-state) org-not-done-keywords))
11913 (defun org-entry-is-done-p ()
11914 (member (org-get-todo-state) org-done-keywords))
11916 (defun org-get-todo-state ()
11917 (save-excursion
11918 (org-back-to-heading t)
11919 (and (looking-at org-todo-line-regexp)
11920 (match-end 2)
11921 (match-string 2))))
11923 (defun org-at-date-range-p (&optional inactive-ok)
11924 "Is the cursor inside a date range?"
11925 (interactive)
11926 (save-excursion
11927 (catch 'exit
11928 (let ((pos (point)))
11929 (skip-chars-backward "^[<\r\n")
11930 (skip-chars-backward "<[")
11931 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
11932 (>= (match-end 0) pos)
11933 (throw 'exit t))
11934 (skip-chars-backward "^<[\r\n")
11935 (skip-chars-backward "<[")
11936 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
11937 (>= (match-end 0) pos)
11938 (throw 'exit t)))
11939 nil)))
11941 (defun org-get-repeat (&optional tagline)
11942 "Check if there is a deadline/schedule with repeater in this entry."
11943 (save-match-data
11944 (save-excursion
11945 (org-back-to-heading t)
11946 (and (re-search-forward (if tagline
11947 (concat tagline "\\s-*" org-repeat-re)
11948 org-repeat-re)
11949 (org-entry-end-position) t)
11950 (match-string-no-properties 1)))))
11952 (defvar org-last-changed-timestamp)
11953 (defvar org-last-inserted-timestamp)
11954 (defvar org-log-post-message)
11955 (defvar org-log-note-purpose)
11956 (defvar org-log-note-how)
11957 (defvar org-log-note-extra)
11958 (defun org-auto-repeat-maybe (done-word)
11959 "Check if the current headline contains a repeated deadline/schedule.
11960 If yes, set TODO state back to what it was and change the base date
11961 of repeating deadline/scheduled time stamps to new date.
11962 This function is run automatically after each state change to a DONE state."
11963 ;; last-state is dynamically scoped into this function
11964 (let* ((repeat (org-get-repeat))
11965 (aa (assoc org-last-state org-todo-kwd-alist))
11966 (interpret (nth 1 aa))
11967 (head (nth 2 aa))
11968 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
11969 (msg "Entry repeats: ")
11970 (org-log-done nil)
11971 (org-todo-log-states nil)
11972 re type n what ts time to-state)
11973 (when repeat
11974 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
11975 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
11976 org-todo-repeat-to-state))
11977 (unless (and to-state (member to-state org-todo-keywords-1))
11978 (setq to-state (if (eq interpret 'type) org-last-state head)))
11979 (org-todo to-state)
11980 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
11981 (org-entry-put nil "LAST_REPEAT" (format-time-string
11982 (org-time-stamp-format t t))))
11983 (when org-log-repeat
11984 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
11985 (memq 'org-add-log-note post-command-hook))
11986 ;; OK, we are already setup for some record
11987 (if (eq org-log-repeat 'note)
11988 ;; make sure we take a note, not only a time stamp
11989 (setq org-log-note-how 'note))
11990 ;; Set up for taking a record
11991 (org-add-log-setup 'state (or done-word (car org-done-keywords))
11992 org-last-state
11993 'findpos org-log-repeat)))
11994 (org-back-to-heading t)
11995 (org-add-planning-info nil nil 'closed)
11996 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
11997 org-deadline-time-regexp "\\)\\|\\("
11998 org-ts-regexp "\\)"))
11999 (while (re-search-forward
12000 re (save-excursion (outline-next-heading) (point)) t)
12001 (setq type (if (match-end 1) org-scheduled-string
12002 (if (match-end 3) org-deadline-string "Plain:"))
12003 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12004 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12005 (setq n (string-to-number (match-string 2 ts))
12006 what (match-string 3 ts))
12007 (if (equal what "w") (setq n (* n 7) what "d"))
12008 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12009 (error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12010 ;; Preparation, see if we need to modify the start date for the change
12011 (when (match-end 1)
12012 (setq time (save-match-data (org-time-string-to-time ts)))
12013 (cond
12014 ((equal (match-string 1 ts) ".")
12015 ;; Shift starting date to today
12016 (org-timestamp-change
12017 (- (org-today) (time-to-days time))
12018 'day))
12019 ((equal (match-string 1 ts) "+")
12020 (let ((nshiftmax 10) (nshift 0))
12021 (while (or (= nshift 0)
12022 (<= (time-to-days time)
12023 (time-to-days (current-time))))
12024 (when (= (incf nshift) nshiftmax)
12025 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12026 (error "Abort")))
12027 (org-timestamp-change n (cdr (assoc what whata)))
12028 (org-at-timestamp-p t)
12029 (setq ts (match-string 1))
12030 (setq time (save-match-data (org-time-string-to-time ts)))))
12031 (org-timestamp-change (- n) (cdr (assoc what whata)))
12032 ;; rematch, so that we have everything in place for the real shift
12033 (org-at-timestamp-p t)
12034 (setq ts (match-string 1))
12035 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12036 (org-timestamp-change n (cdr (assoc what whata)))
12037 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12038 (setq org-log-post-message msg)
12039 (message "%s" msg))))
12041 (defun org-show-todo-tree (arg)
12042 "Make a compact tree which shows all headlines marked with TODO.
12043 The tree will show the lines where the regexp matches, and all higher
12044 headlines above the match.
12045 With a \\[universal-argument] prefix, prompt for a regexp to match.
12046 With a numeric prefix N, construct a sparse tree for the Nth element
12047 of `org-todo-keywords-1'."
12048 (interactive "P")
12049 (let ((case-fold-search nil)
12050 (kwd-re
12051 (cond ((null arg) org-not-done-regexp)
12052 ((equal arg '(4))
12053 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12054 (mapcar 'list org-todo-keywords-1))))
12055 (concat "\\("
12056 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12057 "\\)\\>")))
12058 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12059 (regexp-quote (nth (1- (prefix-numeric-value arg))
12060 org-todo-keywords-1)))
12061 (t (error "Invalid prefix argument: %s" arg)))))
12062 (message "%d TODO entries found"
12063 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12065 (defun org-deadline (&optional remove time)
12066 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12067 With argument REMOVE, remove any deadline from the item.
12068 With argument TIME, set the deadline at the corresponding date. TIME
12069 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12070 (interactive "P")
12071 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12072 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12073 'region-start-level 'region))
12074 org-loop-over-headlines-in-active-region)
12075 (org-map-entries
12076 `(org-deadline ',remove ,time)
12077 org-loop-over-headlines-in-active-region
12078 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12079 (let* ((old-date (org-entry-get nil "DEADLINE"))
12080 (repeater (and old-date
12081 (string-match
12082 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12083 old-date)
12084 (match-string 1 old-date))))
12085 (if remove
12086 (progn
12087 (when (and old-date org-log-redeadline)
12088 (org-add-log-setup 'deldeadline nil old-date 'findpos
12089 org-log-redeadline))
12090 (org-remove-timestamp-with-keyword org-deadline-string)
12091 (message "Item no longer has a deadline."))
12092 (org-add-planning-info 'deadline time 'closed)
12093 (when (and old-date org-log-redeadline
12094 (not (equal old-date
12095 (substring org-last-inserted-timestamp 1 -1))))
12096 (org-add-log-setup 'redeadline nil old-date 'findpos
12097 org-log-redeadline))
12098 (when repeater
12099 (save-excursion
12100 (org-back-to-heading t)
12101 (when (re-search-forward (concat org-deadline-string " "
12102 org-last-inserted-timestamp)
12103 (save-excursion
12104 (outline-next-heading) (point)) t)
12105 (goto-char (1- (match-end 0)))
12106 (insert " " repeater)
12107 (setq org-last-inserted-timestamp
12108 (concat (substring org-last-inserted-timestamp 0 -1)
12109 " " repeater
12110 (substring org-last-inserted-timestamp -1))))))
12111 (message "Deadline on %s" org-last-inserted-timestamp)))))
12113 (defun org-schedule (&optional remove time)
12114 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12115 With argument REMOVE, remove any scheduling date from the item.
12116 With argument TIME, scheduled at the corresponding date. TIME can
12117 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12118 (interactive "P")
12119 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12120 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12121 'region-start-level 'region))
12122 org-loop-over-headlines-in-active-region)
12123 (org-map-entries
12124 `(org-schedule ',remove ,time)
12125 org-loop-over-headlines-in-active-region
12126 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12127 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12128 (repeater (and old-date
12129 (string-match
12130 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12131 old-date)
12132 (match-string 1 old-date))))
12133 (if remove
12134 (progn
12135 (when (and old-date org-log-reschedule)
12136 (org-add-log-setup 'delschedule nil old-date 'findpos
12137 org-log-reschedule))
12138 (org-remove-timestamp-with-keyword org-scheduled-string)
12139 (message "Item is no longer scheduled."))
12140 (org-add-planning-info 'scheduled time 'closed)
12141 (when (and old-date org-log-reschedule
12142 (not (equal old-date
12143 (substring org-last-inserted-timestamp 1 -1))))
12144 (org-add-log-setup 'reschedule nil old-date 'findpos
12145 org-log-reschedule))
12146 (when repeater
12147 (save-excursion
12148 (org-back-to-heading t)
12149 (when (re-search-forward (concat org-scheduled-string " "
12150 org-last-inserted-timestamp)
12151 (save-excursion
12152 (outline-next-heading) (point)) t)
12153 (goto-char (1- (match-end 0)))
12154 (insert " " repeater)
12155 (setq org-last-inserted-timestamp
12156 (concat (substring org-last-inserted-timestamp 0 -1)
12157 " " repeater
12158 (substring org-last-inserted-timestamp -1))))))
12159 (message "Scheduled to %s" org-last-inserted-timestamp)))))
12161 (defun org-get-scheduled-time (pom &optional inherit)
12162 "Get the scheduled time as a time tuple, of a format suitable
12163 for calling org-schedule with, or if there is no scheduling,
12164 returns nil."
12165 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12166 (when time
12167 (apply 'encode-time (org-parse-time-string time)))))
12169 (defun org-get-deadline-time (pom &optional inherit)
12170 "Get the deadline as a time tuple, of a format suitable for
12171 calling org-deadline with, or if there is no scheduling, returns
12172 nil."
12173 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12174 (when time
12175 (apply 'encode-time (org-parse-time-string time)))))
12177 (defun org-remove-timestamp-with-keyword (keyword)
12178 "Remove all time stamps with KEYWORD in the current entry."
12179 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12180 beg)
12181 (save-excursion
12182 (org-back-to-heading t)
12183 (setq beg (point))
12184 (outline-next-heading)
12185 (while (re-search-backward re beg t)
12186 (replace-match "")
12187 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12188 (equal (char-before) ?\ ))
12189 (backward-delete-char 1)
12190 (if (string-match "^[ \t]*$" (buffer-substring
12191 (point-at-bol) (point-at-eol)))
12192 (delete-region (point-at-bol)
12193 (min (point-max) (1+ (point-at-eol))))))))))
12195 (defun org-add-planning-info (what &optional time &rest remove)
12196 "Insert new timestamp with keyword in the line directly after the headline.
12197 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
12198 If non is given, the user is prompted for a date.
12199 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
12200 be removed."
12201 (interactive)
12202 (let (org-time-was-given org-end-time-was-given ts
12203 end default-time default-input)
12205 (catch 'exit
12206 (when (and (memq what '(scheduled deadline))
12207 (or (not time)
12208 (and (stringp time)
12209 (string-match "^[-+]+[0-9]" time))))
12210 ;; Try to get a default date/time from existing timestamp
12211 (save-excursion
12212 (org-back-to-heading t)
12213 (setq end (save-excursion (outline-next-heading) (point)))
12214 (when (re-search-forward (if (eq what 'scheduled)
12215 org-scheduled-time-regexp
12216 org-deadline-time-regexp)
12217 end t)
12218 (setq ts (match-string 1)
12219 default-time
12220 (apply 'encode-time (org-parse-time-string ts))
12221 default-input (and ts (org-get-compact-tod ts))))))
12222 (when what
12223 (setq time
12224 (if (stringp time)
12225 ;; This is a string (relative or absolute), set proper date
12226 (apply 'encode-time
12227 (org-read-date-analyze
12228 time default-time (decode-time default-time)))
12229 ;; If necessary, get the time from the user
12230 (or time (org-read-date nil 'to-time nil nil
12231 default-time default-input)))))
12233 (when (and org-insert-labeled-timestamps-at-point
12234 (member what '(scheduled deadline)))
12235 (insert
12236 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
12237 (org-insert-time-stamp time org-time-was-given
12238 nil nil nil (list org-end-time-was-given))
12239 (setq what nil))
12240 (save-excursion
12241 (save-restriction
12242 (let (col list elt ts buffer-invisibility-spec)
12243 (org-back-to-heading t)
12244 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
12245 (goto-char (match-end 1))
12246 (setq col (current-column))
12247 (goto-char (match-end 0))
12248 (if (eobp) (insert "\n") (forward-char 1))
12249 (when (and (not what)
12250 (not (looking-at
12251 (concat "[ \t]*"
12252 org-keyword-time-not-clock-regexp))))
12253 ;; Nothing to add, nothing to remove...... :-)
12254 (throw 'exit nil))
12255 (if (and (not (looking-at org-outline-regexp))
12256 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
12257 "[^\r\n]*"))
12258 (not (equal (match-string 1) org-clock-string)))
12259 (narrow-to-region (match-beginning 0) (match-end 0))
12260 (insert-before-markers "\n")
12261 (backward-char 1)
12262 (narrow-to-region (point) (point))
12263 (and org-adapt-indentation (org-indent-to-column col)))
12264 ;; Check if we have to remove something.
12265 (setq list (cons what remove))
12266 (while list
12267 (setq elt (pop list))
12268 (when (or (and (eq elt 'scheduled)
12269 (re-search-forward org-scheduled-time-regexp nil t))
12270 (and (eq elt 'deadline)
12271 (re-search-forward org-deadline-time-regexp nil t))
12272 (and (eq elt 'closed)
12273 (re-search-forward org-closed-time-regexp nil t)))
12274 (replace-match "")
12275 (if (looking-at "--+<[^>]+>") (replace-match ""))))
12276 (and (looking-at "[ \t]+") (replace-match ""))
12277 (and org-adapt-indentation (bolp) (org-indent-to-column col))
12278 (when what
12279 (insert
12280 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
12281 (cond ((eq what 'scheduled) org-scheduled-string)
12282 ((eq what 'deadline) org-deadline-string)
12283 ((eq what 'closed) org-closed-string))
12284 " ")
12285 (setq ts (org-insert-time-stamp
12286 time
12287 (or org-time-was-given
12288 (and (eq what 'closed) org-log-done-with-time))
12289 (eq what 'closed)
12290 nil nil (list org-end-time-was-given)))
12291 (insert
12292 (if (not (or (bolp) (eq (char-before) ?\ )
12293 (memq (char-after) '(32 10))
12294 (eobp))) " " ""))
12295 (end-of-line 1))
12296 (goto-char (point-min))
12297 (widen)
12298 (if (and (looking-at "[ \t]*\n")
12299 (equal (char-before) ?\n))
12300 (delete-region (1- (point)) (point-at-eol)))
12301 ts))))))
12303 (defvar org-log-note-marker (make-marker))
12304 (defvar org-log-note-purpose nil)
12305 (defvar org-log-note-state nil)
12306 (defvar org-log-note-previous-state nil)
12307 (defvar org-log-note-how nil)
12308 (defvar org-log-note-extra nil)
12309 (defvar org-log-note-window-configuration nil)
12310 (defvar org-log-note-return-to (make-marker))
12311 (defvar org-log-note-effective-time nil
12312 "Remembered current time so that dynamically scoped
12313 `org-extend-today-until' affects tha timestamps in state change
12314 log")
12316 (defvar org-log-post-message nil
12317 "Message to be displayed after a log note has been stored.
12318 The auto-repeater uses this.")
12320 (defun org-add-note ()
12321 "Add a note to the current entry.
12322 This is done in the same way as adding a state change note."
12323 (interactive)
12324 (org-add-log-setup 'note nil nil 'findpos nil))
12326 (defvar org-property-end-re)
12327 (defun org-add-log-setup (&optional purpose state prev-state
12328 findpos how extra)
12329 "Set up the post command hook to take a note.
12330 If this is about to TODO state change, the new state is expected in STATE.
12331 When FINDPOS is non-nil, find the correct position for the note in
12332 the current entry. If not, assume that it can be inserted at point.
12333 HOW is an indicator what kind of note should be created.
12334 EXTRA is additional text that will be inserted into the notes buffer."
12335 (let* ((org-log-into-drawer (org-log-into-drawer))
12336 (drawer (cond ((stringp org-log-into-drawer)
12337 org-log-into-drawer)
12338 (org-log-into-drawer "LOGBOOK")
12339 (t nil))))
12340 (save-restriction
12341 (save-excursion
12342 (when findpos
12343 (org-back-to-heading t)
12344 (narrow-to-region (point) (save-excursion
12345 (outline-next-heading) (point)))
12346 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
12347 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
12348 "[^\r\n]*\\)?"))
12349 (goto-char (match-end 0))
12350 (cond
12351 (drawer
12352 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
12353 nil t)
12354 (progn
12355 (goto-char (match-end 0))
12356 (or org-log-states-order-reversed
12357 (and (re-search-forward org-property-end-re nil t)
12358 (goto-char (1- (match-beginning 0))))))
12359 (insert "\n:" drawer ":\n:END:")
12360 (beginning-of-line 0)
12361 (org-indent-line-function)
12362 (beginning-of-line 2)
12363 (org-indent-line-function)
12364 (end-of-line 0)))
12365 ((and org-log-state-notes-insert-after-drawers
12366 (save-excursion
12367 (forward-line) (looking-at org-drawer-regexp)))
12368 (forward-line)
12369 (while (looking-at org-drawer-regexp)
12370 (goto-char (match-end 0))
12371 (re-search-forward org-property-end-re (point-max) t)
12372 (forward-line))
12373 (forward-line -1)))
12374 (unless org-log-states-order-reversed
12375 (and (= (char-after) ?\n) (forward-char 1))
12376 (org-skip-over-state-notes)
12377 (skip-chars-backward " \t\n\r")))
12378 (move-marker org-log-note-marker (point))
12379 (setq org-log-note-purpose purpose
12380 org-log-note-state state
12381 org-log-note-previous-state prev-state
12382 org-log-note-how how
12383 org-log-note-extra extra
12384 org-log-note-effective-time (org-current-effective-time))
12385 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
12387 (defun org-skip-over-state-notes ()
12388 "Skip past the list of State notes in an entry."
12389 (if (looking-at "\n[ \t]*- State") (forward-char 1))
12390 (when (ignore-errors (goto-char (org-in-item-p)))
12391 (let* ((struct (org-list-struct))
12392 (prevs (org-list-prevs-alist struct)))
12393 (while (looking-at "[ \t]*- State")
12394 (goto-char (or (org-list-get-next-item (point) struct prevs)
12395 (org-list-get-item-end (point) struct)))))))
12397 (defun org-add-log-note (&optional purpose)
12398 "Pop up a window for taking a note, and add this note later at point."
12399 (remove-hook 'post-command-hook 'org-add-log-note)
12400 (setq org-log-note-window-configuration (current-window-configuration))
12401 (delete-other-windows)
12402 (move-marker org-log-note-return-to (point))
12403 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
12404 (goto-char org-log-note-marker)
12405 (org-switch-to-buffer-other-window "*Org Note*")
12406 (erase-buffer)
12407 (if (memq org-log-note-how '(time state))
12408 (let (current-prefix-arg) (org-store-log-note))
12409 (let ((org-inhibit-startup t)) (org-mode))
12410 (insert (format "# Insert note for %s.
12411 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
12412 (cond
12413 ((eq org-log-note-purpose 'clock-out) "stopped clock")
12414 ((eq org-log-note-purpose 'done) "closed todo item")
12415 ((eq org-log-note-purpose 'state)
12416 (format "state change from \"%s\" to \"%s\""
12417 (or org-log-note-previous-state "")
12418 (or org-log-note-state "")))
12419 ((eq org-log-note-purpose 'reschedule)
12420 "rescheduling")
12421 ((eq org-log-note-purpose 'delschedule)
12422 "no longer scheduled")
12423 ((eq org-log-note-purpose 'redeadline)
12424 "changing deadline")
12425 ((eq org-log-note-purpose 'deldeadline)
12426 "removing deadline")
12427 ((eq org-log-note-purpose 'refile)
12428 "refiling")
12429 ((eq org-log-note-purpose 'note)
12430 "this entry")
12431 (t (error "This should not happen")))))
12432 (if org-log-note-extra (insert org-log-note-extra))
12433 (org-set-local 'org-finish-function 'org-store-log-note)
12434 (run-hooks 'org-log-buffer-setup-hook)))
12436 (defvar org-note-abort nil) ; dynamically scoped
12437 (defun org-store-log-note ()
12438 "Finish taking a log note, and insert it to where it belongs."
12439 (let ((txt (buffer-string))
12440 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
12441 lines ind bul)
12442 (kill-buffer (current-buffer))
12443 (while (string-match "\\`#.*\n[ \t\n]*" txt)
12444 (setq txt (replace-match "" t t txt)))
12445 (if (string-match "\\s-+\\'" txt)
12446 (setq txt (replace-match "" t t txt)))
12447 (setq lines (org-split-string txt "\n"))
12448 (when (and note (string-match "\\S-" note))
12449 (setq note
12450 (org-replace-escapes
12451 note
12452 (list (cons "%u" (user-login-name))
12453 (cons "%U" user-full-name)
12454 (cons "%t" (format-time-string
12455 (org-time-stamp-format 'long 'inactive)
12456 org-log-note-effective-time))
12457 (cons "%T" (format-time-string
12458 (org-time-stamp-format 'long nil)
12459 org-log-note-effective-time))
12460 (cons "%d" (format-time-string
12461 (org-time-stamp-format nil 'inactive)
12462 org-log-note-effective-time))
12463 (cons "%D" (format-time-string
12464 (org-time-stamp-format nil nil)
12465 org-log-note-effective-time))
12466 (cons "%s" (if org-log-note-state
12467 (concat "\"" org-log-note-state "\"")
12468 ""))
12469 (cons "%S" (if org-log-note-previous-state
12470 (concat "\"" org-log-note-previous-state "\"")
12471 "\"\"")))))
12472 (if lines (setq note (concat note " \\\\")))
12473 (push note lines))
12474 (when (or current-prefix-arg org-note-abort)
12475 (when org-log-into-drawer
12476 (org-remove-empty-drawer-at
12477 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
12478 org-log-note-marker))
12479 (setq lines nil))
12480 (when lines
12481 (with-current-buffer (marker-buffer org-log-note-marker)
12482 (save-excursion
12483 (goto-char org-log-note-marker)
12484 (move-marker org-log-note-marker nil)
12485 (end-of-line 1)
12486 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
12487 (setq ind (save-excursion
12488 (if (ignore-errors (goto-char (org-in-item-p)))
12489 (let ((struct (org-list-struct)))
12490 (org-list-get-ind
12491 (org-list-get-top-point struct) struct))
12492 (skip-chars-backward " \r\t\n")
12493 (cond
12494 ((and (org-at-heading-p)
12495 org-adapt-indentation)
12496 (1+ (org-current-level)))
12497 ((org-at-heading-p) 0)
12498 (t (org-get-indentation))))))
12499 (setq bul (org-list-bullet-string "-"))
12500 (org-indent-line-to ind)
12501 (insert bul (pop lines))
12502 (let ((ind-body (+ (length bul) ind)))
12503 (while lines
12504 (insert "\n")
12505 (org-indent-line-to ind-body)
12506 (insert (pop lines))))
12507 (message "Note stored")
12508 (org-back-to-heading t)
12509 (org-cycle-hide-drawers 'children)))))
12510 (set-window-configuration org-log-note-window-configuration)
12511 (with-current-buffer (marker-buffer org-log-note-return-to)
12512 (goto-char org-log-note-return-to))
12513 (move-marker org-log-note-return-to nil)
12514 (and org-log-post-message (message "%s" org-log-post-message)))
12516 (defun org-remove-empty-drawer-at (drawer pos)
12517 "Remove an empty drawer DRAWER at position POS.
12518 POS may also be a marker."
12519 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
12520 (save-excursion
12521 (save-restriction
12522 (widen)
12523 (goto-char pos)
12524 (if (org-in-regexp
12525 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
12526 (replace-match ""))))))
12528 (defun org-sparse-tree (&optional arg)
12529 "Create a sparse tree, prompt for the details.
12530 This command can create sparse trees. You first need to select the type
12531 of match used to create the tree:
12533 t Show all TODO entries.
12534 T Show entries with a specific TODO keyword.
12535 m Show entries selected by a tags/property match.
12536 p Enter a property name and its value (both with completion on existing
12537 names/values) and show entries with that property.
12538 r Show entries matching a regular expression (`/' can be used as well)
12539 d Show deadlines due within `org-deadline-warning-days'.
12540 b Show deadlines and scheduled items before a date.
12541 a Show deadlines and scheduled items after a date."
12542 (interactive "P")
12543 (let (ans kwd value)
12544 (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")
12545 (setq ans (read-char-exclusive))
12546 (cond
12547 ((equal ans ?d)
12548 (call-interactively 'org-check-deadlines))
12549 ((equal ans ?b)
12550 (call-interactively 'org-check-before-date))
12551 ((equal ans ?a)
12552 (call-interactively 'org-check-after-date))
12553 ((equal ans ?D)
12554 (call-interactively 'org-check-dates-range))
12555 ((equal ans ?t)
12556 (org-show-todo-tree nil))
12557 ((equal ans ?T)
12558 (org-show-todo-tree '(4)))
12559 ((member ans '(?T ?m))
12560 (call-interactively 'org-match-sparse-tree))
12561 ((member ans '(?p ?P))
12562 (setq kwd (org-icompleting-read "Property: "
12563 (mapcar 'list (org-buffer-property-keys))))
12564 (setq value (org-icompleting-read "Value: "
12565 (mapcar 'list (org-property-values kwd))))
12566 (unless (string-match "\\`{.*}\\'" value)
12567 (setq value (concat "\"" value "\"")))
12568 (org-match-sparse-tree arg (concat kwd "=" value)))
12569 ((member ans '(?r ?R ?/))
12570 (call-interactively 'org-occur))
12571 (t (error "No such sparse tree command \"%c\"" ans)))))
12573 (defvar org-occur-highlights nil
12574 "List of overlays used for occur matches.")
12575 (make-variable-buffer-local 'org-occur-highlights)
12576 (defvar org-occur-parameters nil
12577 "Parameters of the active org-occur calls.
12578 This is a list, each call to org-occur pushes as cons cell,
12579 containing the regular expression and the callback, onto the list.
12580 The list can contain several entries if `org-occur' has been called
12581 several time with the KEEP-PREVIOUS argument. Otherwise, this list
12582 will only contain one set of parameters. When the highlights are
12583 removed (for example with `C-c C-c', or with the next edit (depending
12584 on `org-remove-highlights-with-change'), this variable is emptied
12585 as well.")
12586 (make-variable-buffer-local 'org-occur-parameters)
12588 (defun org-occur (regexp &optional keep-previous callback)
12589 "Make a compact tree which shows all matches of REGEXP.
12590 The tree will show the lines where the regexp matches, and all higher
12591 headlines above the match. It will also show the heading after the match,
12592 to make sure editing the matching entry is easy.
12593 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
12594 call to `org-occur' will be kept, to allow stacking of calls to this
12595 command.
12596 If CALLBACK is non-nil, it is a function which is called to confirm
12597 that the match should indeed be shown."
12598 (interactive "sRegexp: \nP")
12599 (when (equal regexp "")
12600 (error "Regexp cannot be empty"))
12601 (unless keep-previous
12602 (org-remove-occur-highlights nil nil t))
12603 (push (cons regexp callback) org-occur-parameters)
12604 (let ((cnt 0))
12605 (save-excursion
12606 (goto-char (point-min))
12607 (if (or (not keep-previous) ; do not want to keep
12608 (not org-occur-highlights)) ; no previous matches
12609 ;; hide everything
12610 (org-overview))
12611 (while (re-search-forward regexp nil t)
12612 (when (or (not callback)
12613 (save-match-data (funcall callback)))
12614 (setq cnt (1+ cnt))
12615 (when org-highlight-sparse-tree-matches
12616 (org-highlight-new-match (match-beginning 0) (match-end 0)))
12617 (org-show-context 'occur-tree))))
12618 (when org-remove-highlights-with-change
12619 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
12620 nil 'local))
12621 (unless org-sparse-tree-open-archived-trees
12622 (org-hide-archived-subtrees (point-min) (point-max)))
12623 (run-hooks 'org-occur-hook)
12624 (if (org-called-interactively-p 'interactive)
12625 (message "%d match(es) for regexp %s" cnt regexp))
12626 cnt))
12628 (defun org-occur-next-match (&optional n reset)
12629 "Function for `next-error-function' to find sparse tree matches.
12630 N is the number of matches to move, when negative move backwards.
12631 RESET is entirely ignored - this function always goes back to the
12632 starting point when no match is found."
12633 (let* ((limit (if (< n 0) (point-min) (point-max)))
12634 (search-func (if (< n 0)
12635 'previous-single-char-property-change
12636 'next-single-char-property-change))
12637 (n (abs n))
12638 (pos (point))
12640 (catch 'exit
12641 (while (setq p1 (funcall search-func (point) 'org-type))
12642 (when (equal p1 limit)
12643 (goto-char pos)
12644 (error "No more matches"))
12645 (when (equal (get-char-property p1 'org-type) 'org-occur)
12646 (setq n (1- n))
12647 (when (= n 0)
12648 (goto-char p1)
12649 (throw 'exit (point))))
12650 (goto-char p1))
12651 (goto-char p1)
12652 (error "No more matches"))))
12654 (defun org-show-context (&optional key)
12655 "Make sure point and context are visible.
12656 How much context is shown depends upon the variables
12657 `org-show-hierarchy-above', `org-show-following-heading',
12658 `org-show-entry-below' and `org-show-siblings'."
12659 (let ((heading-p (org-at-heading-p t))
12660 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
12661 (following-p (org-get-alist-option org-show-following-heading key))
12662 (entry-p (org-get-alist-option org-show-entry-below key))
12663 (siblings-p (org-get-alist-option org-show-siblings key)))
12664 (catch 'exit
12665 ;; Show heading or entry text
12666 (if (and heading-p (not entry-p))
12667 (org-flag-heading nil) ; only show the heading
12668 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
12669 (org-show-hidden-entry))) ; show entire entry
12670 (when following-p
12671 ;; Show next sibling, or heading below text
12672 (save-excursion
12673 (and (if heading-p (org-goto-sibling) (outline-next-heading))
12674 (org-flag-heading nil))))
12675 (when siblings-p (org-show-siblings))
12676 (when hierarchy-p
12677 ;; show all higher headings, possibly with siblings
12678 (save-excursion
12679 (while (and (condition-case nil
12680 (progn (org-up-heading-all 1) t)
12681 (error nil))
12682 (not (bobp)))
12683 (org-flag-heading nil)
12684 (when siblings-p (org-show-siblings))))))))
12686 (defvar org-reveal-start-hook nil
12687 "Hook run before revealing a location.")
12689 (defun org-reveal (&optional siblings)
12690 "Show current entry, hierarchy above it, and the following headline.
12691 This can be used to show a consistent set of context around locations
12692 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
12693 not t for the search context.
12695 With optional argument SIBLINGS, on each level of the hierarchy all
12696 siblings are shown. This repairs the tree structure to what it would
12697 look like when opened with hierarchical calls to `org-cycle'.
12698 With double optional argument \\[universal-argument] \\[universal-argument], \
12699 go to the parent and show the
12700 entire tree."
12701 (interactive "P")
12702 (run-hooks 'org-reveal-start-hook)
12703 (let ((org-show-hierarchy-above t)
12704 (org-show-following-heading t)
12705 (org-show-siblings (if siblings t org-show-siblings)))
12706 (org-show-context nil))
12707 (when (equal siblings '(16))
12708 (save-excursion
12709 (when (org-up-heading-safe)
12710 (org-show-subtree)
12711 (run-hook-with-args 'org-cycle-hook 'subtree)))))
12713 (defun org-highlight-new-match (beg end)
12714 "Highlight from BEG to END and mark the highlight is an occur headline."
12715 (let ((ov (make-overlay beg end)))
12716 (overlay-put ov 'face 'secondary-selection)
12717 (overlay-put ov 'org-type 'org-occur)
12718 (push ov org-occur-highlights)))
12720 (defun org-remove-occur-highlights (&optional beg end noremove)
12721 "Remove the occur highlights from the buffer.
12722 BEG and END are ignored. If NOREMOVE is nil, remove this function
12723 from the `before-change-functions' in the current buffer."
12724 (interactive)
12725 (unless org-inhibit-highlight-removal
12726 (mapc 'delete-overlay org-occur-highlights)
12727 (setq org-occur-highlights nil)
12728 (setq org-occur-parameters nil)
12729 (unless noremove
12730 (remove-hook 'before-change-functions
12731 'org-remove-occur-highlights 'local))))
12733 ;;;; Priorities
12735 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
12736 "Regular expression matching the priority indicator.")
12738 (defvar org-remove-priority-next-time nil)
12740 (defun org-priority-up ()
12741 "Increase the priority of the current item."
12742 (interactive)
12743 (org-priority 'up))
12745 (defun org-priority-down ()
12746 "Decrease the priority of the current item."
12747 (interactive)
12748 (org-priority 'down))
12750 (defun org-priority (&optional action)
12751 "Change the priority of an item by ARG.
12752 ACTION can be `set', `up', `down', or a character."
12753 (interactive)
12754 (unless org-enable-priority-commands
12755 (error "Priority commands are disabled"))
12756 (setq action (or action 'set))
12757 (let (current new news have remove)
12758 (save-excursion
12759 (org-back-to-heading t)
12760 (if (looking-at org-priority-regexp)
12761 (setq current (string-to-char (match-string 2))
12762 have t))
12763 (cond
12764 ((eq action 'remove)
12765 (setq remove t new ?\ ))
12766 ((or (eq action 'set)
12767 (if (featurep 'xemacs) (characterp action) (integerp action)))
12768 (if (not (eq action 'set))
12769 (setq new action)
12770 (message "Priority %c-%c, SPC to remove: "
12771 org-highest-priority org-lowest-priority)
12772 (save-match-data
12773 (setq new (read-char-exclusive))))
12774 (if (and (= (upcase org-highest-priority) org-highest-priority)
12775 (= (upcase org-lowest-priority) org-lowest-priority))
12776 (setq new (upcase new)))
12777 (cond ((equal new ?\ ) (setq remove t))
12778 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
12779 (error "Priority must be between `%c' and `%c'"
12780 org-highest-priority org-lowest-priority))))
12781 ((eq action 'up)
12782 (setq new (if have
12783 (1- current) ; normal cycling
12784 ;; last priority was empty
12785 (if (eq last-command this-command)
12786 org-lowest-priority ; wrap around empty to lowest
12787 ;; default
12788 (if org-priority-start-cycle-with-default
12789 org-default-priority
12790 (1- org-default-priority))))))
12791 ((eq action 'down)
12792 (setq new (if have
12793 (1+ current) ; normal cycling
12794 ;; last priority was empty
12795 (if (eq last-command this-command)
12796 org-highest-priority ; wrap around empty to highest
12797 ;; default
12798 (if org-priority-start-cycle-with-default
12799 org-default-priority
12800 (1+ org-default-priority))))))
12801 (t (error "Invalid action")))
12802 (if (or (< (upcase new) org-highest-priority)
12803 (> (upcase new) org-lowest-priority))
12804 (if (and (memq action '(up down))
12805 (not have) (not (eq last-command this-command)))
12806 ;; `new' is from default priority
12807 (error
12808 "The default can not be set, see `org-default-priority' why")
12809 ;; normal cycling: `new' is beyond highest/lowest priority
12810 ;; and is wrapped around to the empty priority
12811 (setq remove t)))
12812 (setq news (format "%c" new))
12813 (if have
12814 (if remove
12815 (replace-match "" t t nil 1)
12816 (replace-match news t t nil 2))
12817 (if remove
12818 (error "No priority cookie found in line")
12819 (let ((case-fold-search nil))
12820 (looking-at org-todo-line-regexp))
12821 (if (match-end 2)
12822 (progn
12823 (goto-char (match-end 2))
12824 (insert " [#" news "]"))
12825 (goto-char (match-beginning 3))
12826 (insert "[#" news "] "))))
12827 (org-preserve-lc (org-set-tags nil 'align)))
12828 (if remove
12829 (message "Priority removed")
12830 (message "Priority of current item set to %s" news))))
12832 (defun org-get-priority (s)
12833 "Find priority cookie and return priority."
12834 (if (functionp org-get-priority-function)
12835 (funcall org-get-priority-function)
12836 (save-match-data
12837 (if (not (string-match org-priority-regexp s))
12838 (* 1000 (- org-lowest-priority org-default-priority))
12839 (* 1000 (- org-lowest-priority
12840 (string-to-char (match-string 2 s))))))))
12842 ;;;; Tags
12844 (defvar org-agenda-archives-mode)
12845 (defvar org-map-continue-from nil
12846 "Position from where mapping should continue.
12847 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
12849 (defvar org-scanner-tags nil
12850 "The current tag list while the tags scanner is running.")
12851 (defvar org-trust-scanner-tags nil
12852 "Should `org-get-tags-at' use the tags for the scanner.
12853 This is for internal dynamical scoping only.
12854 When this is non-nil, the function `org-get-tags-at' will return the value
12855 of `org-scanner-tags' instead of building the list by itself. This
12856 can lead to large speed-ups when the tags scanner is used in a file with
12857 many entries, and when the list of tags is retrieved, for example to
12858 obtain a list of properties. Building the tags list for each entry in such
12859 a file becomes an N^2 operation - but with this variable set, it scales
12860 as N.")
12862 (defun org-scan-tags (action matcher todo-only &optional start-level)
12863 "Scan headline tags with inheritance and produce output ACTION.
12865 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
12866 or `agenda' to produce an entry list for an agenda view. It can also be
12867 a Lisp form or a function that should be called at each matched headline, in
12868 this case the return value is a list of all return values from these calls.
12870 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
12871 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
12872 only lines with a not-done TODO keyword are included in the output.
12873 This should be the same variable that was scoped into
12874 and set by `org-make-tags-matcher' when it constructed MATCHER.
12876 START-LEVEL can be a string with asterisks, reducing the scope to
12877 headlines matching this string."
12878 (require 'org-agenda)
12879 (let* ((re (concat "^"
12880 (if start-level
12881 ;; Get the correct level to match
12882 (concat "\\*\\{" (number-to-string start-level) "\\} ")
12883 org-outline-regexp)
12884 " *\\(\\<\\("
12885 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
12886 (org-re
12887 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
12888 (props (list 'face 'default
12889 'done-face 'org-agenda-done
12890 'undone-face 'default
12891 'mouse-face 'highlight
12892 'org-not-done-regexp org-not-done-regexp
12893 'org-todo-regexp org-todo-regexp
12894 'org-complex-heading-regexp org-complex-heading-regexp
12895 'help-echo
12896 (format "mouse-2 or RET jump to org file %s"
12897 (abbreviate-file-name
12898 (or (buffer-file-name (buffer-base-buffer))
12899 (buffer-name (buffer-base-buffer)))))))
12900 (case-fold-search nil)
12901 (org-map-continue-from nil)
12902 lspos tags tags-list
12903 (tags-alist (list (cons 0 org-file-tags)))
12904 (llast 0) rtn rtn1 level category i txt
12905 todo marker entry priority)
12906 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
12907 (setq action (list 'lambda nil action)))
12908 (save-excursion
12909 (goto-char (point-min))
12910 (when (eq action 'sparse-tree)
12911 (org-overview)
12912 (org-remove-occur-highlights))
12913 (while (re-search-forward re nil t)
12914 (setq org-map-continue-from nil)
12915 (catch :skip
12916 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
12917 tags (if (match-end 4) (org-match-string-no-properties 4)))
12918 (goto-char (setq lspos (match-beginning 0)))
12919 (setq level (org-reduced-level (funcall outline-level))
12920 category (org-get-category))
12921 (setq i llast llast level)
12922 ;; remove tag lists from same and sublevels
12923 (while (>= i level)
12924 (when (setq entry (assoc i tags-alist))
12925 (setq tags-alist (delete entry tags-alist)))
12926 (setq i (1- i)))
12927 ;; add the next tags
12928 (when tags
12929 (setq tags (org-split-string tags ":")
12930 tags-alist
12931 (cons (cons level tags) tags-alist)))
12932 ;; compile tags for current headline
12933 (setq tags-list
12934 (if org-use-tag-inheritance
12935 (apply 'append (mapcar 'cdr (reverse tags-alist)))
12936 tags)
12937 org-scanner-tags tags-list)
12938 (when org-use-tag-inheritance
12939 (setcdr (car tags-alist)
12940 (mapcar (lambda (x)
12941 (setq x (copy-sequence x))
12942 (org-add-prop-inherited x))
12943 (cdar tags-alist))))
12944 (when (and tags org-use-tag-inheritance
12945 (or (not (eq t org-use-tag-inheritance))
12946 org-tags-exclude-from-inheritance))
12947 ;; selective inheritance, remove uninherited ones
12948 (setcdr (car tags-alist)
12949 (org-remove-uninherited-tags (cdar tags-alist))))
12950 (when (and
12952 ;; eval matcher only when the todo condition is OK
12953 (and (or (not todo-only) (member todo org-not-done-keywords))
12954 (let ((case-fold-search t) (org-trust-scanner-tags t))
12955 (eval matcher)))
12957 ;; Call the skipper, but return t if it does not skip,
12958 ;; so that the `and' form continues evaluating
12959 (progn
12960 (unless (eq action 'sparse-tree) (org-agenda-skip))
12963 ;; Check if timestamps are deselecting this entry
12964 (or (not todo-only)
12965 (and (member todo org-not-done-keywords)
12966 (or (not org-agenda-tags-todo-honor-ignore-options)
12967 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
12969 ;; Extra check for the archive tag
12970 ;; FIXME: Does the skipper already do this????
12972 (not (member org-archive-tag tags-list))
12973 ;; we have an archive tag, should we use this anyway?
12974 (or (not org-agenda-skip-archived-trees)
12975 (and (eq action 'agenda) org-agenda-archives-mode))))
12977 ;; select this headline
12979 (cond
12980 ((eq action 'sparse-tree)
12981 (and org-highlight-sparse-tree-matches
12982 (org-get-heading) (match-end 0)
12983 (org-highlight-new-match
12984 (match-beginning 1) (match-end 1)))
12985 (org-show-context 'tags-tree))
12986 ((eq action 'agenda)
12987 (setq txt (org-agenda-format-item
12989 (concat
12990 (if (eq org-tags-match-list-sublevels 'indented)
12991 (make-string (1- level) ?.) "")
12992 (org-get-heading))
12993 category
12994 tags-list)
12995 priority (org-get-priority txt))
12996 (goto-char lspos)
12997 (setq marker (org-agenda-new-marker))
12998 (org-add-props txt props
12999 'org-marker marker 'org-hd-marker marker 'org-category category
13000 'todo-state todo
13001 'priority priority 'type "tagsmatch")
13002 (push txt rtn))
13003 ((functionp action)
13004 (setq org-map-continue-from nil)
13005 (save-excursion
13006 (setq rtn1 (funcall action))
13007 (push rtn1 rtn)))
13008 (t (error "Invalid action")))
13010 ;; if we are to skip sublevels, jump to end of subtree
13011 (unless org-tags-match-list-sublevels
13012 (org-end-of-subtree t)
13013 (backward-char 1))))
13014 ;; Get the correct position from where to continue
13015 (if org-map-continue-from
13016 (goto-char org-map-continue-from)
13017 (and (= (point) lspos) (end-of-line 1)))))
13018 (when (and (eq action 'sparse-tree)
13019 (not org-sparse-tree-open-archived-trees))
13020 (org-hide-archived-subtrees (point-min) (point-max)))
13021 (nreverse rtn)))
13023 (defun org-remove-uninherited-tags (tags)
13024 "Remove all tags that are not inherited from the list TAGS."
13025 (cond
13026 ((eq org-use-tag-inheritance t)
13027 (if org-tags-exclude-from-inheritance
13028 (org-delete-all org-tags-exclude-from-inheritance tags)
13029 tags))
13030 ((not org-use-tag-inheritance) nil)
13031 ((stringp org-use-tag-inheritance)
13032 (delq nil (mapcar
13033 (lambda (x)
13034 (if (and (string-match org-use-tag-inheritance x)
13035 (not (member x org-tags-exclude-from-inheritance)))
13036 x nil))
13037 tags)))
13038 ((listp org-use-tag-inheritance)
13039 (delq nil (mapcar
13040 (lambda (x)
13041 (if (member x org-use-tag-inheritance) x nil))
13042 tags)))))
13044 (defun org-match-sparse-tree (&optional todo-only match)
13045 "Create a sparse tree according to tags string MATCH.
13046 MATCH can contain positive and negative selection of tags, like
13047 \"+WORK+URGENT-WITHBOSS\".
13048 If optional argument TODO-ONLY is non-nil, only select lines that are
13049 also TODO lines."
13050 (interactive "P")
13051 (org-prepare-agenda-buffers (list (current-buffer)))
13052 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13054 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13056 (defvar org-cached-props nil)
13057 (defun org-cached-entry-get (pom property)
13058 (if (or (eq t org-use-property-inheritance)
13059 (and (stringp org-use-property-inheritance)
13060 (string-match org-use-property-inheritance property))
13061 (and (listp org-use-property-inheritance)
13062 (member property org-use-property-inheritance)))
13063 ;; Caching is not possible, check it directly
13064 (org-entry-get pom property 'inherit)
13065 ;; Get all properties, so that we can do complicated checks easily
13066 (cdr (assoc property (or org-cached-props
13067 (setq org-cached-props
13068 (org-entry-properties pom)))))))
13070 (defun org-global-tags-completion-table (&optional files)
13071 "Return the list of all tags in all agenda buffer/files.
13072 Optional FILES argument is a list of files to which can be used
13073 instead of the agenda files."
13074 (save-excursion
13075 (org-uniquify
13076 (delq nil
13077 (apply 'append
13078 (mapcar
13079 (lambda (file)
13080 (set-buffer (find-file-noselect file))
13081 (append (org-get-buffer-tags)
13082 (mapcar (lambda (x) (if (stringp (car-safe x))
13083 (list (car-safe x)) nil))
13084 org-tag-alist)))
13085 (if (and files (car files))
13086 files
13087 (org-agenda-files))))))))
13089 (defun org-make-tags-matcher (match)
13090 "Create the TAGS/TODO matcher form for the selection string MATCH.
13092 The variable `todo-only' is scoped dynamically into this function; it will be
13093 set to t if the matcher restricts matching to TODO entries,
13094 otherwise will not be touched.
13096 Returns a cons of the selection string MATCH and the constructed
13097 lisp form implementing the matcher. The matcher is to be
13098 evaluated at an Org entry, with point on the headline,
13099 and returns t if the entry matches the
13100 selection string MATCH. The returned lisp form references
13101 two variables with information about the entry, which must be
13102 bound around the form's evaluation: todo, the TODO keyword at the
13103 entry (or nil of none); and tags-list, the list of all tags at the
13104 entry including inherited ones. Additionally, the category
13105 of the entry (if any) must be specified as the text property
13106 'org-category on the headline.
13108 See also `org-scan-tags'.
13110 (declare (special todo-only))
13111 (unless (boundp 'todo-only)
13112 (error "org-make-tags-matcher expects todo-only to be scoped in"))
13113 (unless match
13114 ;; Get a new match request, with completion
13115 (let ((org-last-tags-completion-table
13116 (org-global-tags-completion-table)))
13117 (setq match (org-completing-read-no-i
13118 "Match: " 'org-tags-completion-function nil nil nil
13119 'org-tags-history))))
13121 ;; Parse the string and create a lisp form
13122 (let ((match0 match)
13123 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
13124 minus tag mm
13125 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
13126 orterms term orlist re-p str-p level-p level-op time-p
13127 prop-p pn pv po gv rest)
13128 (if (string-match "/+" match)
13129 ;; match contains also a todo-matching request
13130 (progn
13131 (setq tagsmatch (substring match 0 (match-beginning 0))
13132 todomatch (substring match (match-end 0)))
13133 (if (string-match "^!" todomatch)
13134 (setq todo-only t todomatch (substring todomatch 1)))
13135 (if (string-match "^\\s-*$" todomatch)
13136 (setq todomatch nil)))
13137 ;; only matching tags
13138 (setq tagsmatch match todomatch nil))
13140 ;; Make the tags matcher
13141 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
13142 (setq tagsmatcher t)
13143 (setq orterms (org-split-string tagsmatch "|") orlist nil)
13144 (while (setq term (pop orterms))
13145 (while (and (equal (substring term -1) "\\") orterms)
13146 (setq term (concat term "|" (pop orterms)))) ; repair bad split
13147 (while (string-match re term)
13148 (setq rest (substring term (match-end 0))
13149 minus (and (match-end 1)
13150 (equal (match-string 1 term) "-"))
13151 tag (save-match-data (replace-regexp-in-string
13152 "\\\\-" "-"
13153 (match-string 2 term)))
13154 re-p (equal (string-to-char tag) ?{)
13155 level-p (match-end 4)
13156 prop-p (match-end 5)
13157 mm (cond
13158 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
13159 (level-p
13160 (setq level-op (org-op-to-function (match-string 3 term)))
13161 `(,level-op level ,(string-to-number
13162 (match-string 4 term))))
13163 (prop-p
13164 (setq pn (match-string 5 term)
13165 po (match-string 6 term)
13166 pv (match-string 7 term)
13167 re-p (equal (string-to-char pv) ?{)
13168 str-p (equal (string-to-char pv) ?\")
13169 time-p (save-match-data
13170 (string-match "^\"[[<].*[]>]\"$" pv))
13171 pv (if (or re-p str-p) (substring pv 1 -1) pv))
13172 (if time-p (setq pv (org-matcher-time pv)))
13173 (setq po (org-op-to-function po (if time-p 'time str-p)))
13174 (cond
13175 ((equal pn "CATEGORY")
13176 (setq gv '(get-text-property (point) 'org-category)))
13177 ((equal pn "TODO")
13178 (setq gv 'todo))
13180 (setq gv `(org-cached-entry-get nil ,pn))))
13181 (if re-p
13182 (if (eq po 'org<>)
13183 `(not (string-match ,pv (or ,gv "")))
13184 `(string-match ,pv (or ,gv "")))
13185 (if str-p
13186 `(,po (or ,gv "") ,pv)
13187 `(,po (string-to-number (or ,gv ""))
13188 ,(string-to-number pv) ))))
13189 (t `(member ,tag tags-list)))
13190 mm (if minus (list 'not mm) mm)
13191 term rest)
13192 (push mm tagsmatcher))
13193 (push (if (> (length tagsmatcher) 1)
13194 (cons 'and tagsmatcher)
13195 (car tagsmatcher))
13196 orlist)
13197 (setq tagsmatcher nil))
13198 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
13199 (setq tagsmatcher
13200 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
13201 ;; Make the todo matcher
13202 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
13203 (setq todomatcher t)
13204 (setq orterms (org-split-string todomatch "|") orlist nil)
13205 (while (setq term (pop orterms))
13206 (while (string-match re term)
13207 (setq minus (and (match-end 1)
13208 (equal (match-string 1 term) "-"))
13209 kwd (match-string 2 term)
13210 re-p (equal (string-to-char kwd) ?{)
13211 term (substring term (match-end 0))
13212 mm (if re-p
13213 `(string-match ,(substring kwd 1 -1) todo)
13214 (list 'equal 'todo kwd))
13215 mm (if minus (list 'not mm) mm))
13216 (push mm todomatcher))
13217 (push (if (> (length todomatcher) 1)
13218 (cons 'and todomatcher)
13219 (car todomatcher))
13220 orlist)
13221 (setq todomatcher nil))
13222 (setq todomatcher (if (> (length orlist) 1)
13223 (cons 'or orlist) (car orlist))))
13225 ;; Return the string and lisp forms of the matcher
13226 (setq matcher (if todomatcher
13227 (list 'and tagsmatcher todomatcher)
13228 tagsmatcher))
13229 (when todo-only
13230 (setq matcher (list 'and '(member todo org-not-done-keywords)
13231 matcher)))
13232 (cons match0 matcher)))
13234 (defun org-op-to-function (op &optional stringp)
13235 "Turn an operator into the appropriate function."
13236 (setq op
13237 (cond
13238 ((equal op "<" ) '(< string< org-time<))
13239 ((equal op ">" ) '(> org-string> org-time>))
13240 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
13241 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
13242 ((member op '("=" "==")) '(= string= org-time=))
13243 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
13244 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
13246 (defun org<> (a b) (not (= a b)))
13247 (defun org-string<= (a b) (or (string= a b) (string< a b)))
13248 (defun org-string>= (a b) (not (string< a b)))
13249 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
13250 (defun org-string<> (a b) (not (string= a b)))
13251 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= 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) (org<> a b)))
13257 (defun org-2ft (s)
13258 "Convert S to a floating point time.
13259 If S is already a number, just return it. If it is a string, parse
13260 it as a time string and apply `float-time' to it. If S is nil, just return 0."
13261 (cond
13262 ((numberp s) s)
13263 ((stringp s)
13264 (condition-case nil
13265 (float-time (apply 'encode-time (org-parse-time-string s)))
13266 (error 0.)))
13267 (t 0.)))
13269 (defun org-time-today ()
13270 "Time in seconds today at 0:00.
13271 Returns the float number of seconds since the beginning of the
13272 epoch to the beginning of today (00:00)."
13273 (float-time (apply 'encode-time
13274 (append '(0 0 0) (nthcdr 3 (decode-time))))))
13276 (defun org-matcher-time (s)
13277 "Interpret a time comparison value."
13278 (save-match-data
13279 (cond
13280 ((string= s "<now>") (float-time))
13281 ((string= s "<today>") (org-time-today))
13282 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
13283 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
13284 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
13285 (+ (org-time-today)
13286 (* (string-to-number (match-string 1 s))
13287 (cdr (assoc (match-string 2 s)
13288 '(("d" . 86400.0) ("w" . 604800.0)
13289 ("m" . 2678400.0) ("y" . 31557600.0)))))))
13290 (t (org-2ft s)))))
13292 (defun org-match-any-p (re list)
13293 "Does re match any element of list?"
13294 (setq list (mapcar (lambda (x) (string-match re x)) list))
13295 (delq nil list))
13297 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
13298 (defvar org-tags-overlay (make-overlay 1 1))
13299 (org-detach-overlay org-tags-overlay)
13301 (defun org-get-local-tags-at (&optional pos)
13302 "Get a list of tags defined in the current headline."
13303 (org-get-tags-at pos 'local))
13305 (defun org-get-local-tags ()
13306 "Get a list of tags defined in the current headline."
13307 (org-get-tags-at nil 'local))
13309 (defun org-get-tags-at (&optional pos local)
13310 "Get a list of all headline tags applicable at POS.
13311 POS defaults to point. If tags are inherited, the list contains
13312 the targets in the same sequence as the headlines appear, i.e.
13313 the tags of the current headline come last.
13314 When LOCAL is non-nil, only return tags from the current headline,
13315 ignore inherited ones."
13316 (interactive)
13317 (if (and org-trust-scanner-tags
13318 (or (not pos) (equal pos (point)))
13319 (not local))
13320 org-scanner-tags
13321 (let (tags ltags lastpos parent)
13322 (save-excursion
13323 (save-restriction
13324 (widen)
13325 (goto-char (or pos (point)))
13326 (save-match-data
13327 (catch 'done
13328 (condition-case nil
13329 (progn
13330 (org-back-to-heading t)
13331 (while (not (equal lastpos (point)))
13332 (setq lastpos (point))
13333 (when (looking-at
13334 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
13335 (setq ltags (org-split-string
13336 (org-match-string-no-properties 1) ":"))
13337 (when parent
13338 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
13339 (setq tags (append
13340 (if parent
13341 (org-remove-uninherited-tags ltags)
13342 ltags)
13343 tags)))
13344 (or org-use-tag-inheritance (throw 'done t))
13345 (if local (throw 'done t))
13346 (or (org-up-heading-safe) (error nil))
13347 (setq parent t)))
13348 (error nil)))))
13349 (if local
13350 tags
13351 (append (org-remove-uninherited-tags org-file-tags) tags))))))
13353 (defun org-add-prop-inherited (s)
13354 (add-text-properties 0 (length s) '(inherited t) s)
13357 (defun org-toggle-tag (tag &optional onoff)
13358 "Toggle the tag TAG for the current line.
13359 If ONOFF is `on' or `off', don't toggle but set to this state."
13360 (let (res current)
13361 (save-excursion
13362 (org-back-to-heading t)
13363 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
13364 (point-at-eol) t)
13365 (progn
13366 (setq current (match-string 1))
13367 (replace-match ""))
13368 (setq current ""))
13369 (setq current (nreverse (org-split-string current ":")))
13370 (cond
13371 ((eq onoff 'on)
13372 (setq res t)
13373 (or (member tag current) (push tag current)))
13374 ((eq onoff 'off)
13375 (or (not (member tag current)) (setq current (delete tag current))))
13376 (t (if (member tag current)
13377 (setq current (delete tag current))
13378 (setq res t)
13379 (push tag current))))
13380 (end-of-line 1)
13381 (if current
13382 (progn
13383 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
13384 (org-set-tags nil t))
13385 (delete-horizontal-space))
13386 (run-hooks 'org-after-tags-change-hook))
13387 res))
13389 (defun org-align-tags-here (to-col)
13390 ;; Assumes that this is a headline
13391 (let ((pos (point)) (col (current-column)) ncol tags-l p)
13392 (beginning-of-line 1)
13393 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13394 (< pos (match-beginning 2)))
13395 (progn
13396 (setq tags-l (- (match-end 2) (match-beginning 2)))
13397 (goto-char (match-beginning 1))
13398 (insert " ")
13399 (delete-region (point) (1+ (match-beginning 2)))
13400 (setq ncol (max (current-column)
13401 (1+ col)
13402 (if (> to-col 0)
13403 to-col
13404 (- (abs to-col) tags-l))))
13405 (setq p (point))
13406 (insert (make-string (- ncol (current-column)) ?\ ))
13407 (setq ncol (current-column))
13408 (when indent-tabs-mode (tabify p (point-at-eol)))
13409 (org-move-to-column (min ncol col) t))
13410 (goto-char pos))))
13412 (defun org-set-tags-command (&optional arg just-align)
13413 "Call the set-tags command for the current entry."
13414 (interactive "P")
13415 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
13416 (org-set-tags arg just-align)
13417 (save-excursion
13418 (org-back-to-heading t)
13419 (org-set-tags arg just-align))))
13421 (defun org-set-tags-to (data)
13422 "Set the tags of the current entry to DATA, replacing the current tags.
13423 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
13424 If DATA is nil or the empty string, any tags will be removed."
13425 (interactive "sTags: ")
13426 (setq data
13427 (cond
13428 ((eq data nil) "")
13429 ((equal data "") "")
13430 ((stringp data)
13431 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
13432 ":"))
13433 ((listp data)
13434 (concat ":" (mapconcat 'identity data ":") ":"))
13435 (t nil)))
13436 (when data
13437 (save-excursion
13438 (org-back-to-heading t)
13439 (when (looking-at org-complex-heading-regexp)
13440 (if (match-end 5)
13441 (progn
13442 (goto-char (match-beginning 5))
13443 (insert data)
13444 (delete-region (point) (point-at-eol))
13445 (org-set-tags nil 'align))
13446 (goto-char (point-at-eol))
13447 (insert " " data)
13448 (org-set-tags nil 'align)))
13449 (beginning-of-line 1)
13450 (if (looking-at ".*?\\([ \t]+\\)$")
13451 (delete-region (match-beginning 1) (match-end 1))))))
13453 (defun org-align-all-tags ()
13454 "Align the tags i all headings."
13455 (interactive)
13456 (save-excursion
13457 (or (ignore-errors (org-back-to-heading t))
13458 (outline-next-heading))
13459 (if (org-at-heading-p)
13460 (org-set-tags t)
13461 (message "No headings"))))
13463 (defvar org-indent-indentation-per-level)
13464 (defun org-set-tags (&optional arg just-align)
13465 "Set the tags for the current headline.
13466 With prefix ARG, realign all tags in headings in the current buffer."
13467 (interactive "P")
13468 (let* ((re org-outline-regexp-bol)
13469 (current (unless arg (org-get-tags-string)))
13470 (col (current-column))
13471 (org-setting-tags t)
13472 table current-tags inherited-tags ; computed below when needed
13473 tags p0 c0 c1 rpl di tc level)
13474 (if arg
13475 (save-excursion
13476 (goto-char (point-min))
13477 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
13478 (while (re-search-forward re nil t)
13479 (org-set-tags nil t)
13480 (end-of-line 1)))
13481 (message "All tags realigned to column %d" org-tags-column))
13482 (if just-align
13483 (setq tags current)
13484 ;; Get a new set of tags from the user
13485 (save-excursion
13486 (setq table (append org-tag-persistent-alist
13487 (or org-tag-alist (org-get-buffer-tags))
13488 (and
13489 org-complete-tags-always-offer-all-agenda-tags
13490 (org-global-tags-completion-table
13491 (org-agenda-files))))
13492 org-last-tags-completion-table table
13493 current-tags (org-split-string current ":")
13494 inherited-tags (nreverse
13495 (nthcdr (length current-tags)
13496 (nreverse (org-get-tags-at))))
13497 tags
13498 (if (or (eq t org-use-fast-tag-selection)
13499 (and org-use-fast-tag-selection
13500 (delq nil (mapcar 'cdr table))))
13501 (org-fast-tag-selection
13502 current-tags inherited-tags table
13503 (if org-fast-tag-selection-include-todo
13504 org-todo-key-alist))
13505 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
13506 (org-trim
13507 (org-icompleting-read "Tags: "
13508 'org-tags-completion-function
13509 nil nil current 'org-tags-history))))))
13510 (while (string-match "[-+&]+" tags)
13511 ;; No boolean logic, just a list
13512 (setq tags (replace-match ":" t t tags))))
13514 (setq tags (replace-regexp-in-string "[,]" ":" tags))
13516 (if org-tags-sort-function
13517 (setq tags (mapconcat 'identity
13518 (sort (org-split-string
13519 tags (org-re "[^[:alnum:]_@#%]+"))
13520 org-tags-sort-function) ":")))
13522 (if (string-match "\\`[\t ]*\\'" tags)
13523 (setq tags "")
13524 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
13525 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
13527 ;; Insert new tags at the correct column
13528 (beginning-of-line 1)
13529 (setq level (or (and (looking-at org-outline-regexp)
13530 (- (match-end 0) (point) 1))
13532 (cond
13533 ((and (equal current "") (equal tags "")))
13534 ((re-search-forward
13535 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
13536 (point-at-eol) t)
13537 (if (equal tags "")
13538 (setq rpl "")
13539 (goto-char (match-beginning 0))
13540 (setq c0 (current-column)
13541 ;; compute offset for the case of org-indent-mode active
13542 di (if org-indent-mode
13543 (* (1- org-indent-indentation-per-level) (1- level))
13545 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
13546 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
13547 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
13548 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
13549 (replace-match rpl t t)
13550 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
13551 tags)
13552 (t (error "Tags alignment failed")))
13553 (org-move-to-column col)
13554 (unless just-align
13555 (run-hooks 'org-after-tags-change-hook)))))
13557 (defun org-change-tag-in-region (beg end tag off)
13558 "Add or remove TAG for each entry in the region.
13559 This works in the agenda, and also in an org-mode buffer."
13560 (interactive
13561 (list (region-beginning) (region-end)
13562 (let ((org-last-tags-completion-table
13563 (if (derived-mode-p 'org-mode)
13564 (org-get-buffer-tags)
13565 (org-global-tags-completion-table))))
13566 (org-icompleting-read
13567 "Tag: " 'org-tags-completion-function nil nil nil
13568 'org-tags-history))
13569 (progn
13570 (message "[s]et or [r]emove? ")
13571 (equal (read-char-exclusive) ?r))))
13572 (if (fboundp 'deactivate-mark) (deactivate-mark))
13573 (let ((agendap (equal major-mode 'org-agenda-mode))
13574 l1 l2 m buf pos newhead (cnt 0))
13575 (goto-char end)
13576 (setq l2 (1- (org-current-line)))
13577 (goto-char beg)
13578 (setq l1 (org-current-line))
13579 (loop for l from l1 to l2 do
13580 (org-goto-line l)
13581 (setq m (get-text-property (point) 'org-hd-marker))
13582 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
13583 (and agendap m))
13584 (setq buf (if agendap (marker-buffer m) (current-buffer))
13585 pos (if agendap m (point)))
13586 (with-current-buffer buf
13587 (save-excursion
13588 (save-restriction
13589 (goto-char pos)
13590 (setq cnt (1+ cnt))
13591 (org-toggle-tag tag (if off 'off 'on))
13592 (setq newhead (org-get-heading)))))
13593 (and agendap (org-agenda-change-all-lines newhead m))))
13594 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
13596 (defun org-tags-completion-function (string predicate &optional flag)
13597 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
13598 (confirm (lambda (x) (stringp (car x)))))
13599 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
13600 (setq s1 (match-string 1 string)
13601 s2 (match-string 2 string))
13602 (setq s1 "" s2 string))
13603 (cond
13604 ((eq flag nil)
13605 ;; try completion
13606 (setq rtn (try-completion s2 ctable confirm))
13607 (if (stringp rtn)
13608 (setq rtn
13609 (concat s1 s2 (substring rtn (length s2))
13610 (if (and org-add-colon-after-tag-completion
13611 (assoc rtn ctable))
13612 ":" ""))))
13613 rtn)
13614 ((eq flag t)
13615 ;; all-completions
13616 (all-completions s2 ctable confirm)
13618 ((eq flag 'lambda)
13619 ;; exact match?
13620 (assoc s2 ctable)))
13623 (defun org-fast-tag-insert (kwd tags face &optional end)
13624 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
13625 (insert (format "%-12s" (concat kwd ":"))
13626 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
13627 (or end "")))
13629 (defun org-fast-tag-show-exit (flag)
13630 (save-excursion
13631 (org-goto-line 3)
13632 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
13633 (replace-match ""))
13634 (when flag
13635 (end-of-line 1)
13636 (org-move-to-column (- (window-width) 19) t)
13637 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
13639 (defun org-set-current-tags-overlay (current prefix)
13640 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
13641 (if (featurep 'xemacs)
13642 (org-overlay-display org-tags-overlay (concat prefix s)
13643 'secondary-selection)
13644 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
13645 (org-overlay-display org-tags-overlay (concat prefix s)))))
13647 (defvar org-last-tag-selection-key nil)
13648 (defun org-fast-tag-selection (current inherited table &optional todo-table)
13649 "Fast tag selection with single keys.
13650 CURRENT is the current list of tags in the headline, INHERITED is the
13651 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
13652 possibly with grouping information. TODO-TABLE is a similar table with
13653 TODO keywords, should these have keys assigned to them.
13654 If the keys are nil, a-z are automatically assigned.
13655 Returns the new tags string, or nil to not change the current settings."
13656 (let* ((fulltable (append table todo-table))
13657 (maxlen (apply 'max (mapcar
13658 (lambda (x)
13659 (if (stringp (car x)) (string-width (car x)) 0))
13660 fulltable)))
13661 (buf (current-buffer))
13662 (expert (eq org-fast-tag-selection-single-key 'expert))
13663 (buffer-tags nil)
13664 (fwidth (+ maxlen 3 1 3))
13665 (ncol (/ (- (window-width) 4) fwidth))
13666 (i-face 'org-done)
13667 (c-face 'org-todo)
13668 tg cnt e c char c1 c2 ntable tbl rtn
13669 ov-start ov-end ov-prefix
13670 (exit-after-next org-fast-tag-selection-single-key)
13671 (done-keywords org-done-keywords)
13672 groups ingroup)
13673 (save-excursion
13674 (beginning-of-line 1)
13675 (if (looking-at
13676 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13677 (setq ov-start (match-beginning 1)
13678 ov-end (match-end 1)
13679 ov-prefix "")
13680 (setq ov-start (1- (point-at-eol))
13681 ov-end (1+ ov-start))
13682 (skip-chars-forward "^\n\r")
13683 (setq ov-prefix
13684 (concat
13685 (buffer-substring (1- (point)) (point))
13686 (if (> (current-column) org-tags-column)
13688 (make-string (- org-tags-column (current-column)) ?\ ))))))
13689 (move-overlay org-tags-overlay ov-start ov-end)
13690 (save-window-excursion
13691 (if expert
13692 (set-buffer (get-buffer-create " *Org tags*"))
13693 (delete-other-windows)
13694 (split-window-vertically)
13695 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
13696 (erase-buffer)
13697 (org-set-local 'org-done-keywords done-keywords)
13698 (org-fast-tag-insert "Inherited" inherited i-face "\n")
13699 (org-fast-tag-insert "Current" current c-face "\n\n")
13700 (org-fast-tag-show-exit exit-after-next)
13701 (org-set-current-tags-overlay current ov-prefix)
13702 (setq tbl fulltable char ?a cnt 0)
13703 (while (setq e (pop tbl))
13704 (cond
13705 ((equal (car e) :startgroup)
13706 (push '() groups) (setq ingroup t)
13707 (when (not (= cnt 0))
13708 (setq cnt 0)
13709 (insert "\n"))
13710 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
13711 ((equal (car e) :endgroup)
13712 (setq ingroup nil cnt 0)
13713 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
13714 ((equal e '(:newline))
13715 (when (not (= cnt 0))
13716 (setq cnt 0)
13717 (insert "\n")
13718 (setq e (car tbl))
13719 (while (equal (car tbl) '(:newline))
13720 (insert "\n")
13721 (setq tbl (cdr tbl)))))
13723 (setq tg (copy-sequence (car e)) c2 nil)
13724 (if (cdr e)
13725 (setq c (cdr e))
13726 ;; automatically assign a character.
13727 (setq c1 (string-to-char
13728 (downcase (substring
13729 tg (if (= (string-to-char tg) ?@) 1 0)))))
13730 (if (or (rassoc c1 ntable) (rassoc c1 table))
13731 (while (or (rassoc char ntable) (rassoc char table))
13732 (setq char (1+ char)))
13733 (setq c2 c1))
13734 (setq c (or c2 char)))
13735 (if ingroup (push tg (car groups)))
13736 (setq tg (org-add-props tg nil 'face
13737 (cond
13738 ((not (assoc tg table))
13739 (org-get-todo-face tg))
13740 ((member tg current) c-face)
13741 ((member tg inherited) i-face)
13742 (t nil))))
13743 (if (and (= cnt 0) (not ingroup)) (insert " "))
13744 (insert "[" c "] " tg (make-string
13745 (- fwidth 4 (length tg)) ?\ ))
13746 (push (cons tg c) ntable)
13747 (when (= (setq cnt (1+ cnt)) ncol)
13748 (insert "\n")
13749 (if ingroup (insert " "))
13750 (setq cnt 0)))))
13751 (setq ntable (nreverse ntable))
13752 (insert "\n")
13753 (goto-char (point-min))
13754 (if (not expert) (org-fit-window-to-buffer))
13755 (setq rtn
13756 (catch 'exit
13757 (while t
13758 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
13759 (if (not groups) "no " "")
13760 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
13761 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13762 (setq org-last-tag-selection-key c)
13763 (cond
13764 ((= c ?\r) (throw 'exit t))
13765 ((= c ?!)
13766 (setq groups (not groups))
13767 (goto-char (point-min))
13768 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
13769 ((= c ?\C-c)
13770 (if (not expert)
13771 (org-fast-tag-show-exit
13772 (setq exit-after-next (not exit-after-next)))
13773 (setq expert nil)
13774 (delete-other-windows)
13775 (set-window-buffer (split-window-vertically) " *Org tags*")
13776 (org-switch-to-buffer-other-window " *Org tags*")
13777 (org-fit-window-to-buffer)))
13778 ((or (= c ?\C-g)
13779 (and (= c ?q) (not (rassoc c ntable))))
13780 (org-detach-overlay org-tags-overlay)
13781 (setq quit-flag t))
13782 ((= c ?\ )
13783 (setq current nil)
13784 (if exit-after-next (setq exit-after-next 'now)))
13785 ((= c ?\t)
13786 (condition-case nil
13787 (setq tg (org-icompleting-read
13788 "Tag: "
13789 (or buffer-tags
13790 (with-current-buffer buf
13791 (org-get-buffer-tags)))))
13792 (quit (setq tg "")))
13793 (when (string-match "\\S-" tg)
13794 (add-to-list 'buffer-tags (list tg))
13795 (if (member tg current)
13796 (setq current (delete tg current))
13797 (push tg current)))
13798 (if exit-after-next (setq exit-after-next 'now)))
13799 ((setq e (rassoc c todo-table) tg (car e))
13800 (with-current-buffer buf
13801 (save-excursion (org-todo tg)))
13802 (if exit-after-next (setq exit-after-next 'now)))
13803 ((setq e (rassoc c ntable) tg (car e))
13804 (if (member tg current)
13805 (setq current (delete tg current))
13806 (loop for g in groups do
13807 (if (member tg g)
13808 (mapc (lambda (x)
13809 (setq current (delete x current)))
13810 g)))
13811 (push tg current))
13812 (if exit-after-next (setq exit-after-next 'now))))
13814 ;; Create a sorted list
13815 (setq current
13816 (sort current
13817 (lambda (a b)
13818 (assoc b (cdr (memq (assoc a ntable) ntable))))))
13819 (if (eq exit-after-next 'now) (throw 'exit t))
13820 (goto-char (point-min))
13821 (beginning-of-line 2)
13822 (delete-region (point) (point-at-eol))
13823 (org-fast-tag-insert "Current" current c-face)
13824 (org-set-current-tags-overlay current ov-prefix)
13825 (while (re-search-forward
13826 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
13827 (setq tg (match-string 1))
13828 (add-text-properties
13829 (match-beginning 1) (match-end 1)
13830 (list 'face
13831 (cond
13832 ((member tg current) c-face)
13833 ((member tg inherited) i-face)
13834 (t (get-text-property (match-beginning 1) 'face))))))
13835 (goto-char (point-min)))))
13836 (org-detach-overlay org-tags-overlay)
13837 (if rtn
13838 (mapconcat 'identity current ":")
13839 nil))))
13841 (defun org-get-tags-string ()
13842 "Get the TAGS string in the current headline."
13843 (unless (org-at-heading-p t)
13844 (error "Not on a heading"))
13845 (save-excursion
13846 (beginning-of-line 1)
13847 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13848 (org-match-string-no-properties 1)
13849 "")))
13851 (defun org-get-tags ()
13852 "Get the list of tags specified in the current headline."
13853 (org-split-string (org-get-tags-string) ":"))
13855 (defun org-get-buffer-tags ()
13856 "Get a table of all tags used in the buffer, for completion."
13857 (let (tags)
13858 (save-excursion
13859 (goto-char (point-min))
13860 (while (re-search-forward
13861 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
13862 (when (equal (char-after (point-at-bol 0)) ?*)
13863 (mapc (lambda (x) (add-to-list 'tags x))
13864 (org-split-string (org-match-string-no-properties 1) ":")))))
13865 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
13866 (mapcar 'list tags)))
13868 ;;;; The mapping API
13870 ;;;###autoload
13871 (defun org-map-entries (func &optional match scope &rest skip)
13872 "Call FUNC at each headline selected by MATCH in SCOPE.
13874 FUNC is a function or a lisp form. The function will be called without
13875 arguments, with the cursor positioned at the beginning of the headline.
13876 The return values of all calls to the function will be collected and
13877 returned as a list.
13879 The call to FUNC will be wrapped into a save-excursion form, so FUNC
13880 does not need to preserve point. After evaluation, the cursor will be
13881 moved to the end of the line (presumably of the headline of the
13882 processed entry) and search continues from there. Under some
13883 circumstances, this may not produce the wanted results. For example,
13884 if you have removed (e.g. archived) the current (sub)tree it could
13885 mean that the next entry will be skipped entirely. In such cases, you
13886 can specify the position from where search should continue by making
13887 FUNC set the variable `org-map-continue-from' to the desired buffer
13888 position.
13890 MATCH is a tags/property/todo match as it is used in the agenda tags view.
13891 Only headlines that are matched by this query will be considered during
13892 the iteration. When MATCH is nil or t, all headlines will be
13893 visited by the iteration.
13895 SCOPE determines the scope of this command. It can be any of:
13897 nil The current buffer, respecting the restriction if any
13898 tree The subtree started with the entry at point
13899 region The entries within the active region, if any
13900 region-start-level
13901 The entries within the active region, but only those at
13902 the same level than the first one.
13903 file The current buffer, without restriction
13904 file-with-archives
13905 The current buffer, and any archives associated with it
13906 agenda All agenda files
13907 agenda-with-archives
13908 All agenda files with any archive files associated with them
13909 \(file1 file2 ...)
13910 If this is a list, all files in the list will be scanned
13912 The remaining args are treated as settings for the skipping facilities of
13913 the scanner. The following items can be given here:
13915 archive skip trees with the archive tag.
13916 comment skip trees with the COMMENT keyword
13917 function or Emacs Lisp form:
13918 will be used as value for `org-agenda-skip-function', so whenever
13919 the function returns t, FUNC will not be called for that
13920 entry and search will continue from the point where the
13921 function leaves it.
13923 If your function needs to retrieve the tags including inherited tags
13924 at the *current* entry, you can use the value of the variable
13925 `org-scanner-tags' which will be much faster than getting the value
13926 with `org-get-tags-at'. If your function gets properties with
13927 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
13928 to t around the call to `org-entry-properties' to get the same speedup.
13929 Note that if your function moves around to retrieve tags and properties at
13930 a *different* entry, you cannot use these techniques."
13931 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
13932 (not (org-region-active-p)))
13933 (let* ((org-agenda-archives-mode nil) ; just to make sure
13934 (org-agenda-skip-archived-trees (memq 'archive skip))
13935 (org-agenda-skip-comment-trees (memq 'comment skip))
13936 (org-agenda-skip-function
13937 (car (org-delete-all '(comment archive) skip)))
13938 (org-tags-match-list-sublevels t)
13939 (start-level (eq scope 'region-start-level))
13940 matcher file res
13941 org-todo-keywords-for-agenda
13942 org-done-keywords-for-agenda
13943 org-todo-keyword-alist-for-agenda
13944 org-drawers-for-agenda
13945 org-tag-alist-for-agenda
13946 todo-only)
13948 (cond
13949 ((eq match t) (setq matcher t))
13950 ((eq match nil) (setq matcher t))
13951 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
13953 (save-excursion
13954 (save-restriction
13955 (cond ((eq scope 'tree)
13956 (org-back-to-heading t)
13957 (org-narrow-to-subtree)
13958 (setq scope nil))
13959 ((and (or (eq scope 'region) (eq scope 'region-start-level))
13960 (org-region-active-p))
13961 ;; If needed, set start-level to a string like "2"
13962 (when start-level
13963 (save-excursion
13964 (goto-char (region-beginning))
13965 (unless (org-at-heading-p) (outline-next-heading))
13966 (setq start-level (org-current-level))))
13967 (narrow-to-region (region-beginning)
13968 (save-excursion
13969 (goto-char (region-end))
13970 (unless (and (bolp) (org-at-heading-p))
13971 (outline-next-heading))
13972 (point)))
13973 (setq scope nil)))
13975 (if (not scope)
13976 (progn
13977 (org-prepare-agenda-buffers
13978 (list (buffer-file-name (current-buffer))))
13979 (setq res (org-scan-tags func matcher todo-only start-level)))
13980 ;; Get the right scope
13981 (cond
13982 ((and scope (listp scope) (symbolp (car scope)))
13983 (setq scope (eval scope)))
13984 ((eq scope 'agenda)
13985 (setq scope (org-agenda-files t)))
13986 ((eq scope 'agenda-with-archives)
13987 (setq scope (org-agenda-files t))
13988 (setq scope (org-add-archive-files scope)))
13989 ((eq scope 'file)
13990 (setq scope (list (buffer-file-name))))
13991 ((eq scope 'file-with-archives)
13992 (setq scope (org-add-archive-files (list (buffer-file-name))))))
13993 (org-prepare-agenda-buffers scope)
13994 (while (setq file (pop scope))
13995 (with-current-buffer (org-find-base-buffer-visiting file)
13996 (save-excursion
13997 (save-restriction
13998 (widen)
13999 (goto-char (point-min))
14000 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
14001 res)))
14003 ;;;; Properties
14005 ;;; Setting and retrieving properties
14007 (defconst org-special-properties
14008 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
14009 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM")
14010 "The special properties valid in Org-mode.
14012 These are properties that are not defined in the property drawer,
14013 but in some other way.")
14015 (defconst org-default-properties
14016 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
14017 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
14018 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
14019 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
14020 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
14021 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
14022 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
14023 "Some properties that are used by Org-mode for various purposes.
14024 Being in this list makes sure that they are offered for completion.")
14026 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
14027 "Regular expression matching the first line of a property drawer.")
14029 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
14030 "Regular expression matching the last line of a property drawer.")
14032 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
14033 "Regular expression matching the first line of a property drawer.")
14035 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
14036 "Regular expression matching the first line of a property drawer.")
14038 (defconst org-property-drawer-re
14039 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
14040 org-property-end-re "\\)\n?")
14041 "Matches an entire property drawer.")
14043 (defconst org-clock-drawer-re
14044 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
14045 org-property-end-re "\\)\n?")
14046 "Matches an entire clock drawer.")
14048 (defsubst org-re-property (property)
14049 "Return a regexp matching PROPERTY.
14050 Match group 1 will be set to the value "
14051 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
14053 (defun org-property-action ()
14054 "Do an action on properties."
14055 (interactive)
14056 (let (c)
14057 (org-at-property-p)
14058 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14059 (setq c (read-char-exclusive))
14060 (cond
14061 ((equal c ?s)
14062 (call-interactively 'org-set-property))
14063 ((equal c ?d)
14064 (call-interactively 'org-delete-property))
14065 ((equal c ?D)
14066 (call-interactively 'org-delete-property-globally))
14067 ((equal c ?c)
14068 (call-interactively 'org-compute-property-at-point))
14069 (t (error "No such property action %c" c)))))
14071 (defun org-set-effort (&optional value)
14072 "Set the effort property of the current entry.
14073 With numerical prefix arg, use the nth allowed value, 0 stands for the 10th
14074 allowed value."
14075 (interactive "P")
14076 (if (equal value 0) (setq value 10))
14077 (let* ((completion-ignore-case t)
14078 (prop org-effort-property)
14079 (cur (org-entry-get nil prop))
14080 (allowed (org-property-get-allowed-values nil prop 'table))
14081 (existing (mapcar 'list (org-property-values prop)))
14083 (val (cond
14084 ((stringp value) value)
14085 ((and allowed (integerp value))
14086 (or (car (nth (1- value) allowed))
14087 (car (org-last allowed))))
14088 (allowed
14089 (message "Select 1-9,0, [RET%s]: %s"
14090 (if cur (concat "=" cur) "")
14091 (mapconcat 'car allowed " "))
14092 (setq rpl (read-char-exclusive))
14093 (if (equal rpl ?\r)
14095 (setq rpl (- rpl ?0))
14096 (if (equal rpl 0) (setq rpl 10))
14097 (if (and (> rpl 0) (<= rpl (length allowed)))
14098 (car (nth (1- rpl) allowed))
14099 (org-completing-read "Effort: " allowed nil))))
14101 (let (org-completion-use-ido org-completion-use-iswitchb)
14102 (org-completing-read
14103 (concat "Effort " (if (and cur (string-match "\\S-" cur))
14104 (concat "[" cur "]") "")
14105 ": ")
14106 existing nil nil "" nil cur))))))
14107 (unless (equal (org-entry-get nil prop) val)
14108 (org-entry-put nil prop val))
14109 (message "%s is now %s" prop val)))
14111 (defun org-at-property-p ()
14112 "Is cursor inside a property drawer?"
14113 (save-excursion
14114 (beginning-of-line 1)
14115 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
14116 (save-match-data ;; Used by calling procedures
14117 (let ((p (point))
14118 (range (unless (org-before-first-heading-p)
14119 (org-get-property-block))))
14120 (and range (<= (car range) p) (< p (cdr range))))))))
14122 (defun org-get-property-block (&optional beg end force)
14123 "Return the (beg . end) range of the body of the property drawer.
14124 BEG and END can be beginning and end of subtree, if not given
14125 they will be found.
14126 If the drawer does not exist and FORCE is non-nil, create the drawer."
14127 (catch 'exit
14128 (save-excursion
14129 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
14130 (end (or end (progn (outline-next-heading) (point)))))
14131 (goto-char beg)
14132 (if (re-search-forward org-property-start-re end t)
14133 (setq beg (1+ (match-end 0)))
14134 (if force
14135 (save-excursion
14136 (org-insert-property-drawer)
14137 (setq end (progn (outline-next-heading) (point))))
14138 (throw 'exit nil))
14139 (goto-char beg)
14140 (if (re-search-forward org-property-start-re end t)
14141 (setq beg (1+ (match-end 0)))))
14142 (if (re-search-forward org-property-end-re end t)
14143 (setq end (match-beginning 0))
14144 (or force (throw 'exit nil))
14145 (goto-char beg)
14146 (setq end beg)
14147 (org-indent-line-function)
14148 (insert ":END:\n"))
14149 (cons beg end)))))
14151 (defun org-entry-properties (&optional pom which specific)
14152 "Get all properties of the entry at point-or-marker POM.
14153 This includes the TODO keyword, the tags, time strings for deadline,
14154 scheduled, and clocking, and any additional properties defined in the
14155 entry. The return value is an alist, keys may occur multiple times
14156 if the property key was used several times.
14157 POM may also be nil, in which case the current entry is used.
14158 If WHICH is nil or `all', get all properties. If WHICH is
14159 `special' or `standard', only get that subclass. If WHICH
14160 is a string only get exactly this property. SPECIFIC can be a string, the
14161 specific property we are interested in. Specifying it can speed
14162 things up because then unnecessary parsing is avoided."
14163 (setq which (or which 'all))
14164 (org-with-point-at pom
14165 (let ((clockstr (substring org-clock-string 0 -1))
14166 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
14167 (case-fold-search nil)
14168 beg end range props sum-props key key1 value string clocksum)
14169 (save-excursion
14170 (when (condition-case nil
14171 (and (derived-mode-p 'org-mode) (org-back-to-heading t))
14172 (error nil))
14173 (setq beg (point))
14174 (setq sum-props (get-text-property (point) 'org-summaries))
14175 (setq clocksum (get-text-property (point) :org-clock-minutes))
14176 (outline-next-heading)
14177 (setq end (point))
14178 (when (memq which '(all special))
14179 ;; Get the special properties, like TODO and tags
14180 (goto-char beg)
14181 (when (and (or (not specific) (string= specific "TODO"))
14182 (looking-at org-todo-line-regexp) (match-end 2))
14183 (push (cons "TODO" (org-match-string-no-properties 2)) props))
14184 (when (and (or (not specific) (string= specific "PRIORITY"))
14185 (looking-at org-priority-regexp))
14186 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
14187 (when (or (not specific) (string= specific "FILE"))
14188 (push (cons "FILE" buffer-file-name) props))
14189 (when (and (or (not specific) (string= specific "TAGS"))
14190 (setq value (org-get-tags-string))
14191 (string-match "\\S-" value))
14192 (push (cons "TAGS" value) props))
14193 (when (and (or (not specific) (string= specific "ALLTAGS"))
14194 (setq value (org-get-tags-at)))
14195 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
14196 ":"))
14197 props))
14198 (when (or (not specific) (string= specific "BLOCKED"))
14199 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
14200 (when (or (not specific)
14201 (member specific
14202 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
14203 "TIMESTAMP" "TIMESTAMP_IA")))
14204 (catch 'match
14205 (while (re-search-forward org-maybe-keyword-time-regexp end t)
14206 (setq key (if (match-end 1)
14207 (substring (org-match-string-no-properties 1)
14208 0 -1))
14209 string (if (equal key clockstr)
14210 (org-no-properties
14211 (org-trim
14212 (buffer-substring
14213 (match-beginning 3) (goto-char
14214 (point-at-eol)))))
14215 (substring (org-match-string-no-properties 3)
14216 1 -1)))
14217 ;; Get the correct property name from the key. This is
14218 ;; necessary if the user has configured time keywords.
14219 (setq key1 (concat key ":"))
14220 (cond
14221 ((not key)
14222 (setq key
14223 (if (= (char-after (match-beginning 3)) ?\[)
14224 "TIMESTAMP_IA" "TIMESTAMP")))
14225 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
14226 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
14227 ((equal key1 org-closed-string) (setq key "CLOSED"))
14228 ((equal key1 org-clock-string) (setq key "CLOCK")))
14229 (if (and specific (equal key specific) (not (equal key "CLOCK")))
14230 (progn
14231 (push (cons key string) props)
14232 ;; no need to search further if match is found
14233 (throw 'match t))
14234 (when (or (equal key "CLOCK") (not (assoc key props)))
14235 (push (cons key string) props))))))
14238 (when (memq which '(all standard))
14239 ;; Get the standard properties, like :PROP: ...
14240 (setq range (org-get-property-block beg end))
14241 (when range
14242 (goto-char (car range))
14243 (while (re-search-forward
14244 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
14245 (cdr range) t)
14246 (setq key (org-match-string-no-properties 1)
14247 value (org-trim (or (org-match-string-no-properties 2) "")))
14248 (unless (member key excluded)
14249 (push (cons key (or value "")) props)))))
14250 (if clocksum
14251 (push (cons "CLOCKSUM"
14252 (org-columns-number-to-string (/ (float clocksum) 60.)
14253 'add_times))
14254 props))
14255 (unless (assoc "CATEGORY" props)
14256 (push (cons "CATEGORY" (org-get-category)) props))
14257 (append sum-props (nreverse props)))))))
14259 (defun org-entry-get (pom property &optional inherit literal-nil)
14260 "Get value of PROPERTY for entry at point-or-marker POM.
14261 If INHERIT is non-nil and the entry does not have the property,
14262 then also check higher levels of the hierarchy.
14263 If INHERIT is the symbol `selective', use inheritance only if the setting
14264 in `org-use-property-inheritance' selects PROPERTY for inheritance.
14265 If the property is present but empty, the return value is the empty string.
14266 If the property is not present at all, nil is returned.
14268 If LITERAL-NIL is set, return the string value \"nil\" as a string,
14269 do not interpret it as the list atom nil. This is used for inheritance
14270 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
14271 (org-with-point-at pom
14272 (if (and inherit (if (eq inherit 'selective)
14273 (org-property-inherit-p property)
14275 (org-entry-get-with-inheritance property literal-nil)
14276 (if (member property org-special-properties)
14277 ;; We need a special property. Use `org-entry-properties' to
14278 ;; retrieve it, but specify the wanted property
14279 (cdr (assoc property (org-entry-properties nil 'special property)))
14280 (let ((range (unless (org-before-first-heading-p)
14281 (org-get-property-block)))
14282 (props (list (or (assoc property org-file-properties)
14283 (assoc property org-global-properties)
14284 (assoc property org-global-properties-fixed))))
14285 val)
14286 (flet ((ap (key)
14287 (when (re-search-forward
14288 (org-re-property key) (cdr range) t)
14289 (setq props
14290 (org-update-property-plist
14292 (if (match-end 1)
14293 (org-match-string-no-properties 1) "")
14294 props)))))
14295 (when (and range (goto-char (car range)))
14296 (ap property)
14297 (goto-char (car range))
14298 (while (ap (concat property "+")))
14299 (setq val (cdr (assoc property props)))
14300 (when val (if literal-nil val (org-not-nil val))))))))))
14302 (defun org-property-or-variable-value (var &optional inherit)
14303 "Check if there is a property fixing the value of VAR.
14304 If yes, return this value. If not, return the current value of the variable."
14305 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14306 (if (and prop (stringp prop) (string-match "\\S-" prop))
14307 (read prop)
14308 (symbol-value var))))
14310 (defun org-entry-delete (pom property)
14311 "Delete the property PROPERTY from entry at point-or-marker POM."
14312 (org-with-point-at pom
14313 (if (member property org-special-properties)
14314 nil ; cannot delete these properties.
14315 (let ((range (org-get-property-block)))
14316 (if (and range
14317 (goto-char (car range))
14318 (re-search-forward
14319 (org-re-property property)
14320 (cdr range) t))
14321 (progn
14322 (delete-region (match-beginning 0) (1+ (point-at-eol)))
14324 nil)))))
14326 ;; Multi-values properties are properties that contain multiple values
14327 ;; These values are assumed to be single words, separated by whitespace.
14328 (defun org-entry-add-to-multivalued-property (pom property value)
14329 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
14330 (let* ((old (org-entry-get pom property))
14331 (values (and old (org-split-string old "[ \t]"))))
14332 (setq value (org-entry-protect-space value))
14333 (unless (member value values)
14334 (setq values (cons value values))
14335 (org-entry-put pom property
14336 (mapconcat 'identity values " ")))))
14338 (defun org-entry-remove-from-multivalued-property (pom property value)
14339 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
14340 (let* ((old (org-entry-get pom property))
14341 (values (and old (org-split-string old "[ \t]"))))
14342 (setq value (org-entry-protect-space value))
14343 (when (member value values)
14344 (setq values (delete value values))
14345 (org-entry-put pom property
14346 (mapconcat 'identity values " ")))))
14348 (defun org-entry-member-in-multivalued-property (pom property value)
14349 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
14350 (let* ((old (org-entry-get pom property))
14351 (values (and old (org-split-string old "[ \t]"))))
14352 (setq value (org-entry-protect-space value))
14353 (member value values)))
14355 (defun org-entry-get-multivalued-property (pom property)
14356 "Return a list of values in a multivalued property."
14357 (let* ((value (org-entry-get pom property))
14358 (values (and value (org-split-string value "[ \t]"))))
14359 (mapcar 'org-entry-restore-space values)))
14361 (defun org-entry-put-multivalued-property (pom property &rest values)
14362 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
14363 VALUES should be a list of strings. Spaces will be protected."
14364 (org-entry-put pom property
14365 (mapconcat 'org-entry-protect-space values " "))
14366 (let* ((value (org-entry-get pom property))
14367 (values (and value (org-split-string value "[ \t]"))))
14368 (mapcar 'org-entry-restore-space values)))
14370 (defun org-entry-protect-space (s)
14371 "Protect spaces and newline in string S."
14372 (while (string-match " " s)
14373 (setq s (replace-match "%20" t t s)))
14374 (while (string-match "\n" s)
14375 (setq s (replace-match "%0A" t t s)))
14378 (defun org-entry-restore-space (s)
14379 "Restore spaces and newline in string S."
14380 (while (string-match "%20" s)
14381 (setq s (replace-match " " t t s)))
14382 (while (string-match "%0A" s)
14383 (setq s (replace-match "\n" t t s)))
14386 (defvar org-entry-property-inherited-from (make-marker)
14387 "Marker pointing to the entry from where a property was inherited.
14388 Each call to `org-entry-get-with-inheritance' will set this marker to the
14389 location of the entry where the inheritance search matched. If there was
14390 no match, the marker will point nowhere.
14391 Note that also `org-entry-get' calls this function, if the INHERIT flag
14392 is set.")
14394 (defun org-entry-get-with-inheritance (property &optional literal-nil)
14395 "Get entry property, and search higher levels if not present.
14396 The search will stop at the first ancestor which has the property defined.
14397 If the value found is \"nil\", return nil to show that the property
14398 should be considered as undefined (this is the meaning of nil here).
14399 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
14400 (move-marker org-entry-property-inherited-from nil)
14401 (let (tmp)
14402 (unless (org-before-first-heading-p)
14403 (save-excursion
14404 (save-restriction
14405 (widen)
14406 (catch 'ex
14407 (while t
14408 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
14409 (org-back-to-heading t)
14410 (move-marker org-entry-property-inherited-from (point))
14411 (throw 'ex tmp))
14412 (or (org-up-heading-safe) (throw 'ex nil)))))))
14413 (setq tmp (or tmp
14414 (cdr (assoc property org-file-properties))
14415 (cdr (assoc property org-global-properties))
14416 (cdr (assoc property org-global-properties-fixed))))
14417 (if literal-nil tmp (org-not-nil tmp))))
14419 (defvar org-property-changed-functions nil
14420 "Hook called when the value of a property has changed.
14421 Each hook function should accept two arguments, the name of the property
14422 and the new value.")
14424 (defun org-entry-put (pom property value)
14425 "Set PROPERTY to VALUE for entry at point-or-marker POM."
14426 (org-with-point-at pom
14427 (org-back-to-heading t)
14428 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
14429 range)
14430 (cond
14431 ((equal property "TODO")
14432 (when (and (stringp value) (string-match "\\S-" value)
14433 (not (member value org-todo-keywords-1)))
14434 (error "\"%s\" is not a valid TODO state" value))
14435 (if (or (not value)
14436 (not (string-match "\\S-" value)))
14437 (setq value 'none))
14438 (org-todo value)
14439 (org-set-tags nil 'align))
14440 ((equal property "PRIORITY")
14441 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
14442 (string-to-char value) ?\ ))
14443 (org-set-tags nil 'align))
14444 ((equal property "SCHEDULED")
14445 (if (re-search-forward org-scheduled-time-regexp end t)
14446 (cond
14447 ((eq value 'earlier) (org-timestamp-change -1 'day))
14448 ((eq value 'later) (org-timestamp-change 1 'day))
14449 (t (call-interactively 'org-schedule)))
14450 (call-interactively 'org-schedule)))
14451 ((equal property "DEADLINE")
14452 (if (re-search-forward org-deadline-time-regexp end t)
14453 (cond
14454 ((eq value 'earlier) (org-timestamp-change -1 'day))
14455 ((eq value 'later) (org-timestamp-change 1 'day))
14456 (t (call-interactively 'org-deadline)))
14457 (call-interactively 'org-deadline)))
14458 ((member property org-special-properties)
14459 (error "The %s property can not yet be set with `org-entry-put'"
14460 property))
14461 (t ; a non-special property
14462 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
14463 (setq range (org-get-property-block beg end 'force))
14464 (goto-char (car range))
14465 (if (re-search-forward
14466 (org-re-property property) (cdr range) t)
14467 (progn
14468 (delete-region (match-beginning 0) (match-end 0))
14469 (goto-char (match-beginning 0)))
14470 (goto-char (cdr range))
14471 (insert "\n")
14472 (backward-char 1)
14473 (org-indent-line-function))
14474 (insert ":" property ":")
14475 (and value (insert " " value))
14476 (org-indent-line-function)))))
14477 (run-hook-with-args 'org-property-changed-functions property value)))
14479 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
14480 "Get all property keys in the current buffer.
14481 With INCLUDE-SPECIALS, also list the special properties that reflect things
14482 like tags and TODO state.
14483 With INCLUDE-DEFAULTS, also include properties that has special meaning
14484 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
14485 and others.
14486 With INCLUDE-COLUMNS, also include property names given in COLUMN
14487 formats in the current buffer."
14488 (let (rtn range cfmt s p)
14489 (save-excursion
14490 (save-restriction
14491 (widen)
14492 (goto-char (point-min))
14493 (while (re-search-forward org-property-start-re nil t)
14494 (setq range (org-get-property-block))
14495 (goto-char (car range))
14496 (while (re-search-forward
14497 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
14498 (cdr range) t)
14499 (add-to-list 'rtn (org-match-string-no-properties 1)))
14500 (outline-next-heading))))
14502 (when include-specials
14503 (setq rtn (append org-special-properties rtn)))
14505 (when include-defaults
14506 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
14507 (add-to-list 'rtn org-effort-property))
14509 (when include-columns
14510 (save-excursion
14511 (save-restriction
14512 (widen)
14513 (goto-char (point-min))
14514 (while (re-search-forward
14515 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
14516 nil t)
14517 (setq cfmt (match-string 2) s 0)
14518 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
14519 cfmt s)
14520 (setq s (match-end 0)
14521 p (match-string 1 cfmt))
14522 (unless (or (equal p "ITEM")
14523 (member p org-special-properties))
14524 (add-to-list 'rtn (match-string 1 cfmt))))))))
14526 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
14528 (defun org-property-values (key)
14529 "Return a list of all values of property KEY in the current buffer."
14530 (save-excursion
14531 (save-restriction
14532 (widen)
14533 (goto-char (point-min))
14534 (let ((re (org-re-property key))
14535 values)
14536 (while (re-search-forward re nil t)
14537 (add-to-list 'values (org-trim (match-string 1))))
14538 (delete "" values)))))
14540 (defun org-insert-property-drawer ()
14541 "Insert a property drawer into the current entry."
14542 (org-back-to-heading t)
14543 (looking-at org-outline-regexp)
14544 (let ((indent (if org-adapt-indentation
14545 (- (match-end 0) (match-beginning 0))
14547 (beg (point))
14548 (re (concat "^[ \t]*" org-keyword-time-regexp))
14549 end hiddenp)
14550 (outline-next-heading)
14551 (setq end (point))
14552 (goto-char beg)
14553 (while (re-search-forward re end t))
14554 (setq hiddenp (outline-invisible-p))
14555 (end-of-line 1)
14556 (and (equal (char-after) ?\n) (forward-char 1))
14557 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
14558 (if (member (match-string 1) '("CLOCK:" ":END:"))
14559 ;; just skip this line
14560 (beginning-of-line 2)
14561 ;; Drawer start, find the end
14562 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
14563 (beginning-of-line 1)))
14564 (org-skip-over-state-notes)
14565 (skip-chars-backward " \t\n\r")
14566 (if (eq (char-before) ?*) (forward-char 1))
14567 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
14568 (beginning-of-line 0)
14569 (org-indent-to-column indent)
14570 (beginning-of-line 2)
14571 (org-indent-to-column indent)
14572 (beginning-of-line 0)
14573 (if hiddenp
14574 (save-excursion
14575 (org-back-to-heading t)
14576 (hide-entry))
14577 (org-flag-drawer t))))
14579 (defun org-insert-drawer (&optional arg drawer)
14580 "Insert a drawer at point.
14582 Optional argument DRAWER, when non-nil, is a string representing
14583 drawer's name. Otherwise, the user is prompted for a name.
14585 If a region is active, insert the drawer around that region
14586 instead.
14588 Point is left between drawer's boundaries."
14589 (interactive "P")
14590 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
14591 "LOGBOOK"))
14592 ;; SYSTEM-DRAWERS is a list of drawer names that are used
14593 ;; internally by Org. They are meant to be inserted
14594 ;; automatically.
14595 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
14596 ;; Remove system drawers from list. Note: For some reason,
14597 ;; `org-completing-read' ignores the predicate while
14598 ;; `completing-read' handles it fine.
14599 (drawer (if arg "PROPERTIES"
14600 (or drawer
14601 (completing-read
14602 "Drawer: " org-drawers
14603 (lambda (d) (not (member d system-drawers))))))))
14604 (cond
14605 ;; With C-u, fall back on `org-insert-property-drawer'
14606 (arg (org-insert-property-drawer))
14607 ;; With an active region, insert a drawer at point.
14608 ((not (org-region-active-p))
14609 (progn
14610 (unless (bolp) (insert "\n"))
14611 (insert (format ":%s:\n\n:END:\n" drawer))
14612 (forward-line -2)))
14613 ;; Otherwise, insert the drawer at point
14615 (let ((rbeg (region-beginning))
14616 (rend (copy-marker (region-end))))
14617 (unwind-protect
14618 (progn
14619 (goto-char rbeg)
14620 (beginning-of-line)
14621 (when (save-excursion
14622 (re-search-forward org-outline-regexp-bol rend t))
14623 (error "Drawers cannot contain headlines"))
14624 ;; Position point at the beginning of the first
14625 ;; non-blank line in region. Insert drawer's opening
14626 ;; there, then indent it.
14627 (org-skip-whitespace)
14628 (beginning-of-line)
14629 (insert ":" drawer ":\n")
14630 (forward-line -1)
14631 (indent-for-tab-command)
14632 ;; Move point to the beginning of the first blank line
14633 ;; after the last non-blank line in region. Insert
14634 ;; drawer's closing, then indent it.
14635 (goto-char rend)
14636 (skip-chars-backward " \r\t\n")
14637 (insert "\n:END:")
14638 (indent-for-tab-command)
14639 (unless (eolp) (insert "\n")))
14640 ;; Clear marker, whatever the outcome of insertion is.
14641 (set-marker rend nil)))))))
14643 (defvar org-property-set-functions-alist nil
14644 "Property set function alist.
14645 Each entry should have the following format:
14647 (PROPERTY . READ-FUNCTION)
14649 The read function will be called with the same argument as
14650 `org-completing-read'.")
14652 (defun org-set-property-function (property)
14653 "Get the function that should be used to set PROPERTY.
14654 This is computed according to `org-property-set-functions-alist'."
14655 (or (cdr (assoc property org-property-set-functions-alist))
14656 'org-completing-read))
14658 (defun org-read-property-value (property)
14659 "Read PROPERTY value from user."
14660 (let* ((completion-ignore-case t)
14661 (allowed (org-property-get-allowed-values nil property 'table))
14662 (cur (org-entry-get nil property))
14663 (prompt (concat property " value"
14664 (if (and cur (string-match "\\S-" cur))
14665 (concat " [" cur "]") "") ": "))
14666 (set-function (org-set-property-function property))
14667 (val (if allowed
14668 (funcall set-function prompt allowed nil
14669 (not (get-text-property 0 'org-unrestricted
14670 (caar allowed))))
14671 (let (org-completion-use-ido org-completion-use-iswitchb)
14672 (funcall set-function prompt
14673 (mapcar 'list (org-property-values property))
14674 nil nil "" nil cur)))))
14675 (if (equal val "")
14677 val)))
14679 (defvar org-last-set-property nil)
14680 (defun org-read-property-name ()
14681 "Read a property name."
14682 (let* ((completion-ignore-case t)
14683 (keys (org-buffer-property-keys nil t t))
14684 (default-prop (or (save-excursion
14685 (save-match-data
14686 (beginning-of-line)
14687 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
14688 (null (string= (match-string 1) "END"))
14689 (match-string 1))))
14690 org-last-set-property))
14691 (property (org-icompleting-read
14692 (concat "Property"
14693 (if default-prop (concat " [" default-prop "]") "")
14694 ": ")
14695 (mapcar 'list keys)
14696 nil nil nil nil
14697 default-prop
14699 (if (member property keys)
14700 property
14701 (or (cdr (assoc (downcase property)
14702 (mapcar (lambda (x) (cons (downcase x) x))
14703 keys)))
14704 property))))
14706 (defun org-set-property (property value)
14707 "In the current entry, set PROPERTY to VALUE.
14708 When called interactively, this will prompt for a property name, offering
14709 completion on existing and default properties. And then it will prompt
14710 for a value, offering completion either on allowed values (via an inherited
14711 xxx_ALL property) or on existing values in other instances of this property
14712 in the current file."
14713 (interactive (list nil nil))
14714 (let* ((property (or property (org-read-property-name)))
14715 (value (or value (org-read-property-value property)))
14716 (fn (assoc property org-properties-postprocess-alist)))
14717 (setq org-last-set-property property)
14718 ;; Possibly postprocess the inserted value:
14719 (when fn (setq value (funcall (cadr fn) value)))
14720 (unless (equal (org-entry-get nil property) value)
14721 (org-entry-put nil property value))))
14723 (defun org-delete-property (property)
14724 "In the current entry, delete PROPERTY."
14725 (interactive
14726 (let* ((completion-ignore-case t)
14727 (prop (org-icompleting-read "Property: "
14728 (org-entry-properties nil 'standard))))
14729 (list prop)))
14730 (message "Property %s %s" property
14731 (if (org-entry-delete nil property)
14732 "deleted"
14733 "was not present in the entry")))
14735 (defun org-delete-property-globally (property)
14736 "Remove PROPERTY globally, from all entries."
14737 (interactive
14738 (let* ((completion-ignore-case t)
14739 (prop (org-icompleting-read
14740 "Globally remove property: "
14741 (mapcar 'list (org-buffer-property-keys)))))
14742 (list prop)))
14743 (save-excursion
14744 (save-restriction
14745 (widen)
14746 (goto-char (point-min))
14747 (let ((cnt 0))
14748 (while (re-search-forward
14749 (org-re-property property)
14750 nil t)
14751 (setq cnt (1+ cnt))
14752 (delete-region (match-beginning 0) (1+ (point-at-eol))))
14753 (message "Property \"%s\" removed from %d entries" property cnt)))))
14755 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
14757 (defun org-compute-property-at-point ()
14758 "Compute the property at point.
14759 This looks for an enclosing column format, extracts the operator and
14760 then applies it to the property in the column format's scope."
14761 (interactive)
14762 (unless (org-at-property-p)
14763 (error "Not at a property"))
14764 (let ((prop (org-match-string-no-properties 2)))
14765 (org-columns-get-format-and-top-level)
14766 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
14767 (error "No operator defined for property %s" prop))
14768 (org-columns-compute prop)))
14770 (defvar org-property-allowed-value-functions nil
14771 "Hook for functions supplying allowed values for a specific property.
14772 The functions must take a single argument, the name of the property, and
14773 return a flat list of allowed values. If \":ETC\" is one of
14774 the values, this means that these values are intended as defaults for
14775 completion, but that other values should be allowed too.
14776 The functions must return nil if they are not responsible for this
14777 property.")
14779 (defun org-property-get-allowed-values (pom property &optional table)
14780 "Get allowed values for the property PROPERTY.
14781 When TABLE is non-nil, return an alist that can directly be used for
14782 completion."
14783 (let (vals)
14784 (cond
14785 ((equal property "TODO")
14786 (setq vals (org-with-point-at pom
14787 (append org-todo-keywords-1 '("")))))
14788 ((equal property "PRIORITY")
14789 (let ((n org-lowest-priority))
14790 (while (>= n org-highest-priority)
14791 (push (char-to-string n) vals)
14792 (setq n (1- n)))))
14793 ((member property org-special-properties))
14794 ((setq vals (run-hook-with-args-until-success
14795 'org-property-allowed-value-functions property)))
14797 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
14798 (when (and vals (string-match "\\S-" vals))
14799 (setq vals (car (read-from-string (concat "(" vals ")"))))
14800 (setq vals (mapcar (lambda (x)
14801 (cond ((stringp x) x)
14802 ((numberp x) (number-to-string x))
14803 ((symbolp x) (symbol-name x))
14804 (t "???")))
14805 vals)))))
14806 (when (member ":ETC" vals)
14807 (setq vals (remove ":ETC" vals))
14808 (org-add-props (car vals) '(org-unrestricted t)))
14809 (if table (mapcar 'list vals) vals)))
14811 (defun org-property-previous-allowed-value (&optional previous)
14812 "Switch to the next allowed value for this property."
14813 (interactive)
14814 (org-property-next-allowed-value t))
14816 (defun org-property-next-allowed-value (&optional previous)
14817 "Switch to the next allowed value for this property."
14818 (interactive)
14819 (unless (org-at-property-p)
14820 (error "Not at a property"))
14821 (let* ((key (match-string 2))
14822 (value (match-string 3))
14823 (allowed (or (org-property-get-allowed-values (point) key)
14824 (and (member value '("[ ]" "[-]" "[X]"))
14825 '("[ ]" "[X]"))))
14826 nval)
14827 (unless allowed
14828 (error "Allowed values for this property have not been defined"))
14829 (if previous (setq allowed (reverse allowed)))
14830 (if (member value allowed)
14831 (setq nval (car (cdr (member value allowed)))))
14832 (setq nval (or nval (car allowed)))
14833 (if (equal nval value)
14834 (error "Only one allowed value for this property"))
14835 (org-at-property-p)
14836 (replace-match (concat " :" key ": " nval) t t)
14837 (org-indent-line-function)
14838 (beginning-of-line 1)
14839 (skip-chars-forward " \t")
14840 (run-hook-with-args 'org-property-changed-functions key nval)))
14842 (defun org-find-olp (path &optional this-buffer)
14843 "Return a marker pointing to the entry at outline path OLP.
14844 If anything goes wrong, throw an error.
14845 You can wrap this call to catch the error like this:
14847 (condition-case msg
14848 (org-mobile-locate-entry (match-string 4))
14849 (error (nth 1 msg)))
14851 The return value will then be either a string with the error message,
14852 or a marker if everything is OK.
14854 If THIS-BUFFER is set, the outline path does not contain a file,
14855 only headings."
14856 (let* ((file (if this-buffer buffer-file-name (pop path)))
14857 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
14858 (level 1)
14859 (lmin 1)
14860 (lmax 1)
14861 limit re end found pos heading cnt flevel)
14862 (unless buffer (error "File not found :%s" file))
14863 (with-current-buffer buffer
14864 (save-excursion
14865 (save-restriction
14866 (widen)
14867 (setq limit (point-max))
14868 (goto-char (point-min))
14869 (while (setq heading (pop path))
14870 (setq re (format org-complex-heading-regexp-format
14871 (regexp-quote heading)))
14872 (setq cnt 0 pos (point))
14873 (while (re-search-forward re end t)
14874 (setq level (- (match-end 1) (match-beginning 1)))
14875 (if (and (>= level lmin) (<= level lmax))
14876 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
14877 (when (= cnt 0) (error "Heading not found on level %d: %s"
14878 lmax heading))
14879 (when (> cnt 1) (error "Heading not unique on level %d: %s"
14880 lmax heading))
14881 (goto-char found)
14882 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
14883 (setq end (save-excursion (org-end-of-subtree t t))))
14884 (when (org-at-heading-p)
14885 (move-marker (make-marker) (point))))))))
14887 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
14888 "Find node HEADING in BUFFER.
14889 Return a marker to the heading if it was found, or nil if not.
14890 If POS-ONLY is set, return just the position instead of a marker.
14892 The heading text must match exact, but it may have a TODO keyword,
14893 a priority cookie and tags in the standard locations."
14894 (with-current-buffer (or buffer (current-buffer))
14895 (save-excursion
14896 (save-restriction
14897 (widen)
14898 (goto-char (point-min))
14899 (let (case-fold-search)
14900 (if (re-search-forward
14901 (format org-complex-heading-regexp-format
14902 (regexp-quote heading)) nil t)
14903 (if pos-only
14904 (match-beginning 0)
14905 (move-marker (make-marker) (match-beginning 0)))))))))
14907 (defun org-find-exact-heading-in-directory (heading &optional dir)
14908 "Find Org node headline HEADING in all .org files in directory DIR.
14909 When the target headline is found, return a marker to this location."
14910 (let ((files (directory-files (or dir default-directory)
14911 nil "\\`[^.#].*\\.org\\'"))
14912 file visiting m buffer)
14913 (catch 'found
14914 (while (setq file (pop files))
14915 (message "trying %s" file)
14916 (setq visiting (org-find-base-buffer-visiting file))
14917 (setq buffer (or visiting (find-file-noselect file)))
14918 (setq m (org-find-exact-headline-in-buffer
14919 heading buffer))
14920 (when (and (not m) (not visiting)) (kill-buffer buffer))
14921 (and m (throw 'found m))))))
14923 (defun org-find-entry-with-id (ident)
14924 "Locate the entry that contains the ID property with exact value IDENT.
14925 IDENT can be a string, a symbol or a number, this function will search for
14926 the string representation of it.
14927 Return the position where this entry starts, or nil if there is no such entry."
14928 (interactive "sID: ")
14929 (let ((id (cond
14930 ((stringp ident) ident)
14931 ((symbol-name ident) (symbol-name ident))
14932 ((numberp ident) (number-to-string ident))
14933 (t (error "IDENT %s must be a string, symbol or number" ident))))
14934 (case-fold-search nil))
14935 (save-excursion
14936 (save-restriction
14937 (widen)
14938 (goto-char (point-min))
14939 (when (re-search-forward
14940 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
14941 nil t)
14942 (org-back-to-heading t)
14943 (point))))))
14945 ;;;; Timestamps
14947 (defvar org-last-changed-timestamp nil)
14948 (defvar org-last-inserted-timestamp nil
14949 "The last time stamp inserted with `org-insert-time-stamp'.")
14950 (defvar org-time-was-given) ; dynamically scoped parameter
14951 (defvar org-end-time-was-given) ; dynamically scoped parameter
14952 (defvar org-ts-what) ; dynamically scoped parameter
14954 (defun org-time-stamp (arg &optional inactive)
14955 "Prompt for a date/time and insert a time stamp.
14956 If the user specifies a time like HH:MM, or if this command is called
14957 with a prefix argument, the time stamp will contain date and time.
14958 Otherwise, only the date will be included. All parts of a date not
14959 specified by the user will be filled in from the current date/time.
14960 So if you press just return without typing anything, the time stamp
14961 will represent the current date/time. If there is already a timestamp
14962 at the cursor, it will be modified."
14963 (interactive "P")
14964 (let* ((ts nil)
14965 (default-time
14966 ;; Default time is either today, or, when entering a range,
14967 ;; the range start.
14968 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
14969 (save-excursion
14970 (re-search-backward
14971 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
14972 (- (point) 20) t)))
14973 (apply 'encode-time (org-parse-time-string (match-string 1)))
14974 (current-time)))
14975 (default-input (and ts (org-get-compact-tod ts)))
14976 (repeater (save-excursion
14977 (save-match-data
14978 (beginning-of-line)
14979 (when (re-search-forward
14980 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
14981 (save-excursion (progn (end-of-line) (point))) t)
14982 (match-string 0)))))
14983 org-time-was-given org-end-time-was-given time)
14984 (cond
14985 ((and (org-at-timestamp-p t)
14986 (memq last-command '(org-time-stamp org-time-stamp-inactive))
14987 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
14988 (insert "--")
14989 (setq time (let ((this-command this-command))
14990 (org-read-date arg 'totime nil nil
14991 default-time default-input inactive)))
14992 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
14993 ((org-at-timestamp-p t)
14994 (setq time (let ((this-command this-command))
14995 (org-read-date arg 'totime nil nil default-time default-input inactive)))
14996 (when (org-at-timestamp-p t) ; just to get the match data
14997 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
14998 (replace-match "")
14999 (setq org-last-changed-timestamp
15000 (org-insert-time-stamp
15001 time (or org-time-was-given arg)
15002 inactive nil nil (list org-end-time-was-given)))
15003 (when repeater (goto-char (1- (point))) (insert " " repeater)
15004 (setq org-last-changed-timestamp
15005 (concat (substring org-last-inserted-timestamp 0 -1)
15006 " " repeater ">"))))
15007 (message "Timestamp updated"))
15009 (setq time (let ((this-command this-command))
15010 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15011 (org-insert-time-stamp time (or org-time-was-given arg) inactive
15012 nil nil (list org-end-time-was-given))))))
15014 ;; FIXME: can we use this for something else, like computing time differences?
15015 (defun org-get-compact-tod (s)
15016 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
15017 (let* ((t1 (match-string 1 s))
15018 (h1 (string-to-number (match-string 2 s)))
15019 (m1 (string-to-number (match-string 3 s)))
15020 (t2 (and (match-end 4) (match-string 5 s)))
15021 (h2 (and t2 (string-to-number (match-string 6 s))))
15022 (m2 (and t2 (string-to-number (match-string 7 s))))
15023 dh dm)
15024 (if (not t2)
15026 (setq dh (- h2 h1) dm (- m2 m1))
15027 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
15028 (concat t1 "+" (number-to-string dh)
15029 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
15031 (defun org-time-stamp-inactive (&optional arg)
15032 "Insert an inactive time stamp.
15033 An inactive time stamp is enclosed in square brackets instead of angle
15034 brackets. It is inactive in the sense that it does not trigger agenda entries,
15035 does not link to the calendar and cannot be changed with the S-cursor keys.
15036 So these are more for recording a certain time/date."
15037 (interactive "P")
15038 (org-time-stamp arg 'inactive))
15040 (defvar org-date-ovl (make-overlay 1 1))
15041 (overlay-put org-date-ovl 'face 'org-date-selected)
15042 (org-detach-overlay org-date-ovl)
15044 (defvar org-ans1) ; dynamically scoped parameter
15045 (defvar org-ans2) ; dynamically scoped parameter
15047 (defvar org-plain-time-of-day-regexp) ; defined below
15049 (defvar org-overriding-default-time nil) ; dynamically scoped
15050 (defvar org-read-date-overlay nil)
15051 (defvar org-dcst nil) ; dynamically scoped
15052 (defvar org-read-date-history nil)
15053 (defvar org-read-date-final-answer nil)
15054 (defvar org-read-date-analyze-futurep nil)
15055 (defvar org-read-date-analyze-forced-year nil)
15056 (defvar org-read-date-inactive)
15058 (defun org-read-date (&optional org-with-time to-time from-string prompt
15059 default-time default-input inactive)
15060 "Read a date, possibly a time, and make things smooth for the user.
15061 The prompt will suggest to enter an ISO date, but you can also enter anything
15062 which will at least partially be understood by `parse-time-string'.
15063 Unrecognized parts of the date will default to the current day, month, year,
15064 hour and minute. If this command is called to replace a timestamp at point,
15065 or to enter the second timestamp of a range, the default time is taken
15066 from the existing stamp. Furthermore, the command prefers the future,
15067 so if you are giving a date where the year is not given, and the day-month
15068 combination is already past in the current year, it will assume you
15069 mean next year. For details, see the manual. A few examples:
15071 3-2-5 --> 2003-02-05
15072 feb 15 --> currentyear-02-15
15073 2/15 --> currentyear-02-15
15074 sep 12 9 --> 2009-09-12
15075 12:45 --> today 12:45
15076 22 sept 0:34 --> currentyear-09-22 0:34
15077 12 --> currentyear-currentmonth-12
15078 Fri --> nearest Friday (today or later)
15079 etc.
15081 Furthermore you can specify a relative date by giving, as the *first* thing
15082 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
15083 change in days weeks, months, years.
15084 With a single plus or minus, the date is relative to today. With a double
15085 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
15086 +4d --> four days from today
15087 +4 --> same as above
15088 +2w --> two weeks from today
15089 ++5 --> five days from default date
15091 The function understands only English month and weekday abbreviations.
15093 While prompting, a calendar is popped up - you can also select the
15094 date with the mouse (button 1). The calendar shows a period of three
15095 months. To scroll it to other months, use the keys `>' and `<'.
15096 If you don't like the calendar, turn it off with
15097 \(setq org-read-date-popup-calendar nil)
15099 With optional argument TO-TIME, the date will immediately be converted
15100 to an internal time.
15101 With an optional argument WITH-TIME, the prompt will suggest to also
15102 insert a time. Note that when WITH-TIME is not set, you can still
15103 enter a time, and this function will inform the calling routine about
15104 this change. The calling routine may then choose to change the format
15105 used to insert the time stamp into the buffer to include the time.
15106 With optional argument FROM-STRING, read from this string instead from
15107 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
15108 the time/date that is used for everything that is not specified by the
15109 user."
15110 (require 'parse-time)
15111 (let* ((org-time-stamp-rounding-minutes
15112 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
15113 (org-dcst org-display-custom-times)
15114 (ct (org-current-time))
15115 (org-def (or org-overriding-default-time default-time ct))
15116 (org-defdecode (decode-time org-def))
15117 (dummy (progn
15118 (when (< (nth 2 org-defdecode) org-extend-today-until)
15119 (setcar (nthcdr 2 org-defdecode) -1)
15120 (setcar (nthcdr 1 org-defdecode) 59)
15121 (setq org-def (apply 'encode-time org-defdecode)
15122 org-defdecode (decode-time org-def)))))
15123 (calendar-frame-setup nil)
15124 (calendar-setup nil)
15125 (calendar-move-hook nil)
15126 (calendar-view-diary-initially-flag nil)
15127 (calendar-view-holidays-initially-flag nil)
15128 (timestr (format-time-string
15129 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
15130 (prompt (concat (if prompt (concat prompt " ") "")
15131 (format "Date+time [%s]: " timestr)))
15132 ans (org-ans0 "") org-ans1 org-ans2 final)
15134 (cond
15135 (from-string (setq ans from-string))
15136 (org-read-date-popup-calendar
15137 (save-excursion
15138 (save-window-excursion
15139 (calendar)
15140 (org-eval-in-calendar '(setq cursor-type nil) t)
15141 (unwind-protect
15142 (progn
15143 (calendar-forward-day (- (time-to-days org-def)
15144 (calendar-absolute-from-gregorian
15145 (calendar-current-date))))
15146 (org-eval-in-calendar nil t)
15147 (let* ((old-map (current-local-map))
15148 (map (copy-keymap calendar-mode-map))
15149 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
15150 (org-defkey map (kbd "RET") 'org-calendar-select)
15151 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
15152 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
15153 (org-defkey minibuffer-local-map [(meta shift left)]
15154 (lambda () (interactive)
15155 (org-eval-in-calendar '(calendar-backward-month 1))))
15156 (org-defkey minibuffer-local-map [(meta shift right)]
15157 (lambda () (interactive)
15158 (org-eval-in-calendar '(calendar-forward-month 1))))
15159 (org-defkey minibuffer-local-map [(meta shift up)]
15160 (lambda () (interactive)
15161 (org-eval-in-calendar '(calendar-backward-year 1))))
15162 (org-defkey minibuffer-local-map [(meta shift down)]
15163 (lambda () (interactive)
15164 (org-eval-in-calendar '(calendar-forward-year 1))))
15165 (org-defkey minibuffer-local-map [?\e (shift left)]
15166 (lambda () (interactive)
15167 (org-eval-in-calendar '(calendar-backward-month 1))))
15168 (org-defkey minibuffer-local-map [?\e (shift right)]
15169 (lambda () (interactive)
15170 (org-eval-in-calendar '(calendar-forward-month 1))))
15171 (org-defkey minibuffer-local-map [?\e (shift up)]
15172 (lambda () (interactive)
15173 (org-eval-in-calendar '(calendar-backward-year 1))))
15174 (org-defkey minibuffer-local-map [?\e (shift down)]
15175 (lambda () (interactive)
15176 (org-eval-in-calendar '(calendar-forward-year 1))))
15177 (org-defkey minibuffer-local-map [(shift up)]
15178 (lambda () (interactive)
15179 (org-eval-in-calendar '(calendar-backward-week 1))))
15180 (org-defkey minibuffer-local-map [(shift down)]
15181 (lambda () (interactive)
15182 (org-eval-in-calendar '(calendar-forward-week 1))))
15183 (org-defkey minibuffer-local-map [(shift left)]
15184 (lambda () (interactive)
15185 (org-eval-in-calendar '(calendar-backward-day 1))))
15186 (org-defkey minibuffer-local-map [(shift right)]
15187 (lambda () (interactive)
15188 (org-eval-in-calendar '(calendar-forward-day 1))))
15189 (org-defkey minibuffer-local-map ">"
15190 (lambda () (interactive)
15191 (org-eval-in-calendar '(scroll-calendar-left 1))))
15192 (org-defkey minibuffer-local-map "<"
15193 (lambda () (interactive)
15194 (org-eval-in-calendar '(scroll-calendar-right 1))))
15195 (org-defkey minibuffer-local-map "\C-v"
15196 (lambda () (interactive)
15197 (org-eval-in-calendar
15198 '(calendar-scroll-left-three-months 1))))
15199 (org-defkey minibuffer-local-map "\M-v"
15200 (lambda () (interactive)
15201 (org-eval-in-calendar
15202 '(calendar-scroll-right-three-months 1))))
15203 (run-hooks 'org-read-date-minibuffer-setup-hook)
15204 (unwind-protect
15205 (progn
15206 (use-local-map map)
15207 (setq org-read-date-inactive inactive)
15208 (add-hook 'post-command-hook 'org-read-date-display)
15209 (setq org-ans0 (read-string prompt default-input
15210 'org-read-date-history nil))
15211 ;; org-ans0: from prompt
15212 ;; org-ans1: from mouse click
15213 ;; org-ans2: from calendar motion
15214 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
15215 (remove-hook 'post-command-hook 'org-read-date-display)
15216 (use-local-map old-map)
15217 (when org-read-date-overlay
15218 (delete-overlay org-read-date-overlay)
15219 (setq org-read-date-overlay nil)))))
15220 (bury-buffer "*Calendar*")))))
15222 (t ; Naked prompt only
15223 (unwind-protect
15224 (setq ans (read-string prompt default-input
15225 'org-read-date-history timestr))
15226 (when org-read-date-overlay
15227 (delete-overlay org-read-date-overlay)
15228 (setq org-read-date-overlay nil)))))
15230 (setq final (org-read-date-analyze ans org-def org-defdecode))
15232 (when org-read-date-analyze-forced-year
15233 (message "Year was forced into %s"
15234 (if org-read-date-force-compatible-dates
15235 "compatible range (1970-2037)"
15236 "range representable on this machine"))
15237 (ding))
15239 ;; One round trip to get rid of 34th of August and stuff like that....
15240 (setq final (decode-time (apply 'encode-time final)))
15242 (setq org-read-date-final-answer ans)
15244 (if to-time
15245 (apply 'encode-time final)
15246 (if (and (boundp 'org-time-was-given) org-time-was-given)
15247 (format "%04d-%02d-%02d %02d:%02d"
15248 (nth 5 final) (nth 4 final) (nth 3 final)
15249 (nth 2 final) (nth 1 final))
15250 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
15252 (defvar org-def)
15253 (defvar org-defdecode)
15254 (defvar org-with-time)
15255 (defun org-read-date-display ()
15256 "Display the current date prompt interpretation in the minibuffer."
15257 (when org-read-date-display-live
15258 (when org-read-date-overlay
15259 (delete-overlay org-read-date-overlay))
15260 (when (minibufferp (current-buffer))
15261 (save-excursion
15262 (end-of-line 1)
15263 (while (not (equal (buffer-substring
15264 (max (point-min) (- (point) 4)) (point))
15265 " "))
15266 (insert " ")))
15267 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
15268 " " (or org-ans1 org-ans2)))
15269 (org-end-time-was-given nil)
15270 (f (org-read-date-analyze ans org-def org-defdecode))
15271 (fmts (if org-dcst
15272 org-time-stamp-custom-formats
15273 org-time-stamp-formats))
15274 (fmt (if (or org-with-time
15275 (and (boundp 'org-time-was-given) org-time-was-given))
15276 (cdr fmts)
15277 (car fmts)))
15278 (txt (format-time-string fmt (apply 'encode-time f)))
15279 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
15280 (txt (concat "=> " txt)))
15281 (when (and org-end-time-was-given
15282 (string-match org-plain-time-of-day-regexp txt))
15283 (setq txt (concat (substring txt 0 (match-end 0)) "-"
15284 org-end-time-was-given
15285 (substring txt (match-end 0)))))
15286 (when org-read-date-analyze-futurep
15287 (setq txt (concat txt " (=>F)")))
15288 (setq org-read-date-overlay
15289 (make-overlay (1- (point-at-eol)) (point-at-eol)))
15290 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
15292 (defun org-read-date-analyze (ans org-def org-defdecode)
15293 "Analyze the combined answer of the date prompt."
15294 ;; FIXME: cleanup and comment
15295 (let ((nowdecode (decode-time (current-time)))
15296 delta deltan deltaw deltadef year month day
15297 hour minute second wday pm h2 m2 tl wday1
15298 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
15299 (setq org-read-date-analyze-futurep nil
15300 org-read-date-analyze-forced-year nil)
15301 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
15302 (setq ans "+0"))
15304 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
15305 (setq ans (replace-match "" t t ans)
15306 deltan (car delta)
15307 deltaw (nth 1 delta)
15308 deltadef (nth 2 delta)))
15310 ;; Check if there is an iso week date in there
15311 ;; If yes, store the info and postpone interpreting it until the rest
15312 ;; of the parsing is done
15313 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
15314 (setq iso-year (if (match-end 1)
15315 (org-small-year-to-year
15316 (string-to-number (match-string 1 ans))))
15317 iso-weekday (if (match-end 3)
15318 (string-to-number (match-string 3 ans)))
15319 iso-week (string-to-number (match-string 2 ans)))
15320 (setq ans (replace-match "" t t ans)))
15322 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
15323 (when (string-match
15324 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
15325 (setq year (if (match-end 2)
15326 (string-to-number (match-string 2 ans))
15327 (progn (setq kill-year t)
15328 (string-to-number (format-time-string "%Y"))))
15329 month (string-to-number (match-string 3 ans))
15330 day (string-to-number (match-string 4 ans)))
15331 (if (< year 100) (setq year (+ 2000 year)))
15332 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15333 t nil ans)))
15335 ;; Help matching dotted european dates
15336 (when (string-match
15337 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\. ?\\([1-9][0-9][0-9][0-9]\\)?" ans)
15338 (setq year (if (match-end 3)
15339 (string-to-number (match-string 3 ans))
15340 (progn (setq kill-year t)
15341 (string-to-number (format-time-string "%Y"))))
15342 day (string-to-number (match-string 1 ans))
15343 month (string-to-number (match-string 2 ans))
15344 ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15345 t nil ans)))
15347 ;; Help matching american dates, like 5/30 or 5/30/7
15348 (when (string-match
15349 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
15350 (setq year (if (match-end 4)
15351 (string-to-number (match-string 4 ans))
15352 (progn (setq kill-year t)
15353 (string-to-number (format-time-string "%Y"))))
15354 month (string-to-number (match-string 1 ans))
15355 day (string-to-number (match-string 2 ans)))
15356 (if (< year 100) (setq year (+ 2000 year)))
15357 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15358 t nil ans)))
15359 ;; Help matching am/pm times, because `parse-time-string' does not do that.
15360 ;; If there is a time with am/pm, and *no* time without it, we convert
15361 ;; so that matching will be successful.
15362 (loop for i from 1 to 2 do ; twice, for end time as well
15363 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
15364 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
15365 (setq hour (string-to-number (match-string 1 ans))
15366 minute (if (match-end 3)
15367 (string-to-number (match-string 3 ans))
15369 pm (equal ?p
15370 (string-to-char (downcase (match-string 4 ans)))))
15371 (if (and (= hour 12) (not pm))
15372 (setq hour 0)
15373 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
15374 (setq ans (replace-match (format "%02d:%02d" hour minute)
15375 t t ans))))
15377 ;; Check if a time range is given as a duration
15378 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
15379 (setq hour (string-to-number (match-string 1 ans))
15380 h2 (+ hour (string-to-number (match-string 3 ans)))
15381 minute (string-to-number (match-string 2 ans))
15382 m2 (+ minute (if (match-end 5) (string-to-number
15383 (match-string 5 ans))0)))
15384 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
15385 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
15386 t t ans)))
15388 ;; Check if there is a time range
15389 (when (boundp 'org-end-time-was-given)
15390 (setq org-time-was-given nil)
15391 (when (and (string-match org-plain-time-of-day-regexp ans)
15392 (match-end 8))
15393 (setq org-end-time-was-given (match-string 8 ans))
15394 (setq ans (concat (substring ans 0 (match-beginning 7))
15395 (substring ans (match-end 7))))))
15397 (setq tl (parse-time-string ans)
15398 day (or (nth 3 tl) (nth 3 org-defdecode))
15399 month (or (nth 4 tl)
15400 (if (and org-read-date-prefer-future
15401 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
15402 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
15403 (nth 4 org-defdecode)))
15404 year (or (and (not kill-year) (nth 5 tl))
15405 (if (and org-read-date-prefer-future
15406 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
15407 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
15408 (nth 5 org-defdecode)))
15409 hour (or (nth 2 tl) (nth 2 org-defdecode))
15410 minute (or (nth 1 tl) (nth 1 org-defdecode))
15411 second (or (nth 0 tl) 0)
15412 wday (nth 6 tl))
15414 (when (and (eq org-read-date-prefer-future 'time)
15415 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
15416 (equal day (nth 3 nowdecode))
15417 (equal month (nth 4 nowdecode))
15418 (equal year (nth 5 nowdecode))
15419 (nth 2 tl)
15420 (or (< (nth 2 tl) (nth 2 nowdecode))
15421 (and (= (nth 2 tl) (nth 2 nowdecode))
15422 (nth 1 tl)
15423 (< (nth 1 tl) (nth 1 nowdecode)))))
15424 (setq day (1+ day)
15425 futurep t))
15427 ;; Special date definitions below
15428 (cond
15429 (iso-week
15430 ;; There was an iso week
15431 (require 'cal-iso)
15432 (setq futurep nil)
15433 (setq year (or iso-year year)
15434 day (or iso-weekday wday 1)
15435 wday nil ; to make sure that the trigger below does not match
15436 iso-date (calendar-gregorian-from-absolute
15437 (calendar-absolute-from-iso
15438 (list iso-week day year))))
15439 ; FIXME: Should we also push ISO weeks into the future?
15440 ; (when (and org-read-date-prefer-future
15441 ; (not iso-year)
15442 ; (< (calendar-absolute-from-gregorian iso-date)
15443 ; (time-to-days (current-time))))
15444 ; (setq year (1+ year)
15445 ; iso-date (calendar-gregorian-from-absolute
15446 ; (calendar-absolute-from-iso
15447 ; (list iso-week day year)))))
15448 (setq month (car iso-date)
15449 year (nth 2 iso-date)
15450 day (nth 1 iso-date)))
15451 (deltan
15452 (setq futurep nil)
15453 (unless deltadef
15454 (let ((now (decode-time (current-time))))
15455 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
15456 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
15457 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
15458 ((equal deltaw "m") (setq month (+ month deltan)))
15459 ((equal deltaw "y") (setq year (+ year deltan)))))
15460 ((and wday (not (nth 3 tl)))
15461 (setq futurep nil)
15462 ;; Weekday was given, but no day, so pick that day in the week
15463 ;; on or after the derived date.
15464 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
15465 (unless (equal wday wday1)
15466 (setq day (+ day (% (- wday wday1 -7) 7))))))
15467 (if (and (boundp 'org-time-was-given)
15468 (nth 2 tl))
15469 (setq org-time-was-given t))
15470 (if (< year 100) (setq year (+ 2000 year)))
15471 ;; Check of the date is representable
15472 (if org-read-date-force-compatible-dates
15473 (progn
15474 (if (< year 1970)
15475 (setq year 1970 org-read-date-analyze-forced-year t))
15476 (if (> year 2037)
15477 (setq year 2037 org-read-date-analyze-forced-year t)))
15478 (condition-case nil
15479 (ignore (encode-time second minute hour day month year))
15480 (error
15481 (setq year (nth 5 org-defdecode))
15482 (setq org-read-date-analyze-forced-year t))))
15483 (setq org-read-date-analyze-futurep futurep)
15484 (list second minute hour day month year)))
15486 (defvar parse-time-weekdays)
15487 (defun org-read-date-get-relative (s today default)
15488 "Check string S for special relative date string.
15489 TODAY and DEFAULT are internal times, for today and for a default.
15490 Return shift list (N what def-flag)
15491 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
15492 N is the number of WHATs to shift.
15493 DEF-FLAG is t when a double ++ or -- indicates shift relative to
15494 the DEFAULT date rather than TODAY."
15495 (require 'parse-time)
15496 (when (and
15497 (string-match
15498 (concat
15499 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
15500 "\\([0-9]+\\)?"
15501 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
15502 "\\([ \t]\\|$\\)") s)
15503 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
15504 (let* ((dir (if (> (match-end 1) (match-beginning 1))
15505 (string-to-char (substring (match-string 1 s) -1))
15506 ?+))
15507 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
15508 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
15509 (what (if (match-end 3) (match-string 3 s) "d"))
15510 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
15511 (date (if rel default today))
15512 (wday (nth 6 (decode-time date)))
15513 delta)
15514 (if wday1
15515 (progn
15516 (setq delta (mod (+ 7 (- wday1 wday)) 7))
15517 (if (= dir ?-) (setq delta (- delta 7)))
15518 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
15519 (list delta "d" rel))
15520 (list (* n (if (= dir ?-) -1 1)) what rel)))))
15522 (defun org-order-calendar-date-args (arg1 arg2 arg3)
15523 "Turn a user-specified date into the internal representation.
15524 The internal representation needed by the calendar is (month day year).
15525 This is a wrapper to handle the brain-dead convention in calendar that
15526 user function argument order change dependent on argument order."
15527 (if (boundp 'calendar-date-style)
15528 (cond
15529 ((eq calendar-date-style 'american)
15530 (list arg1 arg2 arg3))
15531 ((eq calendar-date-style 'european)
15532 (list arg2 arg1 arg3))
15533 ((eq calendar-date-style 'iso)
15534 (list arg2 arg3 arg1)))
15535 (with-no-warnings ;; european-calendar-style is obsolete as of version 23.1
15536 (if (org-bound-and-true-p european-calendar-style)
15537 (list arg2 arg1 arg3)
15538 (list arg1 arg2 arg3)))))
15540 (defun org-eval-in-calendar (form &optional keepdate)
15541 "Eval FORM in the calendar window and return to current window.
15542 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
15543 otherwise stick to the current value of `org-ans2'."
15544 (let ((sf (selected-frame))
15545 (sw (selected-window)))
15546 (select-window (get-buffer-window "*Calendar*" t))
15547 (eval form)
15548 (when (and (not keepdate) (calendar-cursor-to-date))
15549 (let* ((date (calendar-cursor-to-date))
15550 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15551 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
15552 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
15553 (select-window sw)
15554 (org-select-frame-set-input-focus sf)))
15556 (defun org-calendar-select ()
15557 "Return to `org-read-date' with the date currently selected.
15558 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15559 (interactive)
15560 (when (calendar-cursor-to-date)
15561 (let* ((date (calendar-cursor-to-date))
15562 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15563 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15564 (if (active-minibuffer-window) (exit-minibuffer))))
15566 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
15567 "Insert a date stamp for the date given by the internal TIME.
15568 WITH-HM means use the stamp format that includes the time of the day.
15569 INACTIVE means use square brackets instead of angular ones, so that the
15570 stamp will not contribute to the agenda.
15571 PRE and POST are optional strings to be inserted before and after the
15572 stamp.
15573 The command returns the inserted time stamp."
15574 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
15575 stamp)
15576 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
15577 (insert-before-markers (or pre ""))
15578 (when (listp extra)
15579 (setq extra (car extra))
15580 (if (and (stringp extra)
15581 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
15582 (setq extra (format "-%02d:%02d"
15583 (string-to-number (match-string 1 extra))
15584 (string-to-number (match-string 2 extra))))
15585 (setq extra nil)))
15586 (when extra
15587 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
15588 (insert-before-markers (setq stamp (format-time-string fmt time)))
15589 (insert-before-markers (or post ""))
15590 (setq org-last-inserted-timestamp stamp)))
15592 (defun org-toggle-time-stamp-overlays ()
15593 "Toggle the use of custom time stamp formats."
15594 (interactive)
15595 (setq org-display-custom-times (not org-display-custom-times))
15596 (unless org-display-custom-times
15597 (let ((p (point-min)) (bmp (buffer-modified-p)))
15598 (while (setq p (next-single-property-change p 'display))
15599 (if (and (get-text-property p 'display)
15600 (eq (get-text-property p 'face) 'org-date))
15601 (remove-text-properties
15602 p (setq p (next-single-property-change p 'display))
15603 '(display t))))
15604 (set-buffer-modified-p bmp)))
15605 (if (featurep 'xemacs)
15606 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
15607 (org-restart-font-lock)
15608 (setq org-table-may-need-update t)
15609 (if org-display-custom-times
15610 (message "Time stamps are overlaid with custom format")
15611 (message "Time stamp overlays removed")))
15613 (defun org-display-custom-time (beg end)
15614 "Overlay modified time stamp format over timestamp between BEG and END."
15615 (let* ((ts (buffer-substring beg end))
15616 t1 w1 with-hm tf time str w2 (off 0))
15617 (save-match-data
15618 (setq t1 (org-parse-time-string ts t))
15619 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
15620 (setq off (- (match-end 0) (match-beginning 0)))))
15621 (setq end (- end off))
15622 (setq w1 (- end beg)
15623 with-hm (and (nth 1 t1) (nth 2 t1))
15624 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
15625 time (org-fix-decoded-time t1)
15626 str (org-add-props
15627 (format-time-string
15628 (substring tf 1 -1) (apply 'encode-time time))
15629 nil 'mouse-face 'highlight)
15630 w2 (length str))
15631 (if (not (= w2 w1))
15632 (add-text-properties (1+ beg) (+ 2 beg)
15633 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
15634 (if (featurep 'xemacs)
15635 (progn
15636 (put-text-property beg end 'invisible t)
15637 (put-text-property beg end 'end-glyph (make-glyph str)))
15638 (put-text-property beg end 'display str))))
15640 (defun org-translate-time (string)
15641 "Translate all timestamps in STRING to custom format.
15642 But do this only if the variable `org-display-custom-times' is set."
15643 (when org-display-custom-times
15644 (save-match-data
15645 (let* ((start 0)
15646 (re org-ts-regexp-both)
15647 t1 with-hm inactive tf time str beg end)
15648 (while (setq start (string-match re string start))
15649 (setq beg (match-beginning 0)
15650 end (match-end 0)
15651 t1 (save-match-data
15652 (org-parse-time-string (substring string beg end) t))
15653 with-hm (and (nth 1 t1) (nth 2 t1))
15654 inactive (equal (substring string beg (1+ beg)) "[")
15655 tf (funcall (if with-hm 'cdr 'car)
15656 org-time-stamp-custom-formats)
15657 time (org-fix-decoded-time t1)
15658 str (format-time-string
15659 (concat
15660 (if inactive "[" "<") (substring tf 1 -1)
15661 (if inactive "]" ">"))
15662 (apply 'encode-time time))
15663 string (replace-match str t t string)
15664 start (+ start (length str)))))))
15665 string)
15667 (defun org-fix-decoded-time (time)
15668 "Set 0 instead of nil for the first 6 elements of time.
15669 Don't touch the rest."
15670 (let ((n 0))
15671 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
15673 (defun org-days-to-time (timestamp-string)
15674 "Difference between TIMESTAMP-STRING and now in days."
15675 (- (time-to-days (org-time-string-to-time timestamp-string))
15676 (time-to-days (current-time))))
15678 (defun org-deadline-close (timestamp-string &optional ndays)
15679 "Is the time in TIMESTAMP-STRING close to the current date?"
15680 (setq ndays (or ndays (org-get-wdays timestamp-string)))
15681 (and (< (org-days-to-time timestamp-string) ndays)
15682 (not (org-entry-is-done-p))))
15684 (defun org-get-wdays (ts)
15685 "Get the deadline lead time appropriate for timestring TS."
15686 (cond
15687 ((<= org-deadline-warning-days 0)
15688 ;; 0 or negative, enforce this value no matter what
15689 (- org-deadline-warning-days))
15690 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
15691 ;; lead time is specified.
15692 (floor (* (string-to-number (match-string 1 ts))
15693 (cdr (assoc (match-string 2 ts)
15694 '(("d" . 1) ("w" . 7)
15695 ("m" . 30.4) ("y" . 365.25)))))))
15696 ;; go for the default.
15697 (t org-deadline-warning-days)))
15699 (defun org-calendar-select-mouse (ev)
15700 "Return to `org-read-date' with the date currently selected.
15701 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15702 (interactive "e")
15703 (mouse-set-point ev)
15704 (when (calendar-cursor-to-date)
15705 (let* ((date (calendar-cursor-to-date))
15706 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15707 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15708 (if (active-minibuffer-window) (exit-minibuffer))))
15710 (defun org-check-deadlines (ndays)
15711 "Check if there are any deadlines due or past due.
15712 A deadline is considered due if it happens within `org-deadline-warning-days'
15713 days from today's date. If the deadline appears in an entry marked DONE,
15714 it is not shown. The prefix arg NDAYS can be used to test that many
15715 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
15716 (interactive "P")
15717 (let* ((org-warn-days
15718 (cond
15719 ((equal ndays '(4)) 100000)
15720 (ndays (prefix-numeric-value ndays))
15721 (t (abs org-deadline-warning-days))))
15722 (case-fold-search nil)
15723 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
15724 (callback
15725 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
15727 (message "%d deadlines past-due or due within %d days"
15728 (org-occur regexp nil callback)
15729 org-warn-days)))
15731 (defun org-check-before-date (date)
15732 "Check if there are deadlines or scheduled entries before DATE."
15733 (interactive (list (org-read-date)))
15734 (let ((case-fold-search nil)
15735 (regexp (concat "\\<\\(" org-deadline-string
15736 "\\|" org-scheduled-string
15737 "\\) *<\\([^>]+\\)>"))
15738 (callback
15739 (lambda () (time-less-p
15740 (org-time-string-to-time (match-string 2))
15741 (org-time-string-to-time date)))))
15742 (message "%d entries before %s"
15743 (org-occur regexp nil callback) date)))
15745 (defun org-check-after-date (date)
15746 "Check if there are deadlines or scheduled entries after DATE."
15747 (interactive (list (org-read-date)))
15748 (let ((case-fold-search nil)
15749 (regexp (concat "\\<\\(" org-deadline-string
15750 "\\|" org-scheduled-string
15751 "\\) *<\\([^>]+\\)>"))
15752 (callback
15753 (lambda () (not
15754 (time-less-p
15755 (org-time-string-to-time (match-string 2))
15756 (org-time-string-to-time date))))))
15757 (message "%d entries after %s"
15758 (org-occur regexp nil callback) date)))
15760 (defun org-check-dates-range (start-date end-date)
15761 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
15762 (interactive (list (org-read-date nil nil nil "Range starts")
15763 (org-read-date nil nil nil "Range end")))
15764 (let ((case-fold-search nil)
15765 (regexp (concat "\\<\\(" org-deadline-string
15766 "\\|" org-scheduled-string
15767 "\\) *<\\([^>]+\\)>"))
15768 (callback
15769 (lambda ()
15770 (let ((match (match-string 2)))
15771 (and
15772 (not (time-less-p
15773 (org-time-string-to-time match)
15774 (org-time-string-to-time start-date)))
15775 (time-less-p
15776 (org-time-string-to-time match)
15777 (org-time-string-to-time end-date)))))))
15778 (message "%d entries between %s and %s"
15779 (org-occur regexp nil callback) start-date end-date)))
15781 (defun org-evaluate-time-range (&optional to-buffer)
15782 "Evaluate a time range by computing the difference between start and end.
15783 Normally the result is just printed in the echo area, but with prefix arg
15784 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
15785 If the time range is actually in a table, the result is inserted into the
15786 next column.
15787 For time difference computation, a year is assumed to be exactly 365
15788 days in order to avoid rounding problems."
15789 (interactive "P")
15791 (org-clock-update-time-maybe)
15792 (save-excursion
15793 (unless (org-at-date-range-p t)
15794 (goto-char (point-at-bol))
15795 (re-search-forward org-tr-regexp-both (point-at-eol) t))
15796 (if (not (org-at-date-range-p t))
15797 (error "Not at a time-stamp range, and none found in current line")))
15798 (let* ((ts1 (match-string 1))
15799 (ts2 (match-string 2))
15800 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
15801 (match-end (match-end 0))
15802 (time1 (org-time-string-to-time ts1))
15803 (time2 (org-time-string-to-time ts2))
15804 (t1 (org-float-time time1))
15805 (t2 (org-float-time time2))
15806 (diff (abs (- t2 t1)))
15807 (negative (< (- t2 t1) 0))
15808 ;; (ys (floor (* 365 24 60 60)))
15809 (ds (* 24 60 60))
15810 (hs (* 60 60))
15811 (fy "%dy %dd %02d:%02d")
15812 (fy1 "%dy %dd")
15813 (fd "%dd %02d:%02d")
15814 (fd1 "%dd")
15815 (fh "%02d:%02d")
15816 y d h m align)
15817 (if havetime
15818 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
15820 d (floor (/ diff ds)) diff (mod diff ds)
15821 h (floor (/ diff hs)) diff (mod diff hs)
15822 m (floor (/ diff 60)))
15823 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
15825 d (floor (+ (/ diff ds) 0.5))
15826 h 0 m 0))
15827 (if (not to-buffer)
15828 (message "%s" (org-make-tdiff-string y d h m))
15829 (if (org-at-table-p)
15830 (progn
15831 (goto-char match-end)
15832 (setq align t)
15833 (and (looking-at " *|") (goto-char (match-end 0))))
15834 (goto-char match-end))
15835 (if (looking-at
15836 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
15837 (replace-match ""))
15838 (if negative (insert " -"))
15839 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
15840 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
15841 (insert " " (format fh h m))))
15842 (if align (org-table-align))
15843 (message "Time difference inserted")))))
15845 (defun org-make-tdiff-string (y d h m)
15846 (let ((fmt "")
15847 (l nil))
15848 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
15849 l (push y l)))
15850 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
15851 l (push d l)))
15852 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
15853 l (push h l)))
15854 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
15855 l (push m l)))
15856 (apply 'format fmt (nreverse l))))
15858 (defun org-time-string-to-time (s &optional buffer pos)
15859 (condition-case errdata
15860 (apply 'encode-time (org-parse-time-string s))
15861 (error (error "Bad timestamp `%s'%s\nError was: %s"
15862 s (if (not (and buffer pos))
15864 (format " at %d in buffer `%s'" pos buffer))
15865 (cdr errdata)))))
15867 (defun org-time-string-to-seconds (s)
15868 (org-float-time (org-time-string-to-time s)))
15870 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
15871 "Convert a time stamp to an absolute day number.
15872 If there is a specifier for a cyclic time stamp, get the closest date to
15873 DAYNR.
15874 PREFER and SHOW-ALL are passed through to `org-closest-date'.
15875 The variable date is bound by the calendar when this is called."
15876 (cond
15877 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
15878 (if (org-diary-sexp-entry (match-string 1 s) "" date)
15879 daynr
15880 (+ daynr 1000)))
15881 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
15882 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
15883 (time-to-days (current-time))) (match-string 0 s)
15884 prefer show-all))
15885 (t (time-to-days
15886 (condition-case errdata
15887 (apply 'encode-time (org-parse-time-string s))
15888 (error (error "Bad timestamp `%s'%s\nError was: %s"
15889 s (if (not (and buffer pos))
15891 (format " at %d in buffer `%s'" pos buffer))
15892 (cdr errdata))))))))
15894 (defun org-days-to-iso-week (days)
15895 "Return the iso week number."
15896 (require 'cal-iso)
15897 (car (calendar-iso-from-absolute days)))
15899 (defun org-small-year-to-year (year)
15900 "Convert 2-digit years into 4-digit years.
15901 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
15902 The year 2000 cannot be abbreviated. Any year larger than 99
15903 is returned unchanged."
15904 (if (< year 38)
15905 (setq year (+ 2000 year))
15906 (if (< year 100)
15907 (setq year (+ 1900 year))))
15908 year)
15910 (defun org-time-from-absolute (d)
15911 "Return the time corresponding to date D.
15912 D may be an absolute day number, or a calendar-type list (month day year)."
15913 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
15914 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
15916 (defun org-calendar-holiday ()
15917 "List of holidays, for Diary display in Org-mode."
15918 (require 'holidays)
15919 (let ((hl (funcall
15920 (if (fboundp 'calendar-check-holidays)
15921 'calendar-check-holidays 'check-calendar-holidays) date)))
15922 (if hl (mapconcat 'identity hl "; "))))
15924 (defun org-diary-sexp-entry (sexp entry date)
15925 "Process a SEXP diary ENTRY for DATE."
15926 (require 'diary-lib)
15927 (let ((result (if calendar-debug-sexp
15928 (let ((stack-trace-on-error t))
15929 (eval (car (read-from-string sexp))))
15930 (condition-case nil
15931 (eval (car (read-from-string sexp)))
15932 (error
15933 (beep)
15934 (message "Bad sexp at line %d in %s: %s"
15935 (org-current-line)
15936 (buffer-file-name) sexp)
15937 (sleep-for 2))))))
15938 (cond ((stringp result) (split-string result "; "))
15939 ((and (consp result)
15940 (not (consp (cdr result)))
15941 (stringp (cdr result))) (cdr result))
15942 ((and (consp result)
15943 (stringp (car result))) result)
15944 (result entry)
15945 (t nil))))
15947 (defun org-diary-to-ical-string (frombuf)
15948 "Get iCalendar entries from diary entries in buffer FROMBUF.
15949 This uses the icalendar.el library."
15950 (let* ((tmpdir (if (featurep 'xemacs)
15951 (temp-directory)
15952 temporary-file-directory))
15953 (tmpfile (make-temp-name
15954 (expand-file-name "orgics" tmpdir)))
15955 buf rtn b e)
15956 (with-current-buffer frombuf
15957 (icalendar-export-region (point-min) (point-max) tmpfile)
15958 (setq buf (find-buffer-visiting tmpfile))
15959 (set-buffer buf)
15960 (goto-char (point-min))
15961 (if (re-search-forward "^BEGIN:VEVENT" nil t)
15962 (setq b (match-beginning 0)))
15963 (goto-char (point-max))
15964 (if (re-search-backward "^END:VEVENT" nil t)
15965 (setq e (match-end 0)))
15966 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
15967 (kill-buffer buf)
15968 (delete-file tmpfile)
15969 rtn))
15971 (defun org-closest-date (start current change prefer show-all)
15972 "Find the date closest to CURRENT that is consistent with START and CHANGE.
15973 When PREFER is `past', return a date that is either CURRENT or past.
15974 When PREFER is `future', return a date that is either CURRENT or future.
15975 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
15976 ;; Make the proper lists from the dates
15977 (catch 'exit
15978 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
15979 dn dw sday cday n1 n2 n0
15980 d m y y1 y2 date1 date2 nmonths nm ny m2)
15982 (setq start (org-date-to-gregorian start)
15983 current (org-date-to-gregorian
15984 (if show-all
15985 current
15986 (time-to-days (current-time))))
15987 sday (calendar-absolute-from-gregorian start)
15988 cday (calendar-absolute-from-gregorian current))
15990 (if (<= cday sday) (throw 'exit sday))
15992 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
15993 (setq dn (string-to-number (match-string 1 change))
15994 dw (cdr (assoc (match-string 2 change) a1)))
15995 (error "Invalid change specifier: %s" change))
15996 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
15997 (cond
15998 ((eq dw 'day)
15999 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
16000 n2 (+ n1 dn)))
16001 ((eq dw 'year)
16002 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
16003 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
16004 (setq date1 (list m d y1)
16005 n1 (calendar-absolute-from-gregorian date1)
16006 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
16007 n2 (calendar-absolute-from-gregorian date2)))
16008 ((eq dw 'month)
16009 ;; approx number of month between the two dates
16010 (setq nmonths (floor (/ (- cday sday) 30.436875)))
16011 ;; How often does dn fit in there?
16012 (setq d (nth 1 start) m (car start) y (nth 2 start)
16013 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
16014 m (+ m nm)
16015 ny (floor (/ m 12))
16016 y (+ y ny)
16017 m (- m (* ny 12)))
16018 (while (> m 12) (setq m (- m 12) y (1+ y)))
16019 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
16020 (setq m2 (+ m dn) y2 y)
16021 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16022 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
16023 (while (<= n2 cday)
16024 (setq n1 n2 m m2 y y2)
16025 (setq m2 (+ m dn) y2 y)
16026 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16027 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
16028 ;; Make sure n1 is the earlier date
16029 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
16030 (if show-all
16031 (cond
16032 ((eq prefer 'past) (if (= cday n2) n2 n1))
16033 ((eq prefer 'future) (if (= cday n1) n1 n2))
16034 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
16035 (cond
16036 ((eq prefer 'past) (if (= cday n2) n2 n1))
16037 ((eq prefer 'future) (if (= cday n1) n1 n2))
16038 (t (if (= cday n1) n1 n2)))))))
16040 (defun org-date-to-gregorian (date)
16041 "Turn any specification of DATE into a Gregorian date for the calendar."
16042 (cond ((integerp date) (calendar-gregorian-from-absolute date))
16043 ((and (listp date) (= (length date) 3)) date)
16044 ((stringp date)
16045 (setq date (org-parse-time-string date))
16046 (list (nth 4 date) (nth 3 date) (nth 5 date)))
16047 ((listp date)
16048 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
16050 (defun org-parse-time-string (s &optional nodefault)
16051 "Parse the standard Org-mode time string.
16052 This should be a lot faster than the normal `parse-time-string'.
16053 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
16054 hour and minute fields will be nil if not given."
16055 (if (string-match org-ts-regexp0 s)
16056 (list 0
16057 (if (or (match-beginning 8) (not nodefault))
16058 (string-to-number (or (match-string 8 s) "0")))
16059 (if (or (match-beginning 7) (not nodefault))
16060 (string-to-number (or (match-string 7 s) "0")))
16061 (string-to-number (match-string 4 s))
16062 (string-to-number (match-string 3 s))
16063 (string-to-number (match-string 2 s))
16064 nil nil nil)
16065 (error "Not a standard Org-mode time string: %s" s)))
16067 (defun org-timestamp-up (&optional arg)
16068 "Increase the date item at the cursor by one.
16069 If the cursor is on the year, change the year. If it is on the month,
16070 the day or the time, change that.
16071 With prefix ARG, change by that many units."
16072 (interactive "p")
16073 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
16075 (defun org-timestamp-down (&optional arg)
16076 "Decrease the date item at the cursor by one.
16077 If the cursor is on the year, change the year. If it is on the month,
16078 the day or the time, change that.
16079 With prefix ARG, change by that many units."
16080 (interactive "p")
16081 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
16083 (defun org-timestamp-up-day (&optional arg)
16084 "Increase the date in the time stamp by one day.
16085 With prefix ARG, change that many days."
16086 (interactive "p")
16087 (if (and (not (org-at-timestamp-p t))
16088 (org-at-heading-p))
16089 (org-todo 'up)
16090 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
16092 (defun org-timestamp-down-day (&optional arg)
16093 "Decrease the date in the time stamp by one day.
16094 With prefix ARG, change that many days."
16095 (interactive "p")
16096 (if (and (not (org-at-timestamp-p t))
16097 (org-at-heading-p))
16098 (org-todo 'down)
16099 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
16101 (defun org-at-timestamp-p (&optional inactive-ok)
16102 "Determine if the cursor is in or at a timestamp."
16103 (interactive)
16104 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
16105 (pos (point))
16106 (ans (or (looking-at tsr)
16107 (save-excursion
16108 (skip-chars-backward "^[<\n\r\t")
16109 (if (> (point) (point-min)) (backward-char 1))
16110 (and (looking-at tsr)
16111 (> (- (match-end 0) pos) -1))))))
16112 (and ans
16113 (boundp 'org-ts-what)
16114 (setq org-ts-what
16115 (cond
16116 ((= pos (match-beginning 0)) 'bracket)
16117 ;; Point is considered to be "on the bracket" whether
16118 ;; it's really on it or right after it.
16119 ((or (= pos (1- (match-end 0)))
16120 (= pos (match-end 0))) 'bracket)
16121 ((org-pos-in-match-range pos 2) 'year)
16122 ((org-pos-in-match-range pos 3) 'month)
16123 ((org-pos-in-match-range pos 7) 'hour)
16124 ((org-pos-in-match-range pos 8) 'minute)
16125 ((or (org-pos-in-match-range pos 4)
16126 (org-pos-in-match-range pos 5)) 'day)
16127 ((and (> pos (or (match-end 8) (match-end 5)))
16128 (< pos (match-end 0)))
16129 (- pos (or (match-end 8) (match-end 5))))
16130 (t 'day))))
16131 ans))
16133 (defun org-toggle-timestamp-type ()
16134 "Toggle the type (<active> or [inactive]) of a time stamp."
16135 (interactive)
16136 (when (org-at-timestamp-p t)
16137 (let ((beg (match-beginning 0)) (end (match-end 0))
16138 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
16139 (save-excursion
16140 (goto-char beg)
16141 (while (re-search-forward "[][<>]" end t)
16142 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
16143 t t)))
16144 (message "Timestamp is now %sactive"
16145 (if (equal (char-after beg) ?<) "" "in")))))
16147 (defun org-timestamp-change (n &optional what updown)
16148 "Change the date in the time stamp at point.
16149 The date will be changed by N times WHAT. WHAT can be `day', `month',
16150 `year', `minute', `second'. If WHAT is not given, the cursor position
16151 in the timestamp determines what will be changed."
16152 (let ((origin (point)) origin-cat
16153 with-hm inactive
16154 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
16155 org-ts-what
16156 extra rem
16157 ts time time0)
16158 (if (not (org-at-timestamp-p t))
16159 (error "Not at a timestamp"))
16160 (if (and (not what) (eq org-ts-what 'bracket))
16161 (org-toggle-timestamp-type)
16162 ;; Point isn't on brackets. Remember the part of the time-stamp
16163 ;; the point was in. Indeed, size of time-stamps may change,
16164 ;; but point must be kept in the same category nonetheless.
16165 (setq origin-cat org-ts-what)
16166 (if (and (not what) (not (eq org-ts-what 'day))
16167 org-display-custom-times
16168 (get-text-property (point) 'display)
16169 (not (get-text-property (1- (point)) 'display)))
16170 (setq org-ts-what 'day))
16171 (setq org-ts-what (or what org-ts-what)
16172 inactive (= (char-after (match-beginning 0)) ?\[)
16173 ts (match-string 0))
16174 (replace-match "")
16175 (if (string-match
16176 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
16178 (setq extra (match-string 1 ts)))
16179 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
16180 (setq with-hm t))
16181 (setq time0 (org-parse-time-string ts))
16182 (when (and updown
16183 (eq org-ts-what 'minute)
16184 (not current-prefix-arg))
16185 ;; This looks like s-up and s-down. Change by one rounding step.
16186 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
16187 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
16188 (setcar (cdr time0) (+ (nth 1 time0)
16189 (if (> n 0) (- rem) (- dm rem))))))
16190 (setq time
16191 (encode-time (or (car time0) 0)
16192 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
16193 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
16194 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
16195 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
16196 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
16197 (nthcdr 6 time0)))
16198 (when (and (member org-ts-what '(hour minute))
16199 extra
16200 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
16201 (setq extra (org-modify-ts-extra
16202 extra
16203 (if (eq org-ts-what 'hour) 2 5)
16204 n dm)))
16205 (when (integerp org-ts-what)
16206 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
16207 (if (eq what 'calendar)
16208 (let ((cal-date (org-get-date-from-calendar)))
16209 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
16210 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
16211 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
16212 (setcar time0 (or (car time0) 0))
16213 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
16214 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
16215 (setq time (apply 'encode-time time0))))
16216 ;; Insert the new time-stamp, and ensure point stays in the same
16217 ;; category as before (i.e. not after the last position in that
16218 ;; category).
16219 (let ((pos (point)))
16220 ;; Stay before inserted string. `save-excursion' is of no use.
16221 (setq org-last-changed-timestamp
16222 (org-insert-time-stamp time with-hm inactive nil nil extra))
16223 (goto-char pos))
16224 (save-match-data
16225 (looking-at org-ts-regexp3)
16226 (goto-char (cond
16227 ;; `day' category ends before `hour' if any, or at
16228 ;; the end of the day name.
16229 ((eq origin-cat 'day)
16230 (min (or (match-beginning 7) (1- (match-end 5))) origin))
16231 ((eq origin-cat 'hour) (min (match-end 7) origin))
16232 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
16233 ((integerp origin-cat) (min (1- (match-end 0)) origin))
16234 ;; `year' and `month' have both fixed size: point
16235 ;; couldn't have moved into another part.
16236 (t origin))))
16237 ;; Update clock if on a CLOCK line.
16238 (org-clock-update-time-maybe)
16239 ;; Try to recenter the calendar window, if any.
16240 (if (and org-calendar-follow-timestamp-change
16241 (get-buffer-window "*Calendar*" t)
16242 (memq org-ts-what '(day month year)))
16243 (org-recenter-calendar (time-to-days time))))))
16245 (defun org-modify-ts-extra (s pos n dm)
16246 "Change the different parts of the lead-time and repeat fields in timestamp."
16247 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
16248 ng h m new rem)
16249 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
16250 (cond
16251 ((or (org-pos-in-match-range pos 2)
16252 (org-pos-in-match-range pos 3))
16253 (setq m (string-to-number (match-string 3 s))
16254 h (string-to-number (match-string 2 s)))
16255 (if (org-pos-in-match-range pos 2)
16256 (setq h (+ h n))
16257 (setq n (* dm (org-no-warnings (signum n))))
16258 (when (not (= 0 (setq rem (% m dm))))
16259 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
16260 (setq m (+ m n)))
16261 (if (< m 0) (setq m (+ m 60) h (1- h)))
16262 (if (> m 59) (setq m (- m 60) h (1+ h)))
16263 (setq h (min 24 (max 0 h)))
16264 (setq ng 1 new (format "-%02d:%02d" h m)))
16265 ((org-pos-in-match-range pos 6)
16266 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
16267 ((org-pos-in-match-range pos 5)
16268 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
16270 ((org-pos-in-match-range pos 9)
16271 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
16272 ((org-pos-in-match-range pos 8)
16273 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
16275 (when ng
16276 (setq s (concat
16277 (substring s 0 (match-beginning ng))
16279 (substring s (match-end ng))))))
16282 (defun org-recenter-calendar (date)
16283 "If the calendar is visible, recenter it to DATE."
16284 (let ((cwin (get-buffer-window "*Calendar*" t)))
16285 (when cwin
16286 (let ((calendar-move-hook nil))
16287 (with-selected-window cwin
16288 (calendar-goto-date (if (listp date) date
16289 (calendar-gregorian-from-absolute date))))))))
16291 (defun org-goto-calendar (&optional arg)
16292 "Go to the Emacs calendar at the current date.
16293 If there is a time stamp in the current line, go to that date.
16294 A prefix ARG can be used to force the current date."
16295 (interactive "P")
16296 (let ((tsr org-ts-regexp) diff
16297 (calendar-move-hook nil)
16298 (calendar-view-holidays-initially-flag nil)
16299 (calendar-view-diary-initially-flag nil))
16300 (if (or (org-at-timestamp-p)
16301 (save-excursion
16302 (beginning-of-line 1)
16303 (looking-at (concat ".*" tsr))))
16304 (let ((d1 (time-to-days (current-time)))
16305 (d2 (time-to-days
16306 (org-time-string-to-time (match-string 1)))))
16307 (setq diff (- d2 d1))))
16308 (calendar)
16309 (calendar-goto-today)
16310 (if (and diff (not arg)) (calendar-forward-day diff))))
16312 (defun org-get-date-from-calendar ()
16313 "Return a list (month day year) of date at point in calendar."
16314 (with-current-buffer "*Calendar*"
16315 (save-match-data
16316 (calendar-cursor-to-date))))
16318 (defun org-date-from-calendar ()
16319 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
16320 If there is already a time stamp at the cursor position, update it."
16321 (interactive)
16322 (if (org-at-timestamp-p t)
16323 (org-timestamp-change 0 'calendar)
16324 (let ((cal-date (org-get-date-from-calendar)))
16325 (org-insert-time-stamp
16326 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
16328 (defun org-minutes-to-hh:mm-string (m)
16329 "Compute H:MM from a number of minutes."
16330 (let ((h (/ m 60)))
16331 (setq m (- m (* 60 h)))
16332 (format org-time-clocksum-format h m)))
16334 (defun org-hh:mm-string-to-minutes (s)
16335 "Convert a string H:MM to a number of minutes.
16336 If the string is just a number, interpret it as minutes.
16337 In fact, the first hh:mm or number in the string will be taken,
16338 there can be extra stuff in the string.
16339 If no number is found, the return value is 0."
16340 (cond
16341 ((integerp s) s)
16342 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
16343 (+ (* (string-to-number (match-string 1 s)) 60)
16344 (string-to-number (match-string 2 s))))
16345 ((string-match "\\([0-9]+\\)" s)
16346 (string-to-number (match-string 1 s)))
16347 (t 0)))
16349 (defcustom org-effort-durations
16350 `(("h" . 60)
16351 ("d" . ,(* 60 8))
16352 ("w" . ,(* 60 8 5))
16353 ("m" . ,(* 60 8 5 4))
16354 ("y" . ,(* 60 8 5 40)))
16355 "Conversion factor to minutes for an effort modifier.
16357 Each entry has the form (MODIFIER . MINUTES).
16359 In an effort string, a number followed by MODIFIER is multiplied
16360 by the specified number of MINUTES to obtain an effort in
16361 minutes.
16363 For example, if the value of this variable is ((\"hours\" . 60)), then an
16364 effort string \"2hours\" is equivalent to 120 minutes."
16365 :group 'org-agenda
16366 :version "24.1"
16367 :type '(alist :key-type (string :tag "Modifier")
16368 :value-type (number :tag "Minutes")))
16370 (defun org-duration-string-to-minutes (s)
16371 "Convert a duration string S to minutes.
16373 A bare number is interpreted as minutes, modifiers can be set by
16374 customizing `org-effort-durations' (which see).
16376 Entries containing a colon are interpreted as H:MM by
16377 `org-hh:mm-string-to-minutes'."
16378 (let ((result 0)
16379 (re (concat "\\([0-9]+\\) *\\("
16380 (regexp-opt (mapcar 'car org-effort-durations))
16381 "\\)")))
16382 (while (string-match re s)
16383 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
16384 (string-to-number (match-string 1 s))))
16385 (setq s (replace-match "" nil t s)))
16386 (incf result (org-hh:mm-string-to-minutes s))
16387 result))
16389 ;;;; Files
16391 (defun org-save-all-org-buffers ()
16392 "Save all Org-mode buffers without user confirmation."
16393 (interactive)
16394 (message "Saving all Org-mode buffers...")
16395 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
16396 (when (featurep 'org-id) (org-id-locations-save))
16397 (message "Saving all Org-mode buffers... done"))
16399 (defun org-revert-all-org-buffers ()
16400 "Revert all Org-mode buffers.
16401 Prompt for confirmation when there are unsaved changes.
16402 Be sure you know what you are doing before letting this function
16403 overwrite your changes.
16405 This function is useful in a setup where one tracks org files
16406 with a version control system, to revert on one machine after pulling
16407 changes from another. I believe the procedure must be like this:
16409 1. M-x org-save-all-org-buffers
16410 2. Pull changes from the other machine, resolve conflicts
16411 3. M-x org-revert-all-org-buffers"
16412 (interactive)
16413 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
16414 (error "Abort"))
16415 (save-excursion
16416 (save-window-excursion
16417 (mapc
16418 (lambda (b)
16419 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
16420 (with-current-buffer b buffer-file-name))
16421 (org-pop-to-buffer-same-window b)
16422 (revert-buffer t 'no-confirm)))
16423 (buffer-list))
16424 (when (and (featurep 'org-id) org-id-track-globally)
16425 (org-id-locations-load)))))
16427 ;;;; Agenda files
16429 ;;;###autoload
16430 (defun org-switchb (&optional arg)
16431 "Switch between Org buffers.
16432 With one prefix argument, restrict available buffers to files.
16433 With two prefix arguments, restrict available buffers to agenda files.
16435 Defaults to `iswitchb' for buffer name completion.
16436 Set `org-completion-use-ido' to make it use ido instead."
16437 (interactive "P")
16438 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
16439 ((equal arg '(16)) (org-buffer-list 'agenda))
16440 (t (org-buffer-list))))
16441 (org-completion-use-iswitchb org-completion-use-iswitchb)
16442 (org-completion-use-ido org-completion-use-ido))
16443 (unless (or org-completion-use-ido org-completion-use-iswitchb)
16444 (setq org-completion-use-iswitchb t))
16445 (org-pop-to-buffer-same-window
16446 (org-icompleting-read "Org buffer: "
16447 (mapcar 'list (mapcar 'buffer-name blist))
16448 nil t))))
16450 ;;; Define some older names previously used for this functionality
16451 ;;;###autoload
16452 (defalias 'org-ido-switchb 'org-switchb)
16453 ;;;###autoload
16454 (defalias 'org-iswitchb 'org-switchb)
16456 (defun org-buffer-list (&optional predicate exclude-tmp)
16457 "Return a list of Org buffers.
16458 PREDICATE can be `export', `files' or `agenda'.
16460 export restrict the list to Export buffers.
16461 files restrict the list to buffers visiting Org files.
16462 agenda restrict the list to buffers visiting agenda files.
16464 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
16465 (let* ((bfn nil)
16466 (agenda-files (and (eq predicate 'agenda)
16467 (mapcar 'file-truename (org-agenda-files t))))
16468 (filter
16469 (cond
16470 ((eq predicate 'files)
16471 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
16472 ((eq predicate 'export)
16473 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
16474 ((eq predicate 'agenda)
16475 (lambda (b)
16476 (with-current-buffer b
16477 (and (derived-mode-p 'org-mode)
16478 (setq bfn (buffer-file-name b))
16479 (member (file-truename bfn) agenda-files)))))
16480 (t (lambda (b) (with-current-buffer b
16481 (or (derived-mode-p 'org-mode)
16482 (string-match "\*Org .*Export"
16483 (buffer-name b)))))))))
16484 (delq nil
16485 (mapcar
16486 (lambda(b)
16487 (if (and (funcall filter b)
16488 (or (not exclude-tmp)
16489 (not (string-match "tmp" (buffer-name b)))))
16491 nil))
16492 (buffer-list)))))
16494 (defun org-agenda-files (&optional unrestricted archives)
16495 "Get the list of agenda files.
16496 Optional UNRESTRICTED means return the full list even if a restriction
16497 is currently in place.
16498 When ARCHIVES is t, include all archive files that are really being
16499 used by the agenda files. If ARCHIVE is `ifmode', do this only if
16500 `org-agenda-archives-mode' is t."
16501 (let ((files
16502 (cond
16503 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
16504 ((stringp org-agenda-files) (org-read-agenda-file-list))
16505 ((listp org-agenda-files) org-agenda-files)
16506 (t (error "Invalid value of `org-agenda-files'")))))
16507 (setq files (apply 'append
16508 (mapcar (lambda (f)
16509 (if (file-directory-p f)
16510 (directory-files
16511 f t org-agenda-file-regexp)
16512 (list f)))
16513 files)))
16514 (when org-agenda-skip-unavailable-files
16515 (setq files (delq nil
16516 (mapcar (function
16517 (lambda (file)
16518 (and (file-readable-p file) file)))
16519 files))))
16520 (when (or (eq archives t)
16521 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
16522 (setq files (org-add-archive-files files)))
16523 files))
16525 (defun org-agenda-file-p (&optional file)
16526 "Return non-nil, if FILE is an agenda file.
16527 If FILE is omitted, use the file associated with the current
16528 buffer."
16529 (member (or file (buffer-file-name))
16530 (org-agenda-files t)))
16532 (defun org-edit-agenda-file-list ()
16533 "Edit the list of agenda files.
16534 Depending on setup, this either uses customize to edit the variable
16535 `org-agenda-files', or it visits the file that is holding the list. In the
16536 latter case, the buffer is set up in a way that saving it automatically kills
16537 the buffer and restores the previous window configuration."
16538 (interactive)
16539 (if (stringp org-agenda-files)
16540 (let ((cw (current-window-configuration)))
16541 (find-file org-agenda-files)
16542 (org-set-local 'org-window-configuration cw)
16543 (org-add-hook 'after-save-hook
16544 (lambda ()
16545 (set-window-configuration
16546 (prog1 org-window-configuration
16547 (kill-buffer (current-buffer))))
16548 (org-install-agenda-files-menu)
16549 (message "New agenda file list installed"))
16550 nil 'local)
16551 (message "%s" (substitute-command-keys
16552 "Edit list and finish with \\[save-buffer]")))
16553 (customize-variable 'org-agenda-files)))
16555 (defun org-store-new-agenda-file-list (list)
16556 "Set new value for the agenda file list and save it correctly."
16557 (if (stringp org-agenda-files)
16558 (let ((fe (org-read-agenda-file-list t)) b u)
16559 (while (setq b (find-buffer-visiting org-agenda-files))
16560 (kill-buffer b))
16561 (with-temp-file org-agenda-files
16562 (insert
16563 (mapconcat
16564 (lambda (f) ;; Keep un-expanded entries.
16565 (if (setq u (assoc f fe))
16566 (cdr u)
16568 list "\n")
16569 "\n")))
16570 (let ((org-mode-hook nil) (org-inhibit-startup t)
16571 (org-insert-mode-line-in-empty-file nil))
16572 (setq org-agenda-files list)
16573 (customize-save-variable 'org-agenda-files org-agenda-files))))
16575 (defun org-read-agenda-file-list (&optional pair-with-expansion)
16576 "Read the list of agenda files from a file.
16577 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
16578 filenames, used by `org-store-new-agenda-file-list' to write back
16579 un-expanded file names."
16580 (when (file-directory-p org-agenda-files)
16581 (error "`org-agenda-files' cannot be a single directory"))
16582 (when (stringp org-agenda-files)
16583 (with-temp-buffer
16584 (insert-file-contents org-agenda-files)
16585 (mapcar
16586 (lambda (f)
16587 (let ((e (expand-file-name (substitute-in-file-name f)
16588 org-directory)))
16589 (if pair-with-expansion
16590 (cons e f)
16591 e)))
16592 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
16594 ;;;###autoload
16595 (defun org-cycle-agenda-files ()
16596 "Cycle through the files in `org-agenda-files'.
16597 If the current buffer visits an agenda file, find the next one in the list.
16598 If the current buffer does not, find the first agenda file."
16599 (interactive)
16600 (let* ((fs (org-agenda-files t))
16601 (files (append fs (list (car fs))))
16602 (tcf (if buffer-file-name (file-truename buffer-file-name)))
16603 file)
16604 (unless files (error "No agenda files"))
16605 (catch 'exit
16606 (while (setq file (pop files))
16607 (if (equal (file-truename file) tcf)
16608 (when (car files)
16609 (find-file (car files))
16610 (throw 'exit t))))
16611 (find-file (car fs)))
16612 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
16614 (defun org-agenda-file-to-front (&optional to-end)
16615 "Move/add the current file to the top of the agenda file list.
16616 If the file is not present in the list, it is added to the front. If it is
16617 present, it is moved there. With optional argument TO-END, add/move to the
16618 end of the list."
16619 (interactive "P")
16620 (let ((org-agenda-skip-unavailable-files nil)
16621 (file-alist (mapcar (lambda (x)
16622 (cons (file-truename x) x))
16623 (org-agenda-files t)))
16624 (ctf (file-truename buffer-file-name))
16625 x had)
16626 (setq x (assoc ctf file-alist) had x)
16628 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
16629 (if to-end
16630 (setq file-alist (append (delq x file-alist) (list x)))
16631 (setq file-alist (cons x (delq x file-alist))))
16632 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
16633 (org-install-agenda-files-menu)
16634 (message "File %s to %s of agenda file list"
16635 (if had "moved" "added") (if to-end "end" "front"))))
16637 (defun org-remove-file (&optional file)
16638 "Remove current file from the list of files in variable `org-agenda-files'.
16639 These are the files which are being checked for agenda entries.
16640 Optional argument FILE means use this file instead of the current."
16641 (interactive)
16642 (let* ((org-agenda-skip-unavailable-files nil)
16643 (file (or file buffer-file-name))
16644 (true-file (file-truename file))
16645 (afile (abbreviate-file-name file))
16646 (files (delq nil (mapcar
16647 (lambda (x)
16648 (if (equal true-file
16649 (file-truename x))
16650 nil x))
16651 (org-agenda-files t)))))
16652 (if (not (= (length files) (length (org-agenda-files t))))
16653 (progn
16654 (org-store-new-agenda-file-list files)
16655 (org-install-agenda-files-menu)
16656 (message "Removed file: %s" afile))
16657 (message "File was not in list: %s (not removed)" afile))))
16659 (defun org-file-menu-entry (file)
16660 (vector file (list 'find-file file) t))
16662 (defun org-check-agenda-file (file)
16663 "Make sure FILE exists. If not, ask user what to do."
16664 (when (not (file-exists-p file))
16665 (message "non-existent agenda file %s. [R]emove from list or [A]bort?"
16666 (abbreviate-file-name file))
16667 (let ((r (downcase (read-char-exclusive))))
16668 (cond
16669 ((equal r ?r)
16670 (org-remove-file file)
16671 (throw 'nextfile t))
16672 (t (error "Abort"))))))
16674 (defun org-get-agenda-file-buffer (file)
16675 "Get a buffer visiting FILE. If the buffer needs to be created, add
16676 it to the list of buffers which might be released later."
16677 (let ((buf (org-find-base-buffer-visiting file)))
16678 (if buf
16679 buf ; just return it
16680 ;; Make a new buffer and remember it
16681 (setq buf (find-file-noselect file))
16682 (if buf (push buf org-agenda-new-buffers))
16683 buf)))
16685 (defun org-release-buffers (blist)
16686 "Release all buffers in list, asking the user for confirmation when needed.
16687 When a buffer is unmodified, it is just killed. When modified, it is saved
16688 \(if the user agrees) and then killed."
16689 (let (buf file)
16690 (while (setq buf (pop blist))
16691 (setq file (buffer-file-name buf))
16692 (when (and (buffer-modified-p buf)
16693 file
16694 (y-or-n-p (format "Save file %s? " file)))
16695 (with-current-buffer buf (save-buffer)))
16696 (kill-buffer buf))))
16698 (defun org-prepare-agenda-buffers (files)
16699 "Create buffers for all agenda files, protect archived trees and comments."
16700 (interactive)
16701 (let ((pa '(:org-archived t))
16702 (pc '(:org-comment t))
16703 (pall '(:org-archived t :org-comment t))
16704 (inhibit-read-only t)
16705 (rea (concat ":" org-archive-tag ":"))
16706 bmp file re)
16707 (save-excursion
16708 (save-restriction
16709 (while (setq file (pop files))
16710 (catch 'nextfile
16711 (if (bufferp file)
16712 (set-buffer file)
16713 (org-check-agenda-file file)
16714 (set-buffer (org-get-agenda-file-buffer file)))
16715 (widen)
16716 (setq bmp (buffer-modified-p))
16717 (org-refresh-category-properties)
16718 (setq org-todo-keywords-for-agenda
16719 (append org-todo-keywords-for-agenda org-todo-keywords-1))
16720 (setq org-done-keywords-for-agenda
16721 (append org-done-keywords-for-agenda org-done-keywords))
16722 (setq org-todo-keyword-alist-for-agenda
16723 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
16724 (setq org-drawers-for-agenda
16725 (append org-drawers-for-agenda org-drawers))
16726 (setq org-tag-alist-for-agenda
16727 (append org-tag-alist-for-agenda org-tag-alist))
16729 (save-excursion
16730 (remove-text-properties (point-min) (point-max) pall)
16731 (when org-agenda-skip-archived-trees
16732 (goto-char (point-min))
16733 (while (re-search-forward rea nil t)
16734 (if (org-at-heading-p t)
16735 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
16736 (goto-char (point-min))
16737 (setq re (format org-heading-keyword-regexp-format
16738 org-comment-string))
16739 (while (re-search-forward re nil t)
16740 (add-text-properties
16741 (match-beginning 0) (org-end-of-subtree t) pc)))
16742 (set-buffer-modified-p bmp)))))
16743 (setq org-todo-keywords-for-agenda
16744 (org-uniquify org-todo-keywords-for-agenda))
16745 (setq org-todo-keyword-alist-for-agenda
16746 (org-uniquify org-todo-keyword-alist-for-agenda)
16747 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
16749 ;;;; Embedded LaTeX
16751 (defvar org-cdlatex-mode-map (make-sparse-keymap)
16752 "Keymap for the minor `org-cdlatex-mode'.")
16754 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
16755 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
16756 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
16757 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
16758 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
16760 (defvar org-cdlatex-texmathp-advice-is-done nil
16761 "Flag remembering if we have applied the advice to texmathp already.")
16763 (define-minor-mode org-cdlatex-mode
16764 "Toggle the minor `org-cdlatex-mode'.
16765 This mode supports entering LaTeX environment and math in LaTeX fragments
16766 in Org-mode.
16767 \\{org-cdlatex-mode-map}"
16768 nil " OCDL" nil
16769 (when org-cdlatex-mode
16770 (require 'cdlatex)
16771 (run-hooks 'cdlatex-mode-hook)
16772 (cdlatex-compute-tables))
16773 (unless org-cdlatex-texmathp-advice-is-done
16774 (setq org-cdlatex-texmathp-advice-is-done t)
16775 (defadvice texmathp (around org-math-always-on activate)
16776 "Always return t in org-mode buffers.
16777 This is because we want to insert math symbols without dollars even outside
16778 the LaTeX math segments. If Orgmode thinks that point is actually inside
16779 an embedded LaTeX fragment, let texmathp do its job.
16780 \\[org-cdlatex-mode-map]"
16781 (interactive)
16782 (let (p)
16783 (cond
16784 ((not (derived-mode-p 'org-mode)) ad-do-it)
16785 ((eq this-command 'cdlatex-math-symbol)
16786 (setq ad-return-value t
16787 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
16789 (let ((p (org-inside-LaTeX-fragment-p)))
16790 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
16791 (setq ad-return-value t
16792 texmathp-why '("Org-mode embedded math" . 0))
16793 (if p ad-do-it)))))))))
16795 (defun turn-on-org-cdlatex ()
16796 "Unconditionally turn on `org-cdlatex-mode'."
16797 (org-cdlatex-mode 1))
16799 (defun org-inside-LaTeX-fragment-p ()
16800 "Test if point is inside a LaTeX fragment.
16801 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
16802 sequence appearing also before point.
16803 Even though the matchers for math are configurable, this function assumes
16804 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
16805 delimiters are skipped when they have been removed by customization.
16806 The return value is nil, or a cons cell with the delimiter and the
16807 position of this delimiter.
16809 This function does a reasonably good job, but can locally be fooled by
16810 for example currency specifications. For example it will assume being in
16811 inline math after \"$22.34\". The LaTeX fragment formatter will only format
16812 fragments that are properly closed, but during editing, we have to live
16813 with the uncertainty caused by missing closing delimiters. This function
16814 looks only before point, not after."
16815 (catch 'exit
16816 (let ((pos (point))
16817 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
16818 (lim (progn
16819 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
16820 (point)))
16821 dd-on str (start 0) m re)
16822 (goto-char pos)
16823 (when dodollar
16824 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
16825 re (nth 1 (assoc "$" org-latex-regexps)))
16826 (while (string-match re str start)
16827 (cond
16828 ((= (match-end 0) (length str))
16829 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
16830 ((= (match-end 0) (- (length str) 5))
16831 (throw 'exit nil))
16832 (t (setq start (match-end 0))))))
16833 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
16834 (goto-char pos)
16835 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
16836 (and (match-beginning 2) (throw 'exit nil))
16837 ;; count $$
16838 (while (re-search-backward "\\$\\$" lim t)
16839 (setq dd-on (not dd-on)))
16840 (goto-char pos)
16841 (if dd-on (cons "$$" m))))))
16843 (defun org-inside-latex-macro-p ()
16844 "Is point inside a LaTeX macro or its arguments?"
16845 (save-match-data
16846 (org-in-regexp
16847 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
16849 (defun org-try-cdlatex-tab ()
16850 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
16851 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
16852 - inside a LaTeX fragment, or
16853 - after the first word in a line, where an abbreviation expansion could
16854 insert a LaTeX environment."
16855 (when org-cdlatex-mode
16856 (cond
16857 ;; Before any word on the line: No expansion possible.
16858 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
16859 ;; Just after first word on the line: Expand it. Make sure it
16860 ;; cannot happen on headlines, though.
16861 ((save-excursion
16862 (skip-chars-backward "a-zA-Z0-9*")
16863 (skip-chars-backward " \t")
16864 (and (bolp) (not (org-at-heading-p))))
16865 (cdlatex-tab) t)
16866 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
16868 (defun org-cdlatex-underscore-caret (&optional arg)
16869 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
16870 Revert to the normal definition outside of these fragments."
16871 (interactive "P")
16872 (if (org-inside-LaTeX-fragment-p)
16873 (call-interactively 'cdlatex-sub-superscript)
16874 (let (org-cdlatex-mode)
16875 (call-interactively (key-binding (vector last-input-event))))))
16877 (defun org-cdlatex-math-modify (&optional arg)
16878 "Execute `cdlatex-math-modify' in LaTeX fragments.
16879 Revert to the normal definition outside of these fragments."
16880 (interactive "P")
16881 (if (org-inside-LaTeX-fragment-p)
16882 (call-interactively 'cdlatex-math-modify)
16883 (let (org-cdlatex-mode)
16884 (call-interactively (key-binding (vector last-input-event))))))
16886 (defvar org-latex-fragment-image-overlays nil
16887 "List of overlays carrying the images of latex fragments.")
16888 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
16890 (defun org-remove-latex-fragment-image-overlays ()
16891 "Remove all overlays with LaTeX fragment images in current buffer."
16892 (mapc 'delete-overlay org-latex-fragment-image-overlays)
16893 (setq org-latex-fragment-image-overlays nil))
16895 (defun org-preview-latex-fragment (&optional subtree)
16896 "Preview the LaTeX fragment at point, or all locally or globally.
16897 If the cursor is in a LaTeX fragment, create the image and overlay
16898 it over the source code. If there is no fragment at point, display
16899 all fragments in the current text, from one headline to the next. With
16900 prefix SUBTREE, display all fragments in the current subtree. With a
16901 double prefix arg \\[universal-argument] \\[universal-argument], or when \
16902 the cursor is before the first headline,
16903 display all fragments in the buffer.
16904 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
16905 (interactive "P")
16906 (unless buffer-file-name
16907 (error "Can't preview LaTeX fragment in a non-file buffer"))
16908 (org-remove-latex-fragment-image-overlays)
16909 (save-excursion
16910 (save-restriction
16911 (let (beg end at msg)
16912 (cond
16913 ((or (equal subtree '(16))
16914 (not (save-excursion
16915 (re-search-backward org-outline-regexp-bol nil t))))
16916 (setq beg (point-min) end (point-max)
16917 msg "Creating images for buffer...%s"))
16918 ((equal subtree '(4))
16919 (org-back-to-heading)
16920 (setq beg (point) end (org-end-of-subtree t)
16921 msg "Creating images for subtree...%s"))
16923 (if (setq at (org-inside-LaTeX-fragment-p))
16924 (goto-char (max (point-min) (- (cdr at) 2)))
16925 (org-back-to-heading))
16926 (setq beg (point) end (progn (outline-next-heading) (point))
16927 msg (if at "Creating image...%s"
16928 "Creating images for entry...%s"))))
16929 (message msg "")
16930 (narrow-to-region beg end)
16931 (goto-char beg)
16932 (org-format-latex
16933 (concat "ltxpng/" (file-name-sans-extension
16934 (file-name-nondirectory
16935 buffer-file-name)))
16936 default-directory 'overlays msg at 'forbuffer
16937 org-latex-create-formula-image-program)
16938 (message msg "done. Use `C-c C-c' to remove images.")))))
16940 (defvar org-latex-regexps
16941 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
16942 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
16943 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
16944 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
16945 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
16946 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
16947 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
16948 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
16949 "Regular expressions for matching embedded LaTeX.")
16951 (defvar org-export-have-math nil) ;; dynamic scoping
16952 (defun org-format-latex (prefix &optional dir overlays msg at
16953 forbuffer processing-type)
16954 "Replace LaTeX fragments with links to an image, and produce images.
16955 Some of the options can be changed using the variable
16956 `org-format-latex-options'."
16957 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
16958 (let* ((prefixnodir (file-name-nondirectory prefix))
16959 (absprefix (expand-file-name prefix dir))
16960 (todir (file-name-directory absprefix))
16961 (opt org-format-latex-options)
16962 (matchers (plist-get opt :matchers))
16963 (re-list org-latex-regexps)
16964 (org-format-latex-header-extra
16965 (plist-get (org-infile-export-plist) :latex-header-extra))
16966 (cnt 0) txt hash link beg end re e checkdir
16967 executables-checked string
16968 m n block-type block linkfile movefile ov)
16969 ;; Check the different regular expressions
16970 (while (setq e (pop re-list))
16971 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
16972 block (if block-type "\n\n" ""))
16973 (when (member m matchers)
16974 (goto-char (point-min))
16975 (while (re-search-forward re nil t)
16976 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
16977 (not (get-text-property (match-beginning n)
16978 'org-protected))
16979 (or (not overlays)
16980 (not (eq (get-char-property (match-beginning n)
16981 'org-overlay-type)
16982 'org-latex-overlay))))
16983 (setq org-export-have-math t)
16984 (cond
16985 ((eq processing-type 'verbatim)
16986 ;; Leave the text verbatim, just protect it
16987 (add-text-properties (match-beginning n) (match-end n)
16988 '(org-protected t)))
16989 ((eq processing-type 'mathjax)
16990 ;; Prepare for MathJax processing
16991 (setq string (match-string n))
16992 (if (member m '("$" "$1"))
16993 (save-excursion
16994 (delete-region (match-beginning n) (match-end n))
16995 (goto-char (match-beginning n))
16996 (insert (org-add-props (concat "\\(" (substring string 1 -1)
16997 "\\)")
16998 '(org-protected t))))
16999 (add-text-properties (match-beginning n) (match-end n)
17000 '(org-protected t))))
17001 ((or (eq processing-type 'dvipng)
17002 (eq processing-type 'imagemagick))
17003 ;; Process to an image
17004 (setq txt (match-string n)
17005 beg (match-beginning n) end (match-end n)
17006 cnt (1+ cnt))
17007 (let (print-length print-level) ; make sure full list is printed
17008 (setq hash (sha1 (prin1-to-string
17009 (list org-format-latex-header
17010 org-format-latex-header-extra
17011 org-export-latex-default-packages-alist
17012 org-export-latex-packages-alist
17013 org-format-latex-options
17014 forbuffer txt)))
17015 linkfile (format "%s_%s.png" prefix hash)
17016 movefile (format "%s_%s.png" absprefix hash)))
17017 (setq link (concat block "[[file:" linkfile "]]" block))
17018 (if msg (message msg cnt))
17019 (goto-char beg)
17020 (unless checkdir ; make sure the directory exists
17021 (setq checkdir t)
17022 (or (file-directory-p todir) (make-directory todir t)))
17023 (cond
17024 ((eq processing-type 'dvipng)
17025 (unless executables-checked
17026 (org-check-external-command
17027 "latex" "needed to convert LaTeX fragments to images")
17028 (org-check-external-command
17029 "dvipng" "needed to convert LaTeX fragments to images")
17030 (setq executables-checked t))
17031 (unless (file-exists-p movefile)
17032 (org-create-formula-image-with-dvipng
17033 txt movefile opt forbuffer)))
17034 ((eq processing-type 'imagemagick)
17035 (unless executables-checked
17036 (org-check-external-command
17037 "converte" "you need to install imagemagick")
17038 (setq executables-checked t))
17039 (unless (file-exists-p movefile)
17040 (org-create-formula-image-with-imagemagick
17041 txt movefile opt forbuffer))))
17042 (if overlays
17043 (progn
17044 (mapc (lambda (o)
17045 (if (eq (overlay-get o 'org-overlay-type)
17046 'org-latex-overlay)
17047 (delete-overlay o)))
17048 (overlays-in beg end))
17049 (setq ov (make-overlay beg end))
17050 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
17051 (if (featurep 'xemacs)
17052 (progn
17053 (overlay-put ov 'invisible t)
17054 (overlay-put
17055 ov 'end-glyph
17056 (make-glyph (vector 'png :file movefile))))
17057 (overlay-put
17058 ov 'display
17059 (list 'image :type 'png :file movefile :ascent 'center)))
17060 (push ov org-latex-fragment-image-overlays)
17061 (goto-char end))
17062 (delete-region beg end)
17063 (insert (org-add-props link
17064 (list 'org-latex-src
17065 (replace-regexp-in-string
17066 "\"" "" txt)
17067 'org-latex-src-embed-type
17068 (if block-type 'paragraph 'character))))))
17069 ((eq processing-type 'mathml)
17070 ;; Process to MathML
17071 (unless executables-checked
17072 (unless (save-match-data (org-format-latex-mathml-available-p))
17073 (error "LaTeX to MathML converter not configured"))
17074 (setq executables-checked t))
17075 (setq txt (match-string n)
17076 beg (match-beginning n) end (match-end n)
17077 cnt (1+ cnt))
17078 (if msg (message msg cnt))
17079 (goto-char beg)
17080 (delete-region beg end)
17081 (insert (org-format-latex-as-mathml
17082 txt block-type prefix dir)))
17084 (error "Unknown conversion type %s for latex fragments"
17085 processing-type)))))))))
17087 (defun org-create-math-formula (latex-frag &optional mathml-file)
17088 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
17089 Use `org-latex-to-mathml-convert-command'. If the conversion is
17090 sucessful, return the portion between \"<math...> </math>\"
17091 elements otherwise return nil. When MATHML-FILE is specified,
17092 write the results in to that file. When invoked as an
17093 interactive command, prompt for LATEX-FRAG, with initial value
17094 set to the current active region and echo the results for user
17095 inspection."
17096 (interactive (list (let ((frag (when (region-active-p)
17097 (buffer-substring-no-properties
17098 (region-beginning) (region-end)))))
17099 (read-string "LaTeX Fragment: " frag nil frag))))
17100 (unless latex-frag (error "Invalid latex-frag"))
17101 (let* ((tmp-in-file (file-relative-name
17102 (make-temp-name (expand-file-name "ltxmathml-in"))))
17103 (ignore (write-region latex-frag nil tmp-in-file))
17104 (tmp-out-file (file-relative-name
17105 (make-temp-name (expand-file-name "ltxmathml-out"))))
17106 (cmd (format-spec
17107 org-latex-to-mathml-convert-command
17108 `((?j . ,(shell-quote-argument
17109 (expand-file-name org-latex-to-mathml-jar-file)))
17110 (?I . ,(shell-quote-argument tmp-in-file))
17111 (?o . ,(shell-quote-argument tmp-out-file)))))
17112 mathml shell-command-output)
17113 (when (org-called-interactively-p 'any)
17114 (unless (org-format-latex-mathml-available-p)
17115 (error "LaTeX to MathML converter not configured")))
17116 (message "Running %s" cmd)
17117 (setq shell-command-output (shell-command-to-string cmd))
17118 (setq mathml
17119 (when (file-readable-p tmp-out-file)
17120 (with-current-buffer (find-file-noselect tmp-out-file t)
17121 (goto-char (point-min))
17122 (when (re-search-forward
17123 (concat
17124 (regexp-quote
17125 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
17126 "\\(.\\|\n\\)*"
17127 (regexp-quote "</math>")) nil t)
17128 (prog1 (match-string 0) (kill-buffer))))))
17129 (cond
17130 (mathml
17131 (setq mathml
17132 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
17133 (when mathml-file
17134 (write-region mathml nil mathml-file))
17135 (when (org-called-interactively-p 'any)
17136 (message mathml)))
17137 ((message "LaTeX to MathML conversion failed")
17138 (message shell-command-output)))
17139 (delete-file tmp-in-file)
17140 (when (file-exists-p tmp-out-file)
17141 (delete-file tmp-out-file))
17142 mathml))
17144 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
17145 prefix &optional dir)
17146 "Use `org-create-math-formula' but check local cache first."
17147 (let* ((absprefix (expand-file-name prefix dir))
17148 (print-length nil) (print-level nil)
17149 (formula-id (concat
17150 "formula-"
17151 (sha1
17152 (prin1-to-string
17153 (list latex-frag
17154 org-latex-to-mathml-convert-command)))))
17155 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
17156 (formula-cache-dir (file-name-directory formula-cache)))
17158 (unless (file-directory-p formula-cache-dir)
17159 (make-directory formula-cache-dir t))
17161 (unless (file-exists-p formula-cache)
17162 (org-create-math-formula latex-frag formula-cache))
17164 (if (file-exists-p formula-cache)
17165 ;; Successful conversion. Return the link to MathML file.
17166 (org-add-props
17167 (format "[[file:%s]]" (file-relative-name formula-cache dir))
17168 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
17169 'org-latex-src-embed-type (if latex-frag-type
17170 'paragraph 'character)))
17171 ;; Failed conversion. Return the LaTeX fragment verbatim
17172 (add-text-properties
17173 0 (1- (length latex-frag)) '(org-protected t) latex-frag)
17174 latex-frag)))
17176 ;; This function borrows from Ganesh Swami's latex2png.el
17177 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
17178 "This calls dvipng."
17179 (require 'org-latex)
17180 (let* ((tmpdir (if (featurep 'xemacs)
17181 (temp-directory)
17182 temporary-file-directory))
17183 (texfilebase (make-temp-name
17184 (expand-file-name "orgtex" tmpdir)))
17185 (texfile (concat texfilebase ".tex"))
17186 (dvifile (concat texfilebase ".dvi"))
17187 (pngfile (concat texfilebase ".png"))
17188 (fnh (if (featurep 'xemacs)
17189 (font-height (face-font 'default))
17190 (face-attribute 'default :height nil)))
17191 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17192 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17193 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17194 "Black"))
17195 (bg (or (plist-get options (if buffer :background :html-background))
17196 "Transparent")))
17197 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
17198 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
17199 (with-temp-file texfile
17200 (insert (org-splice-latex-header
17201 org-format-latex-header
17202 org-export-latex-default-packages-alist
17203 org-export-latex-packages-alist t
17204 org-format-latex-header-extra))
17205 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")
17206 (require 'org-latex)
17207 (org-export-latex-fix-inputenc))
17208 (let ((dir default-directory))
17209 (condition-case nil
17210 (progn
17211 (cd tmpdir)
17212 (call-process "latex" nil nil nil texfile))
17213 (error nil))
17214 (cd dir))
17215 (if (not (file-exists-p dvifile))
17216 (progn (message "Failed to create dvi file from %s" texfile) nil)
17217 (condition-case nil
17218 (if (featurep 'xemacs)
17219 (call-process "dvipng" nil nil nil
17220 "-fg" fg "-bg" bg
17221 "-T" "tight"
17222 "-o" pngfile
17223 dvifile)
17224 (call-process "dvipng" nil nil nil
17225 "-fg" fg "-bg" bg
17226 "-D" dpi
17227 ;;"-x" scale "-y" scale
17228 "-T" "tight"
17229 "-o" pngfile
17230 dvifile))
17231 (error nil))
17232 (if (not (file-exists-p pngfile))
17233 (if org-format-latex-signal-error
17234 (error "Failed to create png file from %s" texfile)
17235 (message "Failed to create png file from %s" texfile)
17236 nil)
17237 ;; Use the requested file name and clean up
17238 (copy-file pngfile tofile 'replace)
17239 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
17240 (delete-file (concat texfilebase e)))
17241 pngfile))))
17243 (defvar org-latex-to-pdf-process) ;; Defined in org-latex.el
17244 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
17245 "This calls convert, which is included into imagemagick."
17246 (require 'org-latex)
17247 (let* ((tmpdir (if (featurep 'xemacs)
17248 (temp-directory)
17249 temporary-file-directory))
17250 (texfilebase (make-temp-name
17251 (expand-file-name "orgtex" tmpdir)))
17252 (texfile (concat texfilebase ".tex"))
17253 (pdffile (concat texfilebase ".pdf"))
17254 (pngfile (concat texfilebase ".png"))
17255 (fnh (if (featurep 'xemacs)
17256 (font-height (face-font 'default))
17257 (face-attribute 'default :height nil)))
17258 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17259 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17260 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17261 "black"))
17262 (bg (or (plist-get options (if buffer :background :html-background))
17263 "white")))
17264 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
17265 (setq fg (org-latex-color-format fg)))
17266 (if (eq bg 'default) (setq bg (org-latex-color :background))
17267 (setq bg (org-latex-color-format
17268 (if (string= bg "Transparent")(setq bg "white")))))
17269 (with-temp-file texfile
17270 (insert (org-splice-latex-header
17271 org-format-latex-header
17272 org-export-latex-default-packages-alist
17273 org-export-latex-packages-alist t
17274 org-format-latex-header-extra))
17275 (insert "\n\\begin{document}\n"
17276 "\\definecolor{fg}{rgb}{" fg "}\n"
17277 "\\definecolor{bg}{rgb}{" bg "}\n"
17278 "\n\\pagecolor{bg}\n"
17279 "\n{\\color{fg}\n"
17280 string
17281 "\n}\n"
17282 "\n\\end{document}\n" )
17283 (require 'org-latex)
17284 (org-export-latex-fix-inputenc))
17285 (let ((dir default-directory) cmd cmds latex-frags-cmds)
17286 (condition-case nil
17287 (progn
17288 (cd tmpdir)
17289 (setq cmds org-latex-to-pdf-process)
17290 (while cmds
17291 (setq latex-frags-cmds (pop cmds))
17292 (if (listp latex-frags-cmds)
17293 (setq cmds nil)
17294 (setq latex-frags-cmds (list (car org-latex-to-pdf-process)))))
17295 (while latex-frags-cmds
17296 (setq cmd (pop latex-frags-cmds))
17297 (while (string-match "%b" cmd)
17298 (setq cmd (replace-match
17299 (save-match-data
17300 (shell-quote-argument texfile))
17301 t t cmd)))
17302 (while (string-match "%f" cmd)
17303 (setq cmd (replace-match
17304 (save-match-data
17305 (shell-quote-argument (file-name-nondirectory texfile)))
17306 t t cmd)))
17307 (while (string-match "%o" cmd)
17308 (setq cmd (replace-match
17309 (save-match-data
17310 (shell-quote-argument (file-name-directory texfile)))
17311 t t cmd)))
17312 (shell-command cmd)))
17313 (error nil))
17314 (cd dir))
17315 (if (not (file-exists-p pdffile))
17316 (progn (message "Failed to create pdf file from %s" texfile) nil)
17317 (condition-case nil
17318 (if (featurep 'xemacs)
17319 (call-process "convert" nil nil nil
17320 "-density" "96"
17321 "-trim"
17322 "-antialias"
17323 pdffile
17324 "-quality" "100"
17325 ;; "-sharpen" "0x1.0"
17326 pngfile)
17327 (call-process "convert" nil nil nil
17328 "-density" dpi
17329 "-trim"
17330 "-antialias"
17331 pdffile
17332 "-quality" "100"
17333 ; "-sharpen" "0x1.0"
17334 pngfile))
17335 (error nil))
17336 (if (not (file-exists-p pngfile))
17337 (if org-format-latex-signal-error
17338 (error "Failed to create png file from %s" texfile)
17339 (message "Failed to create png file from %s" texfile)
17340 nil)
17341 ;; Use the requested file name and clean up
17342 (copy-file pngfile tofile 'replace)
17343 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
17344 (delete-file (concat texfilebase e)))
17345 pngfile))))
17347 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
17348 "Fill a LaTeX header template TPL.
17349 In the template, the following place holders will be recognized:
17351 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
17352 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
17353 [PACKAGES] \\usepackage statements for PKG
17354 [NO-PACKAGES] do not include PKG
17355 [EXTRA] the string EXTRA
17356 [NO-EXTRA] do not include EXTRA
17358 For backward compatibility, if both the positive and the negative place
17359 holder is missing, the positive one (without the \"NO-\") will be
17360 assumed to be present at the end of the template.
17361 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
17362 EXTRA is a string.
17363 SNIPPETS-P indicates if this is run to create snippet images for HTML."
17364 (let (rpl (end ""))
17365 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
17366 (setq rpl (if (or (match-end 1) (not def-pkg))
17367 "" (org-latex-packages-to-string def-pkg snippets-p t))
17368 tpl (replace-match rpl t t tpl))
17369 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
17371 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
17372 (setq rpl (if (or (match-end 1) (not pkg))
17373 "" (org-latex-packages-to-string pkg snippets-p t))
17374 tpl (replace-match rpl t t tpl))
17375 (if pkg (setq end
17376 (concat end "\n"
17377 (org-latex-packages-to-string pkg snippets-p)))))
17379 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
17380 (setq rpl (if (or (match-end 1) (not extra))
17381 "" (concat extra "\n"))
17382 tpl (replace-match rpl t t tpl))
17383 (if (and extra (string-match "\\S-" extra))
17384 (setq end (concat end "\n" extra))))
17386 (if (string-match "\\S-" end)
17387 (concat tpl "\n" end)
17388 tpl)))
17390 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
17391 "Turn an alist of packages into a string with the \\usepackage macros."
17392 (setq pkg (mapconcat (lambda(p)
17393 (cond
17394 ((stringp p) p)
17395 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
17396 (format "%% Package %s omitted" (cadr p)))
17397 ((equal "" (car p))
17398 (format "\\usepackage{%s}" (cadr p)))
17400 (format "\\usepackage[%s]{%s}"
17401 (car p) (cadr p)))))
17403 "\n"))
17404 (if newline (concat pkg "\n") pkg))
17406 (defun org-dvipng-color (attr)
17407 "Return a RGB color specification for dvipng."
17408 (apply 'format "rgb %s %s %s"
17409 (mapcar 'org-normalize-color
17410 (if (featurep 'xemacs)
17411 (color-rgb-components
17412 (face-property 'default
17413 (cond ((eq attr :foreground) 'foreground)
17414 ((eq attr :background) 'background))))
17415 (color-values (face-attribute 'default attr nil))))))
17417 (defun org-latex-color (attr)
17418 "Return a RGB color for the LaTeX color package."
17419 (apply 'format "%s,%s,%s"
17420 (mapcar 'org-normalize-color
17421 (if (featurep 'xemacs)
17422 (color-rgb-components
17423 (face-property 'default
17424 (cond ((eq attr :foreground) 'foreground)
17425 ((eq attr :background) 'background))))
17426 (color-values (face-attribute 'default attr nil))))))
17428 (defun org-latex-color-format (color-name)
17429 "Convert COLOR-NAME to a RGB color value."
17430 (apply 'format "%s,%s,%s"
17431 (mapcar 'org-normalize-color
17432 (color-values color-name))))
17434 (defun org-normalize-color (value)
17435 "Return string to be used as color value for an RGB component."
17436 (format "%g" (/ value 65535.0)))
17438 ;; Image display
17441 (defvar org-inline-image-overlays nil)
17442 (make-variable-buffer-local 'org-inline-image-overlays)
17444 (defun org-toggle-inline-images (&optional include-linked)
17445 "Toggle the display of inline images.
17446 INCLUDE-LINKED is passed to `org-display-inline-images'."
17447 (interactive "P")
17448 (if org-inline-image-overlays
17449 (progn
17450 (org-remove-inline-images)
17451 (message "Inline image display turned off"))
17452 (org-display-inline-images include-linked)
17453 (if org-inline-image-overlays
17454 (message "%d images displayed inline"
17455 (length org-inline-image-overlays))
17456 (message "No images to display inline"))))
17458 (defun org-display-inline-images (&optional include-linked refresh beg end)
17459 "Display inline images.
17460 Normally only links without a description part are inlined, because this
17461 is how it will work for export. When INCLUDE-LINKED is set, also links
17462 with a description part will be inlined. This can be nice for a quick
17463 look at those images, but it does not reflect what exported files will look
17464 like.
17465 When REFRESH is set, refresh existing images between BEG and END.
17466 This will create new image displays only if necessary.
17467 BEG and END default to the buffer boundaries."
17468 (interactive "P")
17469 (unless refresh
17470 (org-remove-inline-images)
17471 (if (fboundp 'clear-image-cache) (clear-image-cache)))
17472 (save-excursion
17473 (save-restriction
17474 (widen)
17475 (setq beg (or beg (point-min)) end (or end (point-max)))
17476 (goto-char beg)
17477 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
17478 (substring (org-image-file-name-regexp) 0 -2)
17479 "\\)\\]" (if include-linked "" "\\]")))
17480 old file ov img)
17481 (while (re-search-forward re end t)
17482 (setq old (get-char-property-and-overlay (match-beginning 1)
17483 'org-image-overlay))
17484 (setq file (expand-file-name
17485 (concat (or (match-string 3) "") (match-string 4))))
17486 (when (file-exists-p file)
17487 (if (and (car-safe old) refresh)
17488 (image-refresh (overlay-get (cdr old) 'display))
17489 (setq img (save-match-data (create-image file)))
17490 (when img
17491 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
17492 (overlay-put ov 'display img)
17493 (overlay-put ov 'face 'default)
17494 (overlay-put ov 'org-image-overlay t)
17495 (overlay-put ov 'modification-hooks
17496 (list 'org-display-inline-modification-hook))
17497 (push ov org-inline-image-overlays)))))))))
17499 (defun org-display-inline-modification-hook (ov after beg end &optional len)
17500 "Remove inline-display overlay if a corresponding region is modified."
17501 (let ((inhibit-modification-hooks t))
17502 (when (and ov after)
17503 (delete ov org-inline-image-overlays)
17504 (delete-overlay ov))))
17506 (defun org-remove-inline-images ()
17507 "Remove inline display of images."
17508 (interactive)
17509 (mapc 'delete-overlay org-inline-image-overlays)
17510 (setq org-inline-image-overlays nil))
17512 ;;;; Key bindings
17514 ;; Outline functions from `outline-mode-prefix-map'
17515 ;; that can be remapped in Org:
17516 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
17517 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
17518 (define-key org-mode-map [remap outline-forward-same-level]
17519 'org-forward-same-level)
17520 (define-key org-mode-map [remap outline-backward-same-level]
17521 'org-backward-same-level)
17522 (define-key org-mode-map [remap show-branches]
17523 'org-kill-note-or-show-branches)
17524 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
17525 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
17526 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
17528 ;; Outline functions from `outline-mode-prefix-map'
17529 ;; that can not be remapped in Org:
17530 ;; - the column "key binding" shows whether the Outline function is still
17531 ;; available in Org mode on the same key that it has been bound to in
17532 ;; Outline mode:
17533 ;; - "overridden": key used for a different functionality in Org mode
17534 ;; - else: key still bound to the same Outline function in Org mode
17535 ;; | Outline function | key binding | Org replacement |
17536 ;; |------------------------------------+-------------+-----------------------|
17537 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
17538 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
17539 ;; | `show-children' | `C-c C-i' | visibility cycling |
17540 ;; | `hide-subtree' | overridden | visibility cycling |
17541 ;; | `outline-up-heading' | `C-c C-u' | still same function |
17542 ;; | `hide-body' | overridden | no replacement |
17543 ;; | `show-all' | overridden | no replacement |
17544 ;; | `hide-entry' | overridden | visibility cycling |
17545 ;; | `show-entry' | overridden | no replacement |
17546 ;; | `hide-leaves' | overridden | no replacement |
17547 ;; | `hide-sublevels' | overridden | no replacement |
17548 ;; | `hide-other' | overridden | no replacement |
17549 ;; | `outline-move-subtree-up' | `C-c C-^' | better: org-shiftup |
17550 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
17552 ;; Make `C-c C-x' a prefix key
17553 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
17555 ;; TAB key with modifiers
17556 (org-defkey org-mode-map "\C-i" 'org-cycle)
17557 (org-defkey org-mode-map [(tab)] 'org-cycle)
17558 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
17559 (org-defkey org-mode-map "\M-\t" 'pcomplete)
17560 ;; The following line is necessary under Suse GNU/Linux
17561 (unless (featurep 'xemacs)
17562 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
17563 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
17564 (define-key org-mode-map [backtab] 'org-shifttab)
17566 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
17567 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
17568 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
17570 ;; Cursor keys with modifiers
17571 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
17572 (org-defkey org-mode-map [(meta right)] 'org-metaright)
17573 (org-defkey org-mode-map [(meta up)] 'org-metaup)
17574 (org-defkey org-mode-map [(meta down)] 'org-metadown)
17576 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
17577 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
17578 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
17579 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
17581 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
17582 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
17583 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
17584 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
17586 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
17587 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
17588 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
17589 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
17591 ;; Babel keys
17592 (define-key org-mode-map org-babel-key-prefix org-babel-map)
17593 (mapc (lambda (pair)
17594 (define-key org-babel-map (car pair) (cdr pair)))
17595 org-babel-key-bindings)
17597 ;;; Extra keys for tty access.
17598 ;; We only set them when really needed because otherwise the
17599 ;; menus don't show the simple keys
17601 (when (or org-use-extra-keys
17602 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
17603 (not window-system))
17604 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
17605 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
17606 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
17607 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
17608 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
17609 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
17610 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
17611 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
17612 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
17613 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
17614 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
17615 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
17616 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
17617 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
17618 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
17619 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
17620 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
17621 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
17622 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
17623 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
17624 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
17625 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
17626 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
17627 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
17628 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
17629 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
17630 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
17631 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
17633 ;; All the other keys
17635 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
17636 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
17637 (if (boundp 'narrow-map)
17638 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
17639 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
17640 (if (boundp 'narrow-map)
17641 (org-defkey narrow-map "b" 'org-narrow-to-block)
17642 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
17643 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-same-level)
17644 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-same-level)
17645 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
17646 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
17647 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
17648 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
17649 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
17650 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
17651 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
17652 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
17653 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
17654 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
17655 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
17656 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
17657 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
17658 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
17659 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
17660 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
17661 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
17662 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
17663 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
17664 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
17665 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
17666 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
17667 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
17668 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
17669 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
17670 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
17671 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
17672 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
17673 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
17674 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
17675 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
17676 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
17677 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
17678 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
17679 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
17680 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
17681 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
17682 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
17683 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
17684 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
17685 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
17686 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
17687 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
17688 (org-defkey org-mode-map "\C-c^" 'org-sort)
17689 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
17690 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
17691 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
17692 (org-defkey org-mode-map "\C-m" 'org-return)
17693 (org-defkey org-mode-map "\C-j" 'org-return-indent)
17694 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
17695 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
17696 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
17697 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
17698 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
17699 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
17700 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
17701 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
17702 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
17703 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
17704 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
17705 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
17706 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
17707 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
17708 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
17709 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
17710 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
17711 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
17712 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
17713 (org-defkey org-mode-map "\C-c\C-@" 'org-mark-list)
17714 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
17715 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
17717 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
17718 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
17719 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
17720 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
17722 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
17723 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
17724 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
17725 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
17726 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
17727 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
17728 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
17729 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
17730 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
17731 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
17732 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
17733 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
17734 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
17735 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
17736 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
17737 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
17738 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
17739 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
17741 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
17742 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
17743 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
17744 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
17745 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
17747 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
17749 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
17751 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
17752 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
17754 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
17757 (when (featurep 'xemacs)
17758 (org-defkey org-mode-map 'button3 'popup-mode-menu))
17761 (defconst org-speed-commands-default
17763 ("Outline Navigation")
17764 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
17765 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
17766 ("f" . (org-speed-move-safe 'org-forward-same-level))
17767 ("b" . (org-speed-move-safe 'org-backward-same-level))
17768 ("u" . (org-speed-move-safe 'outline-up-heading))
17769 ("j" . org-goto)
17770 ("g" . (org-refile t))
17771 ("Outline Visibility")
17772 ("c" . org-cycle)
17773 ("C" . org-shifttab)
17774 (" " . org-display-outline-path)
17775 ("Outline Structure Editing")
17776 ("U" . org-shiftmetaup)
17777 ("D" . org-shiftmetadown)
17778 ("r" . org-metaright)
17779 ("l" . org-metaleft)
17780 ("R" . org-shiftmetaright)
17781 ("L" . org-shiftmetaleft)
17782 ("i" . (progn (forward-char 1) (call-interactively
17783 'org-insert-heading-respect-content)))
17784 ("^" . org-sort)
17785 ("w" . org-refile)
17786 ("a" . org-archive-subtree-default-with-confirmation)
17787 ("." . org-mark-subtree)
17788 ("Clock Commands")
17789 ("I" . org-clock-in)
17790 ("O" . org-clock-out)
17791 ("Meta Data Editing")
17792 ("t" . org-todo)
17793 ("0" . (org-priority ?\ ))
17794 ("1" . (org-priority ?A))
17795 ("2" . (org-priority ?B))
17796 ("3" . (org-priority ?C))
17797 (";" . org-set-tags-command)
17798 ("e" . org-set-effort)
17799 ("Agenda Views etc")
17800 ("v" . org-agenda)
17801 ("/" . org-sparse-tree)
17802 ("Misc")
17803 ("o" . org-open-at-point)
17804 ("?" . org-speed-command-help)
17805 ("<" . (org-agenda-set-restriction-lock 'subtree))
17806 (">" . (org-agenda-remove-restriction-lock))
17808 "The default speed commands.")
17810 (defun org-print-speed-command (e)
17811 (if (> (length (car e)) 1)
17812 (progn
17813 (princ "\n")
17814 (princ (car e))
17815 (princ "\n")
17816 (princ (make-string (length (car e)) ?-))
17817 (princ "\n"))
17818 (princ (car e))
17819 (princ " ")
17820 (if (symbolp (cdr e))
17821 (princ (symbol-name (cdr e)))
17822 (prin1 (cdr e)))
17823 (princ "\n")))
17825 (defun org-speed-command-help ()
17826 "Show the available speed commands."
17827 (interactive)
17828 (if (not org-use-speed-commands)
17829 (error "Speed commands are not activated, customize `org-use-speed-commands'")
17830 (with-output-to-temp-buffer "*Help*"
17831 (princ "User-defined Speed commands\n===========================\n")
17832 (mapc 'org-print-speed-command org-speed-commands-user)
17833 (princ "\n")
17834 (princ "Built-in Speed commands\n=======================\n")
17835 (mapc 'org-print-speed-command org-speed-commands-default))
17836 (with-current-buffer "*Help*"
17837 (setq truncate-lines t))))
17839 (defun org-speed-move-safe (cmd)
17840 "Execute CMD, but make sure that the cursor always ends up in a headline.
17841 If not, return to the original position and throw an error."
17842 (interactive)
17843 (let ((pos (point)))
17844 (call-interactively cmd)
17845 (unless (and (bolp) (org-at-heading-p))
17846 (goto-char pos)
17847 (error "Boundary reached while executing %s" cmd))))
17849 (defvar org-self-insert-command-undo-counter 0)
17851 (defvar org-table-auto-blank-field) ; defined in org-table.el
17852 (defvar org-speed-command nil)
17854 (defun org-speed-command-default-hook (keys)
17855 "Hook for activating single-letter speed commands.
17856 `org-speed-commands-default' specifies a minimal command set.
17857 Use `org-speed-commands-user' for further customization."
17858 (when (or (and (bolp) (looking-at org-outline-regexp))
17859 (and (functionp org-use-speed-commands)
17860 (funcall org-use-speed-commands)))
17861 (cdr (assoc keys (append org-speed-commands-user
17862 org-speed-commands-default)))))
17864 (defun org-babel-speed-command-hook (keys)
17865 "Hook for activating single-letter code block commands."
17866 (when (and (bolp) (looking-at org-babel-src-block-regexp))
17867 (cdr (assoc keys org-babel-key-bindings))))
17869 (defcustom org-speed-command-hook
17870 '(org-speed-command-default-hook org-babel-speed-command-hook)
17871 "Hook for activating speed commands at strategic locations.
17872 Hook functions are called in sequence until a valid handler is
17873 found.
17875 Each hook takes a single argument, a user-pressed command key
17876 which is also a `self-insert-command' from the global map.
17878 Within the hook, examine the cursor position and the command key
17879 and return nil or a valid handler as appropriate. Handler could
17880 be one of an interactive command, a function, or a form.
17882 Set `org-use-speed-commands' to non-nil value to enable this
17883 hook. The default setting is `org-speed-command-default-hook'."
17884 :group 'org-structure
17885 :version "24.1"
17886 :type 'hook)
17888 (defun org-self-insert-command (N)
17889 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
17890 If the cursor is in a table looking at whitespace, the whitespace is
17891 overwritten, and the table is not marked as requiring realignment."
17892 (interactive "p")
17893 (org-check-before-invisible-edit 'insert)
17894 (cond
17895 ((and org-use-speed-commands
17896 (setq org-speed-command
17897 (run-hook-with-args-until-success
17898 'org-speed-command-hook (this-command-keys))))
17899 (cond
17900 ((commandp org-speed-command)
17901 (setq this-command org-speed-command)
17902 (call-interactively org-speed-command))
17903 ((functionp org-speed-command)
17904 (funcall org-speed-command))
17905 ((and org-speed-command (listp org-speed-command))
17906 (eval org-speed-command))
17907 (t (let (org-use-speed-commands)
17908 (call-interactively 'org-self-insert-command)))))
17909 ((and
17910 (org-table-p)
17911 (progn
17912 ;; check if we blank the field, and if that triggers align
17913 (and (featurep 'org-table) org-table-auto-blank-field
17914 (member last-command
17915 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
17916 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
17917 ;; got extra space, this field does not determine column width
17918 (let (org-table-may-need-update) (org-table-blank-field))
17919 ;; no extra space, this field may determine column width
17920 (org-table-blank-field)))
17922 (eq N 1)
17923 (looking-at "[^|\n]* |"))
17924 (let (org-table-may-need-update)
17925 (goto-char (1- (match-end 0)))
17926 (backward-delete-char 1)
17927 (goto-char (match-beginning 0))
17928 (self-insert-command N)))
17930 (setq org-table-may-need-update t)
17931 (self-insert-command N)
17932 (org-fix-tags-on-the-fly)
17933 (if org-self-insert-cluster-for-undo
17934 (if (not (eq last-command 'org-self-insert-command))
17935 (setq org-self-insert-command-undo-counter 1)
17936 (if (>= org-self-insert-command-undo-counter 20)
17937 (setq org-self-insert-command-undo-counter 1)
17938 (and (> org-self-insert-command-undo-counter 0)
17939 buffer-undo-list (listp buffer-undo-list)
17940 (not (cadr buffer-undo-list)) ; remove nil entry
17941 (setcdr buffer-undo-list (cddr buffer-undo-list)))
17942 (setq org-self-insert-command-undo-counter
17943 (1+ org-self-insert-command-undo-counter))))))))
17945 (defun org-check-before-invisible-edit (kind)
17946 "Check is editing if kind KIND would be dangerous with invisible text around.
17947 The detailed reaction depends on the user option `org-catch-invisible-edits'."
17948 ;; First, try to get out of here as quickly as possible, to reduce overhead
17949 (if (and org-catch-invisible-edits
17950 (or (not (boundp 'visible-mode)) (not visible-mode))
17951 (or (get-char-property (point) 'invisible)
17952 (get-char-property (max (point-min) (1- (point))) 'invisible)))
17953 ;; OK, we need to take a closer look
17954 (let* ((invisible-at-point (get-char-property (point) 'invisible))
17955 (invisible-before-point (if (bobp) nil (get-char-property
17956 (1- (point)) 'invisible)))
17957 (border-and-ok-direction
17959 ;; Check if we are acting predictably before invisible text
17960 (and invisible-at-point (not invisible-before-point)
17961 (memq kind '(insert delete-backward)))
17962 ;; Check if we are acting predictably after invisible text
17963 ;; This works not well, and I have turned it off. It seems
17964 ;; better to always show and stop after invisible text.
17965 ;; (and (not invisible-at-point) invisible-before-point
17966 ;; (memq kind '(insert delete)))
17969 (when (or (memq invisible-at-point '(outline org-hide-block))
17970 (memq invisible-before-point '(outline org-hide-block)))
17971 (if (eq org-catch-invisible-edits 'error)
17972 (error "Editing in invisible areas is prohibited - make visible first"))
17973 ;; Make the area visible
17974 (save-excursion
17975 (if invisible-before-point
17976 (goto-char (previous-single-char-property-change
17977 (point) 'invisible)))
17978 (org-cycle))
17979 (cond
17980 ((eq org-catch-invisible-edits 'show)
17981 ;; That's it, we do the edit after showing
17982 (message
17983 "Unfolding invisible region around point before editing")
17984 (sit-for 1))
17985 ((and (eq org-catch-invisible-edits 'smart)
17986 border-and-ok-direction)
17987 (message "Unfolding invisible region around point before editing"))
17989 ;; Don't do the edit, make the user repeat it in full visibility
17990 (error "Edit in invisible region aborted, repeat to confirm with text visible")))))))
17992 (defun org-fix-tags-on-the-fly ()
17993 (when (and (equal (char-after (point-at-bol)) ?*)
17994 (org-at-heading-p))
17995 (org-align-tags-here org-tags-column)))
17997 (defun org-delete-backward-char (N)
17998 "Like `delete-backward-char', insert whitespace at field end in tables.
17999 When deleting backwards, in tables this function will insert whitespace in
18000 front of the next \"|\" separator, to keep the table aligned. The table will
18001 still be marked for re-alignment if the field did fill the entire column,
18002 because, in this case the deletion might narrow the column."
18003 (interactive "p")
18004 (org-check-before-invisible-edit 'delete-backward)
18005 (if (and (org-table-p)
18006 (eq N 1)
18007 (string-match "|" (buffer-substring (point-at-bol) (point)))
18008 (looking-at ".*?|"))
18009 (let ((pos (point))
18010 (noalign (looking-at "[^|\n\r]* |"))
18011 (c org-table-may-need-update))
18012 (backward-delete-char N)
18013 (if (not overwrite-mode)
18014 (progn
18015 (skip-chars-forward "^|")
18016 (insert " ")
18017 (goto-char (1- pos))))
18018 ;; noalign: if there were two spaces at the end, this field
18019 ;; does not determine the width of the column.
18020 (if noalign (setq org-table-may-need-update c)))
18021 (backward-delete-char N)
18022 (org-fix-tags-on-the-fly)))
18024 (defun org-delete-char (N)
18025 "Like `delete-char', but insert whitespace at field end in tables.
18026 When deleting characters, in tables this function will insert whitespace in
18027 front of the next \"|\" separator, to keep the table aligned. The table will
18028 still be marked for re-alignment if the field did fill the entire column,
18029 because, in this case the deletion might narrow the column."
18030 (interactive "p")
18031 (org-check-before-invisible-edit 'delete)
18032 (if (and (org-table-p)
18033 (not (bolp))
18034 (not (= (char-after) ?|))
18035 (eq N 1))
18036 (if (looking-at ".*?|")
18037 (let ((pos (point))
18038 (noalign (looking-at "[^|\n\r]* |"))
18039 (c org-table-may-need-update))
18040 (replace-match (concat
18041 (substring (match-string 0) 1 -1)
18042 " |"))
18043 (goto-char pos)
18044 ;; noalign: if there were two spaces at the end, this field
18045 ;; does not determine the width of the column.
18046 (if noalign (setq org-table-may-need-update c)))
18047 (delete-char N))
18048 (delete-char N)
18049 (org-fix-tags-on-the-fly)))
18051 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
18052 (put 'org-self-insert-command 'delete-selection t)
18053 (put 'orgtbl-self-insert-command 'delete-selection t)
18054 (put 'org-delete-char 'delete-selection 'supersede)
18055 (put 'org-delete-backward-char 'delete-selection 'supersede)
18056 (put 'org-yank 'delete-selection 'yank)
18058 ;; Make `flyspell-mode' delay after some commands
18059 (put 'org-self-insert-command 'flyspell-delayed t)
18060 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
18061 (put 'org-delete-char 'flyspell-delayed t)
18062 (put 'org-delete-backward-char 'flyspell-delayed t)
18064 ;; Make pabbrev-mode expand after org-mode commands
18065 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
18066 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
18068 ;; How to do this: Measure non-white length of current string
18069 ;; If equal to column width, we should realign.
18071 (defun org-remap (map &rest commands)
18072 "In MAP, remap the functions given in COMMANDS.
18073 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
18074 (let (new old)
18075 (while commands
18076 (setq old (pop commands) new (pop commands))
18077 (if (fboundp 'command-remapping)
18078 (org-defkey map (vector 'remap old) new)
18079 (substitute-key-definition old new map global-map)))))
18081 (when (eq org-enable-table-editor 'optimized)
18082 ;; If the user wants maximum table support, we need to hijack
18083 ;; some standard editing functions
18084 (org-remap org-mode-map
18085 'self-insert-command 'org-self-insert-command
18086 'delete-char 'org-delete-char
18087 'delete-backward-char 'org-delete-backward-char)
18088 (org-defkey org-mode-map "|" 'org-force-self-insert))
18090 (defvar org-ctrl-c-ctrl-c-hook nil
18091 "Hook for functions attaching themselves to `C-c C-c'.
18093 This can be used to add additional functionality to the C-c C-c
18094 key which executes context-dependent commands. This hook is run
18095 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
18096 run after the last test.
18098 Each function will be called with no arguments. The function
18099 must check if the context is appropriate for it to act. If yes,
18100 it should do its thing and then return a non-nil value. If the
18101 context is wrong, just do nothing and return nil.")
18103 (defvar org-ctrl-c-ctrl-c-final-hook nil
18104 "Hook for functions attaching themselves to `C-c C-c'.
18106 This can be used to add additional functionality to the C-c C-c
18107 key which executes context-dependent commands. This hook is run
18108 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
18109 before the first test.
18111 Each function will be called with no arguments. The function
18112 must check if the context is appropriate for it to act. If yes,
18113 it should do its thing and then return a non-nil value. If the
18114 context is wrong, just do nothing and return nil.")
18116 (defvar org-tab-first-hook nil
18117 "Hook for functions to attach themselves to TAB.
18118 See `org-ctrl-c-ctrl-c-hook' for more information.
18119 This hook runs as the first action when TAB is pressed, even before
18120 `org-cycle' messes around with the `outline-regexp' to cater for
18121 inline tasks and plain list item folding.
18122 If any function in this hook returns t, any other actions that
18123 would have been caused by TAB (such as table field motion or visibility
18124 cycling) will not occur.")
18126 (defvar org-tab-after-check-for-table-hook nil
18127 "Hook for functions to attach themselves to TAB.
18128 See `org-ctrl-c-ctrl-c-hook' for more information.
18129 This hook runs after it has been established that the cursor is not in a
18130 table, but before checking if the cursor is in a headline or if global cycling
18131 should be done.
18132 If any function in this hook returns t, not other actions like visibility
18133 cycling will be done.")
18135 (defvar org-tab-after-check-for-cycling-hook nil
18136 "Hook for functions to attach themselves to TAB.
18137 See `org-ctrl-c-ctrl-c-hook' for more information.
18138 This hook runs after it has been established that not table field motion and
18139 not visibility should be done because of current context. This is probably
18140 the place where a package like yasnippets can hook in.")
18142 (defvar org-tab-before-tab-emulation-hook nil
18143 "Hook for functions to attach themselves to TAB.
18144 See `org-ctrl-c-ctrl-c-hook' for more information.
18145 This hook runs after every other options for TAB have been exhausted, but
18146 before indentation and \t insertion takes place.")
18148 (defvar org-metaleft-hook nil
18149 "Hook for functions attaching themselves to `M-left'.
18150 See `org-ctrl-c-ctrl-c-hook' for more information.")
18151 (defvar org-metaright-hook nil
18152 "Hook for functions attaching themselves to `M-right'.
18153 See `org-ctrl-c-ctrl-c-hook' for more information.")
18154 (defvar org-metaup-hook nil
18155 "Hook for functions attaching themselves to `M-up'.
18156 See `org-ctrl-c-ctrl-c-hook' for more information.")
18157 (defvar org-metadown-hook nil
18158 "Hook for functions attaching themselves to `M-down'.
18159 See `org-ctrl-c-ctrl-c-hook' for more information.")
18160 (defvar org-shiftmetaleft-hook nil
18161 "Hook for functions attaching themselves to `M-S-left'.
18162 See `org-ctrl-c-ctrl-c-hook' for more information.")
18163 (defvar org-shiftmetaright-hook nil
18164 "Hook for functions attaching themselves to `M-S-right'.
18165 See `org-ctrl-c-ctrl-c-hook' for more information.")
18166 (defvar org-shiftmetaup-hook nil
18167 "Hook for functions attaching themselves to `M-S-up'.
18168 See `org-ctrl-c-ctrl-c-hook' for more information.")
18169 (defvar org-shiftmetadown-hook nil
18170 "Hook for functions attaching themselves to `M-S-down'.
18171 See `org-ctrl-c-ctrl-c-hook' for more information.")
18172 (defvar org-metareturn-hook nil
18173 "Hook for functions attaching themselves to `M-RET'.
18174 See `org-ctrl-c-ctrl-c-hook' for more information.")
18175 (defvar org-shiftup-hook nil
18176 "Hook for functions attaching themselves to `S-up'.
18177 See `org-ctrl-c-ctrl-c-hook' for more information.")
18178 (defvar org-shiftup-final-hook nil
18179 "Hook for functions attaching themselves to `S-up'.
18180 This one runs after all other options except shift-select have been excluded.
18181 See `org-ctrl-c-ctrl-c-hook' for more information.")
18182 (defvar org-shiftdown-hook nil
18183 "Hook for functions attaching themselves to `S-down'.
18184 See `org-ctrl-c-ctrl-c-hook' for more information.")
18185 (defvar org-shiftdown-final-hook nil
18186 "Hook for functions attaching themselves to `S-down'.
18187 This one runs after all other options except shift-select have been excluded.
18188 See `org-ctrl-c-ctrl-c-hook' for more information.")
18189 (defvar org-shiftleft-hook nil
18190 "Hook for functions attaching themselves to `S-left'.
18191 See `org-ctrl-c-ctrl-c-hook' for more information.")
18192 (defvar org-shiftleft-final-hook nil
18193 "Hook for functions attaching themselves to `S-left'.
18194 This one runs after all other options except shift-select have been excluded.
18195 See `org-ctrl-c-ctrl-c-hook' for more information.")
18196 (defvar org-shiftright-hook nil
18197 "Hook for functions attaching themselves to `S-right'.
18198 See `org-ctrl-c-ctrl-c-hook' for more information.")
18199 (defvar org-shiftright-final-hook nil
18200 "Hook for functions attaching themselves to `S-right'.
18201 This one runs after all other options except shift-select have been excluded.
18202 See `org-ctrl-c-ctrl-c-hook' for more information.")
18204 (defun org-modifier-cursor-error ()
18205 "Throw an error, a modified cursor command was applied in wrong context."
18206 (error "This command is active in special context like tables, headlines or items"))
18208 (defun org-shiftselect-error ()
18209 "Throw an error because Shift-Cursor command was applied in wrong context."
18210 (if (and (boundp 'shift-select-mode) shift-select-mode)
18211 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
18212 (error "This command works only in special context like headlines or timestamps")))
18214 (defun org-call-for-shift-select (cmd)
18215 (let ((this-command-keys-shift-translated t))
18216 (call-interactively cmd)))
18218 (defun org-shifttab (&optional arg)
18219 "Global visibility cycling or move to previous table field.
18220 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
18221 on context.
18222 See the individual commands for more information."
18223 (interactive "P")
18224 (cond
18225 ((org-at-table-p) (call-interactively 'org-table-previous-field))
18226 ((integerp arg)
18227 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
18228 (message "Content view to level: %d" arg)
18229 (org-content (prefix-numeric-value arg2))
18230 (setq org-cycle-global-status 'overview)))
18231 (t (call-interactively 'org-global-cycle))))
18233 (defun org-shiftmetaleft ()
18234 "Promote subtree or delete table column.
18235 Calls `org-promote-subtree', `org-outdent-item-tree', or
18236 `org-table-delete-column', depending on context. See the
18237 individual commands for more information."
18238 (interactive)
18239 (cond
18240 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
18241 ((org-at-table-p) (call-interactively 'org-table-delete-column))
18242 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
18243 ((if (not (org-region-active-p)) (org-at-item-p)
18244 (save-excursion (goto-char (region-beginning))
18245 (org-at-item-p)))
18246 (call-interactively 'org-outdent-item-tree))
18247 (t (org-modifier-cursor-error))))
18249 (defun org-shiftmetaright ()
18250 "Demote subtree or insert table column.
18251 Calls `org-demote-subtree', `org-indent-item-tree', or
18252 `org-table-insert-column', depending on context. See the
18253 individual commands for more information."
18254 (interactive)
18255 (cond
18256 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
18257 ((org-at-table-p) (call-interactively 'org-table-insert-column))
18258 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
18259 ((if (not (org-region-active-p)) (org-at-item-p)
18260 (save-excursion (goto-char (region-beginning))
18261 (org-at-item-p)))
18262 (call-interactively 'org-indent-item-tree))
18263 (t (org-modifier-cursor-error))))
18265 (defun org-shiftmetaup (&optional arg)
18266 "Move subtree up or kill table row.
18267 Calls `org-move-subtree-up' or `org-table-kill-row' or
18268 `org-move-item-up' depending on context. See the individual commands
18269 for more information."
18270 (interactive "P")
18271 (cond
18272 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
18273 ((org-at-table-p) (call-interactively 'org-table-kill-row))
18274 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18275 ((org-at-item-p) (call-interactively 'org-move-item-up))
18276 (t (org-modifier-cursor-error))))
18278 (defun org-shiftmetadown (&optional arg)
18279 "Move subtree down or insert table row.
18280 Calls `org-move-subtree-down' or `org-table-insert-row' or
18281 `org-move-item-down', depending on context. See the individual
18282 commands for more information."
18283 (interactive "P")
18284 (cond
18285 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
18286 ((org-at-table-p) (call-interactively 'org-table-insert-row))
18287 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
18288 ((org-at-item-p) (call-interactively 'org-move-item-down))
18289 (t (org-modifier-cursor-error))))
18291 (defsubst org-hidden-tree-error ()
18292 (error
18293 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
18295 (defun org-metaleft (&optional arg)
18296 "Promote heading or move table column to left.
18297 Calls `org-do-promote' or `org-table-move-column', depending on context.
18298 With no specific context, calls the Emacs default `backward-word'.
18299 See the individual commands for more information."
18300 (interactive "P")
18301 (cond
18302 ((run-hook-with-args-until-success 'org-metaleft-hook))
18303 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
18304 ((org-with-limited-levels
18305 (or (org-at-heading-p)
18306 (and (org-region-active-p)
18307 (save-excursion
18308 (goto-char (region-beginning))
18309 (org-at-heading-p)))))
18310 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18311 (call-interactively 'org-do-promote))
18312 ;; At an inline task.
18313 ((org-at-heading-p)
18314 (call-interactively 'org-inlinetask-promote))
18315 ((or (org-at-item-p)
18316 (and (org-region-active-p)
18317 (save-excursion
18318 (goto-char (region-beginning))
18319 (org-at-item-p))))
18320 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
18321 (call-interactively 'org-outdent-item))
18322 (t (call-interactively 'backward-word))))
18324 (defun org-metaright (&optional arg)
18325 "Demote a subtree, a list item or move table column to right.
18326 In front of a drawer or a block keyword, indent it correctly.
18327 With no specific context, calls the Emacs default `forward-word'.
18328 See the individual commands for more information."
18329 (interactive "P")
18330 (cond
18331 ((run-hook-with-args-until-success 'org-metaright-hook))
18332 ((org-at-table-p) (call-interactively 'org-table-move-column))
18333 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
18334 ((org-at-block-p) (call-interactively 'org-indent-block))
18335 ((org-with-limited-levels
18336 (or (org-at-heading-p)
18337 (and (org-region-active-p)
18338 (save-excursion
18339 (goto-char (region-beginning))
18340 (org-at-heading-p)))))
18341 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18342 (call-interactively 'org-do-demote))
18343 ;; At an inline task.
18344 ((org-at-heading-p)
18345 (call-interactively 'org-inlinetask-demote))
18346 ((or (org-at-item-p)
18347 (and (org-region-active-p)
18348 (save-excursion
18349 (goto-char (region-beginning))
18350 (org-at-item-p))))
18351 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
18352 (call-interactively 'org-indent-item))
18353 (t (call-interactively 'forward-word))))
18355 (defun org-check-for-hidden (what)
18356 "Check if there are hidden headlines/items in the current visual line.
18357 WHAT can be either `headlines' or `items'. If the current line is
18358 an outline or item heading and it has a folded subtree below it,
18359 this function returns t, nil otherwise."
18360 (let ((re (cond
18361 ((eq what 'headlines) org-outline-regexp-bol)
18362 ((eq what 'items) (org-item-beginning-re))
18363 (t (error "This should not happen"))))
18364 beg end)
18365 (save-excursion
18366 (catch 'exit
18367 (unless (org-region-active-p)
18368 (setq beg (point-at-bol))
18369 (beginning-of-line 2)
18370 (while (and (not (eobp)) ;; this is like `next-line'
18371 (get-char-property (1- (point)) 'invisible))
18372 (beginning-of-line 2))
18373 (setq end (point))
18374 (goto-char beg)
18375 (goto-char (point-at-eol))
18376 (setq end (max end (point)))
18377 (while (re-search-forward re end t)
18378 (if (get-char-property (match-beginning 0) 'invisible)
18379 (throw 'exit t))))
18380 nil))))
18382 (defun org-metaup (&optional arg)
18383 "Move subtree up or move table row up.
18384 Calls `org-move-subtree-up' or `org-table-move-row' or
18385 `org-move-item-up', depending on context. See the individual commands
18386 for more information."
18387 (interactive "P")
18388 (cond
18389 ((run-hook-with-args-until-success 'org-metaup-hook))
18390 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
18391 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18392 ((org-at-item-p) (call-interactively 'org-move-item-up))
18393 (t (transpose-lines 1) (beginning-of-line -1))))
18395 (defun org-metadown (&optional arg)
18396 "Move subtree down or move table row down.
18397 Calls `org-move-subtree-down' or `org-table-move-row' or
18398 `org-move-item-down', depending on context. See the individual
18399 commands for more information."
18400 (interactive "P")
18401 (cond
18402 ((run-hook-with-args-until-success 'org-metadown-hook))
18403 ((org-at-table-p) (call-interactively 'org-table-move-row))
18404 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
18405 ((org-at-item-p) (call-interactively 'org-move-item-down))
18406 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
18408 (defun org-shiftup (&optional arg)
18409 "Increase item in timestamp or increase priority of current headline.
18410 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
18411 depending on context. See the individual commands for more information."
18412 (interactive "P")
18413 (cond
18414 ((run-hook-with-args-until-success 'org-shiftup-hook))
18415 ((and org-support-shift-select (org-region-active-p))
18416 (org-call-for-shift-select 'previous-line))
18417 ((org-at-timestamp-p t)
18418 (call-interactively (if org-edit-timestamp-down-means-later
18419 'org-timestamp-down 'org-timestamp-up)))
18420 ((and (not (eq org-support-shift-select 'always))
18421 org-enable-priority-commands
18422 (org-at-heading-p))
18423 (call-interactively 'org-priority-up))
18424 ((and (not org-support-shift-select) (org-at-item-p))
18425 (call-interactively 'org-previous-item))
18426 ((org-clocktable-try-shift 'up arg))
18427 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
18428 (org-support-shift-select
18429 (org-call-for-shift-select 'previous-line))
18430 (t (org-shiftselect-error))))
18432 (defun org-shiftdown (&optional arg)
18433 "Decrease item in timestamp or decrease priority of current headline.
18434 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
18435 depending on context. See the individual commands for more information."
18436 (interactive "P")
18437 (cond
18438 ((run-hook-with-args-until-success 'org-shiftdown-hook))
18439 ((and org-support-shift-select (org-region-active-p))
18440 (org-call-for-shift-select 'next-line))
18441 ((org-at-timestamp-p t)
18442 (call-interactively (if org-edit-timestamp-down-means-later
18443 'org-timestamp-up 'org-timestamp-down)))
18444 ((and (not (eq org-support-shift-select 'always))
18445 org-enable-priority-commands
18446 (org-at-heading-p))
18447 (call-interactively 'org-priority-down))
18448 ((and (not org-support-shift-select) (org-at-item-p))
18449 (call-interactively 'org-next-item))
18450 ((org-clocktable-try-shift 'down arg))
18451 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
18452 (org-support-shift-select
18453 (org-call-for-shift-select 'next-line))
18454 (t (org-shiftselect-error))))
18456 (defun org-shiftright (&optional arg)
18457 "Cycle the thing at point or in the current line, depending on context.
18458 Depending on context, this does one of the following:
18460 - switch a timestamp at point one day into the future
18461 - on a headline, switch to the next TODO keyword.
18462 - on an item, switch entire list to the next bullet type
18463 - on a property line, switch to the next allowed value
18464 - on a clocktable definition line, move time block into the future"
18465 (interactive "P")
18466 (cond
18467 ((run-hook-with-args-until-success 'org-shiftright-hook))
18468 ((and org-support-shift-select (org-region-active-p))
18469 (org-call-for-shift-select 'forward-char))
18470 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
18471 ((and (not (eq org-support-shift-select 'always))
18472 (org-at-heading-p))
18473 (let ((org-inhibit-logging
18474 (not org-treat-S-cursor-todo-selection-as-state-change))
18475 (org-inhibit-blocking
18476 (not org-treat-S-cursor-todo-selection-as-state-change)))
18477 (org-call-with-arg 'org-todo 'right)))
18478 ((or (and org-support-shift-select
18479 (not (eq org-support-shift-select 'always))
18480 (org-at-item-bullet-p))
18481 (and (not org-support-shift-select) (org-at-item-p)))
18482 (org-call-with-arg 'org-cycle-list-bullet nil))
18483 ((and (not (eq org-support-shift-select 'always))
18484 (org-at-property-p))
18485 (call-interactively 'org-property-next-allowed-value))
18486 ((org-clocktable-try-shift 'right arg))
18487 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
18488 (org-support-shift-select
18489 (org-call-for-shift-select 'forward-char))
18490 (t (org-shiftselect-error))))
18492 (defun org-shiftleft (&optional arg)
18493 "Cycle the thing at point or in the current line, depending on context.
18494 Depending on context, this does one of the following:
18496 - switch a timestamp at point one day into the past
18497 - on a headline, switch to the previous TODO keyword.
18498 - on an item, switch entire list to the previous bullet type
18499 - on a property line, switch to the previous allowed value
18500 - on a clocktable definition line, move time block into the past"
18501 (interactive "P")
18502 (cond
18503 ((run-hook-with-args-until-success 'org-shiftleft-hook))
18504 ((and org-support-shift-select (org-region-active-p))
18505 (org-call-for-shift-select 'backward-char))
18506 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
18507 ((and (not (eq org-support-shift-select 'always))
18508 (org-at-heading-p))
18509 (let ((org-inhibit-logging
18510 (not org-treat-S-cursor-todo-selection-as-state-change))
18511 (org-inhibit-blocking
18512 (not org-treat-S-cursor-todo-selection-as-state-change)))
18513 (org-call-with-arg 'org-todo 'left)))
18514 ((or (and org-support-shift-select
18515 (not (eq org-support-shift-select 'always))
18516 (org-at-item-bullet-p))
18517 (and (not org-support-shift-select) (org-at-item-p)))
18518 (org-call-with-arg 'org-cycle-list-bullet 'previous))
18519 ((and (not (eq org-support-shift-select 'always))
18520 (org-at-property-p))
18521 (call-interactively 'org-property-previous-allowed-value))
18522 ((org-clocktable-try-shift 'left arg))
18523 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
18524 (org-support-shift-select
18525 (org-call-for-shift-select 'backward-char))
18526 (t (org-shiftselect-error))))
18528 (defun org-shiftcontrolright ()
18529 "Switch to next TODO set."
18530 (interactive)
18531 (cond
18532 ((and org-support-shift-select (org-region-active-p))
18533 (org-call-for-shift-select 'forward-word))
18534 ((and (not (eq org-support-shift-select 'always))
18535 (org-at-heading-p))
18536 (org-call-with-arg 'org-todo 'nextset))
18537 (org-support-shift-select
18538 (org-call-for-shift-select 'forward-word))
18539 (t (org-shiftselect-error))))
18541 (defun org-shiftcontrolleft ()
18542 "Switch to previous TODO set."
18543 (interactive)
18544 (cond
18545 ((and org-support-shift-select (org-region-active-p))
18546 (org-call-for-shift-select 'backward-word))
18547 ((and (not (eq org-support-shift-select 'always))
18548 (org-at-heading-p))
18549 (org-call-with-arg 'org-todo 'previousset))
18550 (org-support-shift-select
18551 (org-call-for-shift-select 'backward-word))
18552 (t (org-shiftselect-error))))
18554 (defun org-shiftcontrolup ()
18555 "Change timestamps synchronously up in CLOCK log lines."
18556 (interactive)
18557 (cond ((and (not org-support-shift-select)
18558 (org-at-clock-log-p)
18559 (org-at-timestamp-p t))
18560 (org-clock-timestamps-up))
18561 (t (org-shiftselect-error))))
18563 (defun org-shiftcontroldown ()
18564 "Change timestamps synchronously down in CLOCK log lines."
18565 (interactive)
18566 (cond ((and (not org-support-shift-select)
18567 (org-at-clock-log-p)
18568 (org-at-timestamp-p t))
18569 (org-clock-timestamps-down))
18570 (t (org-shiftselect-error))))
18572 (defun org-ctrl-c-ret ()
18573 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
18574 (interactive)
18575 (cond
18576 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
18577 (t (call-interactively 'org-insert-heading))))
18579 (defun org-find-visible ()
18580 (let ((s (point)))
18581 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
18582 (get-char-property s 'invisible)))
18584 (defun org-find-invisible ()
18585 (let ((s (point)))
18586 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
18587 (not (get-char-property s 'invisible))))
18590 (defun org-copy-visible (beg end)
18591 "Copy the visible parts of the region."
18592 (interactive "r")
18593 (let (snippets s)
18594 (save-excursion
18595 (save-restriction
18596 (narrow-to-region beg end)
18597 (setq s (goto-char (point-min)))
18598 (while (not (= (point) (point-max)))
18599 (goto-char (org-find-invisible))
18600 (push (buffer-substring s (point)) snippets)
18601 (setq s (goto-char (org-find-visible))))))
18602 (kill-new (apply 'concat (nreverse snippets)))))
18604 (defun org-copy-special ()
18605 "Copy region in table or copy current subtree.
18606 Calls `org-table-copy' or `org-copy-subtree', depending on context.
18607 See the individual commands for more information."
18608 (interactive)
18609 (call-interactively
18610 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
18612 (defun org-cut-special ()
18613 "Cut region in table or cut current subtree.
18614 Calls `org-table-copy' or `org-cut-subtree', depending on context.
18615 See the individual commands for more information."
18616 (interactive)
18617 (call-interactively
18618 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
18620 (defun org-paste-special (arg)
18621 "Paste rectangular region into table, or past subtree relative to level.
18622 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
18623 See the individual commands for more information."
18624 (interactive "P")
18625 (if (org-at-table-p)
18626 (org-table-paste-rectangle)
18627 (org-paste-subtree arg)))
18629 (defun org-edit-special (&optional arg)
18630 "Call a special editor for the stuff at point.
18631 When at a table, call the formula editor with `org-table-edit-formulas'.
18632 When at the first line of an src example, call `org-edit-src-code'.
18633 When in an #+include line, visit the include file. Otherwise call
18634 `ffap' to visit the file at point."
18635 (interactive)
18636 ;; possibly prep session before editing source
18637 (when arg
18638 (let* ((info (org-babel-get-src-block-info))
18639 (lang (nth 0 info))
18640 (params (nth 2 info))
18641 (session (cdr (assoc :session params))))
18642 (when (and info session) ;; we are in a source-code block with a session
18643 (funcall
18644 (intern (concat "org-babel-prep-session:" lang)) session params))))
18645 (cond ;; proceed with `org-edit-special'
18646 ((save-excursion
18647 (beginning-of-line 1)
18648 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
18649 (find-file (org-trim (match-string 1))))
18650 ((org-edit-src-code))
18651 ((org-edit-fixed-width-region))
18652 ((org-at-table.el-p)
18653 (org-edit-src-code))
18654 ((or (org-at-table-p)
18655 (save-excursion
18656 (beginning-of-line 1)
18657 (let ((case-fold-search )) (looking-at "[ \t]*#\\+tblfm:"))))
18658 (call-interactively 'org-table-edit-formulas))
18659 (t (call-interactively 'ffap))))
18661 (defvar org-table-coordinate-overlays) ; defined in org-table.el
18662 (defun org-ctrl-c-ctrl-c (&optional arg)
18663 "Set tags in headline, or update according to changed information at point.
18665 This command does many different things, depending on context:
18667 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
18668 this is what we do.
18670 - If the cursor is on a statistics cookie, update it.
18672 - If the cursor is in a headline, prompt for tags and insert them
18673 into the current line, aligned to `org-tags-column'. When called
18674 with prefix arg, realign all tags in the current buffer.
18676 - If the cursor is in one of the special #+KEYWORD lines, this
18677 triggers scanning the buffer for these lines and updating the
18678 information.
18680 - If the cursor is inside a table, realign the table. This command
18681 works even if the automatic table editor has been turned off.
18683 - If the cursor is on a #+TBLFM line, re-apply the formulas to
18684 the entire table.
18686 - If the cursor is at a footnote reference or definition, jump to
18687 the corresponding definition or references, respectively.
18689 - If the cursor is a the beginning of a dynamic block, update it.
18691 - If the current buffer is a capture buffer, close note and file it.
18693 - If the cursor is on a <<<target>>>, update radio targets and
18694 corresponding links in this buffer.
18696 - If the cursor is on a numbered item in a plain list, renumber the
18697 ordered list.
18699 - If the cursor is on a checkbox, toggle it.
18701 - If the cursor is on a code block, evaluate it. The variable
18702 `org-confirm-babel-evaluate' can be used to control prompting
18703 before code block evaluation, by default every code block
18704 evaluation requires confirmation. Code block evaluation can be
18705 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
18706 (interactive "P")
18707 (let ((org-enable-table-editor t))
18708 (cond
18709 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
18710 org-occur-highlights
18711 org-latex-fragment-image-overlays)
18712 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
18713 (org-remove-occur-highlights)
18714 (org-remove-latex-fragment-image-overlays)
18715 (message "Temporary highlights/overlays removed from current buffer"))
18716 ((and (local-variable-p 'org-finish-function (current-buffer))
18717 (fboundp org-finish-function))
18718 (funcall org-finish-function))
18719 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
18720 ((org-in-regexp org-ts-regexp-both)
18721 (org-timestamp-change 0 'day))
18722 ((or (looking-at org-property-start-re)
18723 (org-at-property-p))
18724 (call-interactively 'org-property-action))
18725 ((org-at-target-p) (call-interactively 'org-update-radio-target-regexp))
18726 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
18727 (or (org-at-heading-p) (org-at-item-p)))
18728 (call-interactively 'org-update-statistics-cookies))
18729 ((org-at-heading-p) (call-interactively 'org-set-tags))
18730 ((org-at-table.el-p)
18731 (message "Use C-c ' to edit table.el tables"))
18732 ((org-at-table-p)
18733 (org-table-maybe-eval-formula)
18734 (if arg
18735 (call-interactively 'org-table-recalculate)
18736 (org-table-maybe-recalculate-line))
18737 (call-interactively 'org-table-align)
18738 (orgtbl-send-table 'maybe))
18739 ((or (org-footnote-at-reference-p)
18740 (org-footnote-at-definition-p))
18741 (call-interactively 'org-footnote-action))
18742 ((org-at-item-checkbox-p)
18743 ;; Cursor at a checkbox: repair list and update checkboxes. Send
18744 ;; list only if at top item.
18745 (let* ((cbox (match-string 1))
18746 (struct (org-list-struct))
18747 (old-struct (copy-tree struct))
18748 (parents (org-list-parents-alist struct))
18749 (orderedp (org-entry-get nil "ORDERED"))
18750 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
18751 block-item)
18752 ;; Use a light version of `org-toggle-checkbox' to avoid
18753 ;; computing list structure twice.
18754 (let ((new-box (cond
18755 ((equal arg '(16)) "[-]")
18756 ((equal arg '(4)) nil)
18757 ((equal "[X]" cbox) "[ ]")
18758 (t "[X]"))))
18759 (if (and firstp arg)
18760 ;; If at first item of sub-list, remove check-box from
18761 ;; every item at the same level.
18762 (mapc
18763 (lambda (pos) (org-list-set-checkbox pos struct new-box))
18764 (org-list-get-all-items
18765 (point-at-bol) struct (org-list-prevs-alist struct)))
18766 (org-list-set-checkbox (point-at-bol) struct new-box)))
18767 ;; Replicate `org-list-write-struct', while grabbing a return
18768 ;; value from `org-list-struct-fix-box'.
18769 (org-list-struct-fix-ind struct parents 2)
18770 (org-list-struct-fix-item-end struct)
18771 (let ((prevs (org-list-prevs-alist struct)))
18772 (org-list-struct-fix-bul struct prevs)
18773 (org-list-struct-fix-ind struct parents)
18774 (setq block-item
18775 (org-list-struct-fix-box struct parents prevs orderedp)))
18776 (org-list-struct-apply-struct struct old-struct)
18777 (org-update-checkbox-count-maybe)
18778 (when block-item
18779 (message
18780 "Checkboxes were removed due to unchecked box at line %d"
18781 (org-current-line block-item)))
18782 (when firstp (org-list-send-list 'maybe))))
18783 ((org-at-item-p)
18784 ;; Cursor at an item: repair list. Do checkbox related actions
18785 ;; only if function was called with an argument. Send list only
18786 ;; if at top item.
18787 (let* ((struct (org-list-struct))
18788 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
18789 old-struct)
18790 (when arg
18791 (setq old-struct (copy-tree struct))
18792 (if firstp
18793 ;; If at first item of sub-list, add check-box to every
18794 ;; item at the same level.
18795 (mapc
18796 (lambda (pos)
18797 (unless (org-list-get-checkbox pos struct)
18798 (org-list-set-checkbox pos struct "[ ]")))
18799 (org-list-get-all-items
18800 (point-at-bol) struct (org-list-prevs-alist struct)))
18801 (org-list-set-checkbox (point-at-bol) struct "[ ]")))
18802 (org-list-write-struct
18803 struct (org-list-parents-alist struct) old-struct)
18804 (when arg (org-update-checkbox-count-maybe))
18805 (when firstp (org-list-send-list 'maybe))))
18806 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
18807 ;; Dynamic block
18808 (beginning-of-line 1)
18809 (save-excursion (org-update-dblock)))
18810 ((save-excursion
18811 (let ((case-fold-search t))
18812 (beginning-of-line 1)
18813 (looking-at "[ \t]*#\\+\\([a-z]+\\)")))
18814 (cond
18815 ((or (equal (match-string 1) "TBLFM")
18816 (equal (match-string 1) "tblfm"))
18817 ;; Recalculate the table before this line
18818 (save-excursion
18819 (beginning-of-line 1)
18820 (skip-chars-backward " \r\n\t")
18821 (if (org-at-table-p)
18822 (org-call-with-arg 'org-table-recalculate (or arg t)))))
18824 (let ((org-inhibit-startup-visibility-stuff t)
18825 (org-startup-align-all-tables nil))
18826 (when (boundp 'org-table-coordinate-overlays)
18827 (mapc 'delete-overlay org-table-coordinate-overlays)
18828 (setq org-table-coordinate-overlays nil))
18829 (org-save-outline-visibility 'use-markers (org-mode-restart)))
18830 (message "Local setup has been refreshed"))))
18831 ((org-clock-update-time-maybe))
18833 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
18834 (error "C-c C-c can do nothing useful at this location"))))))
18836 (defun org-mode-restart ()
18837 "Restart Org-mode, to scan again for special lines.
18838 Also updates the keyword regular expressions."
18839 (interactive)
18840 (org-mode)
18841 (message "Org-mode restarted"))
18843 (defun org-kill-note-or-show-branches ()
18844 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
18845 (interactive)
18846 (if (not org-finish-function)
18847 (progn
18848 (hide-subtree)
18849 (call-interactively 'show-branches))
18850 (let ((org-note-abort t))
18851 (funcall org-finish-function))))
18853 (defun org-return (&optional indent)
18854 "Goto next table row or insert a newline.
18855 Calls `org-table-next-row' or `newline', depending on context.
18856 See the individual commands for more information."
18857 (interactive)
18858 (cond
18859 ((or (bobp) (org-in-src-block-p))
18860 (if indent (newline-and-indent) (newline)))
18861 ((org-at-table-p)
18862 (org-table-justify-field-maybe)
18863 (call-interactively 'org-table-next-row))
18864 ;; when `newline-and-indent' is called within a list, make sure
18865 ;; text moved stays inside the item.
18866 ((and (org-in-item-p) indent)
18867 (if (and (org-at-item-p) (>= (point) (match-end 0)))
18868 (progn
18869 (save-match-data (newline))
18870 (org-indent-line-to (length (match-string 0))))
18871 (let ((ind (org-get-indentation)))
18872 (newline)
18873 (if (org-looking-back org-list-end-re)
18874 (org-indent-line-function)
18875 (org-indent-line-to ind)))))
18876 ((and org-return-follows-link
18877 (let ((tprop (get-text-property (point) 'face)))
18878 (or (eq tprop 'org-link)
18879 (and (listp tprop) (memq 'org-link tprop)))))
18880 (call-interactively 'org-open-at-point))
18881 ((and (org-at-heading-p)
18882 (looking-at
18883 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
18884 (org-show-entry)
18885 (end-of-line 1)
18886 (newline))
18887 (t (if indent (newline-and-indent) (newline)))))
18889 (defun org-return-indent ()
18890 "Goto next table row or insert a newline and indent.
18891 Calls `org-table-next-row' or `newline-and-indent', depending on
18892 context. See the individual commands for more information."
18893 (interactive)
18894 (org-return t))
18896 (defun org-ctrl-c-star ()
18897 "Compute table, or change heading status of lines.
18898 Calls `org-table-recalculate' or `org-toggle-heading',
18899 depending on context."
18900 (interactive)
18901 (cond
18902 ((org-at-table-p)
18903 (call-interactively 'org-table-recalculate))
18905 ;; Convert all lines in region to list items
18906 (call-interactively 'org-toggle-heading))))
18908 (defun org-ctrl-c-minus ()
18909 "Insert separator line in table or modify bullet status of line.
18910 Also turns a plain line or a region of lines into list items.
18911 Calls `org-table-insert-hline', `org-toggle-item', or
18912 `org-cycle-list-bullet', depending on context."
18913 (interactive)
18914 (cond
18915 ((org-at-table-p)
18916 (call-interactively 'org-table-insert-hline))
18917 ((org-region-active-p)
18918 (call-interactively 'org-toggle-item))
18919 ((org-in-item-p)
18920 (call-interactively 'org-cycle-list-bullet))
18922 (call-interactively 'org-toggle-item))))
18924 (defun org-toggle-item (arg)
18925 "Convert headings or normal lines to items, items to normal lines.
18926 If there is no active region, only the current line is considered.
18928 If the first non blank line in the region is an headline, convert
18929 all headlines to items, shifting text accordingly.
18931 If it is an item, convert all items to normal lines.
18933 If it is normal text, change region into an item. With a prefix
18934 argument ARG, change each line in region into an item."
18935 (interactive "P")
18936 (let ((shift-text
18937 (function
18938 ;; Shift text in current section to IND, from point to END.
18939 ;; The function leaves point to END line.
18940 (lambda (ind end)
18941 (let ((min-i 1000) (end (copy-marker end)))
18942 ;; First determine the minimum indentation (MIN-I) of
18943 ;; the text.
18944 (save-excursion
18945 (catch 'exit
18946 (while (< (point) end)
18947 (let ((i (org-get-indentation)))
18948 (cond
18949 ;; Skip blank lines and inline tasks.
18950 ((looking-at "^[ \t]*$"))
18951 ((looking-at org-outline-regexp-bol))
18952 ;; We can't find less than 0 indentation.
18953 ((zerop i) (throw 'exit (setq min-i 0)))
18954 ((< i min-i) (setq min-i i))))
18955 (forward-line))))
18956 ;; Then indent each line so that a line indented to
18957 ;; MIN-I becomes indented to IND. Ignore blank lines
18958 ;; and inline tasks in the process.
18959 (let ((delta (- ind min-i)))
18960 (while (< (point) end)
18961 (unless (or (looking-at "^[ \t]*$")
18962 (looking-at org-outline-regexp-bol))
18963 (org-indent-line-to (+ (org-get-indentation) delta)))
18964 (forward-line)))))))
18965 (skip-blanks
18966 (function
18967 ;; Return beginning of first non-blank line, starting from
18968 ;; line at POS.
18969 (lambda (pos)
18970 (save-excursion
18971 (goto-char pos)
18972 (skip-chars-forward " \r\t\n")
18973 (point-at-bol)))))
18974 beg end)
18975 ;; Determine boundaries of changes.
18976 (if (org-region-active-p)
18977 (setq beg (funcall skip-blanks (region-beginning))
18978 end (copy-marker (region-end)))
18979 (setq beg (funcall skip-blanks (point-at-bol))
18980 end (copy-marker (point-at-eol))))
18981 ;; Depending on the starting line, choose an action on the text
18982 ;; between BEG and END.
18983 (org-with-limited-levels
18984 (save-excursion
18985 (goto-char beg)
18986 (cond
18987 ;; Case 1. Start at an item: de-itemize. Note that it only
18988 ;; happens when a region is active: `org-ctrl-c-minus'
18989 ;; would call `org-cycle-list-bullet' otherwise.
18990 ((org-at-item-p)
18991 (while (< (point) end)
18992 (when (org-at-item-p)
18993 (skip-chars-forward " \t")
18994 (delete-region (point) (match-end 0)))
18995 (forward-line)))
18996 ;; Case 2. Start at an heading: convert to items.
18997 ((org-at-heading-p)
18998 (let* ((bul (org-list-bullet-string "-"))
18999 (bul-len (length bul))
19000 ;; Indentation of the first heading. It should be
19001 ;; relative to the indentation of its parent, if any.
19002 (start-ind (save-excursion
19003 (cond
19004 ((not org-adapt-indentation) 0)
19005 ((not (outline-previous-heading)) 0)
19006 (t (length (match-string 0))))))
19007 ;; Level of first heading. Further headings will be
19008 ;; compared to it to determine hierarchy in the list.
19009 (ref-level (org-reduced-level (org-outline-level))))
19010 (while (< (point) end)
19011 (let* ((level (org-reduced-level (org-outline-level)))
19012 (delta (max 0 (- level ref-level))))
19013 ;; If current headline is less indented than the first
19014 ;; one, set it as reference, in order to preserve
19015 ;; subtrees.
19016 (when (< level ref-level) (setq ref-level level))
19017 (replace-match bul t t)
19018 (org-indent-line-to (+ start-ind (* delta bul-len)))
19019 ;; Ensure all text down to END (or SECTION-END) belongs
19020 ;; to the newly created item.
19021 (let ((section-end (save-excursion
19022 (or (outline-next-heading) (point)))))
19023 (forward-line)
19024 (funcall shift-text
19025 (+ start-ind (* (1+ delta) bul-len))
19026 (min end section-end)))))))
19027 ;; Case 3. Normal line with ARG: turn each non-item line into
19028 ;; an item.
19029 (arg
19030 (while (< (point) end)
19031 (unless (or (org-at-heading-p) (org-at-item-p))
19032 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
19033 (replace-match
19034 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
19035 (forward-line)))
19036 ;; Case 4. Normal line without ARG: make the first line of
19037 ;; region an item, and shift indentation of others
19038 ;; lines to set them as item's body.
19039 (t (let* ((bul (org-list-bullet-string "-"))
19040 (bul-len (length bul))
19041 (ref-ind (org-get-indentation)))
19042 (skip-chars-forward " \t")
19043 (insert bul)
19044 (forward-line)
19045 (while (< (point) end)
19046 ;; Ensure that lines less indented than first one
19047 ;; still get included in item body.
19048 (funcall shift-text
19049 (+ ref-ind bul-len)
19050 (min end (save-excursion (or (outline-next-heading)
19051 (point)))))
19052 (forward-line)))))))))
19054 (defun org-toggle-heading (&optional nstars)
19055 "Convert headings to normal text, or items or text to headings.
19056 If there is no active region, only the current line is considered.
19058 If the first non blank line is an headline, remove the stars from
19059 all headlines in the region.
19061 If it is a plain list item, turn all plain list items into headings.
19063 If it is a normal line, turn each and every normal line (i.e. not
19064 an heading or an item) in the region into a heading.
19066 When converting a line into a heading, the number of stars is chosen
19067 such that the lines become children of the current entry. However,
19068 when a prefix argument is given, its value determines the number of
19069 stars to add."
19070 (interactive "P")
19071 (let ((skip-blanks
19072 (function
19073 ;; Return beginning of first non-blank line, starting from
19074 ;; line at POS.
19075 (lambda (pos)
19076 (save-excursion
19077 (goto-char pos)
19078 (skip-chars-forward " \r\t\n")
19079 (point-at-bol)))))
19080 beg end)
19081 ;; Determine boundaries of changes. If region ends at a bol, do
19082 ;; not consider the last line to be in the region.
19083 (if (org-region-active-p)
19084 (setq beg (funcall skip-blanks (region-beginning))
19085 end (copy-marker (save-excursion
19086 (goto-char (region-end))
19087 (if (bolp) (point) (point-at-eol)))))
19088 (setq beg (funcall skip-blanks (point-at-bol))
19089 end (copy-marker (point-at-eol))))
19090 ;; Ensure inline tasks don't count as headings.
19091 (org-with-limited-levels
19092 (save-excursion
19093 (goto-char beg)
19094 (cond
19095 ;; Case 1. Started at an heading: de-star headings.
19096 ((org-at-heading-p)
19097 (while (< (point) end)
19098 (when (org-at-heading-p t)
19099 (looking-at org-outline-regexp) (replace-match ""))
19100 (forward-line)))
19101 ;; Case 2. Started at an item: change items into headlines.
19102 ;; One star will be added by `org-list-to-subtree'.
19103 ((org-at-item-p)
19104 (let* ((stars (make-string
19105 (if nstars
19106 ;; subtract the star that will be added again by
19107 ;; `org-list-to-subtree'
19108 (1- (prefix-numeric-value current-prefix-arg))
19109 (or (org-current-level) 0))
19110 ?*))
19111 (add-stars
19112 (cond (nstars "") ; stars from prefix only
19113 ((equal stars "") "") ; before first heading
19114 (org-odd-levels-only "*") ; inside heading, odd
19115 (t "")))) ; inside heading, oddeven
19116 (while (< (point) end)
19117 (when (org-at-item-p)
19118 ;; Pay attention to cases when region ends before list.
19119 (let* ((struct (org-list-struct))
19120 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
19121 (save-restriction
19122 (narrow-to-region (point) list-end)
19123 (insert
19124 (org-list-to-subtree
19125 (org-list-parse-list t)
19126 '(:istart (concat stars add-stars (funcall get-stars depth))
19127 :icount (concat stars add-stars (funcall get-stars depth))))))))
19128 (forward-line))))
19129 ;; Case 3. Started at normal text: make every line an heading,
19130 ;; skipping headlines and items.
19131 (t (let* ((stars (make-string
19132 (if nstars
19133 (prefix-numeric-value current-prefix-arg)
19134 (or (org-current-level) 0))
19135 ?*))
19136 (add-stars
19137 (cond (nstars "") ; stars from prefix only
19138 ((equal stars "") "*") ; before first heading
19139 (org-odd-levels-only "**") ; inside heading, odd
19140 (t "*"))) ; inside heading, oddeven
19141 (rpl (concat stars add-stars " ")))
19142 (while (< (point) end)
19143 (when (and (not (org-at-heading-p)) (not (org-at-item-p))
19144 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
19145 (replace-match (concat rpl (match-string 2))))
19146 (forward-line)))))))))
19148 (defun org-meta-return (&optional arg)
19149 "Insert a new heading or wrap a region in a table.
19150 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
19151 See the individual commands for more information."
19152 (interactive "P")
19153 (cond
19154 ((run-hook-with-args-until-success 'org-metareturn-hook))
19155 ((or (org-at-drawer-p) (org-at-property-p))
19156 (newline-and-indent))
19157 ((org-at-table-p)
19158 (call-interactively 'org-table-wrap-region))
19159 (t (call-interactively 'org-insert-heading))))
19161 ;;; Menu entries
19163 ;; Define the Org-mode menus
19164 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
19165 '("Tbl"
19166 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
19167 ["Next Field" org-cycle (org-at-table-p)]
19168 ["Previous Field" org-shifttab (org-at-table-p)]
19169 ["Next Row" org-return (org-at-table-p)]
19170 "--"
19171 ["Blank Field" org-table-blank-field (org-at-table-p)]
19172 ["Edit Field" org-table-edit-field (org-at-table-p)]
19173 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
19174 "--"
19175 ("Column"
19176 ["Move Column Left" org-metaleft (org-at-table-p)]
19177 ["Move Column Right" org-metaright (org-at-table-p)]
19178 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
19179 ["Insert Column" org-shiftmetaright (org-at-table-p)])
19180 ("Row"
19181 ["Move Row Up" org-metaup (org-at-table-p)]
19182 ["Move Row Down" org-metadown (org-at-table-p)]
19183 ["Delete Row" org-shiftmetaup (org-at-table-p)]
19184 ["Insert Row" org-shiftmetadown (org-at-table-p)]
19185 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
19186 "--"
19187 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
19188 ("Rectangle"
19189 ["Copy Rectangle" org-copy-special (org-at-table-p)]
19190 ["Cut Rectangle" org-cut-special (org-at-table-p)]
19191 ["Paste Rectangle" org-paste-special (org-at-table-p)]
19192 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
19193 "--"
19194 ("Calculate"
19195 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
19196 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
19197 ["Edit Formulas" org-edit-special (org-at-table-p)]
19198 "--"
19199 ["Recalculate line" org-table-recalculate (org-at-table-p)]
19200 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
19201 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
19202 "--"
19203 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
19204 "--"
19205 ["Sum Column/Rectangle" org-table-sum
19206 (or (org-at-table-p) (org-region-active-p))]
19207 ["Which Column?" org-table-current-column (org-at-table-p)])
19208 ["Debug Formulas"
19209 org-table-toggle-formula-debugger
19210 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
19211 ["Show Col/Row Numbers"
19212 org-table-toggle-coordinate-overlays
19213 :style toggle
19214 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
19215 "--"
19216 ["Create" org-table-create (and (not (org-at-table-p))
19217 org-enable-table-editor)]
19218 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
19219 ["Import from File" org-table-import (not (org-at-table-p))]
19220 ["Export to File" org-table-export (org-at-table-p)]
19221 "--"
19222 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
19224 (easy-menu-define org-org-menu org-mode-map "Org menu"
19225 '("Org"
19226 ("Show/Hide"
19227 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
19228 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
19229 ["Sparse Tree..." org-sparse-tree t]
19230 ["Reveal Context" org-reveal t]
19231 ["Show All" show-all t]
19232 "--"
19233 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
19234 "--"
19235 ["New Heading" org-insert-heading t]
19236 ("Navigate Headings"
19237 ["Up" outline-up-heading t]
19238 ["Next" outline-next-visible-heading t]
19239 ["Previous" outline-previous-visible-heading t]
19240 ["Next Same Level" outline-forward-same-level t]
19241 ["Previous Same Level" outline-backward-same-level t]
19242 "--"
19243 ["Jump" org-goto t])
19244 ("Edit Structure"
19245 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
19246 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
19247 "--"
19248 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
19249 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
19250 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
19251 "--"
19252 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
19253 "--"
19254 ["Copy visible text" org-copy-visible t]
19255 "--"
19256 ["Promote Heading" org-metaleft (not (org-at-table-p))]
19257 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
19258 ["Demote Heading" org-metaright (not (org-at-table-p))]
19259 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
19260 "--"
19261 ["Sort Region/Children" org-sort (not (org-at-table-p))]
19262 "--"
19263 ["Convert to odd levels" org-convert-to-odd-levels t]
19264 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
19265 ("Editing"
19266 ["Emphasis..." org-emphasize t]
19267 ["Edit Source Example" org-edit-special t]
19268 "--"
19269 ["Footnote new/jump" org-footnote-action t]
19270 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
19271 ("Archive"
19272 ["Archive (default method)" org-archive-subtree-default t]
19273 "--"
19274 ["Move Subtree to Archive file" org-advertized-archive-subtree t]
19275 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
19276 ["Move subtree to Archive sibling" org-archive-to-archive-sibling t]
19278 "--"
19279 ("Hyperlinks"
19280 ["Store Link (Global)" org-store-link t]
19281 ["Find existing link to here" org-occur-link-in-agenda-files t]
19282 ["Insert Link" org-insert-link t]
19283 ["Follow Link" org-open-at-point t]
19284 "--"
19285 ["Next link" org-next-link t]
19286 ["Previous link" org-previous-link t]
19287 "--"
19288 ["Descriptive Links"
19289 org-toggle-link-display
19290 :style radio
19291 :selected org-descriptive-links
19293 ["Literal Links"
19294 org-toggle-link-display
19295 :style radio
19296 :selected (not org-descriptive-links)])
19297 "--"
19298 ("TODO Lists"
19299 ["TODO/DONE/-" org-todo t]
19300 ("Select keyword"
19301 ["Next keyword" org-shiftright (org-at-heading-p)]
19302 ["Previous keyword" org-shiftleft (org-at-heading-p)]
19303 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
19304 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
19305 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
19306 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
19307 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
19308 "--"
19309 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
19310 :selected org-enforce-todo-dependencies :style toggle :active t]
19311 "Settings for tree at point"
19312 ["Do Children sequentially" org-toggle-ordered-property :style radio
19313 :selected (org-entry-get nil "ORDERED")
19314 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
19315 ["Do Children parallel" org-toggle-ordered-property :style radio
19316 :selected (not (org-entry-get nil "ORDERED"))
19317 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
19318 "--"
19319 ["Set Priority" org-priority t]
19320 ["Priority Up" org-shiftup t]
19321 ["Priority Down" org-shiftdown t]
19322 "--"
19323 ["Get news from all feeds" org-feed-update-all t]
19324 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
19325 ["Customize feeds" (customize-variable 'org-feed-alist) t])
19326 ("TAGS and Properties"
19327 ["Set Tags" org-set-tags-command t]
19328 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
19329 "--"
19330 ["Set property" org-set-property t]
19331 ["Column view of properties" org-columns t]
19332 ["Insert Column View DBlock" org-insert-columns-dblock t])
19333 ("Dates and Scheduling"
19334 ["Timestamp" org-time-stamp t]
19335 ["Timestamp (inactive)" org-time-stamp-inactive t]
19336 ("Change Date"
19337 ["1 Day Later" org-shiftright t]
19338 ["1 Day Earlier" org-shiftleft t]
19339 ["1 ... Later" org-shiftup t]
19340 ["1 ... Earlier" org-shiftdown t])
19341 ["Compute Time Range" org-evaluate-time-range t]
19342 ["Schedule Item" org-schedule t]
19343 ["Deadline" org-deadline t]
19344 "--"
19345 ["Custom time format" org-toggle-time-stamp-overlays
19346 :style radio :selected org-display-custom-times]
19347 "--"
19348 ["Goto Calendar" org-goto-calendar t]
19349 ["Date from Calendar" org-date-from-calendar t]
19350 "--"
19351 ["Start/Restart Timer" org-timer-start t]
19352 ["Pause/Continue Timer" org-timer-pause-or-continue t]
19353 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
19354 ["Insert Timer String" org-timer t]
19355 ["Insert Timer Item" org-timer-item t])
19356 ("Logging work"
19357 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
19358 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
19359 ["Clock out" org-clock-out t]
19360 ["Clock cancel" org-clock-cancel t]
19361 "--"
19362 ["Mark as default task" org-clock-mark-default-task t]
19363 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
19364 ["Goto running clock" org-clock-goto t]
19365 "--"
19366 ["Display times" org-clock-display t]
19367 ["Create clock table" org-clock-report t]
19368 "--"
19369 ["Record DONE time"
19370 (progn (setq org-log-done (not org-log-done))
19371 (message "Switching to %s will %s record a timestamp"
19372 (car org-done-keywords)
19373 (if org-log-done "automatically" "not")))
19374 :style toggle :selected org-log-done])
19375 "--"
19376 ["Agenda Command..." org-agenda t]
19377 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
19378 ("File List for Agenda")
19379 ("Special views current file"
19380 ["TODO Tree" org-show-todo-tree t]
19381 ["Check Deadlines" org-check-deadlines t]
19382 ["Timeline" org-timeline t]
19383 ["Tags/Property tree" org-match-sparse-tree t])
19384 "--"
19385 ["Export/Publish..." org-export t]
19386 ("LaTeX"
19387 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
19388 :selected org-cdlatex-mode]
19389 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
19390 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
19391 ["Modify math symbol" org-cdlatex-math-modify
19392 (org-inside-LaTeX-fragment-p)]
19393 ["Insert citation" org-reftex-citation t]
19394 "--"
19395 ["Template for BEAMER" (progn (require 'org-beamer)
19396 (org-insert-beamer-options-template)) t])
19397 "--"
19398 ("MobileOrg"
19399 ["Push Files and Views" org-mobile-push t]
19400 ["Get Captured and Flagged" org-mobile-pull t]
19401 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
19402 "--"
19403 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
19404 "--"
19405 ("Documentation"
19406 ["Show Version" org-version t]
19407 ["Info Documentation" org-info t])
19408 ("Customize"
19409 ["Browse Org Group" org-customize t]
19410 "--"
19411 ["Expand This Menu" org-create-customize-menu
19412 (fboundp 'customize-menu-create)])
19413 ["Send bug report" org-submit-bug-report t]
19414 "--"
19415 ("Refresh/Reload"
19416 ["Refresh setup current buffer" org-mode-restart t]
19417 ["Reload Org (after update)" org-reload t]
19418 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
19421 (defun org-info (&optional node)
19422 "Read documentation for Org-mode in the info system.
19423 With optional NODE, go directly to that node."
19424 (interactive)
19425 (info (format "(org)%s" (or node ""))))
19427 ;;;###autoload
19428 (defun org-submit-bug-report ()
19429 "Submit a bug report on Org-mode via mail.
19431 Don't hesitate to report any problems or inaccurate documentation.
19433 If you don't have setup sending mail from (X)Emacs, please copy the
19434 output buffer into your mail program, as it gives us important
19435 information about your Org-mode version and configuration."
19436 (interactive)
19437 (require 'reporter)
19438 (org-load-modules-maybe)
19439 (org-require-autoloaded-modules)
19440 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
19441 (reporter-submit-bug-report
19442 "emacs-orgmode@gnu.org"
19443 (org-version)
19444 (let (list)
19445 (save-window-excursion
19446 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
19447 (delete-other-windows)
19448 (erase-buffer)
19449 (insert "You are about to submit a bug report to the Org-mode mailing list.
19451 We would like to add your full Org-mode and Outline configuration to the
19452 bug report. This greatly simplifies the work of the maintainer and
19453 other experts on the mailing list.
19455 HOWEVER, some variables you have customized may contain private
19456 information. The names of customers, colleagues, or friends, might
19457 appear in the form of file names, tags, todo states, or search strings.
19458 If you answer yes to the prompt, you might want to check and remove
19459 such private information before sending the email.")
19460 (add-text-properties (point-min) (point-max) '(face org-warning))
19461 (when (yes-or-no-p "Include your Org-mode configuration ")
19462 (mapatoms
19463 (lambda (v)
19464 (and (boundp v)
19465 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
19466 (or (and (symbol-value v)
19467 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
19468 (and
19469 (get v 'custom-type) (get v 'standard-value)
19470 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
19471 (push v list)))))
19472 (kill-buffer (get-buffer "*Warn about privacy*"))
19473 list))
19474 nil nil
19475 "Remember to cover the basics, that is, what you expected to happen and
19476 what in fact did happen. You don't know how to make a good report? See
19478 http://orgmode.org/manual/Feedback.html#Feedback
19480 Your bug report will be posted to the Org-mode mailing list.
19481 ------------------------------------------------------------------------")
19482 (save-excursion
19483 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
19484 (replace-match "\\1Bug: \\3 [\\2]")))))
19487 (defun org-install-agenda-files-menu ()
19488 (let ((bl (buffer-list)))
19489 (save-excursion
19490 (while bl
19491 (set-buffer (pop bl))
19492 (if (derived-mode-p 'org-mode) (setq bl nil)))
19493 (when (derived-mode-p 'org-mode)
19494 (easy-menu-change
19495 '("Org") "File List for Agenda"
19496 (append
19497 (list
19498 ["Edit File List" (org-edit-agenda-file-list) t]
19499 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
19500 ["Remove Current File from List" org-remove-file t]
19501 ["Cycle through agenda files" org-cycle-agenda-files t]
19502 ["Occur in all agenda files" org-occur-in-agenda-files t]
19503 "--")
19504 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
19506 ;;;; Documentation
19508 ;;;###autoload
19509 (defun org-require-autoloaded-modules ()
19510 (interactive)
19511 (mapc 'require
19512 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
19513 org-docbook org-exp org-html org-icalendar
19514 org-id org-latex
19515 org-publish org-remember org-table
19516 org-timer org-xoxo)))
19518 ;;;###autoload
19519 (defun org-reload (&optional uncompiled)
19520 "Reload all org lisp files.
19521 With prefix arg UNCOMPILED, load the uncompiled versions."
19522 (interactive "P")
19523 (require 'find-func)
19524 (let* ((file-re "^\\(org\\|orgtbl\\)\\(\\.el\\|-.*\\.el\\)")
19525 (dir-org (file-name-directory (org-find-library-name "org")))
19526 (dir-org-contrib (ignore-errors
19527 (file-name-directory
19528 (org-find-library-name "org-contribdir"))))
19529 (babel-files
19530 (mapcar (lambda (el) (concat "ob" (when el (format "-%s" el)) ".el"))
19531 (append (list nil "comint" "eval" "exp" "keys"
19532 "lob" "ref" "table" "tangle")
19533 (delq nil
19534 (mapcar
19535 (lambda (lang)
19536 (when (cdr lang) (symbol-name (car lang))))
19537 org-babel-load-languages)))))
19538 (files
19539 (append (directory-files dir-org t file-re)
19540 babel-files
19541 (and dir-org-contrib
19542 (directory-files dir-org-contrib t file-re))))
19543 (remove-re (concat (if (featurep 'xemacs)
19544 "org-colview" "org-colview-xemacs")
19545 "\\'")))
19546 (setq files (mapcar 'file-name-sans-extension files))
19547 (setq files (mapcar
19548 (lambda (x) (if (string-match remove-re x) nil x))
19549 files))
19550 (setq files (delq nil files))
19551 (mapc
19552 (lambda (f)
19553 (when (featurep (intern (file-name-nondirectory f)))
19554 (if (and (not uncompiled)
19555 (file-exists-p (concat f ".elc")))
19556 (load (concat f ".elc") nil nil t)
19557 (load (concat f ".el") nil nil t))))
19558 files))
19559 (org-version))
19561 ;;;###autoload
19562 (defun org-customize ()
19563 "Call the customize function with org as argument."
19564 (interactive)
19565 (org-load-modules-maybe)
19566 (org-require-autoloaded-modules)
19567 (customize-browse 'org))
19569 (defun org-create-customize-menu ()
19570 "Create a full customization menu for Org-mode, insert it into the menu."
19571 (interactive)
19572 (org-load-modules-maybe)
19573 (org-require-autoloaded-modules)
19574 (if (fboundp 'customize-menu-create)
19575 (progn
19576 (easy-menu-change
19577 '("Org") "Customize"
19578 `(["Browse Org group" org-customize t]
19579 "--"
19580 ,(customize-menu-create 'org)
19581 ["Set" Custom-set t]
19582 ["Save" Custom-save t]
19583 ["Reset to Current" Custom-reset-current t]
19584 ["Reset to Saved" Custom-reset-saved t]
19585 ["Reset to Standard Settings" Custom-reset-standard t]))
19586 (message "\"Org\"-menu now contains full customization menu"))
19587 (error "Cannot expand menu (outdated version of cus-edit.el)")))
19589 ;;;; Miscellaneous stuff
19591 ;;; Generally useful functions
19593 (defun org-get-at-bol (property)
19594 "Get text property PROPERTY at beginning of line."
19595 (get-text-property (point-at-bol) property))
19597 (defun org-find-text-property-in-string (prop s)
19598 "Return the first non-nil value of property PROP in string S."
19599 (or (get-text-property 0 prop s)
19600 (get-text-property (or (next-single-property-change 0 prop s) 0)
19601 prop s)))
19603 (defun org-display-warning (message) ;; Copied from Emacs-Muse
19604 "Display the given MESSAGE as a warning."
19605 (if (fboundp 'display-warning)
19606 (display-warning 'org message
19607 (if (featurep 'xemacs) 'warning :warning))
19608 (let ((buf (get-buffer-create "*Org warnings*")))
19609 (with-current-buffer buf
19610 (goto-char (point-max))
19611 (insert "Warning (Org): " message)
19612 (unless (bolp)
19613 (newline)))
19614 (display-buffer buf)
19615 (sit-for 0))))
19617 (defun org-eval (form)
19618 "Eval FORM and return result."
19619 (condition-case error
19620 (eval form)
19621 (error (format "%%![Error: %s]" error))))
19623 (defun org-in-clocktable-p ()
19624 "Check if the cursor is in a clocktable."
19625 (let ((pos (point)) start)
19626 (save-excursion
19627 (end-of-line 1)
19628 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
19629 (setq start (match-beginning 0))
19630 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
19631 (>= (match-end 0) pos)
19632 start))))
19634 (defun org-in-commented-line ()
19635 "Is point in a line starting with `#'?"
19636 (equal (char-after (point-at-bol)) ?#))
19638 (defun org-in-indented-comment-line ()
19639 "Is point in a line starting with `#' after some white space?"
19640 (save-excursion
19641 (save-match-data
19642 (goto-char (point-at-bol))
19643 (looking-at "[ \t]*#"))))
19645 (defun org-in-verbatim-emphasis ()
19646 (save-match-data
19647 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
19649 (defun org-goto-marker-or-bmk (marker &optional bookmark)
19650 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
19651 (if (and marker (marker-buffer marker)
19652 (buffer-live-p (marker-buffer marker)))
19653 (progn
19654 (org-pop-to-buffer-same-window (marker-buffer marker))
19655 (if (or (> marker (point-max)) (< marker (point-min)))
19656 (widen))
19657 (goto-char marker)
19658 (org-show-context 'org-goto))
19659 (if bookmark
19660 (bookmark-jump bookmark)
19661 (error "Cannot find location"))))
19663 (defun org-quote-csv-field (s)
19664 "Quote field for inclusion in CSV material."
19665 (if (string-match "[\",]" s)
19666 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
19669 (defun org-force-self-insert (N)
19670 "Needed to enforce self-insert under remapping."
19671 (interactive "p")
19672 (self-insert-command N))
19674 (defun org-string-width (s)
19675 "Compute width of string, ignoring invisible characters.
19676 This ignores character with invisibility property `org-link', and also
19677 characters with property `org-cwidth', because these will become invisible
19678 upon the next fontification round."
19679 (let (b l)
19680 (when (or (eq t buffer-invisibility-spec)
19681 (assq 'org-link buffer-invisibility-spec))
19682 (while (setq b (text-property-any 0 (length s)
19683 'invisible 'org-link s))
19684 (setq s (concat (substring s 0 b)
19685 (substring s (or (next-single-property-change
19686 b 'invisible s) (length s)))))))
19687 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
19688 (setq s (concat (substring s 0 b)
19689 (substring s (or (next-single-property-change
19690 b 'org-cwidth s) (length s))))))
19691 (setq l (string-width s) b -1)
19692 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
19693 (setq l (- l (get-text-property b 'org-dwidth-n s))))
19696 (defun org-shorten-string (s maxlength)
19697 "Shorten string S so tht it is no longer than MAXLENGTH characters.
19698 If the string is shorter or has length MAXLENGTH, just return the
19699 original string. If it is longer, the functions finds a space in the
19700 string, breaks this string off at that locations and adds three dots
19701 as ellipsis. Including the ellipsis, the string will not be longer
19702 than MAXLENGTH. If finding a good breaking point in the string does
19703 not work, the string is just chopped off in the middle of a word
19704 if necessary."
19705 (if (<= (length s) maxlength)
19707 (let* ((n (max (- maxlength 4) 1))
19708 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
19709 (if (string-match re s)
19710 (concat (match-string 1 s) "...")
19711 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
19713 (defun org-get-indentation (&optional line)
19714 "Get the indentation of the current line, interpreting tabs.
19715 When LINE is given, assume it represents a line and compute its indentation."
19716 (if line
19717 (if (string-match "^ *" (org-remove-tabs line))
19718 (match-end 0))
19719 (save-excursion
19720 (beginning-of-line 1)
19721 (skip-chars-forward " \t")
19722 (current-column))))
19724 (defun org-get-string-indentation (s)
19725 "What indentation has S due to SPACE and TAB at the beginning of the string?"
19726 (let ((n -1) (i 0) (w tab-width) c)
19727 (catch 'exit
19728 (while (< (setq n (1+ n)) (length s))
19729 (setq c (aref s n))
19730 (cond ((= c ?\ ) (setq i (1+ i)))
19731 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
19732 (t (throw 'exit t)))))
19735 (defun org-remove-tabs (s &optional width)
19736 "Replace tabulators in S with spaces.
19737 Assumes that s is a single line, starting in column 0."
19738 (setq width (or width tab-width))
19739 (while (string-match "\t" s)
19740 (setq s (replace-match
19741 (make-string
19742 (- (* width (/ (+ (match-beginning 0) width) width))
19743 (match-beginning 0)) ?\ )
19744 t t s)))
19747 (defun org-fix-indentation (line ind)
19748 "Fix indentation in LINE.
19749 IND is a cons cell with target and minimum indentation.
19750 If the current indentation in LINE is smaller than the minimum,
19751 leave it alone. If it is larger than ind, set it to the target."
19752 (let* ((l (org-remove-tabs line))
19753 (i (org-get-indentation l))
19754 (i1 (car ind)) (i2 (cdr ind)))
19755 (if (>= i i2) (setq l (substring line i2)))
19756 (if (> i1 0)
19757 (concat (make-string i1 ?\ ) l)
19758 l)))
19760 (defun org-remove-indentation (code &optional n)
19761 "Remove the maximum common indentation from the lines in CODE.
19762 N may optionally be the number of spaces to remove."
19763 (with-temp-buffer
19764 (insert code)
19765 (org-do-remove-indentation n)
19766 (buffer-string)))
19768 (defun org-do-remove-indentation (&optional n)
19769 "Remove the maximum common indentation from the buffer."
19770 (untabify (point-min) (point-max))
19771 (let ((min 10000) re)
19772 (if n
19773 (setq min n)
19774 (goto-char (point-min))
19775 (while (re-search-forward "^ *[^ \n]" nil t)
19776 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
19777 (unless (or (= min 0) (= min 10000))
19778 (setq re (format "^ \\{%d\\}" min))
19779 (goto-char (point-min))
19780 (while (re-search-forward re nil t)
19781 (replace-match "")
19782 (end-of-line 1))
19783 min)))
19785 (defun org-fill-template (template alist)
19786 "Find each %key of ALIST in TEMPLATE and replace it."
19787 (let ((case-fold-search nil)
19788 entry key value)
19789 (setq alist (sort (copy-sequence alist)
19790 (lambda (a b) (< (length (car a)) (length (car b))))))
19791 (while (setq entry (pop alist))
19792 (setq template
19793 (replace-regexp-in-string
19794 (concat "%" (regexp-quote (car entry)))
19795 (cdr entry) template t t)))
19796 template))
19798 (defun org-base-buffer (buffer)
19799 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
19800 (if (not buffer)
19801 buffer
19802 (or (buffer-base-buffer buffer)
19803 buffer)))
19805 (defun org-trim (s)
19806 "Remove whitespace at beginning and end of string."
19807 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
19808 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
19811 (defun org-wrap (string &optional width lines)
19812 "Wrap string to either a number of lines, or a width in characters.
19813 If WIDTH is non-nil, the string is wrapped to that width, however many lines
19814 that costs. If there is a word longer than WIDTH, the text is actually
19815 wrapped to the length of that word.
19816 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
19817 many lines, whatever width that takes.
19818 The return value is a list of lines, without newlines at the end."
19819 (let* ((words (org-split-string string "[ \t\n]+"))
19820 (maxword (apply 'max (mapcar 'org-string-width words)))
19821 w ll)
19822 (cond (width
19823 (org-do-wrap words (max maxword width)))
19824 (lines
19825 (setq w maxword)
19826 (setq ll (org-do-wrap words maxword))
19827 (if (<= (length ll) lines)
19829 (setq ll words)
19830 (while (> (length ll) lines)
19831 (setq w (1+ w))
19832 (setq ll (org-do-wrap words w)))
19833 ll))
19834 (t (error "Cannot wrap this")))))
19836 (defun org-do-wrap (words width)
19837 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
19838 (let (lines line)
19839 (while words
19840 (setq line (pop words))
19841 (while (and words (< (+ (length line) (length (car words))) width))
19842 (setq line (concat line " " (pop words))))
19843 (setq lines (push line lines)))
19844 (nreverse lines)))
19846 (defun org-split-string (string &optional separators)
19847 "Splits STRING into substrings at SEPARATORS.
19848 No empty strings are returned if there are matches at the beginning
19849 and end of string."
19850 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
19851 (start 0)
19852 notfirst
19853 (list nil))
19854 (while (and (string-match rexp string
19855 (if (and notfirst
19856 (= start (match-beginning 0))
19857 (< start (length string)))
19858 (1+ start) start))
19859 (< (match-beginning 0) (length string)))
19860 (setq notfirst t)
19861 (or (eq (match-beginning 0) 0)
19862 (and (eq (match-beginning 0) (match-end 0))
19863 (eq (match-beginning 0) start))
19864 (setq list
19865 (cons (substring string start (match-beginning 0))
19866 list)))
19867 (setq start (match-end 0)))
19868 (or (eq start (length string))
19869 (setq list
19870 (cons (substring string start)
19871 list)))
19872 (nreverse list)))
19874 (defun org-quote-vert (s)
19875 "Replace \"|\" with \"\\vert\"."
19876 (while (string-match "|" s)
19877 (setq s (replace-match "\\vert" t t s)))
19880 (defun org-uuidgen-p (s)
19881 "Is S an ID created by UUIDGEN?"
19882 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
19884 (defun org-in-src-block-p nil
19885 "Whether point is in a code source block."
19886 (let (ov)
19887 (when (setq ov (overlays-at (point)))
19888 (memq 'org-block-background
19889 (overlay-properties
19890 (car ov))))))
19892 (defun org-context ()
19893 "Return a list of contexts of the current cursor position.
19894 If several contexts apply, all are returned.
19895 Each context entry is a list with a symbol naming the context, and
19896 two positions indicating start and end of the context. Possible
19897 contexts are:
19899 :headline anywhere in a headline
19900 :headline-stars on the leading stars in a headline
19901 :todo-keyword on a TODO keyword (including DONE) in a headline
19902 :tags on the TAGS in a headline
19903 :priority on the priority cookie in a headline
19904 :item on the first line of a plain list item
19905 :item-bullet on the bullet/number of a plain list item
19906 :checkbox on the checkbox in a plain list item
19907 :table in an org-mode table
19908 :table-special on a special filed in a table
19909 :table-table in a table.el table
19910 :clocktable in a clocktable
19911 :src-block in a source block
19912 :link on a hyperlink
19913 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
19914 :target on a <<target>>
19915 :radio-target on a <<<radio-target>>>
19916 :latex-fragment on a LaTeX fragment
19917 :latex-preview on a LaTeX fragment with overlaid preview image
19919 This function expects the position to be visible because it uses font-lock
19920 faces as a help to recognize the following contexts: :table-special, :link,
19921 and :keyword."
19922 (let* ((f (get-text-property (point) 'face))
19923 (faces (if (listp f) f (list f)))
19924 (case-fold-search t)
19925 (p (point)) clist o)
19926 ;; First the large context
19927 (cond
19928 ((org-at-heading-p t)
19929 (push (list :headline (point-at-bol) (point-at-eol)) clist)
19930 (when (progn
19931 (beginning-of-line 1)
19932 (looking-at org-todo-line-tags-regexp))
19933 (push (org-point-in-group p 1 :headline-stars) clist)
19934 (push (org-point-in-group p 2 :todo-keyword) clist)
19935 (push (org-point-in-group p 4 :tags) clist))
19936 (goto-char p)
19937 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
19938 (if (looking-at "\\[#[A-Z0-9]\\]")
19939 (push (org-point-in-group p 0 :priority) clist)))
19941 ((org-at-item-p)
19942 (push (org-point-in-group p 2 :item-bullet) clist)
19943 (push (list :item (point-at-bol)
19944 (save-excursion (org-end-of-item) (point)))
19945 clist)
19946 (and (org-at-item-checkbox-p)
19947 (push (org-point-in-group p 0 :checkbox) clist)))
19949 ((org-at-table-p)
19950 (push (list :table (org-table-begin) (org-table-end)) clist)
19951 (if (memq 'org-formula faces)
19952 (push (list :table-special
19953 (previous-single-property-change p 'face)
19954 (next-single-property-change p 'face)) clist)))
19955 ((org-at-table-p 'any)
19956 (push (list :table-table) clist)))
19957 (goto-char p)
19959 ;; New the "medium" contexts: clocktables, source blocks
19960 (cond ((org-in-clocktable-p)
19961 (push (list :clocktable
19962 (and (or (looking-at "#\\+BEGIN: clocktable")
19963 (search-backward "#+BEGIN: clocktable" nil t))
19964 (match-beginning 0))
19965 (and (re-search-forward "#\\+END:?" nil t)
19966 (match-end 0))) clist))
19967 ((org-in-src-block-p)
19968 (push (list :src-block
19969 (and (or (looking-at "#\\+BEGIN_SRC")
19970 (search-backward "#+BEGIN_SRC" nil t))
19971 (match-beginning 0))
19972 (and (search-forward "#+END_SRC" nil t)
19973 (match-beginning 0))) clist)))
19974 (goto-char p)
19976 ;; Now the small context
19977 (cond
19978 ((org-at-timestamp-p)
19979 (push (org-point-in-group p 0 :timestamp) clist))
19980 ((memq 'org-link faces)
19981 (push (list :link
19982 (previous-single-property-change p 'face)
19983 (next-single-property-change p 'face)) clist))
19984 ((memq 'org-special-keyword faces)
19985 (push (list :keyword
19986 (previous-single-property-change p 'face)
19987 (next-single-property-change p 'face)) clist))
19988 ((org-at-target-p)
19989 (push (org-point-in-group p 0 :target) clist)
19990 (goto-char (1- (match-beginning 0)))
19991 (if (looking-at org-radio-target-regexp)
19992 (push (org-point-in-group p 0 :radio-target) clist))
19993 (goto-char p))
19994 ((setq o (car (delq nil
19995 (mapcar
19996 (lambda (x)
19997 (if (memq x org-latex-fragment-image-overlays) x))
19998 (overlays-at (point))))))
19999 (push (list :latex-fragment
20000 (overlay-start o) (overlay-end o)) clist)
20001 (push (list :latex-preview
20002 (overlay-start o) (overlay-end o)) clist))
20003 ((org-inside-LaTeX-fragment-p)
20004 ;; FIXME: positions wrong.
20005 (push (list :latex-fragment (point) (point)) clist)))
20007 (setq clist (nreverse (delq nil clist)))
20008 clist))
20010 ;; FIXME: Compare with at-regexp-p Do we need both?
20011 (defun org-in-regexp (re &optional nlines visually)
20012 "Check if point is inside a match of regexp.
20013 Normally only the current line is checked, but you can include NLINES extra
20014 lines both before and after point into the search.
20015 If VISUALLY is set, require that the cursor is not after the match but
20016 really on, so that the block visually is on the match."
20017 (catch 'exit
20018 (let ((pos (point))
20019 (eol (point-at-eol (+ 1 (or nlines 0))))
20020 (inc (if visually 1 0)))
20021 (save-excursion
20022 (beginning-of-line (- 1 (or nlines 0)))
20023 (while (re-search-forward re eol t)
20024 (if (and (<= (match-beginning 0) pos)
20025 (>= (+ inc (match-end 0)) pos))
20026 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
20028 (defun org-at-regexp-p (regexp)
20029 "Is point inside a match of REGEXP in the current line?"
20030 (catch 'exit
20031 (save-excursion
20032 (let ((pos (point)) (end (point-at-eol)))
20033 (beginning-of-line 1)
20034 (while (re-search-forward regexp end t)
20035 (if (and (<= (match-beginning 0) pos)
20036 (>= (match-end 0) pos))
20037 (throw 'exit t)))
20038 nil))))
20040 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
20041 "Non-nil when point is between matches of START-RE and END-RE.
20043 Also return a non-nil value when point is on one of the matches.
20045 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
20046 buffer positions. Default values are the positions of headlines
20047 surrounding the point.
20049 The functions returns a cons cell whose car (resp. cdr) is the
20050 position before START-RE (resp. after END-RE)."
20051 (save-match-data
20052 (let ((pos (point))
20053 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
20054 (limit-down (or lim-down (save-excursion (outline-next-heading))))
20055 beg end)
20056 (save-excursion
20057 ;; Point is on a block when on START-RE or if START-RE can be
20058 ;; found before it...
20059 (and (or (org-at-regexp-p start-re)
20060 (re-search-backward start-re limit-up t))
20061 (setq beg (match-beginning 0))
20062 ;; ... and END-RE after it...
20063 (goto-char (match-end 0))
20064 (re-search-forward end-re limit-down t)
20065 (> (setq end (match-end 0)) pos)
20066 ;; ... without another START-RE in-between.
20067 (goto-char (match-beginning 0))
20068 (not (re-search-backward start-re (1+ beg) t))
20069 ;; Return value.
20070 (cons beg end))))))
20072 (defun org-in-block-p (names)
20073 "Non-nil when point belongs to a block whose name belongs to NAMES.
20075 NAMES is a list of strings containing names of blocks.
20077 Return first block name matched, or nil. Beware that in case of
20078 nested blocks, the returned name may not belong to the closest
20079 block from point."
20080 (save-match-data
20081 (catch 'exit
20082 (let ((case-fold-search t)
20083 (lim-up (save-excursion (outline-previous-heading)))
20084 (lim-down (save-excursion (outline-next-heading))))
20085 (mapc (lambda (name)
20086 (let ((n (regexp-quote name)))
20087 (when (org-between-regexps-p
20088 (concat "^[ \t]*#\\+begin_" n)
20089 (concat "^[ \t]*#\\+end_" n)
20090 lim-up lim-down)
20091 (throw 'exit n))))
20092 names))
20093 nil)))
20095 (defun org-occur-in-agenda-files (regexp &optional nlines)
20096 "Call `multi-occur' with buffers for all agenda files."
20097 (interactive "sOrg-files matching: \np")
20098 (let* ((files (org-agenda-files))
20099 (tnames (mapcar 'file-truename files))
20100 (extra org-agenda-text-search-extra-files)
20102 (when (eq (car extra) 'agenda-archives)
20103 (setq extra (cdr extra))
20104 (setq files (org-add-archive-files files)))
20105 (while (setq f (pop extra))
20106 (unless (member (file-truename f) tnames)
20107 (add-to-list 'files f 'append)
20108 (add-to-list 'tnames (file-truename f) 'append)))
20109 (multi-occur
20110 (mapcar (lambda (x)
20111 (with-current-buffer
20112 (or (get-file-buffer x) (find-file-noselect x))
20113 (widen)
20114 (current-buffer)))
20115 files)
20116 regexp)))
20118 (if (boundp 'occur-mode-find-occurrence-hook)
20119 ;; Emacs 23
20120 (add-hook 'occur-mode-find-occurrence-hook
20121 (lambda ()
20122 (when (derived-mode-p 'org-mode)
20123 (org-reveal))))
20124 ;; Emacs 22
20125 (defadvice occur-mode-goto-occurrence
20126 (after org-occur-reveal activate)
20127 (and (derived-mode-p 'org-mode) (org-reveal)))
20128 (defadvice occur-mode-goto-occurrence-other-window
20129 (after org-occur-reveal activate)
20130 (and (derived-mode-p 'org-mode) (org-reveal)))
20131 (defadvice occur-mode-display-occurrence
20132 (after org-occur-reveal activate)
20133 (when (derived-mode-p 'org-mode)
20134 (let ((pos (occur-mode-find-occurrence)))
20135 (with-current-buffer (marker-buffer pos)
20136 (save-excursion
20137 (goto-char pos)
20138 (org-reveal)))))))
20140 (defun org-occur-link-in-agenda-files ()
20141 "Create a link and search for it in the agendas.
20142 The link is not stored in `org-stored-links', it is just created
20143 for the search purpose."
20144 (interactive)
20145 (let ((link (condition-case nil
20146 (org-store-link nil)
20147 (error "Unable to create a link to here"))))
20148 (org-occur-in-agenda-files (regexp-quote link))))
20150 (defun org-uniquify (list)
20151 "Remove duplicate elements from LIST."
20152 (let (res)
20153 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
20154 res))
20156 (defun org-delete-all (elts list)
20157 "Remove all elements in ELTS from LIST."
20158 (while elts
20159 (setq list (delete (pop elts) list)))
20160 list)
20162 (defun org-count (cl-item cl-seq)
20163 "Count the number of occurrences of ITEM in SEQ.
20164 Taken from `count' in cl-seq.el with all keyword arguments removed."
20165 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
20166 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
20167 (while (< cl-start cl-end)
20168 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
20169 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
20170 (setq cl-start (1+ cl-start)))
20171 cl-count))
20173 (defun org-remove-if (predicate seq)
20174 "Remove everything from SEQ that fulfills PREDICATE."
20175 (let (res e)
20176 (while seq
20177 (setq e (pop seq))
20178 (if (not (funcall predicate e)) (push e res)))
20179 (nreverse res)))
20181 (defun org-remove-if-not (predicate seq)
20182 "Remove everything from SEQ that does not fulfill PREDICATE."
20183 (let (res e)
20184 (while seq
20185 (setq e (pop seq))
20186 (if (funcall predicate e) (push e res)))
20187 (nreverse res)))
20189 (defun org-reduce (cl-func cl-seq &rest cl-keys)
20190 "Reduce two-argument FUNCTION across SEQ.
20191 Taken from `reduce' in cl-seq.el with all keyword arguments but
20192 \":initial-value\" removed."
20193 (let ((cl-accum (cond ((memq :initial-value cl-keys)
20194 (cadr (memq :initial-value cl-keys)))
20195 (cl-seq (pop cl-seq))
20196 (t (funcall cl-func)))))
20197 (while cl-seq
20198 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
20199 cl-accum))
20201 (defun org-back-over-empty-lines ()
20202 "Move backwards over whitespace, to the beginning of the first empty line.
20203 Returns the number of empty lines passed."
20204 (let ((pos (point)))
20205 (if (cdr (assoc 'heading org-blank-before-new-entry))
20206 (skip-chars-backward " \t\n\r")
20207 (unless (eobp)
20208 (forward-line -1)))
20209 (beginning-of-line 2)
20210 (goto-char (min (point) pos))
20211 (count-lines (point) pos)))
20213 (defun org-skip-whitespace ()
20214 (skip-chars-forward " \t\n\r"))
20216 (defun org-point-in-group (point group &optional context)
20217 "Check if POINT is in match-group GROUP.
20218 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
20219 match. If the match group does not exist or point is not inside it,
20220 return nil."
20221 (and (match-beginning group)
20222 (>= point (match-beginning group))
20223 (<= point (match-end group))
20224 (if context
20225 (list context (match-beginning group) (match-end group))
20226 t)))
20228 (defun org-switch-to-buffer-other-window (&rest args)
20229 "Switch to buffer in a second window on the current frame.
20230 In particular, do not allow pop-up frames.
20231 Returns the newly created buffer."
20232 (let (pop-up-frames special-display-buffer-names special-display-regexps
20233 special-display-function)
20234 (apply 'switch-to-buffer-other-window args)))
20236 (defun org-combine-plists (&rest plists)
20237 "Create a single property list from all plists in PLISTS.
20238 The process starts by copying the first list, and then setting properties
20239 from the other lists. Settings in the last list are the most significant
20240 ones and overrule settings in the other lists."
20241 (let ((rtn (copy-sequence (pop plists)))
20242 p v ls)
20243 (while plists
20244 (setq ls (pop plists))
20245 (while ls
20246 (setq p (pop ls) v (pop ls))
20247 (setq rtn (plist-put rtn p v))))
20248 rtn))
20250 (defun org-move-line-down (arg)
20251 "Move the current line down. With prefix argument, move it past ARG lines."
20252 (interactive "p")
20253 (let ((col (current-column))
20254 beg end pos)
20255 (beginning-of-line 1) (setq beg (point))
20256 (beginning-of-line 2) (setq end (point))
20257 (beginning-of-line (+ 1 arg))
20258 (setq pos (move-marker (make-marker) (point)))
20259 (insert (delete-and-extract-region beg end))
20260 (goto-char pos)
20261 (org-move-to-column col)))
20263 (defun org-move-line-up (arg)
20264 "Move the current line up. With prefix argument, move it past ARG lines."
20265 (interactive "p")
20266 (let ((col (current-column))
20267 beg end pos)
20268 (beginning-of-line 1) (setq beg (point))
20269 (beginning-of-line 2) (setq end (point))
20270 (beginning-of-line (- arg))
20271 (setq pos (move-marker (make-marker) (point)))
20272 (insert (delete-and-extract-region beg end))
20273 (goto-char pos)
20274 (org-move-to-column col)))
20276 (defun org-replace-escapes (string table)
20277 "Replace %-escapes in STRING with values in TABLE.
20278 TABLE is an association list with keys like \"%a\" and string values.
20279 The sequences in STRING may contain normal field width and padding information,
20280 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
20281 so values can contain further %-escapes if they are define later in TABLE."
20282 (let ((tbl (copy-alist table))
20283 (case-fold-search nil)
20284 (pchg 0)
20285 e re rpl)
20286 (while (setq e (pop tbl))
20287 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
20288 (when (and (cdr e) (string-match re (cdr e)))
20289 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
20290 (safe "SREF"))
20291 (add-text-properties 0 3 (list 'sref sref) safe)
20292 (setcdr e (replace-match safe t t (cdr e)))))
20293 (while (string-match re string)
20294 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
20295 (cdr e)))
20296 (setq string (replace-match rpl t t string))))
20297 (while (setq pchg (next-property-change pchg string))
20298 (let ((sref (get-text-property pchg 'sref string)))
20299 (when (and sref (string-match "SREF" string pchg))
20300 (setq string (replace-match sref t t string)))))
20301 string))
20303 (defun org-sublist (list start end)
20304 "Return a section of LIST, from START to END.
20305 Counting starts at 1."
20306 (let (rtn (c start))
20307 (setq list (nthcdr (1- start) list))
20308 (while (and list (<= c end))
20309 (push (pop list) rtn)
20310 (setq c (1+ c)))
20311 (nreverse rtn)))
20313 (defun org-find-base-buffer-visiting (file)
20314 "Like `find-buffer-visiting' but always return the base buffer and
20315 not an indirect buffer."
20316 (let ((buf (or (get-file-buffer file)
20317 (find-buffer-visiting file))))
20318 (if buf
20319 (or (buffer-base-buffer buf) buf)
20320 nil)))
20322 (defun org-image-file-name-regexp (&optional extensions)
20323 "Return regexp matching the file names of images.
20324 If EXTENSIONS is given, only match these."
20325 (if (and (not extensions) (fboundp 'image-file-name-regexp))
20326 (image-file-name-regexp)
20327 (let ((image-file-name-extensions
20328 (or extensions
20329 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
20330 "xbm" "xpm" "pbm" "pgm" "ppm"))))
20331 (concat "\\."
20332 (regexp-opt (nconc (mapcar 'upcase
20333 image-file-name-extensions)
20334 image-file-name-extensions)
20336 "\\'"))))
20338 (defun org-file-image-p (file &optional extensions)
20339 "Return non-nil if FILE is an image."
20340 (save-match-data
20341 (string-match (org-image-file-name-regexp extensions) file)))
20343 (defun org-get-cursor-date ()
20344 "Return the date at cursor in as a time.
20345 This works in the calendar and in the agenda, anywhere else it just
20346 returns the current time."
20347 (let (date day defd)
20348 (cond
20349 ((eq major-mode 'calendar-mode)
20350 (setq date (calendar-cursor-to-date)
20351 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
20352 ((eq major-mode 'org-agenda-mode)
20353 (setq day (get-text-property (point) 'day))
20354 (if day
20355 (setq date (calendar-gregorian-from-absolute day)
20356 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
20357 (nth 2 date))))))
20358 (or defd (current-time))))
20360 (defvar org-agenda-action-marker (make-marker)
20361 "Marker pointing to the entry for the next agenda action.")
20363 (defun org-mark-entry-for-agenda-action ()
20364 "Mark the current entry as target of an agenda action.
20365 Agenda actions are actions executed from the agenda with the key `k',
20366 which make use of the date at the cursor."
20367 (interactive)
20368 (move-marker org-agenda-action-marker
20369 (save-excursion (org-back-to-heading t) (point))
20370 (current-buffer))
20371 (message
20372 "Entry marked for action; press `k' at desired date in agenda or calendar"))
20374 (defun org-mark-subtree ()
20375 "Mark the current subtree.
20376 This puts point at the start of the current subtree, and mark at the end.
20378 If point is in an inline task, mark that task instead."
20379 (interactive)
20380 (let ((inline-task-p
20381 (and (featurep 'org-inlinetask)
20382 (org-inlinetask-in-task-p)))
20383 (beg))
20384 ;; Get beginning of subtree
20385 (cond
20386 (inline-task-p (org-inlinetask-goto-beginning))
20387 ((org-at-heading-p) (beginning-of-line))
20388 (t (org-with-limited-levels (outline-previous-visible-heading 1))))
20389 (setq beg (point))
20390 ;; Get end of it
20391 (if inline-task-p
20392 (org-inlinetask-goto-end)
20393 (org-end-of-subtree))
20394 ;; Mark zone
20395 (push-mark (point) nil t)
20396 (goto-char beg)))
20398 ;;; Paragraph filling stuff.
20399 ;; We want this to be just right, so use the full arsenal.
20401 (defun org-indent-line-function ()
20402 "Indent line depending on context."
20403 (interactive)
20404 (if org-indent-line-fallback-function
20405 (funcall org-indent-line-fallback-function)
20406 (let* ((pos (point))
20407 (itemp (org-at-item-p))
20408 (case-fold-search t)
20409 (org-drawer-regexp (or org-drawer-regexp "\000"))
20410 (inline-task-p (and (featurep 'org-inlinetask)
20411 (org-inlinetask-in-task-p)))
20412 (inline-re (and inline-task-p
20413 (org-inlinetask-outline-regexp)))
20414 column)
20415 (beginning-of-line 1)
20416 (cond
20417 ;; Comments
20418 ((looking-at "# ") (setq column 0))
20419 ;; Headings
20420 ((looking-at org-outline-regexp) (setq column 0))
20421 ;; Included files
20422 ((looking-at "#\\+include:") (setq column 0))
20423 ;; Footnote definition
20424 ((looking-at org-footnote-definition-re) (setq column 0))
20425 ;; Literal examples
20426 ((looking-at "[ \t]*:\\( \\|$\\)")
20427 (setq column (org-get-indentation))) ; do nothing
20428 ;; Lists
20429 ((ignore-errors (goto-char (org-in-item-p)))
20430 (setq column (if itemp
20431 (org-get-indentation)
20432 (org-list-item-body-column (point))))
20433 (goto-char pos))
20434 ;; Drawers
20435 ((and (looking-at "[ \t]*:END:")
20436 (save-excursion (re-search-backward org-drawer-regexp nil t)))
20437 (save-excursion
20438 (goto-char (1- (match-beginning 1)))
20439 (setq column (current-column))))
20440 ;; Special blocks
20441 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
20442 (save-excursion
20443 (re-search-backward
20444 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
20445 (setq column (org-get-indentation (match-string 0))))
20446 ((and (not (looking-at "[ \t]*#\\+begin_"))
20447 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
20448 (save-excursion
20449 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
20450 (setq column
20451 (cond ((equal (downcase (match-string 1)) "src")
20452 ;; src blocks: let `org-edit-src-exit' handle them
20453 (org-get-indentation))
20454 ((equal (downcase (match-string 1)) "example")
20455 (max (org-get-indentation)
20456 (org-get-indentation (match-string 0))))
20458 (org-get-indentation (match-string 0))))))
20459 ;; This line has nothing special, look at the previous relevant
20460 ;; line to compute indentation
20462 (beginning-of-line 0)
20463 (while (and (not (bobp))
20464 (not (looking-at org-drawer-regexp))
20465 ;; When point started in an inline task, do not move
20466 ;; above task starting line.
20467 (not (and inline-task-p (looking-at inline-re)))
20468 ;; Skip drawers, blocks, empty lines, verbatim,
20469 ;; comments, tables, footnotes definitions, lists,
20470 ;; inline tasks.
20471 (or (and (looking-at "[ \t]*:END:")
20472 (re-search-backward org-drawer-regexp nil t))
20473 (and (looking-at "[ \t]*#\\+end_")
20474 (re-search-backward "[ \t]*#\\+begin_"nil t))
20475 (looking-at "[ \t]*[\n:#|]")
20476 (looking-at org-footnote-definition-re)
20477 (and (ignore-errors (goto-char (org-in-item-p)))
20478 (goto-char
20479 (org-list-get-top-point (org-list-struct))))
20480 (and (not inline-task-p)
20481 (featurep 'org-inlinetask)
20482 (org-inlinetask-in-task-p)
20483 (or (org-inlinetask-goto-beginning) t))))
20484 (beginning-of-line 0))
20485 (cond
20486 ;; There was an heading above.
20487 ((looking-at "\\*+[ \t]+")
20488 (if (not org-adapt-indentation)
20489 (setq column 0)
20490 (goto-char (match-end 0))
20491 (setq column (current-column))))
20492 ;; A drawer had started and is unfinished
20493 ((looking-at org-drawer-regexp)
20494 (goto-char (1- (match-beginning 1)))
20495 (setq column (current-column)))
20496 ;; Else, nothing noticeable found: get indentation and go on.
20497 (t (setq column (org-get-indentation))))))
20498 ;; Now apply indentation and move cursor accordingly
20499 (goto-char pos)
20500 (if (<= (current-column) (current-indentation))
20501 (org-indent-line-to column)
20502 (save-excursion (org-indent-line-to column)))
20503 ;; Special polishing for properties, see `org-property-format'
20504 (setq column (current-column))
20505 (beginning-of-line 1)
20506 (if (looking-at
20507 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
20508 (replace-match (concat (match-string 1)
20509 (format org-property-format
20510 (match-string 2) (match-string 3)))
20511 t t))
20512 (org-move-to-column column))))
20514 (defun org-indent-drawer ()
20515 "Indent the drawer at point."
20516 (interactive)
20517 (let ((p (point))
20518 (e (and (save-excursion (re-search-forward ":END:" nil t))
20519 (match-end 0)))
20520 (folded
20521 (save-excursion
20522 (end-of-line)
20523 (when (overlays-at (point))
20524 (member 'invisible (overlay-properties
20525 (car (overlays-at (point)))))))))
20526 (when folded (org-cycle))
20527 (indent-for-tab-command)
20528 (while (and (move-beginning-of-line 2) (< (point) e))
20529 (indent-for-tab-command))
20530 (goto-char p)
20531 (when folded (org-cycle)))
20532 (message "Drawer at point indented"))
20534 (defun org-indent-block ()
20535 "Indent the block at point."
20536 (interactive)
20537 (let ((p (point))
20538 (case-fold-search t)
20539 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
20540 (match-end 0)))
20541 (folded
20542 (save-excursion
20543 (end-of-line)
20544 (when (overlays-at (point))
20545 (member 'invisible (overlay-properties
20546 (car (overlays-at (point)))))))))
20547 (when folded (org-cycle))
20548 (indent-for-tab-command)
20549 (while (and (move-beginning-of-line 2) (< (point) e))
20550 (indent-for-tab-command))
20551 (goto-char p)
20552 (when folded (org-cycle)))
20553 (message "Block at point indented"))
20555 (defvar org-adaptive-fill-regexp-backup adaptive-fill-regexp
20556 "Variable to store copy of `adaptive-fill-regexp'.
20557 Since `adaptive-fill-regexp' is set to never match, we need to
20558 store a backup of its value before entering `org-mode' so that
20559 the functionality can be provided as a fall-back.")
20561 (defun org-set-autofill-regexps ()
20562 (interactive)
20563 ;; In the paragraph separator we include headlines, because filling
20564 ;; text in a line directly attached to a headline would otherwise
20565 ;; fill the headline as well.
20566 (org-set-local 'comment-start-skip "^#+[ \t]*")
20567 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|#]")
20568 ;; The paragraph starter includes hand-formatted lists.
20569 (org-set-local
20570 'paragraph-start
20571 (concat
20572 "\f" "\\|"
20573 "[ ]*$" "\\|"
20574 org-outline-regexp "\\|"
20575 "[ \t]*#" "\\|"
20576 (org-item-re) "\\|"
20577 "[ \t]*[:|]" "\\|"
20578 "\\$\\$" "\\|"
20579 "\\\\\\(begin\\|end\\|[][]\\)"))
20580 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
20581 ;; But only if the user has not turned off tables or fixed-width regions
20582 (org-set-local
20583 'auto-fill-inhibit-regexp
20584 (concat org-outline-regexp
20585 "\\|#\\+"
20586 "\\|[ \t]*" org-keyword-time-regexp
20587 (if (or org-enable-table-editor org-enable-fixed-width-editor)
20588 (concat
20589 "\\|[ \t]*["
20590 (if org-enable-table-editor "|" "")
20591 (if org-enable-fixed-width-editor ":" "")
20592 "]"))))
20593 ;; We use our own fill-paragraph function, to make sure that tables
20594 ;; and fixed-width regions are not wrapped. That function will pass
20595 ;; through to `fill-paragraph' when appropriate.
20596 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
20597 ;; Prevent auto-fill from inserting unwanted new items.
20598 (if (boundp 'fill-nobreak-predicate)
20599 (org-set-local
20600 'fill-nobreak-predicate
20601 (org-uniquify
20602 (append fill-nobreak-predicate
20603 '(org-fill-item-nobreak-p org-fill-line-break-nobreak-p)))))
20604 ;; Adaptive filling: To get full control, first make sure that
20605 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
20606 (unless (local-variable-p 'adaptive-fill-regexp (current-buffer))
20607 (org-set-local 'org-adaptive-fill-regexp-backup
20608 adaptive-fill-regexp))
20609 (org-set-local 'adaptive-fill-regexp "\000")
20610 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
20611 (org-set-local 'adaptive-fill-function
20612 'org-adaptive-fill-function)
20613 (org-set-local
20614 'align-mode-rules-list
20615 '((org-in-buffer-settings
20616 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
20617 (modes . '(org-mode))))))
20619 (defun org-fill-item-nobreak-p ()
20620 "Non-nil when a line break at point would insert a new item."
20621 (and (looking-at (org-item-re)) (org-list-in-valid-context-p)))
20623 (defun org-fill-line-break-nobreak-p ()
20624 "Non-nil when a line break at point would create an Org line break."
20625 (save-excursion
20626 (skip-chars-backward "[ \t]")
20627 (skip-chars-backward "\\\\")
20628 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
20630 (defun org-fill-paragraph (&optional justify)
20631 "Re-align a table, pass through to fill-paragraph if no table."
20632 (let ((table-p (org-at-table-p))
20633 (table.el-p (org-at-table.el-p))
20634 (itemp (org-in-item-p)))
20635 (cond ((and (equal (char-after (point-at-bol)) ?*)
20636 (save-excursion (goto-char (point-at-bol))
20637 (looking-at org-outline-regexp)))
20638 t) ; skip headlines
20639 (table.el-p t) ; skip table.el tables
20640 (table-p (org-table-align) t) ; align Org tables
20641 (itemp ; align text in items
20642 (let* ((struct (save-excursion (goto-char itemp)
20643 (org-list-struct)))
20644 (parents (org-list-parents-alist struct))
20645 (children (org-list-get-children itemp struct parents))
20646 beg end prev next prefix)
20647 ;; Determine in which part of item point is: before
20648 ;; first child, after last child, between two
20649 ;; sub-lists, or simply in item if there's no child.
20650 (cond
20651 ((not children)
20652 (setq prefix (make-string (org-list-item-body-column itemp) ?\ )
20653 beg itemp
20654 end (org-list-get-item-end itemp struct)))
20655 ((< (point) (setq next (car children)))
20656 (setq prefix (make-string (org-list-item-body-column itemp) ?\ )
20657 beg itemp
20658 end next))
20659 ((> (point) (setq prev (car (last children))))
20660 (setq beg (org-list-get-item-end prev struct)
20661 end (org-list-get-item-end itemp struct)
20662 prefix (save-excursion
20663 (goto-char beg)
20664 (skip-chars-forward " \t")
20665 (make-string (current-column) ?\ ))))
20666 (t (catch 'exit
20667 (while (setq next (pop children))
20668 (if (> (point) next)
20669 (setq prev next)
20670 (setq beg (org-list-get-item-end prev struct)
20671 end next
20672 prefix (save-excursion
20673 (goto-char beg)
20674 (skip-chars-forward " \t")
20675 (make-string (current-column) ?\ )))
20676 (throw 'exit nil))))))
20677 ;; Use `fill-paragraph' with buffer narrowed to item
20678 ;; without any child, and with our computed PREFIX.
20679 (flet ((fill-context-prefix (from to &optional flr) prefix))
20680 (save-restriction
20681 (narrow-to-region beg end)
20682 (save-excursion (fill-paragraph justify)))) t))
20683 ;; Special case where point is not in a list but is on
20684 ;; a paragraph adjacent to a list: make sure this paragraph
20685 ;; doesn't get merged with the end of the list by narrowing
20686 ;; buffer first.
20687 ((and (derived-mode-p 'org-mode)
20688 (save-excursion (forward-paragraph -1)
20689 (setq itemp (org-in-item-p))))
20690 (let ((struct (save-excursion (goto-char itemp)
20691 (org-list-struct))))
20692 (save-restriction
20693 (narrow-to-region (org-list-get-bottom-point struct)
20694 (save-excursion (forward-paragraph 1)
20695 (point)))
20696 (fill-paragraph justify) t)))
20697 ;; Don't fill schedule/deadline line before a paragraph
20698 ;; This only makes sense in real org-mode buffers
20699 ((and (eq major-mode 'org-mode)
20700 (save-excursion (forward-paragraph -1)
20701 (or (looking-at (concat "^[^\n]*" org-scheduled-regexp ".*$"))
20702 (looking-at (concat "^[^\n]*" org-deadline-regexp ".*$")))))
20703 (save-restriction
20704 (narrow-to-region (1+ (match-end 0))
20705 (save-excursion (forward-paragraph 1) (point)))
20706 (fill-paragraph justify) t))
20707 ;; Else falls back on `org-fill-paragraph-fallback-function'
20708 (org-fill-paragraph-fallback-function
20709 (funcall org-fill-paragraph-fallback-function justify))
20710 ;; Else simply call `fill-paragraph'.
20711 (t nil))))
20713 ;; For reference, this is the default value of adaptive-fill-regexp
20714 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
20716 (defun org-adaptive-fill-function ()
20717 "Return a fill prefix for org-mode files."
20718 (let (itemp)
20719 (save-excursion
20720 (cond
20721 ;; Comment line
20722 ((looking-at "#[ \t]+")
20723 (match-string-no-properties 0))
20724 ;; Plain list item
20725 ((org-at-item-p)
20726 (make-string (org-list-item-body-column (point-at-bol)) ?\ ))
20727 ;; Point is in a list after `backward-paragraph': original
20728 ;; point wasn't in the list, or filling would have been taken
20729 ;; care of by `org-auto-fill-function', but the list and the
20730 ;; real paragraph are not separated by a blank line. Thus, move
20731 ;; point after the list to go back to real paragraph and
20732 ;; determine fill-prefix.
20733 ((setq itemp (org-in-item-p))
20734 (goto-char itemp)
20735 (let* ((struct (org-list-struct))
20736 (bottom (org-list-get-bottom-point struct)))
20737 (goto-char bottom)
20738 (make-string (org-get-indentation) ?\ )))
20739 ;; Other text
20740 ((looking-at org-adaptive-fill-regexp-backup)
20741 (match-string-no-properties 0))))))
20743 (defun org-auto-fill-function ()
20744 "Auto-fill function."
20745 (let (itemp prefix)
20746 ;; When in a list, compute an appropriate fill-prefix and make
20747 ;; sure it will be used by `do-auto-fill'.
20748 (cond ((setq itemp (org-in-item-p))
20749 (progn
20750 (setq prefix (make-string (org-list-item-body-column itemp) ?\ ))
20751 (flet ((fill-context-prefix (from to &optional flr) prefix))
20752 (do-auto-fill))))
20753 (org-auto-fill-fallback-function
20754 (let ((fill-prefix ""))
20755 (funcall org-auto-fill-fallback-function)))
20756 ;; Else just use `do-auto-fill'.
20757 (t (do-auto-fill)))))
20759 ;;; Other stuff.
20761 (defun org-toggle-fixed-width-section (arg)
20762 "Toggle the fixed-width export.
20763 If there is no active region, the QUOTE keyword at the current headline is
20764 inserted or removed. When present, it causes the text between this headline
20765 and the next to be exported as fixed-width text, and unmodified.
20766 If there is an active region, this command adds or removes a colon as the
20767 first character of this line. If the first character of a line is a colon,
20768 this line is also exported in fixed-width font."
20769 (interactive "P")
20770 (let* ((cc 0)
20771 (regionp (org-region-active-p))
20772 (beg (if regionp (region-beginning) (point)))
20773 (end (if regionp (region-end)))
20774 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
20775 (case-fold-search nil)
20776 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
20777 off)
20778 (if regionp
20779 (save-excursion
20780 (goto-char beg)
20781 (setq cc (current-column))
20782 (beginning-of-line 1)
20783 (setq off (looking-at re))
20784 (while (> nlines 0)
20785 (setq nlines (1- nlines))
20786 (beginning-of-line 1)
20787 (cond
20788 (arg
20789 (org-move-to-column cc t)
20790 (insert ": \n")
20791 (forward-line -1))
20792 ((and off (looking-at re))
20793 (replace-match "" t t nil 1))
20794 ((not off) (org-move-to-column cc t) (insert ": ")))
20795 (forward-line 1)))
20796 (save-excursion
20797 (org-back-to-heading)
20798 (cond
20799 ((looking-at (format org-heading-keyword-regexp-format
20800 org-quote-string))
20801 (goto-char (match-end 1))
20802 (looking-at (concat " +" org-quote-string))
20803 (replace-match "" t t)
20804 (when (eolp) (insert " ")))
20805 ((looking-at org-outline-regexp)
20806 (goto-char (match-end 0))
20807 (insert org-quote-string " ")))))))
20809 (defun org-reftex-citation ()
20810 "Use reftex-citation to insert a citation into the buffer.
20811 This looks for a line like
20813 #+BIBLIOGRAPHY: foo plain option:-d
20815 and derives from it that foo.bib is the bibliography file relevant
20816 for this document. It then installs the necessary environment for RefTeX
20817 to work in this buffer and calls `reftex-citation' to insert a citation
20818 into the buffer.
20820 Export of such citations to both LaTeX and HTML is handled by the contributed
20821 package org-exp-bibtex by Taru Karttunen."
20822 (interactive)
20823 (let ((reftex-docstruct-symbol 'rds)
20824 (reftex-cite-format "\\cite{%l}")
20825 rds bib)
20826 (save-excursion
20827 (save-restriction
20828 (widen)
20829 (let ((case-fold-search t)
20830 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
20831 (if (not (save-excursion
20832 (or (re-search-forward re nil t)
20833 (re-search-backward re nil t))))
20834 (error "No bibliography defined in file")
20835 (setq bib (concat (match-string 1) ".bib")
20836 rds (list (list 'bib bib)))))))
20837 (call-interactively 'reftex-citation)))
20839 ;;;; Functions extending outline functionality
20841 (defun org-beginning-of-line (&optional arg)
20842 "Go to the beginning of the current line. If that is invisible, continue
20843 to a visible line beginning. This makes the function of C-a more intuitive.
20844 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
20845 first attempt, and only move to after the tags when the cursor is already
20846 beyond the end of the headline."
20847 (interactive "P")
20848 (let ((pos (point))
20849 (special (if (consp org-special-ctrl-a/e)
20850 (car org-special-ctrl-a/e)
20851 org-special-ctrl-a/e))
20852 refpos)
20853 (if (org-bound-and-true-p line-move-visual)
20854 (beginning-of-visual-line 1)
20855 (beginning-of-line 1))
20856 (if (and arg (fboundp 'move-beginning-of-line))
20857 (call-interactively 'move-beginning-of-line)
20858 (if (bobp)
20860 (backward-char 1)
20861 (if (org-truely-invisible-p)
20862 (while (and (not (bobp)) (org-truely-invisible-p))
20863 (backward-char 1)
20864 (beginning-of-line 1))
20865 (forward-char 1))))
20866 (when special
20867 (cond
20868 ((and (looking-at org-complex-heading-regexp)
20869 (= (char-after (match-end 1)) ?\ ))
20870 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
20871 (point-at-eol)))
20872 (goto-char
20873 (if (eq special t)
20874 (cond ((> pos refpos) refpos)
20875 ((= pos (point)) refpos)
20876 (t (point)))
20877 (cond ((> pos (point)) (point))
20878 ((not (eq last-command this-command)) (point))
20879 (t refpos)))))
20880 ((org-at-item-p)
20881 ;; Being at an item and not looking at an the item means point
20882 ;; was previously moved to beginning of a visual line, which
20883 ;; doesn't contain the item. Therefore, do nothing special,
20884 ;; just stay here.
20885 (when (looking-at org-list-full-item-re)
20886 ;; Set special position at first white space character after
20887 ;; bullet, and check-box, if any.
20888 (let ((after-bullet
20889 (let ((box (match-end 3)))
20890 (if (not box) (match-end 1)
20891 (let ((after (char-after box)))
20892 (if (and after (= after ? )) (1+ box) box))))))
20893 ;; Special case: Move point to special position when
20894 ;; currently after it or at beginning of line.
20895 (if (eq special t)
20896 (when (or (> pos after-bullet) (= (point) pos))
20897 (goto-char after-bullet))
20898 ;; Reversed case: Move point to special position when
20899 ;; point was already at beginning of line and command is
20900 ;; repeated.
20901 (when (and (= (point) pos) (eq last-command this-command))
20902 (goto-char after-bullet))))))))
20903 (org-no-warnings
20904 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
20906 (defun org-end-of-line (&optional arg)
20907 "Go to the end of the line.
20908 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
20909 first attempt, and only move to after the tags when the cursor is already
20910 beyond the end of the headline."
20911 (interactive "P")
20912 (let ((special (if (consp org-special-ctrl-a/e)
20913 (cdr org-special-ctrl-a/e)
20914 org-special-ctrl-a/e)))
20915 (cond
20916 ((or (not special) arg
20917 (not (or (org-at-heading-p) (org-at-item-p) (org-at-drawer-p))))
20918 (call-interactively
20919 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
20920 ((fboundp 'move-end-of-line) 'move-end-of-line)
20921 (t 'end-of-line))))
20922 ((org-at-heading-p)
20923 (let ((pos (point)))
20924 (beginning-of-line 1)
20925 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
20926 (if (eq special t)
20927 (if (or (< pos (match-beginning 1))
20928 (= pos (match-end 0)))
20929 (goto-char (match-beginning 1))
20930 (goto-char (match-end 0)))
20931 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
20932 (goto-char (match-end 0))
20933 (goto-char (match-beginning 1))))
20934 (call-interactively (if (fboundp 'move-end-of-line)
20935 'move-end-of-line
20936 'end-of-line)))))
20937 ((org-at-drawer-p)
20938 (move-end-of-line 1)
20939 (when (overlays-at (1- (point))) (backward-char 1)))
20940 ;; At an item: Move before any hidden text.
20941 (t (call-interactively
20942 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
20943 ((fboundp 'move-end-of-line) 'move-end-of-line)
20944 (t 'end-of-line)))))
20945 (org-no-warnings
20946 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
20948 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
20949 (define-key org-mode-map "\C-e" 'org-end-of-line)
20951 (defun org-backward-sentence (&optional arg)
20952 "Go to beginning of sentence, or beginning of table field.
20953 This will call `backward-sentence' or `org-table-beginning-of-field',
20954 depending on context."
20955 (interactive "P")
20956 (cond
20957 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
20958 (t (call-interactively 'backward-sentence))))
20960 (defun org-forward-sentence (&optional arg)
20961 "Go to end of sentence, or end of table field.
20962 This will call `forward-sentence' or `org-table-end-of-field',
20963 depending on context."
20964 (interactive "P")
20965 (cond
20966 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
20967 (t (call-interactively 'forward-sentence))))
20969 (define-key org-mode-map "\M-a" 'org-backward-sentence)
20970 (define-key org-mode-map "\M-e" 'org-forward-sentence)
20972 (defun org-kill-line (&optional arg)
20973 "Kill line, to tags or end of line."
20974 (interactive "P")
20975 (cond
20976 ((or (not org-special-ctrl-k)
20977 (bolp)
20978 (not (org-at-heading-p)))
20979 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
20980 org-ctrl-k-protect-subtree)
20981 (if (or (eq org-ctrl-k-protect-subtree 'error)
20982 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
20983 (error "C-k aborted - would kill hidden subtree")))
20984 (call-interactively
20985 (if (and (boundp 'visual-line-mode) visual-line-mode) 'kill-visual-line 'kill-line)))
20986 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
20987 (kill-region (point) (match-beginning 1))
20988 (org-set-tags nil t))
20989 (t (kill-region (point) (point-at-eol)))))
20991 (define-key org-mode-map "\C-k" 'org-kill-line)
20993 (defun org-yank (&optional arg)
20994 "Yank. If the kill is a subtree, treat it specially.
20995 This command will look at the current kill and check if is a single
20996 subtree, or a series of subtrees[1]. If it passes the test, and if the
20997 cursor is at the beginning of a line or after the stars of a currently
20998 empty headline, then the yank is handled specially. How exactly depends
20999 on the value of the following variables, both set by default.
21001 org-yank-folded-subtrees
21002 When set, the subtree(s) will be folded after insertion, but only
21003 if doing so would now swallow text after the yanked text.
21005 org-yank-adjusted-subtrees
21006 When set, the subtree will be promoted or demoted in order to
21007 fit into the local outline tree structure, which means that the level
21008 will be adjusted so that it becomes the smaller one of the two
21009 *visible* surrounding headings.
21011 Any prefix to this command will cause `yank' to be called directly with
21012 no special treatment. In particular, a simple \\[universal-argument] prefix \
21013 will just
21014 plainly yank the text as it is.
21016 \[1] The test checks if the first non-white line is a heading
21017 and if there are no other headings with fewer stars."
21018 (interactive "P")
21019 (org-yank-generic 'yank arg))
21021 (defun org-yank-generic (command arg)
21022 "Perform some yank-like command.
21024 This function implements the behavior described in the `org-yank'
21025 documentation. However, it has been generalized to work for any
21026 interactive command with similar behavior."
21028 ;; pretend to be command COMMAND
21029 (setq this-command command)
21031 (if arg
21032 (call-interactively command)
21034 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
21035 (and (org-kill-is-subtree-p)
21036 (or (bolp)
21037 (and (looking-at "[ \t]*$")
21038 (string-match
21039 "\\`\\*+\\'"
21040 (buffer-substring (point-at-bol) (point)))))))
21041 swallowp)
21042 (cond
21043 ((and subtreep org-yank-folded-subtrees)
21044 (let ((beg (point))
21045 end)
21046 (if (and subtreep org-yank-adjusted-subtrees)
21047 (org-paste-subtree nil nil 'for-yank)
21048 (call-interactively command))
21050 (setq end (point))
21051 (goto-char beg)
21052 (when (and (bolp) subtreep
21053 (not (setq swallowp
21054 (org-yank-folding-would-swallow-text beg end))))
21055 (org-with-limited-levels
21056 (or (looking-at org-outline-regexp)
21057 (re-search-forward org-outline-regexp-bol end t))
21058 (while (and (< (point) end) (looking-at org-outline-regexp))
21059 (hide-subtree)
21060 (org-cycle-show-empty-lines 'folded)
21061 (condition-case nil
21062 (outline-forward-same-level 1)
21063 (error (goto-char end))))))
21064 (when swallowp
21065 (message
21066 "Inserted text not folded because that would swallow text"))
21068 (goto-char end)
21069 (skip-chars-forward " \t\n\r")
21070 (beginning-of-line 1)
21071 (push-mark beg 'nomsg)))
21072 ((and subtreep org-yank-adjusted-subtrees)
21073 (let ((beg (point-at-bol)))
21074 (org-paste-subtree nil nil 'for-yank)
21075 (push-mark beg 'nomsg)))
21077 (call-interactively command))))))
21079 (defun org-yank-folding-would-swallow-text (beg end)
21080 "Would hide-subtree at BEG swallow any text after END?"
21081 (let (level)
21082 (org-with-limited-levels
21083 (save-excursion
21084 (goto-char beg)
21085 (when (or (looking-at org-outline-regexp)
21086 (re-search-forward org-outline-regexp-bol end t))
21087 (setq level (org-outline-level)))
21088 (goto-char end)
21089 (skip-chars-forward " \t\r\n\v\f")
21090 (if (or (eobp)
21091 (and (bolp) (looking-at org-outline-regexp)
21092 (<= (org-outline-level) level)))
21093 nil ; Nothing would be swallowed
21094 t))))) ; something would swallow
21096 (define-key org-mode-map "\C-y" 'org-yank)
21098 (defun org-truely-invisible-p ()
21099 "Check if point is at a character currently not visible.
21100 This version does not only check the character property, but also
21101 `visible-mode'."
21102 ;; Early versions of noutline don't have `outline-invisible-p'.
21103 (if (org-bound-and-true-p visible-mode)
21105 (outline-invisible-p)))
21107 (defun org-invisible-p2 ()
21108 "Check if point is at a character currently not visible."
21109 (save-excursion
21110 (if (and (eolp) (not (bobp))) (backward-char 1))
21111 ;; Early versions of noutline don't have `outline-invisible-p'.
21112 (outline-invisible-p)))
21114 (defun org-back-to-heading (&optional invisible-ok)
21115 "Call `outline-back-to-heading', but provide a better error message."
21116 (condition-case nil
21117 (outline-back-to-heading invisible-ok)
21118 (error (error "Before first headline at position %d in buffer %s"
21119 (point) (current-buffer)))))
21121 (defun org-beginning-of-defun ()
21122 "Go to the beginning of the subtree, i.e. back to the heading."
21123 (org-back-to-heading))
21124 (defun org-end-of-defun ()
21125 "Go to the end of the subtree."
21126 (org-end-of-subtree nil t))
21128 (defun org-before-first-heading-p ()
21129 "Before first heading?"
21130 (save-excursion
21131 (end-of-line)
21132 (null (re-search-backward org-outline-regexp-bol nil t))))
21134 (defun org-at-heading-p (&optional ignored)
21135 (outline-on-heading-p t))
21136 ;; Compatibility alias with Org versions < 7.8.03
21137 (defalias 'org-on-heading-p 'org-at-heading-p)
21139 (defun org-at-drawer-p nil
21140 "Is cursor at a drawer keyword?"
21141 (save-excursion
21142 (move-beginning-of-line 1)
21143 (looking-at org-drawer-regexp)))
21145 (defun org-at-block-p nil
21146 "Is cursor at a block keyword?"
21147 (save-excursion
21148 (move-beginning-of-line 1)
21149 (looking-at org-block-regexp)))
21151 (defun org-point-at-end-of-empty-headline ()
21152 "If point is at the end of an empty headline, return t, else nil.
21153 If the heading only contains a TODO keyword, it is still still considered
21154 empty."
21155 (and (looking-at "[ \t]*$")
21156 (when org-todo-line-regexp
21157 (save-excursion
21158 (beginning-of-line 1)
21159 (let ((case-fold-search nil))
21160 (looking-at org-todo-line-regexp)
21161 (string= (match-string 3) ""))))))
21163 (defun org-at-heading-or-item-p ()
21164 (or (org-at-heading-p) (org-at-item-p)))
21166 (defun org-at-target-p ()
21167 (or (org-in-regexp org-radio-target-regexp)
21168 (org-in-regexp org-target-regexp)))
21169 ;; Compatibility alias with Org versions < 7.8.03
21170 (defalias 'org-on-target-p 'org-at-target-p)
21172 (defun org-up-heading-all (arg)
21173 "Move to the heading line of which the present line is a subheading.
21174 This function considers both visible and invisible heading lines.
21175 With argument, move up ARG levels."
21176 (if (fboundp 'outline-up-heading-all)
21177 (outline-up-heading-all arg) ; emacs 21 version of outline.el
21178 (outline-up-heading arg t))) ; emacs 22 version of outline.el
21180 (defun org-up-heading-safe ()
21181 "Move to the heading line of which the present line is a subheading.
21182 This version will not throw an error. It will return the level of the
21183 headline found, or nil if no higher level is found.
21185 Also, this function will be a lot faster than `outline-up-heading',
21186 because it relies on stars being the outline starters. This can really
21187 make a significant difference in outlines with very many siblings."
21188 (let (start-level re)
21189 (org-back-to-heading t)
21190 (setq start-level (funcall outline-level))
21191 (if (equal start-level 1)
21193 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
21194 (if (re-search-backward re nil t)
21195 (funcall outline-level)))))
21197 (defun org-first-sibling-p ()
21198 "Is this heading the first child of its parents?"
21199 (interactive)
21200 (let ((re org-outline-regexp-bol)
21201 level l)
21202 (unless (org-at-heading-p t)
21203 (error "Not at a heading"))
21204 (setq level (funcall outline-level))
21205 (save-excursion
21206 (if (not (re-search-backward re nil t))
21208 (setq l (funcall outline-level))
21209 (< l level)))))
21211 (defun org-goto-sibling (&optional previous)
21212 "Goto the next sibling, even if it is invisible.
21213 When PREVIOUS is set, go to the previous sibling instead. Returns t
21214 when a sibling was found. When none is found, return nil and don't
21215 move point."
21216 (let ((fun (if previous 're-search-backward 're-search-forward))
21217 (pos (point))
21218 (re org-outline-regexp-bol)
21219 level l)
21220 (when (condition-case nil (org-back-to-heading t) (error nil))
21221 (setq level (funcall outline-level))
21222 (catch 'exit
21223 (or previous (forward-char 1))
21224 (while (funcall fun re nil t)
21225 (setq l (funcall outline-level))
21226 (when (< l level) (goto-char pos) (throw 'exit nil))
21227 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
21228 (goto-char pos)
21229 nil))))
21231 (defun org-show-siblings ()
21232 "Show all siblings of the current headline."
21233 (save-excursion
21234 (while (org-goto-sibling) (org-flag-heading nil)))
21235 (save-excursion
21236 (while (org-goto-sibling 'previous)
21237 (org-flag-heading nil))))
21239 (defun org-goto-first-child ()
21240 "Goto the first child, even if it is invisible.
21241 Return t when a child was found. Otherwise don't move point and
21242 return nil."
21243 (let (level (pos (point)) (re org-outline-regexp-bol))
21244 (when (condition-case nil (org-back-to-heading t) (error nil))
21245 (setq level (outline-level))
21246 (forward-char 1)
21247 (if (and (re-search-forward re nil t) (> (outline-level) level))
21248 (progn (goto-char (match-beginning 0)) t)
21249 (goto-char pos) nil))))
21251 (defun org-show-hidden-entry ()
21252 "Show an entry where even the heading is hidden."
21253 (save-excursion
21254 (org-show-entry)))
21256 (defun org-flag-heading (flag &optional entry)
21257 "Flag the current heading. FLAG non-nil means make invisible.
21258 When ENTRY is non-nil, show the entire entry."
21259 (save-excursion
21260 (org-back-to-heading t)
21261 ;; Check if we should show the entire entry
21262 (if entry
21263 (progn
21264 (org-show-entry)
21265 (save-excursion
21266 (and (outline-next-heading)
21267 (org-flag-heading nil))))
21268 (outline-flag-region (max (point-min) (1- (point)))
21269 (save-excursion (outline-end-of-heading) (point))
21270 flag))))
21272 (defun org-get-next-sibling ()
21273 "Move to next heading of the same level, and return point.
21274 If there is no such heading, return nil.
21275 This is like outline-next-sibling, but invisible headings are ok."
21276 (let ((level (funcall outline-level)))
21277 (outline-next-heading)
21278 (while (and (not (eobp)) (> (funcall outline-level) level))
21279 (outline-next-heading))
21280 (if (or (eobp) (< (funcall outline-level) level))
21282 (point))))
21284 (defun org-get-last-sibling ()
21285 "Move to previous heading of the same level, and return point.
21286 If there is no such heading, return nil."
21287 (let ((opoint (point))
21288 (level (funcall outline-level)))
21289 (outline-previous-heading)
21290 (when (and (/= (point) opoint) (outline-on-heading-p t))
21291 (while (and (> (funcall outline-level) level)
21292 (not (bobp)))
21293 (outline-previous-heading))
21294 (if (< (funcall outline-level) level)
21296 (point)))))
21298 (defun org-end-of-subtree (&optional invisible-OK to-heading)
21299 ;; This contains an exact copy of the original function, but it uses
21300 ;; `org-back-to-heading', to make it work also in invisible
21301 ;; trees. And is uses an invisible-OK argument.
21302 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
21303 ;; Furthermore, when used inside Org, finding the end of a large subtree
21304 ;; with many children and grandchildren etc, this can be much faster
21305 ;; than the outline version.
21306 (org-back-to-heading invisible-OK)
21307 (let ((first t)
21308 (level (funcall outline-level)))
21309 (if (and (derived-mode-p 'org-mode) (< level 1000))
21310 ;; A true heading (not a plain list item), in Org-mode
21311 ;; This means we can easily find the end by looking
21312 ;; only for the right number of stars. Using a regexp to do
21313 ;; this is so much faster than using a Lisp loop.
21314 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
21315 (forward-char 1)
21316 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
21317 ;; something else, do it the slow way
21318 (while (and (not (eobp))
21319 (or first (> (funcall outline-level) level)))
21320 (setq first nil)
21321 (outline-next-heading)))
21322 (unless to-heading
21323 (if (memq (preceding-char) '(?\n ?\^M))
21324 (progn
21325 ;; Go to end of line before heading
21326 (forward-char -1)
21327 (if (memq (preceding-char) '(?\n ?\^M))
21328 ;; leave blank line before heading
21329 (forward-char -1))))))
21330 (point))
21332 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
21333 "Use Org version in org-mode, for dramatic speed-up."
21334 (if (derived-mode-p 'org-mode)
21335 (progn
21336 (org-end-of-subtree nil t)
21337 (unless (eobp) (backward-char 1)))
21338 ad-do-it))
21340 (defun org-end-of-meta-data-and-drawers ()
21341 "Jump to the first text after meta data and drawers in the current entry.
21342 This will move over empty lines, lines with planning time stamps,
21343 clocking lines, and drawers."
21344 (org-back-to-heading t)
21345 (let ((end (save-excursion (outline-next-heading) (point)))
21346 (re (concat "\\(" org-drawer-regexp "\\)"
21347 "\\|" "[ \t]*" org-keyword-time-regexp)))
21348 (forward-line 1)
21349 (while (re-search-forward re end t)
21350 (if (not (match-end 1))
21351 ;; empty or planning line
21352 (forward-line 1)
21353 ;; a drawer, find the end
21354 (re-search-forward "^[ \t]*:END:" end 'move)
21355 (forward-line 1)))
21356 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
21357 (point)))
21359 (defun org-forward-same-level (arg &optional invisible-ok)
21360 "Move forward to the arg'th subheading at same level as this one.
21361 Stop at the first and last subheadings of a superior heading.
21362 Normally this only looks at visible headings, but when INVISIBLE-OK is non-nil
21363 it wil also look at invisible ones."
21364 (interactive "p")
21365 (org-back-to-heading invisible-ok)
21366 (org-at-heading-p)
21367 (let* ((level (- (match-end 0) (match-beginning 0) 1))
21368 (re (format "^\\*\\{1,%d\\} " level))
21370 (forward-char 1)
21371 (while (> arg 0)
21372 (while (and (re-search-forward re nil 'move)
21373 (setq l (- (match-end 0) (match-beginning 0) 1))
21374 (= l level)
21375 (not invisible-ok)
21376 (progn (backward-char 1) (outline-invisible-p)))
21377 (if (< l level) (setq arg 1)))
21378 (setq arg (1- arg)))
21379 (beginning-of-line 1)))
21381 (defun org-backward-same-level (arg &optional invisible-ok)
21382 "Move backward to the arg'th subheading at same level as this one.
21383 Stop at the first and last subheadings of a superior heading."
21384 (interactive "p")
21385 (org-back-to-heading)
21386 (org-at-heading-p)
21387 (let* ((level (- (match-end 0) (match-beginning 0) 1))
21388 (re (format "^\\*\\{1,%d\\} " level))
21390 (while (> arg 0)
21391 (while (and (re-search-backward re nil 'move)
21392 (setq l (- (match-end 0) (match-beginning 0) 1))
21393 (= l level)
21394 (not invisible-ok)
21395 (outline-invisible-p))
21396 (if (< l level) (setq arg 1)))
21397 (setq arg (1- arg)))))
21399 (defun org-show-subtree ()
21400 "Show everything after this heading at deeper levels."
21401 (interactive)
21402 (outline-flag-region
21403 (point)
21404 (save-excursion
21405 (org-end-of-subtree t t))
21406 nil))
21408 (defun org-show-entry ()
21409 "Show the body directly following this heading.
21410 Show the heading too, if it is currently invisible."
21411 (interactive)
21412 (save-excursion
21413 (condition-case nil
21414 (progn
21415 (org-back-to-heading t)
21416 (outline-flag-region
21417 (max (point-min) (1- (point)))
21418 (save-excursion
21419 (if (re-search-forward
21420 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
21421 (match-beginning 1)
21422 (point-max)))
21423 nil)
21424 (org-cycle-hide-drawers 'children))
21425 (error nil))))
21427 (defun org-make-options-regexp (kwds &optional extra)
21428 "Make a regular expression for keyword lines."
21429 (concat
21431 "#?[ \t]*\\+\\("
21432 (mapconcat 'regexp-quote kwds "\\|")
21433 (if extra (concat "\\|" extra))
21434 "\\):[ \t]*"
21435 "\\(.*\\)"))
21437 ;; Make isearch reveal the necessary context
21438 (defun org-isearch-end ()
21439 "Reveal context after isearch exits."
21440 (when isearch-success ; only if search was successful
21441 (if (featurep 'xemacs)
21442 ;; Under XEmacs, the hook is run in the correct place,
21443 ;; we directly show the context.
21444 (org-show-context 'isearch)
21445 ;; In Emacs the hook runs *before* restoring the overlays.
21446 ;; So we have to use a one-time post-command-hook to do this.
21447 ;; (Emacs 22 has a special variable, see function `org-mode')
21448 (unless (and (boundp 'isearch-mode-end-hook-quit)
21449 isearch-mode-end-hook-quit)
21450 ;; Only when the isearch was not quitted.
21451 (org-add-hook 'post-command-hook 'org-isearch-post-command
21452 'append 'local)))))
21454 (defun org-isearch-post-command ()
21455 "Remove self from hook, and show context."
21456 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
21457 (org-show-context 'isearch))
21460 ;;;; Integration with and fixes for other packages
21462 ;;; Imenu support
21464 (defvar org-imenu-markers nil
21465 "All markers currently used by Imenu.")
21466 (make-variable-buffer-local 'org-imenu-markers)
21468 (defun org-imenu-new-marker (&optional pos)
21469 "Return a new marker for use by Imenu, and remember the marker."
21470 (let ((m (make-marker)))
21471 (move-marker m (or pos (point)))
21472 (push m org-imenu-markers)
21475 (defun org-imenu-get-tree ()
21476 "Produce the index for Imenu."
21477 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
21478 (setq org-imenu-markers nil)
21479 (let* ((n org-imenu-depth)
21480 (re (concat "^" (org-get-limited-outline-regexp)))
21481 (subs (make-vector (1+ n) nil))
21482 (last-level 0)
21483 m level head)
21484 (save-excursion
21485 (save-restriction
21486 (widen)
21487 (goto-char (point-max))
21488 (while (re-search-backward re nil t)
21489 (setq level (org-reduced-level (funcall outline-level)))
21490 (when (and (<= level n)
21491 (looking-at org-complex-heading-regexp))
21492 (setq head (org-link-display-format
21493 (org-match-string-no-properties 4))
21494 m (org-imenu-new-marker))
21495 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
21496 (if (>= level last-level)
21497 (push (cons head m) (aref subs level))
21498 (push (cons head (aref subs (1+ level))) (aref subs level))
21499 (loop for i from (1+ level) to n do (aset subs i nil)))
21500 (setq last-level level)))))
21501 (aref subs 1)))
21503 (eval-after-load "imenu"
21504 '(progn
21505 (add-hook 'imenu-after-jump-hook
21506 (lambda ()
21507 (if (derived-mode-p 'org-mode)
21508 (org-show-context 'org-goto))))))
21510 (defun org-link-display-format (link)
21511 "Replace a link with either the description, or the link target
21512 if no description is present"
21513 (save-match-data
21514 (if (string-match org-bracket-link-analytic-regexp link)
21515 (replace-match (if (match-end 5)
21516 (match-string 5 link)
21517 (concat (match-string 1 link)
21518 (match-string 3 link)))
21519 nil t link)
21520 link)))
21522 (defun org-toggle-link-display ()
21523 "Toggle the literal or descriptive display of links."
21524 (interactive)
21525 (if org-descriptive-links
21526 (progn (org-remove-from-invisibility-spec '(org-link))
21527 (org-restart-font-lock)
21528 (setq org-descriptive-links nil))
21529 (progn (add-to-invisibility-spec '(org-link))
21530 (org-restart-font-lock)
21531 (setq org-descriptive-links t))))
21533 ;; Speedbar support
21535 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
21536 "Overlay marking the agenda restriction line in speedbar.")
21537 (overlay-put org-speedbar-restriction-lock-overlay
21538 'face 'org-agenda-restriction-lock)
21539 (overlay-put org-speedbar-restriction-lock-overlay
21540 'help-echo "Agendas are currently limited to this item.")
21541 (org-detach-overlay org-speedbar-restriction-lock-overlay)
21543 (defun org-speedbar-set-agenda-restriction ()
21544 "Restrict future agenda commands to the location at point in speedbar.
21545 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
21546 (interactive)
21547 (require 'org-agenda)
21548 (let (p m tp np dir txt)
21549 (cond
21550 ((setq p (text-property-any (point-at-bol) (point-at-eol)
21551 'org-imenu t))
21552 (setq m (get-text-property p 'org-imenu-marker))
21553 (with-current-buffer (marker-buffer m)
21554 (goto-char m)
21555 (org-agenda-set-restriction-lock 'subtree)))
21556 ((setq p (text-property-any (point-at-bol) (point-at-eol)
21557 'speedbar-function 'speedbar-find-file))
21558 (setq tp (previous-single-property-change
21559 (1+ p) 'speedbar-function)
21560 np (next-single-property-change
21561 tp 'speedbar-function)
21562 dir (speedbar-line-directory)
21563 txt (buffer-substring-no-properties (or tp (point-min))
21564 (or np (point-max))))
21565 (with-current-buffer (find-file-noselect
21566 (let ((default-directory dir))
21567 (expand-file-name txt)))
21568 (unless (derived-mode-p 'org-mode)
21569 (error "Cannot restrict to non-Org-mode file"))
21570 (org-agenda-set-restriction-lock 'file)))
21571 (t (error "Don't know how to restrict Org-mode's agenda")))
21572 (move-overlay org-speedbar-restriction-lock-overlay
21573 (point-at-bol) (point-at-eol))
21574 (setq current-prefix-arg nil)
21575 (org-agenda-maybe-redo)))
21577 (eval-after-load "speedbar"
21578 '(progn
21579 (speedbar-add-supported-extension ".org")
21580 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
21581 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
21582 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
21583 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
21584 (add-hook 'speedbar-visiting-tag-hook
21585 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
21587 ;;; Fixes and Hacks for problems with other packages
21589 ;; Make flyspell not check words in links, to not mess up our keymap
21590 (defun org-mode-flyspell-verify ()
21591 "Don't let flyspell put overlays at active buttons, or on
21592 {todo,all-time,additional-option-like}-keywords."
21593 (let ((pos (max (1- (point)) (point-min)))
21594 (word (thing-at-point 'word)))
21595 (and (not (get-text-property pos 'keymap))
21596 (not (get-text-property pos 'org-no-flyspell))
21597 (not (member word org-todo-keywords-1))
21598 (not (member word org-all-time-keywords))
21599 (not (member word org-additional-option-like-keywords)))))
21601 (defun org-remove-flyspell-overlays-in (beg end)
21602 "Remove flyspell overlays in region."
21603 (and (org-bound-and-true-p flyspell-mode)
21604 (fboundp 'flyspell-delete-region-overlays)
21605 (flyspell-delete-region-overlays beg end))
21606 (add-text-properties beg end '(org-no-flyspell t)))
21608 ;; Make `bookmark-jump' shows the jump location if it was hidden.
21609 (eval-after-load "bookmark"
21610 '(if (boundp 'bookmark-after-jump-hook)
21611 ;; We can use the hook
21612 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
21613 ;; Hook not available, use advice
21614 (defadvice bookmark-jump (after org-make-visible activate)
21615 "Make the position visible."
21616 (org-bookmark-jump-unhide))))
21618 ;; Make sure saveplace shows the location if it was hidden
21619 (eval-after-load "saveplace"
21620 '(defadvice save-place-find-file-hook (after org-make-visible activate)
21621 "Make the position visible."
21622 (org-bookmark-jump-unhide)))
21624 ;; Make sure ecb shows the location if it was hidden
21625 (eval-after-load "ecb"
21626 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
21627 "Make hierarchy visible when jumping into location from ECB tree buffer."
21628 (if (derived-mode-p 'org-mode)
21629 (org-show-context))))
21631 (defun org-bookmark-jump-unhide ()
21632 "Unhide the current position, to show the bookmark location."
21633 (and (derived-mode-p 'org-mode)
21634 (or (outline-invisible-p)
21635 (save-excursion (goto-char (max (point-min) (1- (point))))
21636 (outline-invisible-p)))
21637 (org-show-context 'bookmark-jump)))
21639 ;; Make session.el ignore our circular variable
21640 (eval-after-load "session"
21641 '(add-to-list 'session-globals-exclude 'org-mark-ring))
21643 ;;;; Experimental code
21645 (defun org-closed-in-range ()
21646 "Sparse tree of items closed in a certain time range.
21647 Still experimental, may disappear in the future."
21648 (interactive)
21649 ;; Get the time interval from the user.
21650 (let* ((time1 (org-float-time
21651 (org-read-date nil 'to-time nil "Starting date: ")))
21652 (time2 (org-float-time
21653 (org-read-date nil 'to-time nil "End date:")))
21654 ;; callback function
21655 (callback (lambda ()
21656 (let ((time
21657 (org-float-time
21658 (apply 'encode-time
21659 (org-parse-time-string
21660 (match-string 1))))))
21661 ;; check if time in interval
21662 (and (>= time time1) (<= time time2))))))
21663 ;; make tree, check each match with the callback
21664 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
21666 ;;;; Finish up
21668 (provide 'org)
21670 (run-hooks 'org-load-hook)
21672 ;;; org.el ends here