org.el (org-goto): Fix docstring and document what C-u does.
[org-mode/org-mode-NeilSmithlineMods.git] / lisp / org.el
blob66bc74ee5e4bda6007fb204440c9d6b7f05c7263
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)
4944 ;;;###autoload
4945 (define-derived-mode org-mode outline-mode "Org"
4946 "Outline-based notes management and organizer, alias
4947 \"Carsten's outline-mode for keeping track of everything.\"
4949 Org-mode develops organizational tasks around a NOTES file which
4950 contains information about projects as plain text. Org-mode is
4951 implemented on top of outline-mode, which is ideal to keep the content
4952 of large files well structured. It supports ToDo items, deadlines and
4953 time stamps, which magically appear in the diary listing of the Emacs
4954 calendar. Tables are easily created with a built-in table editor.
4955 Plain text URL-like links connect to websites, emails (VM), Usenet
4956 messages (Gnus), BBDB entries, and any files related to the project.
4957 For printing and sharing of notes, an Org-mode file (or a part of it)
4958 can be exported as a structured ASCII or HTML file.
4960 The following commands are available:
4962 \\{org-mode-map}"
4964 ;; Get rid of Outline menus, they are not needed
4965 ;; Need to do this here because define-derived-mode sets up
4966 ;; the keymap so late. Still, it is a waste to call this each time
4967 ;; we switch another buffer into org-mode.
4968 (if (featurep 'xemacs)
4969 (when (boundp 'outline-mode-menu-heading)
4970 ;; Assume this is Greg's port, it uses easymenu
4971 (easy-menu-remove outline-mode-menu-heading)
4972 (easy-menu-remove outline-mode-menu-show)
4973 (easy-menu-remove outline-mode-menu-hide))
4974 (define-key org-mode-map [menu-bar headings] 'undefined)
4975 (define-key org-mode-map [menu-bar hide] 'undefined)
4976 (define-key org-mode-map [menu-bar show] 'undefined))
4978 (org-load-modules-maybe)
4979 (easy-menu-add org-org-menu)
4980 (easy-menu-add org-tbl-menu)
4981 (org-install-agenda-files-menu)
4982 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
4983 (add-to-invisibility-spec '(org-cwidth))
4984 (add-to-invisibility-spec '(org-hide-block . t))
4985 (when (featurep 'xemacs)
4986 (org-set-local 'line-move-ignore-invisible t))
4987 (org-set-local 'outline-regexp org-outline-regexp)
4988 (org-set-local 'outline-level 'org-outline-level)
4989 (setq bidi-paragraph-direction 'left-to-right)
4990 (when (and org-ellipsis
4991 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
4992 (fboundp 'make-glyph-code))
4993 (unless org-display-table
4994 (setq org-display-table (make-display-table)))
4995 (set-display-table-slot
4996 org-display-table 4
4997 (vconcat (mapcar
4998 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
4999 org-ellipsis)))
5000 (if (stringp org-ellipsis) org-ellipsis "..."))))
5001 (setq buffer-display-table org-display-table))
5002 (org-set-regexps-and-options)
5003 (when (and org-tag-faces (not org-tags-special-faces-re))
5004 ;; tag faces set outside customize.... force initialization.
5005 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5006 ;; Calc embedded
5007 (org-set-local 'calc-embedded-open-mode "# ")
5008 (modify-syntax-entry ?@ "w")
5009 (if org-startup-truncated (setq truncate-lines t))
5010 (org-set-local 'font-lock-unfontify-region-function
5011 'org-unfontify-region)
5012 ;; Activate before-change-function
5013 (org-set-local 'org-table-may-need-update t)
5014 (org-add-hook 'before-change-functions 'org-before-change-function nil
5015 'local)
5016 ;; Check for running clock before killing a buffer
5017 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5018 ;; Paragraphs and auto-filling
5019 (org-set-autofill-regexps)
5020 (setq indent-line-function 'org-indent-line-function)
5021 (org-update-radio-target-regexp)
5022 ;; Beginning/end of defun
5023 (org-set-local 'beginning-of-defun-function 'org-beginning-of-defun)
5024 (org-set-local 'end-of-defun-function 'org-end-of-defun)
5025 ;; Next error for sparse trees
5026 (org-set-local 'next-error-function 'org-occur-next-match)
5027 ;; Make sure dependence stuff works reliably, even for users who set it
5028 ;; too late :-(
5029 (if org-enforce-todo-dependencies
5030 (add-hook 'org-blocker-hook
5031 'org-block-todo-from-children-or-siblings-or-parent)
5032 (remove-hook 'org-blocker-hook
5033 'org-block-todo-from-children-or-siblings-or-parent))
5034 (if org-enforce-todo-checkbox-dependencies
5035 (add-hook 'org-blocker-hook
5036 'org-block-todo-from-checkboxes)
5037 (remove-hook 'org-blocker-hook
5038 'org-block-todo-from-checkboxes))
5040 ;; Comment characters
5041 (org-set-local 'comment-start "#")
5042 (org-set-local 'comment-padding " ")
5044 ;; Align options lines
5045 (org-set-local
5046 'align-mode-rules-list
5047 '((org-in-buffer-settings
5048 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5049 (modes . '(org-mode)))))
5051 ;; Imenu
5052 (org-set-local 'imenu-create-index-function
5053 'org-imenu-get-tree)
5055 ;; Make isearch reveal context
5056 (if (or (featurep 'xemacs)
5057 (not (boundp 'outline-isearch-open-invisible-function)))
5058 ;; Emacs 21 and XEmacs make use of the hook
5059 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5060 ;; Emacs 22 deals with this through a special variable
5061 (org-set-local 'outline-isearch-open-invisible-function
5062 (lambda (&rest ignore) (org-show-context 'isearch))))
5064 ;; Turn on org-beamer-mode?
5065 (and org-startup-with-beamer-mode (org-beamer-mode 1))
5067 ;; Setup the pcomplete hooks
5068 (set (make-local-variable 'pcomplete-command-completion-function)
5069 'org-pcomplete-initial)
5070 (set (make-local-variable 'pcomplete-command-name-function)
5071 'org-command-at-point)
5072 (set (make-local-variable 'pcomplete-default-completion-function)
5073 'ignore)
5074 (set (make-local-variable 'pcomplete-parse-arguments-function)
5075 'org-parse-arguments)
5076 (set (make-local-variable 'pcomplete-termination-string) "")
5077 (when (>= emacs-major-version 23)
5078 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5080 ;; If empty file that did not turn on org-mode automatically, make it to.
5081 (if (and org-insert-mode-line-in-empty-file
5082 (org-called-interactively-p 'any)
5083 (= (point-min) (point-max)))
5084 (insert "# -*- mode: org -*-\n\n"))
5085 (unless org-inhibit-startup
5086 (when org-startup-align-all-tables
5087 (let ((bmp (buffer-modified-p)))
5088 (org-table-map-tables 'org-table-align 'quietly)
5089 (set-buffer-modified-p bmp)))
5090 (when org-startup-with-inline-images
5091 (org-display-inline-images))
5092 (when org-startup-indented
5093 (require 'org-indent)
5094 (org-indent-mode 1))
5095 (unless org-inhibit-startup-visibility-stuff
5096 (org-set-startup-visibility))))
5098 (when (fboundp 'abbrev-table-put)
5099 (abbrev-table-put org-mode-abbrev-table
5100 :parents (list text-mode-abbrev-table)))
5102 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5104 (defun org-current-time ()
5105 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
5106 (if (> (car org-time-stamp-rounding-minutes) 1)
5107 (let ((r (car org-time-stamp-rounding-minutes))
5108 (time (decode-time)))
5109 (apply 'encode-time
5110 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5111 (nthcdr 2 time))))
5112 (current-time)))
5114 (defun org-today ()
5115 "Return today date, considering `org-extend-today-until'."
5116 (time-to-days
5117 (time-subtract (current-time)
5118 (list 0 (* 3600 org-extend-today-until) 0))))
5120 ;;;; Font-Lock stuff, including the activators
5122 (defvar org-mouse-map (make-sparse-keymap))
5123 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5124 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5125 (when org-mouse-1-follows-link
5126 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5127 (when org-tab-follows-link
5128 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5129 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5131 (require 'font-lock)
5133 (defconst org-non-link-chars "]\t\n\r<>")
5134 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5135 "shell" "elisp" "doi" "message"))
5136 (defvar org-link-types-re nil
5137 "Matches a link that has a url-like prefix like \"http:\"")
5138 (defvar org-link-re-with-space nil
5139 "Matches a link with spaces, optional angular brackets around it.")
5140 (defvar org-link-re-with-space2 nil
5141 "Matches a link with spaces, optional angular brackets around it.")
5142 (defvar org-link-re-with-space3 nil
5143 "Matches a link with spaces, only for internal part in bracket links.")
5144 (defvar org-angle-link-re nil
5145 "Matches link with angular brackets, spaces are allowed.")
5146 (defvar org-plain-link-re nil
5147 "Matches plain link, without spaces.")
5148 (defvar org-bracket-link-regexp nil
5149 "Matches a link in double brackets.")
5150 (defvar org-bracket-link-analytic-regexp nil
5151 "Regular expression used to analyze links.
5152 Here is what the match groups contain after a match:
5153 1: http:
5154 2: http
5155 3: path
5156 4: [desc]
5157 5: desc")
5158 (defvar org-bracket-link-analytic-regexp++ nil
5159 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5160 (defvar org-any-link-re nil
5161 "Regular expression matching any link.")
5163 (defcustom org-match-sexp-depth 3
5164 "Number of stacked braces for sub/superscript matching.
5165 This has to be set before loading org.el to be effective."
5166 :group 'org-export-translation ; ??????????????????????????/
5167 :type 'integer)
5169 (defun org-create-multibrace-regexp (left right n)
5170 "Create a regular expression which will match a balanced sexp.
5171 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5172 as single character strings.
5173 The regexp returned will match the entire expression including the
5174 delimiters. It will also define a single group which contains the
5175 match except for the outermost delimiters. The maximum depth of
5176 stacked delimiters is N. Escaping delimiters is not possible."
5177 (let* ((nothing (concat "[^" left right "]*?"))
5178 (or "\\|")
5179 (re nothing)
5180 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5181 (while (> n 1)
5182 (setq n (1- n)
5183 re (concat re or next)
5184 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5185 (concat left "\\(" re "\\)" right)))
5187 (defvar org-match-substring-regexp
5188 (concat
5189 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5190 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5191 "\\|"
5192 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5193 "\\|"
5194 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5195 "The regular expression matching a sub- or superscript.")
5197 (defvar org-match-substring-with-braces-regexp
5198 (concat
5199 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5200 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5201 "\\)")
5202 "The regular expression matching a sub- or superscript, forcing braces.")
5204 (defun org-make-link-regexps ()
5205 "Update the link regular expressions.
5206 This should be called after the variable `org-link-types' has changed."
5207 (setq org-link-types-re
5208 (concat
5209 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5210 org-link-re-with-space
5211 (concat
5212 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5213 "\\([^" org-non-link-chars " ]"
5214 "[^" org-non-link-chars "]*"
5215 "[^" org-non-link-chars " ]\\)>?")
5216 org-link-re-with-space2
5217 (concat
5218 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5219 "\\([^" org-non-link-chars " ]"
5220 "[^\t\n\r]*"
5221 "[^" org-non-link-chars " ]\\)>?")
5222 org-link-re-with-space3
5223 (concat
5224 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5225 "\\([^" org-non-link-chars " ]"
5226 "[^\t\n\r]*\\)")
5227 org-angle-link-re
5228 (concat
5229 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5230 "\\([^" org-non-link-chars " ]"
5231 "[^" org-non-link-chars "]*"
5232 "\\)>")
5233 org-plain-link-re
5234 (concat
5235 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5236 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5237 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5238 org-bracket-link-regexp
5239 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5240 org-bracket-link-analytic-regexp
5241 (concat
5242 "\\[\\["
5243 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5244 "\\([^]]+\\)"
5245 "\\]"
5246 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5247 "\\]")
5248 org-bracket-link-analytic-regexp++
5249 (concat
5250 "\\[\\["
5251 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5252 "\\([^]]+\\)"
5253 "\\]"
5254 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5255 "\\]")
5256 org-any-link-re
5257 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5258 org-angle-link-re "\\)\\|\\("
5259 org-plain-link-re "\\)")))
5261 (org-make-link-regexps)
5263 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5264 "Regular expression for fast time stamp matching.")
5265 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5266 "Regular expression for fast time stamp matching.")
5267 (defconst org-ts-regexp0
5268 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5269 "Regular expression matching time strings for analysis.
5270 This one does not require the space after the date, so it can be used
5271 on a string that terminates immediately after the date.")
5272 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5273 "Regular expression matching time strings for analysis.")
5274 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5275 "Regular expression matching time stamps, with groups.")
5276 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5277 "Regular expression matching time stamps (also [..]), with groups.")
5278 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5279 "Regular expression matching a time stamp range.")
5280 (defconst org-tr-regexp-both
5281 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5282 "Regular expression matching a time stamp range.")
5283 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5284 org-ts-regexp "\\)?")
5285 "Regular expression matching a time stamp or time stamp range.")
5286 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5287 org-ts-regexp-both "\\)?")
5288 "Regular expression matching a time stamp or time stamp range.
5289 The time stamps may be either active or inactive.")
5291 (defvar org-emph-face nil)
5293 (defun org-do-emphasis-faces (limit)
5294 "Run through the buffer and add overlays to emphasized strings."
5295 (let (rtn a)
5296 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5297 (if (not (= (char-after (match-beginning 3))
5298 (char-after (match-beginning 4))))
5299 (progn
5300 (setq rtn t)
5301 (setq a (assoc (match-string 3) org-emphasis-alist))
5302 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5303 'face
5304 (nth 1 a))
5305 (and (nth 4 a)
5306 (org-remove-flyspell-overlays-in
5307 (match-beginning 0) (match-end 0)))
5308 (add-text-properties (match-beginning 2) (match-end 2)
5309 '(font-lock-multiline t org-emphasis t))
5310 (when org-hide-emphasis-markers
5311 (add-text-properties (match-end 4) (match-beginning 5)
5312 '(invisible org-link))
5313 (add-text-properties (match-beginning 3) (match-end 3)
5314 '(invisible org-link)))))
5315 (backward-char 1))
5316 rtn))
5318 (defun org-emphasize (&optional char)
5319 "Insert or change an emphasis, i.e. a font like bold or italic.
5320 If there is an active region, change that region to a new emphasis.
5321 If there is no region, just insert the marker characters and position
5322 the cursor between them.
5323 CHAR should be either the marker character, or the first character of the
5324 HTML tag associated with that emphasis. If CHAR is a space, the means
5325 to remove the emphasis of the selected region.
5326 If char is not given (for example in an interactive call) it
5327 will be prompted for."
5328 (interactive)
5329 (let ((eal org-emphasis-alist) e det
5330 (erc org-emphasis-regexp-components)
5331 (prompt "")
5332 (string "") beg end move tag c s)
5333 (if (org-region-active-p)
5334 (setq beg (region-beginning) end (region-end)
5335 string (buffer-substring beg end))
5336 (setq move t))
5338 (while (setq e (pop eal))
5339 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5340 c (aref tag 0))
5341 (push (cons c (string-to-char (car e))) det)
5342 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5343 (substring tag 1)))))
5344 (setq det (nreverse det))
5345 (unless char
5346 (message "%s" (concat "Emphasis marker or tag:" prompt))
5347 (setq char (read-char-exclusive)))
5348 (setq char (or (cdr (assoc char det)) char))
5349 (if (equal char ?\ )
5350 (setq s "" move nil)
5351 (unless (assoc (char-to-string char) org-emphasis-alist)
5352 (error "No such emphasis marker: \"%c\"" char))
5353 (setq s (char-to-string char)))
5354 (while (and (> (length string) 1)
5355 (equal (substring string 0 1) (substring string -1))
5356 (assoc (substring string 0 1) org-emphasis-alist))
5357 (setq string (substring string 1 -1)))
5358 (setq string (concat s string s))
5359 (if beg (delete-region beg end))
5360 (unless (or (bolp)
5361 (string-match (concat "[" (nth 0 erc) "\n]")
5362 (char-to-string (char-before (point)))))
5363 (insert " "))
5364 (unless (or (eobp)
5365 (string-match (concat "[" (nth 1 erc) "\n]")
5366 (char-to-string (char-after (point)))))
5367 (insert " ") (backward-char 1))
5368 (insert string)
5369 (and move (backward-char 1))))
5371 (defconst org-nonsticky-props
5372 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
5374 (defsubst org-rear-nonsticky-at (pos)
5375 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5377 (defun org-activate-plain-links (limit)
5378 "Run through the buffer and add overlays to links."
5379 (catch 'exit
5380 (let (f)
5381 (if (re-search-forward org-plain-link-re limit t)
5382 (progn
5383 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5384 (setq f (get-text-property (match-beginning 0) 'face))
5385 (if (or (eq f 'org-tag)
5386 (and (listp f) (memq 'org-tag f)))
5388 (add-text-properties (match-beginning 0) (match-end 0)
5389 (list 'mouse-face 'highlight
5390 'face 'org-link
5391 'keymap org-mouse-map))
5392 (org-rear-nonsticky-at (match-end 0)))
5393 t)))))
5395 (defun org-activate-code (limit)
5396 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5397 (progn
5398 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5399 (remove-text-properties (match-beginning 0) (match-end 0)
5400 '(display t invisible t intangible t))
5401 t)))
5403 (defcustom org-src-fontify-natively nil
5404 "When non-nil, fontify code in code blocks."
5405 :type 'boolean
5406 :version "24.1"
5407 :group 'org-appearance
5408 :group 'org-babel)
5410 (defun org-fontify-meta-lines-and-blocks (limit)
5411 (condition-case nil
5412 (org-fontify-meta-lines-and-blocks-1 limit)
5413 (error (message "org-mode fontification error"))))
5415 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5416 "Fontify #+ lines and blocks, in the correct ways."
5417 (let ((case-fold-search t))
5418 (if (re-search-forward
5419 "^\\([ \t]*#\\+\\(\\([a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5420 limit t)
5421 (let ((beg (match-beginning 0))
5422 (block-start (match-end 0))
5423 (block-end nil)
5424 (lang (match-string 7))
5425 (beg1 (line-beginning-position 2))
5426 (dc1 (downcase (match-string 2)))
5427 (dc3 (downcase (match-string 3)))
5428 end end1 quoting block-type ovl)
5429 (cond
5430 ((member dc1 '("html:" "ascii:" "latex:" "docbook:"))
5431 ;; a single line of backend-specific content
5432 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5433 (remove-text-properties (match-beginning 0) (match-end 0)
5434 '(display t invisible t intangible t))
5435 (add-text-properties (match-beginning 1) (match-end 3)
5436 '(font-lock-fontified t face org-meta-line))
5437 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5438 '(font-lock-fontified t face org-block))
5439 ; for backend-specific code
5441 ((and (match-end 4) (equal dc3 "begin"))
5442 ;; Truly a block
5443 (setq block-type (downcase (match-string 5))
5444 quoting (member block-type org-protecting-blocks))
5445 (when (re-search-forward
5446 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5447 nil t) ;; on purpose, we look further than LIMIT
5448 (setq end (min (point-max) (match-end 0))
5449 end1 (min (point-max) (1- (match-beginning 0))))
5450 (setq block-end (match-beginning 0))
5451 (when quoting
5452 (remove-text-properties beg end
5453 '(display t invisible t intangible t)))
5454 (add-text-properties
5455 beg end
5456 '(font-lock-fontified t font-lock-multiline t))
5457 (add-text-properties beg beg1 '(face org-meta-line))
5458 (add-text-properties end1 (min (point-max) (1+ end))
5459 '(face org-meta-line)) ; for end_src
5460 (cond
5461 ((and lang (not (string= lang "")) org-src-fontify-natively)
5462 (org-src-font-lock-fontify-block lang block-start block-end)
5463 ;; remove old background overlays
5464 (mapc (lambda (ov)
5465 (if (eq (overlay-get ov 'face) 'org-block-background)
5466 (delete-overlay ov)))
5467 (overlays-at (/ (+ beg1 block-end) 2)))
5468 ;; add a background overlay
5469 (setq ovl (make-overlay beg1 block-end))
5470 (overlay-put ovl 'face 'org-block-background)
5471 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5472 (quoting
5473 (add-text-properties beg1 (min (point-max) (1+ end1))
5474 '(face org-block))) ; end of source block
5475 ((not org-fontify-quote-and-verse-blocks))
5476 ((string= block-type "quote")
5477 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5478 ((string= block-type "verse")
5479 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5480 (add-text-properties beg beg1 '(face org-block-begin-line))
5481 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5482 '(face org-block-end-line))
5484 ((member dc1 '("title:" "author:" "email:" "date:"))
5485 (add-text-properties
5486 beg (match-end 3)
5487 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5488 '(font-lock-fontified t invisible t)
5489 '(font-lock-fontified t face org-document-info-keyword)))
5490 (add-text-properties
5491 (match-beginning 6) (match-end 6)
5492 (if (string-equal dc1 "title:")
5493 '(font-lock-fontified t face org-document-title)
5494 '(font-lock-fontified t face org-document-info))))
5495 ((not (member (char-after beg) '(?\ ?\t)))
5496 ;; just any other in-buffer setting, but not indented
5497 (add-text-properties
5498 beg (match-end 0)
5499 '(font-lock-fontified t face org-meta-line))
5501 ((or (member dc1 '("begin:" "end:" "caption:" "label:"
5502 "orgtbl:" "tblfm:" "tblname:" "results:"
5503 "call:" "header:" "headers:" "name:"))
5504 (and (match-end 4) (equal dc3 "attr")))
5505 (add-text-properties
5506 beg (match-end 0)
5507 '(font-lock-fontified t face org-meta-line))
5509 ((member dc3 '(" " ""))
5510 (add-text-properties
5511 beg (match-end 0)
5512 '(font-lock-fontified t face font-lock-comment-face)))
5513 (t nil))))))
5515 (defun org-strip-protective-commas (beg end)
5516 "Strip protective commas between BEG and END in the current buffer."
5517 (interactive "r")
5518 (save-excursion
5519 (save-match-data
5520 (goto-char beg)
5521 (let ((front-line (save-excursion
5522 (re-search-forward
5523 "[^[:space:]]" end t)
5524 (goto-char (match-beginning 0))
5525 (current-column))))
5526 (while (re-search-forward "^[ \t]*\\(,\\)\\([*]\\|#\\+\\)" end t)
5527 (goto-char (match-beginning 1))
5528 (when (= (current-column) front-line)
5529 (replace-match "" nil nil nil 1)))))))
5531 (defun org-activate-angle-links (limit)
5532 "Run through the buffer and add overlays to links."
5533 (if (re-search-forward org-angle-link-re limit t)
5534 (progn
5535 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5536 (add-text-properties (match-beginning 0) (match-end 0)
5537 (list 'mouse-face 'highlight
5538 'keymap org-mouse-map))
5539 (org-rear-nonsticky-at (match-end 0))
5540 t)))
5542 (defun org-activate-footnote-links (limit)
5543 "Run through the buffer and add overlays to footnotes."
5544 (let ((fn (org-footnote-next-reference-or-definition limit)))
5545 (when fn
5546 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5547 (org-remove-flyspell-overlays-in beg end)
5548 (add-text-properties beg end
5549 (list 'mouse-face 'highlight
5550 'keymap org-mouse-map
5551 'help-echo
5552 (if (= (point-at-bol) beg)
5553 "Footnote definition"
5554 "Footnote reference")
5555 'font-lock-fontified t
5556 'font-lock-multiline t
5557 'face 'org-footnote))))))
5559 (defun org-activate-bracket-links (limit)
5560 "Run through the buffer and add overlays to bracketed links."
5561 (if (re-search-forward org-bracket-link-regexp limit t)
5562 (let* ((help (concat "LINK: "
5563 (org-match-string-no-properties 1)))
5564 ;; FIXME: above we should remove the escapes.
5565 ;; but that requires another match, protecting match data,
5566 ;; a lot of overhead for font-lock.
5567 (ip (org-maybe-intangible
5568 (list 'invisible 'org-link
5569 'keymap org-mouse-map 'mouse-face 'highlight
5570 'font-lock-multiline t 'help-echo help)))
5571 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5572 'font-lock-multiline t 'help-echo help)))
5573 ;; We need to remove the invisible property here. Table narrowing
5574 ;; may have made some of this invisible.
5575 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5576 (remove-text-properties (match-beginning 0) (match-end 0)
5577 '(invisible nil))
5578 (if (match-end 3)
5579 (progn
5580 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5581 (org-rear-nonsticky-at (match-beginning 3))
5582 (add-text-properties (match-beginning 3) (match-end 3) vp)
5583 (org-rear-nonsticky-at (match-end 3))
5584 (add-text-properties (match-end 3) (match-end 0) ip)
5585 (org-rear-nonsticky-at (match-end 0)))
5586 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5587 (org-rear-nonsticky-at (match-beginning 1))
5588 (add-text-properties (match-beginning 1) (match-end 1) vp)
5589 (org-rear-nonsticky-at (match-end 1))
5590 (add-text-properties (match-end 1) (match-end 0) ip)
5591 (org-rear-nonsticky-at (match-end 0)))
5592 t)))
5594 (defun org-activate-dates (limit)
5595 "Run through the buffer and add overlays to dates."
5596 (if (re-search-forward org-tsr-regexp-both limit t)
5597 (progn
5598 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5599 (add-text-properties (match-beginning 0) (match-end 0)
5600 (list 'mouse-face 'highlight
5601 'keymap org-mouse-map))
5602 (org-rear-nonsticky-at (match-end 0))
5603 (when org-display-custom-times
5604 (if (match-end 3)
5605 (org-display-custom-time (match-beginning 3) (match-end 3)))
5606 (org-display-custom-time (match-beginning 1) (match-end 1)))
5607 t)))
5609 (defvar org-target-link-regexp nil
5610 "Regular expression matching radio targets in plain text.")
5611 (make-variable-buffer-local 'org-target-link-regexp)
5612 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5613 "Regular expression matching a link target.")
5614 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5615 "Regular expression matching a radio target.")
5616 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5617 "Regular expression matching any target.")
5619 (defun org-activate-target-links (limit)
5620 "Run through the buffer and add overlays to target matches."
5621 (when org-target-link-regexp
5622 (let ((case-fold-search t))
5623 (if (re-search-forward org-target-link-regexp limit t)
5624 (progn
5625 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5626 (add-text-properties (match-beginning 0) (match-end 0)
5627 (list 'mouse-face 'highlight
5628 'keymap org-mouse-map
5629 'help-echo "Radio target link"
5630 'org-linked-text t))
5631 (org-rear-nonsticky-at (match-end 0))
5632 t)))))
5634 (defun org-update-radio-target-regexp ()
5635 "Find all radio targets in this file and update the regular expression."
5636 (interactive)
5637 (when (memq 'radio org-activate-links)
5638 (setq org-target-link-regexp
5639 (org-make-target-link-regexp (org-all-targets 'radio)))
5640 (org-restart-font-lock)))
5642 (defun org-hide-wide-columns (limit)
5643 (let (s e)
5644 (setq s (text-property-any (point) (or limit (point-max))
5645 'org-cwidth t))
5646 (when s
5647 (setq e (next-single-property-change s 'org-cwidth))
5648 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5649 (goto-char e)
5650 t)))
5652 (defvar org-latex-and-specials-regexp nil
5653 "Regular expression for highlighting export special stuff.")
5654 (defvar org-match-substring-regexp)
5655 (defvar org-match-substring-with-braces-regexp)
5657 ;; This should be with the exporter code, but we also use if for font-locking
5658 (defconst org-export-html-special-string-regexps
5659 '(("\\\\-" . "&shy;")
5660 ("---\\([^-]\\)" . "&mdash;\\1")
5661 ("--\\([^-]\\)" . "&ndash;\\1")
5662 ("\\.\\.\\." . "&hellip;"))
5663 "Regular expressions for special string conversion.")
5666 (defun org-compute-latex-and-specials-regexp ()
5667 "Compute regular expression for stuff treated specially by exporters."
5668 (if (not org-highlight-latex-fragments-and-specials)
5669 (org-set-local 'org-latex-and-specials-regexp nil)
5670 (require 'org-exp)
5671 (let*
5672 ((matchers (plist-get org-format-latex-options :matchers))
5673 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5674 org-latex-regexps)))
5675 (org-export-allow-BIND nil)
5676 (options (org-combine-plists (org-default-export-plist)
5677 (org-infile-export-plist)))
5678 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5679 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5680 (org-export-with-TeX-macros (plist-get options :TeX-macros))
5681 (org-export-html-expand (plist-get options :expand-quoted-html))
5682 (org-export-with-special-strings (plist-get options :special-strings))
5683 (re-sub
5684 (cond
5685 ((equal org-export-with-sub-superscripts '{})
5686 (list org-match-substring-with-braces-regexp))
5687 (org-export-with-sub-superscripts
5688 (list org-match-substring-regexp))
5689 (t nil)))
5690 (re-latex
5691 (if org-export-with-LaTeX-fragments
5692 (mapcar (lambda (x) (nth 1 x)) latexs)))
5693 (re-macros
5694 (if org-export-with-TeX-macros
5695 (list (concat "\\\\"
5696 (regexp-opt
5697 (append
5699 (delq nil
5700 (mapcar 'car-safe
5701 (append org-entities-user
5702 org-entities)))
5703 (if (boundp 'org-latex-entities)
5704 (mapcar (lambda (x)
5705 (or (car-safe x) x))
5706 org-latex-entities)
5707 nil))
5708 'words))) ; FIXME
5710 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5711 (re-special (if org-export-with-special-strings
5712 (mapcar (lambda (x) (car x))
5713 org-export-html-special-string-regexps)))
5714 (re-rest
5715 (delq nil
5716 (list
5717 (if org-export-html-expand "@<[^>\n]+>")
5718 ))))
5719 (org-set-local
5720 'org-latex-and-specials-regexp
5721 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5722 re-rest) "\\|")))))
5724 (defun org-do-latex-and-special-faces (limit)
5725 "Run through the buffer and add overlays to links."
5726 (when org-latex-and-specials-regexp
5727 (let (rtn d)
5728 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5729 limit t))
5730 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5731 'face))
5732 '(org-code org-verbatim underline)))
5733 (progn
5734 (setq rtn t
5735 d (cond ((member (char-after (1+ (match-beginning 0)))
5736 '(?_ ?^)) 1)
5737 (t 0)))
5738 (font-lock-prepend-text-property
5739 (+ d (match-beginning 0)) (match-end 0)
5740 'face 'org-latex-and-export-specials)
5741 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5742 '(font-lock-multiline t)))))
5743 rtn)))
5745 (defun org-restart-font-lock ()
5746 "Restart `font-lock-mode', to force refontification."
5747 (when (and (boundp 'font-lock-mode) font-lock-mode)
5748 (font-lock-mode -1)
5749 (font-lock-mode 1)))
5751 (defun org-all-targets (&optional radio)
5752 "Return a list of all targets in this file.
5753 With optional argument RADIO, only find radio targets."
5754 (let ((re (if radio org-radio-target-regexp org-target-regexp))
5755 rtn)
5756 (save-excursion
5757 (goto-char (point-min))
5758 (while (re-search-forward re nil t)
5759 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
5760 rtn)))
5762 (defun org-make-target-link-regexp (targets)
5763 "Make regular expression matching all strings in TARGETS.
5764 The regular expression finds the targets also if there is a line break
5765 between words."
5766 (and targets
5767 (concat
5768 "\\<\\("
5769 (mapconcat
5770 (lambda (x)
5771 (setq x (regexp-quote x))
5772 (while (string-match " +" x)
5773 (setq x (replace-match "\\s-+" t t x)))
5775 targets
5776 "\\|")
5777 "\\)\\>")))
5779 (defun org-activate-tags (limit)
5780 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
5781 (progn
5782 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5783 (add-text-properties (match-beginning 1) (match-end 1)
5784 (list 'mouse-face 'highlight
5785 'keymap org-mouse-map))
5786 (org-rear-nonsticky-at (match-end 1))
5787 t)))
5789 (defun org-outline-level ()
5790 "Compute the outline level of the heading at point.
5791 This function assumes that the cursor is at the beginning of a line matched
5792 by `outline-regexp'. Otherwise it returns garbage.
5793 If this is called at a normal headline, the level is the number of stars.
5794 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
5795 (save-excursion
5796 (looking-at org-outline-regexp)
5797 (1- (- (match-end 0) (match-beginning 0)))))
5799 (defvar org-font-lock-keywords nil)
5801 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\+?\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
5802 "Regular expression matching a property line.")
5804 (defvar org-font-lock-hook nil
5805 "Functions to be called for special font lock stuff.")
5807 (defvar org-font-lock-set-keywords-hook nil
5808 "Functions that can manipulate `org-font-lock-extra-keywords'.
5809 This is called after `org-font-lock-extra-keywords' is defined, but before
5810 it is installed to be used by font lock. This can be useful if something
5811 needs to be inserted at a specific position in the font-lock sequence.")
5813 (defun org-font-lock-hook (limit)
5814 (run-hook-with-args 'org-font-lock-hook limit))
5816 (defun org-set-font-lock-defaults ()
5817 (let* ((em org-fontify-emphasized-text)
5818 (lk org-activate-links)
5819 (org-font-lock-extra-keywords
5820 (list
5821 ;; Call the hook
5822 '(org-font-lock-hook)
5823 ;; Headlines
5824 `(,(if org-fontify-whole-heading-line
5825 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
5826 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
5827 (1 (org-get-level-face 1))
5828 (2 (org-get-level-face 2))
5829 (3 (org-get-level-face 3)))
5830 ;; Table lines
5831 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5832 (1 'org-table t))
5833 ;; Table internals
5834 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5835 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5836 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5837 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
5838 ;; Drawers
5839 (list org-drawer-regexp '(0 'org-special-keyword t))
5840 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5841 ;; Properties
5842 (list org-property-re
5843 '(1 'org-special-keyword t)
5844 '(3 'org-property-value t))
5845 ;; Links
5846 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5847 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5848 (if (memq 'plain lk) '(org-activate-plain-links))
5849 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5850 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5851 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5852 (if (memq 'footnote lk) '(org-activate-footnote-links))
5853 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5854 '(org-hide-wide-columns (0 nil append))
5855 ;; TODO keyword
5856 (list (format org-heading-keyword-regexp-format
5857 org-todo-regexp)
5858 '(2 (org-get-todo-face 2) t))
5859 ;; DONE
5860 (if org-fontify-done-headline
5861 (list (format org-heading-keyword-regexp-format
5862 (concat
5863 "\\(?:"
5864 (mapconcat 'regexp-quote org-done-keywords "\\|")
5865 "\\)"))
5866 '(2 'org-headline-done t))
5867 nil)
5868 ;; Priorities
5869 '(org-font-lock-add-priority-faces)
5870 ;; Tags
5871 '(org-font-lock-add-tag-faces)
5872 ;; Special keywords
5873 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5874 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5875 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5876 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5877 ;; Emphasis
5878 (if em
5879 (if (featurep 'xemacs)
5880 '(org-do-emphasis-faces (0 nil append))
5881 '(org-do-emphasis-faces)))
5882 ;; Checkboxes
5883 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
5884 1 'org-checkbox prepend)
5885 (if (cdr (assq 'checkbox org-list-automatic-rules))
5886 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5887 (0 (org-get-checkbox-statistics-face) t)))
5888 ;; Description list items
5889 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
5890 1 'bold prepend)
5891 ;; ARCHIVEd headings
5892 (list (concat
5893 org-outline-regexp-bol
5894 "\\(.*:" org-archive-tag ":.*\\)")
5895 '(1 'org-archived prepend))
5896 ;; Specials
5897 '(org-do-latex-and-special-faces)
5898 '(org-fontify-entities)
5899 '(org-raise-scripts)
5900 ;; Code
5901 '(org-activate-code (1 'org-code t))
5902 ;; COMMENT
5903 (list (format org-heading-keyword-regexp-format
5904 (concat "\\("
5905 org-comment-string "\\|" org-quote-string
5906 "\\)"))
5907 '(2 'org-special-keyword t))
5908 '("^#.*" (0 'font-lock-comment-face t))
5909 ;; Blocks and meta lines
5910 '(org-fontify-meta-lines-and-blocks)
5912 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5913 (run-hooks 'org-font-lock-set-keywords-hook)
5914 ;; Now set the full font-lock-keywords
5915 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5916 (org-set-local 'font-lock-defaults
5917 '(org-font-lock-keywords t nil nil backward-paragraph))
5918 (kill-local-variable 'font-lock-keywords) nil))
5920 (defun org-toggle-pretty-entities ()
5921 "Toggle the composition display of entities as UTF8 characters."
5922 (interactive)
5923 (org-set-local 'org-pretty-entities (not org-pretty-entities))
5924 (org-restart-font-lock)
5925 (if org-pretty-entities
5926 (message "Entities are displayed as UTF8 characters")
5927 (save-restriction
5928 (widen)
5929 (org-decompose-region (point-min) (point-max))
5930 (message "Entities are displayed plain"))))
5932 (defun org-fontify-entities (limit)
5933 "Find an entity to fontify."
5934 (let (ee)
5935 (when org-pretty-entities
5936 (catch 'match
5937 (while (re-search-forward
5938 "\\\\\\(frac[13][24]\\|[a-zA-Z]+\\)\\($\\|[^[:alpha:]\n]\\)"
5939 limit t)
5940 (if (and (not (org-in-indented-comment-line))
5941 (setq ee (org-entity-get (match-string 1)))
5942 (= (length (nth 6 ee)) 1))
5943 (progn
5944 (add-text-properties
5945 (match-beginning 0) (match-end 1)
5946 (list 'font-lock-fontified t))
5947 (compose-region (match-beginning 0) (match-end 1)
5948 (nth 6 ee) nil)
5949 (backward-char 1)
5950 (throw 'match t))))
5951 nil))))
5953 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
5954 "Fontify string S like in Org-mode."
5955 (with-temp-buffer
5956 (insert s)
5957 (let ((org-odd-levels-only odd-levels))
5958 (org-mode)
5959 (font-lock-fontify-buffer)
5960 (buffer-string))))
5962 (defvar org-m nil)
5963 (defvar org-l nil)
5964 (defvar org-f nil)
5965 (defun org-get-level-face (n)
5966 "Get the right face for match N in font-lock matching of headlines."
5967 (setq org-l (- (match-end 2) (match-beginning 1) 1))
5968 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
5969 (if org-cycle-level-faces
5970 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
5971 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
5972 (cond
5973 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
5974 ((eq n 2) org-f)
5975 (t (if org-level-color-stars-only nil org-f))))
5978 (defun org-get-todo-face (kwd)
5979 "Get the right face for a TODO keyword KWD.
5980 If KWD is a number, get the corresponding match group."
5981 (if (numberp kwd) (setq kwd (match-string kwd)))
5982 (or (org-face-from-face-or-color
5983 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
5984 (and (member kwd org-done-keywords) 'org-done)
5985 'org-todo))
5987 (defun org-face-from-face-or-color (context inherit face-or-color)
5988 "Create a face list that inherits INHERIT, but sets the foreground color.
5989 When FACE-OR-COLOR is not a string, just return it."
5990 (if (stringp face-or-color)
5991 (list :inherit inherit
5992 (cdr (assoc context org-faces-easy-properties))
5993 face-or-color)
5994 face-or-color))
5996 (defun org-font-lock-add-tag-faces (limit)
5997 "Add the special tag faces."
5998 (when (and org-tag-faces org-tags-special-faces-re)
5999 (while (re-search-forward org-tags-special-faces-re limit t)
6000 (add-text-properties (match-beginning 1) (match-end 1)
6001 (list 'face (org-get-tag-face 1)
6002 'font-lock-fontified t))
6003 (backward-char 1))))
6005 (defun org-font-lock-add-priority-faces (limit)
6006 "Add the special priority faces."
6007 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6008 (add-text-properties
6009 (match-beginning 0) (match-end 0)
6010 (list 'face (or (org-face-from-face-or-color
6011 'priority 'org-special-keyword
6012 (cdr (assoc (char-after (match-beginning 1))
6013 org-priority-faces)))
6014 'org-special-keyword)
6015 'font-lock-fontified t))))
6017 (defun org-get-tag-face (kwd)
6018 "Get the right face for a TODO keyword KWD.
6019 If KWD is a number, get the corresponding match group."
6020 (if (numberp kwd) (setq kwd (match-string kwd)))
6021 (or (org-face-from-face-or-color
6022 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6023 'org-tag))
6025 (defun org-unfontify-region (beg end &optional maybe_loudly)
6026 "Remove fontification and activation overlays from links."
6027 (font-lock-default-unfontify-region beg end)
6028 (let* ((buffer-undo-list t)
6029 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6030 (inhibit-modification-hooks t)
6031 deactivate-mark buffer-file-name buffer-file-truename)
6032 (org-decompose-region beg end)
6033 (remove-text-properties beg end
6034 '(mouse-face t keymap t org-linked-text t
6035 invisible t intangible t
6036 org-no-flyspell t org-emphasis t))
6037 (org-remove-font-lock-display-properties beg end)))
6039 (defconst org-script-display '(((raise -0.3) (height 0.7))
6040 ((raise 0.3) (height 0.7))
6041 ((raise -0.5))
6042 ((raise 0.5)))
6043 "Display properties for showing superscripts and subscripts.")
6045 (defun org-remove-font-lock-display-properties (beg end)
6046 "Remove specific display properties that have been added by font lock.
6047 The will remove the raise properties that are used to show superscripts
6048 and subscripts."
6049 (let (next prop)
6050 (while (< beg end)
6051 (setq next (next-single-property-change beg 'display nil end)
6052 prop (get-text-property beg 'display))
6053 (if (member prop org-script-display)
6054 (put-text-property beg next 'display nil))
6055 (setq beg next))))
6057 (defun org-raise-scripts (limit)
6058 "Add raise properties to sub/superscripts."
6059 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6060 (if (re-search-forward
6061 (if (eq org-use-sub-superscripts t)
6062 org-match-substring-regexp
6063 org-match-substring-with-braces-regexp)
6064 limit t)
6065 (let* ((pos (point)) table-p comment-p
6066 (mpos (match-beginning 3))
6067 (emph-p (get-text-property mpos 'org-emphasis))
6068 (link-p (get-text-property mpos 'mouse-face))
6069 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6070 (goto-char (point-at-bol))
6071 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6072 comment-p (org-looking-at-p "[ \t]*#"))
6073 (goto-char pos)
6074 ;; FIXME: Should we go back one character here, for a_b^c
6075 ;; (goto-char (1- pos)) ;????????????????????
6076 (if (or comment-p emph-p link-p keyw-p)
6078 (put-text-property (match-beginning 3) (match-end 0)
6079 'display
6080 (if (equal (char-after (match-beginning 2)) ?^)
6081 (nth (if table-p 3 1) org-script-display)
6082 (nth (if table-p 2 0) org-script-display)))
6083 (add-text-properties (match-beginning 2) (match-end 2)
6084 (list 'invisible t
6085 'org-dwidth t 'org-dwidth-n 1))
6086 (if (and (eq (char-after (match-beginning 3)) ?{)
6087 (eq (char-before (match-end 3)) ?}))
6088 (progn
6089 (add-text-properties
6090 (match-beginning 3) (1+ (match-beginning 3))
6091 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6092 (add-text-properties
6093 (1- (match-end 3)) (match-end 3)
6094 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6095 t)))))
6097 ;;;; Visibility cycling, including org-goto and indirect buffer
6099 ;;; Cycling
6101 (defvar org-cycle-global-status nil)
6102 (make-variable-buffer-local 'org-cycle-global-status)
6103 (defvar org-cycle-subtree-status nil)
6104 (make-variable-buffer-local 'org-cycle-subtree-status)
6106 ;;;###autoload
6108 (defvar org-inlinetask-min-level)
6110 (defun org-cycle (&optional arg)
6111 "TAB-action and visibility cycling for Org-mode.
6113 This is the command invoked in Org-mode by the TAB key. Its main purpose
6114 is outline visibility cycling, but it also invokes other actions
6115 in special contexts.
6117 - When this function is called with a prefix argument, rotate the entire
6118 buffer through 3 states (global cycling)
6119 1. OVERVIEW: Show only top-level headlines.
6120 2. CONTENTS: Show all headlines of all levels, but no body text.
6121 3. SHOW ALL: Show everything.
6122 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6123 determined by the variable `org-startup-folded', and by any VISIBILITY
6124 properties in the buffer.
6125 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6126 including any drawers.
6128 - When inside a table, re-align the table and move to the next field.
6130 - When point is at the beginning of a headline, rotate the subtree started
6131 by this line through 3 different states (local cycling)
6132 1. FOLDED: Only the main headline is shown.
6133 2. CHILDREN: The main headline and the direct children are shown.
6134 From this state, you can move to one of the children
6135 and zoom in further.
6136 3. SUBTREE: Show the entire subtree, including body text.
6137 If there is no subtree, switch directly from CHILDREN to FOLDED.
6139 - When point is at the beginning of an empty headline and the variable
6140 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6141 of the headline by demoting and promoting it to likely levels. This
6142 speeds up creation document structure by pressing TAB once or several
6143 times right after creating a new headline.
6145 - When there is a numeric prefix, go up to a heading with level ARG, do
6146 a `show-subtree' and return to the previous cursor position. If ARG
6147 is negative, go up that many levels.
6149 - When point is not at the beginning of a headline, execute the global
6150 binding for TAB, which is re-indenting the line. See the option
6151 `org-cycle-emulate-tab' for details.
6153 - Special case: if point is at the beginning of the buffer and there is
6154 no headline in line 1, this function will act as if called with prefix arg
6155 (C-u TAB, same as S-TAB) also when called without prefix arg.
6156 But only if also the variable `org-cycle-global-at-bob' is t."
6157 (interactive "P")
6158 (org-load-modules-maybe)
6159 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6160 (and org-cycle-level-after-item/entry-creation
6161 (or (org-cycle-level)
6162 (org-cycle-item-indentation))))
6163 (let* ((limit-level
6164 (or org-cycle-max-level
6165 (and (boundp 'org-inlinetask-min-level)
6166 org-inlinetask-min-level
6167 (1- org-inlinetask-min-level))))
6168 (nstars (and limit-level
6169 (if org-odd-levels-only
6170 (and limit-level (1- (* limit-level 2)))
6171 limit-level)))
6172 (org-outline-regexp
6173 (if (not (derived-mode-p 'org-mode))
6174 outline-regexp
6175 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6176 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6177 (not (looking-at org-outline-regexp))))
6178 (org-cycle-hook
6179 (if bob-special
6180 (delq 'org-optimize-window-after-visibility-change
6181 (copy-sequence org-cycle-hook))
6182 org-cycle-hook))
6183 (pos (point)))
6185 (if (or bob-special (equal arg '(4)))
6186 ;; special case: use global cycling
6187 (setq arg t))
6189 (cond
6191 ((equal arg '(16))
6192 (setq last-command 'dummy)
6193 (org-set-startup-visibility)
6194 (message "Startup visibility, plus VISIBILITY properties"))
6196 ((equal arg '(64))
6197 (show-all)
6198 (message "Entire buffer visible, including drawers"))
6200 ;; Table: enter it or move to the next field.
6201 ((org-at-table-p 'any)
6202 (if (org-at-table.el-p)
6203 (message "Use C-c ' to edit table.el tables")
6204 (if arg (org-table-edit-field t)
6205 (org-table-justify-field-maybe)
6206 (call-interactively 'org-table-next-field))))
6208 ((run-hook-with-args-until-success
6209 'org-tab-after-check-for-table-hook))
6211 ;; Global cycling: delegate to `org-cycle-internal-global'.
6212 ((eq arg t) (org-cycle-internal-global))
6214 ;; Drawers: delegate to `org-flag-drawer'.
6215 ((and org-drawers org-drawer-regexp
6216 (save-excursion
6217 (beginning-of-line 1)
6218 (looking-at org-drawer-regexp)))
6219 (org-flag-drawer ; toggle block visibility
6220 (not (get-char-property (match-end 0) 'invisible))))
6222 ;; Show-subtree, ARG levels up from here.
6223 ((integerp arg)
6224 (save-excursion
6225 (org-back-to-heading)
6226 (outline-up-heading (if (< arg 0) (- arg)
6227 (- (funcall outline-level) arg)))
6228 (org-show-subtree)))
6230 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6231 ((and (featurep 'org-inlinetask)
6232 (org-inlinetask-at-task-p)
6233 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6234 (org-inlinetask-toggle-visibility))
6236 ((org-try-cdlatex-tab))
6238 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6239 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6240 (save-excursion (beginning-of-line 1)
6241 (looking-at org-outline-regexp)))
6242 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6243 (org-cycle-internal-local))
6245 ;; From there: TAB emulation and template completion.
6246 (buffer-read-only (org-back-to-heading))
6248 ((run-hook-with-args-until-success
6249 'org-tab-after-check-for-cycling-hook))
6251 ((org-try-structure-completion))
6253 ((run-hook-with-args-until-success
6254 'org-tab-before-tab-emulation-hook))
6256 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6257 (or (not (bolp))
6258 (not (looking-at org-outline-regexp))))
6259 (call-interactively (global-key-binding "\t")))
6261 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6262 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6263 (or (and (eq org-cycle-emulate-tab 'white)
6264 (= (match-end 0) (point-at-eol)))
6265 (and (eq org-cycle-emulate-tab 'whitestart)
6266 (>= (match-end 0) pos))))
6268 (eq org-cycle-emulate-tab t))
6269 (call-interactively (global-key-binding "\t")))
6271 (t (save-excursion
6272 (org-back-to-heading)
6273 (org-cycle)))))))
6275 (defun org-cycle-internal-global ()
6276 "Do the global cycling action."
6277 ;; Hack to avoid display of messages for .org attachments in Gnus
6278 (let ((ga (string-match "\\*fontification" (buffer-name))))
6279 (cond
6280 ((and (eq last-command this-command)
6281 (eq org-cycle-global-status 'overview))
6282 ;; We just created the overview - now do table of contents
6283 ;; This can be slow in very large buffers, so indicate action
6284 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6285 (unless ga (message "CONTENTS..."))
6286 (org-content)
6287 (unless ga (message "CONTENTS...done"))
6288 (setq org-cycle-global-status 'contents)
6289 (run-hook-with-args 'org-cycle-hook 'contents))
6291 ((and (eq last-command this-command)
6292 (eq org-cycle-global-status 'contents))
6293 ;; We just showed the table of contents - now show everything
6294 (run-hook-with-args 'org-pre-cycle-hook 'all)
6295 (show-all)
6296 (unless ga (message "SHOW ALL"))
6297 (setq org-cycle-global-status 'all)
6298 (run-hook-with-args 'org-cycle-hook 'all))
6301 ;; Default action: go to overview
6302 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6303 (org-overview)
6304 (unless ga (message "OVERVIEW"))
6305 (setq org-cycle-global-status 'overview)
6306 (run-hook-with-args 'org-cycle-hook 'overview)))))
6308 (defun org-cycle-internal-local ()
6309 "Do the local cycling action."
6310 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6311 ;; First, determine end of headline (EOH), end of subtree or item
6312 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6313 (save-excursion
6314 (if (org-at-item-p)
6315 (progn
6316 (beginning-of-line)
6317 (setq struct (org-list-struct))
6318 (setq eoh (point-at-eol))
6319 (setq eos (org-list-get-item-end-before-blank (point) struct))
6320 (setq has-children (org-list-has-child-p (point) struct)))
6321 (org-back-to-heading)
6322 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6323 (setq eos (save-excursion
6324 (org-end-of-subtree t)
6325 (unless (eobp)
6326 (skip-chars-forward " \t\n"))
6327 (if (eobp) (point) (1- (point)))))
6328 (setq has-children
6329 (or (save-excursion
6330 (let ((level (funcall outline-level)))
6331 (outline-next-heading)
6332 (and (org-at-heading-p t)
6333 (> (funcall outline-level) level))))
6334 (save-excursion
6335 (org-list-search-forward (org-item-beginning-re) eos t)))))
6336 ;; Determine end invisible part of buffer (EOL)
6337 (beginning-of-line 2)
6338 ;; XEmacs doesn't have `next-single-char-property-change'
6339 (if (featurep 'xemacs)
6340 (while (and (not (eobp)) ;; this is like `next-line'
6341 (get-char-property (1- (point)) 'invisible))
6342 (beginning-of-line 2))
6343 (while (and (not (eobp)) ;; this is like `next-line'
6344 (get-char-property (1- (point)) 'invisible))
6345 (goto-char (next-single-char-property-change (point) 'invisible))
6346 (and (eolp) (beginning-of-line 2))))
6347 (setq eol (point)))
6348 ;; Find out what to do next and set `this-command'
6349 (cond
6350 ((= eos eoh)
6351 ;; Nothing is hidden behind this heading
6352 (run-hook-with-args 'org-pre-cycle-hook 'empty)
6353 (message "EMPTY ENTRY")
6354 (setq org-cycle-subtree-status nil)
6355 (save-excursion
6356 (goto-char eos)
6357 (outline-next-heading)
6358 (if (outline-invisible-p) (org-flag-heading nil))))
6359 ((and (or (>= eol eos)
6360 (not (string-match "\\S-" (buffer-substring eol eos))))
6361 (or has-children
6362 (not (setq children-skipped
6363 org-cycle-skip-children-state-if-no-children))))
6364 ;; Entire subtree is hidden in one line: children view
6365 (run-hook-with-args 'org-pre-cycle-hook 'children)
6366 (if (org-at-item-p)
6367 (org-list-set-item-visibility (point-at-bol) struct 'children)
6368 (org-show-entry)
6369 (org-with-limited-levels (show-children))
6370 ;; FIXME: This slows down the func way too much.
6371 ;; How keep drawers hidden in subtree anyway?
6372 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6373 ;; (org-cycle-hide-drawers 'subtree))
6375 ;; Fold every list in subtree to top-level items.
6376 (when (eq org-cycle-include-plain-lists 'integrate)
6377 (save-excursion
6378 (org-back-to-heading)
6379 (while (org-list-search-forward (org-item-beginning-re) eos t)
6380 (beginning-of-line 1)
6381 (let* ((struct (org-list-struct))
6382 (prevs (org-list-prevs-alist struct))
6383 (end (org-list-get-bottom-point struct)))
6384 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6385 (org-list-get-all-items (point) struct prevs))
6386 (goto-char end))))))
6387 (message "CHILDREN")
6388 (save-excursion
6389 (goto-char eos)
6390 (outline-next-heading)
6391 (if (outline-invisible-p) (org-flag-heading nil)))
6392 (setq org-cycle-subtree-status 'children)
6393 (run-hook-with-args 'org-cycle-hook 'children))
6394 ((or children-skipped
6395 (and (eq last-command this-command)
6396 (eq org-cycle-subtree-status 'children)))
6397 ;; We just showed the children, or no children are there,
6398 ;; now show everything.
6399 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
6400 (outline-flag-region eoh eos nil)
6401 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6402 (setq org-cycle-subtree-status 'subtree)
6403 (run-hook-with-args 'org-cycle-hook 'subtree))
6405 ;; Default action: hide the subtree.
6406 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6407 (outline-flag-region eoh eos t)
6408 (message "FOLDED")
6409 (setq org-cycle-subtree-status 'folded)
6410 (run-hook-with-args 'org-cycle-hook 'folded)))))
6412 ;;;###autoload
6413 (defun org-global-cycle (&optional arg)
6414 "Cycle the global visibility. For details see `org-cycle'.
6415 With \\[universal-argument] prefix arg, switch to startup visibility.
6416 With a numeric prefix, show all headlines up to that level."
6417 (interactive "P")
6418 (let ((org-cycle-include-plain-lists
6419 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6420 (cond
6421 ((integerp arg)
6422 (show-all)
6423 (hide-sublevels arg)
6424 (setq org-cycle-global-status 'contents))
6425 ((equal arg '(4))
6426 (org-set-startup-visibility)
6427 (message "Startup visibility, plus VISIBILITY properties."))
6429 (org-cycle '(4))))))
6431 (defun org-set-startup-visibility ()
6432 "Set the visibility required by startup options and properties."
6433 (cond
6434 ((eq org-startup-folded t)
6435 (org-cycle '(4)))
6436 ((eq org-startup-folded 'content)
6437 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6438 (org-cycle '(4)) (org-cycle '(4)))))
6439 (unless (eq org-startup-folded 'showeverything)
6440 (if org-hide-block-startup (org-hide-block-all))
6441 (org-set-visibility-according-to-property 'no-cleanup)
6442 (org-cycle-hide-archived-subtrees 'all)
6443 (org-cycle-hide-drawers 'all)
6444 (org-cycle-show-empty-lines t)))
6446 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6447 "Switch subtree visibilities according to :VISIBILITY: property."
6448 (interactive)
6449 (let (org-show-entry-below state)
6450 (save-excursion
6451 (goto-char (point-min))
6452 (while (re-search-forward
6453 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6454 nil t)
6455 (setq state (match-string 1))
6456 (save-excursion
6457 (org-back-to-heading t)
6458 (hide-subtree)
6459 (org-reveal)
6460 (cond
6461 ((equal state '("fold" "folded"))
6462 (hide-subtree))
6463 ((equal state "children")
6464 (org-show-hidden-entry)
6465 (show-children))
6466 ((equal state "content")
6467 (save-excursion
6468 (save-restriction
6469 (org-narrow-to-subtree)
6470 (org-content))))
6471 ((member state '("all" "showall"))
6472 (show-subtree)))))
6473 (unless no-cleanup
6474 (org-cycle-hide-archived-subtrees 'all)
6475 (org-cycle-hide-drawers 'all)
6476 (org-cycle-show-empty-lines 'all)))))
6478 ;; This function uses outline-regexp instead of the more fundamental
6479 ;; org-outline-regexp so that org-cycle-global works outside of Org
6480 ;; buffers, where outline-regexp is needed.
6481 (defun org-overview ()
6482 "Switch to overview mode, showing only top-level headlines.
6483 Really, this shows all headlines with level equal or greater than the level
6484 of the first headline in the buffer. This is important, because if the
6485 first headline is not level one, then (hide-sublevels 1) gives confusing
6486 results."
6487 (interactive)
6488 (let ((level (save-excursion
6489 (goto-char (point-min))
6490 (if (re-search-forward (concat "^" outline-regexp) nil t)
6491 (progn
6492 (goto-char (match-beginning 0))
6493 (funcall outline-level))))))
6494 (and level (hide-sublevels level))))
6496 (defun org-content (&optional arg)
6497 "Show all headlines in the buffer, like a table of contents.
6498 With numerical argument N, show content up to level N."
6499 (interactive "P")
6500 (save-excursion
6501 ;; Visit all headings and show their offspring
6502 (and (integerp arg) (org-overview))
6503 (goto-char (point-max))
6504 (catch 'exit
6505 (while (and (progn (condition-case nil
6506 (outline-previous-visible-heading 1)
6507 (error (goto-char (point-min))))
6509 (looking-at org-outline-regexp))
6510 (if (integerp arg)
6511 (show-children (1- arg))
6512 (show-branches))
6513 (if (bobp) (throw 'exit nil))))))
6516 (defun org-optimize-window-after-visibility-change (state)
6517 "Adjust the window after a change in outline visibility.
6518 This function is the default value of the hook `org-cycle-hook'."
6519 (when (get-buffer-window (current-buffer))
6520 (cond
6521 ((eq state 'content) nil)
6522 ((eq state 'all) nil)
6523 ((eq state 'folded) nil)
6524 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6525 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6527 (defun org-remove-empty-overlays-at (pos)
6528 "Remove outline overlays that do not contain non-white stuff."
6529 (mapc
6530 (lambda (o)
6531 (and (eq 'outline (overlay-get o 'invisible))
6532 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6533 (overlay-end o))))
6534 (delete-overlay o)))
6535 (overlays-at pos)))
6537 (defun org-clean-visibility-after-subtree-move ()
6538 "Fix visibility issues after moving a subtree."
6539 ;; First, find a reasonable region to look at:
6540 ;; Start two siblings above, end three below
6541 (let* ((beg (save-excursion
6542 (and (org-get-last-sibling)
6543 (org-get-last-sibling))
6544 (point)))
6545 (end (save-excursion
6546 (and (org-get-next-sibling)
6547 (org-get-next-sibling)
6548 (org-get-next-sibling))
6549 (if (org-at-heading-p)
6550 (point-at-eol)
6551 (point))))
6552 (level (looking-at "\\*+"))
6553 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6554 (save-excursion
6555 (save-restriction
6556 (narrow-to-region beg end)
6557 (when re
6558 ;; Properly fold already folded siblings
6559 (goto-char (point-min))
6560 (while (re-search-forward re nil t)
6561 (if (and (not (outline-invisible-p))
6562 (save-excursion
6563 (goto-char (point-at-eol)) (outline-invisible-p)))
6564 (hide-entry))))
6565 (org-cycle-show-empty-lines 'overview)
6566 (org-cycle-hide-drawers 'overview)))))
6568 (defun org-cycle-show-empty-lines (state)
6569 "Show empty lines above all visible headlines.
6570 The region to be covered depends on STATE when called through
6571 `org-cycle-hook'. Lisp program can use t for STATE to get the
6572 entire buffer covered. Note that an empty line is only shown if there
6573 are at least `org-cycle-separator-lines' empty lines before the headline."
6574 (when (not (= org-cycle-separator-lines 0))
6575 (save-excursion
6576 (let* ((n (abs org-cycle-separator-lines))
6577 (re (cond
6578 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6579 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6580 (t (let ((ns (number-to-string (- n 2))))
6581 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6582 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6583 beg end b e)
6584 (cond
6585 ((memq state '(overview contents t))
6586 (setq beg (point-min) end (point-max)))
6587 ((memq state '(children folded))
6588 (setq beg (point) end (progn (org-end-of-subtree t t)
6589 (beginning-of-line 2)
6590 (point)))))
6591 (when beg
6592 (goto-char beg)
6593 (while (re-search-forward re end t)
6594 (unless (get-char-property (match-end 1) 'invisible)
6595 (setq e (match-end 1))
6596 (if (< org-cycle-separator-lines 0)
6597 (setq b (save-excursion
6598 (goto-char (match-beginning 0))
6599 (org-back-over-empty-lines)
6600 (if (save-excursion
6601 (goto-char (max (point-min) (1- (point))))
6602 (org-at-heading-p))
6603 (1- (point))
6604 (point))))
6605 (setq b (match-beginning 1)))
6606 (outline-flag-region b e nil)))))))
6607 ;; Never hide empty lines at the end of the file.
6608 (save-excursion
6609 (goto-char (point-max))
6610 (outline-previous-heading)
6611 (outline-end-of-heading)
6612 (if (and (looking-at "[ \t\n]+")
6613 (= (match-end 0) (point-max)))
6614 (outline-flag-region (point) (match-end 0) nil))))
6616 (defun org-show-empty-lines-in-parent ()
6617 "Move to the parent and re-show empty lines before visible headlines."
6618 (save-excursion
6619 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6620 (org-cycle-show-empty-lines context))))
6622 (defun org-files-list ()
6623 "Return `org-agenda-files' list, plus all open org-mode files.
6624 This is useful for operations that need to scan all of a user's
6625 open and agenda-wise Org files."
6626 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6627 (dolist (buf (buffer-list))
6628 (with-current-buffer buf
6629 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
6630 (let ((file (expand-file-name (buffer-file-name))))
6631 (unless (member file files)
6632 (push file files))))))
6633 files))
6635 (defsubst org-entry-beginning-position ()
6636 "Return the beginning position of the current entry."
6637 (save-excursion (outline-back-to-heading t) (point)))
6639 (defsubst org-entry-end-position ()
6640 "Return the end position of the current entry."
6641 (save-excursion (outline-next-heading) (point)))
6643 (defun org-cycle-hide-drawers (state)
6644 "Re-hide all drawers after a visibility state change."
6645 (when (and (derived-mode-p 'org-mode)
6646 (not (memq state '(overview folded contents))))
6647 (save-excursion
6648 (let* ((globalp (memq state '(contents all)))
6649 (beg (if globalp (point-min) (point)))
6650 (end (if globalp (point-max)
6651 (if (eq state 'children)
6652 (save-excursion (outline-next-heading) (point))
6653 (org-end-of-subtree t)))))
6654 (goto-char beg)
6655 (while (re-search-forward org-drawer-regexp end t)
6656 (org-flag-drawer t))))))
6658 (defun org-flag-drawer (flag)
6659 (save-excursion
6660 (beginning-of-line 1)
6661 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6662 (let ((b (match-end 0)))
6663 (if (re-search-forward
6664 "^[ \t]*:END:"
6665 (save-excursion (outline-next-heading) (point)) t)
6666 (outline-flag-region b (point-at-eol) flag)
6667 (error ":END: line missing at position %s" b))))))
6669 (defun org-subtree-end-visible-p ()
6670 "Is the end of the current subtree visible?"
6671 (pos-visible-in-window-p
6672 (save-excursion (org-end-of-subtree t) (point))))
6674 (defun org-first-headline-recenter (&optional N)
6675 "Move cursor to the first headline and recenter the headline.
6676 Optional argument N means put the headline into the Nth line of the window."
6677 (goto-char (point-min))
6678 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
6679 (beginning-of-line)
6680 (recenter (prefix-numeric-value N))))
6682 ;;; Saving and restoring visibility
6684 (defun org-outline-overlay-data (&optional use-markers)
6685 "Return a list of the locations of all outline overlays.
6686 These are overlays with the `invisible' property value `outline'.
6687 The return value is a list of cons cells, with start and stop
6688 positions for each overlay.
6689 If USE-MARKERS is set, return the positions as markers."
6690 (let (beg end)
6691 (save-excursion
6692 (save-restriction
6693 (widen)
6694 (delq nil
6695 (mapcar (lambda (o)
6696 (when (eq (overlay-get o 'invisible) 'outline)
6697 (setq beg (overlay-start o)
6698 end (overlay-end o))
6699 (and beg end (> end beg)
6700 (if use-markers
6701 (cons (move-marker (make-marker) beg)
6702 (move-marker (make-marker) end))
6703 (cons beg end)))))
6704 (overlays-in (point-min) (point-max))))))))
6706 (defun org-set-outline-overlay-data (data)
6707 "Create visibility overlays for all positions in DATA.
6708 DATA should have been made by `org-outline-overlay-data'."
6709 (let (o)
6710 (save-excursion
6711 (save-restriction
6712 (widen)
6713 (show-all)
6714 (mapc (lambda (c)
6715 (outline-flag-region (car c) (cdr c) t))
6716 data)))))
6718 ;;; Folding of blocks
6720 (defvar org-hide-block-overlays nil
6721 "Overlays hiding blocks.")
6722 (make-variable-buffer-local 'org-hide-block-overlays)
6724 (defun org-block-map (function &optional start end)
6725 "Call FUNCTION at the head of all source blocks in the current buffer.
6726 Optional arguments START and END can be used to limit the range."
6727 (let ((start (or start (point-min)))
6728 (end (or end (point-max))))
6729 (save-excursion
6730 (goto-char start)
6731 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
6732 (save-excursion
6733 (save-match-data
6734 (goto-char (match-beginning 0))
6735 (funcall function)))))))
6737 (defun org-hide-block-toggle-all ()
6738 "Toggle the visibility of all blocks in the current buffer."
6739 (org-block-map #'org-hide-block-toggle))
6741 (defun org-hide-block-all ()
6742 "Fold all blocks in the current buffer."
6743 (interactive)
6744 (org-show-block-all)
6745 (org-block-map #'org-hide-block-toggle-maybe))
6747 (defun org-show-block-all ()
6748 "Unfold all blocks in the current buffer."
6749 (interactive)
6750 (mapc 'delete-overlay org-hide-block-overlays)
6751 (setq org-hide-block-overlays nil))
6753 (defun org-hide-block-toggle-maybe ()
6754 "Toggle visibility of block at point."
6755 (interactive)
6756 (let ((case-fold-search t))
6757 (if (save-excursion
6758 (beginning-of-line 1)
6759 (looking-at org-block-regexp))
6760 (progn (org-hide-block-toggle)
6761 t) ;; to signal that we took action
6762 nil))) ;; to signal that we did not
6764 (defun org-hide-block-toggle (&optional force)
6765 "Toggle the visibility of the current block."
6766 (interactive)
6767 (save-excursion
6768 (beginning-of-line)
6769 (if (re-search-forward org-block-regexp nil t)
6770 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
6771 (end (match-end 0)) ;; end of entire body
6773 (if (memq t (mapcar (lambda (overlay)
6774 (eq (overlay-get overlay 'invisible)
6775 'org-hide-block))
6776 (overlays-at start)))
6777 (if (or (not force) (eq force 'off))
6778 (mapc (lambda (ov)
6779 (when (member ov org-hide-block-overlays)
6780 (setq org-hide-block-overlays
6781 (delq ov org-hide-block-overlays)))
6782 (when (eq (overlay-get ov 'invisible)
6783 'org-hide-block)
6784 (delete-overlay ov)))
6785 (overlays-at start)))
6786 (setq ov (make-overlay start end))
6787 (overlay-put ov 'invisible 'org-hide-block)
6788 ;; make the block accessible to isearch
6789 (overlay-put
6790 ov 'isearch-open-invisible
6791 (lambda (ov)
6792 (when (member ov org-hide-block-overlays)
6793 (setq org-hide-block-overlays
6794 (delq ov org-hide-block-overlays)))
6795 (when (eq (overlay-get ov 'invisible)
6796 'org-hide-block)
6797 (delete-overlay ov))))
6798 (push ov org-hide-block-overlays)))
6799 (error "Not looking at a source block"))))
6801 ;; org-tab-after-check-for-cycling-hook
6802 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
6803 ;; Remove overlays when changing major mode
6804 (add-hook 'org-mode-hook
6805 (lambda () (org-add-hook 'change-major-mode-hook
6806 'org-show-block-all 'append 'local)))
6808 ;;; Org-goto
6810 (defvar org-goto-window-configuration nil)
6811 (defvar org-goto-marker nil)
6812 (defvar org-goto-map
6813 (let ((map (make-sparse-keymap)))
6814 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
6815 (while (setq cmd (pop cmds))
6816 (substitute-key-definition cmd cmd map global-map)))
6817 (suppress-keymap map)
6818 (org-defkey map "\C-m" 'org-goto-ret)
6819 (org-defkey map [(return)] 'org-goto-ret)
6820 (org-defkey map [(left)] 'org-goto-left)
6821 (org-defkey map [(right)] 'org-goto-right)
6822 (org-defkey map [(control ?g)] 'org-goto-quit)
6823 (org-defkey map "\C-i" 'org-cycle)
6824 (org-defkey map [(tab)] 'org-cycle)
6825 (org-defkey map [(down)] 'outline-next-visible-heading)
6826 (org-defkey map [(up)] 'outline-previous-visible-heading)
6827 (if org-goto-auto-isearch
6828 (if (fboundp 'define-key-after)
6829 (define-key-after map [t] 'org-goto-local-auto-isearch)
6830 nil)
6831 (org-defkey map "q" 'org-goto-quit)
6832 (org-defkey map "n" 'outline-next-visible-heading)
6833 (org-defkey map "p" 'outline-previous-visible-heading)
6834 (org-defkey map "f" 'outline-forward-same-level)
6835 (org-defkey map "b" 'outline-backward-same-level)
6836 (org-defkey map "u" 'outline-up-heading))
6837 (org-defkey map "/" 'org-occur)
6838 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
6839 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
6840 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
6841 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
6842 (org-defkey map "\C-c\C-u" 'outline-up-heading)
6843 map))
6845 (defconst org-goto-help
6846 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
6847 RET=jump to location [Q]uit and return to previous location
6848 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
6850 (defvar org-goto-start-pos) ; dynamically scoped parameter
6852 ;; FIXME: Docstring does not mention both interfaces
6853 (defun org-goto (&optional alternative-interface)
6854 "Look up a different location in the current file, keeping current visibility.
6856 When you want look-up or go to a different location in a
6857 document, the fastest way is often to fold the entire buffer and
6858 then dive into the tree. This method has the disadvantage, that
6859 the previous location will be folded, which may not be what you
6860 want.
6862 This command works around this by showing a copy of the current
6863 buffer in an indirect buffer, in overview mode. You can dive
6864 into the tree in that copy, use org-occur and incremental search
6865 to find a location. When pressing RET or `Q', the command
6866 returns to the original buffer in which the visibility is still
6867 unchanged. After RET it will also jump to the location selected
6868 in the indirect buffer and expose the headline hierarchy above.
6870 With a prefix argument, use the alternative interface: e.g. if
6871 `org-goto-interface' is 'outline use 'outline-path-completion."
6872 (interactive "P")
6873 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
6874 (org-refile-use-outline-path t)
6875 (org-refile-target-verify-function nil)
6876 (interface
6877 (if (not alternative-interface)
6878 org-goto-interface
6879 (if (eq org-goto-interface 'outline)
6880 'outline-path-completion
6881 'outline)))
6882 (org-goto-start-pos (point))
6883 (selected-point
6884 (if (eq interface 'outline)
6885 (car (org-get-location (current-buffer) org-goto-help))
6886 (let ((pa (org-refile-get-location "Goto" nil nil t)))
6887 (org-refile-check-position pa)
6888 (nth 3 pa)))))
6889 (if selected-point
6890 (progn
6891 (org-mark-ring-push org-goto-start-pos)
6892 (goto-char selected-point)
6893 (if (or (outline-invisible-p) (org-invisible-p2))
6894 (org-show-context 'org-goto)))
6895 (message "Quit"))))
6897 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
6898 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
6899 (defvar org-goto-local-auto-isearch-map) ; defined below
6901 (defun org-get-location (buf help)
6902 "Let the user select a location in the Org-mode buffer BUF.
6903 This function uses a recursive edit. It returns the selected position
6904 or nil."
6905 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
6906 (isearch-hide-immediately nil)
6907 (isearch-search-fun-function
6908 (lambda () 'org-goto-local-search-headings))
6909 (org-goto-selected-point org-goto-exit-command)
6910 (pop-up-frames nil)
6911 (special-display-buffer-names nil)
6912 (special-display-regexps nil)
6913 (special-display-function nil))
6914 (save-excursion
6915 (save-window-excursion
6916 (delete-other-windows)
6917 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
6918 (org-pop-to-buffer-same-window
6919 (condition-case nil
6920 (make-indirect-buffer (current-buffer) "*org-goto*")
6921 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
6922 (with-output-to-temp-buffer "*Help*"
6923 (princ help))
6924 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
6925 (setq buffer-read-only nil)
6926 (let ((org-startup-truncated t)
6927 (org-startup-folded nil)
6928 (org-startup-align-all-tables nil))
6929 (org-mode)
6930 (org-overview))
6931 (setq buffer-read-only t)
6932 (if (and (boundp 'org-goto-start-pos)
6933 (integer-or-marker-p org-goto-start-pos))
6934 (let ((org-show-hierarchy-above t)
6935 (org-show-siblings t)
6936 (org-show-following-heading t))
6937 (goto-char org-goto-start-pos)
6938 (and (outline-invisible-p) (org-show-context)))
6939 (goto-char (point-min)))
6940 (let (org-special-ctrl-a/e) (org-beginning-of-line))
6941 (message "Select location and press RET")
6942 (use-local-map org-goto-map)
6943 (recursive-edit)
6945 (kill-buffer "*org-goto*")
6946 (cons org-goto-selected-point org-goto-exit-command)))
6948 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
6949 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
6950 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
6951 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
6953 (defun org-goto-local-search-headings (string bound noerror)
6954 "Search and make sure that any matches are in headlines."
6955 (catch 'return
6956 (while (if isearch-forward
6957 (search-forward string bound noerror)
6958 (search-backward string bound noerror))
6959 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
6960 (and (member :headline context)
6961 (not (member :tags context))))
6962 (throw 'return (point))))))
6964 (defun org-goto-local-auto-isearch ()
6965 "Start isearch."
6966 (interactive)
6967 (goto-char (point-min))
6968 (let ((keys (this-command-keys)))
6969 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
6970 (isearch-mode t)
6971 (isearch-process-search-char (string-to-char keys)))))
6973 (defun org-goto-ret (&optional arg)
6974 "Finish `org-goto' by going to the new location."
6975 (interactive "P")
6976 (setq org-goto-selected-point (point)
6977 org-goto-exit-command 'return)
6978 (throw 'exit nil))
6980 (defun org-goto-left ()
6981 "Finish `org-goto' by going to the new location."
6982 (interactive)
6983 (if (org-at-heading-p)
6984 (progn
6985 (beginning-of-line 1)
6986 (setq org-goto-selected-point (point)
6987 org-goto-exit-command 'left)
6988 (throw 'exit nil))
6989 (error "Not on a heading")))
6991 (defun org-goto-right ()
6992 "Finish `org-goto' by going to the new location."
6993 (interactive)
6994 (if (org-at-heading-p)
6995 (progn
6996 (setq org-goto-selected-point (point)
6997 org-goto-exit-command 'right)
6998 (throw 'exit nil))
6999 (error "Not on a heading")))
7001 (defun org-goto-quit ()
7002 "Finish `org-goto' without cursor motion."
7003 (interactive)
7004 (setq org-goto-selected-point nil)
7005 (setq org-goto-exit-command 'quit)
7006 (throw 'exit nil))
7008 ;;; Indirect buffer display of subtrees
7010 (defvar org-indirect-dedicated-frame nil
7011 "This is the frame being used for indirect tree display.")
7012 (defvar org-last-indirect-buffer nil)
7014 (defun org-tree-to-indirect-buffer (&optional arg)
7015 "Create indirect buffer and narrow it to current subtree.
7016 With numerical prefix ARG, go up to this level and then take that tree.
7017 If ARG is negative, go up that many levels.
7018 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7019 indirect buffer previously made with this command, to avoid proliferation of
7020 indirect buffers. However, when you call the command with a \
7021 \\[universal-argument] prefix, or
7022 when `org-indirect-buffer-display' is `new-frame', the last buffer
7023 is kept so that you can work with several indirect buffers at the same time.
7024 If `org-indirect-buffer-display' is `dedicated-frame', the \
7025 \\[universal-argument] prefix also
7026 requests that a new frame be made for the new buffer, so that the dedicated
7027 frame is not changed."
7028 (interactive "P")
7029 (let ((cbuf (current-buffer))
7030 (cwin (selected-window))
7031 (pos (point))
7032 beg end level heading ibuf)
7033 (save-excursion
7034 (org-back-to-heading t)
7035 (when (numberp arg)
7036 (setq level (org-outline-level))
7037 (if (< arg 0) (setq arg (+ level arg)))
7038 (while (> (setq level (org-outline-level)) arg)
7039 (outline-up-heading 1 t)))
7040 (setq beg (point)
7041 heading (org-get-heading))
7042 (org-end-of-subtree t t)
7043 (if (org-at-heading-p) (backward-char 1))
7044 (setq end (point)))
7045 (if (and (buffer-live-p org-last-indirect-buffer)
7046 (not (eq org-indirect-buffer-display 'new-frame))
7047 (not arg))
7048 (kill-buffer org-last-indirect-buffer))
7049 (setq ibuf (org-get-indirect-buffer cbuf)
7050 org-last-indirect-buffer ibuf)
7051 (cond
7052 ((or (eq org-indirect-buffer-display 'new-frame)
7053 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7054 (select-frame (make-frame))
7055 (delete-other-windows)
7056 (org-pop-to-buffer-same-window ibuf)
7057 (org-set-frame-title heading))
7058 ((eq org-indirect-buffer-display 'dedicated-frame)
7059 (raise-frame
7060 (select-frame (or (and org-indirect-dedicated-frame
7061 (frame-live-p org-indirect-dedicated-frame)
7062 org-indirect-dedicated-frame)
7063 (setq org-indirect-dedicated-frame (make-frame)))))
7064 (delete-other-windows)
7065 (org-pop-to-buffer-same-window ibuf)
7066 (org-set-frame-title (concat "Indirect: " heading)))
7067 ((eq org-indirect-buffer-display 'current-window)
7068 (org-pop-to-buffer-same-window ibuf))
7069 ((eq org-indirect-buffer-display 'other-window)
7070 (pop-to-buffer ibuf))
7071 (t (error "Invalid value")))
7072 (if (featurep 'xemacs)
7073 (save-excursion (org-mode) (turn-on-font-lock)))
7074 (narrow-to-region beg end)
7075 (show-all)
7076 (goto-char pos)
7077 (run-hook-with-args 'org-cycle-hook 'all)
7078 (and (window-live-p cwin) (select-window cwin))))
7080 (defun org-get-indirect-buffer (&optional buffer)
7081 (setq buffer (or buffer (current-buffer)))
7082 (let ((n 1) (base (buffer-name buffer)) bname)
7083 (while (buffer-live-p
7084 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7085 (setq n (1+ n)))
7086 (condition-case nil
7087 (make-indirect-buffer buffer bname 'clone)
7088 (error (make-indirect-buffer buffer bname)))))
7090 (defun org-set-frame-title (title)
7091 "Set the title of the current frame to the string TITLE."
7092 ;; FIXME: how to name a single frame in XEmacs???
7093 (unless (featurep 'xemacs)
7094 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7096 ;;;; Structure editing
7098 ;;; Inserting headlines
7100 (defun org-previous-line-empty-p ()
7101 (save-excursion
7102 (and (not (bobp))
7103 (or (beginning-of-line 0) t)
7104 (save-match-data
7105 (looking-at "[ \t]*$")))))
7107 (defun org-insert-heading (&optional force-heading invisible-ok)
7108 "Insert a new heading or item with same depth at point.
7109 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
7110 If point is at the beginning of a headline, insert a sibling before the
7111 current headline. If point is not at the beginning, split the line,
7112 create the new headline with the text in the current line after point
7113 \(but see also the variable `org-M-RET-may-split-line').
7115 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7116 This is important for non-interactive uses of the command."
7117 (interactive "P")
7118 (if (or (= (buffer-size) 0)
7119 (and (not (save-excursion
7120 (and (ignore-errors (org-back-to-heading invisible-ok))
7121 (org-at-heading-p))))
7122 (or force-heading (not (org-in-item-p)))))
7123 (progn
7124 (insert "\n* ")
7125 (run-hooks 'org-insert-heading-hook))
7126 (when (or force-heading (not (org-insert-item)))
7127 (let* ((empty-line-p nil)
7128 (level nil)
7129 (on-heading (org-at-heading-p))
7130 (head (save-excursion
7131 (condition-case nil
7132 (progn
7133 (org-back-to-heading invisible-ok)
7134 (when (and (not on-heading)
7135 (featurep 'org-inlinetask)
7136 (integerp org-inlinetask-min-level)
7137 (>= (length (match-string 0))
7138 org-inlinetask-min-level))
7139 ;; Find a heading level before the inline task
7140 (while (and (setq level (org-up-heading-safe))
7141 (>= level org-inlinetask-min-level)))
7142 (if (org-at-heading-p)
7143 (org-back-to-heading invisible-ok)
7144 (error "This should not happen")))
7145 (setq empty-line-p (org-previous-line-empty-p))
7146 (match-string 0))
7147 (error "*"))))
7148 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7149 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7150 pos hide-previous previous-pos)
7151 (cond
7152 ((and (org-at-heading-p) (bolp)
7153 (or (bobp)
7154 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
7155 ;; insert before the current line
7156 (open-line (if blank 2 1)))
7157 ((and (bolp)
7158 (not org-insert-heading-respect-content)
7159 (or (bobp)
7160 (save-excursion
7161 (backward-char 1) (not (outline-invisible-p)))))
7162 ;; insert right here
7163 nil)
7165 ;; somewhere in the line
7166 (save-excursion
7167 (setq previous-pos (point-at-bol))
7168 (end-of-line)
7169 (setq hide-previous (outline-invisible-p)))
7170 (and org-insert-heading-respect-content (org-show-subtree))
7171 (let ((split
7172 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
7173 (save-excursion
7174 (let ((p (point)))
7175 (goto-char (point-at-bol))
7176 (and (looking-at org-complex-heading-regexp)
7177 (match-beginning 4)
7178 (> p (match-beginning 4)))))))
7179 tags pos)
7180 (cond
7181 (org-insert-heading-respect-content
7182 (org-end-of-subtree nil t)
7183 (when (featurep 'org-inlinetask)
7184 (while (and (not (eobp))
7185 (looking-at "\\(\\*+\\)[ \t]+")
7186 (>= (length (match-string 1))
7187 org-inlinetask-min-level))
7188 (org-end-of-subtree nil t)))
7189 (or (bolp) (newline))
7190 (or (org-previous-line-empty-p)
7191 (and blank (newline)))
7192 (open-line 1))
7193 ((org-at-heading-p)
7194 (when hide-previous
7195 (show-children)
7196 (org-show-entry))
7197 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7198 (setq tags (and (match-end 2) (match-string 2)))
7199 (and (match-end 1)
7200 (delete-region (match-beginning 1) (match-end 1)))
7201 (setq pos (point-at-bol))
7202 (or split (end-of-line 1))
7203 (delete-horizontal-space)
7204 (if (string-match "\\`\\*+\\'"
7205 (buffer-substring (point-at-bol) (point)))
7206 (insert " "))
7207 (newline (if blank 2 1))
7208 (when tags
7209 (save-excursion
7210 (goto-char pos)
7211 (end-of-line 1)
7212 (insert " " tags)
7213 (org-set-tags nil 'align))))
7215 (or split (end-of-line 1))
7216 (newline (if blank 2 1)))))))
7217 (insert head) (just-one-space)
7218 (setq pos (point))
7219 (end-of-line 1)
7220 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7221 (when (and org-insert-heading-respect-content hide-previous)
7222 (save-excursion
7223 (goto-char previous-pos)
7224 (hide-subtree)))
7225 (run-hooks 'org-insert-heading-hook)))))
7227 (defun org-get-heading (&optional no-tags no-todo)
7228 "Return the heading of the current entry, without the stars.
7229 When NO-TAGS is non-nil, don't include tags.
7230 When NO-TODO is non-nil, don't include TODO keywords."
7231 (save-excursion
7232 (org-back-to-heading t)
7233 (cond
7234 ((and no-tags no-todo)
7235 (looking-at org-complex-heading-regexp)
7236 (match-string 4))
7237 (no-tags
7238 (looking-at (concat org-outline-regexp
7239 "\\(.*?\\)"
7240 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7241 (match-string 1))
7242 (no-todo
7243 (looking-at org-todo-line-regexp)
7244 (match-string 3))
7245 (t (looking-at org-heading-regexp)
7246 (match-string 2)))))
7248 (defun org-heading-components ()
7249 "Return the components of the current heading.
7250 This is a list with the following elements:
7251 - the level as an integer
7252 - the reduced level, different if `org-odd-levels-only' is set.
7253 - the TODO keyword, or nil
7254 - the priority character, like ?A, or nil if no priority is given
7255 - the headline text itself, or the tags string if no headline text
7256 - the tags string, or nil."
7257 (save-excursion
7258 (org-back-to-heading t)
7259 (if (let (case-fold-search) (looking-at org-complex-heading-regexp))
7260 (list (length (match-string 1))
7261 (org-reduced-level (length (match-string 1)))
7262 (org-match-string-no-properties 2)
7263 (and (match-end 3) (aref (match-string 3) 2))
7264 (org-match-string-no-properties 4)
7265 (org-match-string-no-properties 5)))))
7267 (defun org-get-entry ()
7268 "Get the entry text, after heading, entire subtree."
7269 (save-excursion
7270 (org-back-to-heading t)
7271 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7273 (defun org-insert-heading-after-current ()
7274 "Insert a new heading with same level as current, after current subtree."
7275 (interactive)
7276 (org-back-to-heading)
7277 (org-insert-heading)
7278 (org-move-subtree-down)
7279 (end-of-line 1))
7281 (defun org-insert-heading-respect-content ()
7282 (interactive)
7283 (let ((org-insert-heading-respect-content t))
7284 (org-insert-heading t)))
7286 (defun org-insert-todo-heading-respect-content (&optional force-state)
7287 (interactive "P")
7288 (let ((org-insert-heading-respect-content t))
7289 (org-insert-todo-heading force-state t)))
7291 (defun org-insert-todo-heading (arg &optional force-heading)
7292 "Insert a new heading with the same level and TODO state as current heading.
7293 If the heading has no TODO state, or if the state is DONE, use the first
7294 state (TODO by default). Also with prefix arg, force first state."
7295 (interactive "P")
7296 (when (or force-heading (not (org-insert-item 'checkbox)))
7297 (org-insert-heading force-heading)
7298 (save-excursion
7299 (org-back-to-heading)
7300 (outline-previous-heading)
7301 (looking-at org-todo-line-regexp))
7302 (let*
7303 ((new-mark-x
7304 (if (or arg
7305 (not (match-beginning 2))
7306 (member (match-string 2) org-done-keywords))
7307 (car org-todo-keywords-1)
7308 (match-string 2)))
7309 (new-mark
7311 (run-hook-with-args-until-success
7312 'org-todo-get-default-hook new-mark-x nil)
7313 new-mark-x)))
7314 (beginning-of-line 1)
7315 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7316 (if org-treat-insert-todo-heading-as-state-change
7317 (org-todo new-mark)
7318 (insert new-mark " "))))
7319 (when org-provide-todo-statistics
7320 (org-update-parent-todo-statistics))))
7322 (defun org-insert-subheading (arg)
7323 "Insert a new subheading and demote it.
7324 Works for outline headings and for plain lists alike."
7325 (interactive "P")
7326 (org-insert-heading arg)
7327 (cond
7328 ((org-at-heading-p) (org-do-demote))
7329 ((org-at-item-p) (org-indent-item))))
7331 (defun org-insert-todo-subheading (arg)
7332 "Insert a new subheading with TODO keyword or checkbox and demote it.
7333 Works for outline headings and for plain lists alike."
7334 (interactive "P")
7335 (org-insert-todo-heading arg)
7336 (cond
7337 ((org-at-heading-p) (org-do-demote))
7338 ((org-at-item-p) (org-indent-item))))
7340 ;;; Promotion and Demotion
7342 (defvar org-after-demote-entry-hook nil
7343 "Hook run after an entry has been demoted.
7344 The cursor will be at the beginning of the entry.
7345 When a subtree is being demoted, the hook will be called for each node.")
7347 (defvar org-after-promote-entry-hook nil
7348 "Hook run after an entry has been promoted.
7349 The cursor will be at the beginning of the entry.
7350 When a subtree is being promoted, the hook will be called for each node.")
7352 (defun org-promote-subtree ()
7353 "Promote the entire subtree.
7354 See also `org-promote'."
7355 (interactive)
7356 (save-excursion
7357 (org-with-limited-levels (org-map-tree 'org-promote)))
7358 (org-fix-position-after-promote))
7360 (defun org-demote-subtree ()
7361 "Demote the entire subtree. See `org-demote'.
7362 See also `org-promote'."
7363 (interactive)
7364 (save-excursion
7365 (org-with-limited-levels (org-map-tree 'org-demote)))
7366 (org-fix-position-after-promote))
7369 (defun org-do-promote ()
7370 "Promote the current heading higher up the tree.
7371 If the region is active in `transient-mark-mode', promote all headings
7372 in the region."
7373 (interactive)
7374 (save-excursion
7375 (if (org-region-active-p)
7376 (org-map-region 'org-promote (region-beginning) (region-end))
7377 (org-promote)))
7378 (org-fix-position-after-promote))
7380 (defun org-do-demote ()
7381 "Demote the current heading lower down the tree.
7382 If the region is active in `transient-mark-mode', demote all headings
7383 in the region."
7384 (interactive)
7385 (save-excursion
7386 (if (org-region-active-p)
7387 (org-map-region 'org-demote (region-beginning) (region-end))
7388 (org-demote)))
7389 (org-fix-position-after-promote))
7391 (defun org-fix-position-after-promote ()
7392 "Make sure that after pro/demotion cursor position is right."
7393 (let ((pos (point)))
7394 (when (save-excursion
7395 (beginning-of-line 1)
7396 (looking-at org-todo-line-regexp)
7397 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7398 (cond ((eobp) (insert " "))
7399 ((eolp) (insert " "))
7400 ((equal (char-after) ?\ ) (forward-char 1))))))
7402 (defun org-current-level ()
7403 "Return the level of the current entry, or nil if before the first headline.
7404 The level is the number of stars at the beginning of the headline."
7405 (save-excursion
7406 (org-with-limited-levels
7407 (if (ignore-errors (org-back-to-heading t))
7408 (funcall outline-level)))))
7410 (defun org-get-previous-line-level ()
7411 "Return the outline depth of the last headline before the current line.
7412 Returns 0 for the first headline in the buffer, and nil if before the
7413 first headline."
7414 (let ((current-level (org-current-level))
7415 (prev-level (when (> (line-number-at-pos) 1)
7416 (save-excursion
7417 (beginning-of-line 0)
7418 (org-current-level)))))
7419 (cond ((null current-level) nil) ; Before first headline
7420 ((null prev-level) 0) ; At first headline
7421 (prev-level))))
7423 (defun org-reduced-level (l)
7424 "Compute the effective level of a heading.
7425 This takes into account the setting of `org-odd-levels-only'."
7426 (cond
7427 ((zerop l) 0)
7428 (org-odd-levels-only (1+ (floor (/ l 2))))
7429 (t l)))
7431 (defun org-level-increment ()
7432 "Return the number of stars that will be added or removed at a
7433 time to headlines when structure editing, based on the value of
7434 `org-odd-levels-only'."
7435 (if org-odd-levels-only 2 1))
7437 (defun org-get-valid-level (level &optional change)
7438 "Rectify a level change under the influence of `org-odd-levels-only'
7439 LEVEL is a current level, CHANGE is by how much the level should be
7440 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7441 even level numbers will become the next higher odd number."
7442 (if org-odd-levels-only
7443 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7444 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7445 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7446 (max 1 (+ level (or change 0)))))
7448 (if (boundp 'define-obsolete-function-alias)
7449 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7450 (define-obsolete-function-alias 'org-get-legal-level
7451 'org-get-valid-level)
7452 (define-obsolete-function-alias 'org-get-legal-level
7453 'org-get-valid-level "23.1")))
7455 (defun org-promote ()
7456 "Promote the current heading higher up the tree.
7457 If the region is active in `transient-mark-mode', promote all headings
7458 in the region."
7459 (org-back-to-heading t)
7460 (let* ((level (save-match-data (funcall outline-level)))
7461 (after-change-functions (remove 'flyspell-after-change-function
7462 after-change-functions))
7463 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7464 (diff (abs (- level (length up-head) -1))))
7465 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
7466 (replace-match up-head nil t)
7467 ;; Fixup tag positioning
7468 (and org-auto-align-tags (org-set-tags nil t))
7469 (if org-adapt-indentation (org-fixup-indentation (- diff)))
7470 (run-hooks 'org-after-promote-entry-hook)))
7472 (defun org-demote ()
7473 "Demote the current heading lower down the tree.
7474 If the region is active in `transient-mark-mode', demote all headings
7475 in the region."
7476 (org-back-to-heading t)
7477 (let* ((level (save-match-data (funcall outline-level)))
7478 (after-change-functions (remove 'flyspell-after-change-function
7479 after-change-functions))
7480 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7481 (diff (abs (- level (length down-head) -1))))
7482 (replace-match down-head nil t)
7483 ;; Fixup tag positioning
7484 (and org-auto-align-tags (org-set-tags nil t))
7485 (if org-adapt-indentation (org-fixup-indentation diff))
7486 (run-hooks 'org-after-demote-entry-hook)))
7488 (defun org-cycle-level ()
7489 "Cycle the level of an empty headline through possible states.
7490 This goes first to child, then to parent, level, then up the hierarchy.
7491 After top level, it switches back to sibling level."
7492 (interactive)
7493 (let ((org-adapt-indentation nil))
7494 (when (org-point-at-end-of-empty-headline)
7495 (setq this-command 'org-cycle-level) ; Only needed for caching
7496 (let ((cur-level (org-current-level))
7497 (prev-level (org-get-previous-line-level)))
7498 (cond
7499 ;; If first headline in file, promote to top-level.
7500 ((= prev-level 0)
7501 (loop repeat (/ (- cur-level 1) (org-level-increment))
7502 do (org-do-promote)))
7503 ;; If same level as prev, demote one.
7504 ((= prev-level cur-level)
7505 (org-do-demote))
7506 ;; If parent is top-level, promote to top level if not already.
7507 ((= prev-level 1)
7508 (loop repeat (/ (- cur-level 1) (org-level-increment))
7509 do (org-do-promote)))
7510 ;; If top-level, return to prev-level.
7511 ((= cur-level 1)
7512 (loop repeat (/ (- prev-level 1) (org-level-increment))
7513 do (org-do-demote)))
7514 ;; If less than prev-level, promote one.
7515 ((< cur-level prev-level)
7516 (org-do-promote))
7517 ;; If deeper than prev-level, promote until higher than
7518 ;; prev-level.
7519 ((> cur-level prev-level)
7520 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7521 do (org-do-promote))))
7522 t))))
7524 (defun org-map-tree (fun)
7525 "Call FUN for every heading underneath the current one."
7526 (org-back-to-heading)
7527 (let ((level (funcall outline-level)))
7528 (save-excursion
7529 (funcall fun)
7530 (while (and (progn
7531 (outline-next-heading)
7532 (> (funcall outline-level) level))
7533 (not (eobp)))
7534 (funcall fun)))))
7536 (defun org-map-region (fun beg end)
7537 "Call FUN for every heading between BEG and END."
7538 (let ((org-ignore-region t))
7539 (save-excursion
7540 (setq end (copy-marker end))
7541 (goto-char beg)
7542 (if (and (re-search-forward org-outline-regexp-bol nil t)
7543 (< (point) end))
7544 (funcall fun))
7545 (while (and (progn
7546 (outline-next-heading)
7547 (< (point) end))
7548 (not (eobp)))
7549 (funcall fun)))))
7551 (defvar org-property-end-re) ; silence byte-compiler
7552 (defun org-fixup-indentation (diff)
7553 "Change the indentation in the current entry by DIFF.
7554 However, if any line in the current entry has no indentation, or if it
7555 would end up with no indentation after the change, nothing at all is done."
7556 (save-excursion
7557 (let ((end (save-excursion (outline-next-heading)
7558 (point-marker)))
7559 (prohibit (if (> diff 0)
7560 "^\\S-"
7561 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7562 col)
7563 (unless (save-excursion (end-of-line 1)
7564 (re-search-forward prohibit end t))
7565 (while (and (< (point) end)
7566 (re-search-forward "^[ \t]+" end t))
7567 (goto-char (match-end 0))
7568 (setq col (current-column))
7569 (if (< diff 0) (replace-match ""))
7570 (org-indent-to-column (+ diff col))))
7571 (move-marker end nil))))
7573 (defun org-convert-to-odd-levels ()
7574 "Convert an org-mode file with all levels allowed to one with odd levels.
7575 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7576 level 5 etc."
7577 (interactive)
7578 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7579 (let ((outline-level 'org-outline-level)
7580 (org-odd-levels-only nil) n)
7581 (save-excursion
7582 (goto-char (point-min))
7583 (while (re-search-forward "^\\*\\*+ " nil t)
7584 (setq n (- (length (match-string 0)) 2))
7585 (while (>= (setq n (1- n)) 0)
7586 (org-demote))
7587 (end-of-line 1))))))
7589 (defun org-convert-to-oddeven-levels ()
7590 "Convert an org-mode file with only odd levels to one with odd/even levels.
7591 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7592 file contains a section with an even level, conversion would
7593 destroy the structure of the file. An error is signaled in this
7594 case."
7595 (interactive)
7596 (goto-char (point-min))
7597 ;; First check if there are no even levels
7598 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7599 (org-show-context t)
7600 (error "Not all levels are odd in this file. Conversion not possible"))
7601 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
7602 (let ((outline-regexp org-outline-regexp)
7603 (outline-level 'org-outline-level)
7604 (org-odd-levels-only nil) n)
7605 (save-excursion
7606 (goto-char (point-min))
7607 (while (re-search-forward "^\\*\\*+ " nil t)
7608 (setq n (/ (1- (length (match-string 0))) 2))
7609 (while (>= (setq n (1- n)) 0)
7610 (org-promote))
7611 (end-of-line 1))))))
7613 (defun org-tr-level (n)
7614 "Make N odd if required."
7615 (if org-odd-levels-only (1+ (/ n 2)) n))
7617 ;;; Vertical tree motion, cutting and pasting of subtrees
7619 (defun org-move-subtree-up (&optional arg)
7620 "Move the current subtree up past ARG headlines of the same level."
7621 (interactive "p")
7622 (org-move-subtree-down (- (prefix-numeric-value arg))))
7624 (defun org-move-subtree-down (&optional arg)
7625 "Move the current subtree down past ARG headlines of the same level."
7626 (interactive "p")
7627 (setq arg (prefix-numeric-value arg))
7628 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
7629 'org-get-last-sibling))
7630 (ins-point (make-marker))
7631 (cnt (abs arg))
7632 (col (current-column))
7633 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
7634 ;; Select the tree
7635 (org-back-to-heading)
7636 (setq beg0 (point))
7637 (save-excursion
7638 (setq ne-beg (org-back-over-empty-lines))
7639 (setq beg (point)))
7640 (save-match-data
7641 (save-excursion (outline-end-of-heading)
7642 (setq folded (outline-invisible-p)))
7643 (outline-end-of-subtree))
7644 (outline-next-heading)
7645 (setq ne-end (org-back-over-empty-lines))
7646 (setq end (point))
7647 (goto-char beg0)
7648 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
7649 ;; include less whitespace
7650 (save-excursion
7651 (goto-char beg)
7652 (forward-line (- ne-beg ne-end))
7653 (setq beg (point))))
7654 ;; Find insertion point, with error handling
7655 (while (> cnt 0)
7656 (or (and (funcall movfunc) (looking-at org-outline-regexp))
7657 (progn (goto-char beg0)
7658 (error "Cannot move past superior level or buffer limit")))
7659 (setq cnt (1- cnt)))
7660 (if (> arg 0)
7661 ;; Moving forward - still need to move over subtree
7662 (progn (org-end-of-subtree t t)
7663 (save-excursion
7664 (org-back-over-empty-lines)
7665 (or (bolp) (newline)))))
7666 (setq ne-ins (org-back-over-empty-lines))
7667 (move-marker ins-point (point))
7668 (setq txt (buffer-substring beg end))
7669 (org-save-markers-in-region beg end)
7670 (delete-region beg end)
7671 (org-remove-empty-overlays-at beg)
7672 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
7673 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
7674 (and (not (bolp)) (looking-at "\n") (forward-char 1))
7675 (let ((bbb (point)))
7676 (insert-before-markers txt)
7677 (org-reinstall-markers-in-region bbb)
7678 (move-marker ins-point bbb))
7679 (or (bolp) (insert "\n"))
7680 (setq ins-end (point))
7681 (goto-char ins-point)
7682 (org-skip-whitespace)
7683 (when (and (< arg 0)
7684 (org-first-sibling-p)
7685 (> ne-ins ne-beg))
7686 ;; Move whitespace back to beginning
7687 (save-excursion
7688 (goto-char ins-end)
7689 (let ((kill-whole-line t))
7690 (kill-line (- ne-ins ne-beg)) (point)))
7691 (insert (make-string (- ne-ins ne-beg) ?\n)))
7692 (move-marker ins-point nil)
7693 (if folded
7694 (hide-subtree)
7695 (org-show-entry)
7696 (show-children)
7697 (org-cycle-hide-drawers 'children))
7698 (org-clean-visibility-after-subtree-move)
7699 ;; move back to the initial column we were at
7700 (move-to-column col)))
7702 (defvar org-subtree-clip ""
7703 "Clipboard for cut and paste of subtrees.
7704 This is actually only a copy of the kill, because we use the normal kill
7705 ring. We need it to check if the kill was created by `org-copy-subtree'.")
7707 (defvar org-subtree-clip-folded nil
7708 "Was the last copied subtree folded?
7709 This is used to fold the tree back after pasting.")
7711 (defun org-cut-subtree (&optional n)
7712 "Cut the current subtree into the clipboard.
7713 With prefix arg N, cut this many sequential subtrees.
7714 This is a short-hand for marking the subtree and then cutting it."
7715 (interactive "p")
7716 (org-copy-subtree n 'cut))
7718 (defun org-copy-subtree (&optional n cut force-store-markers)
7719 "Cut the current subtree into the clipboard.
7720 With prefix arg N, cut this many sequential subtrees.
7721 This is a short-hand for marking the subtree and then copying it.
7722 If CUT is non-nil, actually cut the subtree.
7723 If FORCE-STORE-MARKERS is non-nil, store the relative locations
7724 of some markers in the region, even if CUT is non-nil. This is
7725 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
7726 (interactive "p")
7727 (let (beg end folded (beg0 (point)))
7728 (if (org-called-interactively-p 'any)
7729 (org-back-to-heading nil) ; take what looks like a subtree
7730 (org-back-to-heading t)) ; take what is really there
7731 (org-back-over-empty-lines)
7732 (setq beg (point))
7733 (skip-chars-forward " \t\r\n")
7734 (save-match-data
7735 (save-excursion (outline-end-of-heading)
7736 (setq folded (outline-invisible-p)))
7737 (condition-case nil
7738 (org-forward-same-level (1- n) t)
7739 (error nil))
7740 (org-end-of-subtree t t))
7741 (org-back-over-empty-lines)
7742 (setq end (point))
7743 (goto-char beg0)
7744 (when (> end beg)
7745 (setq org-subtree-clip-folded folded)
7746 (when (or cut force-store-markers)
7747 (org-save-markers-in-region beg end))
7748 (if cut (kill-region beg end) (copy-region-as-kill beg end))
7749 (setq org-subtree-clip (current-kill 0))
7750 (message "%s: Subtree(s) with %d characters"
7751 (if cut "Cut" "Copied")
7752 (length org-subtree-clip)))))
7754 (defun org-paste-subtree (&optional level tree for-yank)
7755 "Paste the clipboard as a subtree, with modification of headline level.
7756 The entire subtree is promoted or demoted in order to match a new headline
7757 level.
7759 If the cursor is at the beginning of a headline, the same level as
7760 that headline is used to paste the tree
7762 If not, the new level is derived from the *visible* headings
7763 before and after the insertion point, and taken to be the inferior headline
7764 level of the two. So if the previous visible heading is level 3 and the
7765 next is level 4 (or vice versa), level 4 will be used for insertion.
7766 This makes sure that the subtree remains an independent subtree and does
7767 not swallow low level entries.
7769 You can also force a different level, either by using a numeric prefix
7770 argument, or by inserting the heading marker by hand. For example, if the
7771 cursor is after \"*****\", then the tree will be shifted to level 5.
7773 If optional TREE is given, use this text instead of the kill ring.
7775 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
7776 move back over whitespace before inserting, and move point to the end of
7777 the inserted text when done."
7778 (interactive "P")
7779 (setq tree (or tree (and kill-ring (current-kill 0))))
7780 (unless (org-kill-is-subtree-p tree)
7781 (error "%s"
7782 (substitute-command-keys
7783 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
7784 (org-with-limited-levels
7785 (let* ((visp (not (outline-invisible-p)))
7786 (txt tree)
7787 (^re_ "\\(\\*+\\)[ \t]*")
7788 (old-level (if (string-match org-outline-regexp-bol txt)
7789 (- (match-end 0) (match-beginning 0) 1)
7790 -1))
7791 (force-level (cond (level (prefix-numeric-value level))
7792 ((and (looking-at "[ \t]*$")
7793 (string-match
7794 "^\\*+$" (buffer-substring
7795 (point-at-bol) (point))))
7796 (- (match-end 1) (match-beginning 1)))
7797 ((and (bolp)
7798 (looking-at org-outline-regexp))
7799 (- (match-end 0) (point) 1))
7800 (t nil)))
7801 (previous-level (save-excursion
7802 (condition-case nil
7803 (progn
7804 (outline-previous-visible-heading 1)
7805 (if (looking-at ^re_)
7806 (- (match-end 0) (match-beginning 0) 1)
7808 (error 1))))
7809 (next-level (save-excursion
7810 (condition-case nil
7811 (progn
7812 (or (looking-at org-outline-regexp)
7813 (outline-next-visible-heading 1))
7814 (if (looking-at ^re_)
7815 (- (match-end 0) (match-beginning 0) 1)
7817 (error 1))))
7818 (new-level (or force-level (max previous-level next-level)))
7819 (shift (if (or (= old-level -1)
7820 (= new-level -1)
7821 (= old-level new-level))
7823 (- new-level old-level)))
7824 (delta (if (> shift 0) -1 1))
7825 (func (if (> shift 0) 'org-demote 'org-promote))
7826 (org-odd-levels-only nil)
7827 beg end newend)
7828 ;; Remove the forced level indicator
7829 (if force-level
7830 (delete-region (point-at-bol) (point)))
7831 ;; Paste
7832 (beginning-of-line (if (bolp) 1 2))
7833 (unless for-yank (org-back-over-empty-lines))
7834 (setq beg (point))
7835 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
7836 (insert-before-markers txt)
7837 (unless (string-match "\n\\'" txt) (insert "\n"))
7838 (setq newend (point))
7839 (org-reinstall-markers-in-region beg)
7840 (setq end (point))
7841 (goto-char beg)
7842 (skip-chars-forward " \t\n\r")
7843 (setq beg (point))
7844 (if (and (outline-invisible-p) visp)
7845 (save-excursion (outline-show-heading)))
7846 ;; Shift if necessary
7847 (unless (= shift 0)
7848 (save-restriction
7849 (narrow-to-region beg end)
7850 (while (not (= shift 0))
7851 (org-map-region func (point-min) (point-max))
7852 (setq shift (+ delta shift)))
7853 (goto-char (point-min))
7854 (setq newend (point-max))))
7855 (when (or (org-called-interactively-p 'interactive) for-yank)
7856 (message "Clipboard pasted as level %d subtree" new-level))
7857 (if (and (not for-yank) ; in this case, org-yank will decide about folding
7858 kill-ring
7859 (eq org-subtree-clip (current-kill 0))
7860 org-subtree-clip-folded)
7861 ;; The tree was folded before it was killed/copied
7862 (hide-subtree))
7863 (and for-yank (goto-char newend)))))
7865 (defun org-kill-is-subtree-p (&optional txt)
7866 "Check if the current kill is an outline subtree, or a set of trees.
7867 Returns nil if kill does not start with a headline, or if the first
7868 headline level is not the largest headline level in the tree.
7869 So this will actually accept several entries of equal levels as well,
7870 which is OK for `org-paste-subtree'.
7871 If optional TXT is given, check this string instead of the current kill."
7872 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
7873 (re (org-get-limited-outline-regexp))
7874 (^re (concat "^" re))
7875 (start-level (and kill
7876 (string-match
7877 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
7878 kill)
7879 (- (match-end 2) (match-beginning 2) 1)))
7880 (start (1+ (or (match-beginning 2) -1))))
7881 (if (not start-level)
7882 (progn
7883 nil) ;; does not even start with a heading
7884 (catch 'exit
7885 (while (setq start (string-match ^re kill (1+ start)))
7886 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
7887 (throw 'exit nil)))
7888 t))))
7890 (defvar org-markers-to-move nil
7891 "Markers that should be moved with a cut-and-paste operation.
7892 Those markers are stored together with their positions relative to
7893 the start of the region.")
7895 (defun org-save-markers-in-region (beg end)
7896 "Check markers in region.
7897 If these markers are between BEG and END, record their position relative
7898 to BEG, so that after moving the block of text, we can put the markers back
7899 into place.
7900 This function gets called just before an entry or tree gets cut from the
7901 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
7902 called immediately, to move the markers with the entries."
7903 (setq org-markers-to-move nil)
7904 (when (featurep 'org-clock)
7905 (org-clock-save-markers-for-cut-and-paste beg end))
7906 (when (featurep 'org-agenda)
7907 (org-agenda-save-markers-for-cut-and-paste beg end)))
7909 (defun org-check-and-save-marker (marker beg end)
7910 "Check if MARKER is between BEG and END.
7911 If yes, remember the marker and the distance to BEG."
7912 (when (and (marker-buffer marker)
7913 (equal (marker-buffer marker) (current-buffer)))
7914 (if (and (>= marker beg) (< marker end))
7915 (push (cons marker (- marker beg)) org-markers-to-move))))
7917 (defun org-reinstall-markers-in-region (beg)
7918 "Move all remembered markers to their position relative to BEG."
7919 (mapc (lambda (x)
7920 (move-marker (car x) (+ beg (cdr x))))
7921 org-markers-to-move)
7922 (setq org-markers-to-move nil))
7924 (defun org-narrow-to-subtree ()
7925 "Narrow buffer to the current subtree."
7926 (interactive)
7927 (save-excursion
7928 (save-match-data
7929 (org-with-limited-levels
7930 (narrow-to-region
7931 (progn (org-back-to-heading t) (point))
7932 (progn (org-end-of-subtree t t)
7933 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
7934 (point)))))))
7936 (defun org-narrow-to-block ()
7937 "Narrow buffer to the current block."
7938 (interactive)
7939 (let* ((case-fold-search t)
7940 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
7941 "^[ \t]*#\\+end_.*")))
7942 (if blockp
7943 (narrow-to-region (car blockp) (cdr blockp))
7944 (error "Not in a block"))))
7946 (eval-when-compile
7947 (defvar org-property-drawer-re))
7949 (defvar org-property-start-re) ;; defined below
7950 (defun org-clone-subtree-with-time-shift (n &optional shift)
7951 "Clone the task (subtree) at point N times.
7952 The clones will be inserted as siblings.
7954 In interactive use, the user will be prompted for the number of
7955 clones to be produced, and for a time SHIFT, which may be a
7956 repeater as used in time stamps, for example `+3d'.
7958 When a valid repeater is given and the entry contains any time
7959 stamps, the clones will become a sequence in time, with time
7960 stamps in the subtree shifted for each clone produced. If SHIFT
7961 is nil or the empty string, time stamps will be left alone. The
7962 ID property of the original subtree is removed.
7964 If the original subtree did contain time stamps with a repeater,
7965 the following will happen:
7966 - the repeater will be removed in each clone
7967 - an additional clone will be produced, with the current, unshifted
7968 date(s) in the entry.
7969 - the original entry will be placed *after* all the clones, with
7970 repeater intact.
7971 - the start days in the repeater in the original entry will be shifted
7972 to past the last clone.
7973 In this way you can spell out a number of instances of a repeating task,
7974 and still retain the repeater to cover future instances of the task."
7975 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
7976 (let (beg end template task idprop
7977 shift-n shift-what doshift nmin nmax (n-no-remove -1)
7978 (drawer-re org-drawer-regexp))
7979 (if (not (and (integerp n) (> n 0)))
7980 (error "Invalid number of replications %s" n))
7981 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
7982 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
7983 shift)))
7984 (error "Invalid shift specification %s" shift))
7985 (when doshift
7986 (setq shift-n (string-to-number (match-string 1 shift))
7987 shift-what (cdr (assoc (match-string 2 shift)
7988 '(("d" . day) ("w" . week)
7989 ("m" . month) ("y" . year))))))
7990 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
7991 (setq nmin 1 nmax n)
7992 (org-back-to-heading t)
7993 (setq beg (point))
7994 (setq idprop (org-entry-get nil "ID"))
7995 (org-end-of-subtree t t)
7996 (or (bolp) (insert "\n"))
7997 (setq end (point))
7998 (setq template (buffer-substring beg end))
7999 (when (and doshift
8000 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8001 (delete-region beg end)
8002 (setq end beg)
8003 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8004 (goto-char end)
8005 (loop for n from nmin to nmax do
8006 ;; prepare clone
8007 (with-temp-buffer
8008 (insert template)
8009 (org-mode)
8010 (goto-char (point-min))
8011 (org-show-subtree)
8012 (and idprop (if org-clone-delete-id
8013 (org-entry-delete nil "ID")
8014 (org-id-get-create t)))
8015 (unless (= n 0)
8016 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8017 (kill-whole-line))
8018 (goto-char (point-min))
8019 (while (re-search-forward drawer-re nil t)
8020 (mapc (lambda (d)
8021 (org-remove-empty-drawer-at d (point))) org-drawers)))
8022 (goto-char (point-min))
8023 (when doshift
8024 (while (re-search-forward org-ts-regexp-both nil t)
8025 (org-timestamp-change (* n shift-n) shift-what))
8026 (unless (= n n-no-remove)
8027 (goto-char (point-min))
8028 (while (re-search-forward org-ts-regexp nil t)
8029 (save-excursion
8030 (goto-char (match-beginning 0))
8031 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8032 (delete-region (match-beginning 1) (match-end 1)))))))
8033 (setq task (buffer-string)))
8034 (insert task))
8035 (goto-char beg)))
8037 ;;; Outline Sorting
8039 (defun org-sort (with-case)
8040 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8041 Optional argument WITH-CASE means sort case-sensitively."
8042 (interactive "P")
8043 (cond
8044 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8045 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8047 (org-call-with-arg 'org-sort-entries with-case))))
8049 (defun org-sort-remove-invisible (s)
8050 (remove-text-properties 0 (length s) org-rm-props s)
8051 (while (string-match org-bracket-link-regexp s)
8052 (setq s (replace-match (if (match-end 2)
8053 (match-string 3 s)
8054 (match-string 1 s)) t t s)))
8057 (defvar org-priority-regexp) ; defined later in the file
8059 (defvar org-after-sorting-entries-or-items-hook nil
8060 "Hook that is run after a bunch of entries or items have been sorted.
8061 When children are sorted, the cursor is in the parent line when this
8062 hook gets called. When a region or a plain list is sorted, the cursor
8063 will be in the first entry of the sorted region/list.")
8065 (defun org-sort-entries
8066 (&optional with-case sorting-type getkey-func compare-func property)
8067 "Sort entries on a certain level of an outline tree.
8068 If there is an active region, the entries in the region are sorted.
8069 Else, if the cursor is before the first entry, sort the top-level items.
8070 Else, the children of the entry at point are sorted.
8072 Sorting can be alphabetically, numerically, by date/time as given by
8073 a time stamp, by a property or by priority.
8075 The command prompts for the sorting type unless it has been given to the
8076 function through the SORTING-TYPE argument, which needs to be a character,
8077 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F). Here is the
8078 precise meaning of each character:
8080 n Numerically, by converting the beginning of the entry/item to a number.
8081 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8082 t By date/time, either the first active time stamp in the entry, or, if
8083 none exist, by the first inactive one.
8084 s By the scheduled date/time.
8085 d By deadline date/time.
8086 c By creation time, which is assumed to be the first inactive time stamp
8087 at the beginning of a line.
8088 p By priority according to the cookie.
8089 r By the value of a property.
8091 Capital letters will reverse the sort order.
8093 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8094 called with point at the beginning of the record. It must return either
8095 a string or a number that should serve as the sorting key for that record.
8097 Comparing entries ignores case by default. However, with an optional argument
8098 WITH-CASE, the sorting considers case as well."
8099 (interactive "P")
8100 (let ((case-func (if with-case 'identity 'downcase))
8101 start beg end stars re re2
8102 txt what tmp)
8103 ;; Find beginning and end of region to sort
8104 (cond
8105 ((org-region-active-p)
8106 ;; we will sort the region
8107 (setq end (region-end)
8108 what "region")
8109 (goto-char (region-beginning))
8110 (if (not (org-at-heading-p)) (outline-next-heading))
8111 (setq start (point)))
8112 ((or (org-at-heading-p)
8113 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8114 ;; we will sort the children of the current headline
8115 (org-back-to-heading)
8116 (setq start (point)
8117 end (progn (org-end-of-subtree t t)
8118 (or (bolp) (insert "\n"))
8119 (org-back-over-empty-lines)
8120 (point))
8121 what "children")
8122 (goto-char start)
8123 (show-subtree)
8124 (outline-next-heading))
8126 ;; we will sort the top-level entries in this file
8127 (goto-char (point-min))
8128 (or (org-at-heading-p) (outline-next-heading))
8129 (setq start (point))
8130 (goto-char (point-max))
8131 (beginning-of-line 1)
8132 (when (looking-at ".*?\\S-")
8133 ;; File ends in a non-white line
8134 (end-of-line 1)
8135 (insert "\n"))
8136 (setq end (point-max))
8137 (setq what "top-level")
8138 (goto-char start)
8139 (show-all)))
8141 (setq beg (point))
8142 (if (>= beg end) (error "Nothing to sort"))
8144 (looking-at "\\(\\*+\\)")
8145 (setq stars (match-string 1)
8146 re (concat "^" (regexp-quote stars) " +")
8147 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8148 txt (buffer-substring beg end))
8149 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8150 (if (and (not (equal stars "*")) (string-match re2 txt))
8151 (error "Region to sort contains a level above the first entry"))
8153 (unless sorting-type
8154 (message
8155 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8156 [t]ime [s]cheduled [d]eadline [c]reated
8157 A/N/T/S/D/C/P/O/F means reversed:"
8158 what)
8159 (setq sorting-type (read-char-exclusive))
8161 (and (= (downcase sorting-type) ?f)
8162 (setq getkey-func
8163 (org-icompleting-read "Sort using function: "
8164 obarray 'fboundp t nil nil))
8165 (setq getkey-func (intern getkey-func)))
8167 (and (= (downcase sorting-type) ?r)
8168 (setq property
8169 (org-icompleting-read "Property: "
8170 (mapcar 'list (org-buffer-property-keys t))
8171 nil t))))
8173 (message "Sorting entries...")
8175 (save-restriction
8176 (narrow-to-region start end)
8177 (let ((dcst (downcase sorting-type))
8178 (case-fold-search nil)
8179 (now (current-time)))
8180 (sort-subr
8181 (/= dcst sorting-type)
8182 ;; This function moves to the beginning character of the "record" to
8183 ;; be sorted.
8184 (lambda nil
8185 (if (re-search-forward re nil t)
8186 (goto-char (match-beginning 0))
8187 (goto-char (point-max))))
8188 ;; This function moves to the last character of the "record" being
8189 ;; sorted.
8190 (lambda nil
8191 (save-match-data
8192 (condition-case nil
8193 (outline-forward-same-level 1)
8194 (error
8195 (goto-char (point-max))))))
8196 ;; This function returns the value that gets sorted against.
8197 (lambda nil
8198 (cond
8199 ((= dcst ?n)
8200 (if (looking-at org-complex-heading-regexp)
8201 (string-to-number (match-string 4))
8202 nil))
8203 ((= dcst ?a)
8204 (if (looking-at org-complex-heading-regexp)
8205 (funcall case-func (match-string 4))
8206 nil))
8207 ((= dcst ?t)
8208 (let ((end (save-excursion (outline-next-heading) (point))))
8209 (if (or (re-search-forward org-ts-regexp end t)
8210 (re-search-forward org-ts-regexp-both end t))
8211 (org-time-string-to-seconds (match-string 0))
8212 (org-float-time now))))
8213 ((= dcst ?c)
8214 (let ((end (save-excursion (outline-next-heading) (point))))
8215 (if (re-search-forward
8216 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8217 end t)
8218 (org-time-string-to-seconds (match-string 0))
8219 (org-float-time now))))
8220 ((= dcst ?s)
8221 (let ((end (save-excursion (outline-next-heading) (point))))
8222 (if (re-search-forward org-scheduled-time-regexp end t)
8223 (org-time-string-to-seconds (match-string 1))
8224 (org-float-time now))))
8225 ((= dcst ?d)
8226 (let ((end (save-excursion (outline-next-heading) (point))))
8227 (if (re-search-forward org-deadline-time-regexp end t)
8228 (org-time-string-to-seconds (match-string 1))
8229 (org-float-time now))))
8230 ((= dcst ?p)
8231 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8232 (string-to-char (match-string 2))
8233 org-default-priority))
8234 ((= dcst ?r)
8235 (or (org-entry-get nil property) ""))
8236 ((= dcst ?o)
8237 (if (looking-at org-complex-heading-regexp)
8238 (- 9999 (length (member (match-string 2)
8239 org-todo-keywords-1)))))
8240 ((= dcst ?f)
8241 (if getkey-func
8242 (progn
8243 (setq tmp (funcall getkey-func))
8244 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8245 tmp)
8246 (error "Invalid key function `%s'" getkey-func)))
8247 (t (error "Invalid sorting type `%c'" sorting-type))))
8249 (cond
8250 ((= dcst ?a) 'string<)
8251 ((= dcst ?f) compare-func)
8252 ((member dcst '(?p ?t ?s ?d ?c)) '<)
8253 (t nil)))))
8254 (run-hooks 'org-after-sorting-entries-or-items-hook)
8255 (message "Sorting entries...done")))
8257 (defun org-do-sort (table what &optional with-case sorting-type)
8258 "Sort TABLE of WHAT according to SORTING-TYPE.
8259 The user will be prompted for the SORTING-TYPE if the call to this
8260 function does not specify it. WHAT is only for the prompt, to indicate
8261 what is being sorted. The sorting key will be extracted from
8262 the car of the elements of the table.
8263 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8264 (unless sorting-type
8265 (message
8266 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
8267 what)
8268 (setq sorting-type (read-char-exclusive)))
8269 (let ((dcst (downcase sorting-type))
8270 extractfun comparefun)
8271 ;; Define the appropriate functions
8272 (cond
8273 ((= dcst ?n)
8274 (setq extractfun 'string-to-number
8275 comparefun (if (= dcst sorting-type) '< '>)))
8276 ((= dcst ?a)
8277 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8278 (lambda(x) (downcase (org-sort-remove-invisible x))))
8279 comparefun (if (= dcst sorting-type)
8280 'string<
8281 (lambda (a b) (and (not (string< a b))
8282 (not (string= a b)))))))
8283 ((= dcst ?t)
8284 (setq extractfun
8285 (lambda (x)
8286 (if (or (string-match org-ts-regexp x)
8287 (string-match org-ts-regexp-both x))
8288 (org-float-time
8289 (org-time-string-to-time (match-string 0 x)))
8291 comparefun (if (= dcst sorting-type) '< '>)))
8292 (t (error "Invalid sorting type `%c'" sorting-type)))
8294 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8295 table)
8296 (lambda (a b) (funcall comparefun (car a) (car b))))))
8299 ;;; The orgstruct minor mode
8301 ;; Define a minor mode which can be used in other modes in order to
8302 ;; integrate the org-mode structure editing commands.
8304 ;; This is really a hack, because the org-mode structure commands use
8305 ;; keys which normally belong to the major mode. Here is how it
8306 ;; works: The minor mode defines all the keys necessary to operate the
8307 ;; structure commands, but wraps the commands into a function which
8308 ;; tests if the cursor is currently at a headline or a plain list
8309 ;; item. If that is the case, the structure command is used,
8310 ;; temporarily setting many Org-mode variables like regular
8311 ;; expressions for filling etc. However, when any of those keys is
8312 ;; used at a different location, function uses `key-binding' to look
8313 ;; up if the key has an associated command in another currently active
8314 ;; keymap (minor modes, major mode, global), and executes that
8315 ;; command. There might be problems if any of the keys is otherwise
8316 ;; used as a prefix key.
8318 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
8319 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
8320 ;; addresses this by checking explicitly for both bindings.
8322 (defvar orgstruct-mode-map (make-sparse-keymap)
8323 "Keymap for the minor `orgstruct-mode'.")
8325 (defvar org-local-vars nil
8326 "List of local variables, for use by `orgstruct-mode'.")
8328 ;;;###autoload
8329 (define-minor-mode orgstruct-mode
8330 "Toggle the minor mode `orgstruct-mode'.
8331 This mode is for using Org-mode structure commands in other
8332 modes. The following keys behave as if Org-mode were active, if
8333 the cursor is on a headline, or on a plain list item (both as
8334 defined by Org-mode).
8336 M-up Move entry/item up
8337 M-down Move entry/item down
8338 M-left Promote
8339 M-right Demote
8340 M-S-up Move entry/item up
8341 M-S-down Move entry/item down
8342 M-S-left Promote subtree
8343 M-S-right Demote subtree
8344 M-q Fill paragraph and items like in Org-mode
8345 C-c ^ Sort entries
8346 C-c - Cycle list bullet
8347 TAB Cycle item visibility
8348 M-RET Insert new heading/item
8349 S-M-RET Insert new TODO heading / Checkbox item
8350 C-c C-c Set tags / toggle checkbox"
8351 nil " OrgStruct" nil
8352 (org-load-modules-maybe)
8353 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
8355 ;;;###autoload
8356 (defun turn-on-orgstruct ()
8357 "Unconditionally turn on `orgstruct-mode'."
8358 (orgstruct-mode 1))
8360 (defun orgstruct++-mode (&optional arg)
8361 "Toggle `orgstruct-mode', the enhanced version of it.
8362 In addition to setting orgstruct-mode, this also exports all indentation
8363 and autofilling variables from org-mode into the buffer. It will also
8364 recognize item context in multiline items.
8365 Note that turning off orgstruct-mode will *not* remove the
8366 indentation/paragraph settings. This can only be done by refreshing the
8367 major mode, for example with \\[normal-mode]."
8368 (interactive "P")
8369 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8370 (if (< arg 1)
8371 (orgstruct-mode -1)
8372 (orgstruct-mode 1)
8373 (let (var val)
8374 (mapc
8375 (lambda (x)
8376 (when (string-match
8377 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
8378 (symbol-name (car x)))
8379 (setq var (car x) val (nth 1 x))
8380 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8381 org-local-vars)
8382 (org-set-local 'orgstruct-is-++ t))))
8384 (defvar orgstruct-is-++ nil
8385 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8386 (make-variable-buffer-local 'orgstruct-is-++)
8388 ;;;###autoload
8389 (defun turn-on-orgstruct++ ()
8390 "Unconditionally turn on `orgstruct++-mode'."
8391 (orgstruct++-mode 1))
8393 (defun orgstruct-error ()
8394 "Error when there is no default binding for a structure key."
8395 (interactive)
8396 (error "This key has no function outside structure elements"))
8398 (defun orgstruct-setup ()
8399 "Setup orgstruct keymaps."
8400 (let ((nfunc 0)
8401 (bindings
8402 (list
8403 '([(meta up)] org-metaup)
8404 '([(meta down)] org-metadown)
8405 '([(meta left)] org-metaleft)
8406 '([(meta right)] org-metaright)
8407 '([(meta shift up)] org-shiftmetaup)
8408 '([(meta shift down)] org-shiftmetadown)
8409 '([(meta shift left)] org-shiftmetaleft)
8410 '([(meta shift right)] org-shiftmetaright)
8411 '([?\e (up)] org-metaup)
8412 '([?\e (down)] org-metadown)
8413 '([?\e (left)] org-metaleft)
8414 '([?\e (right)] org-metaright)
8415 '([?\e (shift up)] org-shiftmetaup)
8416 '([?\e (shift down)] org-shiftmetadown)
8417 '([?\e (shift left)] org-shiftmetaleft)
8418 '([?\e (shift right)] org-shiftmetaright)
8419 '([(shift up)] org-shiftup)
8420 '([(shift down)] org-shiftdown)
8421 '([(shift left)] org-shiftleft)
8422 '([(shift right)] org-shiftright)
8423 '("\C-c\C-c" org-ctrl-c-ctrl-c)
8424 '("\M-q" fill-paragraph)
8425 '("\C-c^" org-sort)
8426 '("\C-c-" org-cycle-list-bullet)))
8427 elt key fun cmd)
8428 (while (setq elt (pop bindings))
8429 (setq nfunc (1+ nfunc))
8430 (setq key (org-key (car elt))
8431 fun (nth 1 elt)
8432 cmd (orgstruct-make-binding fun nfunc key))
8433 (org-defkey orgstruct-mode-map key cmd))
8435 ;; Special treatment needed for TAB and RET
8436 (org-defkey orgstruct-mode-map [(tab)]
8437 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
8438 (org-defkey orgstruct-mode-map "\C-i"
8439 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
8441 (org-defkey orgstruct-mode-map "\M-\C-m"
8442 (orgstruct-make-binding 'org-insert-heading 105
8443 "\M-\C-m" [(meta return)]))
8444 (org-defkey orgstruct-mode-map [(meta return)]
8445 (orgstruct-make-binding 'org-insert-heading 106
8446 [(meta return)] "\M-\C-m"))
8448 (org-defkey orgstruct-mode-map [(shift meta return)]
8449 (orgstruct-make-binding 'org-insert-todo-heading 107
8450 [(meta return)] "\M-\C-m"))
8452 (org-defkey orgstruct-mode-map "\e\C-m"
8453 (orgstruct-make-binding 'org-insert-heading 108
8454 "\e\C-m" [?\e (return)]))
8455 (org-defkey orgstruct-mode-map [?\e (return)]
8456 (orgstruct-make-binding 'org-insert-heading 109
8457 [?\e (return)] "\e\C-m"))
8458 (org-defkey orgstruct-mode-map [?\e (shift return)]
8459 (orgstruct-make-binding 'org-insert-todo-heading 110
8460 [?\e (return)] "\e\C-m"))
8462 (unless org-local-vars
8463 (setq org-local-vars (org-get-local-variables)))
8467 (defun orgstruct-make-binding (fun n &rest keys)
8468 "Create a function for binding in the structure minor mode.
8469 FUN is the command to call inside a table. N is used to create a unique
8470 command name. KEYS are keys that should be checked in for a command
8471 to execute outside of tables."
8472 (eval
8473 (list 'defun
8474 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
8475 '(arg)
8476 (concat "In Structure, run `" (symbol-name fun) "'.\n"
8477 "Outside of structure, run the binding of `"
8478 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
8479 "'.")
8480 '(interactive "p")
8481 (list 'if
8482 `(org-context-p 'headline 'item
8483 (and orgstruct-is-++
8484 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
8485 'item-body))
8486 (list 'org-run-like-in-org-mode (list 'quote fun))
8487 (list 'let '(orgstruct-mode)
8488 (list 'call-interactively
8489 (append '(or)
8490 (mapcar (lambda (k)
8491 (list 'key-binding k))
8492 keys)
8493 '('orgstruct-error))))))))
8495 (defun org-context-p (&rest contexts)
8496 "Check if local context is any of CONTEXTS.
8497 Possible values in the list of contexts are `table', `headline', and `item'."
8498 (let ((pos (point)))
8499 (goto-char (point-at-bol))
8500 (prog1 (or (and (memq 'table contexts)
8501 (looking-at "[ \t]*|"))
8502 (and (memq 'headline contexts)
8503 (looking-at org-outline-regexp))
8504 (and (memq 'item contexts)
8505 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
8506 (and (memq 'item-body contexts)
8507 (org-in-item-p)))
8508 (goto-char pos))))
8510 (defun org-get-local-variables ()
8511 "Return a list of all local variables in an org-mode buffer."
8512 (let (varlist)
8513 (with-current-buffer (get-buffer-create "*Org tmp*")
8514 (erase-buffer)
8515 (org-mode)
8516 (setq varlist (buffer-local-variables)))
8517 (kill-buffer "*Org tmp*")
8518 (delq nil
8519 (mapcar
8520 (lambda (x)
8521 (setq x
8522 (if (symbolp x)
8523 (list x)
8524 (list (car x) (list 'quote (cdr x)))))
8525 (if (string-match
8526 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
8527 (symbol-name (car x)))
8528 x nil))
8529 varlist))))
8531 (defun org-clone-local-variables (from-buffer &optional regexp)
8532 "Clone local variables from FROM-BUFFER.
8533 Optional argument REGEXP selects variables to clone."
8534 (mapc
8535 (lambda (pair)
8536 (and (symbolp (car pair))
8537 (or (null regexp)
8538 (string-match regexp (symbol-name (car pair))))
8539 (set (make-local-variable (car pair))
8540 (cdr pair))))
8541 (buffer-local-variables from-buffer)))
8543 ;;;###autoload
8544 (defun org-run-like-in-org-mode (cmd)
8545 "Run a command, pretending that the current buffer is in Org-mode.
8546 This will temporarily bind local variables that are typically bound in
8547 Org-mode to the values they have in Org-mode, and then interactively
8548 call CMD."
8549 (org-load-modules-maybe)
8550 (unless org-local-vars
8551 (setq org-local-vars (org-get-local-variables)))
8552 (eval (list 'let org-local-vars
8553 (list 'call-interactively (list 'quote cmd)))))
8555 ;;;; Archiving
8557 (defun org-get-category (&optional pos force-refresh)
8558 "Get the category applying to position POS."
8559 (save-match-data
8560 (if force-refresh (org-refresh-category-properties))
8561 (let ((pos (or pos (point))))
8562 (or (get-text-property pos 'org-category)
8563 (progn (org-refresh-category-properties)
8564 (get-text-property pos 'org-category))))))
8566 (defun org-refresh-category-properties ()
8567 "Refresh category text properties in the buffer."
8568 (let ((def-cat (cond
8569 ((null org-category)
8570 (if buffer-file-name
8571 (file-name-sans-extension
8572 (file-name-nondirectory buffer-file-name))
8573 "???"))
8574 ((symbolp org-category) (symbol-name org-category))
8575 (t org-category)))
8576 beg end cat pos optionp)
8577 (org-unmodified
8578 (save-excursion
8579 (save-restriction
8580 (widen)
8581 (goto-char (point-min))
8582 (put-text-property (point) (point-max) 'org-category def-cat)
8583 (while (re-search-forward
8584 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8585 (setq pos (match-end 0)
8586 optionp (equal (char-after (match-beginning 0)) ?#)
8587 cat (org-trim (match-string 2)))
8588 (if optionp
8589 (setq beg (point-at-bol) end (point-max))
8590 (org-back-to-heading t)
8591 (setq beg (point) end (org-end-of-subtree t t)))
8592 (put-text-property beg end 'org-category cat)
8593 (put-text-property beg end 'org-category-position beg)
8594 (goto-char pos)))))))
8597 ;;;; Link Stuff
8599 ;;; Link abbreviations
8601 (defun org-link-expand-abbrev (link)
8602 "Apply replacements as defined in `org-link-abbrev-alist."
8603 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
8604 (let* ((key (match-string 1 link))
8605 (as (or (assoc key org-link-abbrev-alist-local)
8606 (assoc key org-link-abbrev-alist)))
8607 (tag (and (match-end 2) (match-string 3 link)))
8608 rpl)
8609 (if (not as)
8610 link
8611 (setq rpl (cdr as))
8612 (cond
8613 ((symbolp rpl) (funcall rpl tag))
8614 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
8615 ((string-match "%h" rpl)
8616 (replace-match (url-hexify-string (or tag "")) t t rpl))
8617 (t (concat rpl tag)))))
8618 link))
8620 ;;; Storing and inserting links
8622 (defvar org-insert-link-history nil
8623 "Minibuffer history for links inserted with `org-insert-link'.")
8625 (defvar org-stored-links nil
8626 "Contains the links stored with `org-store-link'.")
8628 (defvar org-store-link-plist nil
8629 "Plist with info about the most recently link created with `org-store-link'.")
8631 (defvar org-link-protocols nil
8632 "Link protocols added to Org-mode using `org-add-link-type'.")
8634 (defvar org-store-link-functions nil
8635 "List of functions that are called to create and store a link.
8636 Each function will be called in turn until one returns a non-nil
8637 value. Each function should check if it is responsible for creating
8638 this link (for example by looking at the major mode).
8639 If not, it must exit and return nil.
8640 If yes, it should return a non-nil value after a calling
8641 `org-store-link-props' with a list of properties and values.
8642 Special properties are:
8644 :type The link prefix, like \"http\". This must be given.
8645 :link The link, like \"http://www.astro.uva.nl/~dominik\".
8646 This is obligatory as well.
8647 :description Optional default description for the second pair
8648 of brackets in an Org-mode link. The user can still change
8649 this when inserting this link into an Org-mode buffer.
8651 In addition to these, any additional properties can be specified
8652 and then used in remember templates.")
8654 (defun org-add-link-type (type &optional follow export)
8655 "Add TYPE to the list of `org-link-types'.
8656 Re-compute all regular expressions depending on `org-link-types'
8658 FOLLOW and EXPORT are two functions.
8660 FOLLOW should take the link path as the single argument and do whatever
8661 is necessary to follow the link, for example find a file or display
8662 a mail message.
8664 EXPORT should format the link path for export to one of the export formats.
8665 It should be a function accepting three arguments:
8667 path the path of the link, the text after the prefix (like \"http:\")
8668 desc the description of the link, if any, or a description added by
8669 org-export-normalize-links if there is none
8670 format the export format, a symbol like `html' or `latex' or `ascii'..
8672 The function may use the FORMAT information to return different values
8673 depending on the format. The return value will be put literally into
8674 the exported file. If the return value is nil, this means Org should
8675 do what it normally does with links which do not have EXPORT defined.
8677 Org-mode has a built-in default for exporting links. If you are happy with
8678 this default, there is no need to define an export function for the link
8679 type. For a simple example of an export function, see `org-bbdb.el'."
8680 (add-to-list 'org-link-types type t)
8681 (org-make-link-regexps)
8682 (if (assoc type org-link-protocols)
8683 (setcdr (assoc type org-link-protocols) (list follow export))
8684 (push (list type follow export) org-link-protocols)))
8686 (defvar org-agenda-buffer-name)
8688 ;;;###autoload
8689 (defun org-store-link (arg)
8690 "\\<org-mode-map>Store an org-link to the current location.
8691 This link is added to `org-stored-links' and can later be inserted
8692 into an org-buffer with \\[org-insert-link].
8694 For some link types, a prefix arg is interpreted:
8695 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
8696 For file links, arg negates `org-context-in-file-links'."
8697 (interactive "P")
8698 (org-load-modules-maybe)
8699 (setq org-store-link-plist nil) ; reset
8700 (org-with-limited-levels
8701 (let (link cpltxt desc description search txt custom-id agenda-link)
8702 (cond
8704 ((run-hook-with-args-until-success 'org-store-link-functions)
8705 (setq link (plist-get org-store-link-plist :link)
8706 desc (or (plist-get org-store-link-plist :description) link)))
8708 ((org-src-edit-buffer-p)
8709 (let (label gc)
8710 (while (or (not label)
8711 (save-excursion
8712 (save-restriction
8713 (widen)
8714 (goto-char (point-min))
8715 (re-search-forward
8716 (regexp-quote (format org-coderef-label-format label))
8717 nil t))))
8718 (when label (message "Label exists already") (sit-for 2))
8719 (setq label (read-string "Code line label: " label)))
8720 (end-of-line 1)
8721 (setq link (format org-coderef-label-format label))
8722 (setq gc (- 79 (length link)))
8723 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
8724 (insert link)
8725 (setq link (concat "(" label ")") desc nil)))
8727 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
8728 ;; We are in the agenda, link to referenced location
8729 (let ((m (or (get-text-property (point) 'org-hd-marker)
8730 (get-text-property (point) 'org-marker))))
8731 (when m
8732 (org-with-point-at m
8733 (setq agenda-link
8734 (if (org-called-interactively-p 'any)
8735 (call-interactively 'org-store-link)
8736 (org-store-link nil)))))))
8738 ((eq major-mode 'calendar-mode)
8739 (let ((cd (calendar-cursor-to-date)))
8740 (setq link
8741 (format-time-string
8742 (car org-time-stamp-formats)
8743 (apply 'encode-time
8744 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
8745 nil nil nil))))
8746 (org-store-link-props :type "calendar" :date cd)))
8748 ((eq major-mode 'w3-mode)
8749 (setq cpltxt (if (and (buffer-name)
8750 (not (string-match "Untitled" (buffer-name))))
8751 (buffer-name)
8752 (url-view-url t))
8753 link (org-make-link (url-view-url t)))
8754 (org-store-link-props :type "w3" :url (url-view-url t)))
8756 ((eq major-mode 'w3m-mode)
8757 (setq cpltxt (or w3m-current-title w3m-current-url)
8758 link (org-make-link w3m-current-url))
8759 (org-store-link-props :type "w3m" :url (url-view-url t)))
8761 ((setq search (run-hook-with-args-until-success
8762 'org-create-file-search-functions))
8763 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
8764 "::" search))
8765 (setq cpltxt (or description link)))
8767 ((eq major-mode 'image-mode)
8768 (setq cpltxt (concat "file:"
8769 (abbreviate-file-name buffer-file-name))
8770 link (org-make-link cpltxt))
8771 (org-store-link-props :type "image" :file buffer-file-name))
8773 ((eq major-mode 'dired-mode)
8774 ;; link to the file in the current line
8775 (let ((file (dired-get-filename nil t)))
8776 (setq file (if file
8777 (abbreviate-file-name
8778 (expand-file-name (dired-get-filename nil t)))
8779 ;; otherwise, no file so use current directory.
8780 default-directory))
8781 (setq cpltxt (concat "file:" file)
8782 link (org-make-link cpltxt))))
8784 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
8785 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
8786 (cond
8787 ((org-in-regexp "<<\\(.*?\\)>>")
8788 (setq cpltxt
8789 (concat "file:"
8790 (abbreviate-file-name
8791 (buffer-file-name (buffer-base-buffer)))
8792 "::" (match-string 1))
8793 link (org-make-link cpltxt)))
8794 ((and (featurep 'org-id)
8795 (or (eq org-link-to-org-use-id t)
8796 (and (eq org-link-to-org-use-id 'create-if-interactive)
8797 (org-called-interactively-p 'any))
8798 (and (eq org-link-to-org-use-id
8799 'create-if-interactive-and-no-custom-id)
8800 (org-called-interactively-p 'any)
8801 (not custom-id))
8802 (and org-link-to-org-use-id
8803 (org-entry-get nil "ID"))))
8804 ;; We can make a link using the ID.
8805 (setq link (condition-case nil
8806 (prog1 (org-id-store-link)
8807 (setq desc (plist-get org-store-link-plist
8808 :description)))
8809 (error
8810 ;; probably before first headline, link to file only
8811 (concat "file:"
8812 (abbreviate-file-name
8813 (buffer-file-name (buffer-base-buffer))))))))
8815 ;; Just link to current headline
8816 (setq cpltxt (concat "file:"
8817 (abbreviate-file-name
8818 (buffer-file-name (buffer-base-buffer)))))
8819 ;; Add a context search string
8820 (when (org-xor org-context-in-file-links arg)
8821 (setq txt (cond
8822 ((org-at-heading-p) nil)
8823 ((org-region-active-p)
8824 (buffer-substring (region-beginning) (region-end)))
8825 (t nil)))
8826 (when (or (null txt) (string-match "\\S-" txt))
8827 (setq cpltxt
8828 (concat cpltxt "::"
8829 (condition-case nil
8830 (org-make-org-heading-search-string txt)
8831 (error "")))
8832 desc (or (nth 4 (ignore-errors
8833 (org-heading-components))) "NONE"))))
8834 (if (string-match "::\\'" cpltxt)
8835 (setq cpltxt (substring cpltxt 0 -2)))
8836 (setq link (org-make-link cpltxt)))))
8838 ((buffer-file-name (buffer-base-buffer))
8839 ;; Just link to this file here.
8840 (setq cpltxt (concat "file:"
8841 (abbreviate-file-name
8842 (buffer-file-name (buffer-base-buffer)))))
8843 ;; Add a context string
8844 (when (org-xor org-context-in-file-links arg)
8845 (setq txt (if (org-region-active-p)
8846 (buffer-substring (region-beginning) (region-end))
8847 (buffer-substring (point-at-bol) (point-at-eol))))
8848 ;; Only use search option if there is some text.
8849 (when (string-match "\\S-" txt)
8850 (setq cpltxt
8851 (concat cpltxt "::" (org-make-org-heading-search-string txt))
8852 desc "NONE")))
8853 (setq link (org-make-link cpltxt)))
8855 ((org-called-interactively-p 'interactive)
8856 (error "Cannot link to a buffer which is not visiting a file"))
8858 (t (setq link nil)))
8860 (if (consp link) (setq cpltxt (car link) link (cdr link)))
8861 (setq link (or link cpltxt)
8862 desc (or desc cpltxt))
8863 (if (equal desc "NONE") (setq desc nil))
8865 (if (and (or (org-called-interactively-p 'any) executing-kbd-macro) link)
8866 (progn
8867 (setq org-stored-links
8868 (cons (list link desc) org-stored-links))
8869 (message "Stored: %s" (or desc link))
8870 (when custom-id
8871 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
8872 "::#" custom-id))
8873 (setq org-stored-links
8874 (cons (list link desc) org-stored-links))))
8875 (or agenda-link (and link (org-make-link-string link desc)))))))
8877 (defun org-store-link-props (&rest plist)
8878 "Store link properties, extract names and addresses."
8879 (let (x adr)
8880 (when (setq x (plist-get plist :from))
8881 (setq adr (mail-extract-address-components x))
8882 (setq plist (plist-put plist :fromname (car adr)))
8883 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
8884 (when (setq x (plist-get plist :to))
8885 (setq adr (mail-extract-address-components x))
8886 (setq plist (plist-put plist :toname (car adr)))
8887 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
8888 (let ((from (plist-get plist :from))
8889 (to (plist-get plist :to)))
8890 (when (and from to org-from-is-user-regexp)
8891 (setq plist
8892 (plist-put plist :fromto
8893 (if (string-match org-from-is-user-regexp from)
8894 (concat "to %t")
8895 (concat "from %f"))))))
8896 (setq org-store-link-plist plist))
8898 (defun org-add-link-props (&rest plist)
8899 "Add these properties to the link property list."
8900 (let (key value)
8901 (while plist
8902 (setq key (pop plist) value (pop plist))
8903 (setq org-store-link-plist
8904 (plist-put org-store-link-plist key value)))))
8906 (defun org-email-link-description (&optional fmt)
8907 "Return the description part of an email link.
8908 This takes information from `org-store-link-plist' and formats it
8909 according to FMT (default from `org-email-link-description-format')."
8910 (setq fmt (or fmt org-email-link-description-format))
8911 (let* ((p org-store-link-plist)
8912 (to (plist-get p :toaddress))
8913 (from (plist-get p :fromaddress))
8914 (table
8915 (list
8916 (cons "%c" (plist-get p :fromto))
8917 (cons "%F" (plist-get p :from))
8918 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
8919 (cons "%T" (plist-get p :to))
8920 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
8921 (cons "%s" (plist-get p :subject))
8922 (cons "%d" (plist-get p :date))
8923 (cons "%m" (plist-get p :message-id)))))
8924 (when (string-match "%c" fmt)
8925 ;; Check if the user wrote this message
8926 (if (and org-from-is-user-regexp from to
8927 (save-match-data (string-match org-from-is-user-regexp from)))
8928 (setq fmt (replace-match "to %t" t t fmt))
8929 (setq fmt (replace-match "from %f" t t fmt))))
8930 (org-replace-escapes fmt table)))
8932 (defun org-make-org-heading-search-string (&optional string heading)
8933 "Make search string for STRING or current headline."
8934 (interactive)
8935 (let ((s (or string (org-get-heading)))
8936 (lines org-context-in-file-links))
8937 (unless (and string (not heading))
8938 ;; We are using a headline, clean up garbage in there.
8939 (if (string-match org-todo-regexp s)
8940 (setq s (replace-match "" t t s)))
8941 (if (string-match (org-re ":[[:alnum:]_@#%:]+:[ \t]*$") s)
8942 (setq s (replace-match "" t t s)))
8943 (setq s (org-trim s))
8944 (if (string-match (concat "^\\(" org-quote-string "\\|"
8945 org-comment-string "\\)") s)
8946 (setq s (replace-match "" t t s)))
8947 (while (string-match org-ts-regexp s)
8948 (setq s (replace-match "" t t s))))
8949 (or string (setq s (concat "*" s))) ; Add * for headlines
8950 (when (and string (integerp lines) (> lines 0))
8951 (let ((slines (org-split-string s "\n")))
8952 (when (< lines (length slines))
8953 (setq s (mapconcat
8954 'identity
8955 (reverse (nthcdr (- (length slines) lines)
8956 (reverse slines))) "\n")))))
8957 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
8959 (defun org-make-link (&rest strings)
8960 "Concatenate STRINGS."
8961 (apply 'concat strings))
8963 (defun org-make-link-string (link &optional description)
8964 "Make a link with brackets, consisting of LINK and DESCRIPTION."
8965 (unless (string-match "\\S-" link)
8966 (error "Empty link"))
8967 (when (and description
8968 (stringp description)
8969 (not (string-match "\\S-" description)))
8970 (setq description nil))
8971 (when (stringp description)
8972 ;; Remove brackets from the description, they are fatal.
8973 (while (string-match "\\[" description)
8974 (setq description (replace-match "{" t t description)))
8975 (while (string-match "\\]" description)
8976 (setq description (replace-match "}" t t description))))
8977 (when (equal link description)
8978 ;; No description needed, it is identical
8979 (setq description nil))
8980 (when (and (not description)
8981 (not (string-match (org-image-file-name-regexp) link))
8982 (not (equal link (org-link-escape link))))
8983 (setq description (org-extract-attributes link)))
8984 (setq link
8985 (cond ((string-match (org-image-file-name-regexp) link) link)
8986 ((string-match org-link-types-re link)
8987 (concat (match-string 1 link)
8988 (org-link-escape (substring link (match-end 1)))))
8989 (t (org-link-escape link))))
8990 (concat "[[" link "]"
8991 (if description (concat "[" description "]") "")
8992 "]"))
8994 (defconst org-link-escape-chars
8995 '(?\ ?\[ ?\] ?\; ?\= ?\+)
8996 "List of characters that should be escaped in link.
8997 This is the list that is used for internal purposes.")
8999 (defvar org-url-encoding-use-url-hexify nil)
9001 (defconst org-link-escape-chars-browser
9002 '(?\ )
9003 "List of escapes for characters that are problematic in links.
9004 This is the list that is used before handing over to the browser.")
9006 (defun org-link-escape (text &optional table merge)
9007 "Return percent escaped representation of TEXT.
9008 TEXT is a string with the text to escape.
9009 Optional argument TABLE is a list with characters that should be
9010 escaped. When nil, `org-link-escape-chars' is used.
9011 If optional argument MERGE is set, merge TABLE into
9012 `org-link-escape-chars'."
9013 (if (and org-url-encoding-use-url-hexify (not table))
9014 (url-hexify-string text)
9015 (cond
9016 ((and table merge)
9017 (mapc (lambda (defchr)
9018 (unless (member defchr table)
9019 (setq table (cons defchr table)))) org-link-escape-chars))
9020 ((null table)
9021 (setq table org-link-escape-chars)))
9022 (mapconcat
9023 (lambda (char)
9024 (if (or (member char table)
9025 (< char 32) (= char 37) (> char 126))
9026 (mapconcat (lambda (sequence-element)
9027 (format "%%%.2X" sequence-element))
9028 (or (encode-coding-char char 'utf-8)
9029 (error "Unable to percent escape character: %s"
9030 (char-to-string char))) "")
9031 (char-to-string char))) text "")))
9033 (defun org-link-unescape (str)
9034 "Unhex hexified Unicode strings as returned from the JavaScript function
9035 encodeURIComponent. E.g. `%C3%B6' is the german Umlaut `ö'."
9036 (unless (and (null str) (string= "" str))
9037 (let ((pos 0) (case-fold-search t) unhexed)
9038 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9039 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9040 (setq str (replace-match unhexed t t str))
9041 (setq pos (+ pos (length unhexed))))))
9042 str)
9044 (defun org-link-unescape-compound (hex)
9045 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German Umlaut `ö'.
9046 Note: this function also decodes single byte encodings like
9047 `%E1' (\"á\") if not followed by another `%[A-F0-9]{2}' group."
9048 (save-match-data
9049 (let* ((bytes (cdr (split-string hex "%")))
9050 (ret "")
9051 (eat 0)
9052 (sum 0))
9053 (while bytes
9054 (let* ((val (string-to-number (pop bytes) 16))
9055 (shift-xor
9056 (if (= 0 eat)
9057 (cond
9058 ((>= val 252) (cons 6 252))
9059 ((>= val 248) (cons 5 248))
9060 ((>= val 240) (cons 4 240))
9061 ((>= val 224) (cons 3 224))
9062 ((>= val 192) (cons 2 192))
9063 (t (cons 0 0)))
9064 (cons 6 128))))
9065 (if (>= val 192) (setq eat (car shift-xor)))
9066 (setq val (logxor val (cdr shift-xor)))
9067 (setq sum (+ (lsh sum (car shift-xor)) val))
9068 (if (> eat 0) (setq eat (- eat 1)))
9069 (cond
9070 ((= 0 eat) ;multi byte
9071 (setq ret (concat ret (org-char-to-string sum)))
9072 (setq sum 0))
9073 ((not bytes) ; single byte(s)
9074 (setq ret (org-link-unescape-single-byte-sequence hex))))
9075 )) ;; end (while bytes
9076 ret )))
9078 (defun org-link-unescape-single-byte-sequence (hex)
9079 "Unhexify hex-encoded single byte character sequences."
9080 (mapconcat (lambda (byte)
9081 (char-to-string (string-to-number byte 16)))
9082 (cdr (split-string hex "%")) ""))
9084 (defun org-xor (a b)
9085 "Exclusive or."
9086 (if a (not b) b))
9088 (defun org-fixup-message-id-for-http (s)
9089 "Replace special characters in a message id, so it can be used in an http query."
9090 (when (string-match "%" s)
9091 (setq s (mapconcat (lambda (c)
9092 (if (eq c ?%)
9093 "%25"
9094 (char-to-string c)))
9095 s "")))
9096 (while (string-match "<" s)
9097 (setq s (replace-match "%3C" t t s)))
9098 (while (string-match ">" s)
9099 (setq s (replace-match "%3E" t t s)))
9100 (while (string-match "@" s)
9101 (setq s (replace-match "%40" t t s)))
9104 (defun org-link-prettify (link)
9105 "Return a human-readable representation of LINK.
9106 The car of LINK must be a raw link the cdr of LINK must be either
9107 a link description or nil."
9108 (let ((desc (or (cadr link) "<no description>")))
9109 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9110 "[[" (car link) "]]")))
9112 ;;;###autoload
9113 (defun org-insert-link-global ()
9114 "Insert a link like Org-mode does.
9115 This command can be called in any mode to insert a link in Org-mode syntax."
9116 (interactive)
9117 (org-load-modules-maybe)
9118 (org-run-like-in-org-mode 'org-insert-link))
9120 (defun org-insert-link (&optional complete-file link-location default-description)
9121 "Insert a link. At the prompt, enter the link.
9123 Completion can be used to insert any of the link protocol prefixes like
9124 http or ftp in use.
9126 The history can be used to select a link previously stored with
9127 `org-store-link'. When the empty string is entered (i.e. if you just
9128 press RET at the prompt), the link defaults to the most recently
9129 stored link. As SPC triggers completion in the minibuffer, you need to
9130 use M-SPC or C-q SPC to force the insertion of a space character.
9132 You will also be prompted for a description, and if one is given, it will
9133 be displayed in the buffer instead of the link.
9135 If there is already a link at point, this command will allow you to edit link
9136 and description parts.
9138 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9139 be selected using completion. The path to the file will be relative to the
9140 current directory if the file is in the current directory or a subdirectory.
9141 Otherwise, the link will be the absolute path as completed in the minibuffer
9142 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9143 option `org-link-file-path-type'.
9145 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9146 the current directory or below.
9148 With three \\[universal-argument] prefixes, negate the meaning of
9149 `org-keep-stored-link-after-insertion'.
9151 If `org-make-link-description-function' is non-nil, this function will be
9152 called with the link target, and the result will be the default
9153 link description.
9155 If the LINK-LOCATION parameter is non-nil, this value will be
9156 used as the link location instead of reading one interactively.
9158 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9159 be used as the default description."
9160 (interactive "P")
9161 (let* ((wcf (current-window-configuration))
9162 (region (if (org-region-active-p)
9163 (buffer-substring (region-beginning) (region-end))))
9164 (remove (and region (list (region-beginning) (region-end))))
9165 (desc region)
9166 tmphist ; byte-compile incorrectly complains about this
9167 (link link-location)
9168 entry file all-prefixes)
9169 (cond
9170 (link-location) ; specified by arg, just use it.
9171 ((org-in-regexp org-bracket-link-regexp 1)
9172 ;; We do have a link at point, and we are going to edit it.
9173 (setq remove (list (match-beginning 0) (match-end 0)))
9174 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9175 (setq link (read-string "Link: "
9176 (org-link-unescape
9177 (org-match-string-no-properties 1)))))
9178 ((or (org-in-regexp org-angle-link-re)
9179 (org-in-regexp org-plain-link-re))
9180 ;; Convert to bracket link
9181 (setq remove (list (match-beginning 0) (match-end 0))
9182 link (read-string "Link: "
9183 (org-remove-angle-brackets (match-string 0)))))
9184 ((member complete-file '((4) (16)))
9185 ;; Completing read for file names.
9186 (setq link (org-file-complete-link complete-file)))
9188 ;; Read link, with completion for stored links.
9189 (with-output-to-temp-buffer "*Org Links*"
9190 (princ "Insert a link.
9191 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9192 (when org-stored-links
9193 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9194 (princ (mapconcat 'org-link-prettify
9195 (reverse org-stored-links) "\n"))))
9196 (let ((cw (selected-window)))
9197 (select-window (get-buffer-window "*Org Links*" 'visible))
9198 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9199 (unless (pos-visible-in-window-p (point-max))
9200 (org-fit-window-to-buffer))
9201 (and (window-live-p cw) (select-window cw)))
9202 ;; Fake a link history, containing the stored links.
9203 (setq tmphist (append (mapcar 'org-link-prettify org-stored-links)
9204 org-insert-link-history))
9205 (setq all-prefixes (append (mapcar 'car org-link-abbrev-alist-local)
9206 (mapcar 'car org-link-abbrev-alist)
9207 org-link-types))
9208 (unwind-protect
9209 (progn
9210 (setq link
9211 (let ((org-completion-use-ido nil)
9212 (org-completion-use-iswitchb nil))
9213 (org-completing-read
9214 "Link: "
9215 (append
9216 (mapcar (lambda (x) (list (concat x ":")))
9217 all-prefixes)
9218 (mapcar 'car org-stored-links))
9219 nil nil nil
9220 'tmphist
9221 (car (car org-stored-links)))))
9222 (if (not (string-match "\\S-" link))
9223 (error "No link selected"))
9224 (if (or (member link all-prefixes)
9225 (and (equal ":" (substring link -1))
9226 (member (substring link 0 -1) all-prefixes)
9227 (setq link (substring link 0 -1))))
9228 (setq link (org-link-try-special-completion link))))
9229 (set-window-configuration wcf)
9230 (kill-buffer "*Org Links*"))
9231 (setq entry (assoc link org-stored-links))
9232 (or entry (push link org-insert-link-history))
9233 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9234 (not org-keep-stored-link-after-insertion))
9235 (setq org-stored-links (delq (assoc link org-stored-links)
9236 org-stored-links)))
9237 (setq desc (or desc (nth 1 entry)))))
9239 (if (string-match org-plain-link-re link)
9240 ;; URL-like link, normalize the use of angular brackets.
9241 (setq link (org-make-link (org-remove-angle-brackets link))))
9243 ;; Check if we are linking to the current file with a search option
9244 ;; If yes, simplify the link by using only the search option.
9245 (when (and buffer-file-name
9246 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
9247 (let* ((path (match-string 1 link))
9248 (case-fold-search nil)
9249 (search (match-string 2 link)))
9250 (save-match-data
9251 (if (equal (file-truename buffer-file-name) (file-truename path))
9252 ;; We are linking to this same file, with a search option
9253 (setq link search)))))
9255 ;; Check if we can/should use a relative path. If yes, simplify the link
9256 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
9257 (let* ((type (match-string 1 link))
9258 (path (match-string 2 link))
9259 (origpath path)
9260 (case-fold-search nil))
9261 (cond
9262 ((or (eq org-link-file-path-type 'absolute)
9263 (equal complete-file '(16)))
9264 (setq path (abbreviate-file-name (expand-file-name path))))
9265 ((eq org-link-file-path-type 'noabbrev)
9266 (setq path (expand-file-name path)))
9267 ((eq org-link-file-path-type 'relative)
9268 (setq path (file-relative-name path)))
9270 (save-match-data
9271 (if (string-match (concat "^" (regexp-quote
9272 (expand-file-name
9273 (file-name-as-directory
9274 default-directory))))
9275 (expand-file-name path))
9276 ;; We are linking a file with relative path name.
9277 (setq path (substring (expand-file-name path)
9278 (match-end 0)))
9279 (setq path (abbreviate-file-name (expand-file-name path)))))))
9280 (setq link (concat type path))
9281 (if (equal desc origpath)
9282 (setq desc path))))
9284 (if org-make-link-description-function
9285 (setq desc (funcall org-make-link-description-function link desc))
9286 (if default-description (setq desc default-description)))
9288 (setq desc (read-string "Description: " desc))
9289 (unless (string-match "\\S-" desc) (setq desc nil))
9290 (if remove (apply 'delete-region remove))
9291 (insert (org-make-link-string link desc))))
9293 (defun org-link-try-special-completion (type)
9294 "If there is completion support for link type TYPE, offer it."
9295 (let ((fun (intern (concat "org-" type "-complete-link"))))
9296 (if (functionp fun)
9297 (funcall fun)
9298 (read-string "Link (no completion support): " (concat type ":")))))
9300 (defun org-file-complete-link (&optional arg)
9301 "Create a file link using completion."
9302 (let (file link)
9303 (setq file (read-file-name "File: "))
9304 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9305 (pwd1 (file-name-as-directory (abbreviate-file-name
9306 (expand-file-name ".")))))
9307 (cond
9308 ((equal arg '(16))
9309 (setq link (org-make-link
9310 "file:"
9311 (abbreviate-file-name (expand-file-name file)))))
9312 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9313 (setq link (org-make-link "file:" (match-string 1 file))))
9314 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9315 (expand-file-name file))
9316 (setq link (org-make-link
9317 "file:" (match-string 1 (expand-file-name file)))))
9318 (t (setq link (org-make-link "file:" file)))))
9319 link))
9321 (defun org-completing-read (&rest args)
9322 "Completing-read with SPACE being a normal character."
9323 (let ((enable-recursive-minibuffers t)
9324 (minibuffer-local-completion-map
9325 (copy-keymap minibuffer-local-completion-map)))
9326 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
9327 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
9328 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
9329 (apply 'org-icompleting-read args)))
9331 (defun org-completing-read-no-i (&rest args)
9332 (let (org-completion-use-ido org-completion-use-iswitchb)
9333 (apply 'org-completing-read args)))
9335 (defun org-iswitchb-completing-read (prompt choices &rest args)
9336 "Use iswitch as a completing-read replacement to choose from choices.
9337 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
9338 from."
9339 (let* ((iswitchb-use-virtual-buffers nil)
9340 (iswitchb-make-buflist-hook
9341 (lambda ()
9342 (setq iswitchb-temp-buflist choices))))
9343 (iswitchb-read-buffer prompt)))
9345 (defun org-icompleting-read (&rest args)
9346 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
9347 (org-without-partial-completion
9348 (if (and org-completion-use-ido
9349 (fboundp 'ido-completing-read)
9350 (boundp 'ido-mode) ido-mode
9351 (listp (second args)))
9352 (let ((ido-enter-matching-directory nil))
9353 (apply 'ido-completing-read (concat (car args))
9354 (if (consp (car (nth 1 args)))
9355 (mapcar 'car (nth 1 args))
9356 (nth 1 args))
9357 (cddr args)))
9358 (if (and org-completion-use-iswitchb
9359 (boundp 'iswitchb-mode) iswitchb-mode
9360 (listp (second args)))
9361 (apply 'org-iswitchb-completing-read (concat (car args))
9362 (if (consp (car (nth 1 args)))
9363 (mapcar 'car (nth 1 args))
9364 (nth 1 args))
9365 (cddr args))
9366 (apply 'completing-read args)))))
9368 (defun org-extract-attributes (s)
9369 "Extract the attributes cookie from a string and set as text property."
9370 (let (a attr (start 0) key value)
9371 (save-match-data
9372 (when (string-match "{{\\([^}]+\\)}}$" s)
9373 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
9374 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
9375 (setq key (match-string 1 a) value (match-string 2 a)
9376 start (match-end 0)
9377 attr (plist-put attr (intern key) value))))
9378 (org-add-props s nil 'org-attr attr))
9381 (defun org-extract-attributes-from-string (tag)
9382 (let (key value attr)
9383 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
9384 (setq key (match-string 1 tag) value (match-string 2 tag)
9385 tag (replace-match "" t t tag)
9386 attr (plist-put attr (intern key) value)))
9387 (cons tag attr)))
9389 (defun org-attributes-to-string (plist)
9390 "Format a property list into an HTML attribute list."
9391 (let ((s "") key value)
9392 (while plist
9393 (setq key (pop plist) value (pop plist))
9394 (and value
9395 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
9398 ;;; Opening/following a link
9400 (defvar org-link-search-failed nil)
9402 (defvar org-open-link-functions nil
9403 "Hook for functions finding a plain text link.
9404 These functions must take a single argument, the link content.
9405 They will be called for links that look like [[link text][description]]
9406 when LINK TEXT does not have a protocol like \"http:\" and does not look
9407 like a filename (e.g. \"./blue.png\").
9409 These functions will be called *before* Org attempts to resolve the
9410 link by doing text searches in the current buffer - so if you want a
9411 link \"[[target]]\" to still find \"<<target>>\", your function should
9412 handle this as a special case.
9414 When the function does handle the link, it must return a non-nil value.
9415 If it decides that it is not responsible for this link, it must return
9416 nil to indicate that that Org-mode can continue with other options
9417 like exact and fuzzy text search.")
9419 (defun org-next-link ()
9420 "Move forward to the next link.
9421 If the link is in hidden text, expose it."
9422 (interactive)
9423 (when (and org-link-search-failed (eq this-command last-command))
9424 (goto-char (point-min))
9425 (message "Link search wrapped back to beginning of buffer"))
9426 (setq org-link-search-failed nil)
9427 (let* ((pos (point))
9428 (ct (org-context))
9429 (a (assoc :link ct)))
9430 (if a (goto-char (nth 2 a)))
9431 (if (re-search-forward org-any-link-re nil t)
9432 (progn
9433 (goto-char (match-beginning 0))
9434 (if (outline-invisible-p) (org-show-context)))
9435 (goto-char pos)
9436 (setq org-link-search-failed t)
9437 (error "No further link found"))))
9439 (defun org-previous-link ()
9440 "Move backward to the previous link.
9441 If the link is in hidden text, expose it."
9442 (interactive)
9443 (when (and org-link-search-failed (eq this-command last-command))
9444 (goto-char (point-max))
9445 (message "Link search wrapped back to end of buffer"))
9446 (setq org-link-search-failed nil)
9447 (let* ((pos (point))
9448 (ct (org-context))
9449 (a (assoc :link ct)))
9450 (if a (goto-char (nth 1 a)))
9451 (if (re-search-backward org-any-link-re nil t)
9452 (progn
9453 (goto-char (match-beginning 0))
9454 (if (outline-invisible-p) (org-show-context)))
9455 (goto-char pos)
9456 (setq org-link-search-failed t)
9457 (error "No further link found"))))
9459 (defun org-translate-link (s)
9460 "Translate a link string if a translation function has been defined."
9461 (if (and org-link-translation-function
9462 (fboundp org-link-translation-function)
9463 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
9464 (progn
9465 (setq s (funcall org-link-translation-function
9466 (match-string 1) (match-string 2)))
9467 (concat (car s) ":" (cdr s)))
9470 (defun org-translate-link-from-planner (type path)
9471 "Translate a link from Emacs Planner syntax so that Org can follow it.
9472 This is still an experimental function, your mileage may vary."
9473 (cond
9474 ((member type '("http" "https" "news" "ftp"))
9475 ;; standard Internet links are the same.
9476 nil)
9477 ((and (equal type "irc") (string-match "^//" path))
9478 ;; Planner has two / at the beginning of an irc link, we have 1.
9479 ;; We should have zero, actually....
9480 (setq path (substring path 1)))
9481 ((and (equal type "lisp") (string-match "^/" path))
9482 ;; Planner has a slash, we do not.
9483 (setq type "elisp" path (substring path 1)))
9484 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9485 ;; A typical message link. Planner has the id after the final slash,
9486 ;; we separate it with a hash mark
9487 (setq path (concat (match-string 1 path) "#"
9488 (org-remove-angle-brackets (match-string 2 path)))))
9490 (cons type path))
9492 (defun org-find-file-at-mouse (ev)
9493 "Open file link or URL at mouse."
9494 (interactive "e")
9495 (mouse-set-point ev)
9496 (org-open-at-point 'in-emacs))
9498 (defun org-open-at-mouse (ev)
9499 "Open file link or URL at mouse.
9500 See the docstring of `org-open-file' for details."
9501 (interactive "e")
9502 (mouse-set-point ev)
9503 (if (eq major-mode 'org-agenda-mode)
9504 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
9505 (org-open-at-point))
9507 (defvar org-window-config-before-follow-link nil
9508 "The window configuration before following a link.
9509 This is saved in case the need arises to restore it.")
9511 (defvar org-open-link-marker (make-marker)
9512 "Marker pointing to the location where `org-open-at-point; was called.")
9514 ;;;###autoload
9515 (defun org-open-at-point-global ()
9516 "Follow a link like Org-mode does.
9517 This command can be called in any mode to follow a link that has
9518 Org-mode syntax."
9519 (interactive)
9520 (org-run-like-in-org-mode 'org-open-at-point))
9522 ;;;###autoload
9523 (defun org-open-link-from-string (s &optional arg reference-buffer)
9524 "Open a link in the string S, as if it was in Org-mode."
9525 (interactive "sLink: \nP")
9526 (let ((reference-buffer (or reference-buffer (current-buffer))))
9527 (with-temp-buffer
9528 (let ((org-inhibit-startup (not reference-buffer)))
9529 (org-mode)
9530 (insert s)
9531 (goto-char (point-min))
9532 (when reference-buffer
9533 (setq org-link-abbrev-alist-local
9534 (with-current-buffer reference-buffer
9535 org-link-abbrev-alist-local)))
9536 (org-open-at-point arg reference-buffer)))))
9538 (defvar org-open-at-point-functions nil
9539 "Hook that is run when following a link at point.
9541 Functions in this hook must return t if they identify and follow
9542 a link at point. If they don't find anything interesting at point,
9543 they must return nil.")
9545 (defun org-open-at-point (&optional arg reference-buffer)
9546 "Open link at or after point.
9547 If there is no link at point, this function will search forward up to
9548 the end of the current line.
9549 Normally, files will be opened by an appropriate application. If the
9550 optional prefix argument ARG is non-nil, Emacs will visit the file.
9551 With a double prefix argument, try to open outside of Emacs, in the
9552 application the system uses for this file type."
9553 (interactive "P")
9554 ;; if in a code block, then open the block's results
9555 (unless (call-interactively #'org-babel-open-src-block-result)
9556 (org-load-modules-maybe)
9557 (move-marker org-open-link-marker (point))
9558 (setq org-window-config-before-follow-link (current-window-configuration))
9559 (org-remove-occur-highlights nil nil t)
9560 (cond
9561 ((and (org-at-heading-p)
9562 (not (org-in-regexp
9563 (concat org-plain-link-re "\\|"
9564 org-bracket-link-regexp "\\|"
9565 org-angle-link-re "\\|"
9566 "[ \t]:[^ \t\n]+:[ \t]*$")))
9567 (not (get-text-property (point) 'org-linked-text)))
9568 (or (org-offer-links-in-entry arg)
9569 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
9570 ((run-hook-with-args-until-success 'org-open-at-point-functions))
9571 ((org-at-timestamp-p t) (org-follow-timestamp-link))
9572 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
9573 (not (org-in-regexp org-bracket-link-regexp)))
9574 (org-footnote-action))
9576 (let (type path link line search (pos (point)))
9577 (catch 'match
9578 (save-excursion
9579 (skip-chars-forward "^]\n\r")
9580 (when (org-in-regexp org-bracket-link-regexp 1)
9581 (setq link (org-extract-attributes
9582 (org-link-unescape (org-match-string-no-properties 1))))
9583 (while (string-match " *\n *" link)
9584 (setq link (replace-match " " t t link)))
9585 (setq link (org-link-expand-abbrev link))
9586 (cond
9587 ((or (file-name-absolute-p link)
9588 (string-match "^\\.\\.?/" link))
9589 (setq type "file" path link))
9590 ((string-match org-link-re-with-space3 link)
9591 (setq type (match-string 1 link) path (match-string 2 link)))
9592 (t (setq type "thisfile" path link)))
9593 (throw 'match t)))
9595 (when (get-text-property (point) 'org-linked-text)
9596 (setq type "thisfile"
9597 pos (if (get-text-property (1+ (point)) 'org-linked-text)
9598 (1+ (point)) (point))
9599 path (buffer-substring
9600 (or (previous-single-property-change pos 'org-linked-text)
9601 (point-min))
9602 (or (next-single-property-change pos 'org-linked-text)
9603 (point-max))))
9604 (throw 'match t))
9606 (save-excursion
9607 (when (or (org-in-regexp org-angle-link-re)
9608 (org-in-regexp org-plain-link-re))
9609 (setq type (match-string 1)
9610 path (org-link-unescape (match-string 2)))
9611 (throw 'match t)))
9612 (save-excursion
9613 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
9614 (setq type "tags"
9615 path (match-string 1))
9616 (while (string-match ":" path)
9617 (setq path (replace-match "+" t t path)))
9618 (throw 'match t)))
9619 (when (org-in-regexp "<\\([^><\n]+\\)>")
9620 (setq type "tree-match"
9621 path (match-string 1))
9622 (throw 'match t)))
9623 (unless path
9624 (error "No link found"))
9626 ;; switch back to reference buffer
9627 ;; needed when if called in a temporary buffer through
9628 ;; org-open-link-from-string
9629 (with-current-buffer (or reference-buffer (current-buffer))
9631 ;; Remove any trailing spaces in path
9632 (if (string-match " +\\'" path)
9633 (setq path (replace-match "" t t path)))
9634 (if (and org-link-translation-function
9635 (fboundp org-link-translation-function))
9636 ;; Check if we need to translate the link
9637 (let ((tmp (funcall org-link-translation-function type path)))
9638 (setq type (car tmp) path (cdr tmp))))
9640 (cond
9642 ((assoc type org-link-protocols)
9643 (funcall (nth 1 (assoc type org-link-protocols)) path))
9645 ((equal type "mailto")
9646 (let ((cmd (car org-link-mailto-program))
9647 (args (cdr org-link-mailto-program)) args1
9648 (address path) (subject "") a)
9649 (if (string-match "\\(.*\\)::\\(.*\\)" path)
9650 (setq address (match-string 1 path)
9651 subject (org-link-escape (match-string 2 path))))
9652 (while args
9653 (cond
9654 ((not (stringp (car args))) (push (pop args) args1))
9655 (t (setq a (pop args))
9656 (if (string-match "%a" a)
9657 (setq a (replace-match address t t a)))
9658 (if (string-match "%s" a)
9659 (setq a (replace-match subject t t a)))
9660 (push a args1))))
9661 (apply cmd (nreverse args1))))
9663 ((member type '("http" "https" "ftp" "news"))
9664 (browse-url (concat type ":" (if (org-string-match-p "[[:nonascii:] ]" path)
9665 (org-link-escape
9666 path org-link-escape-chars-browser)
9667 path))))
9669 ((string= type "doi")
9670 (browse-url (concat "http://dx.doi.org/" (if (org-string-match-p "[[:nonascii:] ]" path)
9671 (org-link-escape
9672 path org-link-escape-chars-browser)
9673 path))))
9675 ((member type '("message"))
9676 (browse-url (concat type ":" path)))
9678 ((string= type "tags")
9679 (org-tags-view arg path))
9681 ((string= type "tree-match")
9682 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
9684 ((string= type "file")
9685 (if (string-match "::\\([0-9]+\\)\\'" path)
9686 (setq line (string-to-number (match-string 1 path))
9687 path (substring path 0 (match-beginning 0)))
9688 (if (string-match "::\\(.+\\)\\'" path)
9689 (setq search (match-string 1 path)
9690 path (substring path 0 (match-beginning 0)))))
9691 (if (string-match "[*?{]" (file-name-nondirectory path))
9692 (dired path)
9693 (org-open-file path arg line search)))
9695 ((string= type "shell")
9696 (let ((cmd path))
9697 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
9698 (string-match org-confirm-shell-link-not-regexp cmd))
9699 (not org-confirm-shell-link-function)
9700 (funcall org-confirm-shell-link-function
9701 (format "Execute \"%s\" in shell? "
9702 (org-add-props cmd nil
9703 'face 'org-warning))))
9704 (progn
9705 (message "Executing %s" cmd)
9706 (shell-command cmd))
9707 (error "Abort"))))
9709 ((string= type "elisp")
9710 (let ((cmd path))
9711 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
9712 (string-match org-confirm-elisp-link-not-regexp cmd))
9713 (not org-confirm-elisp-link-function)
9714 (funcall org-confirm-elisp-link-function
9715 (format "Execute \"%s\" as elisp? "
9716 (org-add-props cmd nil
9717 'face 'org-warning))))
9718 (message "%s => %s" cmd
9719 (if (equal (string-to-char cmd) ?\()
9720 (eval (read cmd))
9721 (call-interactively (read cmd))))
9722 (error "Abort"))))
9724 ((and (string= type "thisfile")
9725 (run-hook-with-args-until-success
9726 'org-open-link-functions path)))
9728 ((string= type "thisfile")
9729 (if arg
9730 (switch-to-buffer-other-window
9731 (org-get-buffer-for-internal-link (current-buffer)))
9732 (org-mark-ring-push))
9733 (let ((cmd `(org-link-search
9734 ,path
9735 ,(cond ((equal arg '(4)) ''occur)
9736 ((equal arg '(16)) ''org-occur)
9737 (t nil))
9738 ,pos)))
9739 (condition-case nil (let ((org-link-search-inhibit-query t))
9740 (eval cmd))
9741 (error (progn (widen) (eval cmd))))))
9744 (browse-url-at-point)))))))
9745 (move-marker org-open-link-marker nil)
9746 (run-hook-with-args 'org-follow-link-hook)))
9748 (defun org-offer-links-in-entry (&optional nth zero)
9749 "Offer links in the current entry and follow the selected link.
9750 If there is only one link, follow it immediately as well.
9751 If NTH is an integer, immediately pick the NTH link found.
9752 If ZERO is a string, check also this string for a link, and if
9753 there is one, offer it as link number zero."
9754 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
9755 "\\(" org-angle-link-re "\\)\\|"
9756 "\\(" org-plain-link-re "\\)"))
9757 (cnt ?0)
9758 (in-emacs (if (integerp nth) nil nth))
9759 have-zero end links link c)
9760 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
9761 (push (match-string 0 zero) links)
9762 (setq cnt (1- cnt) have-zero t))
9763 (save-excursion
9764 (org-back-to-heading t)
9765 (setq end (save-excursion (outline-next-heading) (point)))
9766 (while (re-search-forward re end t)
9767 (push (match-string 0) links))
9768 (setq links (org-uniquify (reverse links))))
9770 (cond
9771 ((null links)
9772 (message "No links"))
9773 ((equal (length links) 1)
9774 (setq link (list (car links))))
9775 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
9776 (setq link (list (nth (if have-zero nth (1- nth)) links))))
9777 (t ; we have to select a link
9778 (save-excursion
9779 (save-window-excursion
9780 (delete-other-windows)
9781 (with-output-to-temp-buffer "*Select Link*"
9782 (mapc (lambda (l)
9783 (if (not (string-match org-bracket-link-regexp l))
9784 (princ (format "[%c] %s\n" (incf cnt)
9785 (org-remove-angle-brackets l)))
9786 (if (match-end 3)
9787 (princ (format "[%c] %s (%s)\n" (incf cnt)
9788 (match-string 3 l) (match-string 1 l)))
9789 (princ (format "[%c] %s\n" (incf cnt)
9790 (match-string 1 l))))))
9791 links))
9792 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
9793 (message "Select link to open, RET to open all:")
9794 (setq c (read-char-exclusive))
9795 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
9796 (when (equal c ?q) (error "Abort"))
9797 (if (equal c ?\C-m)
9798 (setq link links)
9799 (setq nth (- c ?0))
9800 (if have-zero (setq nth (1+ nth)))
9801 (unless (and (integerp nth) (>= (length links) nth))
9802 (error "Invalid link selection"))
9803 (setq link (list (nth (1- nth) links))))))
9804 (if link
9805 (let ((buf (current-buffer)))
9806 (dolist (l link)
9807 (org-open-link-from-string l in-emacs buf))
9809 nil)))
9811 ;; Add special file links that specify the way of opening
9813 (org-add-link-type "file+sys" 'org-open-file-with-system)
9814 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
9815 (defun org-open-file-with-system (path)
9816 "Open file at PATH using the system way of opening it."
9817 (org-open-file path 'system))
9818 (defun org-open-file-with-emacs (path)
9819 "Open file at PATH in Emacs."
9820 (org-open-file path 'emacs))
9821 (defun org-remove-file-link-modifiers ()
9822 "Remove the file link modifiers in `file+sys:' and `file+emacs:' links."
9823 (goto-char (point-min))
9824 (while (re-search-forward "\\<file\\+\\(sys\\|emacs\\):" nil t)
9825 (org-if-unprotected
9826 (replace-match "file:" t t))))
9827 (eval-after-load "org-exp"
9828 '(add-hook 'org-export-preprocess-before-normalizing-links-hook
9829 'org-remove-file-link-modifiers))
9831 ;;;; Time estimates
9833 (defun org-get-effort (&optional pom)
9834 "Get the effort estimate for the current entry."
9835 (org-entry-get pom org-effort-property))
9837 ;;; File search
9839 (defvar org-create-file-search-functions nil
9840 "List of functions to construct the right search string for a file link.
9841 These functions are called in turn with point at the location to
9842 which the link should point.
9844 A function in the hook should first test if it would like to
9845 handle this file type, for example by checking the `major-mode'
9846 or the file extension. If it decides not to handle this file, it
9847 should just return nil to give other functions a chance. If it
9848 does handle the file, it must return the search string to be used
9849 when following the link. The search string will be part of the
9850 file link, given after a double colon, and `org-open-at-point'
9851 will automatically search for it. If special measures must be
9852 taken to make the search successful, another function should be
9853 added to the companion hook `org-execute-file-search-functions',
9854 which see.
9856 A function in this hook may also use `setq' to set the variable
9857 `description' to provide a suggestion for the descriptive text to
9858 be used for this link when it gets inserted into an Org-mode
9859 buffer with \\[org-insert-link].")
9861 (defvar org-execute-file-search-functions nil
9862 "List of functions to execute a file search triggered by a link.
9864 Functions added to this hook must accept a single argument, the
9865 search string that was part of the file link, the part after the
9866 double colon. The function must first check if it would like to
9867 handle this search, for example by checking the `major-mode' or
9868 the file extension. If it decides not to handle this search, it
9869 should just return nil to give other functions a chance. If it
9870 does handle the search, it must return a non-nil value to keep
9871 other functions from trying.
9873 Each function can access the current prefix argument through the
9874 variable `current-prefix-argument'. Note that a single prefix is
9875 used to force opening a link in Emacs, so it may be good to only
9876 use a numeric or double prefix to guide the search function.
9878 In case this is needed, a function in this hook can also restore
9879 the window configuration before `org-open-at-point' was called using:
9881 (set-window-configuration org-window-config-before-follow-link)")
9883 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
9884 (defun org-link-search (s &optional type avoid-pos stealth)
9885 "Search for a link search option.
9886 If S is surrounded by forward slashes, it is interpreted as a
9887 regular expression. In org-mode files, this will create an `org-occur'
9888 sparse tree. In ordinary files, `occur' will be used to list matches.
9889 If the current buffer is in `dired-mode', grep will be used to search
9890 in all files. If AVOID-POS is given, ignore matches near that position.
9892 When optional argument STEALTH is non-nil, do not modify
9893 visibility around point, thus ignoring
9894 `org-show-hierarchy-above', `org-show-following-heading' and
9895 `org-show-siblings' variables."
9896 (let ((case-fold-search t)
9897 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
9898 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
9899 (append '(("") (" ") ("\t") ("\n"))
9900 org-emphasis-alist)
9901 "\\|") "\\)"))
9902 (pos (point))
9903 (pre nil) (post nil)
9904 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
9905 (cond
9906 ;; First check if there are any special search functions
9907 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
9908 ;; Now try the builtin stuff
9909 ((and (equal (string-to-char s0) ?#)
9910 (> (length s0) 1)
9911 (save-excursion
9912 (goto-char (point-min))
9913 (and
9914 (re-search-forward
9915 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
9916 (setq type 'dedicated
9917 pos (match-beginning 0))))
9918 ;; There is an exact target for this
9919 (goto-char pos)
9920 (org-back-to-heading t)))
9921 ((save-excursion
9922 (goto-char (point-min))
9923 (and
9924 (re-search-forward
9925 (concat "<<" (regexp-quote s0) ">>") nil t)
9926 (setq type 'dedicated
9927 pos (match-beginning 0))))
9928 ;; There is an exact target for this
9929 (goto-char pos))
9930 ((save-excursion
9931 (goto-char (point-min))
9932 (and
9933 (re-search-forward
9934 (format "^[ \t]*#\\+TARGET: %s" (regexp-quote s0)) nil t)
9935 (setq type 'dedicated pos (match-beginning 0))))
9936 ;; Found an invisible target.
9937 (goto-char pos))
9938 ((save-excursion
9939 (goto-char (point-min))
9940 (and
9941 (re-search-forward
9942 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
9943 (setq type 'dedicated pos (match-beginning 0))))
9944 ;; Found an element with a matching #+name affiliated keyword.
9945 (goto-char pos))
9946 ((and (string-match "^(\\(.*\\))$" s0)
9947 (save-excursion
9948 (goto-char (point-min))
9949 (and
9950 (re-search-forward
9951 (concat "[^[]" (regexp-quote
9952 (format org-coderef-label-format
9953 (match-string 1 s0))))
9954 nil t)
9955 (setq type 'dedicated
9956 pos (1+ (match-beginning 0))))))
9957 ;; There is a coderef target for this
9958 (goto-char pos))
9959 ((string-match "^/\\(.*\\)/$" s)
9960 ;; A regular expression
9961 (cond
9962 ((derived-mode-p 'org-mode)
9963 (org-occur (match-string 1 s)))
9964 ;;((eq major-mode 'dired-mode)
9965 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
9966 (t (org-do-occur (match-string 1 s)))))
9967 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
9968 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
9969 (goto-char (point-min))
9970 (cond
9971 ((let (case-fold-search)
9972 (re-search-forward (format org-complex-heading-regexp-format
9973 (regexp-quote s))
9974 nil t))
9975 ;; OK, found a match
9976 (setq type 'dedicated)
9977 (goto-char (match-beginning 0)))
9978 ((and (not org-link-search-inhibit-query)
9979 (eq org-link-search-must-match-exact-headline 'query-to-create)
9980 (y-or-n-p "No match - create this as a new heading? "))
9981 (goto-char (point-max))
9982 (or (bolp) (newline))
9983 (insert "* " s "\n")
9984 (beginning-of-line 0))
9986 (goto-char pos)
9987 (error "No match"))))
9989 ;; A normal search string
9990 (when (equal (string-to-char s) ?*)
9991 ;; Anchor on headlines, post may include tags.
9992 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
9993 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
9994 s (substring s 1)))
9995 (remove-text-properties
9996 0 (length s)
9997 '(face nil mouse-face nil keymap nil fontified nil) s)
9998 ;; Make a series of regular expressions to find a match
9999 (setq words (org-split-string s "[ \n\r\t]+")
10001 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10002 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10003 "\\)" markers)
10004 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
10005 re2a (concat "[ \t\r\n]" re2a_)
10006 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10007 re4 (concat "[^a-zA-Z_]" re4_)
10009 re1 (concat pre re2 post)
10010 re3 (concat pre (if pre re4_ re4) post)
10011 re5 (concat pre ".*" re4)
10012 re2 (concat pre re2)
10013 re2a (concat pre (if pre re2a_ re2a))
10014 re4 (concat pre (if pre re4_ re4))
10015 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10016 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10017 re5 "\\)"
10019 (cond
10020 ((eq type 'org-occur) (org-occur reall))
10021 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10022 (t (goto-char (point-min))
10023 (setq type 'fuzzy)
10024 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
10025 (org-search-not-self 1 re1 nil t)
10026 (org-search-not-self 1 re2 nil t)
10027 (org-search-not-self 1 re2a nil t)
10028 (org-search-not-self 1 re3 nil t)
10029 (org-search-not-self 1 re4 nil t)
10030 (org-search-not-self 1 re5 nil t)
10032 (goto-char (match-beginning 1))
10033 (goto-char pos)
10034 (error "No match"))))))
10035 (and (derived-mode-p 'org-mode)
10036 (not stealth)
10037 (org-show-context 'link-search))
10038 type))
10040 (defun org-search-not-self (group &rest args)
10041 "Execute `re-search-forward', but only accept matches that do not
10042 enclose the position of `org-open-link-marker'."
10043 (let ((m org-open-link-marker))
10044 (catch 'exit
10045 (while (apply 're-search-forward args)
10046 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10047 (goto-char (match-end group))
10048 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10049 (> (match-beginning 0) (marker-position m))
10050 (< (match-end 0) (marker-position m)))
10051 (save-match-data
10052 (or (not (org-in-regexp
10053 org-bracket-link-analytic-regexp 1))
10054 (not (match-end 4)) ; no description
10055 (and (<= (match-beginning 4) (point))
10056 (>= (match-end 4) (point))))))
10057 (throw 'exit (point))))))))
10059 (defun org-get-buffer-for-internal-link (buffer)
10060 "Return a buffer to be used for displaying the link target of internal links."
10061 (cond
10062 ((not org-display-internal-link-with-indirect-buffer)
10063 buffer)
10064 ((string-match "(Clone)$" (buffer-name buffer))
10065 (message "Buffer is already a clone, not making another one")
10066 ;; we also do not modify visibility in this case
10067 buffer)
10068 (t ; make a new indirect buffer for displaying the link
10069 (let* ((bn (buffer-name buffer))
10070 (ibn (concat bn "(Clone)"))
10071 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10072 (with-current-buffer ib (org-overview))
10073 ib))))
10075 (defun org-do-occur (regexp &optional cleanup)
10076 "Call the Emacs command `occur'.
10077 If CLEANUP is non-nil, remove the printout of the regular expression
10078 in the *Occur* buffer. This is useful if the regex is long and not useful
10079 to read."
10080 (occur regexp)
10081 (when cleanup
10082 (let ((cwin (selected-window)) win beg end)
10083 (when (setq win (get-buffer-window "*Occur*"))
10084 (select-window win))
10085 (goto-char (point-min))
10086 (when (re-search-forward "match[a-z]+" nil t)
10087 (setq beg (match-end 0))
10088 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10089 (setq end (1- (match-beginning 0)))))
10090 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10091 (goto-char (point-min))
10092 (select-window cwin))))
10094 ;;; The mark ring for links jumps
10096 (defvar org-mark-ring nil
10097 "Mark ring for positions before jumps in Org-mode.")
10098 (defvar org-mark-ring-last-goto nil
10099 "Last position in the mark ring used to go back.")
10100 ;; Fill and close the ring
10101 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10102 (loop for i from 1 to org-mark-ring-length do
10103 (push (make-marker) org-mark-ring))
10104 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10105 org-mark-ring)
10107 (defun org-mark-ring-push (&optional pos buffer)
10108 "Put the current position or POS into the mark ring and rotate it."
10109 (interactive)
10110 (setq pos (or pos (point)))
10111 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10112 (move-marker (car org-mark-ring)
10113 (or pos (point))
10114 (or buffer (current-buffer)))
10115 (message "%s"
10116 (substitute-command-keys
10117 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10119 (defun org-mark-ring-goto (&optional n)
10120 "Jump to the previous position in the mark ring.
10121 With prefix arg N, jump back that many stored positions. When
10122 called several times in succession, walk through the entire ring.
10123 Org-mode commands jumping to a different position in the current file,
10124 or to another Org-mode file, automatically push the old position
10125 onto the ring."
10126 (interactive "p")
10127 (let (p m)
10128 (if (eq last-command this-command)
10129 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10130 (setq p org-mark-ring))
10131 (setq org-mark-ring-last-goto p)
10132 (setq m (car p))
10133 (org-pop-to-buffer-same-window (marker-buffer m))
10134 (goto-char m)
10135 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10137 (defun org-remove-angle-brackets (s)
10138 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10139 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10141 (defun org-add-angle-brackets (s)
10142 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10143 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10145 (defun org-remove-double-quotes (s)
10146 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10147 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10150 ;;; Following specific links
10152 (defun org-follow-timestamp-link ()
10153 (cond
10154 ((org-at-date-range-p t)
10155 (let ((org-agenda-start-on-weekday)
10156 (t1 (match-string 1))
10157 (t2 (match-string 2)))
10158 (setq t1 (time-to-days (org-time-string-to-time t1))
10159 t2 (time-to-days (org-time-string-to-time t2)))
10160 (org-agenda-list nil t1 (1+ (- t2 t1)))))
10161 ((org-at-timestamp-p t)
10162 (org-agenda-list nil (time-to-days (org-time-string-to-time
10163 (substring (match-string 1) 0 10)))
10165 (t (error "This should not happen"))))
10168 ;;; Following file links
10169 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10170 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10171 (declare-function mailcap-mime-info
10172 "mailcap" (string &optional request no-decode))
10173 (defvar org-wait nil)
10174 (defun org-open-file (path &optional in-emacs line search)
10175 "Open the file at PATH.
10176 First, this expands any special file name abbreviations. Then the
10177 configuration variable `org-file-apps' is checked if it contains an
10178 entry for this file type, and if yes, the corresponding command is launched.
10180 If no application is found, Emacs simply visits the file.
10182 With optional prefix argument IN-EMACS, Emacs will visit the file.
10183 With a double \\[universal-argument] \\[universal-argument] \
10184 prefix arg, Org tries to avoid opening in Emacs
10185 and to use an external application to visit the file.
10187 Optional LINE specifies a line to go to, optional SEARCH a string
10188 to search for. If LINE or SEARCH is given, the file will be
10189 opened in Emacs, unless an entry from org-file-apps that makes
10190 use of groups in a regexp matches.
10192 If you want to change the way frames are used when following a
10193 link, please customize `org-link-frame-setup'.
10195 If the file does not exist, an error is thrown."
10196 (let* ((file (if (equal path "")
10197 buffer-file-name
10198 (substitute-in-file-name (expand-file-name path))))
10199 (file-apps (append org-file-apps (org-default-apps)))
10200 (apps (org-remove-if
10201 'org-file-apps-entry-match-against-dlink-p file-apps))
10202 (apps-dlink (org-remove-if-not
10203 'org-file-apps-entry-match-against-dlink-p file-apps))
10204 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10205 (dirp (if remp nil (file-directory-p file)))
10206 (file (if (and dirp org-open-directory-means-index-dot-org)
10207 (concat (file-name-as-directory file) "index.org")
10208 file))
10209 (a-m-a-p (assq 'auto-mode apps))
10210 (dfile (downcase file))
10211 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10212 (link (cond ((and (eq line nil)
10213 (eq search nil))
10214 file)
10215 (line
10216 (concat file "::" (number-to-string line)))
10217 (search
10218 (concat file "::" search))))
10219 (dlink (downcase link))
10220 (old-buffer (current-buffer))
10221 (old-pos (point))
10222 (old-mode major-mode)
10223 ext cmd link-match-data)
10224 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10225 (setq ext (match-string 1 dfile))
10226 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10227 (setq ext (match-string 1 dfile))))
10228 (cond
10229 ((member in-emacs '((16) system))
10230 (setq cmd (cdr (assoc 'system apps))))
10231 (in-emacs (setq cmd 'emacs))
10233 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10234 (and dirp (cdr (assoc 'directory apps)))
10235 ; first, try matching against apps-dlink
10236 ; if we get a match here, store the match data for later
10237 (let ((match (assoc-default dlink apps-dlink
10238 'string-match)))
10239 (if match
10240 (progn (setq link-match-data (match-data))
10241 match)
10242 (progn (setq in-emacs (or in-emacs line search))
10243 nil))) ; if we have no match in apps-dlink,
10244 ; always open the file in emacs if line or search
10245 ; is given (for backwards compatibility)
10246 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10247 'string-match)
10248 (cdr (assoc ext apps))
10249 (cdr (assoc t apps))))))
10250 (when (eq cmd 'system)
10251 (setq cmd (cdr (assoc 'system apps))))
10252 (when (eq cmd 'default)
10253 (setq cmd (cdr (assoc t apps))))
10254 (when (eq cmd 'mailcap)
10255 (require 'mailcap)
10256 (mailcap-parse-mailcaps)
10257 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10258 (command (mailcap-mime-info mime-type)))
10259 (if (stringp command)
10260 (setq cmd command)
10261 (setq cmd 'emacs))))
10262 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10263 (not (file-exists-p file))
10264 (not org-open-non-existing-files))
10265 (error "No such file: %s" file))
10266 (cond
10267 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10268 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10269 (while (string-match "['\"]%s['\"]" cmd)
10270 (setq cmd (replace-match "%s" t t cmd)))
10271 (while (string-match "%s" cmd)
10272 (setq cmd (replace-match
10273 (save-match-data
10274 (shell-quote-argument
10275 (convert-standard-filename file)))
10276 t t cmd)))
10278 ;; Replace "%1", "%2" etc. in command with group matches from regex
10279 (save-match-data
10280 (let ((match-index 1)
10281 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10282 (set-match-data link-match-data)
10283 (while (<= match-index number-of-groups)
10284 (let ((regex (concat "%" (number-to-string match-index)))
10285 (replace-with (match-string match-index dlink)))
10286 (while (string-match regex cmd)
10287 (setq cmd (replace-match replace-with t t cmd))))
10288 (setq match-index (+ match-index 1)))))
10290 (save-window-excursion
10291 (start-process-shell-command cmd nil cmd)
10292 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
10294 ((or (stringp cmd)
10295 (eq cmd 'emacs))
10296 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10297 (widen)
10298 (if line (org-goto-line line)
10299 (if search (org-link-search search))))
10300 ((consp cmd)
10301 (let ((file (convert-standard-filename file)))
10302 (save-match-data
10303 (set-match-data link-match-data)
10304 (eval cmd))))
10305 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10306 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
10307 (or (not (equal old-buffer (current-buffer)))
10308 (not (equal old-pos (point))))
10309 (org-mark-ring-push old-pos old-buffer))))
10311 (defun org-file-apps-entry-match-against-dlink-p (entry)
10312 "This function returns non-nil if `entry' uses a regular
10313 expression which should be matched against the whole link by
10314 org-open-file.
10316 It assumes that is the case when the entry uses a regular
10317 expression which has at least one grouping construct and the
10318 action is either a lisp form or a command string containing
10319 '%1', i.e. using at least one subexpression match as a
10320 parameter."
10321 (let ((selector (car entry))
10322 (action (cdr entry)))
10323 (if (stringp selector)
10324 (and (> (regexp-opt-depth selector) 0)
10325 (or (and (stringp action)
10326 (string-match "%[0-9]" action))
10327 (consp action)))
10328 nil)))
10330 (defun org-default-apps ()
10331 "Return the default applications for this operating system."
10332 (cond
10333 ((eq system-type 'darwin)
10334 org-file-apps-defaults-macosx)
10335 ((eq system-type 'windows-nt)
10336 org-file-apps-defaults-windowsnt)
10337 (t org-file-apps-defaults-gnu)))
10339 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10340 "Convert extensions to regular expressions in the cars of LIST.
10341 Also, weed out any non-string entries, because the return value is used
10342 only for regexp matching.
10343 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10344 point to the symbol `emacs', indicating that the file should
10345 be opened in Emacs."
10346 (append
10347 (delq nil
10348 (mapcar (lambda (x)
10349 (if (not (stringp (car x)))
10351 (if (string-match "\\W" (car x))
10353 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10354 list))
10355 (if add-auto-mode
10356 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10358 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10359 (defun org-file-remote-p (file)
10360 "Test whether FILE specifies a location on a remote system.
10361 Return non-nil if the location is indeed remote.
10363 For example, the filename \"/user@host:/foo\" specifies a location
10364 on the system \"/user@host:\"."
10365 (cond ((fboundp 'file-remote-p)
10366 (file-remote-p file))
10367 ((fboundp 'tramp-handle-file-remote-p)
10368 (tramp-handle-file-remote-p file))
10369 ((and (boundp 'ange-ftp-name-format)
10370 (string-match (car ange-ftp-name-format) file))
10372 (t nil)))
10375 ;;;; Refiling
10377 (defun org-get-org-file ()
10378 "Read a filename, with default directory `org-directory'."
10379 (let ((default (or org-default-notes-file remember-data-file)))
10380 (read-file-name (format "File name [%s]: " default)
10381 (file-name-as-directory org-directory)
10382 default)))
10384 (defun org-notes-order-reversed-p ()
10385 "Check if the current file should receive notes in reversed order."
10386 (cond
10387 ((not org-reverse-note-order) nil)
10388 ((eq t org-reverse-note-order) t)
10389 ((not (listp org-reverse-note-order)) nil)
10390 (t (catch 'exit
10391 (let ((all org-reverse-note-order)
10392 entry)
10393 (while (setq entry (pop all))
10394 (if (string-match (car entry) buffer-file-name)
10395 (throw 'exit (cdr entry))))
10396 nil)))))
10398 (defvar org-refile-target-table nil
10399 "The list of refile targets, created by `org-refile'.")
10401 (defvar org-agenda-new-buffers nil
10402 "Buffers created to visit agenda files.")
10404 (defvar org-refile-cache nil
10405 "Cache for refile targets.")
10407 (defvar org-refile-markers nil
10408 "All the markers used for caching refile locations.")
10410 (defun org-refile-marker (pos)
10411 "Get a new refile marker, but only if caching is in use."
10412 (if (not org-refile-use-cache)
10414 (let ((m (make-marker)))
10415 (move-marker m pos)
10416 (push m org-refile-markers)
10417 m)))
10419 (defun org-refile-cache-clear ()
10420 "Clear the refile cache and disable all the markers."
10421 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
10422 (setq org-refile-markers nil)
10423 (setq org-refile-cache nil)
10424 (message "Refile cache has been cleared"))
10426 (defun org-refile-cache-check-set (set)
10427 "Check if all the markers in the cache still have live buffers."
10428 (let (marker)
10429 (catch 'exit
10430 (while (and set (setq marker (nth 3 (pop set))))
10431 ;; if org-refile-use-outline-path is 'file, marker may be nil
10432 (when (and marker (null (marker-buffer marker)))
10433 (message "not found") (sit-for 3)
10434 (throw 'exit nil)))
10435 t)))
10437 (defun org-refile-cache-put (set &rest identifiers)
10438 "Push the refile targets SET into the cache, under IDENTIFIERS."
10439 (let* ((key (sha1 (prin1-to-string identifiers)))
10440 (entry (assoc key org-refile-cache)))
10441 (if entry
10442 (setcdr entry set)
10443 (push (cons key set) org-refile-cache))))
10445 (defun org-refile-cache-get (&rest identifiers)
10446 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10447 (cond
10448 ((not org-refile-cache) nil)
10449 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10451 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10452 org-refile-cache))))
10453 (and set (org-refile-cache-check-set set) set)))))
10455 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
10456 "Produce a table with refile targets."
10457 (let ((case-fold-search nil)
10458 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10459 (entries (or org-refile-targets '((nil . (:level . 1)))))
10460 targets tgs txt re files f desc descre fast-path-p level pos0)
10461 (message "Getting targets...")
10462 (with-current-buffer (or default-buffer (current-buffer))
10463 (while (setq entry (pop entries))
10464 (setq files (car entry) desc (cdr entry))
10465 (setq fast-path-p nil)
10466 (cond
10467 ((null files) (setq files (list (current-buffer))))
10468 ((eq files 'org-agenda-files)
10469 (setq files (org-agenda-files 'unrestricted)))
10470 ((and (symbolp files) (fboundp files))
10471 (setq files (funcall files)))
10472 ((and (symbolp files) (boundp files))
10473 (setq files (symbol-value files))))
10474 (if (stringp files) (setq files (list files)))
10475 (cond
10476 ((eq (car desc) :tag)
10477 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
10478 ((eq (car desc) :todo)
10479 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
10480 ((eq (car desc) :regexp)
10481 (setq descre (cdr desc)))
10482 ((eq (car desc) :level)
10483 (setq descre (concat "^\\*\\{" (number-to-string
10484 (if org-odd-levels-only
10485 (1- (* 2 (cdr desc)))
10486 (cdr desc)))
10487 "\\}[ \t]")))
10488 ((eq (car desc) :maxlevel)
10489 (setq fast-path-p t)
10490 (setq descre (concat "^\\*\\{1," (number-to-string
10491 (if org-odd-levels-only
10492 (1- (* 2 (cdr desc)))
10493 (cdr desc)))
10494 "\\}[ \t]")))
10495 (t (error "Bad refiling target description %s" desc)))
10496 (while (setq f (pop files))
10497 (with-current-buffer
10498 (if (bufferp f) f (org-get-agenda-file-buffer f))
10500 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
10501 (progn
10502 (if (bufferp f) (setq f (buffer-file-name
10503 (buffer-base-buffer f))))
10504 (setq f (and f (expand-file-name f)))
10505 (if (eq org-refile-use-outline-path 'file)
10506 (push (list (file-name-nondirectory f) f nil nil) tgs))
10507 (save-excursion
10508 (save-restriction
10509 (widen)
10510 (goto-char (point-min))
10511 (while (re-search-forward descre nil t)
10512 (goto-char (setq pos0 (point-at-bol)))
10513 (catch 'next
10514 (when org-refile-target-verify-function
10515 (save-match-data
10516 (or (funcall org-refile-target-verify-function)
10517 (throw 'next t))))
10518 (when (and (looking-at org-complex-heading-regexp)
10519 (not (member (match-string 4) excluded-entries))
10520 (match-string 4))
10521 (setq level (org-reduced-level
10522 (- (match-end 1) (match-beginning 1)))
10523 txt (org-link-display-format (match-string 4))
10524 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
10525 re (format org-complex-heading-regexp-format
10526 (regexp-quote (match-string 4))))
10527 (when org-refile-use-outline-path
10528 (setq txt (mapconcat
10529 'org-protect-slash
10530 (append
10531 (if (eq org-refile-use-outline-path
10532 'file)
10533 (list (file-name-nondirectory
10534 (buffer-file-name
10535 (buffer-base-buffer))))
10536 (if (eq org-refile-use-outline-path
10537 'full-file-path)
10538 (list (buffer-file-name
10539 (buffer-base-buffer)))))
10540 (org-get-outline-path fast-path-p
10541 level txt)
10542 (list txt))
10543 "/")))
10544 (push (list txt f re (org-refile-marker (point)))
10545 tgs)))
10546 (when (= (point) pos0)
10547 ;; verification function has not moved point
10548 (goto-char (point-at-eol))))))))
10549 (when org-refile-use-cache
10550 (org-refile-cache-put tgs (buffer-file-name) descre))
10551 (setq targets (append tgs targets))
10552 ))))
10553 (message "Getting targets...done")
10554 (nreverse targets)))
10556 (defun org-protect-slash (s)
10557 (while (string-match "/" s)
10558 (setq s (replace-match "\\" t t s)))
10561 (defvar org-olpa (make-vector 20 nil))
10563 (defun org-get-outline-path (&optional fastp level heading)
10564 "Return the outline path to the current entry, as a list.
10566 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
10567 routine which makes outline path derivations for an entire file,
10568 avoiding backtracing. Refile target collection makes use of that."
10569 (if fastp
10570 (progn
10571 (if (> level 19)
10572 (error "Outline path failure, more than 19 levels"))
10573 (loop for i from level upto 19 do
10574 (aset org-olpa i nil))
10575 (prog1
10576 (delq nil (append org-olpa nil))
10577 (aset org-olpa level heading)))
10578 (let (rtn case-fold-search)
10579 (save-excursion
10580 (save-restriction
10581 (widen)
10582 (while (org-up-heading-safe)
10583 (when (looking-at org-complex-heading-regexp)
10584 (push (org-match-string-no-properties 4) rtn)))
10585 rtn)))))
10587 (defun org-format-outline-path (path &optional width prefix)
10588 "Format the outline path PATH for display.
10589 Width is the maximum number of characters that is available.
10590 Prefix is a prefix to be included in the returned string,
10591 such as the file name."
10592 (setq width (or width 79))
10593 (if prefix (setq width (- width (length prefix))))
10594 (if (not path)
10595 (or prefix "")
10596 (let* ((nsteps (length path))
10597 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
10598 (maxwidth (if (<= total-width width)
10599 10000 ;; everything fits
10600 ;; we need to shorten the level headings
10601 (/ (- width nsteps) nsteps)))
10602 (org-odd-levels-only nil)
10603 (n 0)
10604 (total (1+ (length prefix))))
10605 (setq maxwidth (max maxwidth 10))
10606 (concat prefix
10607 (mapconcat
10608 (lambda (h)
10609 (setq n (1+ n))
10610 (if (and (= n nsteps) (< maxwidth 10000))
10611 (setq maxwidth (- total-width total)))
10612 (if (< (length h) maxwidth)
10613 (progn (setq total (+ total (length h) 1)) h)
10614 (setq h (substring h 0 (- maxwidth 2))
10615 total (+ total maxwidth 1))
10616 (if (string-match "[ \t]+\\'" h)
10617 (setq h (substring h 0 (match-beginning 0))))
10618 (setq h (concat h "..")))
10619 (org-add-props h nil 'face
10620 (nth (% (1- n) org-n-level-faces)
10621 org-level-faces))
10623 path "/")))))
10625 (defun org-display-outline-path (&optional file current)
10626 "Display the current outline path in the echo area."
10627 (interactive "P")
10628 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
10629 (case-fold-search nil)
10630 (path (and (derived-mode-p 'org-mode) (org-get-outline-path))))
10631 (if current (setq path (append path
10632 (save-excursion
10633 (org-back-to-heading t)
10634 (if (looking-at org-complex-heading-regexp)
10635 (list (match-string 4)))))))
10636 (message "%s"
10637 (org-format-outline-path
10638 path
10639 (1- (frame-width))
10640 (and file bfn (concat (file-name-nondirectory bfn) "/"))))))
10642 (defvar org-refile-history nil
10643 "History for refiling operations.")
10645 (defvar org-after-refile-insert-hook nil
10646 "Hook run after `org-refile' has inserted its stuff at the new location.
10647 Note that this is still *before* the stuff will be removed from
10648 the *old* location.")
10650 (defvar org-capture-last-stored-marker)
10651 (defun org-refile (&optional goto default-buffer rfloc)
10652 "Move the entry or entries at point to another heading.
10653 The list of target headings is compiled using the information in
10654 `org-refile-targets', which see.
10656 At the target location, the entry is filed as a subitem of the target
10657 heading. Depending on `org-reverse-note-order', the new subitem will
10658 either be the first or the last subitem.
10660 If there is an active region, all entries in that region will be moved.
10661 However, the region must fulfill the requirement that the first heading
10662 is the first one sets the top-level of the moved text - at most siblings
10663 below it are allowed.
10665 With prefix arg GOTO, the command will only visit the target location
10666 and not actually move anything.
10668 With a double prefix arg \\[universal-argument] \\[universal-argument], \
10669 go to the location where the last refiling operation has put the subtree.
10670 With a prefix argument of `2', refile to the running clock.
10672 RFLOC can be a refile location obtained in a different way.
10674 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
10676 If you are using target caching (see `org-refile-use-cache'),
10677 You have to clear the target cache in order to find new targets.
10678 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
10679 prefix argument (`C-u C-u C-u C-c C-w')."
10681 (interactive "P")
10682 (if (member goto '(0 (64)))
10683 (org-refile-cache-clear)
10684 (let* ((cbuf (current-buffer))
10685 (regionp (org-region-active-p))
10686 (region-start (and regionp (region-beginning)))
10687 (region-end (and regionp (region-end)))
10688 (region-length (and regionp (- region-end region-start)))
10689 (filename (buffer-file-name (buffer-base-buffer cbuf)))
10690 pos it nbuf file re level reversed)
10691 (setq last-command nil)
10692 (when regionp
10693 (goto-char region-start)
10694 (or (bolp) (goto-char (point-at-bol)))
10695 (setq region-start (point))
10696 (unless (or (org-kill-is-subtree-p
10697 (buffer-substring region-start region-end))
10698 (prog1 org-refile-active-region-within-subtree
10699 (org-toggle-heading)))
10700 (error "The region is not a (sequence of) subtree(s)")))
10701 (if (equal goto '(16))
10702 (org-refile-goto-last-stored)
10703 (when (or
10704 (and (equal goto 2)
10705 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
10706 (prog1
10707 (setq it (list (or org-clock-heading "running clock")
10708 (buffer-file-name
10709 (marker-buffer org-clock-hd-marker))
10711 (marker-position org-clock-hd-marker)))
10712 (setq goto nil)))
10713 (setq it (or rfloc
10714 (let (heading-text)
10715 (save-excursion
10716 (unless goto
10717 (org-back-to-heading t)
10718 (setq heading-text
10719 (nth 4 (org-heading-components))))
10720 (org-refile-get-location
10721 (cond (goto "Goto")
10722 (regionp "Refile region to")
10723 (t (concat "Refile subtree \""
10724 heading-text "\" to")))
10725 default-buffer
10726 (and (not (equal '(4) goto))
10727 org-refile-allow-creating-parent-nodes)
10728 goto))))))
10729 (setq file (nth 1 it)
10730 re (nth 2 it)
10731 pos (nth 3 it))
10732 (if (and (not goto)
10734 (equal (buffer-file-name) file)
10735 (if regionp
10736 (and (>= pos region-start)
10737 (<= pos region-end))
10738 (and (>= pos (point))
10739 (< pos (save-excursion
10740 (org-end-of-subtree t t))))))
10741 (error "Cannot refile to position inside the tree or region"))
10743 (setq nbuf (or (find-buffer-visiting file)
10744 (find-file-noselect file)))
10745 (if goto
10746 (progn
10747 (org-pop-to-buffer-same-window nbuf)
10748 (goto-char pos)
10749 (org-show-context 'org-goto))
10750 (if regionp
10751 (progn
10752 (org-kill-new (buffer-substring region-start region-end))
10753 (org-save-markers-in-region region-start region-end))
10754 (org-copy-subtree 1 nil t))
10755 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
10756 (find-file-noselect file)))
10757 (setq reversed (org-notes-order-reversed-p))
10758 (save-excursion
10759 (save-restriction
10760 (widen)
10761 (if pos
10762 (progn
10763 (goto-char pos)
10764 (looking-at org-outline-regexp)
10765 (setq level (org-get-valid-level (funcall outline-level) 1))
10766 (goto-char
10767 (if reversed
10768 (or (outline-next-heading) (point-max))
10769 (or (save-excursion (org-get-next-sibling))
10770 (org-end-of-subtree t t)
10771 (point-max)))))
10772 (setq level 1)
10773 (if (not reversed)
10774 (goto-char (point-max))
10775 (goto-char (point-min))
10776 (or (outline-next-heading) (goto-char (point-max)))))
10777 (if (not (bolp)) (newline))
10778 (org-paste-subtree level)
10779 (when org-log-refile
10780 (org-add-log-setup 'refile nil nil 'findpos
10781 org-log-refile)
10782 (unless (eq org-log-refile 'note)
10783 (save-excursion (org-add-log-note))))
10784 (and org-auto-align-tags (org-set-tags nil t))
10785 (bookmark-set "org-refile-last-stored")
10786 ;; If we are refiling for capture, make sure that the
10787 ;; last-capture pointers point here
10788 (when (org-bound-and-true-p org-refile-for-capture)
10789 (bookmark-set "org-capture-last-stored-marker")
10790 (move-marker org-capture-last-stored-marker (point)))
10791 (if (fboundp 'deactivate-mark) (deactivate-mark))
10792 (run-hooks 'org-after-refile-insert-hook))))
10793 (if regionp
10794 (delete-region (point) (+ (point) region-length))
10795 (org-cut-subtree))
10796 (when (featurep 'org-inlinetask)
10797 (org-inlinetask-remove-END-maybe))
10798 (setq org-markers-to-move nil)
10799 (message "Refiled to \"%s\" in file %s" (car it) file)))))))
10801 (defun org-refile-goto-last-stored ()
10802 "Go to the location where the last refile was stored."
10803 (interactive)
10804 (bookmark-jump "org-refile-last-stored")
10805 (message "This is the location of the last refile"))
10807 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
10808 no-exclude)
10809 "Prompt the user for a refile location, using PROMPT.
10810 PROMPT should not be suffixed with a colon and a space, because
10811 this function appends the default value from
10812 `org-refile-history' automatically, if that is not empty.
10813 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
10814 this is used for the GOTO interface."
10815 (let ((org-refile-targets org-refile-targets)
10816 (org-refile-use-outline-path org-refile-use-outline-path)
10817 excluded-entries)
10818 (when (and (derived-mode-p 'org-mode)
10819 (not org-refile-use-cache)
10820 (not no-exclude))
10821 (org-map-tree
10822 (lambda()
10823 (setq excluded-entries
10824 (append excluded-entries (list (org-get-heading t t)))))))
10825 (setq org-refile-target-table
10826 (org-refile-get-targets default-buffer excluded-entries)))
10827 (unless org-refile-target-table
10828 (error "No refile targets"))
10829 (let* ((prompt (concat prompt
10830 (and (car org-refile-history)
10831 (concat " (default " (car org-refile-history) ")"))
10832 ": "))
10833 (cbuf (current-buffer))
10834 (partial-completion-mode nil)
10835 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
10836 (cfunc (if (and org-refile-use-outline-path
10837 org-outline-path-complete-in-steps)
10838 'org-olpath-completing-read
10839 'org-icompleting-read))
10840 (extra (if org-refile-use-outline-path "/" ""))
10841 (filename (and cfn (expand-file-name cfn)))
10842 (tbl (mapcar
10843 (lambda (x)
10844 (if (and (not (member org-refile-use-outline-path
10845 '(file full-file-path)))
10846 (not (equal filename (nth 1 x))))
10847 (cons (concat (car x) extra " ("
10848 (file-name-nondirectory (nth 1 x)) ")")
10849 (cdr x))
10850 (cons (concat (car x) extra) (cdr x))))
10851 org-refile-target-table))
10852 (completion-ignore-case t)
10853 pa answ parent-target child parent old-hist)
10854 (setq old-hist org-refile-history)
10855 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
10856 nil 'org-refile-history (car org-refile-history)))
10857 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
10858 (org-refile-check-position pa)
10859 (if pa
10860 (progn
10861 (when (or (not org-refile-history)
10862 (not (eq old-hist org-refile-history))
10863 (not (equal (car pa) (car org-refile-history))))
10864 (setq org-refile-history
10865 (cons (car pa) (if (assoc (car org-refile-history) tbl)
10866 org-refile-history
10867 (cdr org-refile-history))))
10868 (if (equal (car org-refile-history) (nth 1 org-refile-history))
10869 (pop org-refile-history)))
10871 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
10872 (progn
10873 (setq parent (match-string 1 answ)
10874 child (match-string 2 answ))
10875 (setq parent-target (or (assoc parent tbl)
10876 (assoc (concat parent "/") tbl)))
10877 (when (and parent-target
10878 (or (eq new-nodes t)
10879 (and (eq new-nodes 'confirm)
10880 (y-or-n-p (format "Create new node \"%s\"? "
10881 child)))))
10882 (org-refile-new-child parent-target child)))
10883 (error "Invalid target location")))))
10885 (declare-function org-string-nw-p "org-macs.el" (s))
10886 (defun org-refile-check-position (refile-pointer)
10887 "Check if the refile pointer matches the readline to which it points."
10888 (let* ((file (nth 1 refile-pointer))
10889 (re (nth 2 refile-pointer))
10890 (pos (nth 3 refile-pointer))
10891 buffer)
10892 (when (org-string-nw-p re)
10893 (setq buffer (if (markerp pos)
10894 (marker-buffer pos)
10895 (or (find-buffer-visiting file)
10896 (find-file-noselect file))))
10897 (with-current-buffer buffer
10898 (save-excursion
10899 (save-restriction
10900 (widen)
10901 (goto-char pos)
10902 (beginning-of-line 1)
10903 (unless (org-looking-at-p re)
10904 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
10906 (defun org-refile-new-child (parent-target child)
10907 "Use refile target PARENT-TARGET to add new CHILD below it."
10908 (unless parent-target
10909 (error "Cannot find parent for new node"))
10910 (let ((file (nth 1 parent-target))
10911 (pos (nth 3 parent-target))
10912 level)
10913 (with-current-buffer (or (find-buffer-visiting file)
10914 (find-file-noselect file))
10915 (save-excursion
10916 (save-restriction
10917 (widen)
10918 (if pos
10919 (goto-char pos)
10920 (goto-char (point-max))
10921 (if (not (bolp)) (newline)))
10922 (when (looking-at org-outline-regexp)
10923 (setq level (funcall outline-level))
10924 (org-end-of-subtree t t))
10925 (org-back-over-empty-lines)
10926 (insert "\n" (make-string
10927 (if pos (org-get-valid-level level 1) 1) ?*)
10928 " " child "\n")
10929 (beginning-of-line 0)
10930 (list (concat (car parent-target) "/" child) file "" (point)))))))
10932 (defun org-olpath-completing-read (prompt collection &rest args)
10933 "Read an outline path like a file name."
10934 (let ((thetable collection)
10935 (org-completion-use-ido nil) ; does not work with ido.
10936 (org-completion-use-iswitchb nil)) ; or iswitchb
10937 (apply
10938 'org-icompleting-read prompt
10939 (lambda (string predicate &optional flag)
10940 (let (rtn r f (l (length string)))
10941 (cond
10942 ((eq flag nil)
10943 ;; try completion
10944 (try-completion string thetable))
10945 ((eq flag t)
10946 ;; all-completions
10947 (setq rtn (all-completions string thetable predicate))
10948 (mapcar
10949 (lambda (x)
10950 (setq r (substring x l))
10951 (if (string-match " ([^)]*)$" x)
10952 (setq f (match-string 0 x))
10953 (setq f ""))
10954 (if (string-match "/" r)
10955 (concat string (substring r 0 (match-end 0)) f)
10957 rtn))
10958 ((eq flag 'lambda)
10959 ;; exact match?
10960 (assoc string thetable)))
10962 args)))
10964 ;;;; Dynamic blocks
10966 (defun org-find-dblock (name)
10967 "Find the first dynamic block with name NAME in the buffer.
10968 If not found, stay at current position and return nil."
10969 (let (pos)
10970 (save-excursion
10971 (goto-char (point-min))
10972 (setq pos (and (re-search-forward (concat "^[ \t]*#\\+BEGIN:[ \t]+" name "\\>")
10973 nil t)
10974 (match-beginning 0))))
10975 (if pos (goto-char pos))
10976 pos))
10978 (defconst org-dblock-start-re
10979 "^[ \t]*#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
10980 "Matches the start line of a dynamic block, with parameters.")
10982 (defconst org-dblock-end-re "^[ \t]*#\\+END\\([: \t\r\n]\\|$\\)"
10983 "Matches the end of a dynamic block.")
10985 (defun org-create-dblock (plist)
10986 "Create a dynamic block section, with parameters taken from PLIST.
10987 PLIST must contain a :name entry which is used as name of the block."
10988 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
10989 (end-of-line 1)
10990 (newline))
10991 (let ((col (current-column))
10992 (name (plist-get plist :name)))
10993 (insert "#+BEGIN: " name)
10994 (while plist
10995 (if (eq (car plist) :name)
10996 (setq plist (cddr plist))
10997 (insert " " (prin1-to-string (pop plist)))))
10998 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
10999 (beginning-of-line -2)))
11001 (defun org-prepare-dblock ()
11002 "Prepare dynamic block for refresh.
11003 This empties the block, puts the cursor at the insert position and returns
11004 the property list including an extra property :name with the block name."
11005 (unless (looking-at org-dblock-start-re)
11006 (error "Not at a dynamic block"))
11007 (let* ((begdel (1+ (match-end 0)))
11008 (name (org-no-properties (match-string 1)))
11009 (params (append (list :name name)
11010 (read (concat "(" (match-string 3) ")")))))
11011 (save-excursion
11012 (beginning-of-line 1)
11013 (skip-chars-forward " \t")
11014 (setq params (plist-put params :indentation-column (current-column))))
11015 (unless (re-search-forward org-dblock-end-re nil t)
11016 (error "Dynamic block not terminated"))
11017 (setq params
11018 (append params
11019 (list :content (buffer-substring
11020 begdel (match-beginning 0)))))
11021 (delete-region begdel (match-beginning 0))
11022 (goto-char begdel)
11023 (open-line 1)
11024 params))
11026 (defun org-map-dblocks (&optional command)
11027 "Apply COMMAND to all dynamic blocks in the current buffer.
11028 If COMMAND is not given, use `org-update-dblock'."
11029 (let ((cmd (or command 'org-update-dblock)))
11030 (save-excursion
11031 (goto-char (point-min))
11032 (while (re-search-forward org-dblock-start-re nil t)
11033 (goto-char (match-beginning 0))
11034 (save-excursion
11035 (condition-case nil
11036 (funcall cmd)
11037 (error (message "Error during update of dynamic block"))))
11038 (unless (re-search-forward org-dblock-end-re nil t)
11039 (error "Dynamic block not terminated"))))))
11041 (defun org-dblock-update (&optional arg)
11042 "User command for updating dynamic blocks.
11043 Update the dynamic block at point. With prefix ARG, update all dynamic
11044 blocks in the buffer."
11045 (interactive "P")
11046 (if arg
11047 (org-update-all-dblocks)
11048 (or (looking-at org-dblock-start-re)
11049 (org-beginning-of-dblock))
11050 (org-update-dblock)))
11052 (defun org-update-dblock ()
11053 "Update the dynamic block at point.
11054 This means to empty the block, parse for parameters and then call
11055 the correct writing function."
11056 (interactive)
11057 (save-window-excursion
11058 (let* ((pos (point))
11059 (line (org-current-line))
11060 (params (org-prepare-dblock))
11061 (name (plist-get params :name))
11062 (indent (plist-get params :indentation-column))
11063 (cmd (intern (concat "org-dblock-write:" name))))
11064 (message "Updating dynamic block `%s' at line %d..." name line)
11065 (funcall cmd params)
11066 (message "Updating dynamic block `%s' at line %d...done" name line)
11067 (goto-char pos)
11068 (when (and indent (> indent 0))
11069 (setq indent (make-string indent ?\ ))
11070 (save-excursion
11071 (org-beginning-of-dblock)
11072 (forward-line 1)
11073 (while (not (looking-at org-dblock-end-re))
11074 (insert indent)
11075 (beginning-of-line 2))
11076 (when (looking-at org-dblock-end-re)
11077 (and (looking-at "[ \t]+")
11078 (replace-match ""))
11079 (insert indent)))))))
11081 (defun org-beginning-of-dblock ()
11082 "Find the beginning of the dynamic block at point.
11083 Error if there is no such block at point."
11084 (let ((pos (point))
11085 beg)
11086 (end-of-line 1)
11087 (if (and (re-search-backward org-dblock-start-re nil t)
11088 (setq beg (match-beginning 0))
11089 (re-search-forward org-dblock-end-re nil t)
11090 (> (match-end 0) pos))
11091 (goto-char beg)
11092 (goto-char pos)
11093 (error "Not in a dynamic block"))))
11095 ;;;###autoload
11096 (defun org-update-all-dblocks ()
11097 "Update all dynamic blocks in the buffer.
11098 This function can be used in a hook."
11099 (interactive)
11100 (when (derived-mode-p 'org-mode)
11101 (org-map-dblocks 'org-update-dblock)))
11104 ;;;; Completion
11106 (defconst org-additional-option-like-keywords
11107 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML:"
11108 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook:"
11109 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"
11110 "LATEX_CLASS:" "LATEX_CLASS_OPTIONS:" "ATTR_LaTeX:"
11111 "BEGIN:" "END:"
11112 "ORGTBL" "TBLFM:" "TBLNAME:"
11113 "BEGIN_EXAMPLE" "END_EXAMPLE"
11114 "BEGIN_QUOTE" "END_QUOTE"
11115 "BEGIN_VERSE" "END_VERSE"
11116 "BEGIN_CENTER" "END_CENTER"
11117 "BEGIN_SRC" "END_SRC"
11118 "BEGIN_RESULT" "END_RESULT"
11119 "NAME:" "RESULTS:"
11120 "HEADER:" "HEADERS:"
11121 "CATEGORY:" "COLUMNS:" "PROPERTY:"
11122 "CAPTION:" "LABEL:"
11123 "SETUPFILE:"
11124 "INCLUDE:"
11125 "BIND:"
11126 "MACRO:"))
11128 (defcustom org-structure-template-alist
11130 ("s" "#+BEGIN_SRC ?\n\n#+END_SRC"
11131 "<src lang=\"?\">\n\n</src>")
11132 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE"
11133 "<example>\n?\n</example>")
11134 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE"
11135 "<quote>\n?\n</quote>")
11136 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE"
11137 "<verse>\n?\n</verse>")
11138 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER"
11139 "<center>\n?\n</center>")
11140 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11141 "<literal style=\"latex\">\n?\n</literal>")
11142 ("L" "#+LaTeX: "
11143 "<literal style=\"latex\">?</literal>")
11144 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
11145 "<literal style=\"html\">\n?\n</literal>")
11146 ("H" "#+HTML: "
11147 "<literal style=\"html\">?</literal>")
11148 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
11149 ("A" "#+ASCII: ")
11150 ("i" "#+INDEX: ?"
11151 "#+INDEX: ?")
11152 ("I" "#+INCLUDE %file ?"
11153 "<include file=%file markup=\"?\">")
11155 "Structure completion elements.
11156 This is a list of abbreviation keys and values. The value gets inserted
11157 if you type `<' followed by the key and then press the completion key,
11158 usually `M-TAB'. %file will be replaced by a file name after prompting
11159 for the file using completion. The cursor will be placed at the position
11160 of the `?` in the template.
11161 There are two templates for each key, the first uses the original Org syntax,
11162 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11163 the default when the /org-mtags.el/ module has been loaded. See also the
11164 variable `org-mtags-prefer-muse-templates'."
11165 :group 'org-completion
11166 :type '(repeat
11167 (string :tag "Key")
11168 (string :tag "Template")
11169 (string :tag "Muse Template")))
11171 (defun org-try-structure-completion ()
11172 "Try to complete a structure template before point.
11173 This looks for strings like \"<e\" on an otherwise empty line and
11174 expands them."
11175 (let ((l (buffer-substring (point-at-bol) (point)))
11177 (when (and (looking-at "[ \t]*$")
11178 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
11179 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
11180 (org-complete-expand-structure-template (+ -1 (point-at-bol)
11181 (match-beginning 1)) a)
11182 t)))
11184 (defun org-complete-expand-structure-template (start cell)
11185 "Expand a structure template."
11186 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
11187 (rpl (nth (if musep 2 1) cell))
11188 (ind ""))
11189 (delete-region start (point))
11190 (when (string-match "\\`#\\+" rpl)
11191 (cond
11192 ((bolp))
11193 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
11194 (setq ind (buffer-substring (point-at-bol) (point))))
11195 (t (newline))))
11196 (setq start (point))
11197 (if (string-match "%file" rpl)
11198 (setq rpl (replace-match
11199 (concat
11200 "\""
11201 (save-match-data
11202 (abbreviate-file-name (read-file-name "Include file: ")))
11203 "\"")
11204 t t rpl)))
11205 (setq rpl (mapconcat 'identity (split-string rpl "\n")
11206 (concat "\n" ind)))
11207 (insert rpl)
11208 (if (re-search-backward "\\?" start t) (delete-char 1))))
11210 ;;;; TODO, DEADLINE, Comments
11212 (defun org-toggle-comment ()
11213 "Change the COMMENT state of an entry."
11214 (interactive)
11215 (save-excursion
11216 (org-back-to-heading)
11217 (let (case-fold-search)
11218 (cond
11219 ((looking-at (format org-heading-keyword-regexp-format
11220 org-comment-string))
11221 (goto-char (match-end 1))
11222 (looking-at (concat " +" org-comment-string))
11223 (replace-match "" t t)
11224 (when (eolp) (insert " ")))
11225 ((looking-at org-outline-regexp)
11226 (goto-char (match-end 0))
11227 (insert org-comment-string " "))))))
11229 (defvar org-last-todo-state-is-todo nil
11230 "This is non-nil when the last TODO state change led to a TODO state.
11231 If the last change removed the TODO tag or switched to DONE, then
11232 this is nil.")
11234 (defvar org-setting-tags nil) ; dynamically skipped
11236 (defvar org-todo-setup-filter-hook nil
11237 "Hook for functions that pre-filter todo specs.
11238 Each function takes a todo spec and returns either nil or the spec
11239 transformed into canonical form." )
11241 (defvar org-todo-get-default-hook nil
11242 "Hook for functions that get a default item for todo.
11243 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11244 nil or a string to be used for the todo mark." )
11246 (defvar org-agenda-headline-snapshot-before-repeat)
11248 (defun org-current-effective-time ()
11249 "Return current time adjusted for `org-extend-today-until' variable"
11250 (let* ((ct (org-current-time))
11251 (dct (decode-time ct))
11252 (ct1
11253 (if (and org-use-effective-time
11254 (< (nth 2 dct) org-extend-today-until))
11255 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct))
11256 ct)))
11257 ct1))
11259 (defun org-todo-yesterday (&optional arg)
11260 "Like `org-todo' but the time of change will be 23:59 of yesterday."
11261 (interactive "P")
11262 (if (eq major-mode 'org-agenda-mode)
11263 (apply 'org-agenda-todo-yesterday arg)
11264 (let* ((hour (third (decode-time
11265 (org-current-time))))
11266 (org-extend-today-until (1+ hour)))
11267 (org-todo arg))))
11269 (defun org-todo (&optional arg)
11270 "Change the TODO state of an item.
11271 The state of an item is given by a keyword at the start of the heading,
11272 like
11273 *** TODO Write paper
11274 *** DONE Call mom
11276 The different keywords are specified in the variable `org-todo-keywords'.
11277 By default the available states are \"TODO\" and \"DONE\".
11278 So for this example: when the item starts with TODO, it is changed to DONE.
11279 When it starts with DONE, the DONE is removed. And when neither TODO nor
11280 DONE are present, add TODO at the beginning of the heading.
11282 With \\[universal-argument] prefix arg, use completion to determine the new \
11283 state.
11284 With numeric prefix arg, switch to that state.
11285 With a double \\[universal-argument] prefix, switch to the next set of TODO \
11286 keywords (nextset).
11287 With a triple \\[universal-argument] prefix, circumvent any state blocking.
11288 With a numeric prefix arg of 0, inhibit note taking for the change.
11290 For calling through lisp, arg is also interpreted in the following way:
11291 'none -> empty state
11292 \"\"(empty string) -> switch to empty state
11293 'done -> switch to DONE
11294 'nextset -> switch to the next set of keywords
11295 'previousset -> switch to the previous set of keywords
11296 \"WAITING\" -> switch to the specified keyword, but only if it
11297 really is a member of `org-todo-keywords'."
11298 (interactive "P")
11299 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11300 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
11301 'region-start-level 'region))
11302 org-loop-over-headlines-in-active-region)
11303 (org-map-entries
11304 `(org-todo ,arg)
11305 org-loop-over-headlines-in-active-region
11306 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
11307 (if (equal arg '(16)) (setq arg 'nextset))
11308 (let ((org-blocker-hook org-blocker-hook)
11309 (case-fold-search nil))
11310 (when (equal arg '(64))
11311 (setq arg nil org-blocker-hook nil))
11312 (when (and org-blocker-hook
11313 (or org-inhibit-blocking
11314 (org-entry-get nil "NOBLOCKING")))
11315 (setq org-blocker-hook nil))
11316 (save-excursion
11317 (catch 'exit
11318 (org-back-to-heading t)
11319 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
11320 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
11321 (looking-at "\\(?: *\\|[ \t]*$\\)"))
11322 (let* ((match-data (match-data))
11323 (startpos (point-at-bol))
11324 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
11325 (org-log-done org-log-done)
11326 (org-log-repeat org-log-repeat)
11327 (org-todo-log-states org-todo-log-states)
11328 (org-inhibit-logging
11329 (if (equal arg 0)
11330 (progn (setq arg nil) 'note) org-inhibit-logging))
11331 (this (match-string 1))
11332 (hl-pos (match-beginning 0))
11333 (head (org-get-todo-sequence-head this))
11334 (ass (assoc head org-todo-kwd-alist))
11335 (interpret (nth 1 ass))
11336 (done-word (nth 3 ass))
11337 (final-done-word (nth 4 ass))
11338 (org-last-state (or this ""))
11339 (completion-ignore-case t)
11340 (member (member this org-todo-keywords-1))
11341 (tail (cdr member))
11342 (org-state (cond
11343 ((and org-todo-key-trigger
11344 (or (and (equal arg '(4))
11345 (eq org-use-fast-todo-selection 'prefix))
11346 (and (not arg) org-use-fast-todo-selection
11347 (not (eq org-use-fast-todo-selection
11348 'prefix)))))
11349 ;; Use fast selection
11350 (org-fast-todo-selection))
11351 ((and (equal arg '(4))
11352 (or (not org-use-fast-todo-selection)
11353 (not org-todo-key-trigger)))
11354 ;; Read a state with completion
11355 (org-icompleting-read
11356 "State: " (mapcar (lambda(x) (list x))
11357 org-todo-keywords-1)
11358 nil t))
11359 ((eq arg 'right)
11360 (if this
11361 (if tail (car tail) nil)
11362 (car org-todo-keywords-1)))
11363 ((eq arg 'left)
11364 (if (equal member org-todo-keywords-1)
11366 (if this
11367 (nth (- (length org-todo-keywords-1)
11368 (length tail) 2)
11369 org-todo-keywords-1)
11370 (org-last org-todo-keywords-1))))
11371 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
11372 (setq arg nil))) ; hack to fall back to cycling
11373 (arg
11374 ;; user or caller requests a specific state
11375 (cond
11376 ((equal arg "") nil)
11377 ((eq arg 'none) nil)
11378 ((eq arg 'done) (or done-word (car org-done-keywords)))
11379 ((eq arg 'nextset)
11380 (or (car (cdr (member head org-todo-heads)))
11381 (car org-todo-heads)))
11382 ((eq arg 'previousset)
11383 (let ((org-todo-heads (reverse org-todo-heads)))
11384 (or (car (cdr (member head org-todo-heads)))
11385 (car org-todo-heads))))
11386 ((car (member arg org-todo-keywords-1)))
11387 ((stringp arg)
11388 (error "State `%s' not valid in this file" arg))
11389 ((nth (1- (prefix-numeric-value arg))
11390 org-todo-keywords-1))))
11391 ((null member) (or head (car org-todo-keywords-1)))
11392 ((equal this final-done-word) nil) ;; -> make empty
11393 ((null tail) nil) ;; -> first entry
11394 ((memq interpret '(type priority))
11395 (if (eq this-command last-command)
11396 (car tail)
11397 (if (> (length tail) 0)
11398 (or done-word (car org-done-keywords))
11399 nil)))
11401 (car tail))))
11402 (org-state (or
11403 (run-hook-with-args-until-success
11404 'org-todo-get-default-hook org-state org-last-state)
11405 org-state))
11406 (next (if org-state (concat " " org-state " ") " "))
11407 (change-plist (list :type 'todo-state-change :from this :to org-state
11408 :position startpos))
11409 dolog now-done-p)
11410 (when org-blocker-hook
11411 (setq org-last-todo-state-is-todo
11412 (not (member this org-done-keywords)))
11413 (unless (save-excursion
11414 (save-match-data
11415 (org-with-wide-buffer
11416 (run-hook-with-args-until-failure
11417 'org-blocker-hook change-plist))))
11418 (if (org-called-interactively-p 'interactive)
11419 (error "TODO state change from %s to %s blocked" this org-state)
11420 ;; fail silently
11421 (message "TODO state change from %s to %s blocked" this org-state)
11422 (throw 'exit nil))))
11423 (store-match-data match-data)
11424 (replace-match next t t)
11425 (unless (pos-visible-in-window-p hl-pos)
11426 (message "TODO state changed to %s" (org-trim next)))
11427 (unless head
11428 (setq head (org-get-todo-sequence-head org-state)
11429 ass (assoc head org-todo-kwd-alist)
11430 interpret (nth 1 ass)
11431 done-word (nth 3 ass)
11432 final-done-word (nth 4 ass)))
11433 (when (memq arg '(nextset previousset))
11434 (message "Keyword-Set %d/%d: %s"
11435 (- (length org-todo-sets) -1
11436 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
11437 (length org-todo-sets)
11438 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
11439 (setq org-last-todo-state-is-todo
11440 (not (member org-state org-done-keywords)))
11441 (setq now-done-p (and (member org-state org-done-keywords)
11442 (not (member this org-done-keywords))))
11443 (and logging (org-local-logging logging))
11444 (when (and (or org-todo-log-states org-log-done)
11445 (not (eq org-inhibit-logging t))
11446 (not (memq arg '(nextset previousset))))
11447 ;; we need to look at recording a time and note
11448 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
11449 (nth 2 (assoc this org-todo-log-states))))
11450 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
11451 (setq dolog 'time))
11452 (when (and org-state
11453 (member org-state org-not-done-keywords)
11454 (not (member this org-not-done-keywords)))
11455 ;; This is now a todo state and was not one before
11456 ;; If there was a CLOSED time stamp, get rid of it.
11457 (org-add-planning-info nil nil 'closed))
11458 (when (and now-done-p org-log-done)
11459 ;; It is now done, and it was not done before
11460 (org-add-planning-info 'closed (org-current-effective-time))
11461 (if (and (not dolog) (eq 'note org-log-done))
11462 (org-add-log-setup 'done org-state this 'findpos 'note)))
11463 (when (and org-state dolog)
11464 ;; This is a non-nil state, and we need to log it
11465 (org-add-log-setup 'state org-state this 'findpos dolog)))
11466 ;; Fixup tag positioning
11467 (org-todo-trigger-tag-changes org-state)
11468 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
11469 (when org-provide-todo-statistics
11470 (org-update-parent-todo-statistics))
11471 (run-hooks 'org-after-todo-state-change-hook)
11472 (if (and arg (not (member org-state org-done-keywords)))
11473 (setq head (org-get-todo-sequence-head org-state)))
11474 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
11475 ;; Do we need to trigger a repeat?
11476 (when now-done-p
11477 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
11478 ;; This is for the agenda, take a snapshot of the headline.
11479 (save-match-data
11480 (setq org-agenda-headline-snapshot-before-repeat
11481 (org-get-heading))))
11482 (org-auto-repeat-maybe org-state))
11483 ;; Fixup cursor location if close to the keyword
11484 (if (and (outline-on-heading-p)
11485 (not (bolp))
11486 (save-excursion (beginning-of-line 1)
11487 (looking-at org-todo-line-regexp))
11488 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
11489 (progn
11490 (goto-char (or (match-end 2) (match-end 1)))
11491 (and (looking-at " ") (just-one-space))))
11492 (when org-trigger-hook
11493 (save-excursion
11494 (run-hook-with-args 'org-trigger-hook change-plist)))))))))
11496 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
11497 "Block turning an entry into a TODO, using the hierarchy.
11498 This checks whether the current task should be blocked from state
11499 changes. Such blocking occurs when:
11501 1. The task has children which are not all in a completed state.
11503 2. A task has a parent with the property :ORDERED:, and there
11504 are siblings prior to the current task with incomplete
11505 status.
11507 3. The parent of the task is blocked because it has siblings that should
11508 be done first, or is child of a block grandparent TODO entry."
11510 (if (not org-enforce-todo-dependencies)
11511 t ; if locally turned off don't block
11512 (catch 'dont-block
11513 ;; If this is not a todo state change, or if this entry is already DONE,
11514 ;; do not block
11515 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11516 (member (plist-get change-plist :from)
11517 (cons 'done org-done-keywords))
11518 (member (plist-get change-plist :to)
11519 (cons 'todo org-not-done-keywords))
11520 (not (plist-get change-plist :to)))
11521 (throw 'dont-block t))
11522 ;; If this task has children, and any are undone, it's blocked
11523 (save-excursion
11524 (org-back-to-heading t)
11525 (let ((this-level (funcall outline-level)))
11526 (outline-next-heading)
11527 (let ((child-level (funcall outline-level)))
11528 (while (and (not (eobp))
11529 (> child-level this-level))
11530 ;; this todo has children, check whether they are all
11531 ;; completed
11532 (if (and (not (org-entry-is-done-p))
11533 (org-entry-is-todo-p))
11534 (throw 'dont-block nil))
11535 (outline-next-heading)
11536 (setq child-level (funcall outline-level))))))
11537 ;; Otherwise, if the task's parent has the :ORDERED: property, and
11538 ;; any previous siblings are undone, it's blocked
11539 (save-excursion
11540 (org-back-to-heading t)
11541 (let* ((pos (point))
11542 (parent-pos (and (org-up-heading-safe) (point))))
11543 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11544 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11545 (forward-line 1)
11546 (re-search-forward org-not-done-heading-regexp pos t))
11547 (throw 'dont-block nil)) ; block, there is an older sibling not done.
11548 ;; Search further up the hierarchy, to see if an ancestor is blocked
11549 (while t
11550 (goto-char parent-pos)
11551 (if (not (looking-at org-not-done-heading-regexp))
11552 (throw 'dont-block t)) ; do not block, parent is not a TODO
11553 (setq pos (point))
11554 (setq parent-pos (and (org-up-heading-safe) (point)))
11555 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11556 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11557 (forward-line 1)
11558 (re-search-forward org-not-done-heading-regexp pos t))
11559 (throw 'dont-block nil)))))))) ; block, older sibling not done.
11561 (defcustom org-track-ordered-property-with-tag nil
11562 "Should the ORDERED property also be shown as a tag?
11563 The ORDERED property decides if an entry should require subtasks to be
11564 completed in sequence. Since a property is not very visible, setting
11565 this option means that toggling the ORDERED property with the command
11566 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
11567 not relevant for the behavior, but it makes things more visible.
11569 Note that toggling the tag with tags commands will not change the property
11570 and therefore not influence behavior!
11572 This can be t, meaning the tag ORDERED should be used, It can also be a
11573 string to select a different tag for this task."
11574 :group 'org-todo
11575 :type '(choice
11576 (const :tag "No tracking" nil)
11577 (const :tag "Track with ORDERED tag" t)
11578 (string :tag "Use other tag")))
11580 (defun org-toggle-ordered-property ()
11581 "Toggle the ORDERED property of the current entry.
11582 For better visibility, you can track the value of this property with a tag.
11583 See variable `org-track-ordered-property-with-tag'."
11584 (interactive)
11585 (let* ((t1 org-track-ordered-property-with-tag)
11586 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
11587 (save-excursion
11588 (org-back-to-heading)
11589 (if (org-entry-get nil "ORDERED")
11590 (progn
11591 (org-delete-property "ORDERED")
11592 (and tag (org-toggle-tag tag 'off))
11593 (message "Subtasks can be completed in arbitrary order"))
11594 (org-entry-put nil "ORDERED" "t")
11595 (and tag (org-toggle-tag tag 'on))
11596 (message "Subtasks must be completed in sequence")))))
11598 (defvar org-blocked-by-checkboxes) ; dynamically scoped
11599 (defun org-block-todo-from-checkboxes (change-plist)
11600 "Block turning an entry into a TODO, using checkboxes.
11601 This checks whether the current task should be blocked from state
11602 changes because there are unchecked boxes in this entry."
11603 (if (not org-enforce-todo-checkbox-dependencies)
11604 t ; if locally turned off don't block
11605 (catch 'dont-block
11606 ;; If this is not a todo state change, or if this entry is already DONE,
11607 ;; do not block
11608 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11609 (member (plist-get change-plist :from)
11610 (cons 'done org-done-keywords))
11611 (member (plist-get change-plist :to)
11612 (cons 'todo org-not-done-keywords))
11613 (not (plist-get change-plist :to)))
11614 (throw 'dont-block t))
11615 ;; If this task has checkboxes that are not checked, it's blocked
11616 (save-excursion
11617 (org-back-to-heading t)
11618 (let ((beg (point)) end)
11619 (outline-next-heading)
11620 (setq end (point))
11621 (goto-char beg)
11622 (if (org-list-search-forward
11623 (concat (org-item-beginning-re)
11624 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
11625 "\\[[- ]\\]")
11626 end t)
11627 (progn
11628 (if (boundp 'org-blocked-by-checkboxes)
11629 (setq org-blocked-by-checkboxes t))
11630 (throw 'dont-block nil)))))
11631 t))) ; do not block
11633 (defun org-entry-blocked-p ()
11634 "Is the current entry blocked?"
11635 (if (org-entry-get nil "NOBLOCKING")
11636 nil ;; Never block this entry
11637 (not
11638 (run-hook-with-args-until-failure
11639 'org-blocker-hook
11640 (list :type 'todo-state-change
11641 :position (point)
11642 :from 'todo
11643 :to 'done)))))
11645 (defun org-update-statistics-cookies (all)
11646 "Update the statistics cookie, either from TODO or from checkboxes.
11647 This should be called with the cursor in a line with a statistics cookie."
11648 (interactive "P")
11649 (if all
11650 (progn
11651 (org-update-checkbox-count 'all)
11652 (org-map-entries 'org-update-parent-todo-statistics))
11653 (if (not (org-at-heading-p))
11654 (org-update-checkbox-count)
11655 (let ((pos (move-marker (make-marker) (point)))
11656 end l1 l2)
11657 (ignore-errors (org-back-to-heading t))
11658 (if (not (org-at-heading-p))
11659 (org-update-checkbox-count)
11660 (setq l1 (org-outline-level))
11661 (setq end (save-excursion
11662 (outline-next-heading)
11663 (if (org-at-heading-p) (setq l2 (org-outline-level)))
11664 (point)))
11665 (if (and (save-excursion
11666 (re-search-forward
11667 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
11668 (not (save-excursion (re-search-forward
11669 ":COOKIE_DATA:.*\\<todo\\>" end t))))
11670 (org-update-checkbox-count)
11671 (if (and l2 (> l2 l1))
11672 (progn
11673 (goto-char end)
11674 (org-update-parent-todo-statistics))
11675 (goto-char pos)
11676 (beginning-of-line 1)
11677 (while (re-search-forward
11678 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
11679 (point-at-eol) t)
11680 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
11681 (goto-char pos)
11682 (move-marker pos nil)))))
11684 (defvar org-entry-property-inherited-from) ;; defined below
11685 (defun org-update-parent-todo-statistics ()
11686 "Update any statistics cookie in the parent of the current headline.
11687 When `org-hierarchical-todo-statistics' is nil, statistics will cover
11688 the entire subtree and this will travel up the hierarchy and update
11689 statistics everywhere."
11690 (let* ((prop (save-excursion (org-up-heading-safe)
11691 (org-entry-get nil "COOKIE_DATA" 'inherit)))
11692 (recursive (or (not org-hierarchical-todo-statistics)
11693 (and prop (string-match "\\<recursive\\>" prop))))
11694 (lim (or (and prop (marker-position org-entry-property-inherited-from))
11696 (first t)
11697 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
11698 level ltoggle l1 new ndel
11699 (cnt-all 0) (cnt-done 0) is-percent kwd
11700 checkbox-beg ov ovs ove cookie-present)
11701 (catch 'exit
11702 (save-excursion
11703 (beginning-of-line 1)
11704 (setq ltoggle (funcall outline-level))
11705 ;; Three situations are to consider:
11707 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
11708 ;; to the top-level ancestor on the headline;
11710 ;; 2. If parent has "recursive" property, repeat up to the
11711 ;; headline setting that property, taking inheritance into
11712 ;; account;
11714 ;; 3. Else, move up to direct parent and proceed only once.
11715 (while (and (setq level (org-up-heading-safe))
11716 (or recursive first)
11717 (>= (point) lim))
11718 (setq first nil cookie-present nil)
11719 (unless (and level
11720 (not (string-match
11721 "\\<checkbox\\>"
11722 (downcase (or (org-entry-get nil "COOKIE_DATA")
11723 "")))))
11724 (throw 'exit nil))
11725 (while (re-search-forward box-re (point-at-eol) t)
11726 (setq cnt-all 0 cnt-done 0 cookie-present t)
11727 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
11728 (save-match-data
11729 (unless (outline-next-heading) (throw 'exit nil))
11730 (while (and (looking-at org-complex-heading-regexp)
11731 (> (setq l1 (length (match-string 1))) level))
11732 (setq kwd (and (or recursive (= l1 ltoggle))
11733 (match-string 2)))
11734 (if (or (eq org-provide-todo-statistics 'all-headlines)
11735 (and (listp org-provide-todo-statistics)
11736 (or (member kwd org-provide-todo-statistics)
11737 (member kwd org-done-keywords))))
11738 (setq cnt-all (1+ cnt-all))
11739 (if (eq org-provide-todo-statistics t)
11740 (and kwd (setq cnt-all (1+ cnt-all)))))
11741 (and (member kwd org-done-keywords)
11742 (setq cnt-done (1+ cnt-done)))
11743 (outline-next-heading)))
11744 (setq new
11745 (if is-percent
11746 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
11747 (format "[%d/%d]" cnt-done cnt-all))
11748 ndel (- (match-end 0) checkbox-beg))
11749 ;; handle overlays when updating cookie from column view
11750 (when (setq ov (car (overlays-at checkbox-beg)))
11751 (setq ovs (overlay-start ov) ove (overlay-end ov))
11752 (delete-overlay ov))
11753 (goto-char checkbox-beg)
11754 (insert new)
11755 (delete-region (point) (+ (point) ndel))
11756 (when org-auto-align-tags (org-fix-tags-on-the-fly))
11757 (when ov (move-overlay ov ovs ove)))
11758 (when cookie-present
11759 (run-hook-with-args 'org-after-todo-statistics-hook
11760 cnt-done (- cnt-all cnt-done))))))
11761 (run-hooks 'org-todo-statistics-hook)))
11763 (defvar org-after-todo-statistics-hook nil
11764 "Hook that is called after a TODO statistics cookie has been updated.
11765 Each function is called with two arguments: the number of not-done entries
11766 and the number of done entries.
11768 For example, the following function, when added to this hook, will switch
11769 an entry to DONE when all children are done, and back to TODO when new
11770 entries are set to a TODO status. Note that this hook is only called
11771 when there is a statistics cookie in the headline!
11773 (defun org-summary-todo (n-done n-not-done)
11774 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
11775 (let (org-log-done org-log-states) ; turn off logging
11776 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
11779 (defvar org-todo-statistics-hook nil
11780 "Hook that is run whenever Org thinks TODO statistics should be updated.
11781 This hook runs even if there is no statistics cookie present, in which case
11782 `org-after-todo-statistics-hook' would not run.")
11784 (defun org-todo-trigger-tag-changes (state)
11785 "Apply the changes defined in `org-todo-state-tags-triggers'."
11786 (let ((l org-todo-state-tags-triggers)
11787 changes)
11788 (when (or (not state) (equal state ""))
11789 (setq changes (append changes (cdr (assoc "" l)))))
11790 (when (and (stringp state) (> (length state) 0))
11791 (setq changes (append changes (cdr (assoc state l)))))
11792 (when (member state org-not-done-keywords)
11793 (setq changes (append changes (cdr (assoc 'todo l)))))
11794 (when (member state org-done-keywords)
11795 (setq changes (append changes (cdr (assoc 'done l)))))
11796 (dolist (c changes)
11797 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
11799 (defun org-local-logging (value)
11800 "Get logging settings from a property VALUE."
11801 (let* (words w a)
11802 ;; directly set the variables, they are already local.
11803 (setq org-log-done nil
11804 org-log-repeat nil
11805 org-todo-log-states nil)
11806 (setq words (org-split-string value))
11807 (while (setq w (pop words))
11808 (cond
11809 ((setq a (assoc w org-startup-options))
11810 (and (member (nth 1 a) '(org-log-done org-log-repeat))
11811 (set (nth 1 a) (nth 2 a))))
11812 ((setq a (org-extract-log-state-settings w))
11813 (and (member (car a) org-todo-keywords-1)
11814 (push a org-todo-log-states)))))))
11816 (defun org-get-todo-sequence-head (kwd)
11817 "Return the head of the TODO sequence to which KWD belongs.
11818 If KWD is not set, check if there is a text property remembering the
11819 right sequence."
11820 (let (p)
11821 (cond
11822 ((not kwd)
11823 (or (get-text-property (point-at-bol) 'org-todo-head)
11824 (progn
11825 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
11826 nil (point-at-eol)))
11827 (get-text-property p 'org-todo-head))))
11828 ((not (member kwd org-todo-keywords-1))
11829 (car org-todo-keywords-1))
11830 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
11832 (defun org-fast-todo-selection ()
11833 "Fast TODO keyword selection with single keys.
11834 Returns the new TODO keyword, or nil if no state change should occur."
11835 (let* ((fulltable org-todo-key-alist)
11836 (done-keywords org-done-keywords) ;; needed for the faces.
11837 (maxlen (apply 'max (mapcar
11838 (lambda (x)
11839 (if (stringp (car x)) (string-width (car x)) 0))
11840 fulltable)))
11841 (expert nil)
11842 (fwidth (+ maxlen 3 1 3))
11843 (ncol (/ (- (window-width) 4) fwidth))
11844 tg cnt e c tbl
11845 groups ingroup)
11846 (save-excursion
11847 (save-window-excursion
11848 (if expert
11849 (set-buffer (get-buffer-create " *Org todo*"))
11850 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
11851 (erase-buffer)
11852 (org-set-local 'org-done-keywords done-keywords)
11853 (setq tbl fulltable cnt 0)
11854 (while (setq e (pop tbl))
11855 (cond
11856 ((equal e '(:startgroup))
11857 (push '() groups) (setq ingroup t)
11858 (when (not (= cnt 0))
11859 (setq cnt 0)
11860 (insert "\n"))
11861 (insert "{ "))
11862 ((equal e '(:endgroup))
11863 (setq ingroup nil cnt 0)
11864 (insert "}\n"))
11865 ((equal e '(:newline))
11866 (when (not (= cnt 0))
11867 (setq cnt 0)
11868 (insert "\n")
11869 (setq e (car tbl))
11870 (while (equal (car tbl) '(:newline))
11871 (insert "\n")
11872 (setq tbl (cdr tbl)))))
11874 (setq tg (car e) c (cdr e))
11875 (if ingroup (push tg (car groups)))
11876 (setq tg (org-add-props tg nil 'face
11877 (org-get-todo-face tg)))
11878 (if (and (= cnt 0) (not ingroup)) (insert " "))
11879 (insert "[" c "] " tg (make-string
11880 (- fwidth 4 (length tg)) ?\ ))
11881 (when (= (setq cnt (1+ cnt)) ncol)
11882 (insert "\n")
11883 (if ingroup (insert " "))
11884 (setq cnt 0)))))
11885 (insert "\n")
11886 (goto-char (point-min))
11887 (if (not expert) (org-fit-window-to-buffer))
11888 (message "[a-z..]:Set [SPC]:clear")
11889 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
11890 (cond
11891 ((or (= c ?\C-g)
11892 (and (= c ?q) (not (rassoc c fulltable))))
11893 (setq quit-flag t))
11894 ((= c ?\ ) nil)
11895 ((setq e (rassoc c fulltable) tg (car e))
11897 (t (setq quit-flag t)))))))
11899 (defun org-entry-is-todo-p ()
11900 (member (org-get-todo-state) org-not-done-keywords))
11902 (defun org-entry-is-done-p ()
11903 (member (org-get-todo-state) org-done-keywords))
11905 (defun org-get-todo-state ()
11906 (save-excursion
11907 (org-back-to-heading t)
11908 (and (looking-at org-todo-line-regexp)
11909 (match-end 2)
11910 (match-string 2))))
11912 (defun org-at-date-range-p (&optional inactive-ok)
11913 "Is the cursor inside a date range?"
11914 (interactive)
11915 (save-excursion
11916 (catch 'exit
11917 (let ((pos (point)))
11918 (skip-chars-backward "^[<\r\n")
11919 (skip-chars-backward "<[")
11920 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
11921 (>= (match-end 0) pos)
11922 (throw 'exit t))
11923 (skip-chars-backward "^<[\r\n")
11924 (skip-chars-backward "<[")
11925 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
11926 (>= (match-end 0) pos)
11927 (throw 'exit t)))
11928 nil)))
11930 (defun org-get-repeat (&optional tagline)
11931 "Check if there is a deadline/schedule with repeater in this entry."
11932 (save-match-data
11933 (save-excursion
11934 (org-back-to-heading t)
11935 (and (re-search-forward (if tagline
11936 (concat tagline "\\s-*" org-repeat-re)
11937 org-repeat-re)
11938 (org-entry-end-position) t)
11939 (match-string-no-properties 1)))))
11941 (defvar org-last-changed-timestamp)
11942 (defvar org-last-inserted-timestamp)
11943 (defvar org-log-post-message)
11944 (defvar org-log-note-purpose)
11945 (defvar org-log-note-how)
11946 (defvar org-log-note-extra)
11947 (defun org-auto-repeat-maybe (done-word)
11948 "Check if the current headline contains a repeated deadline/schedule.
11949 If yes, set TODO state back to what it was and change the base date
11950 of repeating deadline/scheduled time stamps to new date.
11951 This function is run automatically after each state change to a DONE state."
11952 ;; last-state is dynamically scoped into this function
11953 (let* ((repeat (org-get-repeat))
11954 (aa (assoc org-last-state org-todo-kwd-alist))
11955 (interpret (nth 1 aa))
11956 (head (nth 2 aa))
11957 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
11958 (msg "Entry repeats: ")
11959 (org-log-done nil)
11960 (org-todo-log-states nil)
11961 re type n what ts time to-state)
11962 (when repeat
11963 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
11964 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
11965 org-todo-repeat-to-state))
11966 (unless (and to-state (member to-state org-todo-keywords-1))
11967 (setq to-state (if (eq interpret 'type) org-last-state head)))
11968 (org-todo to-state)
11969 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
11970 (org-entry-put nil "LAST_REPEAT" (format-time-string
11971 (org-time-stamp-format t t))))
11972 (when org-log-repeat
11973 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
11974 (memq 'org-add-log-note post-command-hook))
11975 ;; OK, we are already setup for some record
11976 (if (eq org-log-repeat 'note)
11977 ;; make sure we take a note, not only a time stamp
11978 (setq org-log-note-how 'note))
11979 ;; Set up for taking a record
11980 (org-add-log-setup 'state (or done-word (car org-done-keywords))
11981 org-last-state
11982 'findpos org-log-repeat)))
11983 (org-back-to-heading t)
11984 (org-add-planning-info nil nil 'closed)
11985 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
11986 org-deadline-time-regexp "\\)\\|\\("
11987 org-ts-regexp "\\)"))
11988 (while (re-search-forward
11989 re (save-excursion (outline-next-heading) (point)) t)
11990 (setq type (if (match-end 1) org-scheduled-string
11991 (if (match-end 3) org-deadline-string "Plain:"))
11992 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
11993 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
11994 (setq n (string-to-number (match-string 2 ts))
11995 what (match-string 3 ts))
11996 (if (equal what "w") (setq n (* n 7) what "d"))
11997 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
11998 (error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
11999 ;; Preparation, see if we need to modify the start date for the change
12000 (when (match-end 1)
12001 (setq time (save-match-data (org-time-string-to-time ts)))
12002 (cond
12003 ((equal (match-string 1 ts) ".")
12004 ;; Shift starting date to today
12005 (org-timestamp-change
12006 (- (org-today) (time-to-days time))
12007 'day))
12008 ((equal (match-string 1 ts) "+")
12009 (let ((nshiftmax 10) (nshift 0))
12010 (while (or (= nshift 0)
12011 (<= (time-to-days time)
12012 (time-to-days (current-time))))
12013 (when (= (incf nshift) nshiftmax)
12014 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12015 (error "Abort")))
12016 (org-timestamp-change n (cdr (assoc what whata)))
12017 (org-at-timestamp-p t)
12018 (setq ts (match-string 1))
12019 (setq time (save-match-data (org-time-string-to-time ts)))))
12020 (org-timestamp-change (- n) (cdr (assoc what whata)))
12021 ;; rematch, so that we have everything in place for the real shift
12022 (org-at-timestamp-p t)
12023 (setq ts (match-string 1))
12024 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12025 (org-timestamp-change n (cdr (assoc what whata)))
12026 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12027 (setq org-log-post-message msg)
12028 (message "%s" msg))))
12030 (defun org-show-todo-tree (arg)
12031 "Make a compact tree which shows all headlines marked with TODO.
12032 The tree will show the lines where the regexp matches, and all higher
12033 headlines above the match.
12034 With a \\[universal-argument] prefix, prompt for a regexp to match.
12035 With a numeric prefix N, construct a sparse tree for the Nth element
12036 of `org-todo-keywords-1'."
12037 (interactive "P")
12038 (let ((case-fold-search nil)
12039 (kwd-re
12040 (cond ((null arg) org-not-done-regexp)
12041 ((equal arg '(4))
12042 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12043 (mapcar 'list org-todo-keywords-1))))
12044 (concat "\\("
12045 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12046 "\\)\\>")))
12047 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12048 (regexp-quote (nth (1- (prefix-numeric-value arg))
12049 org-todo-keywords-1)))
12050 (t (error "Invalid prefix argument: %s" arg)))))
12051 (message "%d TODO entries found"
12052 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12054 (defun org-deadline (&optional remove time)
12055 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12056 With argument REMOVE, remove any deadline from the item.
12057 With argument TIME, set the deadline at the corresponding date. TIME
12058 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12059 (interactive "P")
12060 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12061 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12062 'region-start-level 'region))
12063 org-loop-over-headlines-in-active-region)
12064 (org-map-entries
12065 `(org-deadline ',remove ,time)
12066 org-loop-over-headlines-in-active-region
12067 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12068 (let* ((old-date (org-entry-get nil "DEADLINE"))
12069 (repeater (and old-date
12070 (string-match
12071 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12072 old-date)
12073 (match-string 1 old-date))))
12074 (if remove
12075 (progn
12076 (when (and old-date org-log-redeadline)
12077 (org-add-log-setup 'deldeadline nil old-date 'findpos
12078 org-log-redeadline))
12079 (org-remove-timestamp-with-keyword org-deadline-string)
12080 (message "Item no longer has a deadline."))
12081 (org-add-planning-info 'deadline time 'closed)
12082 (when (and old-date org-log-redeadline
12083 (not (equal old-date
12084 (substring org-last-inserted-timestamp 1 -1))))
12085 (org-add-log-setup 'redeadline nil old-date 'findpos
12086 org-log-redeadline))
12087 (when repeater
12088 (save-excursion
12089 (org-back-to-heading t)
12090 (when (re-search-forward (concat org-deadline-string " "
12091 org-last-inserted-timestamp)
12092 (save-excursion
12093 (outline-next-heading) (point)) t)
12094 (goto-char (1- (match-end 0)))
12095 (insert " " repeater)
12096 (setq org-last-inserted-timestamp
12097 (concat (substring org-last-inserted-timestamp 0 -1)
12098 " " repeater
12099 (substring org-last-inserted-timestamp -1))))))
12100 (message "Deadline on %s" org-last-inserted-timestamp)))))
12102 (defun org-schedule (&optional remove time)
12103 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12104 With argument REMOVE, remove any scheduling date from the item.
12105 With argument TIME, scheduled at the corresponding date. TIME can
12106 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12107 (interactive "P")
12108 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12109 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12110 'region-start-level 'region))
12111 org-loop-over-headlines-in-active-region)
12112 (org-map-entries
12113 `(org-schedule ',remove ,time)
12114 org-loop-over-headlines-in-active-region
12115 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12116 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12117 (repeater (and old-date
12118 (string-match
12119 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12120 old-date)
12121 (match-string 1 old-date))))
12122 (if remove
12123 (progn
12124 (when (and old-date org-log-reschedule)
12125 (org-add-log-setup 'delschedule nil old-date 'findpos
12126 org-log-reschedule))
12127 (org-remove-timestamp-with-keyword org-scheduled-string)
12128 (message "Item is no longer scheduled."))
12129 (org-add-planning-info 'scheduled time 'closed)
12130 (when (and old-date org-log-reschedule
12131 (not (equal old-date
12132 (substring org-last-inserted-timestamp 1 -1))))
12133 (org-add-log-setup 'reschedule nil old-date 'findpos
12134 org-log-reschedule))
12135 (when repeater
12136 (save-excursion
12137 (org-back-to-heading t)
12138 (when (re-search-forward (concat org-scheduled-string " "
12139 org-last-inserted-timestamp)
12140 (save-excursion
12141 (outline-next-heading) (point)) t)
12142 (goto-char (1- (match-end 0)))
12143 (insert " " repeater)
12144 (setq org-last-inserted-timestamp
12145 (concat (substring org-last-inserted-timestamp 0 -1)
12146 " " repeater
12147 (substring org-last-inserted-timestamp -1))))))
12148 (message "Scheduled to %s" org-last-inserted-timestamp)))))
12150 (defun org-get-scheduled-time (pom &optional inherit)
12151 "Get the scheduled time as a time tuple, of a format suitable
12152 for calling org-schedule with, or if there is no scheduling,
12153 returns nil."
12154 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12155 (when time
12156 (apply 'encode-time (org-parse-time-string time)))))
12158 (defun org-get-deadline-time (pom &optional inherit)
12159 "Get the deadline as a time tuple, of a format suitable for
12160 calling org-deadline with, or if there is no scheduling, returns
12161 nil."
12162 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12163 (when time
12164 (apply 'encode-time (org-parse-time-string time)))))
12166 (defun org-remove-timestamp-with-keyword (keyword)
12167 "Remove all time stamps with KEYWORD in the current entry."
12168 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12169 beg)
12170 (save-excursion
12171 (org-back-to-heading t)
12172 (setq beg (point))
12173 (outline-next-heading)
12174 (while (re-search-backward re beg t)
12175 (replace-match "")
12176 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12177 (equal (char-before) ?\ ))
12178 (backward-delete-char 1)
12179 (if (string-match "^[ \t]*$" (buffer-substring
12180 (point-at-bol) (point-at-eol)))
12181 (delete-region (point-at-bol)
12182 (min (point-max) (1+ (point-at-eol))))))))))
12184 (defun org-add-planning-info (what &optional time &rest remove)
12185 "Insert new timestamp with keyword in the line directly after the headline.
12186 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
12187 If non is given, the user is prompted for a date.
12188 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
12189 be removed."
12190 (interactive)
12191 (let (org-time-was-given org-end-time-was-given ts
12192 end default-time default-input)
12194 (catch 'exit
12195 (when (and (memq what '(scheduled deadline))
12196 (or (not time)
12197 (and (stringp time)
12198 (string-match "^[-+]+[0-9]" time))))
12199 ;; Try to get a default date/time from existing timestamp
12200 (save-excursion
12201 (org-back-to-heading t)
12202 (setq end (save-excursion (outline-next-heading) (point)))
12203 (when (re-search-forward (if (eq what 'scheduled)
12204 org-scheduled-time-regexp
12205 org-deadline-time-regexp)
12206 end t)
12207 (setq ts (match-string 1)
12208 default-time
12209 (apply 'encode-time (org-parse-time-string ts))
12210 default-input (and ts (org-get-compact-tod ts))))))
12211 (when what
12212 (setq time
12213 (if (stringp time)
12214 ;; This is a string (relative or absolute), set proper date
12215 (apply 'encode-time
12216 (org-read-date-analyze
12217 time default-time (decode-time default-time)))
12218 ;; If necessary, get the time from the user
12219 (or time (org-read-date nil 'to-time nil nil
12220 default-time default-input)))))
12222 (when (and org-insert-labeled-timestamps-at-point
12223 (member what '(scheduled deadline)))
12224 (insert
12225 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
12226 (org-insert-time-stamp time org-time-was-given
12227 nil nil nil (list org-end-time-was-given))
12228 (setq what nil))
12229 (save-excursion
12230 (save-restriction
12231 (let (col list elt ts buffer-invisibility-spec)
12232 (org-back-to-heading t)
12233 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
12234 (goto-char (match-end 1))
12235 (setq col (current-column))
12236 (goto-char (match-end 0))
12237 (if (eobp) (insert "\n") (forward-char 1))
12238 (when (and (not what)
12239 (not (looking-at
12240 (concat "[ \t]*"
12241 org-keyword-time-not-clock-regexp))))
12242 ;; Nothing to add, nothing to remove...... :-)
12243 (throw 'exit nil))
12244 (if (and (not (looking-at org-outline-regexp))
12245 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
12246 "[^\r\n]*"))
12247 (not (equal (match-string 1) org-clock-string)))
12248 (narrow-to-region (match-beginning 0) (match-end 0))
12249 (insert-before-markers "\n")
12250 (backward-char 1)
12251 (narrow-to-region (point) (point))
12252 (and org-adapt-indentation (org-indent-to-column col)))
12253 ;; Check if we have to remove something.
12254 (setq list (cons what remove))
12255 (while list
12256 (setq elt (pop list))
12257 (when (or (and (eq elt 'scheduled)
12258 (re-search-forward org-scheduled-time-regexp nil t))
12259 (and (eq elt 'deadline)
12260 (re-search-forward org-deadline-time-regexp nil t))
12261 (and (eq elt 'closed)
12262 (re-search-forward org-closed-time-regexp nil t)))
12263 (replace-match "")
12264 (if (looking-at "--+<[^>]+>") (replace-match ""))))
12265 (and (looking-at "[ \t]+") (replace-match ""))
12266 (and org-adapt-indentation (bolp) (org-indent-to-column col))
12267 (when what
12268 (insert
12269 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
12270 (cond ((eq what 'scheduled) org-scheduled-string)
12271 ((eq what 'deadline) org-deadline-string)
12272 ((eq what 'closed) org-closed-string))
12273 " ")
12274 (setq ts (org-insert-time-stamp
12275 time
12276 (or org-time-was-given
12277 (and (eq what 'closed) org-log-done-with-time))
12278 (eq what 'closed)
12279 nil nil (list org-end-time-was-given)))
12280 (insert
12281 (if (not (or (bolp) (eq (char-before) ?\ )
12282 (memq (char-after) '(32 10))
12283 (eobp))) " " ""))
12284 (end-of-line 1))
12285 (goto-char (point-min))
12286 (widen)
12287 (if (and (looking-at "[ \t]*\n")
12288 (equal (char-before) ?\n))
12289 (delete-region (1- (point)) (point-at-eol)))
12290 ts))))))
12292 (defvar org-log-note-marker (make-marker))
12293 (defvar org-log-note-purpose nil)
12294 (defvar org-log-note-state nil)
12295 (defvar org-log-note-previous-state nil)
12296 (defvar org-log-note-how nil)
12297 (defvar org-log-note-extra nil)
12298 (defvar org-log-note-window-configuration nil)
12299 (defvar org-log-note-return-to (make-marker))
12300 (defvar org-log-note-effective-time nil
12301 "Remembered current time so that dynamically scoped
12302 `org-extend-today-until' affects tha timestamps in state change
12303 log")
12305 (defvar org-log-post-message nil
12306 "Message to be displayed after a log note has been stored.
12307 The auto-repeater uses this.")
12309 (defun org-add-note ()
12310 "Add a note to the current entry.
12311 This is done in the same way as adding a state change note."
12312 (interactive)
12313 (org-add-log-setup 'note nil nil 'findpos nil))
12315 (defvar org-property-end-re)
12316 (defun org-add-log-setup (&optional purpose state prev-state
12317 findpos how extra)
12318 "Set up the post command hook to take a note.
12319 If this is about to TODO state change, the new state is expected in STATE.
12320 When FINDPOS is non-nil, find the correct position for the note in
12321 the current entry. If not, assume that it can be inserted at point.
12322 HOW is an indicator what kind of note should be created.
12323 EXTRA is additional text that will be inserted into the notes buffer."
12324 (let* ((org-log-into-drawer (org-log-into-drawer))
12325 (drawer (cond ((stringp org-log-into-drawer)
12326 org-log-into-drawer)
12327 (org-log-into-drawer "LOGBOOK")
12328 (t nil))))
12329 (save-restriction
12330 (save-excursion
12331 (when findpos
12332 (org-back-to-heading t)
12333 (narrow-to-region (point) (save-excursion
12334 (outline-next-heading) (point)))
12335 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
12336 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
12337 "[^\r\n]*\\)?"))
12338 (goto-char (match-end 0))
12339 (cond
12340 (drawer
12341 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
12342 nil t)
12343 (progn
12344 (goto-char (match-end 0))
12345 (or org-log-states-order-reversed
12346 (and (re-search-forward org-property-end-re nil t)
12347 (goto-char (1- (match-beginning 0))))))
12348 (insert "\n:" drawer ":\n:END:")
12349 (beginning-of-line 0)
12350 (org-indent-line-function)
12351 (beginning-of-line 2)
12352 (org-indent-line-function)
12353 (end-of-line 0)))
12354 ((and org-log-state-notes-insert-after-drawers
12355 (save-excursion
12356 (forward-line) (looking-at org-drawer-regexp)))
12357 (forward-line)
12358 (while (looking-at org-drawer-regexp)
12359 (goto-char (match-end 0))
12360 (re-search-forward org-property-end-re (point-max) t)
12361 (forward-line))
12362 (forward-line -1)))
12363 (unless org-log-states-order-reversed
12364 (and (= (char-after) ?\n) (forward-char 1))
12365 (org-skip-over-state-notes)
12366 (skip-chars-backward " \t\n\r")))
12367 (move-marker org-log-note-marker (point))
12368 (setq org-log-note-purpose purpose
12369 org-log-note-state state
12370 org-log-note-previous-state prev-state
12371 org-log-note-how how
12372 org-log-note-extra extra
12373 org-log-note-effective-time (org-current-effective-time))
12374 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
12376 (defun org-skip-over-state-notes ()
12377 "Skip past the list of State notes in an entry."
12378 (if (looking-at "\n[ \t]*- State") (forward-char 1))
12379 (when (ignore-errors (goto-char (org-in-item-p)))
12380 (let* ((struct (org-list-struct))
12381 (prevs (org-list-prevs-alist struct)))
12382 (while (looking-at "[ \t]*- State")
12383 (goto-char (or (org-list-get-next-item (point) struct prevs)
12384 (org-list-get-item-end (point) struct)))))))
12386 (defun org-add-log-note (&optional purpose)
12387 "Pop up a window for taking a note, and add this note later at point."
12388 (remove-hook 'post-command-hook 'org-add-log-note)
12389 (setq org-log-note-window-configuration (current-window-configuration))
12390 (delete-other-windows)
12391 (move-marker org-log-note-return-to (point))
12392 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
12393 (goto-char org-log-note-marker)
12394 (org-switch-to-buffer-other-window "*Org Note*")
12395 (erase-buffer)
12396 (if (memq org-log-note-how '(time state))
12397 (let (current-prefix-arg) (org-store-log-note))
12398 (let ((org-inhibit-startup t)) (org-mode))
12399 (insert (format "# Insert note for %s.
12400 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
12401 (cond
12402 ((eq org-log-note-purpose 'clock-out) "stopped clock")
12403 ((eq org-log-note-purpose 'done) "closed todo item")
12404 ((eq org-log-note-purpose 'state)
12405 (format "state change from \"%s\" to \"%s\""
12406 (or org-log-note-previous-state "")
12407 (or org-log-note-state "")))
12408 ((eq org-log-note-purpose 'reschedule)
12409 "rescheduling")
12410 ((eq org-log-note-purpose 'delschedule)
12411 "no longer scheduled")
12412 ((eq org-log-note-purpose 'redeadline)
12413 "changing deadline")
12414 ((eq org-log-note-purpose 'deldeadline)
12415 "removing deadline")
12416 ((eq org-log-note-purpose 'refile)
12417 "refiling")
12418 ((eq org-log-note-purpose 'note)
12419 "this entry")
12420 (t (error "This should not happen")))))
12421 (if org-log-note-extra (insert org-log-note-extra))
12422 (org-set-local 'org-finish-function 'org-store-log-note)
12423 (run-hooks 'org-log-buffer-setup-hook)))
12425 (defvar org-note-abort nil) ; dynamically scoped
12426 (defun org-store-log-note ()
12427 "Finish taking a log note, and insert it to where it belongs."
12428 (let ((txt (buffer-string))
12429 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
12430 lines ind bul)
12431 (kill-buffer (current-buffer))
12432 (while (string-match "\\`#.*\n[ \t\n]*" txt)
12433 (setq txt (replace-match "" t t txt)))
12434 (if (string-match "\\s-+\\'" txt)
12435 (setq txt (replace-match "" t t txt)))
12436 (setq lines (org-split-string txt "\n"))
12437 (when (and note (string-match "\\S-" note))
12438 (setq note
12439 (org-replace-escapes
12440 note
12441 (list (cons "%u" (user-login-name))
12442 (cons "%U" user-full-name)
12443 (cons "%t" (format-time-string
12444 (org-time-stamp-format 'long 'inactive)
12445 org-log-note-effective-time))
12446 (cons "%T" (format-time-string
12447 (org-time-stamp-format 'long nil)
12448 org-log-note-effective-time))
12449 (cons "%d" (format-time-string
12450 (org-time-stamp-format nil 'inactive)
12451 org-log-note-effective-time))
12452 (cons "%D" (format-time-string
12453 (org-time-stamp-format nil nil)
12454 org-log-note-effective-time))
12455 (cons "%s" (if org-log-note-state
12456 (concat "\"" org-log-note-state "\"")
12457 ""))
12458 (cons "%S" (if org-log-note-previous-state
12459 (concat "\"" org-log-note-previous-state "\"")
12460 "\"\"")))))
12461 (if lines (setq note (concat note " \\\\")))
12462 (push note lines))
12463 (when (or current-prefix-arg org-note-abort)
12464 (when org-log-into-drawer
12465 (org-remove-empty-drawer-at
12466 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
12467 org-log-note-marker))
12468 (setq lines nil))
12469 (when lines
12470 (with-current-buffer (marker-buffer org-log-note-marker)
12471 (save-excursion
12472 (goto-char org-log-note-marker)
12473 (move-marker org-log-note-marker nil)
12474 (end-of-line 1)
12475 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
12476 (setq ind (save-excursion
12477 (if (ignore-errors (goto-char (org-in-item-p)))
12478 (let ((struct (org-list-struct)))
12479 (org-list-get-ind
12480 (org-list-get-top-point struct) struct))
12481 (skip-chars-backward " \r\t\n")
12482 (cond
12483 ((and (org-at-heading-p)
12484 org-adapt-indentation)
12485 (1+ (org-current-level)))
12486 ((org-at-heading-p) 0)
12487 (t (org-get-indentation))))))
12488 (setq bul (org-list-bullet-string "-"))
12489 (org-indent-line-to ind)
12490 (insert bul (pop lines))
12491 (let ((ind-body (+ (length bul) ind)))
12492 (while lines
12493 (insert "\n")
12494 (org-indent-line-to ind-body)
12495 (insert (pop lines))))
12496 (message "Note stored")
12497 (org-back-to-heading t)
12498 (org-cycle-hide-drawers 'children)))))
12499 (set-window-configuration org-log-note-window-configuration)
12500 (with-current-buffer (marker-buffer org-log-note-return-to)
12501 (goto-char org-log-note-return-to))
12502 (move-marker org-log-note-return-to nil)
12503 (and org-log-post-message (message "%s" org-log-post-message)))
12505 (defun org-remove-empty-drawer-at (drawer pos)
12506 "Remove an empty drawer DRAWER at position POS.
12507 POS may also be a marker."
12508 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
12509 (save-excursion
12510 (save-restriction
12511 (widen)
12512 (goto-char pos)
12513 (if (org-in-regexp
12514 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
12515 (replace-match ""))))))
12517 (defun org-sparse-tree (&optional arg)
12518 "Create a sparse tree, prompt for the details.
12519 This command can create sparse trees. You first need to select the type
12520 of match used to create the tree:
12522 t Show all TODO entries.
12523 T Show entries with a specific TODO keyword.
12524 m Show entries selected by a tags/property match.
12525 p Enter a property name and its value (both with completion on existing
12526 names/values) and show entries with that property.
12527 r Show entries matching a regular expression (`/' can be used as well)
12528 d Show deadlines due within `org-deadline-warning-days'.
12529 b Show deadlines and scheduled items before a date.
12530 a Show deadlines and scheduled items after a date."
12531 (interactive "P")
12532 (let (ans kwd value)
12533 (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")
12534 (setq ans (read-char-exclusive))
12535 (cond
12536 ((equal ans ?d)
12537 (call-interactively 'org-check-deadlines))
12538 ((equal ans ?b)
12539 (call-interactively 'org-check-before-date))
12540 ((equal ans ?a)
12541 (call-interactively 'org-check-after-date))
12542 ((equal ans ?D)
12543 (call-interactively 'org-check-dates-range))
12544 ((equal ans ?t)
12545 (org-show-todo-tree nil))
12546 ((equal ans ?T)
12547 (org-show-todo-tree '(4)))
12548 ((member ans '(?T ?m))
12549 (call-interactively 'org-match-sparse-tree))
12550 ((member ans '(?p ?P))
12551 (setq kwd (org-icompleting-read "Property: "
12552 (mapcar 'list (org-buffer-property-keys))))
12553 (setq value (org-icompleting-read "Value: "
12554 (mapcar 'list (org-property-values kwd))))
12555 (unless (string-match "\\`{.*}\\'" value)
12556 (setq value (concat "\"" value "\"")))
12557 (org-match-sparse-tree arg (concat kwd "=" value)))
12558 ((member ans '(?r ?R ?/))
12559 (call-interactively 'org-occur))
12560 (t (error "No such sparse tree command \"%c\"" ans)))))
12562 (defvar org-occur-highlights nil
12563 "List of overlays used for occur matches.")
12564 (make-variable-buffer-local 'org-occur-highlights)
12565 (defvar org-occur-parameters nil
12566 "Parameters of the active org-occur calls.
12567 This is a list, each call to org-occur pushes as cons cell,
12568 containing the regular expression and the callback, onto the list.
12569 The list can contain several entries if `org-occur' has been called
12570 several time with the KEEP-PREVIOUS argument. Otherwise, this list
12571 will only contain one set of parameters. When the highlights are
12572 removed (for example with `C-c C-c', or with the next edit (depending
12573 on `org-remove-highlights-with-change'), this variable is emptied
12574 as well.")
12575 (make-variable-buffer-local 'org-occur-parameters)
12577 (defun org-occur (regexp &optional keep-previous callback)
12578 "Make a compact tree which shows all matches of REGEXP.
12579 The tree will show the lines where the regexp matches, and all higher
12580 headlines above the match. It will also show the heading after the match,
12581 to make sure editing the matching entry is easy.
12582 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
12583 call to `org-occur' will be kept, to allow stacking of calls to this
12584 command.
12585 If CALLBACK is non-nil, it is a function which is called to confirm
12586 that the match should indeed be shown."
12587 (interactive "sRegexp: \nP")
12588 (when (equal regexp "")
12589 (error "Regexp cannot be empty"))
12590 (unless keep-previous
12591 (org-remove-occur-highlights nil nil t))
12592 (push (cons regexp callback) org-occur-parameters)
12593 (let ((cnt 0))
12594 (save-excursion
12595 (goto-char (point-min))
12596 (if (or (not keep-previous) ; do not want to keep
12597 (not org-occur-highlights)) ; no previous matches
12598 ;; hide everything
12599 (org-overview))
12600 (while (re-search-forward regexp nil t)
12601 (when (or (not callback)
12602 (save-match-data (funcall callback)))
12603 (setq cnt (1+ cnt))
12604 (when org-highlight-sparse-tree-matches
12605 (org-highlight-new-match (match-beginning 0) (match-end 0)))
12606 (org-show-context 'occur-tree))))
12607 (when org-remove-highlights-with-change
12608 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
12609 nil 'local))
12610 (unless org-sparse-tree-open-archived-trees
12611 (org-hide-archived-subtrees (point-min) (point-max)))
12612 (run-hooks 'org-occur-hook)
12613 (if (org-called-interactively-p 'interactive)
12614 (message "%d match(es) for regexp %s" cnt regexp))
12615 cnt))
12617 (defun org-occur-next-match (&optional n reset)
12618 "Function for `next-error-function' to find sparse tree matches.
12619 N is the number of matches to move, when negative move backwards.
12620 RESET is entirely ignored - this function always goes back to the
12621 starting point when no match is found."
12622 (let* ((limit (if (< n 0) (point-min) (point-max)))
12623 (search-func (if (< n 0)
12624 'previous-single-char-property-change
12625 'next-single-char-property-change))
12626 (n (abs n))
12627 (pos (point))
12629 (catch 'exit
12630 (while (setq p1 (funcall search-func (point) 'org-type))
12631 (when (equal p1 limit)
12632 (goto-char pos)
12633 (error "No more matches"))
12634 (when (equal (get-char-property p1 'org-type) 'org-occur)
12635 (setq n (1- n))
12636 (when (= n 0)
12637 (goto-char p1)
12638 (throw 'exit (point))))
12639 (goto-char p1))
12640 (goto-char p1)
12641 (error "No more matches"))))
12643 (defun org-show-context (&optional key)
12644 "Make sure point and context are visible.
12645 How much context is shown depends upon the variables
12646 `org-show-hierarchy-above', `org-show-following-heading',
12647 `org-show-entry-below' and `org-show-siblings'."
12648 (let ((heading-p (org-at-heading-p t))
12649 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
12650 (following-p (org-get-alist-option org-show-following-heading key))
12651 (entry-p (org-get-alist-option org-show-entry-below key))
12652 (siblings-p (org-get-alist-option org-show-siblings key)))
12653 (catch 'exit
12654 ;; Show heading or entry text
12655 (if (and heading-p (not entry-p))
12656 (org-flag-heading nil) ; only show the heading
12657 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
12658 (org-show-hidden-entry))) ; show entire entry
12659 (when following-p
12660 ;; Show next sibling, or heading below text
12661 (save-excursion
12662 (and (if heading-p (org-goto-sibling) (outline-next-heading))
12663 (org-flag-heading nil))))
12664 (when siblings-p (org-show-siblings))
12665 (when hierarchy-p
12666 ;; show all higher headings, possibly with siblings
12667 (save-excursion
12668 (while (and (condition-case nil
12669 (progn (org-up-heading-all 1) t)
12670 (error nil))
12671 (not (bobp)))
12672 (org-flag-heading nil)
12673 (when siblings-p (org-show-siblings))))))))
12675 (defvar org-reveal-start-hook nil
12676 "Hook run before revealing a location.")
12678 (defun org-reveal (&optional siblings)
12679 "Show current entry, hierarchy above it, and the following headline.
12680 This can be used to show a consistent set of context around locations
12681 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
12682 not t for the search context.
12684 With optional argument SIBLINGS, on each level of the hierarchy all
12685 siblings are shown. This repairs the tree structure to what it would
12686 look like when opened with hierarchical calls to `org-cycle'.
12687 With double optional argument \\[universal-argument] \\[universal-argument], \
12688 go to the parent and show the
12689 entire tree."
12690 (interactive "P")
12691 (run-hooks 'org-reveal-start-hook)
12692 (let ((org-show-hierarchy-above t)
12693 (org-show-following-heading t)
12694 (org-show-siblings (if siblings t org-show-siblings)))
12695 (org-show-context nil))
12696 (when (equal siblings '(16))
12697 (save-excursion
12698 (when (org-up-heading-safe)
12699 (org-show-subtree)
12700 (run-hook-with-args 'org-cycle-hook 'subtree)))))
12702 (defun org-highlight-new-match (beg end)
12703 "Highlight from BEG to END and mark the highlight is an occur headline."
12704 (let ((ov (make-overlay beg end)))
12705 (overlay-put ov 'face 'secondary-selection)
12706 (overlay-put ov 'org-type 'org-occur)
12707 (push ov org-occur-highlights)))
12709 (defun org-remove-occur-highlights (&optional beg end noremove)
12710 "Remove the occur highlights from the buffer.
12711 BEG and END are ignored. If NOREMOVE is nil, remove this function
12712 from the `before-change-functions' in the current buffer."
12713 (interactive)
12714 (unless org-inhibit-highlight-removal
12715 (mapc 'delete-overlay org-occur-highlights)
12716 (setq org-occur-highlights nil)
12717 (setq org-occur-parameters nil)
12718 (unless noremove
12719 (remove-hook 'before-change-functions
12720 'org-remove-occur-highlights 'local))))
12722 ;;;; Priorities
12724 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
12725 "Regular expression matching the priority indicator.")
12727 (defvar org-remove-priority-next-time nil)
12729 (defun org-priority-up ()
12730 "Increase the priority of the current item."
12731 (interactive)
12732 (org-priority 'up))
12734 (defun org-priority-down ()
12735 "Decrease the priority of the current item."
12736 (interactive)
12737 (org-priority 'down))
12739 (defun org-priority (&optional action)
12740 "Change the priority of an item by ARG.
12741 ACTION can be `set', `up', `down', or a character."
12742 (interactive)
12743 (unless org-enable-priority-commands
12744 (error "Priority commands are disabled"))
12745 (setq action (or action 'set))
12746 (let (current new news have remove)
12747 (save-excursion
12748 (org-back-to-heading t)
12749 (if (looking-at org-priority-regexp)
12750 (setq current (string-to-char (match-string 2))
12751 have t))
12752 (cond
12753 ((eq action 'remove)
12754 (setq remove t new ?\ ))
12755 ((or (eq action 'set)
12756 (if (featurep 'xemacs) (characterp action) (integerp action)))
12757 (if (not (eq action 'set))
12758 (setq new action)
12759 (message "Priority %c-%c, SPC to remove: "
12760 org-highest-priority org-lowest-priority)
12761 (save-match-data
12762 (setq new (read-char-exclusive))))
12763 (if (and (= (upcase org-highest-priority) org-highest-priority)
12764 (= (upcase org-lowest-priority) org-lowest-priority))
12765 (setq new (upcase new)))
12766 (cond ((equal new ?\ ) (setq remove t))
12767 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
12768 (error "Priority must be between `%c' and `%c'"
12769 org-highest-priority org-lowest-priority))))
12770 ((eq action 'up)
12771 (setq new (if have
12772 (1- current) ; normal cycling
12773 ;; last priority was empty
12774 (if (eq last-command this-command)
12775 org-lowest-priority ; wrap around empty to lowest
12776 ;; default
12777 (if org-priority-start-cycle-with-default
12778 org-default-priority
12779 (1- org-default-priority))))))
12780 ((eq action 'down)
12781 (setq new (if have
12782 (1+ current) ; normal cycling
12783 ;; last priority was empty
12784 (if (eq last-command this-command)
12785 org-highest-priority ; wrap around empty to highest
12786 ;; default
12787 (if org-priority-start-cycle-with-default
12788 org-default-priority
12789 (1+ org-default-priority))))))
12790 (t (error "Invalid action")))
12791 (if (or (< (upcase new) org-highest-priority)
12792 (> (upcase new) org-lowest-priority))
12793 (if (and (memq action '(up down))
12794 (not have) (not (eq last-command this-command)))
12795 ;; `new' is from default priority
12796 (error
12797 "The default can not be set, see `org-default-priority' why")
12798 ;; normal cycling: `new' is beyond highest/lowest priority
12799 ;; and is wrapped around to the empty priority
12800 (setq remove t)))
12801 (setq news (format "%c" new))
12802 (if have
12803 (if remove
12804 (replace-match "" t t nil 1)
12805 (replace-match news t t nil 2))
12806 (if remove
12807 (error "No priority cookie found in line")
12808 (let ((case-fold-search nil))
12809 (looking-at org-todo-line-regexp))
12810 (if (match-end 2)
12811 (progn
12812 (goto-char (match-end 2))
12813 (insert " [#" news "]"))
12814 (goto-char (match-beginning 3))
12815 (insert "[#" news "] "))))
12816 (org-preserve-lc (org-set-tags nil 'align)))
12817 (if remove
12818 (message "Priority removed")
12819 (message "Priority of current item set to %s" news))))
12821 (defun org-get-priority (s)
12822 "Find priority cookie and return priority."
12823 (if (functionp org-get-priority-function)
12824 (funcall org-get-priority-function)
12825 (save-match-data
12826 (if (not (string-match org-priority-regexp s))
12827 (* 1000 (- org-lowest-priority org-default-priority))
12828 (* 1000 (- org-lowest-priority
12829 (string-to-char (match-string 2 s))))))))
12831 ;;;; Tags
12833 (defvar org-agenda-archives-mode)
12834 (defvar org-map-continue-from nil
12835 "Position from where mapping should continue.
12836 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
12838 (defvar org-scanner-tags nil
12839 "The current tag list while the tags scanner is running.")
12840 (defvar org-trust-scanner-tags nil
12841 "Should `org-get-tags-at' use the tags for the scanner.
12842 This is for internal dynamical scoping only.
12843 When this is non-nil, the function `org-get-tags-at' will return the value
12844 of `org-scanner-tags' instead of building the list by itself. This
12845 can lead to large speed-ups when the tags scanner is used in a file with
12846 many entries, and when the list of tags is retrieved, for example to
12847 obtain a list of properties. Building the tags list for each entry in such
12848 a file becomes an N^2 operation - but with this variable set, it scales
12849 as N.")
12851 (defun org-scan-tags (action matcher todo-only &optional start-level)
12852 "Scan headline tags with inheritance and produce output ACTION.
12854 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
12855 or `agenda' to produce an entry list for an agenda view. It can also be
12856 a Lisp form or a function that should be called at each matched headline, in
12857 this case the return value is a list of all return values from these calls.
12859 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
12860 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
12861 only lines with a not-done TODO keyword are included in the output.
12862 This should be the same variable that was scoped into
12863 and set by `org-make-tags-matcher' when it constructed MATCHER.
12865 START-LEVEL can be a string with asterisks, reducing the scope to
12866 headlines matching this string."
12867 (require 'org-agenda)
12868 (let* ((re (concat "^"
12869 (if start-level
12870 ;; Get the correct level to match
12871 (concat "\\*\\{" (number-to-string start-level) "\\} ")
12872 org-outline-regexp)
12873 " *\\(\\<\\("
12874 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
12875 (org-re
12876 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
12877 (props (list 'face 'default
12878 'done-face 'org-agenda-done
12879 'undone-face 'default
12880 'mouse-face 'highlight
12881 'org-not-done-regexp org-not-done-regexp
12882 'org-todo-regexp org-todo-regexp
12883 'org-complex-heading-regexp org-complex-heading-regexp
12884 'help-echo
12885 (format "mouse-2 or RET jump to org file %s"
12886 (abbreviate-file-name
12887 (or (buffer-file-name (buffer-base-buffer))
12888 (buffer-name (buffer-base-buffer)))))))
12889 (case-fold-search nil)
12890 (org-map-continue-from nil)
12891 lspos tags tags-list
12892 (tags-alist (list (cons 0 org-file-tags)))
12893 (llast 0) rtn rtn1 level category i txt
12894 todo marker entry priority)
12895 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
12896 (setq action (list 'lambda nil action)))
12897 (save-excursion
12898 (goto-char (point-min))
12899 (when (eq action 'sparse-tree)
12900 (org-overview)
12901 (org-remove-occur-highlights))
12902 (while (re-search-forward re nil t)
12903 (setq org-map-continue-from nil)
12904 (catch :skip
12905 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
12906 tags (if (match-end 4) (org-match-string-no-properties 4)))
12907 (goto-char (setq lspos (match-beginning 0)))
12908 (setq level (org-reduced-level (funcall outline-level))
12909 category (org-get-category))
12910 (setq i llast llast level)
12911 ;; remove tag lists from same and sublevels
12912 (while (>= i level)
12913 (when (setq entry (assoc i tags-alist))
12914 (setq tags-alist (delete entry tags-alist)))
12915 (setq i (1- i)))
12916 ;; add the next tags
12917 (when tags
12918 (setq tags (org-split-string tags ":")
12919 tags-alist
12920 (cons (cons level tags) tags-alist)))
12921 ;; compile tags for current headline
12922 (setq tags-list
12923 (if org-use-tag-inheritance
12924 (apply 'append (mapcar 'cdr (reverse tags-alist)))
12925 tags)
12926 org-scanner-tags tags-list)
12927 (when org-use-tag-inheritance
12928 (setcdr (car tags-alist)
12929 (mapcar (lambda (x)
12930 (setq x (copy-sequence x))
12931 (org-add-prop-inherited x))
12932 (cdar tags-alist))))
12933 (when (and tags org-use-tag-inheritance
12934 (or (not (eq t org-use-tag-inheritance))
12935 org-tags-exclude-from-inheritance))
12936 ;; selective inheritance, remove uninherited ones
12937 (setcdr (car tags-alist)
12938 (org-remove-uninherited-tags (cdar tags-alist))))
12939 (when (and
12941 ;; eval matcher only when the todo condition is OK
12942 (and (or (not todo-only) (member todo org-not-done-keywords))
12943 (let ((case-fold-search t) (org-trust-scanner-tags t))
12944 (eval matcher)))
12946 ;; Call the skipper, but return t if it does not skip,
12947 ;; so that the `and' form continues evaluating
12948 (progn
12949 (unless (eq action 'sparse-tree) (org-agenda-skip))
12952 ;; Check if timestamps are deselecting this entry
12953 (or (not todo-only)
12954 (and (member todo org-not-done-keywords)
12955 (or (not org-agenda-tags-todo-honor-ignore-options)
12956 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
12958 ;; Extra check for the archive tag
12959 ;; FIXME: Does the skipper already do this????
12961 (not (member org-archive-tag tags-list))
12962 ;; we have an archive tag, should we use this anyway?
12963 (or (not org-agenda-skip-archived-trees)
12964 (and (eq action 'agenda) org-agenda-archives-mode))))
12966 ;; select this headline
12968 (cond
12969 ((eq action 'sparse-tree)
12970 (and org-highlight-sparse-tree-matches
12971 (org-get-heading) (match-end 0)
12972 (org-highlight-new-match
12973 (match-beginning 1) (match-end 1)))
12974 (org-show-context 'tags-tree))
12975 ((eq action 'agenda)
12976 (setq txt (org-agenda-format-item
12978 (concat
12979 (if (eq org-tags-match-list-sublevels 'indented)
12980 (make-string (1- level) ?.) "")
12981 (org-get-heading))
12982 category
12983 tags-list)
12984 priority (org-get-priority txt))
12985 (goto-char lspos)
12986 (setq marker (org-agenda-new-marker))
12987 (org-add-props txt props
12988 'org-marker marker 'org-hd-marker marker 'org-category category
12989 'todo-state todo
12990 'priority priority 'type "tagsmatch")
12991 (push txt rtn))
12992 ((functionp action)
12993 (setq org-map-continue-from nil)
12994 (save-excursion
12995 (setq rtn1 (funcall action))
12996 (push rtn1 rtn)))
12997 (t (error "Invalid action")))
12999 ;; if we are to skip sublevels, jump to end of subtree
13000 (unless org-tags-match-list-sublevels
13001 (org-end-of-subtree t)
13002 (backward-char 1))))
13003 ;; Get the correct position from where to continue
13004 (if org-map-continue-from
13005 (goto-char org-map-continue-from)
13006 (and (= (point) lspos) (end-of-line 1)))))
13007 (when (and (eq action 'sparse-tree)
13008 (not org-sparse-tree-open-archived-trees))
13009 (org-hide-archived-subtrees (point-min) (point-max)))
13010 (nreverse rtn)))
13012 (defun org-remove-uninherited-tags (tags)
13013 "Remove all tags that are not inherited from the list TAGS."
13014 (cond
13015 ((eq org-use-tag-inheritance t)
13016 (if org-tags-exclude-from-inheritance
13017 (org-delete-all org-tags-exclude-from-inheritance tags)
13018 tags))
13019 ((not org-use-tag-inheritance) nil)
13020 ((stringp org-use-tag-inheritance)
13021 (delq nil (mapcar
13022 (lambda (x)
13023 (if (and (string-match org-use-tag-inheritance x)
13024 (not (member x org-tags-exclude-from-inheritance)))
13025 x nil))
13026 tags)))
13027 ((listp org-use-tag-inheritance)
13028 (delq nil (mapcar
13029 (lambda (x)
13030 (if (member x org-use-tag-inheritance) x nil))
13031 tags)))))
13033 (defun org-match-sparse-tree (&optional todo-only match)
13034 "Create a sparse tree according to tags string MATCH.
13035 MATCH can contain positive and negative selection of tags, like
13036 \"+WORK+URGENT-WITHBOSS\".
13037 If optional argument TODO-ONLY is non-nil, only select lines that are
13038 also TODO lines."
13039 (interactive "P")
13040 (org-prepare-agenda-buffers (list (current-buffer)))
13041 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13043 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13045 (defvar org-cached-props nil)
13046 (defun org-cached-entry-get (pom property)
13047 (if (or (eq t org-use-property-inheritance)
13048 (and (stringp org-use-property-inheritance)
13049 (string-match org-use-property-inheritance property))
13050 (and (listp org-use-property-inheritance)
13051 (member property org-use-property-inheritance)))
13052 ;; Caching is not possible, check it directly
13053 (org-entry-get pom property 'inherit)
13054 ;; Get all properties, so that we can do complicated checks easily
13055 (cdr (assoc property (or org-cached-props
13056 (setq org-cached-props
13057 (org-entry-properties pom)))))))
13059 (defun org-global-tags-completion-table (&optional files)
13060 "Return the list of all tags in all agenda buffer/files.
13061 Optional FILES argument is a list of files to which can be used
13062 instead of the agenda files."
13063 (save-excursion
13064 (org-uniquify
13065 (delq nil
13066 (apply 'append
13067 (mapcar
13068 (lambda (file)
13069 (set-buffer (find-file-noselect file))
13070 (append (org-get-buffer-tags)
13071 (mapcar (lambda (x) (if (stringp (car-safe x))
13072 (list (car-safe x)) nil))
13073 org-tag-alist)))
13074 (if (and files (car files))
13075 files
13076 (org-agenda-files))))))))
13078 (defun org-make-tags-matcher (match)
13079 "Create the TAGS/TODO matcher form for the selection string MATCH.
13081 The variable `todo-only' is scoped dynamically into this function; it will be
13082 set to t if the matcher restricts matching to TODO entries,
13083 otherwise will not be touched.
13085 Returns a cons of the selection string MATCH and the constructed
13086 lisp form implementing the matcher. The matcher is to be
13087 evaluated at an Org entry, with point on the headline,
13088 and returns t if the entry matches the
13089 selection string MATCH. The returned lisp form references
13090 two variables with information about the entry, which must be
13091 bound around the form's evaluation: todo, the TODO keyword at the
13092 entry (or nil of none); and tags-list, the list of all tags at the
13093 entry including inherited ones. Additionally, the category
13094 of the entry (if any) must be specified as the text property
13095 'org-category on the headline.
13097 See also `org-scan-tags'.
13099 (declare (special todo-only))
13100 (unless (boundp 'todo-only)
13101 (error "org-make-tags-matcher expects todo-only to be scoped in"))
13102 (unless match
13103 ;; Get a new match request, with completion
13104 (let ((org-last-tags-completion-table
13105 (org-global-tags-completion-table)))
13106 (setq match (org-completing-read-no-i
13107 "Match: " 'org-tags-completion-function nil nil nil
13108 'org-tags-history))))
13110 ;; Parse the string and create a lisp form
13111 (let ((match0 match)
13112 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
13113 minus tag mm
13114 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
13115 orterms term orlist re-p str-p level-p level-op time-p
13116 prop-p pn pv po gv rest)
13117 (if (string-match "/+" match)
13118 ;; match contains also a todo-matching request
13119 (progn
13120 (setq tagsmatch (substring match 0 (match-beginning 0))
13121 todomatch (substring match (match-end 0)))
13122 (if (string-match "^!" todomatch)
13123 (setq todo-only t todomatch (substring todomatch 1)))
13124 (if (string-match "^\\s-*$" todomatch)
13125 (setq todomatch nil)))
13126 ;; only matching tags
13127 (setq tagsmatch match todomatch nil))
13129 ;; Make the tags matcher
13130 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
13131 (setq tagsmatcher t)
13132 (setq orterms (org-split-string tagsmatch "|") orlist nil)
13133 (while (setq term (pop orterms))
13134 (while (and (equal (substring term -1) "\\") orterms)
13135 (setq term (concat term "|" (pop orterms)))) ; repair bad split
13136 (while (string-match re term)
13137 (setq rest (substring term (match-end 0))
13138 minus (and (match-end 1)
13139 (equal (match-string 1 term) "-"))
13140 tag (save-match-data (replace-regexp-in-string
13141 "\\\\-" "-"
13142 (match-string 2 term)))
13143 re-p (equal (string-to-char tag) ?{)
13144 level-p (match-end 4)
13145 prop-p (match-end 5)
13146 mm (cond
13147 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
13148 (level-p
13149 (setq level-op (org-op-to-function (match-string 3 term)))
13150 `(,level-op level ,(string-to-number
13151 (match-string 4 term))))
13152 (prop-p
13153 (setq pn (match-string 5 term)
13154 po (match-string 6 term)
13155 pv (match-string 7 term)
13156 re-p (equal (string-to-char pv) ?{)
13157 str-p (equal (string-to-char pv) ?\")
13158 time-p (save-match-data
13159 (string-match "^\"[[<].*[]>]\"$" pv))
13160 pv (if (or re-p str-p) (substring pv 1 -1) pv))
13161 (if time-p (setq pv (org-matcher-time pv)))
13162 (setq po (org-op-to-function po (if time-p 'time str-p)))
13163 (cond
13164 ((equal pn "CATEGORY")
13165 (setq gv '(get-text-property (point) 'org-category)))
13166 ((equal pn "TODO")
13167 (setq gv 'todo))
13169 (setq gv `(org-cached-entry-get nil ,pn))))
13170 (if re-p
13171 (if (eq po 'org<>)
13172 `(not (string-match ,pv (or ,gv "")))
13173 `(string-match ,pv (or ,gv "")))
13174 (if str-p
13175 `(,po (or ,gv "") ,pv)
13176 `(,po (string-to-number (or ,gv ""))
13177 ,(string-to-number pv) ))))
13178 (t `(member ,tag tags-list)))
13179 mm (if minus (list 'not mm) mm)
13180 term rest)
13181 (push mm tagsmatcher))
13182 (push (if (> (length tagsmatcher) 1)
13183 (cons 'and tagsmatcher)
13184 (car tagsmatcher))
13185 orlist)
13186 (setq tagsmatcher nil))
13187 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
13188 (setq tagsmatcher
13189 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
13190 ;; Make the todo matcher
13191 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
13192 (setq todomatcher t)
13193 (setq orterms (org-split-string todomatch "|") orlist nil)
13194 (while (setq term (pop orterms))
13195 (while (string-match re term)
13196 (setq minus (and (match-end 1)
13197 (equal (match-string 1 term) "-"))
13198 kwd (match-string 2 term)
13199 re-p (equal (string-to-char kwd) ?{)
13200 term (substring term (match-end 0))
13201 mm (if re-p
13202 `(string-match ,(substring kwd 1 -1) todo)
13203 (list 'equal 'todo kwd))
13204 mm (if minus (list 'not mm) mm))
13205 (push mm todomatcher))
13206 (push (if (> (length todomatcher) 1)
13207 (cons 'and todomatcher)
13208 (car todomatcher))
13209 orlist)
13210 (setq todomatcher nil))
13211 (setq todomatcher (if (> (length orlist) 1)
13212 (cons 'or orlist) (car orlist))))
13214 ;; Return the string and lisp forms of the matcher
13215 (setq matcher (if todomatcher
13216 (list 'and tagsmatcher todomatcher)
13217 tagsmatcher))
13218 (when todo-only
13219 (setq matcher (list 'and '(member todo org-not-done-keywords)
13220 matcher)))
13221 (cons match0 matcher)))
13223 (defun org-op-to-function (op &optional stringp)
13224 "Turn an operator into the appropriate function."
13225 (setq op
13226 (cond
13227 ((equal op "<" ) '(< string< org-time<))
13228 ((equal op ">" ) '(> org-string> org-time>))
13229 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
13230 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
13231 ((member op '("=" "==")) '(= string= org-time=))
13232 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
13233 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
13235 (defun org<> (a b) (not (= a b)))
13236 (defun org-string<= (a b) (or (string= a b) (string< a b)))
13237 (defun org-string>= (a b) (not (string< a b)))
13238 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
13239 (defun org-string<> (a b) (not (string= a b)))
13240 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
13241 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
13242 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
13243 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
13244 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
13245 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
13246 (defun org-2ft (s)
13247 "Convert S to a floating point time.
13248 If S is already a number, just return it. If it is a string, parse
13249 it as a time string and apply `float-time' to it. If S is nil, just return 0."
13250 (cond
13251 ((numberp s) s)
13252 ((stringp s)
13253 (condition-case nil
13254 (float-time (apply 'encode-time (org-parse-time-string s)))
13255 (error 0.)))
13256 (t 0.)))
13258 (defun org-time-today ()
13259 "Time in seconds today at 0:00.
13260 Returns the float number of seconds since the beginning of the
13261 epoch to the beginning of today (00:00)."
13262 (float-time (apply 'encode-time
13263 (append '(0 0 0) (nthcdr 3 (decode-time))))))
13265 (defun org-matcher-time (s)
13266 "Interpret a time comparison value."
13267 (save-match-data
13268 (cond
13269 ((string= s "<now>") (float-time))
13270 ((string= s "<today>") (org-time-today))
13271 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
13272 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
13273 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
13274 (+ (org-time-today)
13275 (* (string-to-number (match-string 1 s))
13276 (cdr (assoc (match-string 2 s)
13277 '(("d" . 86400.0) ("w" . 604800.0)
13278 ("m" . 2678400.0) ("y" . 31557600.0)))))))
13279 (t (org-2ft s)))))
13281 (defun org-match-any-p (re list)
13282 "Does re match any element of list?"
13283 (setq list (mapcar (lambda (x) (string-match re x)) list))
13284 (delq nil list))
13286 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
13287 (defvar org-tags-overlay (make-overlay 1 1))
13288 (org-detach-overlay org-tags-overlay)
13290 (defun org-get-local-tags-at (&optional pos)
13291 "Get a list of tags defined in the current headline."
13292 (org-get-tags-at pos 'local))
13294 (defun org-get-local-tags ()
13295 "Get a list of tags defined in the current headline."
13296 (org-get-tags-at nil 'local))
13298 (defun org-get-tags-at (&optional pos local)
13299 "Get a list of all headline tags applicable at POS.
13300 POS defaults to point. If tags are inherited, the list contains
13301 the targets in the same sequence as the headlines appear, i.e.
13302 the tags of the current headline come last.
13303 When LOCAL is non-nil, only return tags from the current headline,
13304 ignore inherited ones."
13305 (interactive)
13306 (if (and org-trust-scanner-tags
13307 (or (not pos) (equal pos (point)))
13308 (not local))
13309 org-scanner-tags
13310 (let (tags ltags lastpos parent)
13311 (save-excursion
13312 (save-restriction
13313 (widen)
13314 (goto-char (or pos (point)))
13315 (save-match-data
13316 (catch 'done
13317 (condition-case nil
13318 (progn
13319 (org-back-to-heading t)
13320 (while (not (equal lastpos (point)))
13321 (setq lastpos (point))
13322 (when (looking-at
13323 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
13324 (setq ltags (org-split-string
13325 (org-match-string-no-properties 1) ":"))
13326 (when parent
13327 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
13328 (setq tags (append
13329 (if parent
13330 (org-remove-uninherited-tags ltags)
13331 ltags)
13332 tags)))
13333 (or org-use-tag-inheritance (throw 'done t))
13334 (if local (throw 'done t))
13335 (or (org-up-heading-safe) (error nil))
13336 (setq parent t)))
13337 (error nil)))))
13338 (if local
13339 tags
13340 (append (org-remove-uninherited-tags org-file-tags) tags))))))
13342 (defun org-add-prop-inherited (s)
13343 (add-text-properties 0 (length s) '(inherited t) s)
13346 (defun org-toggle-tag (tag &optional onoff)
13347 "Toggle the tag TAG for the current line.
13348 If ONOFF is `on' or `off', don't toggle but set to this state."
13349 (let (res current)
13350 (save-excursion
13351 (org-back-to-heading t)
13352 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
13353 (point-at-eol) t)
13354 (progn
13355 (setq current (match-string 1))
13356 (replace-match ""))
13357 (setq current ""))
13358 (setq current (nreverse (org-split-string current ":")))
13359 (cond
13360 ((eq onoff 'on)
13361 (setq res t)
13362 (or (member tag current) (push tag current)))
13363 ((eq onoff 'off)
13364 (or (not (member tag current)) (setq current (delete tag current))))
13365 (t (if (member tag current)
13366 (setq current (delete tag current))
13367 (setq res t)
13368 (push tag current))))
13369 (end-of-line 1)
13370 (if current
13371 (progn
13372 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
13373 (org-set-tags nil t))
13374 (delete-horizontal-space))
13375 (run-hooks 'org-after-tags-change-hook))
13376 res))
13378 (defun org-align-tags-here (to-col)
13379 ;; Assumes that this is a headline
13380 (let ((pos (point)) (col (current-column)) ncol tags-l p)
13381 (beginning-of-line 1)
13382 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13383 (< pos (match-beginning 2)))
13384 (progn
13385 (setq tags-l (- (match-end 2) (match-beginning 2)))
13386 (goto-char (match-beginning 1))
13387 (insert " ")
13388 (delete-region (point) (1+ (match-beginning 2)))
13389 (setq ncol (max (current-column)
13390 (1+ col)
13391 (if (> to-col 0)
13392 to-col
13393 (- (abs to-col) tags-l))))
13394 (setq p (point))
13395 (insert (make-string (- ncol (current-column)) ?\ ))
13396 (setq ncol (current-column))
13397 (when indent-tabs-mode (tabify p (point-at-eol)))
13398 (org-move-to-column (min ncol col) t))
13399 (goto-char pos))))
13401 (defun org-set-tags-command (&optional arg just-align)
13402 "Call the set-tags command for the current entry."
13403 (interactive "P")
13404 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
13405 (org-set-tags arg just-align)
13406 (save-excursion
13407 (org-back-to-heading t)
13408 (org-set-tags arg just-align))))
13410 (defun org-set-tags-to (data)
13411 "Set the tags of the current entry to DATA, replacing the current tags.
13412 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
13413 If DATA is nil or the empty string, any tags will be removed."
13414 (interactive "sTags: ")
13415 (setq data
13416 (cond
13417 ((eq data nil) "")
13418 ((equal data "") "")
13419 ((stringp data)
13420 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
13421 ":"))
13422 ((listp data)
13423 (concat ":" (mapconcat 'identity data ":") ":"))
13424 (t nil)))
13425 (when data
13426 (save-excursion
13427 (org-back-to-heading t)
13428 (when (looking-at org-complex-heading-regexp)
13429 (if (match-end 5)
13430 (progn
13431 (goto-char (match-beginning 5))
13432 (insert data)
13433 (delete-region (point) (point-at-eol))
13434 (org-set-tags nil 'align))
13435 (goto-char (point-at-eol))
13436 (insert " " data)
13437 (org-set-tags nil 'align)))
13438 (beginning-of-line 1)
13439 (if (looking-at ".*?\\([ \t]+\\)$")
13440 (delete-region (match-beginning 1) (match-end 1))))))
13442 (defun org-align-all-tags ()
13443 "Align the tags i all headings."
13444 (interactive)
13445 (save-excursion
13446 (or (ignore-errors (org-back-to-heading t))
13447 (outline-next-heading))
13448 (if (org-at-heading-p)
13449 (org-set-tags t)
13450 (message "No headings"))))
13452 (defvar org-indent-indentation-per-level)
13453 (defun org-set-tags (&optional arg just-align)
13454 "Set the tags for the current headline.
13455 With prefix ARG, realign all tags in headings in the current buffer."
13456 (interactive "P")
13457 (let* ((re org-outline-regexp-bol)
13458 (current (unless arg (org-get-tags-string)))
13459 (col (current-column))
13460 (org-setting-tags t)
13461 table current-tags inherited-tags ; computed below when needed
13462 tags p0 c0 c1 rpl di tc level)
13463 (if arg
13464 (save-excursion
13465 (goto-char (point-min))
13466 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
13467 (while (re-search-forward re nil t)
13468 (org-set-tags nil t)
13469 (end-of-line 1)))
13470 (message "All tags realigned to column %d" org-tags-column))
13471 (if just-align
13472 (setq tags current)
13473 ;; Get a new set of tags from the user
13474 (save-excursion
13475 (setq table (append org-tag-persistent-alist
13476 (or org-tag-alist (org-get-buffer-tags))
13477 (and
13478 org-complete-tags-always-offer-all-agenda-tags
13479 (org-global-tags-completion-table
13480 (org-agenda-files))))
13481 org-last-tags-completion-table table
13482 current-tags (org-split-string current ":")
13483 inherited-tags (nreverse
13484 (nthcdr (length current-tags)
13485 (nreverse (org-get-tags-at))))
13486 tags
13487 (if (or (eq t org-use-fast-tag-selection)
13488 (and org-use-fast-tag-selection
13489 (delq nil (mapcar 'cdr table))))
13490 (org-fast-tag-selection
13491 current-tags inherited-tags table
13492 (if org-fast-tag-selection-include-todo
13493 org-todo-key-alist))
13494 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
13495 (org-trim
13496 (org-icompleting-read "Tags: "
13497 'org-tags-completion-function
13498 nil nil current 'org-tags-history))))))
13499 (while (string-match "[-+&]+" tags)
13500 ;; No boolean logic, just a list
13501 (setq tags (replace-match ":" t t tags))))
13503 (setq tags (replace-regexp-in-string "[,]" ":" tags))
13505 (if org-tags-sort-function
13506 (setq tags (mapconcat 'identity
13507 (sort (org-split-string
13508 tags (org-re "[^[:alnum:]_@#%]+"))
13509 org-tags-sort-function) ":")))
13511 (if (string-match "\\`[\t ]*\\'" tags)
13512 (setq tags "")
13513 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
13514 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
13516 ;; Insert new tags at the correct column
13517 (beginning-of-line 1)
13518 (setq level (or (and (looking-at org-outline-regexp)
13519 (- (match-end 0) (point) 1))
13521 (cond
13522 ((and (equal current "") (equal tags "")))
13523 ((re-search-forward
13524 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
13525 (point-at-eol) t)
13526 (if (equal tags "")
13527 (setq rpl "")
13528 (goto-char (match-beginning 0))
13529 (setq c0 (current-column)
13530 ;; compute offset for the case of org-indent-mode active
13531 di (if org-indent-mode
13532 (* (1- org-indent-indentation-per-level) (1- level))
13534 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
13535 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
13536 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
13537 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
13538 (replace-match rpl t t)
13539 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
13540 tags)
13541 (t (error "Tags alignment failed")))
13542 (org-move-to-column col)
13543 (unless just-align
13544 (run-hooks 'org-after-tags-change-hook)))))
13546 (defun org-change-tag-in-region (beg end tag off)
13547 "Add or remove TAG for each entry in the region.
13548 This works in the agenda, and also in an org-mode buffer."
13549 (interactive
13550 (list (region-beginning) (region-end)
13551 (let ((org-last-tags-completion-table
13552 (if (derived-mode-p 'org-mode)
13553 (org-get-buffer-tags)
13554 (org-global-tags-completion-table))))
13555 (org-icompleting-read
13556 "Tag: " 'org-tags-completion-function nil nil nil
13557 'org-tags-history))
13558 (progn
13559 (message "[s]et or [r]emove? ")
13560 (equal (read-char-exclusive) ?r))))
13561 (if (fboundp 'deactivate-mark) (deactivate-mark))
13562 (let ((agendap (equal major-mode 'org-agenda-mode))
13563 l1 l2 m buf pos newhead (cnt 0))
13564 (goto-char end)
13565 (setq l2 (1- (org-current-line)))
13566 (goto-char beg)
13567 (setq l1 (org-current-line))
13568 (loop for l from l1 to l2 do
13569 (org-goto-line l)
13570 (setq m (get-text-property (point) 'org-hd-marker))
13571 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
13572 (and agendap m))
13573 (setq buf (if agendap (marker-buffer m) (current-buffer))
13574 pos (if agendap m (point)))
13575 (with-current-buffer buf
13576 (save-excursion
13577 (save-restriction
13578 (goto-char pos)
13579 (setq cnt (1+ cnt))
13580 (org-toggle-tag tag (if off 'off 'on))
13581 (setq newhead (org-get-heading)))))
13582 (and agendap (org-agenda-change-all-lines newhead m))))
13583 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
13585 (defun org-tags-completion-function (string predicate &optional flag)
13586 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
13587 (confirm (lambda (x) (stringp (car x)))))
13588 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
13589 (setq s1 (match-string 1 string)
13590 s2 (match-string 2 string))
13591 (setq s1 "" s2 string))
13592 (cond
13593 ((eq flag nil)
13594 ;; try completion
13595 (setq rtn (try-completion s2 ctable confirm))
13596 (if (stringp rtn)
13597 (setq rtn
13598 (concat s1 s2 (substring rtn (length s2))
13599 (if (and org-add-colon-after-tag-completion
13600 (assoc rtn ctable))
13601 ":" ""))))
13602 rtn)
13603 ((eq flag t)
13604 ;; all-completions
13605 (all-completions s2 ctable confirm)
13607 ((eq flag 'lambda)
13608 ;; exact match?
13609 (assoc s2 ctable)))
13612 (defun org-fast-tag-insert (kwd tags face &optional end)
13613 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
13614 (insert (format "%-12s" (concat kwd ":"))
13615 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
13616 (or end "")))
13618 (defun org-fast-tag-show-exit (flag)
13619 (save-excursion
13620 (org-goto-line 3)
13621 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
13622 (replace-match ""))
13623 (when flag
13624 (end-of-line 1)
13625 (org-move-to-column (- (window-width) 19) t)
13626 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
13628 (defun org-set-current-tags-overlay (current prefix)
13629 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
13630 (if (featurep 'xemacs)
13631 (org-overlay-display org-tags-overlay (concat prefix s)
13632 'secondary-selection)
13633 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
13634 (org-overlay-display org-tags-overlay (concat prefix s)))))
13636 (defvar org-last-tag-selection-key nil)
13637 (defun org-fast-tag-selection (current inherited table &optional todo-table)
13638 "Fast tag selection with single keys.
13639 CURRENT is the current list of tags in the headline, INHERITED is the
13640 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
13641 possibly with grouping information. TODO-TABLE is a similar table with
13642 TODO keywords, should these have keys assigned to them.
13643 If the keys are nil, a-z are automatically assigned.
13644 Returns the new tags string, or nil to not change the current settings."
13645 (let* ((fulltable (append table todo-table))
13646 (maxlen (apply 'max (mapcar
13647 (lambda (x)
13648 (if (stringp (car x)) (string-width (car x)) 0))
13649 fulltable)))
13650 (buf (current-buffer))
13651 (expert (eq org-fast-tag-selection-single-key 'expert))
13652 (buffer-tags nil)
13653 (fwidth (+ maxlen 3 1 3))
13654 (ncol (/ (- (window-width) 4) fwidth))
13655 (i-face 'org-done)
13656 (c-face 'org-todo)
13657 tg cnt e c char c1 c2 ntable tbl rtn
13658 ov-start ov-end ov-prefix
13659 (exit-after-next org-fast-tag-selection-single-key)
13660 (done-keywords org-done-keywords)
13661 groups ingroup)
13662 (save-excursion
13663 (beginning-of-line 1)
13664 (if (looking-at
13665 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13666 (setq ov-start (match-beginning 1)
13667 ov-end (match-end 1)
13668 ov-prefix "")
13669 (setq ov-start (1- (point-at-eol))
13670 ov-end (1+ ov-start))
13671 (skip-chars-forward "^\n\r")
13672 (setq ov-prefix
13673 (concat
13674 (buffer-substring (1- (point)) (point))
13675 (if (> (current-column) org-tags-column)
13677 (make-string (- org-tags-column (current-column)) ?\ ))))))
13678 (move-overlay org-tags-overlay ov-start ov-end)
13679 (save-window-excursion
13680 (if expert
13681 (set-buffer (get-buffer-create " *Org tags*"))
13682 (delete-other-windows)
13683 (split-window-vertically)
13684 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
13685 (erase-buffer)
13686 (org-set-local 'org-done-keywords done-keywords)
13687 (org-fast-tag-insert "Inherited" inherited i-face "\n")
13688 (org-fast-tag-insert "Current" current c-face "\n\n")
13689 (org-fast-tag-show-exit exit-after-next)
13690 (org-set-current-tags-overlay current ov-prefix)
13691 (setq tbl fulltable char ?a cnt 0)
13692 (while (setq e (pop tbl))
13693 (cond
13694 ((equal (car e) :startgroup)
13695 (push '() groups) (setq ingroup t)
13696 (when (not (= cnt 0))
13697 (setq cnt 0)
13698 (insert "\n"))
13699 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
13700 ((equal (car e) :endgroup)
13701 (setq ingroup nil cnt 0)
13702 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
13703 ((equal e '(:newline))
13704 (when (not (= cnt 0))
13705 (setq cnt 0)
13706 (insert "\n")
13707 (setq e (car tbl))
13708 (while (equal (car tbl) '(:newline))
13709 (insert "\n")
13710 (setq tbl (cdr tbl)))))
13712 (setq tg (copy-sequence (car e)) c2 nil)
13713 (if (cdr e)
13714 (setq c (cdr e))
13715 ;; automatically assign a character.
13716 (setq c1 (string-to-char
13717 (downcase (substring
13718 tg (if (= (string-to-char tg) ?@) 1 0)))))
13719 (if (or (rassoc c1 ntable) (rassoc c1 table))
13720 (while (or (rassoc char ntable) (rassoc char table))
13721 (setq char (1+ char)))
13722 (setq c2 c1))
13723 (setq c (or c2 char)))
13724 (if ingroup (push tg (car groups)))
13725 (setq tg (org-add-props tg nil 'face
13726 (cond
13727 ((not (assoc tg table))
13728 (org-get-todo-face tg))
13729 ((member tg current) c-face)
13730 ((member tg inherited) i-face)
13731 (t nil))))
13732 (if (and (= cnt 0) (not ingroup)) (insert " "))
13733 (insert "[" c "] " tg (make-string
13734 (- fwidth 4 (length tg)) ?\ ))
13735 (push (cons tg c) ntable)
13736 (when (= (setq cnt (1+ cnt)) ncol)
13737 (insert "\n")
13738 (if ingroup (insert " "))
13739 (setq cnt 0)))))
13740 (setq ntable (nreverse ntable))
13741 (insert "\n")
13742 (goto-char (point-min))
13743 (if (not expert) (org-fit-window-to-buffer))
13744 (setq rtn
13745 (catch 'exit
13746 (while t
13747 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
13748 (if (not groups) "no " "")
13749 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
13750 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13751 (setq org-last-tag-selection-key c)
13752 (cond
13753 ((= c ?\r) (throw 'exit t))
13754 ((= c ?!)
13755 (setq groups (not groups))
13756 (goto-char (point-min))
13757 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
13758 ((= c ?\C-c)
13759 (if (not expert)
13760 (org-fast-tag-show-exit
13761 (setq exit-after-next (not exit-after-next)))
13762 (setq expert nil)
13763 (delete-other-windows)
13764 (set-window-buffer (split-window-vertically) " *Org tags*")
13765 (org-switch-to-buffer-other-window " *Org tags*")
13766 (org-fit-window-to-buffer)))
13767 ((or (= c ?\C-g)
13768 (and (= c ?q) (not (rassoc c ntable))))
13769 (org-detach-overlay org-tags-overlay)
13770 (setq quit-flag t))
13771 ((= c ?\ )
13772 (setq current nil)
13773 (if exit-after-next (setq exit-after-next 'now)))
13774 ((= c ?\t)
13775 (condition-case nil
13776 (setq tg (org-icompleting-read
13777 "Tag: "
13778 (or buffer-tags
13779 (with-current-buffer buf
13780 (org-get-buffer-tags)))))
13781 (quit (setq tg "")))
13782 (when (string-match "\\S-" tg)
13783 (add-to-list 'buffer-tags (list tg))
13784 (if (member tg current)
13785 (setq current (delete tg current))
13786 (push tg current)))
13787 (if exit-after-next (setq exit-after-next 'now)))
13788 ((setq e (rassoc c todo-table) tg (car e))
13789 (with-current-buffer buf
13790 (save-excursion (org-todo tg)))
13791 (if exit-after-next (setq exit-after-next 'now)))
13792 ((setq e (rassoc c ntable) tg (car e))
13793 (if (member tg current)
13794 (setq current (delete tg current))
13795 (loop for g in groups do
13796 (if (member tg g)
13797 (mapc (lambda (x)
13798 (setq current (delete x current)))
13799 g)))
13800 (push tg current))
13801 (if exit-after-next (setq exit-after-next 'now))))
13803 ;; Create a sorted list
13804 (setq current
13805 (sort current
13806 (lambda (a b)
13807 (assoc b (cdr (memq (assoc a ntable) ntable))))))
13808 (if (eq exit-after-next 'now) (throw 'exit t))
13809 (goto-char (point-min))
13810 (beginning-of-line 2)
13811 (delete-region (point) (point-at-eol))
13812 (org-fast-tag-insert "Current" current c-face)
13813 (org-set-current-tags-overlay current ov-prefix)
13814 (while (re-search-forward
13815 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
13816 (setq tg (match-string 1))
13817 (add-text-properties
13818 (match-beginning 1) (match-end 1)
13819 (list 'face
13820 (cond
13821 ((member tg current) c-face)
13822 ((member tg inherited) i-face)
13823 (t (get-text-property (match-beginning 1) 'face))))))
13824 (goto-char (point-min)))))
13825 (org-detach-overlay org-tags-overlay)
13826 (if rtn
13827 (mapconcat 'identity current ":")
13828 nil))))
13830 (defun org-get-tags-string ()
13831 "Get the TAGS string in the current headline."
13832 (unless (org-at-heading-p t)
13833 (error "Not on a heading"))
13834 (save-excursion
13835 (beginning-of-line 1)
13836 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13837 (org-match-string-no-properties 1)
13838 "")))
13840 (defun org-get-tags ()
13841 "Get the list of tags specified in the current headline."
13842 (org-split-string (org-get-tags-string) ":"))
13844 (defun org-get-buffer-tags ()
13845 "Get a table of all tags used in the buffer, for completion."
13846 (let (tags)
13847 (save-excursion
13848 (goto-char (point-min))
13849 (while (re-search-forward
13850 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
13851 (when (equal (char-after (point-at-bol 0)) ?*)
13852 (mapc (lambda (x) (add-to-list 'tags x))
13853 (org-split-string (org-match-string-no-properties 1) ":")))))
13854 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
13855 (mapcar 'list tags)))
13857 ;;;; The mapping API
13859 ;;;###autoload
13860 (defun org-map-entries (func &optional match scope &rest skip)
13861 "Call FUNC at each headline selected by MATCH in SCOPE.
13863 FUNC is a function or a lisp form. The function will be called without
13864 arguments, with the cursor positioned at the beginning of the headline.
13865 The return values of all calls to the function will be collected and
13866 returned as a list.
13868 The call to FUNC will be wrapped into a save-excursion form, so FUNC
13869 does not need to preserve point. After evaluation, the cursor will be
13870 moved to the end of the line (presumably of the headline of the
13871 processed entry) and search continues from there. Under some
13872 circumstances, this may not produce the wanted results. For example,
13873 if you have removed (e.g. archived) the current (sub)tree it could
13874 mean that the next entry will be skipped entirely. In such cases, you
13875 can specify the position from where search should continue by making
13876 FUNC set the variable `org-map-continue-from' to the desired buffer
13877 position.
13879 MATCH is a tags/property/todo match as it is used in the agenda tags view.
13880 Only headlines that are matched by this query will be considered during
13881 the iteration. When MATCH is nil or t, all headlines will be
13882 visited by the iteration.
13884 SCOPE determines the scope of this command. It can be any of:
13886 nil The current buffer, respecting the restriction if any
13887 tree The subtree started with the entry at point
13888 region The entries within the active region, if any
13889 region-start-level
13890 The entries within the active region, but only those at
13891 the same level than the first one.
13892 file The current buffer, without restriction
13893 file-with-archives
13894 The current buffer, and any archives associated with it
13895 agenda All agenda files
13896 agenda-with-archives
13897 All agenda files with any archive files associated with them
13898 \(file1 file2 ...)
13899 If this is a list, all files in the list will be scanned
13901 The remaining args are treated as settings for the skipping facilities of
13902 the scanner. The following items can be given here:
13904 archive skip trees with the archive tag.
13905 comment skip trees with the COMMENT keyword
13906 function or Emacs Lisp form:
13907 will be used as value for `org-agenda-skip-function', so whenever
13908 the function returns t, FUNC will not be called for that
13909 entry and search will continue from the point where the
13910 function leaves it.
13912 If your function needs to retrieve the tags including inherited tags
13913 at the *current* entry, you can use the value of the variable
13914 `org-scanner-tags' which will be much faster than getting the value
13915 with `org-get-tags-at'. If your function gets properties with
13916 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
13917 to t around the call to `org-entry-properties' to get the same speedup.
13918 Note that if your function moves around to retrieve tags and properties at
13919 a *different* entry, you cannot use these techniques."
13920 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
13921 (not (org-region-active-p)))
13922 (let* ((org-agenda-archives-mode nil) ; just to make sure
13923 (org-agenda-skip-archived-trees (memq 'archive skip))
13924 (org-agenda-skip-comment-trees (memq 'comment skip))
13925 (org-agenda-skip-function
13926 (car (org-delete-all '(comment archive) skip)))
13927 (org-tags-match-list-sublevels t)
13928 (start-level (eq scope 'region-start-level))
13929 matcher file res
13930 org-todo-keywords-for-agenda
13931 org-done-keywords-for-agenda
13932 org-todo-keyword-alist-for-agenda
13933 org-drawers-for-agenda
13934 org-tag-alist-for-agenda
13935 todo-only)
13937 (cond
13938 ((eq match t) (setq matcher t))
13939 ((eq match nil) (setq matcher t))
13940 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
13942 (save-excursion
13943 (save-restriction
13944 (cond ((eq scope 'tree)
13945 (org-back-to-heading t)
13946 (org-narrow-to-subtree)
13947 (setq scope nil))
13948 ((and (or (eq scope 'region) (eq scope 'region-start-level))
13949 (org-region-active-p))
13950 ;; If needed, set start-level to a string like "2"
13951 (when start-level
13952 (save-excursion
13953 (goto-char (region-beginning))
13954 (unless (org-at-heading-p) (outline-next-heading))
13955 (setq start-level (org-current-level))))
13956 (narrow-to-region (region-beginning)
13957 (save-excursion
13958 (goto-char (region-end))
13959 (unless (and (bolp) (org-at-heading-p))
13960 (outline-next-heading))
13961 (point)))
13962 (setq scope nil)))
13964 (if (not scope)
13965 (progn
13966 (org-prepare-agenda-buffers
13967 (list (buffer-file-name (current-buffer))))
13968 (setq res (org-scan-tags func matcher todo-only start-level)))
13969 ;; Get the right scope
13970 (cond
13971 ((and scope (listp scope) (symbolp (car scope)))
13972 (setq scope (eval scope)))
13973 ((eq scope 'agenda)
13974 (setq scope (org-agenda-files t)))
13975 ((eq scope 'agenda-with-archives)
13976 (setq scope (org-agenda-files t))
13977 (setq scope (org-add-archive-files scope)))
13978 ((eq scope 'file)
13979 (setq scope (list (buffer-file-name))))
13980 ((eq scope 'file-with-archives)
13981 (setq scope (org-add-archive-files (list (buffer-file-name))))))
13982 (org-prepare-agenda-buffers scope)
13983 (while (setq file (pop scope))
13984 (with-current-buffer (org-find-base-buffer-visiting file)
13985 (save-excursion
13986 (save-restriction
13987 (widen)
13988 (goto-char (point-min))
13989 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
13990 res)))
13992 ;;;; Properties
13994 ;;; Setting and retrieving properties
13996 (defconst org-special-properties
13997 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
13998 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM")
13999 "The special properties valid in Org-mode.
14001 These are properties that are not defined in the property drawer,
14002 but in some other way.")
14004 (defconst org-default-properties
14005 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
14006 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
14007 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
14008 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
14009 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
14010 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
14011 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
14012 "Some properties that are used by Org-mode for various purposes.
14013 Being in this list makes sure that they are offered for completion.")
14015 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
14016 "Regular expression matching the first line of a property drawer.")
14018 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
14019 "Regular expression matching the last line of a property drawer.")
14021 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
14022 "Regular expression matching the first line of a property drawer.")
14024 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
14025 "Regular expression matching the first line of a property drawer.")
14027 (defconst org-property-drawer-re
14028 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
14029 org-property-end-re "\\)\n?")
14030 "Matches an entire property drawer.")
14032 (defconst org-clock-drawer-re
14033 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
14034 org-property-end-re "\\)\n?")
14035 "Matches an entire clock drawer.")
14037 (defsubst org-re-property (property)
14038 "Return a regexp matching PROPERTY.
14039 Match group 1 will be set to the value "
14040 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
14042 (defun org-property-action ()
14043 "Do an action on properties."
14044 (interactive)
14045 (let (c)
14046 (org-at-property-p)
14047 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14048 (setq c (read-char-exclusive))
14049 (cond
14050 ((equal c ?s)
14051 (call-interactively 'org-set-property))
14052 ((equal c ?d)
14053 (call-interactively 'org-delete-property))
14054 ((equal c ?D)
14055 (call-interactively 'org-delete-property-globally))
14056 ((equal c ?c)
14057 (call-interactively 'org-compute-property-at-point))
14058 (t (error "No such property action %c" c)))))
14060 (defun org-set-effort (&optional value)
14061 "Set the effort property of the current entry.
14062 With numerical prefix arg, use the nth allowed value, 0 stands for the 10th
14063 allowed value."
14064 (interactive "P")
14065 (if (equal value 0) (setq value 10))
14066 (let* ((completion-ignore-case t)
14067 (prop org-effort-property)
14068 (cur (org-entry-get nil prop))
14069 (allowed (org-property-get-allowed-values nil prop 'table))
14070 (existing (mapcar 'list (org-property-values prop)))
14072 (val (cond
14073 ((stringp value) value)
14074 ((and allowed (integerp value))
14075 (or (car (nth (1- value) allowed))
14076 (car (org-last allowed))))
14077 (allowed
14078 (message "Select 1-9,0, [RET%s]: %s"
14079 (if cur (concat "=" cur) "")
14080 (mapconcat 'car allowed " "))
14081 (setq rpl (read-char-exclusive))
14082 (if (equal rpl ?\r)
14084 (setq rpl (- rpl ?0))
14085 (if (equal rpl 0) (setq rpl 10))
14086 (if (and (> rpl 0) (<= rpl (length allowed)))
14087 (car (nth (1- rpl) allowed))
14088 (org-completing-read "Effort: " allowed nil))))
14090 (let (org-completion-use-ido org-completion-use-iswitchb)
14091 (org-completing-read
14092 (concat "Effort " (if (and cur (string-match "\\S-" cur))
14093 (concat "[" cur "]") "")
14094 ": ")
14095 existing nil nil "" nil cur))))))
14096 (unless (equal (org-entry-get nil prop) val)
14097 (org-entry-put nil prop val))
14098 (message "%s is now %s" prop val)))
14100 (defun org-at-property-p ()
14101 "Is cursor inside a property drawer?"
14102 (save-excursion
14103 (beginning-of-line 1)
14104 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
14105 (save-match-data ;; Used by calling procedures
14106 (let ((p (point))
14107 (range (unless (org-before-first-heading-p)
14108 (org-get-property-block))))
14109 (and range (<= (car range) p) (< p (cdr range))))))))
14111 (defun org-get-property-block (&optional beg end force)
14112 "Return the (beg . end) range of the body of the property drawer.
14113 BEG and END can be beginning and end of subtree, if not given
14114 they will be found.
14115 If the drawer does not exist and FORCE is non-nil, create the drawer."
14116 (catch 'exit
14117 (save-excursion
14118 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
14119 (end (or end (progn (outline-next-heading) (point)))))
14120 (goto-char beg)
14121 (if (re-search-forward org-property-start-re end t)
14122 (setq beg (1+ (match-end 0)))
14123 (if force
14124 (save-excursion
14125 (org-insert-property-drawer)
14126 (setq end (progn (outline-next-heading) (point))))
14127 (throw 'exit nil))
14128 (goto-char beg)
14129 (if (re-search-forward org-property-start-re end t)
14130 (setq beg (1+ (match-end 0)))))
14131 (if (re-search-forward org-property-end-re end t)
14132 (setq end (match-beginning 0))
14133 (or force (throw 'exit nil))
14134 (goto-char beg)
14135 (setq end beg)
14136 (org-indent-line-function)
14137 (insert ":END:\n"))
14138 (cons beg end)))))
14140 (defun org-entry-properties (&optional pom which specific)
14141 "Get all properties of the entry at point-or-marker POM.
14142 This includes the TODO keyword, the tags, time strings for deadline,
14143 scheduled, and clocking, and any additional properties defined in the
14144 entry. The return value is an alist, keys may occur multiple times
14145 if the property key was used several times.
14146 POM may also be nil, in which case the current entry is used.
14147 If WHICH is nil or `all', get all properties. If WHICH is
14148 `special' or `standard', only get that subclass. If WHICH
14149 is a string only get exactly this property. SPECIFIC can be a string, the
14150 specific property we are interested in. Specifying it can speed
14151 things up because then unnecessary parsing is avoided."
14152 (setq which (or which 'all))
14153 (org-with-point-at pom
14154 (let ((clockstr (substring org-clock-string 0 -1))
14155 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
14156 (case-fold-search nil)
14157 beg end range props sum-props key key1 value string clocksum)
14158 (save-excursion
14159 (when (condition-case nil
14160 (and (derived-mode-p 'org-mode) (org-back-to-heading t))
14161 (error nil))
14162 (setq beg (point))
14163 (setq sum-props (get-text-property (point) 'org-summaries))
14164 (setq clocksum (get-text-property (point) :org-clock-minutes))
14165 (outline-next-heading)
14166 (setq end (point))
14167 (when (memq which '(all special))
14168 ;; Get the special properties, like TODO and tags
14169 (goto-char beg)
14170 (when (and (or (not specific) (string= specific "TODO"))
14171 (looking-at org-todo-line-regexp) (match-end 2))
14172 (push (cons "TODO" (org-match-string-no-properties 2)) props))
14173 (when (and (or (not specific) (string= specific "PRIORITY"))
14174 (looking-at org-priority-regexp))
14175 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
14176 (when (or (not specific) (string= specific "FILE"))
14177 (push (cons "FILE" buffer-file-name) props))
14178 (when (and (or (not specific) (string= specific "TAGS"))
14179 (setq value (org-get-tags-string))
14180 (string-match "\\S-" value))
14181 (push (cons "TAGS" value) props))
14182 (when (and (or (not specific) (string= specific "ALLTAGS"))
14183 (setq value (org-get-tags-at)))
14184 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
14185 ":"))
14186 props))
14187 (when (or (not specific) (string= specific "BLOCKED"))
14188 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
14189 (when (or (not specific)
14190 (member specific
14191 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
14192 "TIMESTAMP" "TIMESTAMP_IA")))
14193 (catch 'match
14194 (while (re-search-forward org-maybe-keyword-time-regexp end t)
14195 (setq key (if (match-end 1)
14196 (substring (org-match-string-no-properties 1)
14197 0 -1))
14198 string (if (equal key clockstr)
14199 (org-no-properties
14200 (org-trim
14201 (buffer-substring
14202 (match-beginning 3) (goto-char
14203 (point-at-eol)))))
14204 (substring (org-match-string-no-properties 3)
14205 1 -1)))
14206 ;; Get the correct property name from the key. This is
14207 ;; necessary if the user has configured time keywords.
14208 (setq key1 (concat key ":"))
14209 (cond
14210 ((not key)
14211 (setq key
14212 (if (= (char-after (match-beginning 3)) ?\[)
14213 "TIMESTAMP_IA" "TIMESTAMP")))
14214 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
14215 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
14216 ((equal key1 org-closed-string) (setq key "CLOSED"))
14217 ((equal key1 org-clock-string) (setq key "CLOCK")))
14218 (if (and specific (equal key specific) (not (equal key "CLOCK")))
14219 (progn
14220 (push (cons key string) props)
14221 ;; no need to search further if match is found
14222 (throw 'match t))
14223 (when (or (equal key "CLOCK") (not (assoc key props)))
14224 (push (cons key string) props))))))
14227 (when (memq which '(all standard))
14228 ;; Get the standard properties, like :PROP: ...
14229 (setq range (org-get-property-block beg end))
14230 (when range
14231 (goto-char (car range))
14232 (while (re-search-forward
14233 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
14234 (cdr range) t)
14235 (setq key (org-match-string-no-properties 1)
14236 value (org-trim (or (org-match-string-no-properties 2) "")))
14237 (unless (member key excluded)
14238 (push (cons key (or value "")) props)))))
14239 (if clocksum
14240 (push (cons "CLOCKSUM"
14241 (org-columns-number-to-string (/ (float clocksum) 60.)
14242 'add_times))
14243 props))
14244 (unless (assoc "CATEGORY" props)
14245 (push (cons "CATEGORY" (org-get-category)) props))
14246 (append sum-props (nreverse props)))))))
14248 (defun org-entry-get (pom property &optional inherit literal-nil)
14249 "Get value of PROPERTY for entry at point-or-marker POM.
14250 If INHERIT is non-nil and the entry does not have the property,
14251 then also check higher levels of the hierarchy.
14252 If INHERIT is the symbol `selective', use inheritance only if the setting
14253 in `org-use-property-inheritance' selects PROPERTY for inheritance.
14254 If the property is present but empty, the return value is the empty string.
14255 If the property is not present at all, nil is returned.
14257 If LITERAL-NIL is set, return the string value \"nil\" as a string,
14258 do not interpret it as the list atom nil. This is used for inheritance
14259 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
14260 (org-with-point-at pom
14261 (if (and inherit (if (eq inherit 'selective)
14262 (org-property-inherit-p property)
14264 (org-entry-get-with-inheritance property literal-nil)
14265 (if (member property org-special-properties)
14266 ;; We need a special property. Use `org-entry-properties' to
14267 ;; retrieve it, but specify the wanted property
14268 (cdr (assoc property (org-entry-properties nil 'special property)))
14269 (let ((range (unless (org-before-first-heading-p)
14270 (org-get-property-block)))
14271 (props (list (or (assoc property org-file-properties)
14272 (assoc property org-global-properties)
14273 (assoc property org-global-properties-fixed))))
14274 val)
14275 (flet ((ap (key)
14276 (when (re-search-forward
14277 (org-re-property key) (cdr range) t)
14278 (setq props
14279 (org-update-property-plist
14281 (if (match-end 1)
14282 (org-match-string-no-properties 1) "")
14283 props)))))
14284 (when (and range (goto-char (car range)))
14285 (ap property)
14286 (goto-char (car range))
14287 (while (ap (concat property "+")))
14288 (setq val (cdr (assoc property props)))
14289 (when val (if literal-nil val (org-not-nil val))))))))))
14291 (defun org-property-or-variable-value (var &optional inherit)
14292 "Check if there is a property fixing the value of VAR.
14293 If yes, return this value. If not, return the current value of the variable."
14294 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14295 (if (and prop (stringp prop) (string-match "\\S-" prop))
14296 (read prop)
14297 (symbol-value var))))
14299 (defun org-entry-delete (pom property)
14300 "Delete the property PROPERTY from entry at point-or-marker POM."
14301 (org-with-point-at pom
14302 (if (member property org-special-properties)
14303 nil ; cannot delete these properties.
14304 (let ((range (org-get-property-block)))
14305 (if (and range
14306 (goto-char (car range))
14307 (re-search-forward
14308 (org-re-property property)
14309 (cdr range) t))
14310 (progn
14311 (delete-region (match-beginning 0) (1+ (point-at-eol)))
14313 nil)))))
14315 ;; Multi-values properties are properties that contain multiple values
14316 ;; These values are assumed to be single words, separated by whitespace.
14317 (defun org-entry-add-to-multivalued-property (pom property value)
14318 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
14319 (let* ((old (org-entry-get pom property))
14320 (values (and old (org-split-string old "[ \t]"))))
14321 (setq value (org-entry-protect-space value))
14322 (unless (member value values)
14323 (setq values (cons value values))
14324 (org-entry-put pom property
14325 (mapconcat 'identity values " ")))))
14327 (defun org-entry-remove-from-multivalued-property (pom property value)
14328 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
14329 (let* ((old (org-entry-get pom property))
14330 (values (and old (org-split-string old "[ \t]"))))
14331 (setq value (org-entry-protect-space value))
14332 (when (member value values)
14333 (setq values (delete value values))
14334 (org-entry-put pom property
14335 (mapconcat 'identity values " ")))))
14337 (defun org-entry-member-in-multivalued-property (pom property value)
14338 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
14339 (let* ((old (org-entry-get pom property))
14340 (values (and old (org-split-string old "[ \t]"))))
14341 (setq value (org-entry-protect-space value))
14342 (member value values)))
14344 (defun org-entry-get-multivalued-property (pom property)
14345 "Return a list of values in a multivalued property."
14346 (let* ((value (org-entry-get pom property))
14347 (values (and value (org-split-string value "[ \t]"))))
14348 (mapcar 'org-entry-restore-space values)))
14350 (defun org-entry-put-multivalued-property (pom property &rest values)
14351 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
14352 VALUES should be a list of strings. Spaces will be protected."
14353 (org-entry-put pom property
14354 (mapconcat 'org-entry-protect-space values " "))
14355 (let* ((value (org-entry-get pom property))
14356 (values (and value (org-split-string value "[ \t]"))))
14357 (mapcar 'org-entry-restore-space values)))
14359 (defun org-entry-protect-space (s)
14360 "Protect spaces and newline in string S."
14361 (while (string-match " " s)
14362 (setq s (replace-match "%20" t t s)))
14363 (while (string-match "\n" s)
14364 (setq s (replace-match "%0A" t t s)))
14367 (defun org-entry-restore-space (s)
14368 "Restore spaces and newline in string S."
14369 (while (string-match "%20" s)
14370 (setq s (replace-match " " t t s)))
14371 (while (string-match "%0A" s)
14372 (setq s (replace-match "\n" t t s)))
14375 (defvar org-entry-property-inherited-from (make-marker)
14376 "Marker pointing to the entry from where a property was inherited.
14377 Each call to `org-entry-get-with-inheritance' will set this marker to the
14378 location of the entry where the inheritance search matched. If there was
14379 no match, the marker will point nowhere.
14380 Note that also `org-entry-get' calls this function, if the INHERIT flag
14381 is set.")
14383 (defun org-entry-get-with-inheritance (property &optional literal-nil)
14384 "Get entry property, and search higher levels if not present.
14385 The search will stop at the first ancestor which has the property defined.
14386 If the value found is \"nil\", return nil to show that the property
14387 should be considered as undefined (this is the meaning of nil here).
14388 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
14389 (move-marker org-entry-property-inherited-from nil)
14390 (let (tmp)
14391 (unless (org-before-first-heading-p)
14392 (save-excursion
14393 (save-restriction
14394 (widen)
14395 (catch 'ex
14396 (while t
14397 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
14398 (org-back-to-heading t)
14399 (move-marker org-entry-property-inherited-from (point))
14400 (throw 'ex tmp))
14401 (or (org-up-heading-safe) (throw 'ex nil)))))))
14402 (setq tmp (or tmp
14403 (cdr (assoc property org-file-properties))
14404 (cdr (assoc property org-global-properties))
14405 (cdr (assoc property org-global-properties-fixed))))
14406 (if literal-nil tmp (org-not-nil tmp))))
14408 (defvar org-property-changed-functions nil
14409 "Hook called when the value of a property has changed.
14410 Each hook function should accept two arguments, the name of the property
14411 and the new value.")
14413 (defun org-entry-put (pom property value)
14414 "Set PROPERTY to VALUE for entry at point-or-marker POM."
14415 (org-with-point-at pom
14416 (org-back-to-heading t)
14417 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
14418 range)
14419 (cond
14420 ((equal property "TODO")
14421 (when (and (stringp value) (string-match "\\S-" value)
14422 (not (member value org-todo-keywords-1)))
14423 (error "\"%s\" is not a valid TODO state" value))
14424 (if (or (not value)
14425 (not (string-match "\\S-" value)))
14426 (setq value 'none))
14427 (org-todo value)
14428 (org-set-tags nil 'align))
14429 ((equal property "PRIORITY")
14430 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
14431 (string-to-char value) ?\ ))
14432 (org-set-tags nil 'align))
14433 ((equal property "SCHEDULED")
14434 (if (re-search-forward org-scheduled-time-regexp end t)
14435 (cond
14436 ((eq value 'earlier) (org-timestamp-change -1 'day))
14437 ((eq value 'later) (org-timestamp-change 1 'day))
14438 (t (call-interactively 'org-schedule)))
14439 (call-interactively 'org-schedule)))
14440 ((equal property "DEADLINE")
14441 (if (re-search-forward org-deadline-time-regexp end t)
14442 (cond
14443 ((eq value 'earlier) (org-timestamp-change -1 'day))
14444 ((eq value 'later) (org-timestamp-change 1 'day))
14445 (t (call-interactively 'org-deadline)))
14446 (call-interactively 'org-deadline)))
14447 ((member property org-special-properties)
14448 (error "The %s property can not yet be set with `org-entry-put'"
14449 property))
14450 (t ; a non-special property
14451 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
14452 (setq range (org-get-property-block beg end 'force))
14453 (goto-char (car range))
14454 (if (re-search-forward
14455 (org-re-property property) (cdr range) t)
14456 (progn
14457 (delete-region (match-beginning 0) (match-end 0))
14458 (goto-char (match-beginning 0)))
14459 (goto-char (cdr range))
14460 (insert "\n")
14461 (backward-char 1)
14462 (org-indent-line-function))
14463 (insert ":" property ":")
14464 (and value (insert " " value))
14465 (org-indent-line-function)))))
14466 (run-hook-with-args 'org-property-changed-functions property value)))
14468 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
14469 "Get all property keys in the current buffer.
14470 With INCLUDE-SPECIALS, also list the special properties that reflect things
14471 like tags and TODO state.
14472 With INCLUDE-DEFAULTS, also include properties that has special meaning
14473 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
14474 and others.
14475 With INCLUDE-COLUMNS, also include property names given in COLUMN
14476 formats in the current buffer."
14477 (let (rtn range cfmt s p)
14478 (save-excursion
14479 (save-restriction
14480 (widen)
14481 (goto-char (point-min))
14482 (while (re-search-forward org-property-start-re nil t)
14483 (setq range (org-get-property-block))
14484 (goto-char (car range))
14485 (while (re-search-forward
14486 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
14487 (cdr range) t)
14488 (add-to-list 'rtn (org-match-string-no-properties 1)))
14489 (outline-next-heading))))
14491 (when include-specials
14492 (setq rtn (append org-special-properties rtn)))
14494 (when include-defaults
14495 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
14496 (add-to-list 'rtn org-effort-property))
14498 (when include-columns
14499 (save-excursion
14500 (save-restriction
14501 (widen)
14502 (goto-char (point-min))
14503 (while (re-search-forward
14504 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
14505 nil t)
14506 (setq cfmt (match-string 2) s 0)
14507 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
14508 cfmt s)
14509 (setq s (match-end 0)
14510 p (match-string 1 cfmt))
14511 (unless (or (equal p "ITEM")
14512 (member p org-special-properties))
14513 (add-to-list 'rtn (match-string 1 cfmt))))))))
14515 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
14517 (defun org-property-values (key)
14518 "Return a list of all values of property KEY in the current buffer."
14519 (save-excursion
14520 (save-restriction
14521 (widen)
14522 (goto-char (point-min))
14523 (let ((re (org-re-property key))
14524 values)
14525 (while (re-search-forward re nil t)
14526 (add-to-list 'values (org-trim (match-string 1))))
14527 (delete "" values)))))
14529 (defun org-insert-property-drawer ()
14530 "Insert a property drawer into the current entry."
14531 (org-back-to-heading t)
14532 (looking-at org-outline-regexp)
14533 (let ((indent (if org-adapt-indentation
14534 (- (match-end 0) (match-beginning 0))
14536 (beg (point))
14537 (re (concat "^[ \t]*" org-keyword-time-regexp))
14538 end hiddenp)
14539 (outline-next-heading)
14540 (setq end (point))
14541 (goto-char beg)
14542 (while (re-search-forward re end t))
14543 (setq hiddenp (outline-invisible-p))
14544 (end-of-line 1)
14545 (and (equal (char-after) ?\n) (forward-char 1))
14546 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
14547 (if (member (match-string 1) '("CLOCK:" ":END:"))
14548 ;; just skip this line
14549 (beginning-of-line 2)
14550 ;; Drawer start, find the end
14551 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
14552 (beginning-of-line 1)))
14553 (org-skip-over-state-notes)
14554 (skip-chars-backward " \t\n\r")
14555 (if (eq (char-before) ?*) (forward-char 1))
14556 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
14557 (beginning-of-line 0)
14558 (org-indent-to-column indent)
14559 (beginning-of-line 2)
14560 (org-indent-to-column indent)
14561 (beginning-of-line 0)
14562 (if hiddenp
14563 (save-excursion
14564 (org-back-to-heading t)
14565 (hide-entry))
14566 (org-flag-drawer t))))
14568 (defun org-insert-drawer (&optional arg drawer)
14569 "Insert a drawer at point.
14571 Optional argument DRAWER, when non-nil, is a string representing
14572 drawer's name. Otherwise, the user is prompted for a name.
14574 If a region is active, insert the drawer around that region
14575 instead.
14577 Point is left between drawer's boundaries."
14578 (interactive "P")
14579 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
14580 "LOGBOOK"))
14581 ;; SYSTEM-DRAWERS is a list of drawer names that are used
14582 ;; internally by Org. They are meant to be inserted
14583 ;; automatically.
14584 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
14585 ;; Remove system drawers from list. Note: For some reason,
14586 ;; `org-completing-read' ignores the predicate while
14587 ;; `completing-read' handles it fine.
14588 (drawer (if arg "PROPERTIES"
14589 (or drawer
14590 (completing-read
14591 "Drawer: " org-drawers
14592 (lambda (d) (not (member d system-drawers))))))))
14593 (cond
14594 ;; With C-u, fall back on `org-insert-property-drawer'
14595 (arg (org-insert-property-drawer))
14596 ;; With an active region, insert a drawer at point.
14597 ((not (org-region-active-p))
14598 (progn
14599 (unless (bolp) (insert "\n"))
14600 (insert (format ":%s:\n\n:END:\n" drawer))
14601 (forward-line -2)))
14602 ;; Otherwise, insert the drawer at point
14604 (let ((rbeg (region-beginning))
14605 (rend (copy-marker (region-end))))
14606 (unwind-protect
14607 (progn
14608 (goto-char rbeg)
14609 (beginning-of-line)
14610 (when (save-excursion
14611 (re-search-forward org-outline-regexp-bol rend t))
14612 (error "Drawers cannot contain headlines"))
14613 ;; Position point at the beginning of the first
14614 ;; non-blank line in region. Insert drawer's opening
14615 ;; there, then indent it.
14616 (org-skip-whitespace)
14617 (beginning-of-line)
14618 (insert ":" drawer ":\n")
14619 (forward-line -1)
14620 (indent-for-tab-command)
14621 ;; Move point to the beginning of the first blank line
14622 ;; after the last non-blank line in region. Insert
14623 ;; drawer's closing, then indent it.
14624 (goto-char rend)
14625 (skip-chars-backward " \r\t\n")
14626 (insert "\n:END:")
14627 (indent-for-tab-command)
14628 (unless (eolp) (insert "\n")))
14629 ;; Clear marker, whatever the outcome of insertion is.
14630 (set-marker rend nil)))))))
14632 (defvar org-property-set-functions-alist nil
14633 "Property set function alist.
14634 Each entry should have the following format:
14636 (PROPERTY . READ-FUNCTION)
14638 The read function will be called with the same argument as
14639 `org-completing-read'.")
14641 (defun org-set-property-function (property)
14642 "Get the function that should be used to set PROPERTY.
14643 This is computed according to `org-property-set-functions-alist'."
14644 (or (cdr (assoc property org-property-set-functions-alist))
14645 'org-completing-read))
14647 (defun org-read-property-value (property)
14648 "Read PROPERTY value from user."
14649 (let* ((completion-ignore-case t)
14650 (allowed (org-property-get-allowed-values nil property 'table))
14651 (cur (org-entry-get nil property))
14652 (prompt (concat property " value"
14653 (if (and cur (string-match "\\S-" cur))
14654 (concat " [" cur "]") "") ": "))
14655 (set-function (org-set-property-function property))
14656 (val (if allowed
14657 (funcall set-function prompt allowed nil
14658 (not (get-text-property 0 'org-unrestricted
14659 (caar allowed))))
14660 (let (org-completion-use-ido org-completion-use-iswitchb)
14661 (funcall set-function prompt
14662 (mapcar 'list (org-property-values property))
14663 nil nil "" nil cur)))))
14664 (if (equal val "")
14666 val)))
14668 (defvar org-last-set-property nil)
14669 (defun org-read-property-name ()
14670 "Read a property name."
14671 (let* ((completion-ignore-case t)
14672 (keys (org-buffer-property-keys nil t t))
14673 (default-prop (or (save-excursion
14674 (save-match-data
14675 (beginning-of-line)
14676 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
14677 (null (string= (match-string 1) "END"))
14678 (match-string 1))))
14679 org-last-set-property))
14680 (property (org-icompleting-read
14681 (concat "Property"
14682 (if default-prop (concat " [" default-prop "]") "")
14683 ": ")
14684 (mapcar 'list keys)
14685 nil nil nil nil
14686 default-prop
14688 (if (member property keys)
14689 property
14690 (or (cdr (assoc (downcase property)
14691 (mapcar (lambda (x) (cons (downcase x) x))
14692 keys)))
14693 property))))
14695 (defun org-set-property (property value)
14696 "In the current entry, set PROPERTY to VALUE.
14697 When called interactively, this will prompt for a property name, offering
14698 completion on existing and default properties. And then it will prompt
14699 for a value, offering completion either on allowed values (via an inherited
14700 xxx_ALL property) or on existing values in other instances of this property
14701 in the current file."
14702 (interactive (list nil nil))
14703 (let* ((property (or property (org-read-property-name)))
14704 (value (or value (org-read-property-value property)))
14705 (fn (assoc property org-properties-postprocess-alist)))
14706 (setq org-last-set-property property)
14707 ;; Possibly postprocess the inserted value:
14708 (when fn (setq value (funcall (cadr fn) value)))
14709 (unless (equal (org-entry-get nil property) value)
14710 (org-entry-put nil property value))))
14712 (defun org-delete-property (property)
14713 "In the current entry, delete PROPERTY."
14714 (interactive
14715 (let* ((completion-ignore-case t)
14716 (prop (org-icompleting-read "Property: "
14717 (org-entry-properties nil 'standard))))
14718 (list prop)))
14719 (message "Property %s %s" property
14720 (if (org-entry-delete nil property)
14721 "deleted"
14722 "was not present in the entry")))
14724 (defun org-delete-property-globally (property)
14725 "Remove PROPERTY globally, from all entries."
14726 (interactive
14727 (let* ((completion-ignore-case t)
14728 (prop (org-icompleting-read
14729 "Globally remove property: "
14730 (mapcar 'list (org-buffer-property-keys)))))
14731 (list prop)))
14732 (save-excursion
14733 (save-restriction
14734 (widen)
14735 (goto-char (point-min))
14736 (let ((cnt 0))
14737 (while (re-search-forward
14738 (org-re-property property)
14739 nil t)
14740 (setq cnt (1+ cnt))
14741 (delete-region (match-beginning 0) (1+ (point-at-eol))))
14742 (message "Property \"%s\" removed from %d entries" property cnt)))))
14744 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
14746 (defun org-compute-property-at-point ()
14747 "Compute the property at point.
14748 This looks for an enclosing column format, extracts the operator and
14749 then applies it to the property in the column format's scope."
14750 (interactive)
14751 (unless (org-at-property-p)
14752 (error "Not at a property"))
14753 (let ((prop (org-match-string-no-properties 2)))
14754 (org-columns-get-format-and-top-level)
14755 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
14756 (error "No operator defined for property %s" prop))
14757 (org-columns-compute prop)))
14759 (defvar org-property-allowed-value-functions nil
14760 "Hook for functions supplying allowed values for a specific property.
14761 The functions must take a single argument, the name of the property, and
14762 return a flat list of allowed values. If \":ETC\" is one of
14763 the values, this means that these values are intended as defaults for
14764 completion, but that other values should be allowed too.
14765 The functions must return nil if they are not responsible for this
14766 property.")
14768 (defun org-property-get-allowed-values (pom property &optional table)
14769 "Get allowed values for the property PROPERTY.
14770 When TABLE is non-nil, return an alist that can directly be used for
14771 completion."
14772 (let (vals)
14773 (cond
14774 ((equal property "TODO")
14775 (setq vals (org-with-point-at pom
14776 (append org-todo-keywords-1 '("")))))
14777 ((equal property "PRIORITY")
14778 (let ((n org-lowest-priority))
14779 (while (>= n org-highest-priority)
14780 (push (char-to-string n) vals)
14781 (setq n (1- n)))))
14782 ((member property org-special-properties))
14783 ((setq vals (run-hook-with-args-until-success
14784 'org-property-allowed-value-functions property)))
14786 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
14787 (when (and vals (string-match "\\S-" vals))
14788 (setq vals (car (read-from-string (concat "(" vals ")"))))
14789 (setq vals (mapcar (lambda (x)
14790 (cond ((stringp x) x)
14791 ((numberp x) (number-to-string x))
14792 ((symbolp x) (symbol-name x))
14793 (t "???")))
14794 vals)))))
14795 (when (member ":ETC" vals)
14796 (setq vals (remove ":ETC" vals))
14797 (org-add-props (car vals) '(org-unrestricted t)))
14798 (if table (mapcar 'list vals) vals)))
14800 (defun org-property-previous-allowed-value (&optional previous)
14801 "Switch to the next allowed value for this property."
14802 (interactive)
14803 (org-property-next-allowed-value t))
14805 (defun org-property-next-allowed-value (&optional previous)
14806 "Switch to the next allowed value for this property."
14807 (interactive)
14808 (unless (org-at-property-p)
14809 (error "Not at a property"))
14810 (let* ((key (match-string 2))
14811 (value (match-string 3))
14812 (allowed (or (org-property-get-allowed-values (point) key)
14813 (and (member value '("[ ]" "[-]" "[X]"))
14814 '("[ ]" "[X]"))))
14815 nval)
14816 (unless allowed
14817 (error "Allowed values for this property have not been defined"))
14818 (if previous (setq allowed (reverse allowed)))
14819 (if (member value allowed)
14820 (setq nval (car (cdr (member value allowed)))))
14821 (setq nval (or nval (car allowed)))
14822 (if (equal nval value)
14823 (error "Only one allowed value for this property"))
14824 (org-at-property-p)
14825 (replace-match (concat " :" key ": " nval) t t)
14826 (org-indent-line-function)
14827 (beginning-of-line 1)
14828 (skip-chars-forward " \t")
14829 (run-hook-with-args 'org-property-changed-functions key nval)))
14831 (defun org-find-olp (path &optional this-buffer)
14832 "Return a marker pointing to the entry at outline path OLP.
14833 If anything goes wrong, throw an error.
14834 You can wrap this call to catch the error like this:
14836 (condition-case msg
14837 (org-mobile-locate-entry (match-string 4))
14838 (error (nth 1 msg)))
14840 The return value will then be either a string with the error message,
14841 or a marker if everything is OK.
14843 If THIS-BUFFER is set, the outline path does not contain a file,
14844 only headings."
14845 (let* ((file (if this-buffer buffer-file-name (pop path)))
14846 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
14847 (level 1)
14848 (lmin 1)
14849 (lmax 1)
14850 limit re end found pos heading cnt flevel)
14851 (unless buffer (error "File not found :%s" file))
14852 (with-current-buffer buffer
14853 (save-excursion
14854 (save-restriction
14855 (widen)
14856 (setq limit (point-max))
14857 (goto-char (point-min))
14858 (while (setq heading (pop path))
14859 (setq re (format org-complex-heading-regexp-format
14860 (regexp-quote heading)))
14861 (setq cnt 0 pos (point))
14862 (while (re-search-forward re end t)
14863 (setq level (- (match-end 1) (match-beginning 1)))
14864 (if (and (>= level lmin) (<= level lmax))
14865 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
14866 (when (= cnt 0) (error "Heading not found on level %d: %s"
14867 lmax heading))
14868 (when (> cnt 1) (error "Heading not unique on level %d: %s"
14869 lmax heading))
14870 (goto-char found)
14871 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
14872 (setq end (save-excursion (org-end-of-subtree t t))))
14873 (when (org-at-heading-p)
14874 (move-marker (make-marker) (point))))))))
14876 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
14877 "Find node HEADING in BUFFER.
14878 Return a marker to the heading if it was found, or nil if not.
14879 If POS-ONLY is set, return just the position instead of a marker.
14881 The heading text must match exact, but it may have a TODO keyword,
14882 a priority cookie and tags in the standard locations."
14883 (with-current-buffer (or buffer (current-buffer))
14884 (save-excursion
14885 (save-restriction
14886 (widen)
14887 (goto-char (point-min))
14888 (let (case-fold-search)
14889 (if (re-search-forward
14890 (format org-complex-heading-regexp-format
14891 (regexp-quote heading)) nil t)
14892 (if pos-only
14893 (match-beginning 0)
14894 (move-marker (make-marker) (match-beginning 0)))))))))
14896 (defun org-find-exact-heading-in-directory (heading &optional dir)
14897 "Find Org node headline HEADING in all .org files in directory DIR.
14898 When the target headline is found, return a marker to this location."
14899 (let ((files (directory-files (or dir default-directory)
14900 nil "\\`[^.#].*\\.org\\'"))
14901 file visiting m buffer)
14902 (catch 'found
14903 (while (setq file (pop files))
14904 (message "trying %s" file)
14905 (setq visiting (org-find-base-buffer-visiting file))
14906 (setq buffer (or visiting (find-file-noselect file)))
14907 (setq m (org-find-exact-headline-in-buffer
14908 heading buffer))
14909 (when (and (not m) (not visiting)) (kill-buffer buffer))
14910 (and m (throw 'found m))))))
14912 (defun org-find-entry-with-id (ident)
14913 "Locate the entry that contains the ID property with exact value IDENT.
14914 IDENT can be a string, a symbol or a number, this function will search for
14915 the string representation of it.
14916 Return the position where this entry starts, or nil if there is no such entry."
14917 (interactive "sID: ")
14918 (let ((id (cond
14919 ((stringp ident) ident)
14920 ((symbol-name ident) (symbol-name ident))
14921 ((numberp ident) (number-to-string ident))
14922 (t (error "IDENT %s must be a string, symbol or number" ident))))
14923 (case-fold-search nil))
14924 (save-excursion
14925 (save-restriction
14926 (widen)
14927 (goto-char (point-min))
14928 (when (re-search-forward
14929 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
14930 nil t)
14931 (org-back-to-heading t)
14932 (point))))))
14934 ;;;; Timestamps
14936 (defvar org-last-changed-timestamp nil)
14937 (defvar org-last-inserted-timestamp nil
14938 "The last time stamp inserted with `org-insert-time-stamp'.")
14939 (defvar org-time-was-given) ; dynamically scoped parameter
14940 (defvar org-end-time-was-given) ; dynamically scoped parameter
14941 (defvar org-ts-what) ; dynamically scoped parameter
14943 (defun org-time-stamp (arg &optional inactive)
14944 "Prompt for a date/time and insert a time stamp.
14945 If the user specifies a time like HH:MM, or if this command is called
14946 with a prefix argument, the time stamp will contain date and time.
14947 Otherwise, only the date will be included. All parts of a date not
14948 specified by the user will be filled in from the current date/time.
14949 So if you press just return without typing anything, the time stamp
14950 will represent the current date/time. If there is already a timestamp
14951 at the cursor, it will be modified."
14952 (interactive "P")
14953 (let* ((ts nil)
14954 (default-time
14955 ;; Default time is either today, or, when entering a range,
14956 ;; the range start.
14957 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
14958 (save-excursion
14959 (re-search-backward
14960 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
14961 (- (point) 20) t)))
14962 (apply 'encode-time (org-parse-time-string (match-string 1)))
14963 (current-time)))
14964 (default-input (and ts (org-get-compact-tod ts)))
14965 (repeater (save-excursion
14966 (save-match-data
14967 (beginning-of-line)
14968 (when (re-search-forward
14969 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
14970 (save-excursion (progn (end-of-line) (point))) t)
14971 (match-string 0)))))
14972 org-time-was-given org-end-time-was-given time)
14973 (cond
14974 ((and (org-at-timestamp-p t)
14975 (memq last-command '(org-time-stamp org-time-stamp-inactive))
14976 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
14977 (insert "--")
14978 (setq time (let ((this-command this-command))
14979 (org-read-date arg 'totime nil nil
14980 default-time default-input inactive)))
14981 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
14982 ((org-at-timestamp-p t)
14983 (setq time (let ((this-command this-command))
14984 (org-read-date arg 'totime nil nil default-time default-input inactive)))
14985 (when (org-at-timestamp-p t) ; just to get the match data
14986 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
14987 (replace-match "")
14988 (setq org-last-changed-timestamp
14989 (org-insert-time-stamp
14990 time (or org-time-was-given arg)
14991 inactive nil nil (list org-end-time-was-given)))
14992 (when repeater (goto-char (1- (point))) (insert " " repeater)
14993 (setq org-last-changed-timestamp
14994 (concat (substring org-last-inserted-timestamp 0 -1)
14995 " " repeater ">"))))
14996 (message "Timestamp updated"))
14998 (setq time (let ((this-command this-command))
14999 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15000 (org-insert-time-stamp time (or org-time-was-given arg) inactive
15001 nil nil (list org-end-time-was-given))))))
15003 ;; FIXME: can we use this for something else, like computing time differences?
15004 (defun org-get-compact-tod (s)
15005 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
15006 (let* ((t1 (match-string 1 s))
15007 (h1 (string-to-number (match-string 2 s)))
15008 (m1 (string-to-number (match-string 3 s)))
15009 (t2 (and (match-end 4) (match-string 5 s)))
15010 (h2 (and t2 (string-to-number (match-string 6 s))))
15011 (m2 (and t2 (string-to-number (match-string 7 s))))
15012 dh dm)
15013 (if (not t2)
15015 (setq dh (- h2 h1) dm (- m2 m1))
15016 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
15017 (concat t1 "+" (number-to-string dh)
15018 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
15020 (defun org-time-stamp-inactive (&optional arg)
15021 "Insert an inactive time stamp.
15022 An inactive time stamp is enclosed in square brackets instead of angle
15023 brackets. It is inactive in the sense that it does not trigger agenda entries,
15024 does not link to the calendar and cannot be changed with the S-cursor keys.
15025 So these are more for recording a certain time/date."
15026 (interactive "P")
15027 (org-time-stamp arg 'inactive))
15029 (defvar org-date-ovl (make-overlay 1 1))
15030 (overlay-put org-date-ovl 'face 'org-date-selected)
15031 (org-detach-overlay org-date-ovl)
15033 (defvar org-ans1) ; dynamically scoped parameter
15034 (defvar org-ans2) ; dynamically scoped parameter
15036 (defvar org-plain-time-of-day-regexp) ; defined below
15038 (defvar org-overriding-default-time nil) ; dynamically scoped
15039 (defvar org-read-date-overlay nil)
15040 (defvar org-dcst nil) ; dynamically scoped
15041 (defvar org-read-date-history nil)
15042 (defvar org-read-date-final-answer nil)
15043 (defvar org-read-date-analyze-futurep nil)
15044 (defvar org-read-date-analyze-forced-year nil)
15045 (defvar org-read-date-inactive)
15047 (defun org-read-date (&optional org-with-time to-time from-string prompt
15048 default-time default-input inactive)
15049 "Read a date, possibly a time, and make things smooth for the user.
15050 The prompt will suggest to enter an ISO date, but you can also enter anything
15051 which will at least partially be understood by `parse-time-string'.
15052 Unrecognized parts of the date will default to the current day, month, year,
15053 hour and minute. If this command is called to replace a timestamp at point,
15054 or to enter the second timestamp of a range, the default time is taken
15055 from the existing stamp. Furthermore, the command prefers the future,
15056 so if you are giving a date where the year is not given, and the day-month
15057 combination is already past in the current year, it will assume you
15058 mean next year. For details, see the manual. A few examples:
15060 3-2-5 --> 2003-02-05
15061 feb 15 --> currentyear-02-15
15062 2/15 --> currentyear-02-15
15063 sep 12 9 --> 2009-09-12
15064 12:45 --> today 12:45
15065 22 sept 0:34 --> currentyear-09-22 0:34
15066 12 --> currentyear-currentmonth-12
15067 Fri --> nearest Friday (today or later)
15068 etc.
15070 Furthermore you can specify a relative date by giving, as the *first* thing
15071 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
15072 change in days weeks, months, years.
15073 With a single plus or minus, the date is relative to today. With a double
15074 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
15075 +4d --> four days from today
15076 +4 --> same as above
15077 +2w --> two weeks from today
15078 ++5 --> five days from default date
15080 The function understands only English month and weekday abbreviations.
15082 While prompting, a calendar is popped up - you can also select the
15083 date with the mouse (button 1). The calendar shows a period of three
15084 months. To scroll it to other months, use the keys `>' and `<'.
15085 If you don't like the calendar, turn it off with
15086 \(setq org-read-date-popup-calendar nil)
15088 With optional argument TO-TIME, the date will immediately be converted
15089 to an internal time.
15090 With an optional argument WITH-TIME, the prompt will suggest to also
15091 insert a time. Note that when WITH-TIME is not set, you can still
15092 enter a time, and this function will inform the calling routine about
15093 this change. The calling routine may then choose to change the format
15094 used to insert the time stamp into the buffer to include the time.
15095 With optional argument FROM-STRING, read from this string instead from
15096 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
15097 the time/date that is used for everything that is not specified by the
15098 user."
15099 (require 'parse-time)
15100 (let* ((org-time-stamp-rounding-minutes
15101 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
15102 (org-dcst org-display-custom-times)
15103 (ct (org-current-time))
15104 (org-def (or org-overriding-default-time default-time ct))
15105 (org-defdecode (decode-time org-def))
15106 (dummy (progn
15107 (when (< (nth 2 org-defdecode) org-extend-today-until)
15108 (setcar (nthcdr 2 org-defdecode) -1)
15109 (setcar (nthcdr 1 org-defdecode) 59)
15110 (setq org-def (apply 'encode-time org-defdecode)
15111 org-defdecode (decode-time org-def)))))
15112 (calendar-frame-setup nil)
15113 (calendar-setup nil)
15114 (calendar-move-hook nil)
15115 (calendar-view-diary-initially-flag nil)
15116 (calendar-view-holidays-initially-flag nil)
15117 (timestr (format-time-string
15118 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
15119 (prompt (concat (if prompt (concat prompt " ") "")
15120 (format "Date+time [%s]: " timestr)))
15121 ans (org-ans0 "") org-ans1 org-ans2 final)
15123 (cond
15124 (from-string (setq ans from-string))
15125 (org-read-date-popup-calendar
15126 (save-excursion
15127 (save-window-excursion
15128 (calendar)
15129 (org-eval-in-calendar '(setq cursor-type nil))
15130 (unwind-protect
15131 (progn
15132 (calendar-forward-day (- (time-to-days org-def)
15133 (calendar-absolute-from-gregorian
15134 (calendar-current-date))))
15135 (org-eval-in-calendar nil t)
15136 (let* ((old-map (current-local-map))
15137 (map (copy-keymap calendar-mode-map))
15138 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
15139 (org-defkey map (kbd "RET") 'org-calendar-select)
15140 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
15141 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
15142 (org-defkey minibuffer-local-map [(meta shift left)]
15143 (lambda () (interactive)
15144 (org-eval-in-calendar '(calendar-backward-month 1))))
15145 (org-defkey minibuffer-local-map [(meta shift right)]
15146 (lambda () (interactive)
15147 (org-eval-in-calendar '(calendar-forward-month 1))))
15148 (org-defkey minibuffer-local-map [(meta shift up)]
15149 (lambda () (interactive)
15150 (org-eval-in-calendar '(calendar-backward-year 1))))
15151 (org-defkey minibuffer-local-map [(meta shift down)]
15152 (lambda () (interactive)
15153 (org-eval-in-calendar '(calendar-forward-year 1))))
15154 (org-defkey minibuffer-local-map [?\e (shift left)]
15155 (lambda () (interactive)
15156 (org-eval-in-calendar '(calendar-backward-month 1))))
15157 (org-defkey minibuffer-local-map [?\e (shift right)]
15158 (lambda () (interactive)
15159 (org-eval-in-calendar '(calendar-forward-month 1))))
15160 (org-defkey minibuffer-local-map [?\e (shift up)]
15161 (lambda () (interactive)
15162 (org-eval-in-calendar '(calendar-backward-year 1))))
15163 (org-defkey minibuffer-local-map [?\e (shift down)]
15164 (lambda () (interactive)
15165 (org-eval-in-calendar '(calendar-forward-year 1))))
15166 (org-defkey minibuffer-local-map [(shift up)]
15167 (lambda () (interactive)
15168 (org-eval-in-calendar '(calendar-backward-week 1))))
15169 (org-defkey minibuffer-local-map [(shift down)]
15170 (lambda () (interactive)
15171 (org-eval-in-calendar '(calendar-forward-week 1))))
15172 (org-defkey minibuffer-local-map [(shift left)]
15173 (lambda () (interactive)
15174 (org-eval-in-calendar '(calendar-backward-day 1))))
15175 (org-defkey minibuffer-local-map [(shift right)]
15176 (lambda () (interactive)
15177 (org-eval-in-calendar '(calendar-forward-day 1))))
15178 (org-defkey minibuffer-local-map ">"
15179 (lambda () (interactive)
15180 (org-eval-in-calendar '(scroll-calendar-left 1))))
15181 (org-defkey minibuffer-local-map "<"
15182 (lambda () (interactive)
15183 (org-eval-in-calendar '(scroll-calendar-right 1))))
15184 (org-defkey minibuffer-local-map "\C-v"
15185 (lambda () (interactive)
15186 (org-eval-in-calendar
15187 '(calendar-scroll-left-three-months 1))))
15188 (org-defkey minibuffer-local-map "\M-v"
15189 (lambda () (interactive)
15190 (org-eval-in-calendar
15191 '(calendar-scroll-right-three-months 1))))
15192 (run-hooks 'org-read-date-minibuffer-setup-hook)
15193 (unwind-protect
15194 (progn
15195 (use-local-map map)
15196 (setq org-read-date-inactive inactive)
15197 (add-hook 'post-command-hook 'org-read-date-display)
15198 (setq org-ans0 (read-string prompt default-input
15199 'org-read-date-history nil))
15200 ;; org-ans0: from prompt
15201 ;; org-ans1: from mouse click
15202 ;; org-ans2: from calendar motion
15203 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
15204 (remove-hook 'post-command-hook 'org-read-date-display)
15205 (use-local-map old-map)
15206 (when org-read-date-overlay
15207 (delete-overlay org-read-date-overlay)
15208 (setq org-read-date-overlay nil)))))
15209 (bury-buffer "*Calendar*")))))
15211 (t ; Naked prompt only
15212 (unwind-protect
15213 (setq ans (read-string prompt default-input
15214 'org-read-date-history timestr))
15215 (when org-read-date-overlay
15216 (delete-overlay org-read-date-overlay)
15217 (setq org-read-date-overlay nil)))))
15219 (setq final (org-read-date-analyze ans org-def org-defdecode))
15221 (when org-read-date-analyze-forced-year
15222 (message "Year was forced into %s"
15223 (if org-read-date-force-compatible-dates
15224 "compatible range (1970-2037)"
15225 "range representable on this machine"))
15226 (ding))
15228 ;; One round trip to get rid of 34th of August and stuff like that....
15229 (setq final (decode-time (apply 'encode-time final)))
15231 (setq org-read-date-final-answer ans)
15233 (if to-time
15234 (apply 'encode-time final)
15235 (if (and (boundp 'org-time-was-given) org-time-was-given)
15236 (format "%04d-%02d-%02d %02d:%02d"
15237 (nth 5 final) (nth 4 final) (nth 3 final)
15238 (nth 2 final) (nth 1 final))
15239 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
15241 (defvar org-def)
15242 (defvar org-defdecode)
15243 (defvar org-with-time)
15244 (defun org-read-date-display ()
15245 "Display the current date prompt interpretation in the minibuffer."
15246 (when org-read-date-display-live
15247 (when org-read-date-overlay
15248 (delete-overlay org-read-date-overlay))
15249 (when (minibufferp (current-buffer))
15250 (save-excursion
15251 (end-of-line 1)
15252 (while (not (equal (buffer-substring
15253 (max (point-min) (- (point) 4)) (point))
15254 " "))
15255 (insert " ")))
15256 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
15257 " " (or org-ans1 org-ans2)))
15258 (org-end-time-was-given nil)
15259 (f (org-read-date-analyze ans org-def org-defdecode))
15260 (fmts (if org-dcst
15261 org-time-stamp-custom-formats
15262 org-time-stamp-formats))
15263 (fmt (if (or org-with-time
15264 (and (boundp 'org-time-was-given) org-time-was-given))
15265 (cdr fmts)
15266 (car fmts)))
15267 (txt (format-time-string fmt (apply 'encode-time f)))
15268 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
15269 (txt (concat "=> " txt)))
15270 (when (and org-end-time-was-given
15271 (string-match org-plain-time-of-day-regexp txt))
15272 (setq txt (concat (substring txt 0 (match-end 0)) "-"
15273 org-end-time-was-given
15274 (substring txt (match-end 0)))))
15275 (when org-read-date-analyze-futurep
15276 (setq txt (concat txt " (=>F)")))
15277 (setq org-read-date-overlay
15278 (make-overlay (1- (point-at-eol)) (point-at-eol)))
15279 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
15281 (defun org-read-date-analyze (ans org-def org-defdecode)
15282 "Analyze the combined answer of the date prompt."
15283 ;; FIXME: cleanup and comment
15284 (let ((nowdecode (decode-time (current-time)))
15285 delta deltan deltaw deltadef year month day
15286 hour minute second wday pm h2 m2 tl wday1
15287 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
15288 (setq org-read-date-analyze-futurep nil
15289 org-read-date-analyze-forced-year nil)
15290 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
15291 (setq ans "+0"))
15293 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
15294 (setq ans (replace-match "" t t ans)
15295 deltan (car delta)
15296 deltaw (nth 1 delta)
15297 deltadef (nth 2 delta)))
15299 ;; Check if there is an iso week date in there
15300 ;; If yes, store the info and postpone interpreting it until the rest
15301 ;; of the parsing is done
15302 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
15303 (setq iso-year (if (match-end 1)
15304 (org-small-year-to-year
15305 (string-to-number (match-string 1 ans))))
15306 iso-weekday (if (match-end 3)
15307 (string-to-number (match-string 3 ans)))
15308 iso-week (string-to-number (match-string 2 ans)))
15309 (setq ans (replace-match "" t t ans)))
15311 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
15312 (when (string-match
15313 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
15314 (setq year (if (match-end 2)
15315 (string-to-number (match-string 2 ans))
15316 (progn (setq kill-year t)
15317 (string-to-number (format-time-string "%Y"))))
15318 month (string-to-number (match-string 3 ans))
15319 day (string-to-number (match-string 4 ans)))
15320 (if (< year 100) (setq year (+ 2000 year)))
15321 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15322 t nil ans)))
15324 ;; Help matching dotted european dates
15325 (when (string-match
15326 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\. ?\\([1-9][0-9][0-9][0-9]\\)?" ans)
15327 (setq year (if (match-end 3)
15328 (string-to-number (match-string 3 ans))
15329 (progn (setq kill-year t)
15330 (string-to-number (format-time-string "%Y"))))
15331 day (string-to-number (match-string 1 ans))
15332 month (string-to-number (match-string 2 ans))
15333 ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15334 t nil ans)))
15336 ;; Help matching american dates, like 5/30 or 5/30/7
15337 (when (string-match
15338 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
15339 (setq year (if (match-end 4)
15340 (string-to-number (match-string 4 ans))
15341 (progn (setq kill-year t)
15342 (string-to-number (format-time-string "%Y"))))
15343 month (string-to-number (match-string 1 ans))
15344 day (string-to-number (match-string 2 ans)))
15345 (if (< year 100) (setq year (+ 2000 year)))
15346 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15347 t nil ans)))
15348 ;; Help matching am/pm times, because `parse-time-string' does not do that.
15349 ;; If there is a time with am/pm, and *no* time without it, we convert
15350 ;; so that matching will be successful.
15351 (loop for i from 1 to 2 do ; twice, for end time as well
15352 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
15353 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
15354 (setq hour (string-to-number (match-string 1 ans))
15355 minute (if (match-end 3)
15356 (string-to-number (match-string 3 ans))
15358 pm (equal ?p
15359 (string-to-char (downcase (match-string 4 ans)))))
15360 (if (and (= hour 12) (not pm))
15361 (setq hour 0)
15362 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
15363 (setq ans (replace-match (format "%02d:%02d" hour minute)
15364 t t ans))))
15366 ;; Check if a time range is given as a duration
15367 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
15368 (setq hour (string-to-number (match-string 1 ans))
15369 h2 (+ hour (string-to-number (match-string 3 ans)))
15370 minute (string-to-number (match-string 2 ans))
15371 m2 (+ minute (if (match-end 5) (string-to-number
15372 (match-string 5 ans))0)))
15373 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
15374 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
15375 t t ans)))
15377 ;; Check if there is a time range
15378 (when (boundp 'org-end-time-was-given)
15379 (setq org-time-was-given nil)
15380 (when (and (string-match org-plain-time-of-day-regexp ans)
15381 (match-end 8))
15382 (setq org-end-time-was-given (match-string 8 ans))
15383 (setq ans (concat (substring ans 0 (match-beginning 7))
15384 (substring ans (match-end 7))))))
15386 (setq tl (parse-time-string ans)
15387 day (or (nth 3 tl) (nth 3 org-defdecode))
15388 month (or (nth 4 tl)
15389 (if (and org-read-date-prefer-future
15390 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
15391 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
15392 (nth 4 org-defdecode)))
15393 year (or (and (not kill-year) (nth 5 tl))
15394 (if (and org-read-date-prefer-future
15395 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
15396 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
15397 (nth 5 org-defdecode)))
15398 hour (or (nth 2 tl) (nth 2 org-defdecode))
15399 minute (or (nth 1 tl) (nth 1 org-defdecode))
15400 second (or (nth 0 tl) 0)
15401 wday (nth 6 tl))
15403 (when (and (eq org-read-date-prefer-future 'time)
15404 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
15405 (equal day (nth 3 nowdecode))
15406 (equal month (nth 4 nowdecode))
15407 (equal year (nth 5 nowdecode))
15408 (nth 2 tl)
15409 (or (< (nth 2 tl) (nth 2 nowdecode))
15410 (and (= (nth 2 tl) (nth 2 nowdecode))
15411 (nth 1 tl)
15412 (< (nth 1 tl) (nth 1 nowdecode)))))
15413 (setq day (1+ day)
15414 futurep t))
15416 ;; Special date definitions below
15417 (cond
15418 (iso-week
15419 ;; There was an iso week
15420 (require 'cal-iso)
15421 (setq futurep nil)
15422 (setq year (or iso-year year)
15423 day (or iso-weekday wday 1)
15424 wday nil ; to make sure that the trigger below does not match
15425 iso-date (calendar-gregorian-from-absolute
15426 (calendar-absolute-from-iso
15427 (list iso-week day year))))
15428 ; FIXME: Should we also push ISO weeks into the future?
15429 ; (when (and org-read-date-prefer-future
15430 ; (not iso-year)
15431 ; (< (calendar-absolute-from-gregorian iso-date)
15432 ; (time-to-days (current-time))))
15433 ; (setq year (1+ year)
15434 ; iso-date (calendar-gregorian-from-absolute
15435 ; (calendar-absolute-from-iso
15436 ; (list iso-week day year)))))
15437 (setq month (car iso-date)
15438 year (nth 2 iso-date)
15439 day (nth 1 iso-date)))
15440 (deltan
15441 (setq futurep nil)
15442 (unless deltadef
15443 (let ((now (decode-time (current-time))))
15444 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
15445 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
15446 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
15447 ((equal deltaw "m") (setq month (+ month deltan)))
15448 ((equal deltaw "y") (setq year (+ year deltan)))))
15449 ((and wday (not (nth 3 tl)))
15450 (setq futurep nil)
15451 ;; Weekday was given, but no day, so pick that day in the week
15452 ;; on or after the derived date.
15453 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
15454 (unless (equal wday wday1)
15455 (setq day (+ day (% (- wday wday1 -7) 7))))))
15456 (if (and (boundp 'org-time-was-given)
15457 (nth 2 tl))
15458 (setq org-time-was-given t))
15459 (if (< year 100) (setq year (+ 2000 year)))
15460 ;; Check of the date is representable
15461 (if org-read-date-force-compatible-dates
15462 (progn
15463 (if (< year 1970)
15464 (setq year 1970 org-read-date-analyze-forced-year t))
15465 (if (> year 2037)
15466 (setq year 2037 org-read-date-analyze-forced-year t)))
15467 (condition-case nil
15468 (ignore (encode-time second minute hour day month year))
15469 (error
15470 (setq year (nth 5 org-defdecode))
15471 (setq org-read-date-analyze-forced-year t))))
15472 (setq org-read-date-analyze-futurep futurep)
15473 (list second minute hour day month year)))
15475 (defvar parse-time-weekdays)
15476 (defun org-read-date-get-relative (s today default)
15477 "Check string S for special relative date string.
15478 TODAY and DEFAULT are internal times, for today and for a default.
15479 Return shift list (N what def-flag)
15480 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
15481 N is the number of WHATs to shift.
15482 DEF-FLAG is t when a double ++ or -- indicates shift relative to
15483 the DEFAULT date rather than TODAY."
15484 (require 'parse-time)
15485 (when (and
15486 (string-match
15487 (concat
15488 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
15489 "\\([0-9]+\\)?"
15490 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
15491 "\\([ \t]\\|$\\)") s)
15492 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
15493 (let* ((dir (if (> (match-end 1) (match-beginning 1))
15494 (string-to-char (substring (match-string 1 s) -1))
15495 ?+))
15496 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
15497 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
15498 (what (if (match-end 3) (match-string 3 s) "d"))
15499 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
15500 (date (if rel default today))
15501 (wday (nth 6 (decode-time date)))
15502 delta)
15503 (if wday1
15504 (progn
15505 (setq delta (mod (+ 7 (- wday1 wday)) 7))
15506 (if (= dir ?-) (setq delta (- delta 7)))
15507 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
15508 (list delta "d" rel))
15509 (list (* n (if (= dir ?-) -1 1)) what rel)))))
15511 (defun org-order-calendar-date-args (arg1 arg2 arg3)
15512 "Turn a user-specified date into the internal representation.
15513 The internal representation needed by the calendar is (month day year).
15514 This is a wrapper to handle the brain-dead convention in calendar that
15515 user function argument order change dependent on argument order."
15516 (if (boundp 'calendar-date-style)
15517 (cond
15518 ((eq calendar-date-style 'american)
15519 (list arg1 arg2 arg3))
15520 ((eq calendar-date-style 'european)
15521 (list arg2 arg1 arg3))
15522 ((eq calendar-date-style 'iso)
15523 (list arg2 arg3 arg1)))
15524 (with-no-warnings ;; european-calendar-style is obsolete as of version 23.1
15525 (if (org-bound-and-true-p european-calendar-style)
15526 (list arg2 arg1 arg3)
15527 (list arg1 arg2 arg3)))))
15529 (defun org-eval-in-calendar (form &optional keepdate)
15530 "Eval FORM in the calendar window and return to current window.
15531 Also, store the cursor date in variable org-ans2."
15532 (let ((sf (selected-frame))
15533 (sw (selected-window)))
15534 (select-window (get-buffer-window "*Calendar*" t))
15535 (eval form)
15536 (when (and (not keepdate) (calendar-cursor-to-date))
15537 (let* ((date (calendar-cursor-to-date))
15538 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15539 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
15540 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
15541 (select-window sw)
15542 (org-select-frame-set-input-focus sf)))
15544 (defun org-calendar-select ()
15545 "Return to `org-read-date' with the date currently selected.
15546 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15547 (interactive)
15548 (when (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-ans1 (format-time-string "%Y-%m-%d" time)))
15552 (if (active-minibuffer-window) (exit-minibuffer))))
15554 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
15555 "Insert a date stamp for the date given by the internal TIME.
15556 WITH-HM means use the stamp format that includes the time of the day.
15557 INACTIVE means use square brackets instead of angular ones, so that the
15558 stamp will not contribute to the agenda.
15559 PRE and POST are optional strings to be inserted before and after the
15560 stamp.
15561 The command returns the inserted time stamp."
15562 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
15563 stamp)
15564 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
15565 (insert-before-markers (or pre ""))
15566 (when (listp extra)
15567 (setq extra (car extra))
15568 (if (and (stringp extra)
15569 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
15570 (setq extra (format "-%02d:%02d"
15571 (string-to-number (match-string 1 extra))
15572 (string-to-number (match-string 2 extra))))
15573 (setq extra nil)))
15574 (when extra
15575 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
15576 (insert-before-markers (setq stamp (format-time-string fmt time)))
15577 (insert-before-markers (or post ""))
15578 (setq org-last-inserted-timestamp stamp)))
15580 (defun org-toggle-time-stamp-overlays ()
15581 "Toggle the use of custom time stamp formats."
15582 (interactive)
15583 (setq org-display-custom-times (not org-display-custom-times))
15584 (unless org-display-custom-times
15585 (let ((p (point-min)) (bmp (buffer-modified-p)))
15586 (while (setq p (next-single-property-change p 'display))
15587 (if (and (get-text-property p 'display)
15588 (eq (get-text-property p 'face) 'org-date))
15589 (remove-text-properties
15590 p (setq p (next-single-property-change p 'display))
15591 '(display t))))
15592 (set-buffer-modified-p bmp)))
15593 (if (featurep 'xemacs)
15594 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
15595 (org-restart-font-lock)
15596 (setq org-table-may-need-update t)
15597 (if org-display-custom-times
15598 (message "Time stamps are overlaid with custom format")
15599 (message "Time stamp overlays removed")))
15601 (defun org-display-custom-time (beg end)
15602 "Overlay modified time stamp format over timestamp between BEG and END."
15603 (let* ((ts (buffer-substring beg end))
15604 t1 w1 with-hm tf time str w2 (off 0))
15605 (save-match-data
15606 (setq t1 (org-parse-time-string ts t))
15607 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
15608 (setq off (- (match-end 0) (match-beginning 0)))))
15609 (setq end (- end off))
15610 (setq w1 (- end beg)
15611 with-hm (and (nth 1 t1) (nth 2 t1))
15612 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
15613 time (org-fix-decoded-time t1)
15614 str (org-add-props
15615 (format-time-string
15616 (substring tf 1 -1) (apply 'encode-time time))
15617 nil 'mouse-face 'highlight)
15618 w2 (length str))
15619 (if (not (= w2 w1))
15620 (add-text-properties (1+ beg) (+ 2 beg)
15621 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
15622 (if (featurep 'xemacs)
15623 (progn
15624 (put-text-property beg end 'invisible t)
15625 (put-text-property beg end 'end-glyph (make-glyph str)))
15626 (put-text-property beg end 'display str))))
15628 (defun org-translate-time (string)
15629 "Translate all timestamps in STRING to custom format.
15630 But do this only if the variable `org-display-custom-times' is set."
15631 (when org-display-custom-times
15632 (save-match-data
15633 (let* ((start 0)
15634 (re org-ts-regexp-both)
15635 t1 with-hm inactive tf time str beg end)
15636 (while (setq start (string-match re string start))
15637 (setq beg (match-beginning 0)
15638 end (match-end 0)
15639 t1 (save-match-data
15640 (org-parse-time-string (substring string beg end) t))
15641 with-hm (and (nth 1 t1) (nth 2 t1))
15642 inactive (equal (substring string beg (1+ beg)) "[")
15643 tf (funcall (if with-hm 'cdr 'car)
15644 org-time-stamp-custom-formats)
15645 time (org-fix-decoded-time t1)
15646 str (format-time-string
15647 (concat
15648 (if inactive "[" "<") (substring tf 1 -1)
15649 (if inactive "]" ">"))
15650 (apply 'encode-time time))
15651 string (replace-match str t t string)
15652 start (+ start (length str)))))))
15653 string)
15655 (defun org-fix-decoded-time (time)
15656 "Set 0 instead of nil for the first 6 elements of time.
15657 Don't touch the rest."
15658 (let ((n 0))
15659 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
15661 (defun org-days-to-time (timestamp-string)
15662 "Difference between TIMESTAMP-STRING and now in days."
15663 (- (time-to-days (org-time-string-to-time timestamp-string))
15664 (time-to-days (current-time))))
15666 (defun org-deadline-close (timestamp-string &optional ndays)
15667 "Is the time in TIMESTAMP-STRING close to the current date?"
15668 (setq ndays (or ndays (org-get-wdays timestamp-string)))
15669 (and (< (org-days-to-time timestamp-string) ndays)
15670 (not (org-entry-is-done-p))))
15672 (defun org-get-wdays (ts)
15673 "Get the deadline lead time appropriate for timestring TS."
15674 (cond
15675 ((<= org-deadline-warning-days 0)
15676 ;; 0 or negative, enforce this value no matter what
15677 (- org-deadline-warning-days))
15678 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
15679 ;; lead time is specified.
15680 (floor (* (string-to-number (match-string 1 ts))
15681 (cdr (assoc (match-string 2 ts)
15682 '(("d" . 1) ("w" . 7)
15683 ("m" . 30.4) ("y" . 365.25)))))))
15684 ;; go for the default.
15685 (t org-deadline-warning-days)))
15687 (defun org-calendar-select-mouse (ev)
15688 "Return to `org-read-date' with the date currently selected.
15689 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15690 (interactive "e")
15691 (mouse-set-point ev)
15692 (when (calendar-cursor-to-date)
15693 (let* ((date (calendar-cursor-to-date))
15694 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15695 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15696 (if (active-minibuffer-window) (exit-minibuffer))))
15698 (defun org-check-deadlines (ndays)
15699 "Check if there are any deadlines due or past due.
15700 A deadline is considered due if it happens within `org-deadline-warning-days'
15701 days from today's date. If the deadline appears in an entry marked DONE,
15702 it is not shown. The prefix arg NDAYS can be used to test that many
15703 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
15704 (interactive "P")
15705 (let* ((org-warn-days
15706 (cond
15707 ((equal ndays '(4)) 100000)
15708 (ndays (prefix-numeric-value ndays))
15709 (t (abs org-deadline-warning-days))))
15710 (case-fold-search nil)
15711 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
15712 (callback
15713 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
15715 (message "%d deadlines past-due or due within %d days"
15716 (org-occur regexp nil callback)
15717 org-warn-days)))
15719 (defun org-check-before-date (date)
15720 "Check if there are deadlines or scheduled entries before DATE."
15721 (interactive (list (org-read-date)))
15722 (let ((case-fold-search nil)
15723 (regexp (concat "\\<\\(" org-deadline-string
15724 "\\|" org-scheduled-string
15725 "\\) *<\\([^>]+\\)>"))
15726 (callback
15727 (lambda () (time-less-p
15728 (org-time-string-to-time (match-string 2))
15729 (org-time-string-to-time date)))))
15730 (message "%d entries before %s"
15731 (org-occur regexp nil callback) date)))
15733 (defun org-check-after-date (date)
15734 "Check if there are deadlines or scheduled entries after DATE."
15735 (interactive (list (org-read-date)))
15736 (let ((case-fold-search nil)
15737 (regexp (concat "\\<\\(" org-deadline-string
15738 "\\|" org-scheduled-string
15739 "\\) *<\\([^>]+\\)>"))
15740 (callback
15741 (lambda () (not
15742 (time-less-p
15743 (org-time-string-to-time (match-string 2))
15744 (org-time-string-to-time date))))))
15745 (message "%d entries after %s"
15746 (org-occur regexp nil callback) date)))
15748 (defun org-check-dates-range (start-date end-date)
15749 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
15750 (interactive (list (org-read-date nil nil nil "Range starts")
15751 (org-read-date nil nil nil "Range end")))
15752 (let ((case-fold-search nil)
15753 (regexp (concat "\\<\\(" org-deadline-string
15754 "\\|" org-scheduled-string
15755 "\\) *<\\([^>]+\\)>"))
15756 (callback
15757 (lambda ()
15758 (let ((match (match-string 2)))
15759 (and
15760 (not (time-less-p
15761 (org-time-string-to-time match)
15762 (org-time-string-to-time start-date)))
15763 (time-less-p
15764 (org-time-string-to-time match)
15765 (org-time-string-to-time end-date)))))))
15766 (message "%d entries between %s and %s"
15767 (org-occur regexp nil callback) start-date end-date)))
15769 (defun org-evaluate-time-range (&optional to-buffer)
15770 "Evaluate a time range by computing the difference between start and end.
15771 Normally the result is just printed in the echo area, but with prefix arg
15772 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
15773 If the time range is actually in a table, the result is inserted into the
15774 next column.
15775 For time difference computation, a year is assumed to be exactly 365
15776 days in order to avoid rounding problems."
15777 (interactive "P")
15779 (org-clock-update-time-maybe)
15780 (save-excursion
15781 (unless (org-at-date-range-p t)
15782 (goto-char (point-at-bol))
15783 (re-search-forward org-tr-regexp-both (point-at-eol) t))
15784 (if (not (org-at-date-range-p t))
15785 (error "Not at a time-stamp range, and none found in current line")))
15786 (let* ((ts1 (match-string 1))
15787 (ts2 (match-string 2))
15788 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
15789 (match-end (match-end 0))
15790 (time1 (org-time-string-to-time ts1))
15791 (time2 (org-time-string-to-time ts2))
15792 (t1 (org-float-time time1))
15793 (t2 (org-float-time time2))
15794 (diff (abs (- t2 t1)))
15795 (negative (< (- t2 t1) 0))
15796 ;; (ys (floor (* 365 24 60 60)))
15797 (ds (* 24 60 60))
15798 (hs (* 60 60))
15799 (fy "%dy %dd %02d:%02d")
15800 (fy1 "%dy %dd")
15801 (fd "%dd %02d:%02d")
15802 (fd1 "%dd")
15803 (fh "%02d:%02d")
15804 y d h m align)
15805 (if havetime
15806 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
15808 d (floor (/ diff ds)) diff (mod diff ds)
15809 h (floor (/ diff hs)) diff (mod diff hs)
15810 m (floor (/ diff 60)))
15811 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
15813 d (floor (+ (/ diff ds) 0.5))
15814 h 0 m 0))
15815 (if (not to-buffer)
15816 (message "%s" (org-make-tdiff-string y d h m))
15817 (if (org-at-table-p)
15818 (progn
15819 (goto-char match-end)
15820 (setq align t)
15821 (and (looking-at " *|") (goto-char (match-end 0))))
15822 (goto-char match-end))
15823 (if (looking-at
15824 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
15825 (replace-match ""))
15826 (if negative (insert " -"))
15827 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
15828 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
15829 (insert " " (format fh h m))))
15830 (if align (org-table-align))
15831 (message "Time difference inserted")))))
15833 (defun org-make-tdiff-string (y d h m)
15834 (let ((fmt "")
15835 (l nil))
15836 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
15837 l (push y l)))
15838 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
15839 l (push d l)))
15840 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
15841 l (push h l)))
15842 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
15843 l (push m l)))
15844 (apply 'format fmt (nreverse l))))
15846 (defun org-time-string-to-time (s &optional buffer pos)
15847 (condition-case errdata
15848 (apply 'encode-time (org-parse-time-string s))
15849 (error (error "Bad timestamp `%s'%s\nError was: %s"
15850 s (if (not (and buffer pos))
15852 (format " at %d in buffer `%s'" pos buffer))
15853 (cdr errdata)))))
15855 (defun org-time-string-to-seconds (s)
15856 (org-float-time (org-time-string-to-time s)))
15858 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
15859 "Convert a time stamp to an absolute day number.
15860 If there is a specifier for a cyclic time stamp, get the closest date to
15861 DAYNR.
15862 PREFER and SHOW-ALL are passed through to `org-closest-date'.
15863 The variable date is bound by the calendar when this is called."
15864 (cond
15865 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
15866 (if (org-diary-sexp-entry (match-string 1 s) "" date)
15867 daynr
15868 (+ daynr 1000)))
15869 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
15870 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
15871 (time-to-days (current-time))) (match-string 0 s)
15872 prefer show-all))
15873 (t (time-to-days
15874 (condition-case errdata
15875 (apply 'encode-time (org-parse-time-string s))
15876 (error (error "Bad timestamp `%s'%s\nError was: %s"
15877 s (if (not (and buffer pos))
15879 (format " at %d in buffer `%s'" pos buffer))
15880 (cdr errdata))))))))
15882 (defun org-days-to-iso-week (days)
15883 "Return the iso week number."
15884 (require 'cal-iso)
15885 (car (calendar-iso-from-absolute days)))
15887 (defun org-small-year-to-year (year)
15888 "Convert 2-digit years into 4-digit years.
15889 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
15890 The year 2000 cannot be abbreviated. Any year larger than 99
15891 is returned unchanged."
15892 (if (< year 38)
15893 (setq year (+ 2000 year))
15894 (if (< year 100)
15895 (setq year (+ 1900 year))))
15896 year)
15898 (defun org-time-from-absolute (d)
15899 "Return the time corresponding to date D.
15900 D may be an absolute day number, or a calendar-type list (month day year)."
15901 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
15902 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
15904 (defun org-calendar-holiday ()
15905 "List of holidays, for Diary display in Org-mode."
15906 (require 'holidays)
15907 (let ((hl (funcall
15908 (if (fboundp 'calendar-check-holidays)
15909 'calendar-check-holidays 'check-calendar-holidays) date)))
15910 (if hl (mapconcat 'identity hl "; "))))
15912 (defun org-diary-sexp-entry (sexp entry date)
15913 "Process a SEXP diary ENTRY for DATE."
15914 (require 'diary-lib)
15915 (let ((result (if calendar-debug-sexp
15916 (let ((stack-trace-on-error t))
15917 (eval (car (read-from-string sexp))))
15918 (condition-case nil
15919 (eval (car (read-from-string sexp)))
15920 (error
15921 (beep)
15922 (message "Bad sexp at line %d in %s: %s"
15923 (org-current-line)
15924 (buffer-file-name) sexp)
15925 (sleep-for 2))))))
15926 (cond ((stringp result) (split-string result "; "))
15927 ((and (consp result)
15928 (not (consp (cdr result)))
15929 (stringp (cdr result))) (cdr result))
15930 ((and (consp result)
15931 (stringp (car result))) result)
15932 (result entry)
15933 (t nil))))
15935 (defun org-diary-to-ical-string (frombuf)
15936 "Get iCalendar entries from diary entries in buffer FROMBUF.
15937 This uses the icalendar.el library."
15938 (let* ((tmpdir (if (featurep 'xemacs)
15939 (temp-directory)
15940 temporary-file-directory))
15941 (tmpfile (make-temp-name
15942 (expand-file-name "orgics" tmpdir)))
15943 buf rtn b e)
15944 (with-current-buffer frombuf
15945 (icalendar-export-region (point-min) (point-max) tmpfile)
15946 (setq buf (find-buffer-visiting tmpfile))
15947 (set-buffer buf)
15948 (goto-char (point-min))
15949 (if (re-search-forward "^BEGIN:VEVENT" nil t)
15950 (setq b (match-beginning 0)))
15951 (goto-char (point-max))
15952 (if (re-search-backward "^END:VEVENT" nil t)
15953 (setq e (match-end 0)))
15954 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
15955 (kill-buffer buf)
15956 (delete-file tmpfile)
15957 rtn))
15959 (defun org-closest-date (start current change prefer show-all)
15960 "Find the date closest to CURRENT that is consistent with START and CHANGE.
15961 When PREFER is `past', return a date that is either CURRENT or past.
15962 When PREFER is `future', return a date that is either CURRENT or future.
15963 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
15964 ;; Make the proper lists from the dates
15965 (catch 'exit
15966 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
15967 dn dw sday cday n1 n2 n0
15968 d m y y1 y2 date1 date2 nmonths nm ny m2)
15970 (setq start (org-date-to-gregorian start)
15971 current (org-date-to-gregorian
15972 (if show-all
15973 current
15974 (time-to-days (current-time))))
15975 sday (calendar-absolute-from-gregorian start)
15976 cday (calendar-absolute-from-gregorian current))
15978 (if (<= cday sday) (throw 'exit sday))
15980 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
15981 (setq dn (string-to-number (match-string 1 change))
15982 dw (cdr (assoc (match-string 2 change) a1)))
15983 (error "Invalid change specifier: %s" change))
15984 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
15985 (cond
15986 ((eq dw 'day)
15987 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
15988 n2 (+ n1 dn)))
15989 ((eq dw 'year)
15990 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
15991 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
15992 (setq date1 (list m d y1)
15993 n1 (calendar-absolute-from-gregorian date1)
15994 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
15995 n2 (calendar-absolute-from-gregorian date2)))
15996 ((eq dw 'month)
15997 ;; approx number of month between the two dates
15998 (setq nmonths (floor (/ (- cday sday) 30.436875)))
15999 ;; How often does dn fit in there?
16000 (setq d (nth 1 start) m (car start) y (nth 2 start)
16001 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
16002 m (+ m nm)
16003 ny (floor (/ m 12))
16004 y (+ y ny)
16005 m (- m (* ny 12)))
16006 (while (> m 12) (setq m (- m 12) y (1+ y)))
16007 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
16008 (setq m2 (+ m dn) y2 y)
16009 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16010 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
16011 (while (<= n2 cday)
16012 (setq n1 n2 m m2 y y2)
16013 (setq m2 (+ m dn) y2 y)
16014 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16015 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
16016 ;; Make sure n1 is the earlier date
16017 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
16018 (if show-all
16019 (cond
16020 ((eq prefer 'past) (if (= cday n2) n2 n1))
16021 ((eq prefer 'future) (if (= cday n1) n1 n2))
16022 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
16023 (cond
16024 ((eq prefer 'past) (if (= cday n2) n2 n1))
16025 ((eq prefer 'future) (if (= cday n1) n1 n2))
16026 (t (if (= cday n1) n1 n2)))))))
16028 (defun org-date-to-gregorian (date)
16029 "Turn any specification of DATE into a Gregorian date for the calendar."
16030 (cond ((integerp date) (calendar-gregorian-from-absolute date))
16031 ((and (listp date) (= (length date) 3)) date)
16032 ((stringp date)
16033 (setq date (org-parse-time-string date))
16034 (list (nth 4 date) (nth 3 date) (nth 5 date)))
16035 ((listp date)
16036 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
16038 (defun org-parse-time-string (s &optional nodefault)
16039 "Parse the standard Org-mode time string.
16040 This should be a lot faster than the normal `parse-time-string'.
16041 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
16042 hour and minute fields will be nil if not given."
16043 (if (string-match org-ts-regexp0 s)
16044 (list 0
16045 (if (or (match-beginning 8) (not nodefault))
16046 (string-to-number (or (match-string 8 s) "0")))
16047 (if (or (match-beginning 7) (not nodefault))
16048 (string-to-number (or (match-string 7 s) "0")))
16049 (string-to-number (match-string 4 s))
16050 (string-to-number (match-string 3 s))
16051 (string-to-number (match-string 2 s))
16052 nil nil nil)
16053 (error "Not a standard Org-mode time string: %s" s)))
16055 (defun org-timestamp-up (&optional arg)
16056 "Increase the date item at the cursor by one.
16057 If the cursor is on the year, change the year. If it is on the month,
16058 the day or the time, change that.
16059 With prefix ARG, change by that many units."
16060 (interactive "p")
16061 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
16063 (defun org-timestamp-down (&optional arg)
16064 "Decrease the date item at the cursor by one.
16065 If the cursor is on the year, change the year. If it is on the month,
16066 the day or the time, change that.
16067 With prefix ARG, change by that many units."
16068 (interactive "p")
16069 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
16071 (defun org-timestamp-up-day (&optional arg)
16072 "Increase the date in the time stamp by one day.
16073 With prefix ARG, change that many days."
16074 (interactive "p")
16075 (if (and (not (org-at-timestamp-p t))
16076 (org-at-heading-p))
16077 (org-todo 'up)
16078 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
16080 (defun org-timestamp-down-day (&optional arg)
16081 "Decrease the date in the time stamp by one day.
16082 With prefix ARG, change that many days."
16083 (interactive "p")
16084 (if (and (not (org-at-timestamp-p t))
16085 (org-at-heading-p))
16086 (org-todo 'down)
16087 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
16089 (defun org-at-timestamp-p (&optional inactive-ok)
16090 "Determine if the cursor is in or at a timestamp."
16091 (interactive)
16092 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
16093 (pos (point))
16094 (ans (or (looking-at tsr)
16095 (save-excursion
16096 (skip-chars-backward "^[<\n\r\t")
16097 (if (> (point) (point-min)) (backward-char 1))
16098 (and (looking-at tsr)
16099 (> (- (match-end 0) pos) -1))))))
16100 (and ans
16101 (boundp 'org-ts-what)
16102 (setq org-ts-what
16103 (cond
16104 ((= pos (match-beginning 0)) 'bracket)
16105 ;; Point is considered to be "on the bracket" whether
16106 ;; it's really on it or right after it.
16107 ((or (= pos (1- (match-end 0)))
16108 (= pos (match-end 0))) 'bracket)
16109 ((org-pos-in-match-range pos 2) 'year)
16110 ((org-pos-in-match-range pos 3) 'month)
16111 ((org-pos-in-match-range pos 7) 'hour)
16112 ((org-pos-in-match-range pos 8) 'minute)
16113 ((or (org-pos-in-match-range pos 4)
16114 (org-pos-in-match-range pos 5)) 'day)
16115 ((and (> pos (or (match-end 8) (match-end 5)))
16116 (< pos (match-end 0)))
16117 (- pos (or (match-end 8) (match-end 5))))
16118 (t 'day))))
16119 ans))
16121 (defun org-toggle-timestamp-type ()
16122 "Toggle the type (<active> or [inactive]) of a time stamp."
16123 (interactive)
16124 (when (org-at-timestamp-p t)
16125 (let ((beg (match-beginning 0)) (end (match-end 0))
16126 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
16127 (save-excursion
16128 (goto-char beg)
16129 (while (re-search-forward "[][<>]" end t)
16130 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
16131 t t)))
16132 (message "Timestamp is now %sactive"
16133 (if (equal (char-after beg) ?<) "" "in")))))
16135 (defun org-timestamp-change (n &optional what updown)
16136 "Change the date in the time stamp at point.
16137 The date will be changed by N times WHAT. WHAT can be `day', `month',
16138 `year', `minute', `second'. If WHAT is not given, the cursor position
16139 in the timestamp determines what will be changed."
16140 (let ((origin (point)) origin-cat
16141 with-hm inactive
16142 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
16143 org-ts-what
16144 extra rem
16145 ts time time0)
16146 (if (not (org-at-timestamp-p t))
16147 (error "Not at a timestamp"))
16148 (if (and (not what) (eq org-ts-what 'bracket))
16149 (org-toggle-timestamp-type)
16150 ;; Point isn't on brackets. Remember the part of the time-stamp
16151 ;; the point was in. Indeed, size of time-stamps may change,
16152 ;; but point must be kept in the same category nonetheless.
16153 (setq origin-cat org-ts-what)
16154 (if (and (not what) (not (eq org-ts-what 'day))
16155 org-display-custom-times
16156 (get-text-property (point) 'display)
16157 (not (get-text-property (1- (point)) 'display)))
16158 (setq org-ts-what 'day))
16159 (setq org-ts-what (or what org-ts-what)
16160 inactive (= (char-after (match-beginning 0)) ?\[)
16161 ts (match-string 0))
16162 (replace-match "")
16163 (if (string-match
16164 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
16166 (setq extra (match-string 1 ts)))
16167 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
16168 (setq with-hm t))
16169 (setq time0 (org-parse-time-string ts))
16170 (when (and updown
16171 (eq org-ts-what 'minute)
16172 (not current-prefix-arg))
16173 ;; This looks like s-up and s-down. Change by one rounding step.
16174 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
16175 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
16176 (setcar (cdr time0) (+ (nth 1 time0)
16177 (if (> n 0) (- rem) (- dm rem))))))
16178 (setq time
16179 (encode-time (or (car time0) 0)
16180 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
16181 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
16182 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
16183 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
16184 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
16185 (nthcdr 6 time0)))
16186 (when (and (member org-ts-what '(hour minute))
16187 extra
16188 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
16189 (setq extra (org-modify-ts-extra
16190 extra
16191 (if (eq org-ts-what 'hour) 2 5)
16192 n dm)))
16193 (when (integerp org-ts-what)
16194 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
16195 (if (eq what 'calendar)
16196 (let ((cal-date (org-get-date-from-calendar)))
16197 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
16198 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
16199 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
16200 (setcar time0 (or (car time0) 0))
16201 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
16202 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
16203 (setq time (apply 'encode-time time0))))
16204 ;; Insert the new time-stamp, and ensure point stays in the same
16205 ;; category as before (i.e. not after the last position in that
16206 ;; category).
16207 (let ((pos (point)))
16208 ;; Stay before inserted string. `save-excursion' is of no use.
16209 (setq org-last-changed-timestamp
16210 (org-insert-time-stamp time with-hm inactive nil nil extra))
16211 (goto-char pos))
16212 (save-match-data
16213 (looking-at org-ts-regexp3)
16214 (goto-char (cond
16215 ;; `day' category ends before `hour' if any, or at
16216 ;; the end of the day name.
16217 ((eq origin-cat 'day)
16218 (min (or (match-beginning 7) (1- (match-end 5))) origin))
16219 ((eq origin-cat 'hour) (min (match-end 7) origin))
16220 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
16221 ((integerp origin-cat) (min (1- (match-end 0)) origin))
16222 ;; `year' and `month' have both fixed size: point
16223 ;; couldn't have moved into another part.
16224 (t origin))))
16225 ;; Update clock if on a CLOCK line.
16226 (org-clock-update-time-maybe)
16227 ;; Try to recenter the calendar window, if any.
16228 (if (and org-calendar-follow-timestamp-change
16229 (get-buffer-window "*Calendar*" t)
16230 (memq org-ts-what '(day month year)))
16231 (org-recenter-calendar (time-to-days time))))))
16233 (defun org-modify-ts-extra (s pos n dm)
16234 "Change the different parts of the lead-time and repeat fields in timestamp."
16235 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
16236 ng h m new rem)
16237 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
16238 (cond
16239 ((or (org-pos-in-match-range pos 2)
16240 (org-pos-in-match-range pos 3))
16241 (setq m (string-to-number (match-string 3 s))
16242 h (string-to-number (match-string 2 s)))
16243 (if (org-pos-in-match-range pos 2)
16244 (setq h (+ h n))
16245 (setq n (* dm (org-no-warnings (signum n))))
16246 (when (not (= 0 (setq rem (% m dm))))
16247 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
16248 (setq m (+ m n)))
16249 (if (< m 0) (setq m (+ m 60) h (1- h)))
16250 (if (> m 59) (setq m (- m 60) h (1+ h)))
16251 (setq h (min 24 (max 0 h)))
16252 (setq ng 1 new (format "-%02d:%02d" h m)))
16253 ((org-pos-in-match-range pos 6)
16254 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
16255 ((org-pos-in-match-range pos 5)
16256 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
16258 ((org-pos-in-match-range pos 9)
16259 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
16260 ((org-pos-in-match-range pos 8)
16261 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
16263 (when ng
16264 (setq s (concat
16265 (substring s 0 (match-beginning ng))
16267 (substring s (match-end ng))))))
16270 (defun org-recenter-calendar (date)
16271 "If the calendar is visible, recenter it to DATE."
16272 (let ((cwin (get-buffer-window "*Calendar*" t)))
16273 (when cwin
16274 (let ((calendar-move-hook nil))
16275 (with-selected-window cwin
16276 (calendar-goto-date (if (listp date) date
16277 (calendar-gregorian-from-absolute date))))))))
16279 (defun org-goto-calendar (&optional arg)
16280 "Go to the Emacs calendar at the current date.
16281 If there is a time stamp in the current line, go to that date.
16282 A prefix ARG can be used to force the current date."
16283 (interactive "P")
16284 (let ((tsr org-ts-regexp) diff
16285 (calendar-move-hook nil)
16286 (calendar-view-holidays-initially-flag nil)
16287 (calendar-view-diary-initially-flag nil))
16288 (if (or (org-at-timestamp-p)
16289 (save-excursion
16290 (beginning-of-line 1)
16291 (looking-at (concat ".*" tsr))))
16292 (let ((d1 (time-to-days (current-time)))
16293 (d2 (time-to-days
16294 (org-time-string-to-time (match-string 1)))))
16295 (setq diff (- d2 d1))))
16296 (calendar)
16297 (calendar-goto-today)
16298 (if (and diff (not arg)) (calendar-forward-day diff))))
16300 (defun org-get-date-from-calendar ()
16301 "Return a list (month day year) of date at point in calendar."
16302 (with-current-buffer "*Calendar*"
16303 (save-match-data
16304 (calendar-cursor-to-date))))
16306 (defun org-date-from-calendar ()
16307 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
16308 If there is already a time stamp at the cursor position, update it."
16309 (interactive)
16310 (if (org-at-timestamp-p t)
16311 (org-timestamp-change 0 'calendar)
16312 (let ((cal-date (org-get-date-from-calendar)))
16313 (org-insert-time-stamp
16314 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
16316 (defun org-minutes-to-hh:mm-string (m)
16317 "Compute H:MM from a number of minutes."
16318 (let ((h (/ m 60)))
16319 (setq m (- m (* 60 h)))
16320 (format org-time-clocksum-format h m)))
16322 (defun org-hh:mm-string-to-minutes (s)
16323 "Convert a string H:MM to a number of minutes.
16324 If the string is just a number, interpret it as minutes.
16325 In fact, the first hh:mm or number in the string will be taken,
16326 there can be extra stuff in the string.
16327 If no number is found, the return value is 0."
16328 (cond
16329 ((integerp s) s)
16330 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
16331 (+ (* (string-to-number (match-string 1 s)) 60)
16332 (string-to-number (match-string 2 s))))
16333 ((string-match "\\([0-9]+\\)" s)
16334 (string-to-number (match-string 1 s)))
16335 (t 0)))
16337 (defcustom org-effort-durations
16338 `(("h" . 60)
16339 ("d" . ,(* 60 8))
16340 ("w" . ,(* 60 8 5))
16341 ("m" . ,(* 60 8 5 4))
16342 ("y" . ,(* 60 8 5 40)))
16343 "Conversion factor to minutes for an effort modifier.
16345 Each entry has the form (MODIFIER . MINUTES).
16347 In an effort string, a number followed by MODIFIER is multiplied
16348 by the specified number of MINUTES to obtain an effort in
16349 minutes.
16351 For example, if the value of this variable is ((\"hours\" . 60)), then an
16352 effort string \"2hours\" is equivalent to 120 minutes."
16353 :group 'org-agenda
16354 :version "24.1"
16355 :type '(alist :key-type (string :tag "Modifier")
16356 :value-type (number :tag "Minutes")))
16358 (defun org-duration-string-to-minutes (s)
16359 "Convert a duration string S to minutes.
16361 A bare number is interpreted as minutes, modifiers can be set by
16362 customizing `org-effort-durations' (which see).
16364 Entries containing a colon are interpreted as H:MM by
16365 `org-hh:mm-string-to-minutes'."
16366 (let ((result 0)
16367 (re (concat "\\([0-9]+\\) *\\("
16368 (regexp-opt (mapcar 'car org-effort-durations))
16369 "\\)")))
16370 (while (string-match re s)
16371 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
16372 (string-to-number (match-string 1 s))))
16373 (setq s (replace-match "" nil t s)))
16374 (incf result (org-hh:mm-string-to-minutes s))
16375 result))
16377 ;;;; Files
16379 (defun org-save-all-org-buffers ()
16380 "Save all Org-mode buffers without user confirmation."
16381 (interactive)
16382 (message "Saving all Org-mode buffers...")
16383 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
16384 (when (featurep 'org-id) (org-id-locations-save))
16385 (message "Saving all Org-mode buffers... done"))
16387 (defun org-revert-all-org-buffers ()
16388 "Revert all Org-mode buffers.
16389 Prompt for confirmation when there are unsaved changes.
16390 Be sure you know what you are doing before letting this function
16391 overwrite your changes.
16393 This function is useful in a setup where one tracks org files
16394 with a version control system, to revert on one machine after pulling
16395 changes from another. I believe the procedure must be like this:
16397 1. M-x org-save-all-org-buffers
16398 2. Pull changes from the other machine, resolve conflicts
16399 3. M-x org-revert-all-org-buffers"
16400 (interactive)
16401 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
16402 (error "Abort"))
16403 (save-excursion
16404 (save-window-excursion
16405 (mapc
16406 (lambda (b)
16407 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
16408 (with-current-buffer b buffer-file-name))
16409 (org-pop-to-buffer-same-window b)
16410 (revert-buffer t 'no-confirm)))
16411 (buffer-list))
16412 (when (and (featurep 'org-id) org-id-track-globally)
16413 (org-id-locations-load)))))
16415 ;;;; Agenda files
16417 ;;;###autoload
16418 (defun org-switchb (&optional arg)
16419 "Switch between Org buffers.
16420 With one prefix argument, restrict available buffers to files.
16421 With two prefix arguments, restrict available buffers to agenda files.
16423 Defaults to `iswitchb' for buffer name completion.
16424 Set `org-completion-use-ido' to make it use ido instead."
16425 (interactive "P")
16426 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
16427 ((equal arg '(16)) (org-buffer-list 'agenda))
16428 (t (org-buffer-list))))
16429 (org-completion-use-iswitchb org-completion-use-iswitchb)
16430 (org-completion-use-ido org-completion-use-ido))
16431 (unless (or org-completion-use-ido org-completion-use-iswitchb)
16432 (setq org-completion-use-iswitchb t))
16433 (org-pop-to-buffer-same-window
16434 (org-icompleting-read "Org buffer: "
16435 (mapcar 'list (mapcar 'buffer-name blist))
16436 nil t))))
16438 ;;; Define some older names previously used for this functionality
16439 ;;;###autoload
16440 (defalias 'org-ido-switchb 'org-switchb)
16441 ;;;###autoload
16442 (defalias 'org-iswitchb 'org-switchb)
16444 (defun org-buffer-list (&optional predicate exclude-tmp)
16445 "Return a list of Org buffers.
16446 PREDICATE can be `export', `files' or `agenda'.
16448 export restrict the list to Export buffers.
16449 files restrict the list to buffers visiting Org files.
16450 agenda restrict the list to buffers visiting agenda files.
16452 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
16453 (let* ((bfn nil)
16454 (agenda-files (and (eq predicate 'agenda)
16455 (mapcar 'file-truename (org-agenda-files t))))
16456 (filter
16457 (cond
16458 ((eq predicate 'files)
16459 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
16460 ((eq predicate 'export)
16461 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
16462 ((eq predicate 'agenda)
16463 (lambda (b)
16464 (with-current-buffer b
16465 (and (derived-mode-p 'org-mode)
16466 (setq bfn (buffer-file-name b))
16467 (member (file-truename bfn) agenda-files)))))
16468 (t (lambda (b) (with-current-buffer b
16469 (or (derived-mode-p 'org-mode)
16470 (string-match "\*Org .*Export"
16471 (buffer-name b)))))))))
16472 (delq nil
16473 (mapcar
16474 (lambda(b)
16475 (if (and (funcall filter b)
16476 (or (not exclude-tmp)
16477 (not (string-match "tmp" (buffer-name b)))))
16479 nil))
16480 (buffer-list)))))
16482 (defun org-agenda-files (&optional unrestricted archives)
16483 "Get the list of agenda files.
16484 Optional UNRESTRICTED means return the full list even if a restriction
16485 is currently in place.
16486 When ARCHIVES is t, include all archive files that are really being
16487 used by the agenda files. If ARCHIVE is `ifmode', do this only if
16488 `org-agenda-archives-mode' is t."
16489 (let ((files
16490 (cond
16491 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
16492 ((stringp org-agenda-files) (org-read-agenda-file-list))
16493 ((listp org-agenda-files) org-agenda-files)
16494 (t (error "Invalid value of `org-agenda-files'")))))
16495 (setq files (apply 'append
16496 (mapcar (lambda (f)
16497 (if (file-directory-p f)
16498 (directory-files
16499 f t org-agenda-file-regexp)
16500 (list f)))
16501 files)))
16502 (when org-agenda-skip-unavailable-files
16503 (setq files (delq nil
16504 (mapcar (function
16505 (lambda (file)
16506 (and (file-readable-p file) file)))
16507 files))))
16508 (when (or (eq archives t)
16509 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
16510 (setq files (org-add-archive-files files)))
16511 files))
16513 (defun org-agenda-file-p (&optional file)
16514 "Return non-nil, if FILE is an agenda file.
16515 If FILE is omitted, use the file associated with the current
16516 buffer."
16517 (member (or file (buffer-file-name))
16518 (org-agenda-files t)))
16520 (defun org-edit-agenda-file-list ()
16521 "Edit the list of agenda files.
16522 Depending on setup, this either uses customize to edit the variable
16523 `org-agenda-files', or it visits the file that is holding the list. In the
16524 latter case, the buffer is set up in a way that saving it automatically kills
16525 the buffer and restores the previous window configuration."
16526 (interactive)
16527 (if (stringp org-agenda-files)
16528 (let ((cw (current-window-configuration)))
16529 (find-file org-agenda-files)
16530 (org-set-local 'org-window-configuration cw)
16531 (org-add-hook 'after-save-hook
16532 (lambda ()
16533 (set-window-configuration
16534 (prog1 org-window-configuration
16535 (kill-buffer (current-buffer))))
16536 (org-install-agenda-files-menu)
16537 (message "New agenda file list installed"))
16538 nil 'local)
16539 (message "%s" (substitute-command-keys
16540 "Edit list and finish with \\[save-buffer]")))
16541 (customize-variable 'org-agenda-files)))
16543 (defun org-store-new-agenda-file-list (list)
16544 "Set new value for the agenda file list and save it correctly."
16545 (if (stringp org-agenda-files)
16546 (let ((fe (org-read-agenda-file-list t)) b u)
16547 (while (setq b (find-buffer-visiting org-agenda-files))
16548 (kill-buffer b))
16549 (with-temp-file org-agenda-files
16550 (insert
16551 (mapconcat
16552 (lambda (f) ;; Keep un-expanded entries.
16553 (if (setq u (assoc f fe))
16554 (cdr u)
16556 list "\n")
16557 "\n")))
16558 (let ((org-mode-hook nil) (org-inhibit-startup t)
16559 (org-insert-mode-line-in-empty-file nil))
16560 (setq org-agenda-files list)
16561 (customize-save-variable 'org-agenda-files org-agenda-files))))
16563 (defun org-read-agenda-file-list (&optional pair-with-expansion)
16564 "Read the list of agenda files from a file.
16565 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
16566 filenames, used by `org-store-new-agenda-file-list' to write back
16567 un-expanded file names."
16568 (when (file-directory-p org-agenda-files)
16569 (error "`org-agenda-files' cannot be a single directory"))
16570 (when (stringp org-agenda-files)
16571 (with-temp-buffer
16572 (insert-file-contents org-agenda-files)
16573 (mapcar
16574 (lambda (f)
16575 (let ((e (expand-file-name (substitute-in-file-name f)
16576 org-directory)))
16577 (if pair-with-expansion
16578 (cons e f)
16579 e)))
16580 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
16582 ;;;###autoload
16583 (defun org-cycle-agenda-files ()
16584 "Cycle through the files in `org-agenda-files'.
16585 If the current buffer visits an agenda file, find the next one in the list.
16586 If the current buffer does not, find the first agenda file."
16587 (interactive)
16588 (let* ((fs (org-agenda-files t))
16589 (files (append fs (list (car fs))))
16590 (tcf (if buffer-file-name (file-truename buffer-file-name)))
16591 file)
16592 (unless files (error "No agenda files"))
16593 (catch 'exit
16594 (while (setq file (pop files))
16595 (if (equal (file-truename file) tcf)
16596 (when (car files)
16597 (find-file (car files))
16598 (throw 'exit t))))
16599 (find-file (car fs)))
16600 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
16602 (defun org-agenda-file-to-front (&optional to-end)
16603 "Move/add the current file to the top of the agenda file list.
16604 If the file is not present in the list, it is added to the front. If it is
16605 present, it is moved there. With optional argument TO-END, add/move to the
16606 end of the list."
16607 (interactive "P")
16608 (let ((org-agenda-skip-unavailable-files nil)
16609 (file-alist (mapcar (lambda (x)
16610 (cons (file-truename x) x))
16611 (org-agenda-files t)))
16612 (ctf (file-truename buffer-file-name))
16613 x had)
16614 (setq x (assoc ctf file-alist) had x)
16616 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
16617 (if to-end
16618 (setq file-alist (append (delq x file-alist) (list x)))
16619 (setq file-alist (cons x (delq x file-alist))))
16620 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
16621 (org-install-agenda-files-menu)
16622 (message "File %s to %s of agenda file list"
16623 (if had "moved" "added") (if to-end "end" "front"))))
16625 (defun org-remove-file (&optional file)
16626 "Remove current file from the list of files in variable `org-agenda-files'.
16627 These are the files which are being checked for agenda entries.
16628 Optional argument FILE means use this file instead of the current."
16629 (interactive)
16630 (let* ((org-agenda-skip-unavailable-files nil)
16631 (file (or file buffer-file-name))
16632 (true-file (file-truename file))
16633 (afile (abbreviate-file-name file))
16634 (files (delq nil (mapcar
16635 (lambda (x)
16636 (if (equal true-file
16637 (file-truename x))
16638 nil x))
16639 (org-agenda-files t)))))
16640 (if (not (= (length files) (length (org-agenda-files t))))
16641 (progn
16642 (org-store-new-agenda-file-list files)
16643 (org-install-agenda-files-menu)
16644 (message "Removed file: %s" afile))
16645 (message "File was not in list: %s (not removed)" afile))))
16647 (defun org-file-menu-entry (file)
16648 (vector file (list 'find-file file) t))
16650 (defun org-check-agenda-file (file)
16651 "Make sure FILE exists. If not, ask user what to do."
16652 (when (not (file-exists-p file))
16653 (message "non-existent agenda file %s. [R]emove from list or [A]bort?"
16654 (abbreviate-file-name file))
16655 (let ((r (downcase (read-char-exclusive))))
16656 (cond
16657 ((equal r ?r)
16658 (org-remove-file file)
16659 (throw 'nextfile t))
16660 (t (error "Abort"))))))
16662 (defun org-get-agenda-file-buffer (file)
16663 "Get a buffer visiting FILE. If the buffer needs to be created, add
16664 it to the list of buffers which might be released later."
16665 (let ((buf (org-find-base-buffer-visiting file)))
16666 (if buf
16667 buf ; just return it
16668 ;; Make a new buffer and remember it
16669 (setq buf (find-file-noselect file))
16670 (if buf (push buf org-agenda-new-buffers))
16671 buf)))
16673 (defun org-release-buffers (blist)
16674 "Release all buffers in list, asking the user for confirmation when needed.
16675 When a buffer is unmodified, it is just killed. When modified, it is saved
16676 \(if the user agrees) and then killed."
16677 (let (buf file)
16678 (while (setq buf (pop blist))
16679 (setq file (buffer-file-name buf))
16680 (when (and (buffer-modified-p buf)
16681 file
16682 (y-or-n-p (format "Save file %s? " file)))
16683 (with-current-buffer buf (save-buffer)))
16684 (kill-buffer buf))))
16686 (defun org-prepare-agenda-buffers (files)
16687 "Create buffers for all agenda files, protect archived trees and comments."
16688 (interactive)
16689 (let ((pa '(:org-archived t))
16690 (pc '(:org-comment t))
16691 (pall '(:org-archived t :org-comment t))
16692 (inhibit-read-only t)
16693 (rea (concat ":" org-archive-tag ":"))
16694 bmp file re)
16695 (save-excursion
16696 (save-restriction
16697 (while (setq file (pop files))
16698 (catch 'nextfile
16699 (if (bufferp file)
16700 (set-buffer file)
16701 (org-check-agenda-file file)
16702 (set-buffer (org-get-agenda-file-buffer file)))
16703 (widen)
16704 (setq bmp (buffer-modified-p))
16705 (org-refresh-category-properties)
16706 (setq org-todo-keywords-for-agenda
16707 (append org-todo-keywords-for-agenda org-todo-keywords-1))
16708 (setq org-done-keywords-for-agenda
16709 (append org-done-keywords-for-agenda org-done-keywords))
16710 (setq org-todo-keyword-alist-for-agenda
16711 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
16712 (setq org-drawers-for-agenda
16713 (append org-drawers-for-agenda org-drawers))
16714 (setq org-tag-alist-for-agenda
16715 (append org-tag-alist-for-agenda org-tag-alist))
16717 (save-excursion
16718 (remove-text-properties (point-min) (point-max) pall)
16719 (when org-agenda-skip-archived-trees
16720 (goto-char (point-min))
16721 (while (re-search-forward rea nil t)
16722 (if (org-at-heading-p t)
16723 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
16724 (goto-char (point-min))
16725 (setq re (format org-heading-keyword-regexp-format
16726 org-comment-string))
16727 (while (re-search-forward re nil t)
16728 (add-text-properties
16729 (match-beginning 0) (org-end-of-subtree t) pc)))
16730 (set-buffer-modified-p bmp)))))
16731 (setq org-todo-keywords-for-agenda
16732 (org-uniquify org-todo-keywords-for-agenda))
16733 (setq org-todo-keyword-alist-for-agenda
16734 (org-uniquify org-todo-keyword-alist-for-agenda)
16735 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
16737 ;;;; Embedded LaTeX
16739 (defvar org-cdlatex-mode-map (make-sparse-keymap)
16740 "Keymap for the minor `org-cdlatex-mode'.")
16742 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
16743 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
16744 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
16745 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
16746 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
16748 (defvar org-cdlatex-texmathp-advice-is-done nil
16749 "Flag remembering if we have applied the advice to texmathp already.")
16751 (define-minor-mode org-cdlatex-mode
16752 "Toggle the minor `org-cdlatex-mode'.
16753 This mode supports entering LaTeX environment and math in LaTeX fragments
16754 in Org-mode.
16755 \\{org-cdlatex-mode-map}"
16756 nil " OCDL" nil
16757 (when org-cdlatex-mode
16758 (require 'cdlatex)
16759 (run-hooks 'cdlatex-mode-hook)
16760 (cdlatex-compute-tables))
16761 (unless org-cdlatex-texmathp-advice-is-done
16762 (setq org-cdlatex-texmathp-advice-is-done t)
16763 (defadvice texmathp (around org-math-always-on activate)
16764 "Always return t in org-mode buffers.
16765 This is because we want to insert math symbols without dollars even outside
16766 the LaTeX math segments. If Orgmode thinks that point is actually inside
16767 an embedded LaTeX fragment, let texmathp do its job.
16768 \\[org-cdlatex-mode-map]"
16769 (interactive)
16770 (let (p)
16771 (cond
16772 ((not (derived-mode-p 'org-mode)) ad-do-it)
16773 ((eq this-command 'cdlatex-math-symbol)
16774 (setq ad-return-value t
16775 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
16777 (let ((p (org-inside-LaTeX-fragment-p)))
16778 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
16779 (setq ad-return-value t
16780 texmathp-why '("Org-mode embedded math" . 0))
16781 (if p ad-do-it)))))))))
16783 (defun turn-on-org-cdlatex ()
16784 "Unconditionally turn on `org-cdlatex-mode'."
16785 (org-cdlatex-mode 1))
16787 (defun org-inside-LaTeX-fragment-p ()
16788 "Test if point is inside a LaTeX fragment.
16789 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
16790 sequence appearing also before point.
16791 Even though the matchers for math are configurable, this function assumes
16792 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
16793 delimiters are skipped when they have been removed by customization.
16794 The return value is nil, or a cons cell with the delimiter and the
16795 position of this delimiter.
16797 This function does a reasonably good job, but can locally be fooled by
16798 for example currency specifications. For example it will assume being in
16799 inline math after \"$22.34\". The LaTeX fragment formatter will only format
16800 fragments that are properly closed, but during editing, we have to live
16801 with the uncertainty caused by missing closing delimiters. This function
16802 looks only before point, not after."
16803 (catch 'exit
16804 (let ((pos (point))
16805 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
16806 (lim (progn
16807 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
16808 (point)))
16809 dd-on str (start 0) m re)
16810 (goto-char pos)
16811 (when dodollar
16812 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
16813 re (nth 1 (assoc "$" org-latex-regexps)))
16814 (while (string-match re str start)
16815 (cond
16816 ((= (match-end 0) (length str))
16817 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
16818 ((= (match-end 0) (- (length str) 5))
16819 (throw 'exit nil))
16820 (t (setq start (match-end 0))))))
16821 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
16822 (goto-char pos)
16823 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
16824 (and (match-beginning 2) (throw 'exit nil))
16825 ;; count $$
16826 (while (re-search-backward "\\$\\$" lim t)
16827 (setq dd-on (not dd-on)))
16828 (goto-char pos)
16829 (if dd-on (cons "$$" m))))))
16831 (defun org-inside-latex-macro-p ()
16832 "Is point inside a LaTeX macro or its arguments?"
16833 (save-match-data
16834 (org-in-regexp
16835 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
16837 (defun org-try-cdlatex-tab ()
16838 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
16839 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
16840 - inside a LaTeX fragment, or
16841 - after the first word in a line, where an abbreviation expansion could
16842 insert a LaTeX environment."
16843 (when org-cdlatex-mode
16844 (cond
16845 ;; Before any word on the line: No expansion possible.
16846 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
16847 ;; Just after first word on the line: Expand it. Make sure it
16848 ;; cannot happen on headlines, though.
16849 ((save-excursion
16850 (skip-chars-backward "a-zA-Z0-9*")
16851 (skip-chars-backward " \t")
16852 (and (bolp) (not (org-at-heading-p))))
16853 (cdlatex-tab) t)
16854 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
16856 (defun org-cdlatex-underscore-caret (&optional arg)
16857 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
16858 Revert to the normal definition outside of these fragments."
16859 (interactive "P")
16860 (if (org-inside-LaTeX-fragment-p)
16861 (call-interactively 'cdlatex-sub-superscript)
16862 (let (org-cdlatex-mode)
16863 (call-interactively (key-binding (vector last-input-event))))))
16865 (defun org-cdlatex-math-modify (&optional arg)
16866 "Execute `cdlatex-math-modify' in LaTeX fragments.
16867 Revert to the normal definition outside of these fragments."
16868 (interactive "P")
16869 (if (org-inside-LaTeX-fragment-p)
16870 (call-interactively 'cdlatex-math-modify)
16871 (let (org-cdlatex-mode)
16872 (call-interactively (key-binding (vector last-input-event))))))
16874 (defvar org-latex-fragment-image-overlays nil
16875 "List of overlays carrying the images of latex fragments.")
16876 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
16878 (defun org-remove-latex-fragment-image-overlays ()
16879 "Remove all overlays with LaTeX fragment images in current buffer."
16880 (mapc 'delete-overlay org-latex-fragment-image-overlays)
16881 (setq org-latex-fragment-image-overlays nil))
16883 (defun org-preview-latex-fragment (&optional subtree)
16884 "Preview the LaTeX fragment at point, or all locally or globally.
16885 If the cursor is in a LaTeX fragment, create the image and overlay
16886 it over the source code. If there is no fragment at point, display
16887 all fragments in the current text, from one headline to the next. With
16888 prefix SUBTREE, display all fragments in the current subtree. With a
16889 double prefix arg \\[universal-argument] \\[universal-argument], or when \
16890 the cursor is before the first headline,
16891 display all fragments in the buffer.
16892 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
16893 (interactive "P")
16894 (unless buffer-file-name
16895 (error "Can't preview LaTeX fragment in a non-file buffer"))
16896 (org-remove-latex-fragment-image-overlays)
16897 (save-excursion
16898 (save-restriction
16899 (let (beg end at msg)
16900 (cond
16901 ((or (equal subtree '(16))
16902 (not (save-excursion
16903 (re-search-backward org-outline-regexp-bol nil t))))
16904 (setq beg (point-min) end (point-max)
16905 msg "Creating images for buffer...%s"))
16906 ((equal subtree '(4))
16907 (org-back-to-heading)
16908 (setq beg (point) end (org-end-of-subtree t)
16909 msg "Creating images for subtree...%s"))
16911 (if (setq at (org-inside-LaTeX-fragment-p))
16912 (goto-char (max (point-min) (- (cdr at) 2)))
16913 (org-back-to-heading))
16914 (setq beg (point) end (progn (outline-next-heading) (point))
16915 msg (if at "Creating image...%s"
16916 "Creating images for entry...%s"))))
16917 (message msg "")
16918 (narrow-to-region beg end)
16919 (goto-char beg)
16920 (org-format-latex
16921 (concat "ltxpng/" (file-name-sans-extension
16922 (file-name-nondirectory
16923 buffer-file-name)))
16924 default-directory 'overlays msg at 'forbuffer
16925 org-latex-create-formula-image-program)
16926 (message msg "done. Use `C-c C-c' to remove images.")))))
16928 (defvar org-latex-regexps
16929 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
16930 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
16931 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
16932 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
16933 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
16934 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
16935 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
16936 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
16937 "Regular expressions for matching embedded LaTeX.")
16939 (defvar org-export-have-math nil) ;; dynamic scoping
16940 (defun org-format-latex (prefix &optional dir overlays msg at
16941 forbuffer processing-type)
16942 "Replace LaTeX fragments with links to an image, and produce images.
16943 Some of the options can be changed using the variable
16944 `org-format-latex-options'."
16945 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
16946 (let* ((prefixnodir (file-name-nondirectory prefix))
16947 (absprefix (expand-file-name prefix dir))
16948 (todir (file-name-directory absprefix))
16949 (opt org-format-latex-options)
16950 (matchers (plist-get opt :matchers))
16951 (re-list org-latex-regexps)
16952 (org-format-latex-header-extra
16953 (plist-get (org-infile-export-plist) :latex-header-extra))
16954 (cnt 0) txt hash link beg end re e checkdir
16955 executables-checked string
16956 m n block-type block linkfile movefile ov)
16957 ;; Check the different regular expressions
16958 (while (setq e (pop re-list))
16959 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
16960 block (if block-type "\n\n" ""))
16961 (when (member m matchers)
16962 (goto-char (point-min))
16963 (while (re-search-forward re nil t)
16964 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
16965 (not (get-text-property (match-beginning n)
16966 'org-protected))
16967 (or (not overlays)
16968 (not (eq (get-char-property (match-beginning n)
16969 'org-overlay-type)
16970 'org-latex-overlay))))
16971 (setq org-export-have-math t)
16972 (cond
16973 ((eq processing-type 'verbatim)
16974 ;; Leave the text verbatim, just protect it
16975 (add-text-properties (match-beginning n) (match-end n)
16976 '(org-protected t)))
16977 ((eq processing-type 'mathjax)
16978 ;; Prepare for MathJax processing
16979 (setq string (match-string n))
16980 (if (member m '("$" "$1"))
16981 (save-excursion
16982 (delete-region (match-beginning n) (match-end n))
16983 (goto-char (match-beginning n))
16984 (insert (org-add-props (concat "\\(" (substring string 1 -1)
16985 "\\)")
16986 '(org-protected t))))
16987 (add-text-properties (match-beginning n) (match-end n)
16988 '(org-protected t))))
16989 ((or (eq processing-type 'dvipng)
16990 (eq processing-type 'imagemagick))
16991 ;; Process to an image
16992 (setq txt (match-string n)
16993 beg (match-beginning n) end (match-end n)
16994 cnt (1+ cnt))
16995 (let (print-length print-level) ; make sure full list is printed
16996 (setq hash (sha1 (prin1-to-string
16997 (list org-format-latex-header
16998 org-format-latex-header-extra
16999 org-export-latex-default-packages-alist
17000 org-export-latex-packages-alist
17001 org-format-latex-options
17002 forbuffer txt)))
17003 linkfile (format "%s_%s.png" prefix hash)
17004 movefile (format "%s_%s.png" absprefix hash)))
17005 (setq link (concat block "[[file:" linkfile "]]" block))
17006 (if msg (message msg cnt))
17007 (goto-char beg)
17008 (unless checkdir ; make sure the directory exists
17009 (setq checkdir t)
17010 (or (file-directory-p todir) (make-directory todir t)))
17011 (cond
17012 ((eq processing-type 'dvipng)
17013 (unless executables-checked
17014 (org-check-external-command
17015 "latex" "needed to convert LaTeX fragments to images")
17016 (org-check-external-command
17017 "dvipng" "needed to convert LaTeX fragments to images")
17018 (setq executables-checked t))
17019 (unless (file-exists-p movefile)
17020 (org-create-formula-image-with-dvipng
17021 txt movefile opt forbuffer)))
17022 ((eq processing-type 'imagemagick)
17023 (unless executables-checked
17024 (org-check-external-command
17025 "converte" "you need to install imagemagick")
17026 (setq executables-checked t))
17027 (unless (file-exists-p movefile)
17028 (org-create-formula-image-with-imagemagick
17029 txt movefile opt forbuffer))))
17030 (if overlays
17031 (progn
17032 (mapc (lambda (o)
17033 (if (eq (overlay-get o 'org-overlay-type)
17034 'org-latex-overlay)
17035 (delete-overlay o)))
17036 (overlays-in beg end))
17037 (setq ov (make-overlay beg end))
17038 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
17039 (if (featurep 'xemacs)
17040 (progn
17041 (overlay-put ov 'invisible t)
17042 (overlay-put
17043 ov 'end-glyph
17044 (make-glyph (vector 'png :file movefile))))
17045 (overlay-put
17046 ov 'display
17047 (list 'image :type 'png :file movefile :ascent 'center)))
17048 (push ov org-latex-fragment-image-overlays)
17049 (goto-char end))
17050 (delete-region beg end)
17051 (insert (org-add-props link
17052 (list 'org-latex-src
17053 (replace-regexp-in-string
17054 "\"" "" txt)
17055 'org-latex-src-embed-type
17056 (if block-type 'paragraph 'character))))))
17057 ((eq processing-type 'mathml)
17058 ;; Process to MathML
17059 (unless executables-checked
17060 (unless (save-match-data (org-format-latex-mathml-available-p))
17061 (error "LaTeX to MathML converter not configured"))
17062 (setq executables-checked t))
17063 (setq txt (match-string n)
17064 beg (match-beginning n) end (match-end n)
17065 cnt (1+ cnt))
17066 (if msg (message msg cnt))
17067 (goto-char beg)
17068 (delete-region beg end)
17069 (insert (org-format-latex-as-mathml
17070 txt block-type prefix dir)))
17072 (error "Unknown conversion type %s for latex fragments"
17073 processing-type)))))))))
17075 (defun org-create-math-formula (latex-frag &optional mathml-file)
17076 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
17077 Use `org-latex-to-mathml-convert-command'. If the conversion is
17078 sucessful, return the portion between \"<math...> </math>\"
17079 elements otherwise return nil. When MATHML-FILE is specified,
17080 write the results in to that file. When invoked as an
17081 interactive command, prompt for LATEX-FRAG, with initial value
17082 set to the current active region and echo the results for user
17083 inspection."
17084 (interactive (list (let ((frag (when (region-active-p)
17085 (buffer-substring-no-properties
17086 (region-beginning) (region-end)))))
17087 (read-string "LaTeX Fragment: " frag nil frag))))
17088 (unless latex-frag (error "Invalid latex-frag"))
17089 (let* ((tmp-in-file (file-relative-name
17090 (make-temp-name (expand-file-name "ltxmathml-in"))))
17091 (ignore (write-region latex-frag nil tmp-in-file))
17092 (tmp-out-file (file-relative-name
17093 (make-temp-name (expand-file-name "ltxmathml-out"))))
17094 (cmd (format-spec
17095 org-latex-to-mathml-convert-command
17096 `((?j . ,(shell-quote-argument
17097 (expand-file-name org-latex-to-mathml-jar-file)))
17098 (?I . ,(shell-quote-argument tmp-in-file))
17099 (?o . ,(shell-quote-argument tmp-out-file)))))
17100 mathml shell-command-output)
17101 (when (org-called-interactively-p 'any)
17102 (unless (org-format-latex-mathml-available-p)
17103 (error "LaTeX to MathML converter not configured")))
17104 (message "Running %s" cmd)
17105 (setq shell-command-output (shell-command-to-string cmd))
17106 (setq mathml
17107 (when (file-readable-p tmp-out-file)
17108 (with-current-buffer (find-file-noselect tmp-out-file t)
17109 (goto-char (point-min))
17110 (when (re-search-forward
17111 (concat
17112 (regexp-quote
17113 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
17114 "\\(.\\|\n\\)*"
17115 (regexp-quote "</math>")) nil t)
17116 (prog1 (match-string 0) (kill-buffer))))))
17117 (cond
17118 (mathml
17119 (setq mathml
17120 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
17121 (when mathml-file
17122 (write-region mathml nil mathml-file))
17123 (when (org-called-interactively-p 'any)
17124 (message mathml)))
17125 ((message "LaTeX to MathML conversion failed")
17126 (message shell-command-output)))
17127 (delete-file tmp-in-file)
17128 (when (file-exists-p tmp-out-file)
17129 (delete-file tmp-out-file))
17130 mathml))
17132 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
17133 prefix &optional dir)
17134 "Use `org-create-math-formula' but check local cache first."
17135 (let* ((absprefix (expand-file-name prefix dir))
17136 (print-length nil) (print-level nil)
17137 (formula-id (concat
17138 "formula-"
17139 (sha1
17140 (prin1-to-string
17141 (list latex-frag
17142 org-latex-to-mathml-convert-command)))))
17143 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
17144 (formula-cache-dir (file-name-directory formula-cache)))
17146 (unless (file-directory-p formula-cache-dir)
17147 (make-directory formula-cache-dir t))
17149 (unless (file-exists-p formula-cache)
17150 (org-create-math-formula latex-frag formula-cache))
17152 (if (file-exists-p formula-cache)
17153 ;; Successful conversion. Return the link to MathML file.
17154 (org-add-props
17155 (format "[[file:%s]]" (file-relative-name formula-cache dir))
17156 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
17157 'org-latex-src-embed-type (if latex-frag-type
17158 'paragraph 'character)))
17159 ;; Failed conversion. Return the LaTeX fragment verbatim
17160 (add-text-properties
17161 0 (1- (length latex-frag)) '(org-protected t) latex-frag)
17162 latex-frag)))
17164 ;; This function borrows from Ganesh Swami's latex2png.el
17165 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
17166 "This calls dvipng."
17167 (require 'org-latex)
17168 (let* ((tmpdir (if (featurep 'xemacs)
17169 (temp-directory)
17170 temporary-file-directory))
17171 (texfilebase (make-temp-name
17172 (expand-file-name "orgtex" tmpdir)))
17173 (texfile (concat texfilebase ".tex"))
17174 (dvifile (concat texfilebase ".dvi"))
17175 (pngfile (concat texfilebase ".png"))
17176 (fnh (if (featurep 'xemacs)
17177 (font-height (face-font 'default))
17178 (face-attribute 'default :height nil)))
17179 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17180 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17181 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17182 "Black"))
17183 (bg (or (plist-get options (if buffer :background :html-background))
17184 "Transparent")))
17185 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
17186 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
17187 (with-temp-file texfile
17188 (insert (org-splice-latex-header
17189 org-format-latex-header
17190 org-export-latex-default-packages-alist
17191 org-export-latex-packages-alist t
17192 org-format-latex-header-extra))
17193 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")
17194 (require 'org-latex)
17195 (org-export-latex-fix-inputenc))
17196 (let ((dir default-directory))
17197 (condition-case nil
17198 (progn
17199 (cd tmpdir)
17200 (call-process "latex" nil nil nil texfile))
17201 (error nil))
17202 (cd dir))
17203 (if (not (file-exists-p dvifile))
17204 (progn (message "Failed to create dvi file from %s" texfile) nil)
17205 (condition-case nil
17206 (if (featurep 'xemacs)
17207 (call-process "dvipng" nil nil nil
17208 "-fg" fg "-bg" bg
17209 "-T" "tight"
17210 "-o" pngfile
17211 dvifile)
17212 (call-process "dvipng" nil nil nil
17213 "-fg" fg "-bg" bg
17214 "-D" dpi
17215 ;;"-x" scale "-y" scale
17216 "-T" "tight"
17217 "-o" pngfile
17218 dvifile))
17219 (error nil))
17220 (if (not (file-exists-p pngfile))
17221 (if org-format-latex-signal-error
17222 (error "Failed to create png file from %s" texfile)
17223 (message "Failed to create png file from %s" texfile)
17224 nil)
17225 ;; Use the requested file name and clean up
17226 (copy-file pngfile tofile 'replace)
17227 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
17228 (delete-file (concat texfilebase e)))
17229 pngfile))))
17231 (defvar org-latex-to-pdf-process) ;; Defined in org-latex.el
17232 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
17233 "This calls convert, which is included into imagemagick."
17234 (require 'org-latex)
17235 (let* ((tmpdir (if (featurep 'xemacs)
17236 (temp-directory)
17237 temporary-file-directory))
17238 (texfilebase (make-temp-name
17239 (expand-file-name "orgtex" tmpdir)))
17240 (texfile (concat texfilebase ".tex"))
17241 (pdffile (concat texfilebase ".pdf"))
17242 (pngfile (concat texfilebase ".png"))
17243 (fnh (if (featurep 'xemacs)
17244 (font-height (face-font 'default))
17245 (face-attribute 'default :height nil)))
17246 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17247 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17248 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17249 "black"))
17250 (bg (or (plist-get options (if buffer :background :html-background))
17251 "white")))
17252 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
17253 (setq fg (org-latex-color-format fg)))
17254 (if (eq bg 'default) (setq bg (org-latex-color :background))
17255 (setq bg (org-latex-color-format
17256 (if (string= bg "Transparent")(setq bg "white")))))
17257 (with-temp-file texfile
17258 (insert (org-splice-latex-header
17259 org-format-latex-header
17260 org-export-latex-default-packages-alist
17261 org-export-latex-packages-alist t
17262 org-format-latex-header-extra))
17263 (insert "\n\\begin{document}\n"
17264 "\\definecolor{fg}{rgb}{" fg "}\n"
17265 "\\definecolor{bg}{rgb}{" bg "}\n"
17266 "\n\\pagecolor{bg}\n"
17267 "\n{\\color{fg}\n"
17268 string
17269 "\n}\n"
17270 "\n\\end{document}\n" )
17271 (require 'org-latex)
17272 (org-export-latex-fix-inputenc))
17273 (let ((dir default-directory) cmd cmds latex-frags-cmds)
17274 (condition-case nil
17275 (progn
17276 (cd tmpdir)
17277 (setq cmds org-latex-to-pdf-process)
17278 (while cmds
17279 (setq latex-frags-cmds (pop cmds))
17280 (if (listp latex-frags-cmds)
17281 (setq cmds nil)
17282 (setq latex-frags-cmds (list (car org-latex-to-pdf-process)))))
17283 (while latex-frags-cmds
17284 (setq cmd (pop latex-frags-cmds))
17285 (while (string-match "%b" cmd)
17286 (setq cmd (replace-match
17287 (save-match-data
17288 (shell-quote-argument texfile))
17289 t t cmd)))
17290 (while (string-match "%f" cmd)
17291 (setq cmd (replace-match
17292 (save-match-data
17293 (shell-quote-argument (file-name-nondirectory texfile)))
17294 t t cmd)))
17295 (while (string-match "%o" cmd)
17296 (setq cmd (replace-match
17297 (save-match-data
17298 (shell-quote-argument (file-name-directory texfile)))
17299 t t cmd)))
17300 (shell-command cmd)))
17301 (error nil))
17302 (cd dir))
17303 (if (not (file-exists-p pdffile))
17304 (progn (message "Failed to create pdf file from %s" texfile) nil)
17305 (condition-case nil
17306 (if (featurep 'xemacs)
17307 (call-process "convert" nil nil nil
17308 "-density" "96"
17309 "-trim"
17310 "-antialias"
17311 pdffile
17312 "-quality" "100"
17313 ;; "-sharpen" "0x1.0"
17314 pngfile)
17315 (call-process "convert" nil nil nil
17316 "-density" dpi
17317 "-trim"
17318 "-antialias"
17319 pdffile
17320 "-quality" "100"
17321 ; "-sharpen" "0x1.0"
17322 pngfile))
17323 (error nil))
17324 (if (not (file-exists-p pngfile))
17325 (if org-format-latex-signal-error
17326 (error "Failed to create png file from %s" texfile)
17327 (message "Failed to create png file from %s" texfile)
17328 nil)
17329 ;; Use the requested file name and clean up
17330 (copy-file pngfile tofile 'replace)
17331 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
17332 (delete-file (concat texfilebase e)))
17333 pngfile))))
17335 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
17336 "Fill a LaTeX header template TPL.
17337 In the template, the following place holders will be recognized:
17339 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
17340 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
17341 [PACKAGES] \\usepackage statements for PKG
17342 [NO-PACKAGES] do not include PKG
17343 [EXTRA] the string EXTRA
17344 [NO-EXTRA] do not include EXTRA
17346 For backward compatibility, if both the positive and the negative place
17347 holder is missing, the positive one (without the \"NO-\") will be
17348 assumed to be present at the end of the template.
17349 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
17350 EXTRA is a string.
17351 SNIPPETS-P indicates if this is run to create snippet images for HTML."
17352 (let (rpl (end ""))
17353 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
17354 (setq rpl (if (or (match-end 1) (not def-pkg))
17355 "" (org-latex-packages-to-string def-pkg snippets-p t))
17356 tpl (replace-match rpl t t tpl))
17357 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
17359 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
17360 (setq rpl (if (or (match-end 1) (not pkg))
17361 "" (org-latex-packages-to-string pkg snippets-p t))
17362 tpl (replace-match rpl t t tpl))
17363 (if pkg (setq end
17364 (concat end "\n"
17365 (org-latex-packages-to-string pkg snippets-p)))))
17367 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
17368 (setq rpl (if (or (match-end 1) (not extra))
17369 "" (concat extra "\n"))
17370 tpl (replace-match rpl t t tpl))
17371 (if (and extra (string-match "\\S-" extra))
17372 (setq end (concat end "\n" extra))))
17374 (if (string-match "\\S-" end)
17375 (concat tpl "\n" end)
17376 tpl)))
17378 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
17379 "Turn an alist of packages into a string with the \\usepackage macros."
17380 (setq pkg (mapconcat (lambda(p)
17381 (cond
17382 ((stringp p) p)
17383 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
17384 (format "%% Package %s omitted" (cadr p)))
17385 ((equal "" (car p))
17386 (format "\\usepackage{%s}" (cadr p)))
17388 (format "\\usepackage[%s]{%s}"
17389 (car p) (cadr p)))))
17391 "\n"))
17392 (if newline (concat pkg "\n") pkg))
17394 (defun org-dvipng-color (attr)
17395 "Return a RGB color specification for dvipng."
17396 (apply 'format "rgb %s %s %s"
17397 (mapcar 'org-normalize-color
17398 (if (featurep 'xemacs)
17399 (color-rgb-components
17400 (face-property 'default
17401 (cond ((eq attr :foreground) 'foreground)
17402 ((eq attr :background) 'background))))
17403 (color-values (face-attribute 'default attr nil))))))
17405 (defun org-latex-color (attr)
17406 "Return a RGB color for the LaTeX color package."
17407 (apply 'format "%s,%s,%s"
17408 (mapcar 'org-normalize-color
17409 (if (featurep 'xemacs)
17410 (color-rgb-components
17411 (face-property 'default
17412 (cond ((eq attr :foreground) 'foreground)
17413 ((eq attr :background) 'background))))
17414 (color-values (face-attribute 'default attr nil))))))
17416 (defun org-latex-color-format (color-name)
17417 "Convert COLOR-NAME to a RGB color value."
17418 (apply 'format "%s,%s,%s"
17419 (mapcar 'org-normalize-color
17420 (color-values color-name))))
17422 (defun org-normalize-color (value)
17423 "Return string to be used as color value for an RGB component."
17424 (format "%g" (/ value 65535.0)))
17426 ;; Image display
17429 (defvar org-inline-image-overlays nil)
17430 (make-variable-buffer-local 'org-inline-image-overlays)
17432 (defun org-toggle-inline-images (&optional include-linked)
17433 "Toggle the display of inline images.
17434 INCLUDE-LINKED is passed to `org-display-inline-images'."
17435 (interactive "P")
17436 (if org-inline-image-overlays
17437 (progn
17438 (org-remove-inline-images)
17439 (message "Inline image display turned off"))
17440 (org-display-inline-images include-linked)
17441 (if org-inline-image-overlays
17442 (message "%d images displayed inline"
17443 (length org-inline-image-overlays))
17444 (message "No images to display inline"))))
17446 (defun org-display-inline-images (&optional include-linked refresh beg end)
17447 "Display inline images.
17448 Normally only links without a description part are inlined, because this
17449 is how it will work for export. When INCLUDE-LINKED is set, also links
17450 with a description part will be inlined. This can be nice for a quick
17451 look at those images, but it does not reflect what exported files will look
17452 like.
17453 When REFRESH is set, refresh existing images between BEG and END.
17454 This will create new image displays only if necessary.
17455 BEG and END default to the buffer boundaries."
17456 (interactive "P")
17457 (unless refresh
17458 (org-remove-inline-images)
17459 (if (fboundp 'clear-image-cache) (clear-image-cache)))
17460 (save-excursion
17461 (save-restriction
17462 (widen)
17463 (setq beg (or beg (point-min)) end (or end (point-max)))
17464 (goto-char beg)
17465 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
17466 (substring (org-image-file-name-regexp) 0 -2)
17467 "\\)\\]" (if include-linked "" "\\]")))
17468 old file ov img)
17469 (while (re-search-forward re end t)
17470 (setq old (get-char-property-and-overlay (match-beginning 1)
17471 'org-image-overlay))
17472 (setq file (expand-file-name
17473 (concat (or (match-string 3) "") (match-string 4))))
17474 (when (file-exists-p file)
17475 (if (and (car-safe old) refresh)
17476 (image-refresh (overlay-get (cdr old) 'display))
17477 (setq img (save-match-data (create-image file)))
17478 (when img
17479 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
17480 (overlay-put ov 'display img)
17481 (overlay-put ov 'face 'default)
17482 (overlay-put ov 'org-image-overlay t)
17483 (overlay-put ov 'modification-hooks
17484 (list 'org-display-inline-modification-hook))
17485 (push ov org-inline-image-overlays)))))))))
17487 (defun org-display-inline-modification-hook (ov after beg end &optional len)
17488 "Remove inline-display overlay if a corresponding region is modified."
17489 (let ((inhibit-modification-hooks t))
17490 (when (and ov after)
17491 (delete ov org-inline-image-overlays)
17492 (delete-overlay ov))))
17494 (defun org-remove-inline-images ()
17495 "Remove inline display of images."
17496 (interactive)
17497 (mapc 'delete-overlay org-inline-image-overlays)
17498 (setq org-inline-image-overlays nil))
17500 ;;;; Key bindings
17502 ;; Outline functions from `outline-mode-prefix-map'
17503 ;; that can be remapped in Org:
17504 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
17505 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
17506 (define-key org-mode-map [remap outline-forward-same-level]
17507 'org-forward-same-level)
17508 (define-key org-mode-map [remap outline-backward-same-level]
17509 'org-backward-same-level)
17510 (define-key org-mode-map [remap show-branches]
17511 'org-kill-note-or-show-branches)
17512 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
17513 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
17514 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
17516 ;; Outline functions from `outline-mode-prefix-map'
17517 ;; that can not be remapped in Org:
17518 ;; - the column "key binding" shows whether the Outline function is still
17519 ;; available in Org mode on the same key that it has been bound to in
17520 ;; Outline mode:
17521 ;; - "overridden": key used for a different functionality in Org mode
17522 ;; - else: key still bound to the same Outline function in Org mode
17523 ;; | Outline function | key binding | Org replacement |
17524 ;; |------------------------------------+-------------+-----------------------|
17525 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
17526 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
17527 ;; | `show-children' | `C-c C-i' | visibility cycling |
17528 ;; | `hide-subtree' | overridden | visibility cycling |
17529 ;; | `outline-up-heading' | `C-c C-u' | still same function |
17530 ;; | `hide-body' | overridden | no replacement |
17531 ;; | `show-all' | overridden | no replacement |
17532 ;; | `hide-entry' | overridden | visibility cycling |
17533 ;; | `show-entry' | overridden | no replacement |
17534 ;; | `hide-leaves' | overridden | no replacement |
17535 ;; | `hide-sublevels' | overridden | no replacement |
17536 ;; | `hide-other' | overridden | no replacement |
17537 ;; | `outline-move-subtree-up' | `C-c C-^' | better: org-shiftup |
17538 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
17540 ;; Make `C-c C-x' a prefix key
17541 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
17543 ;; TAB key with modifiers
17544 (org-defkey org-mode-map "\C-i" 'org-cycle)
17545 (org-defkey org-mode-map [(tab)] 'org-cycle)
17546 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
17547 (org-defkey org-mode-map "\M-\t" 'pcomplete)
17548 ;; The following line is necessary under Suse GNU/Linux
17549 (unless (featurep 'xemacs)
17550 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
17551 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
17552 (define-key org-mode-map [backtab] 'org-shifttab)
17554 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
17555 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
17556 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
17558 ;; Cursor keys with modifiers
17559 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
17560 (org-defkey org-mode-map [(meta right)] 'org-metaright)
17561 (org-defkey org-mode-map [(meta up)] 'org-metaup)
17562 (org-defkey org-mode-map [(meta down)] 'org-metadown)
17564 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
17565 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
17566 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
17567 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
17569 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
17570 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
17571 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
17572 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
17574 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
17575 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
17576 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
17577 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
17579 ;; Babel keys
17580 (define-key org-mode-map org-babel-key-prefix org-babel-map)
17581 (mapc (lambda (pair)
17582 (define-key org-babel-map (car pair) (cdr pair)))
17583 org-babel-key-bindings)
17585 ;;; Extra keys for tty access.
17586 ;; We only set them when really needed because otherwise the
17587 ;; menus don't show the simple keys
17589 (when (or org-use-extra-keys
17590 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
17591 (not window-system))
17592 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
17593 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
17594 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
17595 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
17596 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
17597 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
17598 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
17599 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
17600 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
17601 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
17602 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
17603 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
17604 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
17605 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
17606 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
17607 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
17608 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
17609 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
17610 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
17611 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
17612 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
17613 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
17614 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
17615 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
17616 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
17617 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
17618 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
17619 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
17621 ;; All the other keys
17623 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
17624 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
17625 (if (boundp 'narrow-map)
17626 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
17627 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
17628 (if (boundp 'narrow-map)
17629 (org-defkey narrow-map "b" 'org-narrow-to-block)
17630 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
17631 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-same-level)
17632 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-same-level)
17633 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
17634 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
17635 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
17636 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
17637 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
17638 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
17639 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
17640 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
17641 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
17642 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
17643 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
17644 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
17645 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
17646 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
17647 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
17648 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
17649 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
17650 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
17651 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
17652 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
17653 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
17654 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
17655 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
17656 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
17657 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
17658 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
17659 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
17660 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
17661 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
17662 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
17663 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
17664 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
17665 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
17666 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
17667 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
17668 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
17669 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
17670 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
17671 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
17672 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
17673 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
17674 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
17675 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
17676 (org-defkey org-mode-map "\C-c^" 'org-sort)
17677 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
17678 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
17679 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
17680 (org-defkey org-mode-map "\C-m" 'org-return)
17681 (org-defkey org-mode-map "\C-j" 'org-return-indent)
17682 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
17683 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
17684 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
17685 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
17686 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
17687 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
17688 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
17689 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
17690 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
17691 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
17692 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
17693 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
17694 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
17695 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
17696 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
17697 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
17698 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
17699 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
17700 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
17701 (org-defkey org-mode-map "\C-c\C-@" 'org-mark-list)
17702 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
17703 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
17705 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
17706 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
17707 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
17708 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
17710 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
17711 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
17712 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
17713 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
17714 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
17715 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
17716 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
17717 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
17718 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
17719 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
17720 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
17721 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
17722 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
17723 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
17724 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
17725 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
17726 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
17727 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
17729 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
17730 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
17731 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
17732 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
17733 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
17735 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
17737 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
17739 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
17740 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
17742 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
17745 (when (featurep 'xemacs)
17746 (org-defkey org-mode-map 'button3 'popup-mode-menu))
17749 (defconst org-speed-commands-default
17751 ("Outline Navigation")
17752 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
17753 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
17754 ("f" . (org-speed-move-safe 'org-forward-same-level))
17755 ("b" . (org-speed-move-safe 'org-backward-same-level))
17756 ("u" . (org-speed-move-safe 'outline-up-heading))
17757 ("j" . org-goto)
17758 ("g" . (org-refile t))
17759 ("Outline Visibility")
17760 ("c" . org-cycle)
17761 ("C" . org-shifttab)
17762 (" " . org-display-outline-path)
17763 ("Outline Structure Editing")
17764 ("U" . org-shiftmetaup)
17765 ("D" . org-shiftmetadown)
17766 ("r" . org-metaright)
17767 ("l" . org-metaleft)
17768 ("R" . org-shiftmetaright)
17769 ("L" . org-shiftmetaleft)
17770 ("i" . (progn (forward-char 1) (call-interactively
17771 'org-insert-heading-respect-content)))
17772 ("^" . org-sort)
17773 ("w" . org-refile)
17774 ("a" . org-archive-subtree-default-with-confirmation)
17775 ("." . org-mark-subtree)
17776 ("Clock Commands")
17777 ("I" . org-clock-in)
17778 ("O" . org-clock-out)
17779 ("Meta Data Editing")
17780 ("t" . org-todo)
17781 ("0" . (org-priority ?\ ))
17782 ("1" . (org-priority ?A))
17783 ("2" . (org-priority ?B))
17784 ("3" . (org-priority ?C))
17785 (";" . org-set-tags-command)
17786 ("e" . org-set-effort)
17787 ("Agenda Views etc")
17788 ("v" . org-agenda)
17789 ("/" . org-sparse-tree)
17790 ("Misc")
17791 ("o" . org-open-at-point)
17792 ("?" . org-speed-command-help)
17793 ("<" . (org-agenda-set-restriction-lock 'subtree))
17794 (">" . (org-agenda-remove-restriction-lock))
17796 "The default speed commands.")
17798 (defun org-print-speed-command (e)
17799 (if (> (length (car e)) 1)
17800 (progn
17801 (princ "\n")
17802 (princ (car e))
17803 (princ "\n")
17804 (princ (make-string (length (car e)) ?-))
17805 (princ "\n"))
17806 (princ (car e))
17807 (princ " ")
17808 (if (symbolp (cdr e))
17809 (princ (symbol-name (cdr e)))
17810 (prin1 (cdr e)))
17811 (princ "\n")))
17813 (defun org-speed-command-help ()
17814 "Show the available speed commands."
17815 (interactive)
17816 (if (not org-use-speed-commands)
17817 (error "Speed commands are not activated, customize `org-use-speed-commands'")
17818 (with-output-to-temp-buffer "*Help*"
17819 (princ "User-defined Speed commands\n===========================\n")
17820 (mapc 'org-print-speed-command org-speed-commands-user)
17821 (princ "\n")
17822 (princ "Built-in Speed commands\n=======================\n")
17823 (mapc 'org-print-speed-command org-speed-commands-default))
17824 (with-current-buffer "*Help*"
17825 (setq truncate-lines t))))
17827 (defun org-speed-move-safe (cmd)
17828 "Execute CMD, but make sure that the cursor always ends up in a headline.
17829 If not, return to the original position and throw an error."
17830 (interactive)
17831 (let ((pos (point)))
17832 (call-interactively cmd)
17833 (unless (and (bolp) (org-at-heading-p))
17834 (goto-char pos)
17835 (error "Boundary reached while executing %s" cmd))))
17837 (defvar org-self-insert-command-undo-counter 0)
17839 (defvar org-table-auto-blank-field) ; defined in org-table.el
17840 (defvar org-speed-command nil)
17842 (defun org-speed-command-default-hook (keys)
17843 "Hook for activating single-letter speed commands.
17844 `org-speed-commands-default' specifies a minimal command set.
17845 Use `org-speed-commands-user' for further customization."
17846 (when (or (and (bolp) (looking-at org-outline-regexp))
17847 (and (functionp org-use-speed-commands)
17848 (funcall org-use-speed-commands)))
17849 (cdr (assoc keys (append org-speed-commands-user
17850 org-speed-commands-default)))))
17852 (defun org-babel-speed-command-hook (keys)
17853 "Hook for activating single-letter code block commands."
17854 (when (and (bolp) (looking-at org-babel-src-block-regexp))
17855 (cdr (assoc keys org-babel-key-bindings))))
17857 (defcustom org-speed-command-hook
17858 '(org-speed-command-default-hook org-babel-speed-command-hook)
17859 "Hook for activating speed commands at strategic locations.
17860 Hook functions are called in sequence until a valid handler is
17861 found.
17863 Each hook takes a single argument, a user-pressed command key
17864 which is also a `self-insert-command' from the global map.
17866 Within the hook, examine the cursor position and the command key
17867 and return nil or a valid handler as appropriate. Handler could
17868 be one of an interactive command, a function, or a form.
17870 Set `org-use-speed-commands' to non-nil value to enable this
17871 hook. The default setting is `org-speed-command-default-hook'."
17872 :group 'org-structure
17873 :version "24.1"
17874 :type 'hook)
17876 (defun org-self-insert-command (N)
17877 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
17878 If the cursor is in a table looking at whitespace, the whitespace is
17879 overwritten, and the table is not marked as requiring realignment."
17880 (interactive "p")
17881 (org-check-before-invisible-edit 'insert)
17882 (cond
17883 ((and org-use-speed-commands
17884 (setq org-speed-command
17885 (run-hook-with-args-until-success
17886 'org-speed-command-hook (this-command-keys))))
17887 (cond
17888 ((commandp org-speed-command)
17889 (setq this-command org-speed-command)
17890 (call-interactively org-speed-command))
17891 ((functionp org-speed-command)
17892 (funcall org-speed-command))
17893 ((and org-speed-command (listp org-speed-command))
17894 (eval org-speed-command))
17895 (t (let (org-use-speed-commands)
17896 (call-interactively 'org-self-insert-command)))))
17897 ((and
17898 (org-table-p)
17899 (progn
17900 ;; check if we blank the field, and if that triggers align
17901 (and (featurep 'org-table) org-table-auto-blank-field
17902 (member last-command
17903 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
17904 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
17905 ;; got extra space, this field does not determine column width
17906 (let (org-table-may-need-update) (org-table-blank-field))
17907 ;; no extra space, this field may determine column width
17908 (org-table-blank-field)))
17910 (eq N 1)
17911 (looking-at "[^|\n]* |"))
17912 (let (org-table-may-need-update)
17913 (goto-char (1- (match-end 0)))
17914 (backward-delete-char 1)
17915 (goto-char (match-beginning 0))
17916 (self-insert-command N)))
17918 (setq org-table-may-need-update t)
17919 (self-insert-command N)
17920 (org-fix-tags-on-the-fly)
17921 (if org-self-insert-cluster-for-undo
17922 (if (not (eq last-command 'org-self-insert-command))
17923 (setq org-self-insert-command-undo-counter 1)
17924 (if (>= org-self-insert-command-undo-counter 20)
17925 (setq org-self-insert-command-undo-counter 1)
17926 (and (> org-self-insert-command-undo-counter 0)
17927 buffer-undo-list (listp buffer-undo-list)
17928 (not (cadr buffer-undo-list)) ; remove nil entry
17929 (setcdr buffer-undo-list (cddr buffer-undo-list)))
17930 (setq org-self-insert-command-undo-counter
17931 (1+ org-self-insert-command-undo-counter))))))))
17933 (defun org-check-before-invisible-edit (kind)
17934 "Check is editing if kind KIND would be dangerous with invisible text around.
17935 The detailed reaction depends on the user option `org-catch-invisible-edits'."
17936 ;; First, try to get out of here as quickly as possible, to reduce overhead
17937 (if (and org-catch-invisible-edits
17938 (or (not (boundp 'visible-mode)) (not visible-mode))
17939 (or (get-char-property (point) 'invisible)
17940 (get-char-property (max (point-min) (1- (point))) 'invisible)))
17941 ;; OK, we need to take a closer look
17942 (let* ((invisible-at-point (get-char-property (point) 'invisible))
17943 (invisible-before-point (if (bobp) nil (get-char-property
17944 (1- (point)) 'invisible)))
17945 (border-and-ok-direction
17947 ;; Check if we are acting predictably before invisible text
17948 (and invisible-at-point (not invisible-before-point)
17949 (memq kind '(insert delete-backward)))
17950 ;; Check if we are acting predictably after invisible text
17951 ;; This works not well, and I have turned it off. It seems
17952 ;; better to always show and stop after invisible text.
17953 ;; (and (not invisible-at-point) invisible-before-point
17954 ;; (memq kind '(insert delete)))
17957 (when (or (memq invisible-at-point '(outline org-hide-block))
17958 (memq invisible-before-point '(outline org-hide-block)))
17959 (if (eq org-catch-invisible-edits 'error)
17960 (error "Editing in invisible areas is prohibited - make visible first"))
17961 ;; Make the area visible
17962 (save-excursion
17963 (if invisible-before-point
17964 (goto-char (previous-single-char-property-change
17965 (point) 'invisible)))
17966 (org-cycle))
17967 (cond
17968 ((eq org-catch-invisible-edits 'show)
17969 ;; That's it, we do the edit after showing
17970 (message
17971 "Unfolding invisible region around point before editing")
17972 (sit-for 1))
17973 ((and (eq org-catch-invisible-edits 'smart)
17974 border-and-ok-direction)
17975 (message "Unfolding invisible region around point before editing"))
17977 ;; Don't do the edit, make the user repeat it in full visibility
17978 (error "Edit in invisible region aborted, repeat to confirm with text visible")))))))
17980 (defun org-fix-tags-on-the-fly ()
17981 (when (and (equal (char-after (point-at-bol)) ?*)
17982 (org-at-heading-p))
17983 (org-align-tags-here org-tags-column)))
17985 (defun org-delete-backward-char (N)
17986 "Like `delete-backward-char', insert whitespace at field end in tables.
17987 When deleting backwards, in tables this function will insert whitespace in
17988 front of the next \"|\" separator, to keep the table aligned. The table will
17989 still be marked for re-alignment if the field did fill the entire column,
17990 because, in this case the deletion might narrow the column."
17991 (interactive "p")
17992 (org-check-before-invisible-edit 'delete-backward)
17993 (if (and (org-table-p)
17994 (eq N 1)
17995 (string-match "|" (buffer-substring (point-at-bol) (point)))
17996 (looking-at ".*?|"))
17997 (let ((pos (point))
17998 (noalign (looking-at "[^|\n\r]* |"))
17999 (c org-table-may-need-update))
18000 (backward-delete-char N)
18001 (if (not overwrite-mode)
18002 (progn
18003 (skip-chars-forward "^|")
18004 (insert " ")
18005 (goto-char (1- pos))))
18006 ;; noalign: if there were two spaces at the end, this field
18007 ;; does not determine the width of the column.
18008 (if noalign (setq org-table-may-need-update c)))
18009 (backward-delete-char N)
18010 (org-fix-tags-on-the-fly)))
18012 (defun org-delete-char (N)
18013 "Like `delete-char', but insert whitespace at field end in tables.
18014 When deleting characters, in tables this function will insert whitespace in
18015 front of the next \"|\" separator, to keep the table aligned. The table will
18016 still be marked for re-alignment if the field did fill the entire column,
18017 because, in this case the deletion might narrow the column."
18018 (interactive "p")
18019 (org-check-before-invisible-edit 'delete)
18020 (if (and (org-table-p)
18021 (not (bolp))
18022 (not (= (char-after) ?|))
18023 (eq N 1))
18024 (if (looking-at ".*?|")
18025 (let ((pos (point))
18026 (noalign (looking-at "[^|\n\r]* |"))
18027 (c org-table-may-need-update))
18028 (replace-match (concat
18029 (substring (match-string 0) 1 -1)
18030 " |"))
18031 (goto-char pos)
18032 ;; noalign: if there were two spaces at the end, this field
18033 ;; does not determine the width of the column.
18034 (if noalign (setq org-table-may-need-update c)))
18035 (delete-char N))
18036 (delete-char N)
18037 (org-fix-tags-on-the-fly)))
18039 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
18040 (put 'org-self-insert-command 'delete-selection t)
18041 (put 'orgtbl-self-insert-command 'delete-selection t)
18042 (put 'org-delete-char 'delete-selection 'supersede)
18043 (put 'org-delete-backward-char 'delete-selection 'supersede)
18044 (put 'org-yank 'delete-selection 'yank)
18046 ;; Make `flyspell-mode' delay after some commands
18047 (put 'org-self-insert-command 'flyspell-delayed t)
18048 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
18049 (put 'org-delete-char 'flyspell-delayed t)
18050 (put 'org-delete-backward-char 'flyspell-delayed t)
18052 ;; Make pabbrev-mode expand after org-mode commands
18053 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
18054 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
18056 ;; How to do this: Measure non-white length of current string
18057 ;; If equal to column width, we should realign.
18059 (defun org-remap (map &rest commands)
18060 "In MAP, remap the functions given in COMMANDS.
18061 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
18062 (let (new old)
18063 (while commands
18064 (setq old (pop commands) new (pop commands))
18065 (if (fboundp 'command-remapping)
18066 (org-defkey map (vector 'remap old) new)
18067 (substitute-key-definition old new map global-map)))))
18069 (when (eq org-enable-table-editor 'optimized)
18070 ;; If the user wants maximum table support, we need to hijack
18071 ;; some standard editing functions
18072 (org-remap org-mode-map
18073 'self-insert-command 'org-self-insert-command
18074 'delete-char 'org-delete-char
18075 'delete-backward-char 'org-delete-backward-char)
18076 (org-defkey org-mode-map "|" 'org-force-self-insert))
18078 (defvar org-ctrl-c-ctrl-c-hook nil
18079 "Hook for functions attaching themselves to `C-c C-c'.
18081 This can be used to add additional functionality to the C-c C-c
18082 key which executes context-dependent commands. This hook is run
18083 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
18084 run after the last test.
18086 Each function will be called with no arguments. The function
18087 must check if the context is appropriate for it to act. If yes,
18088 it should do its thing and then return a non-nil value. If the
18089 context is wrong, just do nothing and return nil.")
18091 (defvar org-ctrl-c-ctrl-c-final-hook nil
18092 "Hook for functions attaching themselves to `C-c C-c'.
18094 This can be used to add additional functionality to the C-c C-c
18095 key which executes context-dependent commands. This hook is run
18096 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
18097 before the first test.
18099 Each function will be called with no arguments. The function
18100 must check if the context is appropriate for it to act. If yes,
18101 it should do its thing and then return a non-nil value. If the
18102 context is wrong, just do nothing and return nil.")
18104 (defvar org-tab-first-hook nil
18105 "Hook for functions to attach themselves to TAB.
18106 See `org-ctrl-c-ctrl-c-hook' for more information.
18107 This hook runs as the first action when TAB is pressed, even before
18108 `org-cycle' messes around with the `outline-regexp' to cater for
18109 inline tasks and plain list item folding.
18110 If any function in this hook returns t, any other actions that
18111 would have been caused by TAB (such as table field motion or visibility
18112 cycling) will not occur.")
18114 (defvar org-tab-after-check-for-table-hook nil
18115 "Hook for functions to attach themselves to TAB.
18116 See `org-ctrl-c-ctrl-c-hook' for more information.
18117 This hook runs after it has been established that the cursor is not in a
18118 table, but before checking if the cursor is in a headline or if global cycling
18119 should be done.
18120 If any function in this hook returns t, not other actions like visibility
18121 cycling will be done.")
18123 (defvar org-tab-after-check-for-cycling-hook nil
18124 "Hook for functions to attach themselves to TAB.
18125 See `org-ctrl-c-ctrl-c-hook' for more information.
18126 This hook runs after it has been established that not table field motion and
18127 not visibility should be done because of current context. This is probably
18128 the place where a package like yasnippets can hook in.")
18130 (defvar org-tab-before-tab-emulation-hook nil
18131 "Hook for functions to attach themselves to TAB.
18132 See `org-ctrl-c-ctrl-c-hook' for more information.
18133 This hook runs after every other options for TAB have been exhausted, but
18134 before indentation and \t insertion takes place.")
18136 (defvar org-metaleft-hook nil
18137 "Hook for functions attaching themselves to `M-left'.
18138 See `org-ctrl-c-ctrl-c-hook' for more information.")
18139 (defvar org-metaright-hook nil
18140 "Hook for functions attaching themselves to `M-right'.
18141 See `org-ctrl-c-ctrl-c-hook' for more information.")
18142 (defvar org-metaup-hook nil
18143 "Hook for functions attaching themselves to `M-up'.
18144 See `org-ctrl-c-ctrl-c-hook' for more information.")
18145 (defvar org-metadown-hook nil
18146 "Hook for functions attaching themselves to `M-down'.
18147 See `org-ctrl-c-ctrl-c-hook' for more information.")
18148 (defvar org-shiftmetaleft-hook nil
18149 "Hook for functions attaching themselves to `M-S-left'.
18150 See `org-ctrl-c-ctrl-c-hook' for more information.")
18151 (defvar org-shiftmetaright-hook nil
18152 "Hook for functions attaching themselves to `M-S-right'.
18153 See `org-ctrl-c-ctrl-c-hook' for more information.")
18154 (defvar org-shiftmetaup-hook nil
18155 "Hook for functions attaching themselves to `M-S-up'.
18156 See `org-ctrl-c-ctrl-c-hook' for more information.")
18157 (defvar org-shiftmetadown-hook nil
18158 "Hook for functions attaching themselves to `M-S-down'.
18159 See `org-ctrl-c-ctrl-c-hook' for more information.")
18160 (defvar org-metareturn-hook nil
18161 "Hook for functions attaching themselves to `M-RET'.
18162 See `org-ctrl-c-ctrl-c-hook' for more information.")
18163 (defvar org-shiftup-hook nil
18164 "Hook for functions attaching themselves to `S-up'.
18165 See `org-ctrl-c-ctrl-c-hook' for more information.")
18166 (defvar org-shiftup-final-hook nil
18167 "Hook for functions attaching themselves to `S-up'.
18168 This one runs after all other options except shift-select have been excluded.
18169 See `org-ctrl-c-ctrl-c-hook' for more information.")
18170 (defvar org-shiftdown-hook nil
18171 "Hook for functions attaching themselves to `S-down'.
18172 See `org-ctrl-c-ctrl-c-hook' for more information.")
18173 (defvar org-shiftdown-final-hook nil
18174 "Hook for functions attaching themselves to `S-down'.
18175 This one runs after all other options except shift-select have been excluded.
18176 See `org-ctrl-c-ctrl-c-hook' for more information.")
18177 (defvar org-shiftleft-hook nil
18178 "Hook for functions attaching themselves to `S-left'.
18179 See `org-ctrl-c-ctrl-c-hook' for more information.")
18180 (defvar org-shiftleft-final-hook nil
18181 "Hook for functions attaching themselves to `S-left'.
18182 This one runs after all other options except shift-select have been excluded.
18183 See `org-ctrl-c-ctrl-c-hook' for more information.")
18184 (defvar org-shiftright-hook nil
18185 "Hook for functions attaching themselves to `S-right'.
18186 See `org-ctrl-c-ctrl-c-hook' for more information.")
18187 (defvar org-shiftright-final-hook nil
18188 "Hook for functions attaching themselves to `S-right'.
18189 This one runs after all other options except shift-select have been excluded.
18190 See `org-ctrl-c-ctrl-c-hook' for more information.")
18192 (defun org-modifier-cursor-error ()
18193 "Throw an error, a modified cursor command was applied in wrong context."
18194 (error "This command is active in special context like tables, headlines or items"))
18196 (defun org-shiftselect-error ()
18197 "Throw an error because Shift-Cursor command was applied in wrong context."
18198 (if (and (boundp 'shift-select-mode) shift-select-mode)
18199 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
18200 (error "This command works only in special context like headlines or timestamps")))
18202 (defun org-call-for-shift-select (cmd)
18203 (let ((this-command-keys-shift-translated t))
18204 (call-interactively cmd)))
18206 (defun org-shifttab (&optional arg)
18207 "Global visibility cycling or move to previous table field.
18208 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
18209 on context.
18210 See the individual commands for more information."
18211 (interactive "P")
18212 (cond
18213 ((org-at-table-p) (call-interactively 'org-table-previous-field))
18214 ((integerp arg)
18215 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
18216 (message "Content view to level: %d" arg)
18217 (org-content (prefix-numeric-value arg2))
18218 (setq org-cycle-global-status 'overview)))
18219 (t (call-interactively 'org-global-cycle))))
18221 (defun org-shiftmetaleft ()
18222 "Promote subtree or delete table column.
18223 Calls `org-promote-subtree', `org-outdent-item-tree', or
18224 `org-table-delete-column', depending on context. See the
18225 individual commands for more information."
18226 (interactive)
18227 (cond
18228 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
18229 ((org-at-table-p) (call-interactively 'org-table-delete-column))
18230 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
18231 ((if (not (org-region-active-p)) (org-at-item-p)
18232 (save-excursion (goto-char (region-beginning))
18233 (org-at-item-p)))
18234 (call-interactively 'org-outdent-item-tree))
18235 (t (org-modifier-cursor-error))))
18237 (defun org-shiftmetaright ()
18238 "Demote subtree or insert table column.
18239 Calls `org-demote-subtree', `org-indent-item-tree', or
18240 `org-table-insert-column', depending on context. See the
18241 individual commands for more information."
18242 (interactive)
18243 (cond
18244 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
18245 ((org-at-table-p) (call-interactively 'org-table-insert-column))
18246 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
18247 ((if (not (org-region-active-p)) (org-at-item-p)
18248 (save-excursion (goto-char (region-beginning))
18249 (org-at-item-p)))
18250 (call-interactively 'org-indent-item-tree))
18251 (t (org-modifier-cursor-error))))
18253 (defun org-shiftmetaup (&optional arg)
18254 "Move subtree up or kill table row.
18255 Calls `org-move-subtree-up' or `org-table-kill-row' or
18256 `org-move-item-up' depending on context. See the individual commands
18257 for more information."
18258 (interactive "P")
18259 (cond
18260 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
18261 ((org-at-table-p) (call-interactively 'org-table-kill-row))
18262 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18263 ((org-at-item-p) (call-interactively 'org-move-item-up))
18264 (t (org-modifier-cursor-error))))
18266 (defun org-shiftmetadown (&optional arg)
18267 "Move subtree down or insert table row.
18268 Calls `org-move-subtree-down' or `org-table-insert-row' or
18269 `org-move-item-down', depending on context. See the individual
18270 commands for more information."
18271 (interactive "P")
18272 (cond
18273 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
18274 ((org-at-table-p) (call-interactively 'org-table-insert-row))
18275 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
18276 ((org-at-item-p) (call-interactively 'org-move-item-down))
18277 (t (org-modifier-cursor-error))))
18279 (defsubst org-hidden-tree-error ()
18280 (error
18281 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
18283 (defun org-metaleft (&optional arg)
18284 "Promote heading or move table column to left.
18285 Calls `org-do-promote' or `org-table-move-column', depending on context.
18286 With no specific context, calls the Emacs default `backward-word'.
18287 See the individual commands for more information."
18288 (interactive "P")
18289 (cond
18290 ((run-hook-with-args-until-success 'org-metaleft-hook))
18291 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
18292 ((org-with-limited-levels
18293 (or (org-at-heading-p)
18294 (and (org-region-active-p)
18295 (save-excursion
18296 (goto-char (region-beginning))
18297 (org-at-heading-p)))))
18298 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18299 (call-interactively 'org-do-promote))
18300 ;; At an inline task.
18301 ((org-at-heading-p)
18302 (call-interactively 'org-inlinetask-promote))
18303 ((or (org-at-item-p)
18304 (and (org-region-active-p)
18305 (save-excursion
18306 (goto-char (region-beginning))
18307 (org-at-item-p))))
18308 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
18309 (call-interactively 'org-outdent-item))
18310 (t (call-interactively 'backward-word))))
18312 (defun org-metaright (&optional arg)
18313 "Demote a subtree, a list item or move table column to right.
18314 In front of a drawer or a block keyword, indent it correctly.
18315 With no specific context, calls the Emacs default `forward-word'.
18316 See the individual commands for more information."
18317 (interactive "P")
18318 (cond
18319 ((run-hook-with-args-until-success 'org-metaright-hook))
18320 ((org-at-table-p) (call-interactively 'org-table-move-column))
18321 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
18322 ((org-at-block-p) (call-interactively 'org-indent-block))
18323 ((org-with-limited-levels
18324 (or (org-at-heading-p)
18325 (and (org-region-active-p)
18326 (save-excursion
18327 (goto-char (region-beginning))
18328 (org-at-heading-p)))))
18329 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18330 (call-interactively 'org-do-demote))
18331 ;; At an inline task.
18332 ((org-at-heading-p)
18333 (call-interactively 'org-inlinetask-demote))
18334 ((or (org-at-item-p)
18335 (and (org-region-active-p)
18336 (save-excursion
18337 (goto-char (region-beginning))
18338 (org-at-item-p))))
18339 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
18340 (call-interactively 'org-indent-item))
18341 (t (call-interactively 'forward-word))))
18343 (defun org-check-for-hidden (what)
18344 "Check if there are hidden headlines/items in the current visual line.
18345 WHAT can be either `headlines' or `items'. If the current line is
18346 an outline or item heading and it has a folded subtree below it,
18347 this function returns t, nil otherwise."
18348 (let ((re (cond
18349 ((eq what 'headlines) org-outline-regexp-bol)
18350 ((eq what 'items) (org-item-beginning-re))
18351 (t (error "This should not happen"))))
18352 beg end)
18353 (save-excursion
18354 (catch 'exit
18355 (unless (org-region-active-p)
18356 (setq beg (point-at-bol))
18357 (beginning-of-line 2)
18358 (while (and (not (eobp)) ;; this is like `next-line'
18359 (get-char-property (1- (point)) 'invisible))
18360 (beginning-of-line 2))
18361 (setq end (point))
18362 (goto-char beg)
18363 (goto-char (point-at-eol))
18364 (setq end (max end (point)))
18365 (while (re-search-forward re end t)
18366 (if (get-char-property (match-beginning 0) 'invisible)
18367 (throw 'exit t))))
18368 nil))))
18370 (defun org-metaup (&optional arg)
18371 "Move subtree up or move table row up.
18372 Calls `org-move-subtree-up' or `org-table-move-row' or
18373 `org-move-item-up', depending on context. See the individual commands
18374 for more information."
18375 (interactive "P")
18376 (cond
18377 ((run-hook-with-args-until-success 'org-metaup-hook))
18378 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
18379 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18380 ((org-at-item-p) (call-interactively 'org-move-item-up))
18381 (t (transpose-lines 1) (beginning-of-line -1))))
18383 (defun org-metadown (&optional arg)
18384 "Move subtree down or move table row down.
18385 Calls `org-move-subtree-down' or `org-table-move-row' or
18386 `org-move-item-down', depending on context. See the individual
18387 commands for more information."
18388 (interactive "P")
18389 (cond
18390 ((run-hook-with-args-until-success 'org-metadown-hook))
18391 ((org-at-table-p) (call-interactively 'org-table-move-row))
18392 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
18393 ((org-at-item-p) (call-interactively 'org-move-item-down))
18394 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
18396 (defun org-shiftup (&optional arg)
18397 "Increase item in timestamp or increase priority of current headline.
18398 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
18399 depending on context. See the individual commands for more information."
18400 (interactive "P")
18401 (cond
18402 ((run-hook-with-args-until-success 'org-shiftup-hook))
18403 ((and org-support-shift-select (org-region-active-p))
18404 (org-call-for-shift-select 'previous-line))
18405 ((org-at-timestamp-p t)
18406 (call-interactively (if org-edit-timestamp-down-means-later
18407 'org-timestamp-down 'org-timestamp-up)))
18408 ((and (not (eq org-support-shift-select 'always))
18409 org-enable-priority-commands
18410 (org-at-heading-p))
18411 (call-interactively 'org-priority-up))
18412 ((and (not org-support-shift-select) (org-at-item-p))
18413 (call-interactively 'org-previous-item))
18414 ((org-clocktable-try-shift 'up arg))
18415 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
18416 (org-support-shift-select
18417 (org-call-for-shift-select 'previous-line))
18418 (t (org-shiftselect-error))))
18420 (defun org-shiftdown (&optional arg)
18421 "Decrease item in timestamp or decrease priority of current headline.
18422 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
18423 depending on context. See the individual commands for more information."
18424 (interactive "P")
18425 (cond
18426 ((run-hook-with-args-until-success 'org-shiftdown-hook))
18427 ((and org-support-shift-select (org-region-active-p))
18428 (org-call-for-shift-select 'next-line))
18429 ((org-at-timestamp-p t)
18430 (call-interactively (if org-edit-timestamp-down-means-later
18431 'org-timestamp-up 'org-timestamp-down)))
18432 ((and (not (eq org-support-shift-select 'always))
18433 org-enable-priority-commands
18434 (org-at-heading-p))
18435 (call-interactively 'org-priority-down))
18436 ((and (not org-support-shift-select) (org-at-item-p))
18437 (call-interactively 'org-next-item))
18438 ((org-clocktable-try-shift 'down arg))
18439 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
18440 (org-support-shift-select
18441 (org-call-for-shift-select 'next-line))
18442 (t (org-shiftselect-error))))
18444 (defun org-shiftright (&optional arg)
18445 "Cycle the thing at point or in the current line, depending on context.
18446 Depending on context, this does one of the following:
18448 - switch a timestamp at point one day into the future
18449 - on a headline, switch to the next TODO keyword.
18450 - on an item, switch entire list to the next bullet type
18451 - on a property line, switch to the next allowed value
18452 - on a clocktable definition line, move time block into the future"
18453 (interactive "P")
18454 (cond
18455 ((run-hook-with-args-until-success 'org-shiftright-hook))
18456 ((and org-support-shift-select (org-region-active-p))
18457 (org-call-for-shift-select 'forward-char))
18458 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
18459 ((and (not (eq org-support-shift-select 'always))
18460 (org-at-heading-p))
18461 (let ((org-inhibit-logging
18462 (not org-treat-S-cursor-todo-selection-as-state-change))
18463 (org-inhibit-blocking
18464 (not org-treat-S-cursor-todo-selection-as-state-change)))
18465 (org-call-with-arg 'org-todo 'right)))
18466 ((or (and org-support-shift-select
18467 (not (eq org-support-shift-select 'always))
18468 (org-at-item-bullet-p))
18469 (and (not org-support-shift-select) (org-at-item-p)))
18470 (org-call-with-arg 'org-cycle-list-bullet nil))
18471 ((and (not (eq org-support-shift-select 'always))
18472 (org-at-property-p))
18473 (call-interactively 'org-property-next-allowed-value))
18474 ((org-clocktable-try-shift 'right arg))
18475 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
18476 (org-support-shift-select
18477 (org-call-for-shift-select 'forward-char))
18478 (t (org-shiftselect-error))))
18480 (defun org-shiftleft (&optional arg)
18481 "Cycle the thing at point or in the current line, depending on context.
18482 Depending on context, this does one of the following:
18484 - switch a timestamp at point one day into the past
18485 - on a headline, switch to the previous TODO keyword.
18486 - on an item, switch entire list to the previous bullet type
18487 - on a property line, switch to the previous allowed value
18488 - on a clocktable definition line, move time block into the past"
18489 (interactive "P")
18490 (cond
18491 ((run-hook-with-args-until-success 'org-shiftleft-hook))
18492 ((and org-support-shift-select (org-region-active-p))
18493 (org-call-for-shift-select 'backward-char))
18494 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
18495 ((and (not (eq org-support-shift-select 'always))
18496 (org-at-heading-p))
18497 (let ((org-inhibit-logging
18498 (not org-treat-S-cursor-todo-selection-as-state-change))
18499 (org-inhibit-blocking
18500 (not org-treat-S-cursor-todo-selection-as-state-change)))
18501 (org-call-with-arg 'org-todo 'left)))
18502 ((or (and org-support-shift-select
18503 (not (eq org-support-shift-select 'always))
18504 (org-at-item-bullet-p))
18505 (and (not org-support-shift-select) (org-at-item-p)))
18506 (org-call-with-arg 'org-cycle-list-bullet 'previous))
18507 ((and (not (eq org-support-shift-select 'always))
18508 (org-at-property-p))
18509 (call-interactively 'org-property-previous-allowed-value))
18510 ((org-clocktable-try-shift 'left arg))
18511 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
18512 (org-support-shift-select
18513 (org-call-for-shift-select 'backward-char))
18514 (t (org-shiftselect-error))))
18516 (defun org-shiftcontrolright ()
18517 "Switch to next TODO set."
18518 (interactive)
18519 (cond
18520 ((and org-support-shift-select (org-region-active-p))
18521 (org-call-for-shift-select 'forward-word))
18522 ((and (not (eq org-support-shift-select 'always))
18523 (org-at-heading-p))
18524 (org-call-with-arg 'org-todo 'nextset))
18525 (org-support-shift-select
18526 (org-call-for-shift-select 'forward-word))
18527 (t (org-shiftselect-error))))
18529 (defun org-shiftcontrolleft ()
18530 "Switch to previous TODO set."
18531 (interactive)
18532 (cond
18533 ((and org-support-shift-select (org-region-active-p))
18534 (org-call-for-shift-select 'backward-word))
18535 ((and (not (eq org-support-shift-select 'always))
18536 (org-at-heading-p))
18537 (org-call-with-arg 'org-todo 'previousset))
18538 (org-support-shift-select
18539 (org-call-for-shift-select 'backward-word))
18540 (t (org-shiftselect-error))))
18542 (defun org-shiftcontrolup ()
18543 "Change timestamps synchronously up in CLOCK log lines."
18544 (interactive)
18545 (cond ((and (not org-support-shift-select)
18546 (org-at-clock-log-p)
18547 (org-at-timestamp-p t))
18548 (org-clock-timestamps-up))
18549 (t (org-shiftselect-error))))
18551 (defun org-shiftcontroldown ()
18552 "Change timestamps synchronously down in CLOCK log lines."
18553 (interactive)
18554 (cond ((and (not org-support-shift-select)
18555 (org-at-clock-log-p)
18556 (org-at-timestamp-p t))
18557 (org-clock-timestamps-down))
18558 (t (org-shiftselect-error))))
18560 (defun org-ctrl-c-ret ()
18561 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
18562 (interactive)
18563 (cond
18564 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
18565 (t (call-interactively 'org-insert-heading))))
18567 (defun org-find-visible ()
18568 (let ((s (point)))
18569 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
18570 (get-char-property s 'invisible)))
18572 (defun org-find-invisible ()
18573 (let ((s (point)))
18574 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
18575 (not (get-char-property s 'invisible))))
18578 (defun org-copy-visible (beg end)
18579 "Copy the visible parts of the region."
18580 (interactive "r")
18581 (let (snippets s)
18582 (save-excursion
18583 (save-restriction
18584 (narrow-to-region beg end)
18585 (setq s (goto-char (point-min)))
18586 (while (not (= (point) (point-max)))
18587 (goto-char (org-find-invisible))
18588 (push (buffer-substring s (point)) snippets)
18589 (setq s (goto-char (org-find-visible))))))
18590 (kill-new (apply 'concat (nreverse snippets)))))
18592 (defun org-copy-special ()
18593 "Copy region in table or copy current subtree.
18594 Calls `org-table-copy' or `org-copy-subtree', depending on context.
18595 See the individual commands for more information."
18596 (interactive)
18597 (call-interactively
18598 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
18600 (defun org-cut-special ()
18601 "Cut region in table or cut current subtree.
18602 Calls `org-table-copy' or `org-cut-subtree', depending on context.
18603 See the individual commands for more information."
18604 (interactive)
18605 (call-interactively
18606 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
18608 (defun org-paste-special (arg)
18609 "Paste rectangular region into table, or past subtree relative to level.
18610 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
18611 See the individual commands for more information."
18612 (interactive "P")
18613 (if (org-at-table-p)
18614 (org-table-paste-rectangle)
18615 (org-paste-subtree arg)))
18617 (defun org-edit-special (&optional arg)
18618 "Call a special editor for the stuff at point.
18619 When at a table, call the formula editor with `org-table-edit-formulas'.
18620 When at the first line of an src example, call `org-edit-src-code'.
18621 When in an #+include line, visit the include file. Otherwise call
18622 `ffap' to visit the file at point."
18623 (interactive)
18624 ;; possibly prep session before editing source
18625 (when arg
18626 (let* ((info (org-babel-get-src-block-info))
18627 (lang (nth 0 info))
18628 (params (nth 2 info))
18629 (session (cdr (assoc :session params))))
18630 (when (and info session) ;; we are in a source-code block with a session
18631 (funcall
18632 (intern (concat "org-babel-prep-session:" lang)) session params))))
18633 (cond ;; proceed with `org-edit-special'
18634 ((save-excursion
18635 (beginning-of-line 1)
18636 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
18637 (find-file (org-trim (match-string 1))))
18638 ((org-edit-src-code))
18639 ((org-edit-fixed-width-region))
18640 ((org-at-table.el-p)
18641 (org-edit-src-code))
18642 ((or (org-at-table-p)
18643 (save-excursion
18644 (beginning-of-line 1)
18645 (let ((case-fold-search )) (looking-at "[ \t]*#\\+tblfm:"))))
18646 (call-interactively 'org-table-edit-formulas))
18647 (t (call-interactively 'ffap))))
18649 (defvar org-table-coordinate-overlays) ; defined in org-table.el
18650 (defun org-ctrl-c-ctrl-c (&optional arg)
18651 "Set tags in headline, or update according to changed information at point.
18653 This command does many different things, depending on context:
18655 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
18656 this is what we do.
18658 - If the cursor is on a statistics cookie, update it.
18660 - If the cursor is in a headline, prompt for tags and insert them
18661 into the current line, aligned to `org-tags-column'. When called
18662 with prefix arg, realign all tags in the current buffer.
18664 - If the cursor is in one of the special #+KEYWORD lines, this
18665 triggers scanning the buffer for these lines and updating the
18666 information.
18668 - If the cursor is inside a table, realign the table. This command
18669 works even if the automatic table editor has been turned off.
18671 - If the cursor is on a #+TBLFM line, re-apply the formulas to
18672 the entire table.
18674 - If the cursor is at a footnote reference or definition, jump to
18675 the corresponding definition or references, respectively.
18677 - If the cursor is a the beginning of a dynamic block, update it.
18679 - If the current buffer is a capture buffer, close note and file it.
18681 - If the cursor is on a <<<target>>>, update radio targets and
18682 corresponding links in this buffer.
18684 - If the cursor is on a numbered item in a plain list, renumber the
18685 ordered list.
18687 - If the cursor is on a checkbox, toggle it.
18689 - If the cursor is on a code block, evaluate it. The variable
18690 `org-confirm-babel-evaluate' can be used to control prompting
18691 before code block evaluation, by default every code block
18692 evaluation requires confirmation. Code block evaluation can be
18693 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
18694 (interactive "P")
18695 (let ((org-enable-table-editor t))
18696 (cond
18697 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
18698 org-occur-highlights
18699 org-latex-fragment-image-overlays)
18700 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
18701 (org-remove-occur-highlights)
18702 (org-remove-latex-fragment-image-overlays)
18703 (message "Temporary highlights/overlays removed from current buffer"))
18704 ((and (local-variable-p 'org-finish-function (current-buffer))
18705 (fboundp org-finish-function))
18706 (funcall org-finish-function))
18707 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
18708 ((org-in-regexp org-ts-regexp-both)
18709 (org-timestamp-change 0 'day))
18710 ((or (looking-at org-property-start-re)
18711 (org-at-property-p))
18712 (call-interactively 'org-property-action))
18713 ((org-at-target-p) (call-interactively 'org-update-radio-target-regexp))
18714 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
18715 (or (org-at-heading-p) (org-at-item-p)))
18716 (call-interactively 'org-update-statistics-cookies))
18717 ((org-at-heading-p) (call-interactively 'org-set-tags))
18718 ((org-at-table.el-p)
18719 (message "Use C-c ' to edit table.el tables"))
18720 ((org-at-table-p)
18721 (org-table-maybe-eval-formula)
18722 (if arg
18723 (call-interactively 'org-table-recalculate)
18724 (org-table-maybe-recalculate-line))
18725 (call-interactively 'org-table-align)
18726 (orgtbl-send-table 'maybe))
18727 ((or (org-footnote-at-reference-p)
18728 (org-footnote-at-definition-p))
18729 (call-interactively 'org-footnote-action))
18730 ((org-at-item-checkbox-p)
18731 ;; Cursor at a checkbox: repair list and update checkboxes. Send
18732 ;; list only if at top item.
18733 (let* ((cbox (match-string 1))
18734 (struct (org-list-struct))
18735 (old-struct (copy-tree struct))
18736 (parents (org-list-parents-alist struct))
18737 (orderedp (org-entry-get nil "ORDERED"))
18738 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
18739 block-item)
18740 ;; Use a light version of `org-toggle-checkbox' to avoid
18741 ;; computing list structure twice.
18742 (let ((new-box (cond
18743 ((equal arg '(16)) "[-]")
18744 ((equal arg '(4)) nil)
18745 ((equal "[X]" cbox) "[ ]")
18746 (t "[X]"))))
18747 (if (and firstp arg)
18748 ;; If at first item of sub-list, remove check-box from
18749 ;; every item at the same level.
18750 (mapc
18751 (lambda (pos) (org-list-set-checkbox pos struct new-box))
18752 (org-list-get-all-items
18753 (point-at-bol) struct (org-list-prevs-alist struct)))
18754 (org-list-set-checkbox (point-at-bol) struct new-box)))
18755 ;; Replicate `org-list-write-struct', while grabbing a return
18756 ;; value from `org-list-struct-fix-box'.
18757 (org-list-struct-fix-ind struct parents 2)
18758 (org-list-struct-fix-item-end struct)
18759 (let ((prevs (org-list-prevs-alist struct)))
18760 (org-list-struct-fix-bul struct prevs)
18761 (org-list-struct-fix-ind struct parents)
18762 (setq block-item
18763 (org-list-struct-fix-box struct parents prevs orderedp)))
18764 (org-list-struct-apply-struct struct old-struct)
18765 (org-update-checkbox-count-maybe)
18766 (when block-item
18767 (message
18768 "Checkboxes were removed due to unchecked box at line %d"
18769 (org-current-line block-item)))
18770 (when firstp (org-list-send-list 'maybe))))
18771 ((org-at-item-p)
18772 ;; Cursor at an item: repair list. Do checkbox related actions
18773 ;; only if function was called with an argument. Send list only
18774 ;; if at top item.
18775 (let* ((struct (org-list-struct))
18776 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
18777 old-struct)
18778 (when arg
18779 (setq old-struct (copy-tree struct))
18780 (if firstp
18781 ;; If at first item of sub-list, add check-box to every
18782 ;; item at the same level.
18783 (mapc
18784 (lambda (pos)
18785 (unless (org-list-get-checkbox pos struct)
18786 (org-list-set-checkbox pos struct "[ ]")))
18787 (org-list-get-all-items
18788 (point-at-bol) struct (org-list-prevs-alist struct)))
18789 (org-list-set-checkbox (point-at-bol) struct "[ ]")))
18790 (org-list-write-struct
18791 struct (org-list-parents-alist struct) old-struct)
18792 (when arg (org-update-checkbox-count-maybe))
18793 (when firstp (org-list-send-list 'maybe))))
18794 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
18795 ;; Dynamic block
18796 (beginning-of-line 1)
18797 (save-excursion (org-update-dblock)))
18798 ((save-excursion
18799 (let ((case-fold-search t))
18800 (beginning-of-line 1)
18801 (looking-at "[ \t]*#\\+\\([a-z]+\\)")))
18802 (cond
18803 ((or (equal (match-string 1) "TBLFM")
18804 (equal (match-string 1) "tblfm"))
18805 ;; Recalculate the table before this line
18806 (save-excursion
18807 (beginning-of-line 1)
18808 (skip-chars-backward " \r\n\t")
18809 (if (org-at-table-p)
18810 (org-call-with-arg 'org-table-recalculate (or arg t)))))
18812 (let ((org-inhibit-startup-visibility-stuff t)
18813 (org-startup-align-all-tables nil))
18814 (when (boundp 'org-table-coordinate-overlays)
18815 (mapc 'delete-overlay org-table-coordinate-overlays)
18816 (setq org-table-coordinate-overlays nil))
18817 (org-save-outline-visibility 'use-markers (org-mode-restart)))
18818 (message "Local setup has been refreshed"))))
18819 ((org-clock-update-time-maybe))
18821 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
18822 (error "C-c C-c can do nothing useful at this location"))))))
18824 (defun org-mode-restart ()
18825 "Restart Org-mode, to scan again for special lines.
18826 Also updates the keyword regular expressions."
18827 (interactive)
18828 (org-mode)
18829 (message "Org-mode restarted"))
18831 (defun org-kill-note-or-show-branches ()
18832 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
18833 (interactive)
18834 (if (not org-finish-function)
18835 (progn
18836 (hide-subtree)
18837 (call-interactively 'show-branches))
18838 (let ((org-note-abort t))
18839 (funcall org-finish-function))))
18841 (defun org-return (&optional indent)
18842 "Goto next table row or insert a newline.
18843 Calls `org-table-next-row' or `newline', depending on context.
18844 See the individual commands for more information."
18845 (interactive)
18846 (cond
18847 ((or (bobp) (org-in-src-block-p))
18848 (if indent (newline-and-indent) (newline)))
18849 ((org-at-table-p)
18850 (org-table-justify-field-maybe)
18851 (call-interactively 'org-table-next-row))
18852 ;; when `newline-and-indent' is called within a list, make sure
18853 ;; text moved stays inside the item.
18854 ((and (org-in-item-p) indent)
18855 (if (and (org-at-item-p) (>= (point) (match-end 0)))
18856 (progn
18857 (save-match-data (newline))
18858 (org-indent-line-to (length (match-string 0))))
18859 (let ((ind (org-get-indentation)))
18860 (newline)
18861 (if (org-looking-back org-list-end-re)
18862 (org-indent-line-function)
18863 (org-indent-line-to ind)))))
18864 ((and org-return-follows-link
18865 (let ((tprop (get-text-property (point) 'face)))
18866 (or (eq tprop 'org-link)
18867 (and (listp tprop) (memq 'org-link tprop)))))
18868 (call-interactively 'org-open-at-point))
18869 ((and (org-at-heading-p)
18870 (looking-at
18871 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
18872 (org-show-entry)
18873 (end-of-line 1)
18874 (newline))
18875 (t (if indent (newline-and-indent) (newline)))))
18877 (defun org-return-indent ()
18878 "Goto next table row or insert a newline and indent.
18879 Calls `org-table-next-row' or `newline-and-indent', depending on
18880 context. See the individual commands for more information."
18881 (interactive)
18882 (org-return t))
18884 (defun org-ctrl-c-star ()
18885 "Compute table, or change heading status of lines.
18886 Calls `org-table-recalculate' or `org-toggle-heading',
18887 depending on context."
18888 (interactive)
18889 (cond
18890 ((org-at-table-p)
18891 (call-interactively 'org-table-recalculate))
18893 ;; Convert all lines in region to list items
18894 (call-interactively 'org-toggle-heading))))
18896 (defun org-ctrl-c-minus ()
18897 "Insert separator line in table or modify bullet status of line.
18898 Also turns a plain line or a region of lines into list items.
18899 Calls `org-table-insert-hline', `org-toggle-item', or
18900 `org-cycle-list-bullet', depending on context."
18901 (interactive)
18902 (cond
18903 ((org-at-table-p)
18904 (call-interactively 'org-table-insert-hline))
18905 ((org-region-active-p)
18906 (call-interactively 'org-toggle-item))
18907 ((org-in-item-p)
18908 (call-interactively 'org-cycle-list-bullet))
18910 (call-interactively 'org-toggle-item))))
18912 (defun org-toggle-item (arg)
18913 "Convert headings or normal lines to items, items to normal lines.
18914 If there is no active region, only the current line is considered.
18916 If the first non blank line in the region is an headline, convert
18917 all headlines to items, shifting text accordingly.
18919 If it is an item, convert all items to normal lines.
18921 If it is normal text, change region into an item. With a prefix
18922 argument ARG, change each line in region into an item."
18923 (interactive "P")
18924 (let ((shift-text
18925 (function
18926 ;; Shift text in current section to IND, from point to END.
18927 ;; The function leaves point to END line.
18928 (lambda (ind end)
18929 (let ((min-i 1000) (end (copy-marker end)))
18930 ;; First determine the minimum indentation (MIN-I) of
18931 ;; the text.
18932 (save-excursion
18933 (catch 'exit
18934 (while (< (point) end)
18935 (let ((i (org-get-indentation)))
18936 (cond
18937 ;; Skip blank lines and inline tasks.
18938 ((looking-at "^[ \t]*$"))
18939 ((looking-at org-outline-regexp-bol))
18940 ;; We can't find less than 0 indentation.
18941 ((zerop i) (throw 'exit (setq min-i 0)))
18942 ((< i min-i) (setq min-i i))))
18943 (forward-line))))
18944 ;; Then indent each line so that a line indented to
18945 ;; MIN-I becomes indented to IND. Ignore blank lines
18946 ;; and inline tasks in the process.
18947 (let ((delta (- ind min-i)))
18948 (while (< (point) end)
18949 (unless (or (looking-at "^[ \t]*$")
18950 (looking-at org-outline-regexp-bol))
18951 (org-indent-line-to (+ (org-get-indentation) delta)))
18952 (forward-line)))))))
18953 (skip-blanks
18954 (function
18955 ;; Return beginning of first non-blank line, starting from
18956 ;; line at POS.
18957 (lambda (pos)
18958 (save-excursion
18959 (goto-char pos)
18960 (skip-chars-forward " \r\t\n")
18961 (point-at-bol)))))
18962 beg end)
18963 ;; Determine boundaries of changes.
18964 (if (org-region-active-p)
18965 (setq beg (funcall skip-blanks (region-beginning))
18966 end (copy-marker (region-end)))
18967 (setq beg (funcall skip-blanks (point-at-bol))
18968 end (copy-marker (point-at-eol))))
18969 ;; Depending on the starting line, choose an action on the text
18970 ;; between BEG and END.
18971 (org-with-limited-levels
18972 (save-excursion
18973 (goto-char beg)
18974 (cond
18975 ;; Case 1. Start at an item: de-itemize. Note that it only
18976 ;; happens when a region is active: `org-ctrl-c-minus'
18977 ;; would call `org-cycle-list-bullet' otherwise.
18978 ((org-at-item-p)
18979 (while (< (point) end)
18980 (when (org-at-item-p)
18981 (skip-chars-forward " \t")
18982 (delete-region (point) (match-end 0)))
18983 (forward-line)))
18984 ;; Case 2. Start at an heading: convert to items.
18985 ((org-at-heading-p)
18986 (let* ((bul (org-list-bullet-string "-"))
18987 (bul-len (length bul))
18988 ;; Indentation of the first heading. It should be
18989 ;; relative to the indentation of its parent, if any.
18990 (start-ind (save-excursion
18991 (cond
18992 ((not org-adapt-indentation) 0)
18993 ((not (outline-previous-heading)) 0)
18994 (t (length (match-string 0))))))
18995 ;; Level of first heading. Further headings will be
18996 ;; compared to it to determine hierarchy in the list.
18997 (ref-level (org-reduced-level (org-outline-level))))
18998 (while (< (point) end)
18999 (let* ((level (org-reduced-level (org-outline-level)))
19000 (delta (max 0 (- level ref-level))))
19001 ;; If current headline is less indented than the first
19002 ;; one, set it as reference, in order to preserve
19003 ;; subtrees.
19004 (when (< level ref-level) (setq ref-level level))
19005 (replace-match bul t t)
19006 (org-indent-line-to (+ start-ind (* delta bul-len)))
19007 ;; Ensure all text down to END (or SECTION-END) belongs
19008 ;; to the newly created item.
19009 (let ((section-end (save-excursion
19010 (or (outline-next-heading) (point)))))
19011 (forward-line)
19012 (funcall shift-text
19013 (+ start-ind (* (1+ delta) bul-len))
19014 (min end section-end)))))))
19015 ;; Case 3. Normal line with ARG: turn each non-item line into
19016 ;; an item.
19017 (arg
19018 (while (< (point) end)
19019 (unless (or (org-at-heading-p) (org-at-item-p))
19020 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
19021 (replace-match
19022 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
19023 (forward-line)))
19024 ;; Case 4. Normal line without ARG: make the first line of
19025 ;; region an item, and shift indentation of others
19026 ;; lines to set them as item's body.
19027 (t (let* ((bul (org-list-bullet-string "-"))
19028 (bul-len (length bul))
19029 (ref-ind (org-get-indentation)))
19030 (skip-chars-forward " \t")
19031 (insert bul)
19032 (forward-line)
19033 (while (< (point) end)
19034 ;; Ensure that lines less indented than first one
19035 ;; still get included in item body.
19036 (funcall shift-text
19037 (+ ref-ind bul-len)
19038 (min end (save-excursion (or (outline-next-heading)
19039 (point)))))
19040 (forward-line)))))))))
19042 (defun org-toggle-heading (&optional nstars)
19043 "Convert headings to normal text, or items or text to headings.
19044 If there is no active region, only the current line is considered.
19046 If the first non blank line is an headline, remove the stars from
19047 all headlines in the region.
19049 If it is a plain list item, turn all plain list items into headings.
19051 If it is a normal line, turn each and every normal line (i.e. not
19052 an heading or an item) in the region into a heading.
19054 When converting a line into a heading, the number of stars is chosen
19055 such that the lines become children of the current entry. However,
19056 when a prefix argument is given, its value determines the number of
19057 stars to add."
19058 (interactive "P")
19059 (let ((skip-blanks
19060 (function
19061 ;; Return beginning of first non-blank line, starting from
19062 ;; line at POS.
19063 (lambda (pos)
19064 (save-excursion
19065 (goto-char pos)
19066 (skip-chars-forward " \r\t\n")
19067 (point-at-bol)))))
19068 beg end)
19069 ;; Determine boundaries of changes. If region ends at a bol, do
19070 ;; not consider the last line to be in the region.
19071 (if (org-region-active-p)
19072 (setq beg (funcall skip-blanks (region-beginning))
19073 end (copy-marker (save-excursion
19074 (goto-char (region-end))
19075 (if (bolp) (point) (point-at-eol)))))
19076 (setq beg (funcall skip-blanks (point-at-bol))
19077 end (copy-marker (point-at-eol))))
19078 ;; Ensure inline tasks don't count as headings.
19079 (org-with-limited-levels
19080 (save-excursion
19081 (goto-char beg)
19082 (cond
19083 ;; Case 1. Started at an heading: de-star headings.
19084 ((org-at-heading-p)
19085 (while (< (point) end)
19086 (when (org-at-heading-p t)
19087 (looking-at org-outline-regexp) (replace-match ""))
19088 (forward-line)))
19089 ;; Case 2. Started at an item: change items into headlines.
19090 ;; One star will be added by `org-list-to-subtree'.
19091 ((org-at-item-p)
19092 (let* ((stars (make-string
19093 (if nstars
19094 ;; subtract the star that will be added again by
19095 ;; `org-list-to-subtree'
19096 (1- (prefix-numeric-value current-prefix-arg))
19097 (or (org-current-level) 0))
19098 ?*))
19099 (add-stars
19100 (cond (nstars "") ; stars from prefix only
19101 ((equal stars "") "") ; before first heading
19102 (org-odd-levels-only "*") ; inside heading, odd
19103 (t "")))) ; inside heading, oddeven
19104 (while (< (point) end)
19105 (when (org-at-item-p)
19106 ;; Pay attention to cases when region ends before list.
19107 (let* ((struct (org-list-struct))
19108 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
19109 (save-restriction
19110 (narrow-to-region (point) list-end)
19111 (insert
19112 (org-list-to-subtree
19113 (org-list-parse-list t)
19114 '(:istart (concat stars add-stars (funcall get-stars depth))
19115 :icount (concat stars add-stars (funcall get-stars depth))))))))
19116 (forward-line))))
19117 ;; Case 3. Started at normal text: make every line an heading,
19118 ;; skipping headlines and items.
19119 (t (let* ((stars (make-string
19120 (if nstars
19121 (prefix-numeric-value current-prefix-arg)
19122 (or (org-current-level) 0))
19123 ?*))
19124 (add-stars
19125 (cond (nstars "") ; stars from prefix only
19126 ((equal stars "") "*") ; before first heading
19127 (org-odd-levels-only "**") ; inside heading, odd
19128 (t "*"))) ; inside heading, oddeven
19129 (rpl (concat stars add-stars " ")))
19130 (while (< (point) end)
19131 (when (and (not (org-at-heading-p)) (not (org-at-item-p))
19132 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
19133 (replace-match (concat rpl (match-string 2))))
19134 (forward-line)))))))))
19136 (defun org-meta-return (&optional arg)
19137 "Insert a new heading or wrap a region in a table.
19138 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
19139 See the individual commands for more information."
19140 (interactive "P")
19141 (cond
19142 ((run-hook-with-args-until-success 'org-metareturn-hook))
19143 ((or (org-at-drawer-p) (org-at-property-p))
19144 (newline-and-indent))
19145 ((org-at-table-p)
19146 (call-interactively 'org-table-wrap-region))
19147 (t (call-interactively 'org-insert-heading))))
19149 ;;; Menu entries
19151 ;; Define the Org-mode menus
19152 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
19153 '("Tbl"
19154 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
19155 ["Next Field" org-cycle (org-at-table-p)]
19156 ["Previous Field" org-shifttab (org-at-table-p)]
19157 ["Next Row" org-return (org-at-table-p)]
19158 "--"
19159 ["Blank Field" org-table-blank-field (org-at-table-p)]
19160 ["Edit Field" org-table-edit-field (org-at-table-p)]
19161 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
19162 "--"
19163 ("Column"
19164 ["Move Column Left" org-metaleft (org-at-table-p)]
19165 ["Move Column Right" org-metaright (org-at-table-p)]
19166 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
19167 ["Insert Column" org-shiftmetaright (org-at-table-p)])
19168 ("Row"
19169 ["Move Row Up" org-metaup (org-at-table-p)]
19170 ["Move Row Down" org-metadown (org-at-table-p)]
19171 ["Delete Row" org-shiftmetaup (org-at-table-p)]
19172 ["Insert Row" org-shiftmetadown (org-at-table-p)]
19173 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
19174 "--"
19175 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
19176 ("Rectangle"
19177 ["Copy Rectangle" org-copy-special (org-at-table-p)]
19178 ["Cut Rectangle" org-cut-special (org-at-table-p)]
19179 ["Paste Rectangle" org-paste-special (org-at-table-p)]
19180 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
19181 "--"
19182 ("Calculate"
19183 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
19184 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
19185 ["Edit Formulas" org-edit-special (org-at-table-p)]
19186 "--"
19187 ["Recalculate line" org-table-recalculate (org-at-table-p)]
19188 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
19189 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
19190 "--"
19191 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
19192 "--"
19193 ["Sum Column/Rectangle" org-table-sum
19194 (or (org-at-table-p) (org-region-active-p))]
19195 ["Which Column?" org-table-current-column (org-at-table-p)])
19196 ["Debug Formulas"
19197 org-table-toggle-formula-debugger
19198 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
19199 ["Show Col/Row Numbers"
19200 org-table-toggle-coordinate-overlays
19201 :style toggle
19202 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
19203 "--"
19204 ["Create" org-table-create (and (not (org-at-table-p))
19205 org-enable-table-editor)]
19206 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
19207 ["Import from File" org-table-import (not (org-at-table-p))]
19208 ["Export to File" org-table-export (org-at-table-p)]
19209 "--"
19210 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
19212 (easy-menu-define org-org-menu org-mode-map "Org menu"
19213 '("Org"
19214 ("Show/Hide"
19215 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
19216 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
19217 ["Sparse Tree..." org-sparse-tree t]
19218 ["Reveal Context" org-reveal t]
19219 ["Show All" show-all t]
19220 "--"
19221 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
19222 "--"
19223 ["New Heading" org-insert-heading t]
19224 ("Navigate Headings"
19225 ["Up" outline-up-heading t]
19226 ["Next" outline-next-visible-heading t]
19227 ["Previous" outline-previous-visible-heading t]
19228 ["Next Same Level" outline-forward-same-level t]
19229 ["Previous Same Level" outline-backward-same-level t]
19230 "--"
19231 ["Jump" org-goto t])
19232 ("Edit Structure"
19233 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
19234 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
19235 "--"
19236 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
19237 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
19238 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
19239 "--"
19240 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
19241 "--"
19242 ["Copy visible text" org-copy-visible t]
19243 "--"
19244 ["Promote Heading" org-metaleft (not (org-at-table-p))]
19245 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
19246 ["Demote Heading" org-metaright (not (org-at-table-p))]
19247 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
19248 "--"
19249 ["Sort Region/Children" org-sort (not (org-at-table-p))]
19250 "--"
19251 ["Convert to odd levels" org-convert-to-odd-levels t]
19252 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
19253 ("Editing"
19254 ["Emphasis..." org-emphasize t]
19255 ["Edit Source Example" org-edit-special t]
19256 "--"
19257 ["Footnote new/jump" org-footnote-action t]
19258 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
19259 ("Archive"
19260 ["Archive (default method)" org-archive-subtree-default t]
19261 "--"
19262 ["Move Subtree to Archive file" org-advertized-archive-subtree t]
19263 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
19264 ["Move subtree to Archive sibling" org-archive-to-archive-sibling t]
19266 "--"
19267 ("Hyperlinks"
19268 ["Store Link (Global)" org-store-link t]
19269 ["Find existing link to here" org-occur-link-in-agenda-files t]
19270 ["Insert Link" org-insert-link t]
19271 ["Follow Link" org-open-at-point t]
19272 "--"
19273 ["Next link" org-next-link t]
19274 ["Previous link" org-previous-link t]
19275 "--"
19276 ["Descriptive Links"
19277 org-toggle-link-display
19278 :style radio
19279 :selected org-descriptive-links
19281 ["Literal Links"
19282 org-toggle-link-display
19283 :style radio
19284 :selected (not org-descriptive-links)])
19285 "--"
19286 ("TODO Lists"
19287 ["TODO/DONE/-" org-todo t]
19288 ("Select keyword"
19289 ["Next keyword" org-shiftright (org-at-heading-p)]
19290 ["Previous keyword" org-shiftleft (org-at-heading-p)]
19291 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
19292 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
19293 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
19294 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
19295 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
19296 "--"
19297 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
19298 :selected org-enforce-todo-dependencies :style toggle :active t]
19299 "Settings for tree at point"
19300 ["Do Children sequentially" org-toggle-ordered-property :style radio
19301 :selected (org-entry-get nil "ORDERED")
19302 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
19303 ["Do Children parallel" org-toggle-ordered-property :style radio
19304 :selected (not (org-entry-get nil "ORDERED"))
19305 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
19306 "--"
19307 ["Set Priority" org-priority t]
19308 ["Priority Up" org-shiftup t]
19309 ["Priority Down" org-shiftdown t]
19310 "--"
19311 ["Get news from all feeds" org-feed-update-all t]
19312 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
19313 ["Customize feeds" (customize-variable 'org-feed-alist) t])
19314 ("TAGS and Properties"
19315 ["Set Tags" org-set-tags-command t]
19316 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
19317 "--"
19318 ["Set property" org-set-property t]
19319 ["Column view of properties" org-columns t]
19320 ["Insert Column View DBlock" org-insert-columns-dblock t])
19321 ("Dates and Scheduling"
19322 ["Timestamp" org-time-stamp t]
19323 ["Timestamp (inactive)" org-time-stamp-inactive t]
19324 ("Change Date"
19325 ["1 Day Later" org-shiftright t]
19326 ["1 Day Earlier" org-shiftleft t]
19327 ["1 ... Later" org-shiftup t]
19328 ["1 ... Earlier" org-shiftdown t])
19329 ["Compute Time Range" org-evaluate-time-range t]
19330 ["Schedule Item" org-schedule t]
19331 ["Deadline" org-deadline t]
19332 "--"
19333 ["Custom time format" org-toggle-time-stamp-overlays
19334 :style radio :selected org-display-custom-times]
19335 "--"
19336 ["Goto Calendar" org-goto-calendar t]
19337 ["Date from Calendar" org-date-from-calendar t]
19338 "--"
19339 ["Start/Restart Timer" org-timer-start t]
19340 ["Pause/Continue Timer" org-timer-pause-or-continue t]
19341 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
19342 ["Insert Timer String" org-timer t]
19343 ["Insert Timer Item" org-timer-item t])
19344 ("Logging work"
19345 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
19346 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
19347 ["Clock out" org-clock-out t]
19348 ["Clock cancel" org-clock-cancel t]
19349 "--"
19350 ["Mark as default task" org-clock-mark-default-task t]
19351 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
19352 ["Goto running clock" org-clock-goto t]
19353 "--"
19354 ["Display times" org-clock-display t]
19355 ["Create clock table" org-clock-report t]
19356 "--"
19357 ["Record DONE time"
19358 (progn (setq org-log-done (not org-log-done))
19359 (message "Switching to %s will %s record a timestamp"
19360 (car org-done-keywords)
19361 (if org-log-done "automatically" "not")))
19362 :style toggle :selected org-log-done])
19363 "--"
19364 ["Agenda Command..." org-agenda t]
19365 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
19366 ("File List for Agenda")
19367 ("Special views current file"
19368 ["TODO Tree" org-show-todo-tree t]
19369 ["Check Deadlines" org-check-deadlines t]
19370 ["Timeline" org-timeline t]
19371 ["Tags/Property tree" org-match-sparse-tree t])
19372 "--"
19373 ["Export/Publish..." org-export t]
19374 ("LaTeX"
19375 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
19376 :selected org-cdlatex-mode]
19377 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
19378 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
19379 ["Modify math symbol" org-cdlatex-math-modify
19380 (org-inside-LaTeX-fragment-p)]
19381 ["Insert citation" org-reftex-citation t]
19382 "--"
19383 ["Template for BEAMER" (progn (require 'org-beamer)
19384 (org-insert-beamer-options-template)) t])
19385 "--"
19386 ("MobileOrg"
19387 ["Push Files and Views" org-mobile-push t]
19388 ["Get Captured and Flagged" org-mobile-pull t]
19389 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
19390 "--"
19391 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
19392 "--"
19393 ("Documentation"
19394 ["Show Version" org-version t]
19395 ["Info Documentation" org-info t])
19396 ("Customize"
19397 ["Browse Org Group" org-customize t]
19398 "--"
19399 ["Expand This Menu" org-create-customize-menu
19400 (fboundp 'customize-menu-create)])
19401 ["Send bug report" org-submit-bug-report t]
19402 "--"
19403 ("Refresh/Reload"
19404 ["Refresh setup current buffer" org-mode-restart t]
19405 ["Reload Org (after update)" org-reload t]
19406 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
19409 (defun org-info (&optional node)
19410 "Read documentation for Org-mode in the info system.
19411 With optional NODE, go directly to that node."
19412 (interactive)
19413 (info (format "(org)%s" (or node ""))))
19415 ;;;###autoload
19416 (defun org-submit-bug-report ()
19417 "Submit a bug report on Org-mode via mail.
19419 Don't hesitate to report any problems or inaccurate documentation.
19421 If you don't have setup sending mail from (X)Emacs, please copy the
19422 output buffer into your mail program, as it gives us important
19423 information about your Org-mode version and configuration."
19424 (interactive)
19425 (require 'reporter)
19426 (org-load-modules-maybe)
19427 (org-require-autoloaded-modules)
19428 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
19429 (reporter-submit-bug-report
19430 "emacs-orgmode@gnu.org"
19431 (org-version)
19432 (let (list)
19433 (save-window-excursion
19434 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
19435 (delete-other-windows)
19436 (erase-buffer)
19437 (insert "You are about to submit a bug report to the Org-mode mailing list.
19439 We would like to add your full Org-mode and Outline configuration to the
19440 bug report. This greatly simplifies the work of the maintainer and
19441 other experts on the mailing list.
19443 HOWEVER, some variables you have customized may contain private
19444 information. The names of customers, colleagues, or friends, might
19445 appear in the form of file names, tags, todo states, or search strings.
19446 If you answer yes to the prompt, you might want to check and remove
19447 such private information before sending the email.")
19448 (add-text-properties (point-min) (point-max) '(face org-warning))
19449 (when (yes-or-no-p "Include your Org-mode configuration ")
19450 (mapatoms
19451 (lambda (v)
19452 (and (boundp v)
19453 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
19454 (or (and (symbol-value v)
19455 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
19456 (and
19457 (get v 'custom-type) (get v 'standard-value)
19458 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
19459 (push v list)))))
19460 (kill-buffer (get-buffer "*Warn about privacy*"))
19461 list))
19462 nil nil
19463 "Remember to cover the basics, that is, what you expected to happen and
19464 what in fact did happen. You don't know how to make a good report? See
19466 http://orgmode.org/manual/Feedback.html#Feedback
19468 Your bug report will be posted to the Org-mode mailing list.
19469 ------------------------------------------------------------------------")
19470 (save-excursion
19471 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
19472 (replace-match "\\1Bug: \\3 [\\2]")))))
19475 (defun org-install-agenda-files-menu ()
19476 (let ((bl (buffer-list)))
19477 (save-excursion
19478 (while bl
19479 (set-buffer (pop bl))
19480 (if (derived-mode-p 'org-mode) (setq bl nil)))
19481 (when (derived-mode-p 'org-mode)
19482 (easy-menu-change
19483 '("Org") "File List for Agenda"
19484 (append
19485 (list
19486 ["Edit File List" (org-edit-agenda-file-list) t]
19487 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
19488 ["Remove Current File from List" org-remove-file t]
19489 ["Cycle through agenda files" org-cycle-agenda-files t]
19490 ["Occur in all agenda files" org-occur-in-agenda-files t]
19491 "--")
19492 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
19494 ;;;; Documentation
19496 ;;;###autoload
19497 (defun org-require-autoloaded-modules ()
19498 (interactive)
19499 (mapc 'require
19500 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
19501 org-docbook org-exp org-html org-icalendar
19502 org-id org-latex
19503 org-publish org-remember org-table
19504 org-timer org-xoxo)))
19506 ;;;###autoload
19507 (defun org-reload (&optional uncompiled)
19508 "Reload all org lisp files.
19509 With prefix arg UNCOMPILED, load the uncompiled versions."
19510 (interactive "P")
19511 (require 'find-func)
19512 (let* ((file-re "^\\(org\\|orgtbl\\)\\(\\.el\\|-.*\\.el\\)")
19513 (dir-org (file-name-directory (org-find-library-name "org")))
19514 (dir-org-contrib (ignore-errors
19515 (file-name-directory
19516 (org-find-library-name "org-contribdir"))))
19517 (babel-files
19518 (mapcar (lambda (el) (concat "ob" (when el (format "-%s" el)) ".el"))
19519 (append (list nil "comint" "eval" "exp" "keys"
19520 "lob" "ref" "table" "tangle")
19521 (delq nil
19522 (mapcar
19523 (lambda (lang)
19524 (when (cdr lang) (symbol-name (car lang))))
19525 org-babel-load-languages)))))
19526 (files
19527 (append (directory-files dir-org t file-re)
19528 babel-files
19529 (and dir-org-contrib
19530 (directory-files dir-org-contrib t file-re))))
19531 (remove-re (concat (if (featurep 'xemacs)
19532 "org-colview" "org-colview-xemacs")
19533 "\\'")))
19534 (setq files (mapcar 'file-name-sans-extension files))
19535 (setq files (mapcar
19536 (lambda (x) (if (string-match remove-re x) nil x))
19537 files))
19538 (setq files (delq nil files))
19539 (mapc
19540 (lambda (f)
19541 (when (featurep (intern (file-name-nondirectory f)))
19542 (if (and (not uncompiled)
19543 (file-exists-p (concat f ".elc")))
19544 (load (concat f ".elc") nil nil t)
19545 (load (concat f ".el") nil nil t))))
19546 files))
19547 (org-version))
19549 ;;;###autoload
19550 (defun org-customize ()
19551 "Call the customize function with org as argument."
19552 (interactive)
19553 (org-load-modules-maybe)
19554 (org-require-autoloaded-modules)
19555 (customize-browse 'org))
19557 (defun org-create-customize-menu ()
19558 "Create a full customization menu for Org-mode, insert it into the menu."
19559 (interactive)
19560 (org-load-modules-maybe)
19561 (org-require-autoloaded-modules)
19562 (if (fboundp 'customize-menu-create)
19563 (progn
19564 (easy-menu-change
19565 '("Org") "Customize"
19566 `(["Browse Org group" org-customize t]
19567 "--"
19568 ,(customize-menu-create 'org)
19569 ["Set" Custom-set t]
19570 ["Save" Custom-save t]
19571 ["Reset to Current" Custom-reset-current t]
19572 ["Reset to Saved" Custom-reset-saved t]
19573 ["Reset to Standard Settings" Custom-reset-standard t]))
19574 (message "\"Org\"-menu now contains full customization menu"))
19575 (error "Cannot expand menu (outdated version of cus-edit.el)")))
19577 ;;;; Miscellaneous stuff
19579 ;;; Generally useful functions
19581 (defun org-get-at-bol (property)
19582 "Get text property PROPERTY at beginning of line."
19583 (get-text-property (point-at-bol) property))
19585 (defun org-find-text-property-in-string (prop s)
19586 "Return the first non-nil value of property PROP in string S."
19587 (or (get-text-property 0 prop s)
19588 (get-text-property (or (next-single-property-change 0 prop s) 0)
19589 prop s)))
19591 (defun org-display-warning (message) ;; Copied from Emacs-Muse
19592 "Display the given MESSAGE as a warning."
19593 (if (fboundp 'display-warning)
19594 (display-warning 'org message
19595 (if (featurep 'xemacs) 'warning :warning))
19596 (let ((buf (get-buffer-create "*Org warnings*")))
19597 (with-current-buffer buf
19598 (goto-char (point-max))
19599 (insert "Warning (Org): " message)
19600 (unless (bolp)
19601 (newline)))
19602 (display-buffer buf)
19603 (sit-for 0))))
19605 (defun org-eval (form)
19606 "Eval FORM and return result."
19607 (condition-case error
19608 (eval form)
19609 (error (format "%%![Error: %s]" error))))
19611 (defun org-in-clocktable-p ()
19612 "Check if the cursor is in a clocktable."
19613 (let ((pos (point)) start)
19614 (save-excursion
19615 (end-of-line 1)
19616 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
19617 (setq start (match-beginning 0))
19618 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
19619 (>= (match-end 0) pos)
19620 start))))
19622 (defun org-in-commented-line ()
19623 "Is point in a line starting with `#'?"
19624 (equal (char-after (point-at-bol)) ?#))
19626 (defun org-in-indented-comment-line ()
19627 "Is point in a line starting with `#' after some white space?"
19628 (save-excursion
19629 (save-match-data
19630 (goto-char (point-at-bol))
19631 (looking-at "[ \t]*#"))))
19633 (defun org-in-verbatim-emphasis ()
19634 (save-match-data
19635 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
19637 (defun org-goto-marker-or-bmk (marker &optional bookmark)
19638 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
19639 (if (and marker (marker-buffer marker)
19640 (buffer-live-p (marker-buffer marker)))
19641 (progn
19642 (org-pop-to-buffer-same-window (marker-buffer marker))
19643 (if (or (> marker (point-max)) (< marker (point-min)))
19644 (widen))
19645 (goto-char marker)
19646 (org-show-context 'org-goto))
19647 (if bookmark
19648 (bookmark-jump bookmark)
19649 (error "Cannot find location"))))
19651 (defun org-quote-csv-field (s)
19652 "Quote field for inclusion in CSV material."
19653 (if (string-match "[\",]" s)
19654 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
19657 (defun org-force-self-insert (N)
19658 "Needed to enforce self-insert under remapping."
19659 (interactive "p")
19660 (self-insert-command N))
19662 (defun org-string-width (s)
19663 "Compute width of string, ignoring invisible characters.
19664 This ignores character with invisibility property `org-link', and also
19665 characters with property `org-cwidth', because these will become invisible
19666 upon the next fontification round."
19667 (let (b l)
19668 (when (or (eq t buffer-invisibility-spec)
19669 (assq 'org-link buffer-invisibility-spec))
19670 (while (setq b (text-property-any 0 (length s)
19671 'invisible 'org-link s))
19672 (setq s (concat (substring s 0 b)
19673 (substring s (or (next-single-property-change
19674 b 'invisible s) (length s)))))))
19675 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
19676 (setq s (concat (substring s 0 b)
19677 (substring s (or (next-single-property-change
19678 b 'org-cwidth s) (length s))))))
19679 (setq l (string-width s) b -1)
19680 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
19681 (setq l (- l (get-text-property b 'org-dwidth-n s))))
19684 (defun org-shorten-string (s maxlength)
19685 "Shorten string S so tht it is no longer than MAXLENGTH characters.
19686 If the string is shorter or has length MAXLENGTH, just return the
19687 original string. If it is longer, the functions finds a space in the
19688 string, breaks this string off at that locations and adds three dots
19689 as ellipsis. Including the ellipsis, the string will not be longer
19690 than MAXLENGTH. If finding a good breaking point in the string does
19691 not work, the string is just chopped off in the middle of a word
19692 if necessary."
19693 (if (<= (length s) maxlength)
19695 (let* ((n (max (- maxlength 4) 1))
19696 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
19697 (if (string-match re s)
19698 (concat (match-string 1 s) "...")
19699 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
19701 (defun org-get-indentation (&optional line)
19702 "Get the indentation of the current line, interpreting tabs.
19703 When LINE is given, assume it represents a line and compute its indentation."
19704 (if line
19705 (if (string-match "^ *" (org-remove-tabs line))
19706 (match-end 0))
19707 (save-excursion
19708 (beginning-of-line 1)
19709 (skip-chars-forward " \t")
19710 (current-column))))
19712 (defun org-get-string-indentation (s)
19713 "What indentation has S due to SPACE and TAB at the beginning of the string?"
19714 (let ((n -1) (i 0) (w tab-width) c)
19715 (catch 'exit
19716 (while (< (setq n (1+ n)) (length s))
19717 (setq c (aref s n))
19718 (cond ((= c ?\ ) (setq i (1+ i)))
19719 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
19720 (t (throw 'exit t)))))
19723 (defun org-remove-tabs (s &optional width)
19724 "Replace tabulators in S with spaces.
19725 Assumes that s is a single line, starting in column 0."
19726 (setq width (or width tab-width))
19727 (while (string-match "\t" s)
19728 (setq s (replace-match
19729 (make-string
19730 (- (* width (/ (+ (match-beginning 0) width) width))
19731 (match-beginning 0)) ?\ )
19732 t t s)))
19735 (defun org-fix-indentation (line ind)
19736 "Fix indentation in LINE.
19737 IND is a cons cell with target and minimum indentation.
19738 If the current indentation in LINE is smaller than the minimum,
19739 leave it alone. If it is larger than ind, set it to the target."
19740 (let* ((l (org-remove-tabs line))
19741 (i (org-get-indentation l))
19742 (i1 (car ind)) (i2 (cdr ind)))
19743 (if (>= i i2) (setq l (substring line i2)))
19744 (if (> i1 0)
19745 (concat (make-string i1 ?\ ) l)
19746 l)))
19748 (defun org-remove-indentation (code &optional n)
19749 "Remove the maximum common indentation from the lines in CODE.
19750 N may optionally be the number of spaces to remove."
19751 (with-temp-buffer
19752 (insert code)
19753 (org-do-remove-indentation n)
19754 (buffer-string)))
19756 (defun org-do-remove-indentation (&optional n)
19757 "Remove the maximum common indentation from the buffer."
19758 (untabify (point-min) (point-max))
19759 (let ((min 10000) re)
19760 (if n
19761 (setq min n)
19762 (goto-char (point-min))
19763 (while (re-search-forward "^ *[^ \n]" nil t)
19764 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
19765 (unless (or (= min 0) (= min 10000))
19766 (setq re (format "^ \\{%d\\}" min))
19767 (goto-char (point-min))
19768 (while (re-search-forward re nil t)
19769 (replace-match "")
19770 (end-of-line 1))
19771 min)))
19773 (defun org-fill-template (template alist)
19774 "Find each %key of ALIST in TEMPLATE and replace it."
19775 (let ((case-fold-search nil)
19776 entry key value)
19777 (setq alist (sort (copy-sequence alist)
19778 (lambda (a b) (< (length (car a)) (length (car b))))))
19779 (while (setq entry (pop alist))
19780 (setq template
19781 (replace-regexp-in-string
19782 (concat "%" (regexp-quote (car entry)))
19783 (cdr entry) template t t)))
19784 template))
19786 (defun org-base-buffer (buffer)
19787 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
19788 (if (not buffer)
19789 buffer
19790 (or (buffer-base-buffer buffer)
19791 buffer)))
19793 (defun org-trim (s)
19794 "Remove whitespace at beginning and end of string."
19795 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
19796 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
19799 (defun org-wrap (string &optional width lines)
19800 "Wrap string to either a number of lines, or a width in characters.
19801 If WIDTH is non-nil, the string is wrapped to that width, however many lines
19802 that costs. If there is a word longer than WIDTH, the text is actually
19803 wrapped to the length of that word.
19804 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
19805 many lines, whatever width that takes.
19806 The return value is a list of lines, without newlines at the end."
19807 (let* ((words (org-split-string string "[ \t\n]+"))
19808 (maxword (apply 'max (mapcar 'org-string-width words)))
19809 w ll)
19810 (cond (width
19811 (org-do-wrap words (max maxword width)))
19812 (lines
19813 (setq w maxword)
19814 (setq ll (org-do-wrap words maxword))
19815 (if (<= (length ll) lines)
19817 (setq ll words)
19818 (while (> (length ll) lines)
19819 (setq w (1+ w))
19820 (setq ll (org-do-wrap words w)))
19821 ll))
19822 (t (error "Cannot wrap this")))))
19824 (defun org-do-wrap (words width)
19825 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
19826 (let (lines line)
19827 (while words
19828 (setq line (pop words))
19829 (while (and words (< (+ (length line) (length (car words))) width))
19830 (setq line (concat line " " (pop words))))
19831 (setq lines (push line lines)))
19832 (nreverse lines)))
19834 (defun org-split-string (string &optional separators)
19835 "Splits STRING into substrings at SEPARATORS.
19836 No empty strings are returned if there are matches at the beginning
19837 and end of string."
19838 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
19839 (start 0)
19840 notfirst
19841 (list nil))
19842 (while (and (string-match rexp string
19843 (if (and notfirst
19844 (= start (match-beginning 0))
19845 (< start (length string)))
19846 (1+ start) start))
19847 (< (match-beginning 0) (length string)))
19848 (setq notfirst t)
19849 (or (eq (match-beginning 0) 0)
19850 (and (eq (match-beginning 0) (match-end 0))
19851 (eq (match-beginning 0) start))
19852 (setq list
19853 (cons (substring string start (match-beginning 0))
19854 list)))
19855 (setq start (match-end 0)))
19856 (or (eq start (length string))
19857 (setq list
19858 (cons (substring string start)
19859 list)))
19860 (nreverse list)))
19862 (defun org-quote-vert (s)
19863 "Replace \"|\" with \"\\vert\"."
19864 (while (string-match "|" s)
19865 (setq s (replace-match "\\vert" t t s)))
19868 (defun org-uuidgen-p (s)
19869 "Is S an ID created by UUIDGEN?"
19870 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
19872 (defun org-in-src-block-p nil
19873 "Whether point is in a code source block."
19874 (let (ov)
19875 (when (setq ov (overlays-at (point)))
19876 (memq 'org-block-background
19877 (overlay-properties
19878 (car ov))))))
19880 (defun org-context ()
19881 "Return a list of contexts of the current cursor position.
19882 If several contexts apply, all are returned.
19883 Each context entry is a list with a symbol naming the context, and
19884 two positions indicating start and end of the context. Possible
19885 contexts are:
19887 :headline anywhere in a headline
19888 :headline-stars on the leading stars in a headline
19889 :todo-keyword on a TODO keyword (including DONE) in a headline
19890 :tags on the TAGS in a headline
19891 :priority on the priority cookie in a headline
19892 :item on the first line of a plain list item
19893 :item-bullet on the bullet/number of a plain list item
19894 :checkbox on the checkbox in a plain list item
19895 :table in an org-mode table
19896 :table-special on a special filed in a table
19897 :table-table in a table.el table
19898 :clocktable in a clocktable
19899 :src-block in a source block
19900 :link on a hyperlink
19901 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
19902 :target on a <<target>>
19903 :radio-target on a <<<radio-target>>>
19904 :latex-fragment on a LaTeX fragment
19905 :latex-preview on a LaTeX fragment with overlaid preview image
19907 This function expects the position to be visible because it uses font-lock
19908 faces as a help to recognize the following contexts: :table-special, :link,
19909 and :keyword."
19910 (let* ((f (get-text-property (point) 'face))
19911 (faces (if (listp f) f (list f)))
19912 (case-fold-search t)
19913 (p (point)) clist o)
19914 ;; First the large context
19915 (cond
19916 ((org-at-heading-p t)
19917 (push (list :headline (point-at-bol) (point-at-eol)) clist)
19918 (when (progn
19919 (beginning-of-line 1)
19920 (looking-at org-todo-line-tags-regexp))
19921 (push (org-point-in-group p 1 :headline-stars) clist)
19922 (push (org-point-in-group p 2 :todo-keyword) clist)
19923 (push (org-point-in-group p 4 :tags) clist))
19924 (goto-char p)
19925 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
19926 (if (looking-at "\\[#[A-Z0-9]\\]")
19927 (push (org-point-in-group p 0 :priority) clist)))
19929 ((org-at-item-p)
19930 (push (org-point-in-group p 2 :item-bullet) clist)
19931 (push (list :item (point-at-bol)
19932 (save-excursion (org-end-of-item) (point)))
19933 clist)
19934 (and (org-at-item-checkbox-p)
19935 (push (org-point-in-group p 0 :checkbox) clist)))
19937 ((org-at-table-p)
19938 (push (list :table (org-table-begin) (org-table-end)) clist)
19939 (if (memq 'org-formula faces)
19940 (push (list :table-special
19941 (previous-single-property-change p 'face)
19942 (next-single-property-change p 'face)) clist)))
19943 ((org-at-table-p 'any)
19944 (push (list :table-table) clist)))
19945 (goto-char p)
19947 ;; New the "medium" contexts: clocktables, source blocks
19948 (cond ((org-in-clocktable-p)
19949 (push (list :clocktable
19950 (and (or (looking-at "#\\+BEGIN: clocktable")
19951 (search-backward "#+BEGIN: clocktable" nil t))
19952 (match-beginning 0))
19953 (and (re-search-forward "#\\+END:?" nil t)
19954 (match-end 0))) clist))
19955 ((org-in-src-block-p)
19956 (push (list :src-block
19957 (and (or (looking-at "#\\+BEGIN_SRC")
19958 (search-backward "#+BEGIN_SRC" nil t))
19959 (match-beginning 0))
19960 (and (search-forward "#+END_SRC" nil t)
19961 (match-beginning 0))) clist)))
19962 (goto-char p)
19964 ;; Now the small context
19965 (cond
19966 ((org-at-timestamp-p)
19967 (push (org-point-in-group p 0 :timestamp) clist))
19968 ((memq 'org-link faces)
19969 (push (list :link
19970 (previous-single-property-change p 'face)
19971 (next-single-property-change p 'face)) clist))
19972 ((memq 'org-special-keyword faces)
19973 (push (list :keyword
19974 (previous-single-property-change p 'face)
19975 (next-single-property-change p 'face)) clist))
19976 ((org-at-target-p)
19977 (push (org-point-in-group p 0 :target) clist)
19978 (goto-char (1- (match-beginning 0)))
19979 (if (looking-at org-radio-target-regexp)
19980 (push (org-point-in-group p 0 :radio-target) clist))
19981 (goto-char p))
19982 ((setq o (car (delq nil
19983 (mapcar
19984 (lambda (x)
19985 (if (memq x org-latex-fragment-image-overlays) x))
19986 (overlays-at (point))))))
19987 (push (list :latex-fragment
19988 (overlay-start o) (overlay-end o)) clist)
19989 (push (list :latex-preview
19990 (overlay-start o) (overlay-end o)) clist))
19991 ((org-inside-LaTeX-fragment-p)
19992 ;; FIXME: positions wrong.
19993 (push (list :latex-fragment (point) (point)) clist)))
19995 (setq clist (nreverse (delq nil clist)))
19996 clist))
19998 ;; FIXME: Compare with at-regexp-p Do we need both?
19999 (defun org-in-regexp (re &optional nlines visually)
20000 "Check if point is inside a match of regexp.
20001 Normally only the current line is checked, but you can include NLINES extra
20002 lines both before and after point into the search.
20003 If VISUALLY is set, require that the cursor is not after the match but
20004 really on, so that the block visually is on the match."
20005 (catch 'exit
20006 (let ((pos (point))
20007 (eol (point-at-eol (+ 1 (or nlines 0))))
20008 (inc (if visually 1 0)))
20009 (save-excursion
20010 (beginning-of-line (- 1 (or nlines 0)))
20011 (while (re-search-forward re eol t)
20012 (if (and (<= (match-beginning 0) pos)
20013 (>= (+ inc (match-end 0)) pos))
20014 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
20016 (defun org-at-regexp-p (regexp)
20017 "Is point inside a match of REGEXP in the current line?"
20018 (catch 'exit
20019 (save-excursion
20020 (let ((pos (point)) (end (point-at-eol)))
20021 (beginning-of-line 1)
20022 (while (re-search-forward regexp end t)
20023 (if (and (<= (match-beginning 0) pos)
20024 (>= (match-end 0) pos))
20025 (throw 'exit t)))
20026 nil))))
20028 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
20029 "Non-nil when point is between matches of START-RE and END-RE.
20031 Also return a non-nil value when point is on one of the matches.
20033 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
20034 buffer positions. Default values are the positions of headlines
20035 surrounding the point.
20037 The functions returns a cons cell whose car (resp. cdr) is the
20038 position before START-RE (resp. after END-RE)."
20039 (save-match-data
20040 (let ((pos (point))
20041 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
20042 (limit-down (or lim-down (save-excursion (outline-next-heading))))
20043 beg end)
20044 (save-excursion
20045 ;; Point is on a block when on START-RE or if START-RE can be
20046 ;; found before it...
20047 (and (or (org-at-regexp-p start-re)
20048 (re-search-backward start-re limit-up t))
20049 (setq beg (match-beginning 0))
20050 ;; ... and END-RE after it...
20051 (goto-char (match-end 0))
20052 (re-search-forward end-re limit-down t)
20053 (> (setq end (match-end 0)) pos)
20054 ;; ... without another START-RE in-between.
20055 (goto-char (match-beginning 0))
20056 (not (re-search-backward start-re (1+ beg) t))
20057 ;; Return value.
20058 (cons beg end))))))
20060 (defun org-in-block-p (names)
20061 "Non-nil when point belongs to a block whose name belongs to NAMES.
20063 NAMES is a list of strings containing names of blocks.
20065 Return first block name matched, or nil. Beware that in case of
20066 nested blocks, the returned name may not belong to the closest
20067 block from point."
20068 (save-match-data
20069 (catch 'exit
20070 (let ((case-fold-search t)
20071 (lim-up (save-excursion (outline-previous-heading)))
20072 (lim-down (save-excursion (outline-next-heading))))
20073 (mapc (lambda (name)
20074 (let ((n (regexp-quote name)))
20075 (when (org-between-regexps-p
20076 (concat "^[ \t]*#\\+begin_" n)
20077 (concat "^[ \t]*#\\+end_" n)
20078 lim-up lim-down)
20079 (throw 'exit n))))
20080 names))
20081 nil)))
20083 (defun org-occur-in-agenda-files (regexp &optional nlines)
20084 "Call `multi-occur' with buffers for all agenda files."
20085 (interactive "sOrg-files matching: \np")
20086 (let* ((files (org-agenda-files))
20087 (tnames (mapcar 'file-truename files))
20088 (extra org-agenda-text-search-extra-files)
20090 (when (eq (car extra) 'agenda-archives)
20091 (setq extra (cdr extra))
20092 (setq files (org-add-archive-files files)))
20093 (while (setq f (pop extra))
20094 (unless (member (file-truename f) tnames)
20095 (add-to-list 'files f 'append)
20096 (add-to-list 'tnames (file-truename f) 'append)))
20097 (multi-occur
20098 (mapcar (lambda (x)
20099 (with-current-buffer
20100 (or (get-file-buffer x) (find-file-noselect x))
20101 (widen)
20102 (current-buffer)))
20103 files)
20104 regexp)))
20106 (if (boundp 'occur-mode-find-occurrence-hook)
20107 ;; Emacs 23
20108 (add-hook 'occur-mode-find-occurrence-hook
20109 (lambda ()
20110 (when (derived-mode-p 'org-mode)
20111 (org-reveal))))
20112 ;; Emacs 22
20113 (defadvice occur-mode-goto-occurrence
20114 (after org-occur-reveal activate)
20115 (and (derived-mode-p 'org-mode) (org-reveal)))
20116 (defadvice occur-mode-goto-occurrence-other-window
20117 (after org-occur-reveal activate)
20118 (and (derived-mode-p 'org-mode) (org-reveal)))
20119 (defadvice occur-mode-display-occurrence
20120 (after org-occur-reveal activate)
20121 (when (derived-mode-p 'org-mode)
20122 (let ((pos (occur-mode-find-occurrence)))
20123 (with-current-buffer (marker-buffer pos)
20124 (save-excursion
20125 (goto-char pos)
20126 (org-reveal)))))))
20128 (defun org-occur-link-in-agenda-files ()
20129 "Create a link and search for it in the agendas.
20130 The link is not stored in `org-stored-links', it is just created
20131 for the search purpose."
20132 (interactive)
20133 (let ((link (condition-case nil
20134 (org-store-link nil)
20135 (error "Unable to create a link to here"))))
20136 (org-occur-in-agenda-files (regexp-quote link))))
20138 (defun org-uniquify (list)
20139 "Remove duplicate elements from LIST."
20140 (let (res)
20141 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
20142 res))
20144 (defun org-delete-all (elts list)
20145 "Remove all elements in ELTS from LIST."
20146 (while elts
20147 (setq list (delete (pop elts) list)))
20148 list)
20150 (defun org-count (cl-item cl-seq)
20151 "Count the number of occurrences of ITEM in SEQ.
20152 Taken from `count' in cl-seq.el with all keyword arguments removed."
20153 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
20154 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
20155 (while (< cl-start cl-end)
20156 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
20157 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
20158 (setq cl-start (1+ cl-start)))
20159 cl-count))
20161 (defun org-remove-if (predicate seq)
20162 "Remove everything from SEQ that fulfills PREDICATE."
20163 (let (res e)
20164 (while seq
20165 (setq e (pop seq))
20166 (if (not (funcall predicate e)) (push e res)))
20167 (nreverse res)))
20169 (defun org-remove-if-not (predicate seq)
20170 "Remove everything from SEQ that does not fulfill PREDICATE."
20171 (let (res e)
20172 (while seq
20173 (setq e (pop seq))
20174 (if (funcall predicate e) (push e res)))
20175 (nreverse res)))
20177 (defun org-reduce (cl-func cl-seq &rest cl-keys)
20178 "Reduce two-argument FUNCTION across SEQ.
20179 Taken from `reduce' in cl-seq.el with all keyword arguments but
20180 \":initial-value\" removed."
20181 (let ((cl-accum (cond ((memq :initial-value cl-keys)
20182 (cadr (memq :initial-value cl-keys)))
20183 (cl-seq (pop cl-seq))
20184 (t (funcall cl-func)))))
20185 (while cl-seq
20186 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
20187 cl-accum))
20189 (defun org-back-over-empty-lines ()
20190 "Move backwards over whitespace, to the beginning of the first empty line.
20191 Returns the number of empty lines passed."
20192 (let ((pos (point)))
20193 (if (cdr (assoc 'heading org-blank-before-new-entry))
20194 (skip-chars-backward " \t\n\r")
20195 (unless (eobp)
20196 (forward-line -1)))
20197 (beginning-of-line 2)
20198 (goto-char (min (point) pos))
20199 (count-lines (point) pos)))
20201 (defun org-skip-whitespace ()
20202 (skip-chars-forward " \t\n\r"))
20204 (defun org-point-in-group (point group &optional context)
20205 "Check if POINT is in match-group GROUP.
20206 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
20207 match. If the match group does not exist or point is not inside it,
20208 return nil."
20209 (and (match-beginning group)
20210 (>= point (match-beginning group))
20211 (<= point (match-end group))
20212 (if context
20213 (list context (match-beginning group) (match-end group))
20214 t)))
20216 (defun org-switch-to-buffer-other-window (&rest args)
20217 "Switch to buffer in a second window on the current frame.
20218 In particular, do not allow pop-up frames.
20219 Returns the newly created buffer."
20220 (let (pop-up-frames special-display-buffer-names special-display-regexps
20221 special-display-function)
20222 (apply 'switch-to-buffer-other-window args)))
20224 (defun org-combine-plists (&rest plists)
20225 "Create a single property list from all plists in PLISTS.
20226 The process starts by copying the first list, and then setting properties
20227 from the other lists. Settings in the last list are the most significant
20228 ones and overrule settings in the other lists."
20229 (let ((rtn (copy-sequence (pop plists)))
20230 p v ls)
20231 (while plists
20232 (setq ls (pop plists))
20233 (while ls
20234 (setq p (pop ls) v (pop ls))
20235 (setq rtn (plist-put rtn p v))))
20236 rtn))
20238 (defun org-move-line-down (arg)
20239 "Move the current line down. With prefix argument, move it past ARG lines."
20240 (interactive "p")
20241 (let ((col (current-column))
20242 beg end pos)
20243 (beginning-of-line 1) (setq beg (point))
20244 (beginning-of-line 2) (setq end (point))
20245 (beginning-of-line (+ 1 arg))
20246 (setq pos (move-marker (make-marker) (point)))
20247 (insert (delete-and-extract-region beg end))
20248 (goto-char pos)
20249 (org-move-to-column col)))
20251 (defun org-move-line-up (arg)
20252 "Move the current line up. With prefix argument, move it past ARG lines."
20253 (interactive "p")
20254 (let ((col (current-column))
20255 beg end pos)
20256 (beginning-of-line 1) (setq beg (point))
20257 (beginning-of-line 2) (setq end (point))
20258 (beginning-of-line (- arg))
20259 (setq pos (move-marker (make-marker) (point)))
20260 (insert (delete-and-extract-region beg end))
20261 (goto-char pos)
20262 (org-move-to-column col)))
20264 (defun org-replace-escapes (string table)
20265 "Replace %-escapes in STRING with values in TABLE.
20266 TABLE is an association list with keys like \"%a\" and string values.
20267 The sequences in STRING may contain normal field width and padding information,
20268 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
20269 so values can contain further %-escapes if they are define later in TABLE."
20270 (let ((tbl (copy-alist table))
20271 (case-fold-search nil)
20272 (pchg 0)
20273 e re rpl)
20274 (while (setq e (pop tbl))
20275 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
20276 (when (and (cdr e) (string-match re (cdr e)))
20277 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
20278 (safe "SREF"))
20279 (add-text-properties 0 3 (list 'sref sref) safe)
20280 (setcdr e (replace-match safe t t (cdr e)))))
20281 (while (string-match re string)
20282 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
20283 (cdr e)))
20284 (setq string (replace-match rpl t t string))))
20285 (while (setq pchg (next-property-change pchg string))
20286 (let ((sref (get-text-property pchg 'sref string)))
20287 (when (and sref (string-match "SREF" string pchg))
20288 (setq string (replace-match sref t t string)))))
20289 string))
20291 (defun org-sublist (list start end)
20292 "Return a section of LIST, from START to END.
20293 Counting starts at 1."
20294 (let (rtn (c start))
20295 (setq list (nthcdr (1- start) list))
20296 (while (and list (<= c end))
20297 (push (pop list) rtn)
20298 (setq c (1+ c)))
20299 (nreverse rtn)))
20301 (defun org-find-base-buffer-visiting (file)
20302 "Like `find-buffer-visiting' but always return the base buffer and
20303 not an indirect buffer."
20304 (let ((buf (or (get-file-buffer file)
20305 (find-buffer-visiting file))))
20306 (if buf
20307 (or (buffer-base-buffer buf) buf)
20308 nil)))
20310 (defun org-image-file-name-regexp (&optional extensions)
20311 "Return regexp matching the file names of images.
20312 If EXTENSIONS is given, only match these."
20313 (if (and (not extensions) (fboundp 'image-file-name-regexp))
20314 (image-file-name-regexp)
20315 (let ((image-file-name-extensions
20316 (or extensions
20317 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
20318 "xbm" "xpm" "pbm" "pgm" "ppm"))))
20319 (concat "\\."
20320 (regexp-opt (nconc (mapcar 'upcase
20321 image-file-name-extensions)
20322 image-file-name-extensions)
20324 "\\'"))))
20326 (defun org-file-image-p (file &optional extensions)
20327 "Return non-nil if FILE is an image."
20328 (save-match-data
20329 (string-match (org-image-file-name-regexp extensions) file)))
20331 (defun org-get-cursor-date ()
20332 "Return the date at cursor in as a time.
20333 This works in the calendar and in the agenda, anywhere else it just
20334 returns the current time."
20335 (let (date day defd)
20336 (cond
20337 ((eq major-mode 'calendar-mode)
20338 (setq date (calendar-cursor-to-date)
20339 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
20340 ((eq major-mode 'org-agenda-mode)
20341 (setq day (get-text-property (point) 'day))
20342 (if day
20343 (setq date (calendar-gregorian-from-absolute day)
20344 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
20345 (nth 2 date))))))
20346 (or defd (current-time))))
20348 (defvar org-agenda-action-marker (make-marker)
20349 "Marker pointing to the entry for the next agenda action.")
20351 (defun org-mark-entry-for-agenda-action ()
20352 "Mark the current entry as target of an agenda action.
20353 Agenda actions are actions executed from the agenda with the key `k',
20354 which make use of the date at the cursor."
20355 (interactive)
20356 (move-marker org-agenda-action-marker
20357 (save-excursion (org-back-to-heading t) (point))
20358 (current-buffer))
20359 (message
20360 "Entry marked for action; press `k' at desired date in agenda or calendar"))
20362 (defun org-mark-subtree ()
20363 "Mark the current subtree.
20364 This puts point at the start of the current subtree, and mark at the end.
20366 If point is in an inline task, mark that task instead."
20367 (interactive)
20368 (let ((inline-task-p
20369 (and (featurep 'org-inlinetask)
20370 (org-inlinetask-in-task-p)))
20371 (beg))
20372 ;; Get beginning of subtree
20373 (cond
20374 (inline-task-p (org-inlinetask-goto-beginning))
20375 ((org-at-heading-p) (beginning-of-line))
20376 (t (org-with-limited-levels (outline-previous-visible-heading 1))))
20377 (setq beg (point))
20378 ;; Get end of it
20379 (if inline-task-p
20380 (org-inlinetask-goto-end)
20381 (org-end-of-subtree))
20382 ;; Mark zone
20383 (push-mark (point) nil t)
20384 (goto-char beg)))
20386 ;;; Paragraph filling stuff.
20387 ;; We want this to be just right, so use the full arsenal.
20389 (defun org-indent-line-function ()
20390 "Indent line depending on context."
20391 (interactive)
20392 (let* ((pos (point))
20393 (itemp (org-at-item-p))
20394 (case-fold-search t)
20395 (org-drawer-regexp (or org-drawer-regexp "\000"))
20396 (inline-task-p (and (featurep 'org-inlinetask)
20397 (org-inlinetask-in-task-p)))
20398 (inline-re (and inline-task-p
20399 (org-inlinetask-outline-regexp)))
20400 column)
20401 (beginning-of-line 1)
20402 (cond
20403 ;; Comments
20404 ((looking-at "# ") (setq column 0))
20405 ;; Headings
20406 ((looking-at org-outline-regexp) (setq column 0))
20407 ;; Included files
20408 ((looking-at "#\\+include:") (setq column 0))
20409 ;; Footnote definition
20410 ((looking-at org-footnote-definition-re) (setq column 0))
20411 ;; Literal examples
20412 ((looking-at "[ \t]*:\\( \\|$\\)")
20413 (setq column (org-get-indentation))) ; do nothing
20414 ;; Lists
20415 ((ignore-errors (goto-char (org-in-item-p)))
20416 (setq column (if itemp
20417 (org-get-indentation)
20418 (org-list-item-body-column (point))))
20419 (goto-char pos))
20420 ;; Drawers
20421 ((and (looking-at "[ \t]*:END:")
20422 (save-excursion (re-search-backward org-drawer-regexp nil t)))
20423 (save-excursion
20424 (goto-char (1- (match-beginning 1)))
20425 (setq column (current-column))))
20426 ;; Special blocks
20427 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
20428 (save-excursion
20429 (re-search-backward
20430 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
20431 (setq column (org-get-indentation (match-string 0))))
20432 ((and (not (looking-at "[ \t]*#\\+begin_"))
20433 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
20434 (save-excursion
20435 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
20436 (setq column
20437 (cond ((equal (downcase (match-string 1)) "src")
20438 ;; src blocks: let `org-edit-src-exit' handle them
20439 (org-get-indentation))
20440 ((equal (downcase (match-string 1)) "example")
20441 (max (org-get-indentation)
20442 (org-get-indentation (match-string 0))))
20444 (org-get-indentation (match-string 0))))))
20445 ;; This line has nothing special, look at the previous relevant
20446 ;; line to compute indentation
20448 (beginning-of-line 0)
20449 (while (and (not (bobp))
20450 (not (looking-at org-drawer-regexp))
20451 ;; When point started in an inline task, do not move
20452 ;; above task starting line.
20453 (not (and inline-task-p (looking-at inline-re)))
20454 ;; Skip drawers, blocks, empty lines, verbatim,
20455 ;; comments, tables, footnotes definitions, lists,
20456 ;; inline tasks.
20457 (or (and (looking-at "[ \t]*:END:")
20458 (re-search-backward org-drawer-regexp nil t))
20459 (and (looking-at "[ \t]*#\\+end_")
20460 (re-search-backward "[ \t]*#\\+begin_"nil t))
20461 (looking-at "[ \t]*[\n:#|]")
20462 (looking-at org-footnote-definition-re)
20463 (and (ignore-errors (goto-char (org-in-item-p)))
20464 (goto-char
20465 (org-list-get-top-point (org-list-struct))))
20466 (and (not inline-task-p)
20467 (featurep 'org-inlinetask)
20468 (org-inlinetask-in-task-p)
20469 (or (org-inlinetask-goto-beginning) t))))
20470 (beginning-of-line 0))
20471 (cond
20472 ;; There was an heading above.
20473 ((looking-at "\\*+[ \t]+")
20474 (if (not org-adapt-indentation)
20475 (setq column 0)
20476 (goto-char (match-end 0))
20477 (setq column (current-column))))
20478 ;; A drawer had started and is unfinished
20479 ((looking-at org-drawer-regexp)
20480 (goto-char (1- (match-beginning 1)))
20481 (setq column (current-column)))
20482 ;; Else, nothing noticeable found: get indentation and go on.
20483 (t (setq column (org-get-indentation))))))
20484 ;; Now apply indentation and move cursor accordingly
20485 (goto-char pos)
20486 (if (<= (current-column) (current-indentation))
20487 (org-indent-line-to column)
20488 (save-excursion (org-indent-line-to column)))
20489 ;; Special polishing for properties, see `org-property-format'
20490 (setq column (current-column))
20491 (beginning-of-line 1)
20492 (if (looking-at
20493 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
20494 (replace-match (concat (match-string 1)
20495 (format org-property-format
20496 (match-string 2) (match-string 3)))
20497 t t))
20498 (org-move-to-column column)))
20500 (defun org-indent-drawer ()
20501 "Indent the drawer at point."
20502 (interactive)
20503 (let ((p (point))
20504 (e (and (save-excursion (re-search-forward ":END:" nil t))
20505 (match-end 0)))
20506 (folded
20507 (save-excursion
20508 (end-of-line)
20509 (when (overlays-at (point))
20510 (member 'invisible (overlay-properties
20511 (car (overlays-at (point)))))))))
20512 (when folded (org-cycle))
20513 (indent-for-tab-command)
20514 (while (and (move-beginning-of-line 2) (< (point) e))
20515 (indent-for-tab-command))
20516 (goto-char p)
20517 (when folded (org-cycle)))
20518 (message "Drawer at point indented"))
20520 (defun org-indent-block ()
20521 "Indent the block at point."
20522 (interactive)
20523 (let ((p (point))
20524 (case-fold-search t)
20525 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
20526 (match-end 0)))
20527 (folded
20528 (save-excursion
20529 (end-of-line)
20530 (when (overlays-at (point))
20531 (member 'invisible (overlay-properties
20532 (car (overlays-at (point)))))))))
20533 (when folded (org-cycle))
20534 (indent-for-tab-command)
20535 (while (and (move-beginning-of-line 2) (< (point) e))
20536 (indent-for-tab-command))
20537 (goto-char p)
20538 (when folded (org-cycle)))
20539 (message "Block at point indented"))
20541 (defvar org-adaptive-fill-regexp-backup adaptive-fill-regexp
20542 "Variable to store copy of `adaptive-fill-regexp'.
20543 Since `adaptive-fill-regexp' is set to never match, we need to
20544 store a backup of its value before entering `org-mode' so that
20545 the functionality can be provided as a fall-back.")
20547 (defun org-set-autofill-regexps ()
20548 (interactive)
20549 ;; In the paragraph separator we include headlines, because filling
20550 ;; text in a line directly attached to a headline would otherwise
20551 ;; fill the headline as well.
20552 (org-set-local 'comment-start-skip "^#+[ \t]*")
20553 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|#]")
20554 ;; The paragraph starter includes hand-formatted lists.
20555 (org-set-local
20556 'paragraph-start
20557 (concat
20558 "\f" "\\|"
20559 "[ ]*$" "\\|"
20560 org-outline-regexp "\\|"
20561 "[ \t]*#" "\\|"
20562 (org-item-re) "\\|"
20563 "[ \t]*[:|]" "\\|"
20564 "\\$\\$" "\\|"
20565 "\\\\\\(begin\\|end\\|[][]\\)"))
20566 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
20567 ;; But only if the user has not turned off tables or fixed-width regions
20568 (org-set-local
20569 'auto-fill-inhibit-regexp
20570 (concat org-outline-regexp
20571 "\\|#\\+"
20572 "\\|[ \t]*" org-keyword-time-regexp
20573 (if (or org-enable-table-editor org-enable-fixed-width-editor)
20574 (concat
20575 "\\|[ \t]*["
20576 (if org-enable-table-editor "|" "")
20577 (if org-enable-fixed-width-editor ":" "")
20578 "]"))))
20579 ;; We use our own fill-paragraph function, to make sure that tables
20580 ;; and fixed-width regions are not wrapped. That function will pass
20581 ;; through to `fill-paragraph' when appropriate.
20582 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
20583 ;; Prevent auto-fill from inserting unwanted new items.
20584 (if (boundp 'fill-nobreak-predicate)
20585 (org-set-local
20586 'fill-nobreak-predicate
20587 (org-uniquify
20588 (append fill-nobreak-predicate
20589 '(org-fill-item-nobreak-p org-fill-line-break-nobreak-p)))))
20590 ;; Adaptive filling: To get full control, first make sure that
20591 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
20592 (unless (local-variable-p 'adaptive-fill-regexp (current-buffer))
20593 (org-set-local 'org-adaptive-fill-regexp-backup
20594 adaptive-fill-regexp))
20595 (org-set-local 'adaptive-fill-regexp "\000")
20596 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
20597 (org-set-local 'adaptive-fill-function
20598 'org-adaptive-fill-function)
20599 (org-set-local
20600 'align-mode-rules-list
20601 '((org-in-buffer-settings
20602 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
20603 (modes . '(org-mode))))))
20605 (defun org-fill-item-nobreak-p ()
20606 "Non-nil when a line break at point would insert a new item."
20607 (and (looking-at (org-item-re)) (org-list-in-valid-context-p)))
20609 (defun org-fill-line-break-nobreak-p ()
20610 "Non-nil when a line break at point would create an Org line break."
20611 (save-excursion
20612 (skip-chars-backward "[ \t]")
20613 (skip-chars-backward "\\\\")
20614 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
20616 (defun org-fill-paragraph (&optional justify)
20617 "Re-align a table, pass through to fill-paragraph if no table."
20618 (let ((table-p (org-at-table-p))
20619 (table.el-p (org-at-table.el-p))
20620 (itemp (org-in-item-p)))
20621 (cond ((and (equal (char-after (point-at-bol)) ?*)
20622 (save-excursion (goto-char (point-at-bol))
20623 (looking-at org-outline-regexp)))
20624 t) ; skip headlines
20625 (table.el-p t) ; skip table.el tables
20626 (table-p (org-table-align) t) ; align Org tables
20627 (itemp ; align text in items
20628 (let* ((struct (save-excursion (goto-char itemp)
20629 (org-list-struct)))
20630 (parents (org-list-parents-alist struct))
20631 (children (org-list-get-children itemp struct parents))
20632 beg end prev next prefix)
20633 ;; Determine in which part of item point is: before
20634 ;; first child, after last child, between two
20635 ;; sub-lists, or simply in item if there's no child.
20636 (cond
20637 ((not children)
20638 (setq prefix (make-string (org-list-item-body-column itemp) ?\ )
20639 beg itemp
20640 end (org-list-get-item-end itemp struct)))
20641 ((< (point) (setq next (car children)))
20642 (setq prefix (make-string (org-list-item-body-column itemp) ?\ )
20643 beg itemp
20644 end next))
20645 ((> (point) (setq prev (car (last children))))
20646 (setq beg (org-list-get-item-end prev struct)
20647 end (org-list-get-item-end itemp struct)
20648 prefix (save-excursion
20649 (goto-char beg)
20650 (skip-chars-forward " \t")
20651 (make-string (current-column) ?\ ))))
20652 (t (catch 'exit
20653 (while (setq next (pop children))
20654 (if (> (point) next)
20655 (setq prev next)
20656 (setq beg (org-list-get-item-end prev struct)
20657 end next
20658 prefix (save-excursion
20659 (goto-char beg)
20660 (skip-chars-forward " \t")
20661 (make-string (current-column) ?\ )))
20662 (throw 'exit nil))))))
20663 ;; Use `fill-paragraph' with buffer narrowed to item
20664 ;; without any child, and with our computed PREFIX.
20665 (flet ((fill-context-prefix (from to &optional flr) prefix))
20666 (save-restriction
20667 (narrow-to-region beg end)
20668 (save-excursion (fill-paragraph justify)))) t))
20669 ;; Special case where point is not in a list but is on
20670 ;; a paragraph adjacent to a list: make sure this paragraph
20671 ;; doesn't get merged with the end of the list by narrowing
20672 ;; buffer first.
20673 ((save-excursion (forward-paragraph -1)
20674 (setq itemp (org-in-item-p)))
20675 (let ((struct (save-excursion (goto-char itemp)
20676 (org-list-struct))))
20677 (save-restriction
20678 (narrow-to-region (org-list-get-bottom-point struct)
20679 (save-excursion (forward-paragraph 1)
20680 (point)))
20681 (fill-paragraph justify) t)))
20682 ;; Don't fill schedule/deadline line before a paragraph
20683 ((save-excursion (forward-paragraph -1)
20684 (or (looking-at (concat "^[^\n]*" org-scheduled-regexp ".*$"))
20685 (looking-at (concat "^[^\n]*" org-deadline-regexp ".*$"))))
20686 (save-restriction
20687 (narrow-to-region (1+ (match-end 0))
20688 (save-excursion (forward-paragraph 1) (point)))
20689 (fill-paragraph justify) t))
20690 ;; Else simply call `fill-paragraph'.
20691 (t nil))))
20693 ;; For reference, this is the default value of adaptive-fill-regexp
20694 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
20696 (defun org-adaptive-fill-function ()
20697 "Return a fill prefix for org-mode files."
20698 (let (itemp)
20699 (save-excursion
20700 (cond
20701 ;; Comment line
20702 ((looking-at "#[ \t]+")
20703 (match-string-no-properties 0))
20704 ;; Plain list item
20705 ((org-at-item-p)
20706 (make-string (org-list-item-body-column (point-at-bol)) ?\ ))
20707 ;; Point is in a list after `backward-paragraph': original
20708 ;; point wasn't in the list, or filling would have been taken
20709 ;; care of by `org-auto-fill-function', but the list and the
20710 ;; real paragraph are not separated by a blank line. Thus, move
20711 ;; point after the list to go back to real paragraph and
20712 ;; determine fill-prefix.
20713 ((setq itemp (org-in-item-p))
20714 (goto-char itemp)
20715 (let* ((struct (org-list-struct))
20716 (bottom (org-list-get-bottom-point struct)))
20717 (goto-char bottom)
20718 (make-string (org-get-indentation) ?\ )))
20719 ;; Other text
20720 ((looking-at org-adaptive-fill-regexp-backup)
20721 (match-string-no-properties 0))))))
20723 (defun org-auto-fill-function ()
20724 "Auto-fill function."
20725 (let (itemp prefix)
20726 ;; When in a list, compute an appropriate fill-prefix and make
20727 ;; sure it will be used by `do-auto-fill'.
20728 (if (setq itemp (org-in-item-p))
20729 (progn
20730 (setq prefix (make-string (org-list-item-body-column itemp) ?\ ))
20731 (flet ((fill-context-prefix (from to &optional flr) prefix))
20732 (do-auto-fill)))
20733 ;; Else just use `do-auto-fill'.
20734 (do-auto-fill))))
20736 ;;; Other stuff.
20738 (defun org-toggle-fixed-width-section (arg)
20739 "Toggle the fixed-width export.
20740 If there is no active region, the QUOTE keyword at the current headline is
20741 inserted or removed. When present, it causes the text between this headline
20742 and the next to be exported as fixed-width text, and unmodified.
20743 If there is an active region, this command adds or removes a colon as the
20744 first character of this line. If the first character of a line is a colon,
20745 this line is also exported in fixed-width font."
20746 (interactive "P")
20747 (let* ((cc 0)
20748 (regionp (org-region-active-p))
20749 (beg (if regionp (region-beginning) (point)))
20750 (end (if regionp (region-end)))
20751 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
20752 (case-fold-search nil)
20753 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
20754 off)
20755 (if regionp
20756 (save-excursion
20757 (goto-char beg)
20758 (setq cc (current-column))
20759 (beginning-of-line 1)
20760 (setq off (looking-at re))
20761 (while (> nlines 0)
20762 (setq nlines (1- nlines))
20763 (beginning-of-line 1)
20764 (cond
20765 (arg
20766 (org-move-to-column cc t)
20767 (insert ": \n")
20768 (forward-line -1))
20769 ((and off (looking-at re))
20770 (replace-match "" t t nil 1))
20771 ((not off) (org-move-to-column cc t) (insert ": ")))
20772 (forward-line 1)))
20773 (save-excursion
20774 (org-back-to-heading)
20775 (cond
20776 ((looking-at (format org-heading-keyword-regexp-format
20777 org-quote-string))
20778 (goto-char (match-end 1))
20779 (looking-at (concat " +" org-quote-string))
20780 (replace-match "" t t)
20781 (when (eolp) (insert " ")))
20782 ((looking-at org-outline-regexp)
20783 (goto-char (match-end 0))
20784 (insert org-quote-string " ")))))))
20786 (defun org-reftex-citation ()
20787 "Use reftex-citation to insert a citation into the buffer.
20788 This looks for a line like
20790 #+BIBLIOGRAPHY: foo plain option:-d
20792 and derives from it that foo.bib is the bibliography file relevant
20793 for this document. It then installs the necessary environment for RefTeX
20794 to work in this buffer and calls `reftex-citation' to insert a citation
20795 into the buffer.
20797 Export of such citations to both LaTeX and HTML is handled by the contributed
20798 package org-exp-bibtex by Taru Karttunen."
20799 (interactive)
20800 (let ((reftex-docstruct-symbol 'rds)
20801 (reftex-cite-format "\\cite{%l}")
20802 rds bib)
20803 (save-excursion
20804 (save-restriction
20805 (widen)
20806 (let ((case-fold-search t)
20807 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
20808 (if (not (save-excursion
20809 (or (re-search-forward re nil t)
20810 (re-search-backward re nil t))))
20811 (error "No bibliography defined in file")
20812 (setq bib (concat (match-string 1) ".bib")
20813 rds (list (list 'bib bib)))))))
20814 (call-interactively 'reftex-citation)))
20816 ;;;; Functions extending outline functionality
20818 (defun org-beginning-of-line (&optional arg)
20819 "Go to the beginning of the current line. If that is invisible, continue
20820 to a visible line beginning. This makes the function of C-a more intuitive.
20821 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
20822 first attempt, and only move to after the tags when the cursor is already
20823 beyond the end of the headline."
20824 (interactive "P")
20825 (let ((pos (point))
20826 (special (if (consp org-special-ctrl-a/e)
20827 (car org-special-ctrl-a/e)
20828 org-special-ctrl-a/e))
20829 refpos)
20830 (if (org-bound-and-true-p line-move-visual)
20831 (beginning-of-visual-line 1)
20832 (beginning-of-line 1))
20833 (if (and arg (fboundp 'move-beginning-of-line))
20834 (call-interactively 'move-beginning-of-line)
20835 (if (bobp)
20837 (backward-char 1)
20838 (if (org-truely-invisible-p)
20839 (while (and (not (bobp)) (org-truely-invisible-p))
20840 (backward-char 1)
20841 (beginning-of-line 1))
20842 (forward-char 1))))
20843 (when special
20844 (cond
20845 ((and (looking-at org-complex-heading-regexp)
20846 (= (char-after (match-end 1)) ?\ ))
20847 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
20848 (point-at-eol)))
20849 (goto-char
20850 (if (eq special t)
20851 (cond ((> pos refpos) refpos)
20852 ((= pos (point)) refpos)
20853 (t (point)))
20854 (cond ((> pos (point)) (point))
20855 ((not (eq last-command this-command)) (point))
20856 (t refpos)))))
20857 ((org-at-item-p)
20858 ;; Being at an item and not looking at an the item means point
20859 ;; was previously moved to beginning of a visual line, which
20860 ;; doesn't contain the item. Therefore, do nothing special,
20861 ;; just stay here.
20862 (when (looking-at org-list-full-item-re)
20863 ;; Set special position at first white space character after
20864 ;; bullet, and check-box, if any.
20865 (let ((after-bullet
20866 (let ((box (match-end 3)))
20867 (if (not box) (match-end 1)
20868 (let ((after (char-after box)))
20869 (if (and after (= after ? )) (1+ box) box))))))
20870 ;; Special case: Move point to special position when
20871 ;; currently after it or at beginning of line.
20872 (if (eq special t)
20873 (when (or (> pos after-bullet) (= (point) pos))
20874 (goto-char after-bullet))
20875 ;; Reversed case: Move point to special position when
20876 ;; point was already at beginning of line and command is
20877 ;; repeated.
20878 (when (and (= (point) pos) (eq last-command this-command))
20879 (goto-char after-bullet))))))))
20880 (org-no-warnings
20881 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
20883 (defun org-end-of-line (&optional arg)
20884 "Go to the end of the line.
20885 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
20886 first attempt, and only move to after the tags when the cursor is already
20887 beyond the end of the headline."
20888 (interactive "P")
20889 (let ((special (if (consp org-special-ctrl-a/e)
20890 (cdr org-special-ctrl-a/e)
20891 org-special-ctrl-a/e)))
20892 (cond
20893 ((or (not special) arg
20894 (not (or (org-at-heading-p) (org-at-item-p) (org-at-drawer-p))))
20895 (call-interactively
20896 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
20897 ((fboundp 'move-end-of-line) 'move-end-of-line)
20898 (t 'end-of-line))))
20899 ((org-at-heading-p)
20900 (let ((pos (point)))
20901 (beginning-of-line 1)
20902 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
20903 (if (eq special t)
20904 (if (or (< pos (match-beginning 1))
20905 (= pos (match-end 0)))
20906 (goto-char (match-beginning 1))
20907 (goto-char (match-end 0)))
20908 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
20909 (goto-char (match-end 0))
20910 (goto-char (match-beginning 1))))
20911 (call-interactively (if (fboundp 'move-end-of-line)
20912 'move-end-of-line
20913 'end-of-line)))))
20914 ((org-at-drawer-p)
20915 (move-end-of-line 1)
20916 (when (overlays-at (1- (point))) (backward-char 1)))
20917 ;; At an item: Move before any hidden text.
20918 (t (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-no-warnings
20923 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
20925 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
20926 (define-key org-mode-map "\C-e" 'org-end-of-line)
20928 (defun org-backward-sentence (&optional arg)
20929 "Go to beginning of sentence, or beginning of table field.
20930 This will call `backward-sentence' or `org-table-beginning-of-field',
20931 depending on context."
20932 (interactive "P")
20933 (cond
20934 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
20935 (t (call-interactively 'backward-sentence))))
20937 (defun org-forward-sentence (&optional arg)
20938 "Go to end of sentence, or end of table field.
20939 This will call `forward-sentence' or `org-table-end-of-field',
20940 depending on context."
20941 (interactive "P")
20942 (cond
20943 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
20944 (t (call-interactively 'forward-sentence))))
20946 (define-key org-mode-map "\M-a" 'org-backward-sentence)
20947 (define-key org-mode-map "\M-e" 'org-forward-sentence)
20949 (defun org-kill-line (&optional arg)
20950 "Kill line, to tags or end of line."
20951 (interactive "P")
20952 (cond
20953 ((or (not org-special-ctrl-k)
20954 (bolp)
20955 (not (org-at-heading-p)))
20956 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
20957 org-ctrl-k-protect-subtree)
20958 (if (or (eq org-ctrl-k-protect-subtree 'error)
20959 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
20960 (error "C-k aborted - would kill hidden subtree")))
20961 (call-interactively
20962 (if (and (boundp 'visual-line-mode) visual-line-mode) 'kill-visual-line 'kill-line)))
20963 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
20964 (kill-region (point) (match-beginning 1))
20965 (org-set-tags nil t))
20966 (t (kill-region (point) (point-at-eol)))))
20968 (define-key org-mode-map "\C-k" 'org-kill-line)
20970 (defun org-yank (&optional arg)
20971 "Yank. If the kill is a subtree, treat it specially.
20972 This command will look at the current kill and check if is a single
20973 subtree, or a series of subtrees[1]. If it passes the test, and if the
20974 cursor is at the beginning of a line or after the stars of a currently
20975 empty headline, then the yank is handled specially. How exactly depends
20976 on the value of the following variables, both set by default.
20978 org-yank-folded-subtrees
20979 When set, the subtree(s) will be folded after insertion, but only
20980 if doing so would now swallow text after the yanked text.
20982 org-yank-adjusted-subtrees
20983 When set, the subtree will be promoted or demoted in order to
20984 fit into the local outline tree structure, which means that the level
20985 will be adjusted so that it becomes the smaller one of the two
20986 *visible* surrounding headings.
20988 Any prefix to this command will cause `yank' to be called directly with
20989 no special treatment. In particular, a simple \\[universal-argument] prefix \
20990 will just
20991 plainly yank the text as it is.
20993 \[1] The test checks if the first non-white line is a heading
20994 and if there are no other headings with fewer stars."
20995 (interactive "P")
20996 (org-yank-generic 'yank arg))
20998 (defun org-yank-generic (command arg)
20999 "Perform some yank-like command.
21001 This function implements the behavior described in the `org-yank'
21002 documentation. However, it has been generalized to work for any
21003 interactive command with similar behavior."
21005 ;; pretend to be command COMMAND
21006 (setq this-command command)
21008 (if arg
21009 (call-interactively command)
21011 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
21012 (and (org-kill-is-subtree-p)
21013 (or (bolp)
21014 (and (looking-at "[ \t]*$")
21015 (string-match
21016 "\\`\\*+\\'"
21017 (buffer-substring (point-at-bol) (point)))))))
21018 swallowp)
21019 (cond
21020 ((and subtreep org-yank-folded-subtrees)
21021 (let ((beg (point))
21022 end)
21023 (if (and subtreep org-yank-adjusted-subtrees)
21024 (org-paste-subtree nil nil 'for-yank)
21025 (call-interactively command))
21027 (setq end (point))
21028 (goto-char beg)
21029 (when (and (bolp) subtreep
21030 (not (setq swallowp
21031 (org-yank-folding-would-swallow-text beg end))))
21032 (org-with-limited-levels
21033 (or (looking-at org-outline-regexp)
21034 (re-search-forward org-outline-regexp-bol end t))
21035 (while (and (< (point) end) (looking-at org-outline-regexp))
21036 (hide-subtree)
21037 (org-cycle-show-empty-lines 'folded)
21038 (condition-case nil
21039 (outline-forward-same-level 1)
21040 (error (goto-char end))))))
21041 (when swallowp
21042 (message
21043 "Inserted text not folded because that would swallow text"))
21045 (goto-char end)
21046 (skip-chars-forward " \t\n\r")
21047 (beginning-of-line 1)
21048 (push-mark beg 'nomsg)))
21049 ((and subtreep org-yank-adjusted-subtrees)
21050 (let ((beg (point-at-bol)))
21051 (org-paste-subtree nil nil 'for-yank)
21052 (push-mark beg 'nomsg)))
21054 (call-interactively command))))))
21056 (defun org-yank-folding-would-swallow-text (beg end)
21057 "Would hide-subtree at BEG swallow any text after END?"
21058 (let (level)
21059 (org-with-limited-levels
21060 (save-excursion
21061 (goto-char beg)
21062 (when (or (looking-at org-outline-regexp)
21063 (re-search-forward org-outline-regexp-bol end t))
21064 (setq level (org-outline-level)))
21065 (goto-char end)
21066 (skip-chars-forward " \t\r\n\v\f")
21067 (if (or (eobp)
21068 (and (bolp) (looking-at org-outline-regexp)
21069 (<= (org-outline-level) level)))
21070 nil ; Nothing would be swallowed
21071 t))))) ; something would swallow
21073 (define-key org-mode-map "\C-y" 'org-yank)
21075 (defun org-truely-invisible-p ()
21076 "Check if point is at a character currently not visible.
21077 This version does not only check the character property, but also
21078 `visible-mode'."
21079 ;; Early versions of noutline don't have `outline-invisible-p'.
21080 (if (org-bound-and-true-p visible-mode)
21082 (outline-invisible-p)))
21084 (defun org-invisible-p2 ()
21085 "Check if point is at a character currently not visible."
21086 (save-excursion
21087 (if (and (eolp) (not (bobp))) (backward-char 1))
21088 ;; Early versions of noutline don't have `outline-invisible-p'.
21089 (outline-invisible-p)))
21091 (defun org-back-to-heading (&optional invisible-ok)
21092 "Call `outline-back-to-heading', but provide a better error message."
21093 (condition-case nil
21094 (outline-back-to-heading invisible-ok)
21095 (error (error "Before first headline at position %d in buffer %s"
21096 (point) (current-buffer)))))
21098 (defun org-beginning-of-defun ()
21099 "Go to the beginning of the subtree, i.e. back to the heading."
21100 (org-back-to-heading))
21101 (defun org-end-of-defun ()
21102 "Go to the end of the subtree."
21103 (org-end-of-subtree nil t))
21105 (defun org-before-first-heading-p ()
21106 "Before first heading?"
21107 (save-excursion
21108 (end-of-line)
21109 (null (re-search-backward org-outline-regexp-bol nil t))))
21111 (defun org-at-heading-p (&optional ignored)
21112 (outline-on-heading-p t))
21113 ;; Compatibility alias with Org versions < 7.8.03
21114 (defalias 'org-on-heading-p 'org-at-heading-p)
21116 (defun org-at-drawer-p nil
21117 "Is cursor at a drawer keyword?"
21118 (save-excursion
21119 (move-beginning-of-line 1)
21120 (looking-at org-drawer-regexp)))
21122 (defun org-at-block-p nil
21123 "Is cursor at a block keyword?"
21124 (save-excursion
21125 (move-beginning-of-line 1)
21126 (looking-at org-block-regexp)))
21128 (defun org-point-at-end-of-empty-headline ()
21129 "If point is at the end of an empty headline, return t, else nil.
21130 If the heading only contains a TODO keyword, it is still still considered
21131 empty."
21132 (and (looking-at "[ \t]*$")
21133 (when org-todo-line-regexp
21134 (save-excursion
21135 (beginning-of-line 1)
21136 (let ((case-fold-search nil))
21137 (looking-at org-todo-line-regexp)
21138 (string= (match-string 3) ""))))))
21140 (defun org-at-heading-or-item-p ()
21141 (or (org-at-heading-p) (org-at-item-p)))
21143 (defun org-at-target-p ()
21144 (or (org-in-regexp org-radio-target-regexp)
21145 (org-in-regexp org-target-regexp)))
21146 ;; Compatibility alias with Org versions < 7.8.03
21147 (defalias 'org-on-target-p 'org-at-target-p)
21149 (defun org-up-heading-all (arg)
21150 "Move to the heading line of which the present line is a subheading.
21151 This function considers both visible and invisible heading lines.
21152 With argument, move up ARG levels."
21153 (if (fboundp 'outline-up-heading-all)
21154 (outline-up-heading-all arg) ; emacs 21 version of outline.el
21155 (outline-up-heading arg t))) ; emacs 22 version of outline.el
21157 (defun org-up-heading-safe ()
21158 "Move to the heading line of which the present line is a subheading.
21159 This version will not throw an error. It will return the level of the
21160 headline found, or nil if no higher level is found.
21162 Also, this function will be a lot faster than `outline-up-heading',
21163 because it relies on stars being the outline starters. This can really
21164 make a significant difference in outlines with very many siblings."
21165 (let (start-level re)
21166 (org-back-to-heading t)
21167 (setq start-level (funcall outline-level))
21168 (if (equal start-level 1)
21170 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
21171 (if (re-search-backward re nil t)
21172 (funcall outline-level)))))
21174 (defun org-first-sibling-p ()
21175 "Is this heading the first child of its parents?"
21176 (interactive)
21177 (let ((re org-outline-regexp-bol)
21178 level l)
21179 (unless (org-at-heading-p t)
21180 (error "Not at a heading"))
21181 (setq level (funcall outline-level))
21182 (save-excursion
21183 (if (not (re-search-backward re nil t))
21185 (setq l (funcall outline-level))
21186 (< l level)))))
21188 (defun org-goto-sibling (&optional previous)
21189 "Goto the next sibling, even if it is invisible.
21190 When PREVIOUS is set, go to the previous sibling instead. Returns t
21191 when a sibling was found. When none is found, return nil and don't
21192 move point."
21193 (let ((fun (if previous 're-search-backward 're-search-forward))
21194 (pos (point))
21195 (re org-outline-regexp-bol)
21196 level l)
21197 (when (condition-case nil (org-back-to-heading t) (error nil))
21198 (setq level (funcall outline-level))
21199 (catch 'exit
21200 (or previous (forward-char 1))
21201 (while (funcall fun re nil t)
21202 (setq l (funcall outline-level))
21203 (when (< l level) (goto-char pos) (throw 'exit nil))
21204 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
21205 (goto-char pos)
21206 nil))))
21208 (defun org-show-siblings ()
21209 "Show all siblings of the current headline."
21210 (save-excursion
21211 (while (org-goto-sibling) (org-flag-heading nil)))
21212 (save-excursion
21213 (while (org-goto-sibling 'previous)
21214 (org-flag-heading nil))))
21216 (defun org-goto-first-child ()
21217 "Goto the first child, even if it is invisible.
21218 Return t when a child was found. Otherwise don't move point and
21219 return nil."
21220 (let (level (pos (point)) (re org-outline-regexp-bol))
21221 (when (condition-case nil (org-back-to-heading t) (error nil))
21222 (setq level (outline-level))
21223 (forward-char 1)
21224 (if (and (re-search-forward re nil t) (> (outline-level) level))
21225 (progn (goto-char (match-beginning 0)) t)
21226 (goto-char pos) nil))))
21228 (defun org-show-hidden-entry ()
21229 "Show an entry where even the heading is hidden."
21230 (save-excursion
21231 (org-show-entry)))
21233 (defun org-flag-heading (flag &optional entry)
21234 "Flag the current heading. FLAG non-nil means make invisible.
21235 When ENTRY is non-nil, show the entire entry."
21236 (save-excursion
21237 (org-back-to-heading t)
21238 ;; Check if we should show the entire entry
21239 (if entry
21240 (progn
21241 (org-show-entry)
21242 (save-excursion
21243 (and (outline-next-heading)
21244 (org-flag-heading nil))))
21245 (outline-flag-region (max (point-min) (1- (point)))
21246 (save-excursion (outline-end-of-heading) (point))
21247 flag))))
21249 (defun org-get-next-sibling ()
21250 "Move to next heading of the same level, and return point.
21251 If there is no such heading, return nil.
21252 This is like outline-next-sibling, but invisible headings are ok."
21253 (let ((level (funcall outline-level)))
21254 (outline-next-heading)
21255 (while (and (not (eobp)) (> (funcall outline-level) level))
21256 (outline-next-heading))
21257 (if (or (eobp) (< (funcall outline-level) level))
21259 (point))))
21261 (defun org-get-last-sibling ()
21262 "Move to previous heading of the same level, and return point.
21263 If there is no such heading, return nil."
21264 (let ((opoint (point))
21265 (level (funcall outline-level)))
21266 (outline-previous-heading)
21267 (when (and (/= (point) opoint) (outline-on-heading-p t))
21268 (while (and (> (funcall outline-level) level)
21269 (not (bobp)))
21270 (outline-previous-heading))
21271 (if (< (funcall outline-level) level)
21273 (point)))))
21275 (defun org-end-of-subtree (&optional invisible-OK to-heading)
21276 ;; This contains an exact copy of the original function, but it uses
21277 ;; `org-back-to-heading', to make it work also in invisible
21278 ;; trees. And is uses an invisible-OK argument.
21279 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
21280 ;; Furthermore, when used inside Org, finding the end of a large subtree
21281 ;; with many children and grandchildren etc, this can be much faster
21282 ;; than the outline version.
21283 (org-back-to-heading invisible-OK)
21284 (let ((first t)
21285 (level (funcall outline-level)))
21286 (if (and (derived-mode-p 'org-mode) (< level 1000))
21287 ;; A true heading (not a plain list item), in Org-mode
21288 ;; This means we can easily find the end by looking
21289 ;; only for the right number of stars. Using a regexp to do
21290 ;; this is so much faster than using a Lisp loop.
21291 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
21292 (forward-char 1)
21293 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
21294 ;; something else, do it the slow way
21295 (while (and (not (eobp))
21296 (or first (> (funcall outline-level) level)))
21297 (setq first nil)
21298 (outline-next-heading)))
21299 (unless to-heading
21300 (if (memq (preceding-char) '(?\n ?\^M))
21301 (progn
21302 ;; Go to end of line before heading
21303 (forward-char -1)
21304 (if (memq (preceding-char) '(?\n ?\^M))
21305 ;; leave blank line before heading
21306 (forward-char -1))))))
21307 (point))
21309 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
21310 "Use Org version in org-mode, for dramatic speed-up."
21311 (if (derived-mode-p 'org-mode)
21312 (progn
21313 (org-end-of-subtree nil t)
21314 (unless (eobp) (backward-char 1)))
21315 ad-do-it))
21317 (defun org-end-of-meta-data-and-drawers ()
21318 "Jump to the first text after meta data and drawers in the current entry.
21319 This will move over empty lines, lines with planning time stamps,
21320 clocking lines, and drawers."
21321 (org-back-to-heading t)
21322 (let ((end (save-excursion (outline-next-heading) (point)))
21323 (re (concat "\\(" org-drawer-regexp "\\)"
21324 "\\|" "[ \t]*" org-keyword-time-regexp)))
21325 (forward-line 1)
21326 (while (re-search-forward re end t)
21327 (if (not (match-end 1))
21328 ;; empty or planning line
21329 (forward-line 1)
21330 ;; a drawer, find the end
21331 (re-search-forward "^[ \t]*:END:" end 'move)
21332 (forward-line 1)))
21333 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
21334 (point)))
21336 (defun org-forward-same-level (arg &optional invisible-ok)
21337 "Move forward to the arg'th subheading at same level as this one.
21338 Stop at the first and last subheadings of a superior heading.
21339 Normally this only looks at visible headings, but when INVISIBLE-OK is non-nil
21340 it wil also look at invisible ones."
21341 (interactive "p")
21342 (org-back-to-heading invisible-ok)
21343 (org-at-heading-p)
21344 (let* ((level (- (match-end 0) (match-beginning 0) 1))
21345 (re (format "^\\*\\{1,%d\\} " level))
21347 (forward-char 1)
21348 (while (> arg 0)
21349 (while (and (re-search-forward re nil 'move)
21350 (setq l (- (match-end 0) (match-beginning 0) 1))
21351 (= l level)
21352 (not invisible-ok)
21353 (progn (backward-char 1) (outline-invisible-p)))
21354 (if (< l level) (setq arg 1)))
21355 (setq arg (1- arg)))
21356 (beginning-of-line 1)))
21358 (defun org-backward-same-level (arg &optional invisible-ok)
21359 "Move backward to the arg'th subheading at same level as this one.
21360 Stop at the first and last subheadings of a superior heading."
21361 (interactive "p")
21362 (org-back-to-heading)
21363 (org-at-heading-p)
21364 (let* ((level (- (match-end 0) (match-beginning 0) 1))
21365 (re (format "^\\*\\{1,%d\\} " level))
21367 (while (> arg 0)
21368 (while (and (re-search-backward re nil 'move)
21369 (setq l (- (match-end 0) (match-beginning 0) 1))
21370 (= l level)
21371 (not invisible-ok)
21372 (outline-invisible-p))
21373 (if (< l level) (setq arg 1)))
21374 (setq arg (1- arg)))))
21376 (defun org-show-subtree ()
21377 "Show everything after this heading at deeper levels."
21378 (interactive)
21379 (outline-flag-region
21380 (point)
21381 (save-excursion
21382 (org-end-of-subtree t t))
21383 nil))
21385 (defun org-show-entry ()
21386 "Show the body directly following this heading.
21387 Show the heading too, if it is currently invisible."
21388 (interactive)
21389 (save-excursion
21390 (condition-case nil
21391 (progn
21392 (org-back-to-heading t)
21393 (outline-flag-region
21394 (max (point-min) (1- (point)))
21395 (save-excursion
21396 (if (re-search-forward
21397 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
21398 (match-beginning 1)
21399 (point-max)))
21400 nil)
21401 (org-cycle-hide-drawers 'children))
21402 (error nil))))
21404 (defun org-make-options-regexp (kwds &optional extra)
21405 "Make a regular expression for keyword lines."
21406 (concat
21408 "#?[ \t]*\\+\\("
21409 (mapconcat 'regexp-quote kwds "\\|")
21410 (if extra (concat "\\|" extra))
21411 "\\):[ \t]*"
21412 "\\(.*\\)"))
21414 ;; Make isearch reveal the necessary context
21415 (defun org-isearch-end ()
21416 "Reveal context after isearch exits."
21417 (when isearch-success ; only if search was successful
21418 (if (featurep 'xemacs)
21419 ;; Under XEmacs, the hook is run in the correct place,
21420 ;; we directly show the context.
21421 (org-show-context 'isearch)
21422 ;; In Emacs the hook runs *before* restoring the overlays.
21423 ;; So we have to use a one-time post-command-hook to do this.
21424 ;; (Emacs 22 has a special variable, see function `org-mode')
21425 (unless (and (boundp 'isearch-mode-end-hook-quit)
21426 isearch-mode-end-hook-quit)
21427 ;; Only when the isearch was not quitted.
21428 (org-add-hook 'post-command-hook 'org-isearch-post-command
21429 'append 'local)))))
21431 (defun org-isearch-post-command ()
21432 "Remove self from hook, and show context."
21433 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
21434 (org-show-context 'isearch))
21437 ;;;; Integration with and fixes for other packages
21439 ;;; Imenu support
21441 (defvar org-imenu-markers nil
21442 "All markers currently used by Imenu.")
21443 (make-variable-buffer-local 'org-imenu-markers)
21445 (defun org-imenu-new-marker (&optional pos)
21446 "Return a new marker for use by Imenu, and remember the marker."
21447 (let ((m (make-marker)))
21448 (move-marker m (or pos (point)))
21449 (push m org-imenu-markers)
21452 (defun org-imenu-get-tree ()
21453 "Produce the index for Imenu."
21454 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
21455 (setq org-imenu-markers nil)
21456 (let* ((n org-imenu-depth)
21457 (re (concat "^" (org-get-limited-outline-regexp)))
21458 (subs (make-vector (1+ n) nil))
21459 (last-level 0)
21460 m level head)
21461 (save-excursion
21462 (save-restriction
21463 (widen)
21464 (goto-char (point-max))
21465 (while (re-search-backward re nil t)
21466 (setq level (org-reduced-level (funcall outline-level)))
21467 (when (and (<= level n)
21468 (looking-at org-complex-heading-regexp))
21469 (setq head (org-link-display-format
21470 (org-match-string-no-properties 4))
21471 m (org-imenu-new-marker))
21472 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
21473 (if (>= level last-level)
21474 (push (cons head m) (aref subs level))
21475 (push (cons head (aref subs (1+ level))) (aref subs level))
21476 (loop for i from (1+ level) to n do (aset subs i nil)))
21477 (setq last-level level)))))
21478 (aref subs 1)))
21480 (eval-after-load "imenu"
21481 '(progn
21482 (add-hook 'imenu-after-jump-hook
21483 (lambda ()
21484 (if (derived-mode-p 'org-mode)
21485 (org-show-context 'org-goto))))))
21487 (defun org-link-display-format (link)
21488 "Replace a link with either the description, or the link target
21489 if no description is present"
21490 (save-match-data
21491 (if (string-match org-bracket-link-analytic-regexp link)
21492 (replace-match (if (match-end 5)
21493 (match-string 5 link)
21494 (concat (match-string 1 link)
21495 (match-string 3 link)))
21496 nil t link)
21497 link)))
21499 (defun org-toggle-link-display ()
21500 "Toggle the literal or descriptive display of links."
21501 (interactive)
21502 (if org-descriptive-links
21503 (progn (org-remove-from-invisibility-spec '(org-link))
21504 (org-restart-font-lock)
21505 (setq org-descriptive-links nil))
21506 (progn (add-to-invisibility-spec '(org-link))
21507 (org-restart-font-lock)
21508 (setq org-descriptive-links t))))
21510 ;; Speedbar support
21512 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
21513 "Overlay marking the agenda restriction line in speedbar.")
21514 (overlay-put org-speedbar-restriction-lock-overlay
21515 'face 'org-agenda-restriction-lock)
21516 (overlay-put org-speedbar-restriction-lock-overlay
21517 'help-echo "Agendas are currently limited to this item.")
21518 (org-detach-overlay org-speedbar-restriction-lock-overlay)
21520 (defun org-speedbar-set-agenda-restriction ()
21521 "Restrict future agenda commands to the location at point in speedbar.
21522 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
21523 (interactive)
21524 (require 'org-agenda)
21525 (let (p m tp np dir txt)
21526 (cond
21527 ((setq p (text-property-any (point-at-bol) (point-at-eol)
21528 'org-imenu t))
21529 (setq m (get-text-property p 'org-imenu-marker))
21530 (with-current-buffer (marker-buffer m)
21531 (goto-char m)
21532 (org-agenda-set-restriction-lock 'subtree)))
21533 ((setq p (text-property-any (point-at-bol) (point-at-eol)
21534 'speedbar-function 'speedbar-find-file))
21535 (setq tp (previous-single-property-change
21536 (1+ p) 'speedbar-function)
21537 np (next-single-property-change
21538 tp 'speedbar-function)
21539 dir (speedbar-line-directory)
21540 txt (buffer-substring-no-properties (or tp (point-min))
21541 (or np (point-max))))
21542 (with-current-buffer (find-file-noselect
21543 (let ((default-directory dir))
21544 (expand-file-name txt)))
21545 (unless (derived-mode-p 'org-mode)
21546 (error "Cannot restrict to non-Org-mode file"))
21547 (org-agenda-set-restriction-lock 'file)))
21548 (t (error "Don't know how to restrict Org-mode's agenda")))
21549 (move-overlay org-speedbar-restriction-lock-overlay
21550 (point-at-bol) (point-at-eol))
21551 (setq current-prefix-arg nil)
21552 (org-agenda-maybe-redo)))
21554 (eval-after-load "speedbar"
21555 '(progn
21556 (speedbar-add-supported-extension ".org")
21557 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
21558 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
21559 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
21560 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
21561 (add-hook 'speedbar-visiting-tag-hook
21562 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
21564 ;;; Fixes and Hacks for problems with other packages
21566 ;; Make flyspell not check words in links, to not mess up our keymap
21567 (defun org-mode-flyspell-verify ()
21568 "Don't let flyspell put overlays at active buttons, or on
21569 {todo,all-time,additional-option-like}-keywords."
21570 (let ((pos (max (1- (point)) (point-min)))
21571 (word (thing-at-point 'word)))
21572 (and (not (get-text-property pos 'keymap))
21573 (not (get-text-property pos 'org-no-flyspell))
21574 (not (member word org-todo-keywords-1))
21575 (not (member word org-all-time-keywords))
21576 (not (member word org-additional-option-like-keywords)))))
21578 (defun org-remove-flyspell-overlays-in (beg end)
21579 "Remove flyspell overlays in region."
21580 (and (org-bound-and-true-p flyspell-mode)
21581 (fboundp 'flyspell-delete-region-overlays)
21582 (flyspell-delete-region-overlays beg end))
21583 (add-text-properties beg end '(org-no-flyspell t)))
21585 ;; Make `bookmark-jump' shows the jump location if it was hidden.
21586 (eval-after-load "bookmark"
21587 '(if (boundp 'bookmark-after-jump-hook)
21588 ;; We can use the hook
21589 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
21590 ;; Hook not available, use advice
21591 (defadvice bookmark-jump (after org-make-visible activate)
21592 "Make the position visible."
21593 (org-bookmark-jump-unhide))))
21595 ;; Make sure saveplace shows the location if it was hidden
21596 (eval-after-load "saveplace"
21597 '(defadvice save-place-find-file-hook (after org-make-visible activate)
21598 "Make the position visible."
21599 (org-bookmark-jump-unhide)))
21601 ;; Make sure ecb shows the location if it was hidden
21602 (eval-after-load "ecb"
21603 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
21604 "Make hierarchy visible when jumping into location from ECB tree buffer."
21605 (if (derived-mode-p 'org-mode)
21606 (org-show-context))))
21608 (defun org-bookmark-jump-unhide ()
21609 "Unhide the current position, to show the bookmark location."
21610 (and (derived-mode-p 'org-mode)
21611 (or (outline-invisible-p)
21612 (save-excursion (goto-char (max (point-min) (1- (point))))
21613 (outline-invisible-p)))
21614 (org-show-context 'bookmark-jump)))
21616 ;; Make session.el ignore our circular variable
21617 (eval-after-load "session"
21618 '(add-to-list 'session-globals-exclude 'org-mark-ring))
21620 ;;;; Experimental code
21622 (defun org-closed-in-range ()
21623 "Sparse tree of items closed in a certain time range.
21624 Still experimental, may disappear in the future."
21625 (interactive)
21626 ;; Get the time interval from the user.
21627 (let* ((time1 (org-float-time
21628 (org-read-date nil 'to-time nil "Starting date: ")))
21629 (time2 (org-float-time
21630 (org-read-date nil 'to-time nil "End date:")))
21631 ;; callback function
21632 (callback (lambda ()
21633 (let ((time
21634 (org-float-time
21635 (apply 'encode-time
21636 (org-parse-time-string
21637 (match-string 1))))))
21638 ;; check if time in interval
21639 (and (>= time time1) (<= time time2))))))
21640 ;; make tree, check each match with the callback
21641 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
21643 ;;;; Finish up
21645 (provide 'org)
21647 (run-hooks 'org-load-hook)
21649 ;;; org.el ends here