Require parse-time for `org-read-date-get-relative'
[org-mode/org-tableheadings.git] / lisp / org.el
blobed73613ee1e466cb7b0469ac3d6cd6f8426bb7d8
1 ;;; org.el --- Outline-based notes management and organizer
2 ;; Carstens outline-mode for keeping track of everything.
3 ;; Copyright (C) 2004-2011 Free Software Foundation, Inc.
4 ;;
5 ;; Author: Carsten Dominik <carsten at orgmode dot org>
6 ;; Maintainer: Bastien Guerry <bzg at gnu dot org>
7 ;; Keywords: outlines, hypermedia, calendar, wp
8 ;; Homepage: http://orgmode.org
9 ;; Version: 7.7
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)
79 ;; Emacs 22 calendar compatibility: Make sure the new variables are available
80 (when (fboundp 'defvaralias)
81 (unless (boundp 'calendar-view-holidays-initially-flag)
82 (defvaralias 'calendar-view-holidays-initially-flag
83 'view-calendar-holidays-initially))
84 (unless (boundp 'calendar-view-diary-initially-flag)
85 (defvaralias 'calendar-view-diary-initially-flag
86 'view-diary-entries-initially))
87 (unless (boundp 'diary-fancy-buffer)
88 (defvaralias 'diary-fancy-buffer 'fancy-diary-buffer)))
90 (require 'outline) (require 'noutline)
91 ;; Other stuff we need.
92 (require 'time-date)
93 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
94 (require 'easymenu)
95 (require 'overlay)
97 (require 'org-macs)
98 (require 'org-entities)
99 (require 'org-compat)
100 (require 'org-faces)
101 (require 'org-list)
102 (require 'org-pcomplete)
103 (require 'org-src)
104 (require 'org-footnote)
106 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
107 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
108 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
109 (declare-function org-pop-to-buffer-same-window "org-compat" (&optional buffer-or-name norecord label))
110 (declare-function org-at-clock-log-p "org-clock" ())
111 (declare-function org-clock-timestamps-up "org-clock" ())
112 (declare-function org-clock-timestamps-down "org-clock" ())
114 ;; babel
115 (require 'ob)
116 (require 'ob-table)
117 (require 'ob-lob)
118 (require 'ob-ref)
119 (require 'ob-tangle)
120 (require 'ob-comint)
121 (require 'ob-keys)
123 ;; load languages based on value of `org-babel-load-languages'
124 (defvar org-babel-load-languages)
125 ;;;###autoload
126 (defun org-babel-do-load-languages (sym value)
127 "Load the languages defined in `org-babel-load-languages'."
128 (set-default sym value)
129 (mapc (lambda (pair)
130 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
131 (if active
132 (progn
133 (require (intern (concat "ob-" lang))))
134 (progn
135 (funcall 'fmakunbound
136 (intern (concat "org-babel-execute:" lang)))
137 (funcall 'fmakunbound
138 (intern (concat "org-babel-expand-body:" lang)))))))
139 org-babel-load-languages))
141 (defcustom org-babel-load-languages '((emacs-lisp . t))
142 "Languages which can be evaluated in Org-mode buffers.
143 This list can be used to load support for any of the languages
144 below, note that each language will depend on a different set of
145 system executables and/or Emacs modes. When a language is
146 \"loaded\", then code blocks in that language can be evaluated
147 with `org-babel-execute-src-block' bound by default to C-c
148 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
149 be set to remove code block evaluation from the C-c C-c
150 keybinding. By default only Emacs Lisp (which has no
151 requirements) is loaded."
152 :group 'org-babel
153 :set 'org-babel-do-load-languages
154 :type '(alist :tag "Babel Languages"
155 :key-type
156 (choice
157 (const :tag "Awk" awk)
158 (const :tag "C" C)
159 (const :tag "R" R)
160 (const :tag "Asymptote" asymptote)
161 (const :tag "Calc" calc)
162 (const :tag "Clojure" clojure)
163 (const :tag "CSS" css)
164 (const :tag "Ditaa" ditaa)
165 (const :tag "Dot" dot)
166 (const :tag "Emacs Lisp" emacs-lisp)
167 (const :tag "Fortran" fortran)
168 (const :tag "Gnuplot" gnuplot)
169 (const :tag "Haskell" haskell)
170 (const :tag "Java" java)
171 (const :tag "Javascript" js)
172 (const :tag "Latex" latex)
173 (const :tag "Ledger" ledger)
174 (const :tag "Lilypond" lilypond)
175 (const :tag "Maxima" maxima)
176 (const :tag "Matlab" matlab)
177 (const :tag "Mscgen" mscgen)
178 (const :tag "Ocaml" ocaml)
179 (const :tag "Octave" octave)
180 (const :tag "Org" org)
181 (const :tag "Perl" perl)
182 (const :tag "PlantUML" plantuml)
183 (const :tag "Python" python)
184 (const :tag "Ruby" ruby)
185 (const :tag "Sass" sass)
186 (const :tag "Scheme" scheme)
187 (const :tag "Screen" screen)
188 (const :tag "Shell Script" sh)
189 (const :tag "Shen" shen)
190 (const :tag "Sql" sql)
191 (const :tag "Sqlite" sqlite))
192 :value-type (boolean :tag "Activate" :value t)))
194 ;;;; Customization variables
195 (defcustom org-clone-delete-id nil
196 "Remove ID property of clones of a subtree.
197 When non-nil, clones of a subtree don't inherit the ID property.
198 Otherwise they inherit the ID property with a new unique
199 identifier."
200 :type 'boolean
201 :group 'org-id)
203 ;;; Version
205 (defconst org-version "7.7"
206 "The version number of the file org.el.")
208 (defun org-version (&optional here)
209 "Show the org-mode version in the echo area.
210 With prefix arg HERE, insert it at point."
211 (interactive "P")
212 (let* ((origin default-directory)
213 (version org-version)
214 (git-version)
215 (dir (concat (file-name-directory (locate-library "org")) "../" )))
216 (when (and (file-exists-p (expand-file-name ".git" dir))
217 (executable-find "git"))
218 (unwind-protect
219 (progn
220 (cd dir)
221 (when (eql 0 (shell-command "git describe --abbrev=4 HEAD"))
222 (with-current-buffer "*Shell Command Output*"
223 (goto-char (point-min))
224 (setq git-version (buffer-substring (point) (point-at-eol))))
225 (subst-char-in-string ?- ?. git-version t)
226 (when (string-match "\\S-"
227 (shell-command-to-string
228 "git diff-index --name-only HEAD --"))
229 (setq git-version (concat git-version ".dirty")))
230 (setq version (concat version " (" git-version ")"))))
231 (cd origin)))
232 (setq version (format "Org-mode version %s" version))
233 (if here (insert version))
234 (message version)))
236 ;;; Compatibility constants
238 ;;; The custom variables
240 (defgroup org nil
241 "Outline-based notes management and organizer."
242 :tag "Org"
243 :group 'outlines
244 :group 'calendar)
246 (defcustom org-mode-hook nil
247 "Mode hook for Org-mode, run after the mode was turned on."
248 :group 'org
249 :type 'hook)
251 (defcustom org-load-hook nil
252 "Hook that is run after org.el has been loaded."
253 :group 'org
254 :type 'hook)
256 (defcustom org-log-buffer-setup-hook nil
257 "Hook that is run after an Org log buffer is created."
258 :group 'org
259 :type 'hook)
261 (defvar org-modules) ; defined below
262 (defvar org-modules-loaded nil
263 "Have the modules been loaded already?")
265 (defun org-load-modules-maybe (&optional force)
266 "Load all extensions listed in `org-modules'."
267 (when (or force (not org-modules-loaded))
268 (mapc (lambda (ext)
269 (condition-case nil (require ext)
270 (error (message "Problems while trying to load feature `%s'" ext))))
271 org-modules)
272 (setq org-modules-loaded t)))
274 (defun org-set-modules (var value)
275 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
276 (set var value)
277 (when (featurep 'org)
278 (org-load-modules-maybe 'force)))
280 (when (org-bound-and-true-p org-modules)
281 (let ((a (member 'org-infojs org-modules)))
282 (and a (setcar a 'org-jsinfo))))
284 (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)
285 "Modules that should always be loaded together with org.el.
286 If a description starts with <C>, the file is not part of Emacs
287 and loading it will require that you have downloaded and properly installed
288 the org-mode distribution.
290 You can also use this system to load external packages (i.e. neither Org
291 core modules, nor modules from the CONTRIB directory). Just add symbols
292 to the end of the list. If the package is called org-xyz.el, then you need
293 to add the symbol `xyz', and the package must have a call to
295 (provide 'org-xyz)"
296 :group 'org
297 :set 'org-set-modules
298 :type
299 '(set :greedy t
300 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
301 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
302 (const :tag " crypt: Encryption of subtrees" org-crypt)
303 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
304 (const :tag " docview: Links to doc-view buffers" org-docview)
305 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
306 (const :tag " id: Global IDs for identifying entries" org-id)
307 (const :tag " info: Links to Info nodes" org-info)
308 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
309 (const :tag " habit: Track your consistency with habits" org-habit)
310 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
311 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
312 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
313 (const :tag " mew Links to Mew folders/messages" org-mew)
314 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
315 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
316 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
317 (const :tag " special-blocks: Turn blocks into LaTeX envs and HTML divs" org-special-blocks)
318 (const :tag " vm: Links to VM folders/messages" org-vm)
319 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
320 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
321 (const :tag " mouse: Additional mouse support" org-mouse)
322 (const :tag " TaskJuggler: Export tasks to a TaskJuggler project" org-taskjuggler)
324 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
325 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
326 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
327 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
328 (const :tag "C collector: Collect properties into tables" org-collector)
329 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
330 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
331 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
332 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
333 (const :tag "C eval: Include command output as text" org-eval)
334 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
335 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
336 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
337 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
338 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
340 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
342 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
343 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
344 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
345 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
346 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
347 (const :tag "C mac-link-grabber Grab links and URLs from various Mac applications" org-mac-link-grabber)
348 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
349 (const :tag "C mtags: Support for muse-like tags" org-mtags)
350 (const :tag "C odt: OpenDocumentText exporter for Org-mode" org-odt)
351 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
352 (const :tag "C registry: A registry for Org-mode links" org-registry)
353 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
354 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
355 (const :tag "C secretary: Team management with org-mode" org-secretary)
356 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
357 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
358 (const :tag "C track: Keep up with Org-mode development" org-track)
359 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
360 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
361 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
363 (defcustom org-support-shift-select nil
364 "Non-nil means make shift-cursor commands select text when possible.
366 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
367 start selecting a region, or enlarge regions started in this way.
368 In Org-mode, in special contexts, these same keys are used for
369 other purposes, important enough to compete with shift selection.
370 Org tries to balance these needs by supporting `shift-select-mode'
371 outside these special contexts, under control of this variable.
373 The default of this variable is nil, to avoid confusing behavior. Shifted
374 cursor keys will then execute Org commands in the following contexts:
375 - on a headline, changing TODO state (left/right) and priority (up/down)
376 - on a time stamp, changing the time
377 - in a plain list item, changing the bullet type
378 - in a property definition line, switching between allowed values
379 - in the BEGIN line of a clock table (changing the time block).
380 Outside these contexts, the commands will throw an error.
382 When this variable is t and the cursor is not in a special
383 context, Org-mode will support shift-selection for making and
384 enlarging regions. To make this more effective, the bullet
385 cycling will no longer happen anywhere in an item line, but only
386 if the cursor is exactly on the bullet.
388 If you set this variable to the symbol `always', then the keys
389 will not be special in headlines, property lines, and item lines,
390 to make shift selection work there as well. If this is what you
391 want, you can use the following alternative commands: `C-c C-t'
392 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
393 can be used to switch TODO sets, `C-c -' to cycle item bullet
394 types, and properties can be edited by hand or in column view.
396 However, when the cursor is on a timestamp, shift-cursor commands
397 will still edit the time stamp - this is just too good to give up.
399 XEmacs user should have this variable set to nil, because
400 `shift-select-mode' is in Emacs 23 or later only."
401 :group 'org
402 :type '(choice
403 (const :tag "Never" nil)
404 (const :tag "When outside special context" t)
405 (const :tag "Everywhere except timestamps" always)))
407 (defcustom org-loop-over-headlines-in-active-region nil
408 "Shall some commands act upon headlines in the active region?
410 When set to `t', some commands will be performed in all headlines
411 within the active region.
413 When set to a string, those commands will be performed on the
414 matching headlines within the active region. Such string must be
415 a tags/property/todo match as it is used in the agenda tags view.
417 The list of commands is:
418 - `org-schedule'
419 - `org-deadline'"
420 :type '(choice (const :tag "Don't loop" nil)
421 (const :tag "All headlines in active region" t)
422 (string :tag "Tags/Property/Todo matcher"))
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 :type '(choice
492 (const :tag "Always interpret" t)
493 (const :tag "Only with braces" {})
494 (const :tag "Never interpret" nil)))
496 (if (fboundp 'defvaralias)
497 (defvaralias 'org-export-with-sub-superscripts 'org-use-sub-superscripts))
500 (defcustom org-startup-with-beamer-mode nil
501 "Non-nil means turn on `org-beamer-mode' on startup.
502 This can also be configured on a per-file basis by adding one of
503 the following lines anywhere in the buffer:
505 #+STARTUP: beamer"
506 :group 'org-startup
507 :type 'boolean)
509 (defcustom org-startup-align-all-tables nil
510 "Non-nil means align all tables when visiting a file.
511 This is useful when the column width in tables is forced with <N> cookies
512 in table fields. Such tables will look correct only after the first re-align.
513 This can also be configured on a per-file basis by adding one of
514 the following lines anywhere in the buffer:
515 #+STARTUP: align
516 #+STARTUP: noalign"
517 :group 'org-startup
518 :type 'boolean)
520 (defcustom org-startup-with-inline-images nil
521 "Non-nil means show inline images when loading a new Org file.
522 This can also be configured on a per-file basis by adding one of
523 the following lines anywhere in the buffer:
524 #+STARTUP: inlineimages
525 #+STARTUP: noinlineimages"
526 :group 'org-startup
527 :type 'boolean)
529 (defcustom org-insert-mode-line-in-empty-file nil
530 "Non-nil means insert the first line setting Org-mode in empty files.
531 When the function `org-mode' is called interactively in an empty file, this
532 normally means that the file name does not automatically trigger Org-mode.
533 To ensure that the file will always be in Org-mode in the future, a
534 line enforcing Org-mode will be inserted into the buffer, if this option
535 has been set."
536 :group 'org-startup
537 :type 'boolean)
539 (defcustom org-replace-disputed-keys nil
540 "Non-nil means use alternative key bindings for some keys.
541 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
542 These keys are also used by other packages like shift-selection-mode'
543 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
544 If you want to use Org-mode together with one of these other modes,
545 or more generally if you would like to move some Org-mode commands to
546 other keys, set this variable and configure the keys with the variable
547 `org-disputed-keys'.
549 This option is only relevant at load-time of Org-mode, and must be set
550 *before* org.el is loaded. Changing it requires a restart of Emacs to
551 become effective."
552 :group 'org-startup
553 :type 'boolean)
555 (defcustom org-use-extra-keys nil
556 "Non-nil means use extra key sequence definitions for certain commands.
557 This happens automatically if you run XEmacs or if `window-system'
558 is nil. This variable lets you do the same manually. You must
559 set it before loading org.
561 Example: on Carbon Emacs 22 running graphically, with an external
562 keyboard on a Powerbook, the default way of setting M-left might
563 not work for either Alt or ESC. Setting this variable will make
564 it work for ESC."
565 :group 'org-startup
566 :type 'boolean)
568 (if (fboundp 'defvaralias)
569 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
571 (defcustom org-disputed-keys
572 '(([(shift up)] . [(meta p)])
573 ([(shift down)] . [(meta n)])
574 ([(shift left)] . [(meta -)])
575 ([(shift right)] . [(meta +)])
576 ([(control shift right)] . [(meta shift +)])
577 ([(control shift left)] . [(meta shift -)]))
578 "Keys for which Org-mode and other modes compete.
579 This is an alist, cars are the default keys, second element specifies
580 the alternative to use when `org-replace-disputed-keys' is t.
582 Keys can be specified in any syntax supported by `define-key'.
583 The value of this option takes effect only at Org-mode's startup,
584 therefore you'll have to restart Emacs to apply it after changing."
585 :group 'org-startup
586 :type 'alist)
588 (defun org-key (key)
589 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
590 Or return the original if not disputed.
591 Also apply the translations defined in `org-xemacs-key-equivalents'."
592 (when org-replace-disputed-keys
593 (let* ((nkey (key-description key))
594 (x (org-find-if (lambda (x)
595 (equal (key-description (car x)) nkey))
596 org-disputed-keys)))
597 (setq key (if x (cdr x) key))))
598 (when (featurep 'xemacs)
599 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
600 key)
602 (defun org-find-if (predicate seq)
603 (catch 'exit
604 (while seq
605 (if (funcall predicate (car seq))
606 (throw 'exit (car seq))
607 (pop seq)))))
609 (defun org-defkey (keymap key def)
610 "Define a key, possibly translated, as returned by `org-key'."
611 (define-key keymap (org-key key) def))
613 (defcustom org-ellipsis nil
614 "The ellipsis to use in the Org-mode outline.
615 When nil, just use the standard three dots. When a string, use that instead,
616 When a face, use the standard 3 dots, but with the specified face.
617 The change affects only Org-mode (which will then use its own display table).
618 Changing this requires executing `M-x org-mode' in a buffer to become
619 effective."
620 :group 'org-startup
621 :type '(choice (const :tag "Default" nil)
622 (face :tag "Face" :value org-warning)
623 (string :tag "String" :value "...#")))
625 (defvar org-display-table nil
626 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
628 (defgroup org-keywords nil
629 "Keywords in Org-mode."
630 :tag "Org Keywords"
631 :group 'org)
633 (defcustom org-deadline-string "DEADLINE:"
634 "String to mark deadline entries.
635 A deadline is this string, followed by a time stamp. Should be a word,
636 terminated by a colon. You can insert a schedule keyword and
637 a timestamp with \\[org-deadline].
638 Changes become only effective after restarting Emacs."
639 :group 'org-keywords
640 :type 'string)
642 (defcustom org-scheduled-string "SCHEDULED:"
643 "String to mark scheduled TODO entries.
644 A schedule is this string, followed by a time stamp. Should be a word,
645 terminated by a colon. You can insert a schedule keyword and
646 a timestamp with \\[org-schedule].
647 Changes become only effective after restarting Emacs."
648 :group 'org-keywords
649 :type 'string)
651 (defcustom org-closed-string "CLOSED:"
652 "String used as the prefix for timestamps logging closing a TODO entry."
653 :group 'org-keywords
654 :type 'string)
656 (defcustom org-clock-string "CLOCK:"
657 "String used as prefix for timestamps clocking work hours on an item."
658 :group 'org-keywords
659 :type 'string)
661 (defcustom org-comment-string "COMMENT"
662 "Entries starting with this keyword will never be exported.
663 An entry can be toggled between COMMENT and normal with
664 \\[org-toggle-comment].
665 Changes become only effective after restarting Emacs."
666 :group 'org-keywords
667 :type 'string)
669 (defcustom org-quote-string "QUOTE"
670 "Entries starting with this keyword will be exported in fixed-width font.
671 Quoting applies only to the text in the entry following the headline, and does
672 not extend beyond the next headline, even if that is lower level.
673 An entry can be toggled between QUOTE and normal with
674 \\[org-toggle-fixed-width-section]."
675 :group 'org-keywords
676 :type 'string)
678 (defconst org-repeat-re
679 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)"
680 "Regular expression for specifying repeated events.
681 After a match, group 1 contains the repeat expression.")
683 (defgroup org-structure nil
684 "Options concerning the general structure of Org-mode files."
685 :tag "Org Structure"
686 :group 'org)
688 (defgroup org-reveal-location nil
689 "Options about how to make context of a location visible."
690 :tag "Org Reveal Location"
691 :group 'org-structure)
693 (defconst org-context-choice
694 '(choice
695 (const :tag "Always" t)
696 (const :tag "Never" nil)
697 (repeat :greedy t :tag "Individual contexts"
698 (cons
699 (choice :tag "Context"
700 (const agenda)
701 (const org-goto)
702 (const occur-tree)
703 (const tags-tree)
704 (const link-search)
705 (const mark-goto)
706 (const bookmark-jump)
707 (const isearch)
708 (const default))
709 (boolean))))
710 "Contexts for the reveal options.")
712 (defcustom org-show-hierarchy-above '((default . t))
713 "Non-nil means show full hierarchy when revealing a location.
714 Org-mode often shows locations in an org-mode file which might have
715 been invisible before. When this is set, the hierarchy of headings
716 above the exposed location is shown.
717 Turning this off for example for sparse trees makes them very compact.
718 Instead of t, this can also be an alist specifying this option for different
719 contexts. Valid contexts are
720 agenda when exposing an entry from the agenda
721 org-goto when using the command `org-goto' on key C-c C-j
722 occur-tree when using the command `org-occur' on key C-c /
723 tags-tree when constructing a sparse tree based on tags matches
724 link-search when exposing search matches associated with a link
725 mark-goto when exposing the jump goal of a mark
726 bookmark-jump when exposing a bookmark location
727 isearch when exiting from an incremental search
728 default default for all contexts not set explicitly"
729 :group 'org-reveal-location
730 :type org-context-choice)
732 (defcustom org-show-following-heading '((default . nil))
733 "Non-nil means show following heading when revealing a location.
734 Org-mode often shows locations in an org-mode file which might have
735 been invisible before. When this is set, the heading following the
736 match is shown.
737 Turning this off for example for sparse trees makes them very compact,
738 but makes it harder to edit the location of the match. In such a case,
739 use the command \\[org-reveal] to show more context.
740 Instead of t, this can also be an alist specifying this option for different
741 contexts. See `org-show-hierarchy-above' for valid contexts."
742 :group 'org-reveal-location
743 :type org-context-choice)
745 (defcustom org-show-siblings '((default . nil) (isearch t))
746 "Non-nil means show all sibling heading when revealing a location.
747 Org-mode often shows locations in an org-mode file which might have
748 been invisible before. When this is set, the sibling of the current entry
749 heading are all made visible. If `org-show-hierarchy-above' is t,
750 the same happens on each level of the hierarchy above the current entry.
752 By default this is on for the isearch context, off for all other contexts.
753 Turning this off for example for sparse trees makes them very compact,
754 but makes it harder to edit the location of the match. In such a case,
755 use the command \\[org-reveal] to show more context.
756 Instead of t, this can also be an alist specifying this option for different
757 contexts. See `org-show-hierarchy-above' for valid contexts."
758 :group 'org-reveal-location
759 :type org-context-choice)
761 (defcustom org-show-entry-below '((default . nil))
762 "Non-nil means show the entry below a headline when revealing a location.
763 Org-mode often shows locations in an org-mode file which might have
764 been invisible before. When this is set, the text below the headline that is
765 exposed is also shown.
767 By default this is off for all contexts.
768 Instead of t, this can also be an alist specifying this option for different
769 contexts. See `org-show-hierarchy-above' for valid contexts."
770 :group 'org-reveal-location
771 :type org-context-choice)
773 (defcustom org-indirect-buffer-display 'other-window
774 "How should indirect tree buffers be displayed?
775 This applies to indirect buffers created with the commands
776 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
777 Valid values are:
778 current-window Display in the current window
779 other-window Just display in another window.
780 dedicated-frame Create one new frame, and re-use it each time.
781 new-frame Make a new frame each time. Note that in this case
782 previously-made indirect buffers are kept, and you need to
783 kill these buffers yourself."
784 :group 'org-structure
785 :group 'org-agenda-windows
786 :type '(choice
787 (const :tag "In current window" current-window)
788 (const :tag "In current frame, other window" other-window)
789 (const :tag "Each time a new frame" new-frame)
790 (const :tag "One dedicated frame" dedicated-frame)))
792 (defcustom org-use-speed-commands nil
793 "Non-nil means activate single letter commands at beginning of a headline.
794 This may also be a function to test for appropriate locations where speed
795 commands should be active."
796 :group 'org-structure
797 :type '(choice
798 (const :tag "Never" nil)
799 (const :tag "At beginning of headline stars" t)
800 (function)))
802 (defcustom org-speed-commands-user nil
803 "Alist of additional speed commands.
804 This list will be checked before `org-speed-commands-default'
805 when the variable `org-use-speed-commands' is non-nil
806 and when the cursor is at the beginning of a headline.
807 The car if each entry is a string with a single letter, which must
808 be assigned to `self-insert-command' in the global map.
809 The cdr is either a command to be called interactively, a function
810 to be called, or a form to be evaluated.
811 An entry that is just a list with a single string will be interpreted
812 as a descriptive headline that will be added when listing the speed
813 commands in the Help buffer using the `?' speed command."
814 :group 'org-structure
815 :type '(repeat :value ("k" . ignore)
816 (choice :value ("k" . ignore)
817 (list :tag "Descriptive Headline" (string :tag "Headline"))
818 (cons :tag "Letter and Command"
819 (string :tag "Command letter")
820 (choice
821 (function)
822 (sexp))))))
824 (defgroup org-cycle nil
825 "Options concerning visibility cycling in Org-mode."
826 :tag "Org Cycle"
827 :group 'org-structure)
829 (defcustom org-cycle-skip-children-state-if-no-children t
830 "Non-nil means skip CHILDREN state in entries that don't have any."
831 :group 'org-cycle
832 :type 'boolean)
834 (defcustom org-cycle-max-level nil
835 "Maximum level which should still be subject to visibility cycling.
836 Levels higher than this will, for cycling, be treated as text, not a headline.
837 When `org-odd-levels-only' is set, a value of N in this variable actually
838 means 2N-1 stars as the limiting headline.
839 When nil, cycle all levels.
840 Note that the limiting level of cycling is also influenced by
841 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
842 `org-inlinetask-min-level' is, cycling will be limited to levels one less
843 than its value."
844 :group 'org-cycle
845 :type '(choice
846 (const :tag "No limit" nil)
847 (integer :tag "Maximum level")))
849 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK")
850 "Names of drawers. Drawers are not opened by cycling on the headline above.
851 Drawers only open with a TAB on the drawer line itself. A drawer looks like
852 this:
853 :DRAWERNAME:
854 .....
855 :END:
856 The drawer \"PROPERTIES\" is special for capturing properties through
857 the property API.
859 Drawers can be defined on the per-file basis with a line like:
861 #+DRAWERS: HIDDEN STATE PROPERTIES"
862 :group 'org-structure
863 :group 'org-cycle
864 :type '(repeat (string :tag "Drawer Name")))
866 (defcustom org-hide-block-startup nil
867 "Non-nil means entering Org-mode will fold all blocks.
868 This can also be set in on a per-file basis with
870 #+STARTUP: hideblocks
871 #+STARTUP: showblocks"
872 :group 'org-startup
873 :group 'org-cycle
874 :type 'boolean)
876 (defcustom org-cycle-global-at-bob nil
877 "Cycle globally if cursor is at beginning of buffer and not at a headline.
878 This makes it possible to do global cycling without having to use S-TAB or
879 \\[universal-argument] TAB. For this special case to work, the first line \
880 of the buffer
881 must not be a headline - it may be empty or some other text. When used in
882 this way, `org-cycle-hook' is disables temporarily, to make sure the
883 cursor stays at the beginning of the buffer.
884 When this option is nil, don't do anything special at the beginning
885 of the buffer."
886 :group 'org-cycle
887 :type 'boolean)
889 (defcustom org-cycle-level-after-item/entry-creation t
890 "Non-nil means cycle entry level or item indentation in new empty entries.
892 When the cursor is at the end of an empty headline, i.e with only stars
893 and maybe a TODO keyword, TAB will then switch the entry to become a child,
894 and then all possible ancestor states, before returning to the original state.
895 This makes data entry extremely fast: M-RET to create a new headline,
896 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
898 When the cursor is at the end of an empty plain list item, one TAB will
899 make it a subitem, two or more tabs will back up to make this an item
900 higher up in the item hierarchy."
901 :group 'org-cycle
902 :type 'boolean)
904 (defcustom org-cycle-emulate-tab t
905 "Where should `org-cycle' emulate TAB.
906 nil Never
907 white Only in completely white lines
908 whitestart Only at the beginning of lines, before the first non-white char
909 t Everywhere except in headlines
910 exc-hl-bol Everywhere except at the start of a headline
911 If TAB is used in a place where it does not emulate TAB, the current subtree
912 visibility is cycled."
913 :group 'org-cycle
914 :type '(choice (const :tag "Never" nil)
915 (const :tag "Only in completely white lines" white)
916 (const :tag "Before first char in a line" whitestart)
917 (const :tag "Everywhere except in headlines" t)
918 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
921 (defcustom org-cycle-separator-lines 2
922 "Number of empty lines needed to keep an empty line between collapsed trees.
923 If you leave an empty line between the end of a subtree and the following
924 headline, this empty line is hidden when the subtree is folded.
925 Org-mode will leave (exactly) one empty line visible if the number of
926 empty lines is equal or larger to the number given in this variable.
927 So the default 2 means at least 2 empty lines after the end of a subtree
928 are needed to produce free space between a collapsed subtree and the
929 following headline.
931 If the number is negative, and the number of empty lines is at least -N,
932 all empty lines are shown.
934 Special case: when 0, never leave empty lines in collapsed view."
935 :group 'org-cycle
936 :type 'integer)
937 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
939 (defcustom org-pre-cycle-hook nil
940 "Hook that is run before visibility cycling is happening.
941 The function(s) in this hook must accept a single argument which indicates
942 the new state that will be set right after running this hook. The
943 argument is a symbol. Before a global state change, it can have the values
944 `overview', `content', or `all'. Before a local state change, it can have
945 the values `folded', `children', or `subtree'."
946 :group 'org-cycle
947 :type 'hook)
949 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
950 org-cycle-hide-drawers
951 org-cycle-show-empty-lines
952 org-optimize-window-after-visibility-change)
953 "Hook that is run after `org-cycle' has changed the buffer visibility.
954 The function(s) in this hook must accept a single argument which indicates
955 the new state that was set by the most recent `org-cycle' command. The
956 argument is a symbol. After a global state change, it can have the values
957 `overview', `content', or `all'. After a local state change, it can have
958 the values `folded', `children', or `subtree'."
959 :group 'org-cycle
960 :type 'hook)
962 (defgroup org-edit-structure nil
963 "Options concerning structure editing in Org-mode."
964 :tag "Org Edit Structure"
965 :group 'org-structure)
967 (defcustom org-odd-levels-only nil
968 "Non-nil means skip even levels and only use odd levels for the outline.
969 This has the effect that two stars are being added/taken away in
970 promotion/demotion commands. It also influences how levels are
971 handled by the exporters.
972 Changing it requires restart of `font-lock-mode' to become effective
973 for fontification also in regions already fontified.
974 You may also set this on a per-file basis by adding one of the following
975 lines to the buffer:
977 #+STARTUP: odd
978 #+STARTUP: oddeven"
979 :group 'org-edit-structure
980 :group 'org-appearance
981 :type 'boolean)
983 (defcustom org-adapt-indentation t
984 "Non-nil means adapt indentation to outline node level.
986 When this variable is set, Org assumes that you write outlines by
987 indenting text in each node to align with the headline (after the stars).
988 The following issues are influenced by this variable:
990 - When this is set and the *entire* text in an entry is indented, the
991 indentation is increased by one space in a demotion command, and
992 decreased by one in a promotion command. If any line in the entry
993 body starts with text at column 0, indentation is not changed at all.
995 - Property drawers and planning information is inserted indented when
996 this variable s set. When nil, they will not be indented.
998 - TAB indents a line relative to context. The lines below a headline
999 will be indented when this variable is set.
1001 Note that this is all about true indentation, by adding and removing
1002 space characters. See also `org-indent.el' which does level-dependent
1003 indentation in a virtual way, i.e. at display time in Emacs."
1004 :group 'org-edit-structure
1005 :type 'boolean)
1007 (defcustom org-special-ctrl-a/e nil
1008 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1010 When t, `C-a' will bring back the cursor to the beginning of the
1011 headline text, i.e. after the stars and after a possible TODO keyword.
1012 In an item, this will be the position after the bullet.
1013 When the cursor is already at that position, another `C-a' will bring
1014 it to the beginning of the line.
1016 `C-e' will jump to the end of the headline, ignoring the presence of tags
1017 in the headline. A second `C-e' will then jump to the true end of the
1018 line, after any tags. This also means that, when this variable is
1019 non-nil, `C-e' also will never jump beyond the end of the heading of a
1020 folded section, i.e. not after the ellipses.
1022 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
1023 going to the true line boundary first. Only a directly following, identical
1024 keypress will bring the cursor to the special positions.
1026 This may also be a cons cell where the behavior for `C-a' and `C-e' is
1027 set separately."
1028 :group 'org-edit-structure
1029 :type '(choice
1030 (const :tag "off" nil)
1031 (const :tag "on: after stars/bullet and before tags first" t)
1032 (const :tag "reversed: true line boundary first" reversed)
1033 (cons :tag "Set C-a and C-e separately"
1034 (choice :tag "Special C-a"
1035 (const :tag "off" nil)
1036 (const :tag "on: after stars/bullet first" t)
1037 (const :tag "reversed: before stars/bullet first" reversed))
1038 (choice :tag "Special C-e"
1039 (const :tag "off" nil)
1040 (const :tag "on: before tags first" t)
1041 (const :tag "reversed: after tags first" reversed)))))
1042 (if (fboundp 'defvaralias)
1043 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
1045 (defcustom org-special-ctrl-k nil
1046 "Non-nil means `C-k' will behave specially in headlines.
1047 When nil, `C-k' will call the default `kill-line' command.
1048 When t, the following will happen while the cursor is in the headline:
1050 - When the cursor is at the beginning of a headline, kill the entire
1051 line and possible the folded subtree below the line.
1052 - When in the middle of the headline text, kill the headline up to the tags.
1053 - When after the headline text, kill the tags."
1054 :group 'org-edit-structure
1055 :type 'boolean)
1057 (defcustom org-ctrl-k-protect-subtree nil
1058 "Non-nil means, do not delete a hidden subtree with C-k.
1059 When set to the symbol `error', simply throw an error when C-k is
1060 used to kill (part-of) a headline that has hidden text behind it.
1061 Any other non-nil value will result in a query to the user, if it is
1062 OK to kill that hidden subtree. When nil, kill without remorse."
1063 :group 'org-edit-structure
1064 :type '(choice
1065 (const :tag "Do not protect hidden subtrees" nil)
1066 (const :tag "Protect hidden subtrees with a security query" t)
1067 (const :tag "Never kill a hidden subtree with C-k" error)))
1069 (defcustom org-catch-invisible-edits nil
1070 "Check if in invisible region before inserting or deleting a character.
1071 Valid values are:
1073 nil Do not check, so just do invisible edits.
1074 error Throw an error and do nothing.
1075 show Make point visible, and do the requested edit.
1076 show-and-error Make point visible, then throw an error and abort the edit.
1077 smart Make point visible, and do insertion/deletion if it is
1078 adjacent to visible text and the change feels predictable.
1079 Never delete a previously invisible character or add in the
1080 middle or right after an invisible region. Basically, this
1081 allows insertion and backward-delete right before ellipses.
1082 FIXME: maybe in this case we should not even show?"
1083 :group 'org-edit-structure
1084 :type '(choice
1085 (const :tag "Do not check" nil)
1086 (const :tag "Throw error when trying to edit" error)
1087 (const :tag "Unhide, but do not do the edit" show-and-error)
1088 (const :tag "Show invisible part and do the edit" show)
1089 (const :tag "Be smart and do the right thing" smart)))
1091 (defcustom org-yank-folded-subtrees t
1092 "Non-nil means when yanking subtrees, fold them.
1093 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1094 it starts with a heading and all other headings in it are either children
1095 or siblings, then fold all the subtrees. However, do this only if no
1096 text after the yank would be swallowed into a folded tree by this action."
1097 :group 'org-edit-structure
1098 :type 'boolean)
1100 (defcustom org-yank-adjusted-subtrees nil
1101 "Non-nil means when yanking subtrees, adjust the level.
1102 With this setting, `org-paste-subtree' is used to insert the subtree, see
1103 this function for details."
1104 :group 'org-edit-structure
1105 :type 'boolean)
1107 (defcustom org-M-RET-may-split-line '((default . t))
1108 "Non-nil means M-RET will split the line at the cursor position.
1109 When nil, it will go to the end of the line before making a
1110 new line.
1111 You may also set this option in a different way for different
1112 contexts. Valid contexts are:
1114 headline when creating a new headline
1115 item when creating a new item
1116 table in a table field
1117 default the value to be used for all contexts not explicitly
1118 customized"
1119 :group 'org-structure
1120 :group 'org-table
1121 :type '(choice
1122 (const :tag "Always" t)
1123 (const :tag "Never" nil)
1124 (repeat :greedy t :tag "Individual contexts"
1125 (cons
1126 (choice :tag "Context"
1127 (const headline)
1128 (const item)
1129 (const table)
1130 (const default))
1131 (boolean)))))
1134 (defcustom org-insert-heading-respect-content nil
1135 "Non-nil means insert new headings after the current subtree.
1136 When nil, the new heading is created directly after the current line.
1137 The commands \\[org-insert-heading-respect-content] and
1138 \\[org-insert-todo-heading-respect-content] turn this variable on
1139 for the duration of the command."
1140 :group 'org-structure
1141 :type 'boolean)
1143 (defcustom org-blank-before-new-entry '((heading . auto)
1144 (plain-list-item . auto))
1145 "Should `org-insert-heading' leave a blank line before new heading/item?
1146 The value is an alist, with `heading' and `plain-list-item' as CAR,
1147 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1148 which case Org will look at the surrounding headings/items and try to
1149 make an intelligent decision whether to insert a blank line or not.
1151 For plain lists, if the variable `org-empty-line-terminates-plain-lists' is
1152 set, the setting here is ignored and no empty line is inserted, to avoid
1153 breaking the list structure."
1154 :group 'org-edit-structure
1155 :type '(list
1156 (cons (const heading)
1157 (choice (const :tag "Never" nil)
1158 (const :tag "Always" t)
1159 (const :tag "Auto" auto)))
1160 (cons (const plain-list-item)
1161 (choice (const :tag "Never" nil)
1162 (const :tag "Always" t)
1163 (const :tag "Auto" auto)))))
1165 (defcustom org-insert-heading-hook nil
1166 "Hook being run after inserting a new heading."
1167 :group 'org-edit-structure
1168 :type 'hook)
1170 (defcustom org-enable-fixed-width-editor t
1171 "Non-nil means lines starting with \":\" are treated as fixed-width.
1172 This currently only means they are never auto-wrapped.
1173 When nil, such lines will be treated like ordinary lines.
1174 See also the QUOTE keyword."
1175 :group 'org-edit-structure
1176 :type 'boolean)
1178 (defcustom org-goto-auto-isearch t
1179 "Non-nil means typing characters in `org-goto' starts incremental search."
1180 :group 'org-edit-structure
1181 :type 'boolean)
1183 (defgroup org-sparse-trees nil
1184 "Options concerning sparse trees in Org-mode."
1185 :tag "Org Sparse Trees"
1186 :group 'org-structure)
1188 (defcustom org-highlight-sparse-tree-matches t
1189 "Non-nil means highlight all matches that define a sparse tree.
1190 The highlights will automatically disappear the next time the buffer is
1191 changed by an edit command."
1192 :group 'org-sparse-trees
1193 :type 'boolean)
1195 (defcustom org-remove-highlights-with-change t
1196 "Non-nil means any change to the buffer will remove temporary highlights.
1197 Such highlights are created by `org-occur' and `org-clock-display'.
1198 When nil, `C-c C-c needs to be used to get rid of the highlights.
1199 The highlights created by `org-preview-latex-fragment' always need
1200 `C-c C-c' to be removed."
1201 :group 'org-sparse-trees
1202 :group 'org-time
1203 :type 'boolean)
1206 (defcustom org-occur-hook '(org-first-headline-recenter)
1207 "Hook that is run after `org-occur' has constructed a sparse tree.
1208 This can be used to recenter the window to show as much of the structure
1209 as possible."
1210 :group 'org-sparse-trees
1211 :type 'hook)
1213 (defgroup org-imenu-and-speedbar nil
1214 "Options concerning imenu and speedbar in Org-mode."
1215 :tag "Org Imenu and Speedbar"
1216 :group 'org-structure)
1218 (defcustom org-imenu-depth 2
1219 "The maximum level for Imenu access to Org-mode headlines.
1220 This also applied for speedbar access."
1221 :group 'org-imenu-and-speedbar
1222 :type 'integer)
1224 (defgroup org-table nil
1225 "Options concerning tables in Org-mode."
1226 :tag "Org Table"
1227 :group 'org)
1229 (defcustom org-enable-table-editor 'optimized
1230 "Non-nil means lines starting with \"|\" are handled by the table editor.
1231 When nil, such lines will be treated like ordinary lines.
1233 When equal to the symbol `optimized', the table editor will be optimized to
1234 do the following:
1235 - Automatic overwrite mode in front of whitespace in table fields.
1236 This makes the structure of the table stay in tact as long as the edited
1237 field does not exceed the column width.
1238 - Minimize the number of realigns. Normally, the table is aligned each time
1239 TAB or RET are pressed to move to another field. With optimization this
1240 happens only if changes to a field might have changed the column width.
1241 Optimization requires replacing the functions `self-insert-command',
1242 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1243 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1244 very good at guessing when a re-align will be necessary, but you can always
1245 force one with \\[org-ctrl-c-ctrl-c].
1247 If you would like to use the optimized version in Org-mode, but the
1248 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1250 This variable can be used to turn on and off the table editor during a session,
1251 but in order to toggle optimization, a restart is required.
1253 See also the variable `org-table-auto-blank-field'."
1254 :group 'org-table
1255 :type '(choice
1256 (const :tag "off" nil)
1257 (const :tag "on" t)
1258 (const :tag "on, optimized" optimized)))
1260 (defcustom org-self-insert-cluster-for-undo t
1261 "Non-nil means cluster self-insert commands for undo when possible.
1262 If this is set, then, like in the Emacs command loop, 20 consecutive
1263 characters will be undone together.
1264 This is configurable, because there is some impact on typing performance."
1265 :group 'org-table
1266 :type 'boolean)
1268 (defcustom org-table-tab-recognizes-table.el t
1269 "Non-nil means TAB will automatically notice a table.el table.
1270 When it sees such a table, it moves point into it and - if necessary -
1271 calls `table-recognize-table'."
1272 :group 'org-table-editing
1273 :type 'boolean)
1275 (defgroup org-link nil
1276 "Options concerning links in Org-mode."
1277 :tag "Org Link"
1278 :group 'org)
1280 (defvar org-link-abbrev-alist-local nil
1281 "Buffer-local version of `org-link-abbrev-alist', which see.
1282 The value of this is taken from the #+LINK lines.")
1283 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1285 (defcustom org-link-abbrev-alist nil
1286 "Alist of link abbreviations.
1287 The car of each element is a string, to be replaced at the start of a link.
1288 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1289 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1291 [[linkkey:tag][description]]
1293 The 'linkkey' must be a word word, starting with a letter, followed
1294 by letters, numbers, '-' or '_'.
1296 If REPLACE is a string, the tag will simply be appended to create the link.
1297 If the string contains \"%s\", the tag will be inserted there. Alternatively,
1298 the placeholder \"%h\" will cause a url-encoded version of the tag to
1299 be inserted at that point (see the function `url-hexify-string').
1301 REPLACE may also be a function that will be called with the tag as the
1302 only argument to create the link, which should be returned as a string.
1304 See the manual for examples."
1305 :group 'org-link
1306 :type '(repeat
1307 (cons
1308 (string :tag "Protocol")
1309 (choice
1310 (string :tag "Format")
1311 (function)))))
1313 (defcustom org-descriptive-links t
1314 "Non-nil means Org will display descriptive links.
1315 E.g. [[http://orgmode.org][Org website]] will be displayed as
1316 \"Org Website\", hiding the link itself and just displaying its
1317 description. When set to `nil', Org will display the full links
1318 literally.
1320 You can interactively set the value of this variable by calling
1321 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1322 :group 'org-link
1323 :type 'boolean)
1325 (defcustom org-link-file-path-type 'adaptive
1326 "How the path name in file links should be stored.
1327 Valid values are:
1329 relative Relative to the current directory, i.e. the directory of the file
1330 into which the link is being inserted.
1331 absolute Absolute path, if possible with ~ for home directory.
1332 noabbrev Absolute path, no abbreviation of home directory.
1333 adaptive Use relative path for files in the current directory and sub-
1334 directories of it. For other files, use an absolute path."
1335 :group 'org-link
1336 :type '(choice
1337 (const relative)
1338 (const absolute)
1339 (const noabbrev)
1340 (const adaptive)))
1342 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1343 "Types of links that should be activated in Org-mode files.
1344 This is a list of symbols, each leading to the activation of a certain link
1345 type. In principle, it does not hurt to turn on most link types - there may
1346 be a small gain when turning off unused link types. The types are:
1348 bracket The recommended [[link][description]] or [[link]] links with hiding.
1349 angle Links in angular brackets that may contain whitespace like
1350 <bbdb:Carsten Dominik>.
1351 plain Plain links in normal text, no whitespace, like http://google.com.
1352 radio Text that is matched by a radio target, see manual for details.
1353 tag Tag settings in a headline (link to tag search).
1354 date Time stamps (link to calendar).
1355 footnote Footnote labels.
1357 Changing this variable requires a restart of Emacs to become effective."
1358 :group 'org-link
1359 :type '(set :greedy t
1360 (const :tag "Double bracket links" bracket)
1361 (const :tag "Angular bracket links" angle)
1362 (const :tag "Plain text links" plain)
1363 (const :tag "Radio target matches" radio)
1364 (const :tag "Tags" tag)
1365 (const :tag "Timestamps" date)
1366 (const :tag "Footnotes" footnote)))
1368 (defcustom org-make-link-description-function nil
1369 "Function to use to generate link descriptions from links.
1370 If nil the link location will be used. This function must take
1371 two parameters; the first is the link and the second the
1372 description `org-insert-link' has generated, and should return the
1373 description to use."
1374 :group 'org-link
1375 :type 'function)
1377 (defgroup org-link-store nil
1378 "Options concerning storing links in Org-mode."
1379 :tag "Org Store Link"
1380 :group 'org-link)
1382 (defcustom org-email-link-description-format "Email %c: %.30s"
1383 "Format of the description part of a link to an email or usenet message.
1384 The following %-escapes will be replaced by corresponding information:
1386 %F full \"From\" field
1387 %f name, taken from \"From\" field, address if no name
1388 %T full \"To\" field
1389 %t first name in \"To\" field, address if no name
1390 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1391 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1392 %s subject
1393 %d date
1394 %m message-id.
1396 You may use normal field width specification between the % and the letter.
1397 This is for example useful to limit the length of the subject.
1399 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1400 :group 'org-link-store
1401 :type 'string)
1403 (defcustom org-from-is-user-regexp
1404 (let (r1 r2)
1405 (when (and user-mail-address (not (string= user-mail-address "")))
1406 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1407 (when (and user-full-name (not (string= user-full-name "")))
1408 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1409 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1410 "Regexp matched against the \"From:\" header of an email or usenet message.
1411 It should match if the message is from the user him/herself."
1412 :group 'org-link-store
1413 :type 'regexp)
1415 (defcustom org-link-to-org-use-id 'create-if-interactive-and-no-custom-id
1416 "Non-nil means storing a link to an Org file will use entry IDs.
1418 Note that before this variable is even considered, org-id must be loaded,
1419 so please customize `org-modules' and turn it on.
1421 The variable can have the following values:
1423 t Create an ID if needed to make a link to the current entry.
1425 create-if-interactive
1426 If `org-store-link' is called directly (interactively, as a user
1427 command), do create an ID to support the link. But when doing the
1428 job for remember, only use the ID if it already exists. The
1429 purpose of this setting is to avoid proliferation of unwanted
1430 IDs, just because you happen to be in an Org file when you
1431 call `org-remember' that automatically and preemptively
1432 creates a link. If you do want to get an ID link in a remember
1433 template to an entry not having an ID, create it first by
1434 explicitly creating a link to it, using `C-c C-l' first.
1436 create-if-interactive-and-no-custom-id
1437 Like create-if-interactive, but do not create an ID if there is
1438 a CUSTOM_ID property defined in the entry. This is the default.
1440 use-existing
1441 Use existing ID, do not create one.
1443 nil Never use an ID to make a link, instead link using a text search for
1444 the headline text."
1445 :group 'org-link-store
1446 :type '(choice
1447 (const :tag "Create ID to make link" t)
1448 (const :tag "Create if storing link interactively"
1449 create-if-interactive)
1450 (const :tag "Create if storing link interactively and no CUSTOM_ID is present"
1451 create-if-interactive-and-no-custom-id)
1452 (const :tag "Only use existing" use-existing)
1453 (const :tag "Do not use ID to create link" nil)))
1455 (defcustom org-context-in-file-links t
1456 "Non-nil means file links from `org-store-link' contain context.
1457 A search string will be added to the file name with :: as separator and
1458 used to find the context when the link is activated by the command
1459 `org-open-at-point'. When this option is t, the entire active region
1460 will be placed in the search string of the file link. If set to a
1461 positive integer, only the first n lines of context will be stored.
1463 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1464 negates this setting for the duration of the command."
1465 :group 'org-link-store
1466 :type '(choice boolean integer))
1468 (defcustom org-keep-stored-link-after-insertion nil
1469 "Non-nil means keep link in list for entire session.
1471 The command `org-store-link' adds a link pointing to the current
1472 location to an internal list. These links accumulate during a session.
1473 The command `org-insert-link' can be used to insert links into any
1474 Org-mode file (offering completion for all stored links). When this
1475 option is nil, every link which has been inserted once using \\[org-insert-link]
1476 will be removed from the list, to make completing the unused links
1477 more efficient."
1478 :group 'org-link-store
1479 :type 'boolean)
1481 (defgroup org-link-follow nil
1482 "Options concerning following links in Org-mode."
1483 :tag "Org Follow Link"
1484 :group 'org-link)
1486 (defcustom org-link-translation-function nil
1487 "Function to translate links with different syntax to Org syntax.
1488 This can be used to translate links created for example by the Planner
1489 or emacs-wiki packages to Org syntax.
1490 The function must accept two parameters, a TYPE containing the link
1491 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1492 which is everything after the link protocol. It should return a cons
1493 with possibly modified values of type and path.
1494 Org contains a function for this, so if you set this variable to
1495 `org-translate-link-from-planner', you should be able follow many
1496 links created by planner."
1497 :group 'org-link-follow
1498 :type 'function)
1500 (defcustom org-follow-link-hook nil
1501 "Hook that is run after a link has been followed."
1502 :group 'org-link-follow
1503 :type 'hook)
1505 (defcustom org-tab-follows-link nil
1506 "Non-nil means on links TAB will follow the link.
1507 Needs to be set before org.el is loaded.
1508 This really should not be used, it does not make sense, and the
1509 implementation is bad."
1510 :group 'org-link-follow
1511 :type 'boolean)
1513 (defcustom org-return-follows-link nil
1514 "Non-nil means on links RET will follow the link."
1515 :group 'org-link-follow
1516 :type 'boolean)
1518 (defcustom org-mouse-1-follows-link
1519 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1520 "Non-nil means mouse-1 on a link will follow the link.
1521 A longer mouse click will still set point. Does not work on XEmacs.
1522 Needs to be set before org.el is loaded."
1523 :group 'org-link-follow
1524 :type 'boolean)
1526 (defcustom org-mark-ring-length 4
1527 "Number of different positions to be recorded in the ring.
1528 Changing this requires a restart of Emacs to work correctly."
1529 :group 'org-link-follow
1530 :type 'integer)
1532 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1533 "Non-nil means internal links in Org files must exactly match a headline.
1534 When nil, the link search tries to match a phrase with all words
1535 in the search text."
1536 :group 'org-link-follow
1537 :type '(choice
1538 (const :tag "Use fuzzy text search" nil)
1539 (const :tag "Match only exact headline" t)
1540 (const :tag "Match exact headline or query to create it"
1541 query-to-create)))
1543 (defcustom org-link-frame-setup
1544 '((vm . vm-visit-folder-other-frame)
1545 (gnus . org-gnus-no-new-news)
1546 (file . find-file-other-window)
1547 (wl . wl-other-frame))
1548 "Setup the frame configuration for following links.
1549 When following a link with Emacs, it may often be useful to display
1550 this link in another window or frame. This variable can be used to
1551 set this up for the different types of links.
1552 For VM, use any of
1553 `vm-visit-folder'
1554 `vm-visit-folder-other-window'
1555 `vm-visit-folder-other-frame'
1556 For Gnus, use any of
1557 `gnus'
1558 `gnus-other-frame'
1559 `org-gnus-no-new-news'
1560 For FILE, use any of
1561 `find-file'
1562 `find-file-other-window'
1563 `find-file-other-frame'
1564 For Wanderlust use any of
1565 `wl'
1566 `wl-other-frame'
1567 For the calendar, use the variable `calendar-setup'.
1568 For BBDB, it is currently only possible to display the matches in
1569 another window."
1570 :group 'org-link-follow
1571 :type '(list
1572 (cons (const vm)
1573 (choice
1574 (const vm-visit-folder)
1575 (const vm-visit-folder-other-window)
1576 (const vm-visit-folder-other-frame)))
1577 (cons (const gnus)
1578 (choice
1579 (const gnus)
1580 (const gnus-other-frame)
1581 (const org-gnus-no-new-news)))
1582 (cons (const file)
1583 (choice
1584 (const find-file)
1585 (const find-file-other-window)
1586 (const find-file-other-frame)))
1587 (cons (const wl)
1588 (choice
1589 (const wl)
1590 (const wl-other-frame)))))
1592 (defcustom org-display-internal-link-with-indirect-buffer nil
1593 "Non-nil means use indirect buffer to display infile links.
1594 Activating internal links (from one location in a file to another location
1595 in the same file) normally just jumps to the location. When the link is
1596 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1597 is displayed in
1598 another window. When this option is set, the other window actually displays
1599 an indirect buffer clone of the current buffer, to avoid any visibility
1600 changes to the current buffer."
1601 :group 'org-link-follow
1602 :type 'boolean)
1604 (defcustom org-open-non-existing-files nil
1605 "Non-nil means `org-open-file' will open non-existing files.
1606 When nil, an error will be generated.
1607 This variable applies only to external applications because they
1608 might choke on non-existing files. If the link is to a file that
1609 will be opened in Emacs, the variable is ignored."
1610 :group 'org-link-follow
1611 :type 'boolean)
1613 (defcustom org-open-directory-means-index-dot-org nil
1614 "Non-nil means a link to a directory really means to index.org.
1615 When nil, following a directory link will run dired or open a finder/explorer
1616 window on that directory."
1617 :group 'org-link-follow
1618 :type 'boolean)
1620 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1621 "Function and arguments to call for following mailto links.
1622 This is a list with the first element being a Lisp function, and the
1623 remaining elements being arguments to the function. In string arguments,
1624 %a will be replaced by the address, and %s will be replaced by the subject
1625 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1626 :group 'org-link-follow
1627 :type '(choice
1628 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1629 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1630 (const :tag "message-mail" (message-mail "%a" "%s"))
1631 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1633 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1634 "Non-nil means ask for confirmation before executing shell links.
1635 Shell links can be dangerous: just think about a link
1637 [[shell:rm -rf ~/*][Google Search]]
1639 This link would show up in your Org-mode document as \"Google Search\",
1640 but really it would remove your entire home directory.
1641 Therefore we advise against setting this variable to nil.
1642 Just change it to `y-or-n-p' if you want to confirm with a
1643 single keystroke rather than having to type \"yes\"."
1644 :group 'org-link-follow
1645 :type '(choice
1646 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1647 (const :tag "with y-or-n (faster)" y-or-n-p)
1648 (const :tag "no confirmation (dangerous)" nil)))
1649 (put 'org-confirm-shell-link-function
1650 'safe-local-variable
1651 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1653 (defcustom org-confirm-shell-link-not-regexp ""
1654 "A regexp to skip confirmation for shell links."
1655 :group 'org-link-follow
1656 :type 'regexp)
1658 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1659 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1660 Elisp links can be dangerous: just think about a link
1662 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1664 This link would show up in your Org-mode document as \"Google Search\",
1665 but really it would remove your entire home directory.
1666 Therefore we advise against setting this variable to nil.
1667 Just change it to `y-or-n-p' if you want to confirm with a
1668 single keystroke rather than having to type \"yes\"."
1669 :group 'org-link-follow
1670 :type '(choice
1671 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1672 (const :tag "with y-or-n (faster)" y-or-n-p)
1673 (const :tag "no confirmation (dangerous)" nil)))
1674 (put 'org-confirm-shell-link-function
1675 'safe-local-variable
1676 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1678 (defcustom org-confirm-elisp-link-not-regexp ""
1679 "A regexp to skip confirmation for Elisp links."
1680 :group 'org-link-follow
1681 :type 'regexp)
1683 (defconst org-file-apps-defaults-gnu
1684 '((remote . emacs)
1685 (system . mailcap)
1686 (t . mailcap))
1687 "Default file applications on a UNIX or GNU/Linux system.
1688 See `org-file-apps'.")
1690 (defconst org-file-apps-defaults-macosx
1691 '((remote . emacs)
1692 (t . "open %s")
1693 (system . "open %s")
1694 ("ps.gz" . "gv %s")
1695 ("eps.gz" . "gv %s")
1696 ("dvi" . "xdvi %s")
1697 ("fig" . "xfig %s"))
1698 "Default file applications on a MacOS X system.
1699 The system \"open\" is known as a default, but we use X11 applications
1700 for some files for which the OS does not have a good default.
1701 See `org-file-apps'.")
1703 (defconst org-file-apps-defaults-windowsnt
1704 (list
1705 '(remote . emacs)
1706 (cons t
1707 (list (if (featurep 'xemacs)
1708 'mswindows-shell-execute
1709 'w32-shell-execute)
1710 "open" 'file))
1711 (cons 'system
1712 (list (if (featurep 'xemacs)
1713 'mswindows-shell-execute
1714 'w32-shell-execute)
1715 "open" 'file)))
1716 "Default file applications on a Windows NT system.
1717 The system \"open\" is used for most files.
1718 See `org-file-apps'.")
1720 (defcustom org-file-apps
1722 (auto-mode . emacs)
1723 ("\\.mm\\'" . default)
1724 ("\\.x?html?\\'" . default)
1725 ("\\.pdf\\'" . default)
1727 "External applications for opening `file:path' items in a document.
1728 Org-mode uses system defaults for different file types, but
1729 you can use this variable to set the application for a given file
1730 extension. The entries in this list are cons cells where the car identifies
1731 files and the cdr the corresponding command. Possible values for the
1732 file identifier are
1733 \"string\" A string as a file identifier can be interpreted in different
1734 ways, depending on its contents:
1736 - Alphanumeric characters only:
1737 Match links with this file extension.
1738 Example: (\"pdf\" . \"evince %s\")
1739 to open PDFs with evince.
1741 - Regular expression: Match links where the
1742 filename matches the regexp. If you want to
1743 use groups here, use shy groups.
1745 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1746 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1747 to open *.html and *.xhtml with firefox.
1749 - Regular expression which contains (non-shy) groups:
1750 Match links where the whole link, including \"::\", and
1751 anything after that, matches the regexp.
1752 In a custom command string, %1, %2, etc. are replaced with
1753 the parts of the link that were matched by the groups.
1754 For backwards compatibility, if a command string is given
1755 that does not use any of the group matches, this case is
1756 handled identically to the second one (i.e. match against
1757 file name only).
1758 In a custom lisp form, you can access the group matches with
1759 (match-string n link).
1761 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1762 to open [[file:document.pdf::5]] with evince at page 5.
1764 `directory' Matches a directory
1765 `remote' Matches a remote file, accessible through tramp or efs.
1766 Remote files most likely should be visited through Emacs
1767 because external applications cannot handle such paths.
1768 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1769 so all files Emacs knows how to handle. Using this with
1770 command `emacs' will open most files in Emacs. Beware that this
1771 will also open html files inside Emacs, unless you add
1772 (\"html\" . default) to the list as well.
1773 t Default for files not matched by any of the other options.
1774 `system' The system command to open files, like `open' on Windows
1775 and Mac OS X, and mailcap under GNU/Linux. This is the command
1776 that will be selected if you call `C-c C-o' with a double
1777 \\[universal-argument] \\[universal-argument] prefix.
1779 Possible values for the command are:
1780 `emacs' The file will be visited by the current Emacs process.
1781 `default' Use the default application for this file type, which is the
1782 association for t in the list, most likely in the system-specific
1783 part.
1784 This can be used to overrule an unwanted setting in the
1785 system-specific variable.
1786 `system' Use the system command for opening files, like \"open\".
1787 This command is specified by the entry whose car is `system'.
1788 Most likely, the system-specific version of this variable
1789 does define this command, but you can overrule/replace it
1790 here.
1791 string A command to be executed by a shell; %s will be replaced
1792 by the path to the file.
1793 sexp A Lisp form which will be evaluated. The file path will
1794 be available in the Lisp variable `file'.
1795 For more examples, see the system specific constants
1796 `org-file-apps-defaults-macosx'
1797 `org-file-apps-defaults-windowsnt'
1798 `org-file-apps-defaults-gnu'."
1799 :group 'org-link-follow
1800 :type '(repeat
1801 (cons (choice :value ""
1802 (string :tag "Extension")
1803 (const :tag "System command to open files" system)
1804 (const :tag "Default for unrecognized files" t)
1805 (const :tag "Remote file" remote)
1806 (const :tag "Links to a directory" directory)
1807 (const :tag "Any files that have Emacs modes"
1808 auto-mode))
1809 (choice :value ""
1810 (const :tag "Visit with Emacs" emacs)
1811 (const :tag "Use default" default)
1812 (const :tag "Use the system command" system)
1813 (string :tag "Command")
1814 (sexp :tag "Lisp form")))))
1818 (defgroup org-refile nil
1819 "Options concerning refiling entries in Org-mode."
1820 :tag "Org Refile"
1821 :group 'org)
1823 (defcustom org-directory "~/org"
1824 "Directory with org files.
1825 This is just a default location to look for Org files. There is no need
1826 at all to put your files into this directory. It is only used in the
1827 following situations:
1829 1. When a remember template specifies a target file that is not an
1830 absolute path. The path will then be interpreted relative to
1831 `org-directory'
1832 2. When a remember note is filed away in an interactive way (when exiting the
1833 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1834 with `org-directory' as the default path."
1835 :group 'org-refile
1836 :group 'org-remember
1837 :type 'directory)
1839 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1840 "Default target for storing notes.
1841 Used as a fall back file for org-remember.el and org-capture.el, for
1842 templates that do not specify a target file."
1843 :group 'org-refile
1844 :group 'org-remember
1845 :type '(choice
1846 (const :tag "Default from remember-data-file" nil)
1847 file))
1849 (defcustom org-goto-interface 'outline
1850 "The default interface to be used for `org-goto'.
1851 Allowed values are:
1852 outline The interface shows an outline of the relevant file
1853 and the correct heading is found by moving through
1854 the outline or by searching with incremental search.
1855 outline-path-completion Headlines in the current buffer are offered via
1856 completion. This is the interface also used by
1857 the refile command."
1858 :group 'org-refile
1859 :type '(choice
1860 (const :tag "Outline" outline)
1861 (const :tag "Outline-path-completion" outline-path-completion)))
1863 (defcustom org-goto-max-level 5
1864 "Maximum target level when running `org-goto' with refile interface."
1865 :group 'org-refile
1866 :type 'integer)
1868 (defcustom org-reverse-note-order nil
1869 "Non-nil means store new notes at the beginning of a file or entry.
1870 When nil, new notes will be filed to the end of a file or entry.
1871 This can also be a list with cons cells of regular expressions that
1872 are matched against file names, and values."
1873 :group 'org-remember
1874 :group 'org-refile
1875 :type '(choice
1876 (const :tag "Reverse always" t)
1877 (const :tag "Reverse never" nil)
1878 (repeat :tag "By file name regexp"
1879 (cons regexp boolean))))
1881 (defcustom org-log-refile nil
1882 "Information to record when a task is refiled.
1884 Possible values are:
1886 nil Don't add anything
1887 time Add a time stamp to the task
1888 note Prompt for a note and add it with template `org-log-note-headings'
1890 This option can also be set with on a per-file-basis with
1892 #+STARTUP: nologrefile
1893 #+STARTUP: logrefile
1894 #+STARTUP: lognoterefile
1896 You can have local logging settings for a subtree by setting the LOGGING
1897 property to one or more of these keywords.
1899 When bulk-refiling from the agenda, the value `note' is forbidden and
1900 will temporarily be changed to `time'."
1901 :group 'org-refile
1902 :group 'org-progress
1903 :type '(choice
1904 (const :tag "No logging" nil)
1905 (const :tag "Record timestamp" time)
1906 (const :tag "Record timestamp with note." note)))
1908 (defcustom org-refile-targets nil
1909 "Targets for refiling entries with \\[org-refile].
1910 This is a list of cons cells. Each cell contains:
1911 - a specification of the files to be considered, either a list of files,
1912 or a symbol whose function or variable value will be used to retrieve
1913 a file name or a list of file names. If you use `org-agenda-files' for
1914 that, all agenda files will be scanned for targets. Nil means consider
1915 headings in the current buffer.
1916 - A specification of how to find candidate refile targets. This may be
1917 any of:
1918 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1919 This tag has to be present in all target headlines, inheritance will
1920 not be considered.
1921 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1922 todo keyword.
1923 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1924 headlines that are refiling targets.
1925 - a cons cell (:level . N). Any headline of level N is considered a target.
1926 Note that, when `org-odd-levels-only' is set, level corresponds to
1927 order in hierarchy, not to the number of stars.
1928 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1929 Note that, when `org-odd-levels-only' is set, level corresponds to
1930 order in hierarchy, not to the number of stars.
1932 Each element of this list generates a set of possible targets.
1933 The union of these sets is presented (with completion) to
1934 the user by `org-refile'.
1936 You can set the variable `org-refile-target-verify-function' to a function
1937 to verify each headline found by the simple criteria above.
1939 When this variable is nil, all top-level headlines in the current buffer
1940 are used, equivalent to the value `((nil . (:level . 1))'."
1941 :group 'org-refile
1942 :type '(repeat
1943 (cons
1944 (choice :value org-agenda-files
1945 (const :tag "All agenda files" org-agenda-files)
1946 (const :tag "Current buffer" nil)
1947 (function) (variable) (file))
1948 (choice :tag "Identify target headline by"
1949 (cons :tag "Specific tag" (const :value :tag) (string))
1950 (cons :tag "TODO keyword" (const :value :todo) (string))
1951 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1952 (cons :tag "Level number" (const :value :level) (integer))
1953 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1955 (defcustom org-refile-target-verify-function nil
1956 "Function to verify if the headline at point should be a refile target.
1957 The function will be called without arguments, with point at the
1958 beginning of the headline. It should return t and leave point
1959 where it is if the headline is a valid target for refiling.
1961 If the target should not be selected, the function must return nil.
1962 In addition to this, it may move point to a place from where the search
1963 should be continued. For example, the function may decide that the entire
1964 subtree of the current entry should be excluded and move point to the end
1965 of the subtree."
1966 :group 'org-refile
1967 :type 'function)
1969 (defcustom org-refile-use-cache nil
1970 "Non-nil means cache refile targets to speed up the process.
1971 The cache for a particular file will be updated automatically when
1972 the buffer has been killed, or when any of the marker used for flagging
1973 refile targets no longer points at a live buffer.
1974 If you have added new entries to a buffer that might themselves be targets,
1975 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
1976 find that easier, `C-u C-u C-u C-c C-w'."
1977 :group 'org-refile
1978 :type 'boolean)
1980 (defcustom org-refile-use-outline-path nil
1981 "Non-nil means provide refile targets as paths.
1982 So a level 3 headline will be available as level1/level2/level3.
1984 When the value is `file', also include the file name (without directory)
1985 into the path. In this case, you can also stop the completion after
1986 the file name, to get entries inserted as top level in the file.
1988 When `full-file-path', include the full file path."
1989 :group 'org-refile
1990 :type '(choice
1991 (const :tag "Not" nil)
1992 (const :tag "Yes" t)
1993 (const :tag "Start with file name" file)
1994 (const :tag "Start with full file path" full-file-path)))
1996 (defcustom org-outline-path-complete-in-steps t
1997 "Non-nil means complete the outline path in hierarchical steps.
1998 When Org-mode uses the refile interface to select an outline path
1999 \(see variable `org-refile-use-outline-path'), the completion of
2000 the path can be done is a single go, or if can be done in steps down
2001 the headline hierarchy. Going in steps is probably the best if you
2002 do not use a special completion package like `ido' or `icicles'.
2003 However, when using these packages, going in one step can be very
2004 fast, while still showing the whole path to the entry."
2005 :group 'org-refile
2006 :type 'boolean)
2008 (defcustom org-refile-allow-creating-parent-nodes nil
2009 "Non-nil means allow to create new nodes as refile targets.
2010 New nodes are then created by adding \"/new node name\" to the completion
2011 of an existing node. When the value of this variable is `confirm',
2012 new node creation must be confirmed by the user (recommended)
2013 When nil, the completion must match an existing entry.
2015 Note that, if the new heading is not seen by the criteria
2016 listed in `org-refile-targets', multiple instances of the same
2017 heading would be created by trying again to file under the new
2018 heading."
2019 :group 'org-refile
2020 :type '(choice
2021 (const :tag "Never" nil)
2022 (const :tag "Always" t)
2023 (const :tag "Prompt for confirmation" confirm)))
2025 (defcustom org-refile-active-region-within-subtree nil
2026 "Non-nil means also refile active region within a subtree.
2028 By default `org-refile' doesn't allow refiling regions if they
2029 don't contain a set of subtrees, but it might be convenient to
2030 do so sometimes: in that case, the first line of the region is
2031 converted to a headline before refiling."
2032 :group 'org-refile
2033 :type 'boolean)
2035 (defgroup org-todo nil
2036 "Options concerning TODO items in Org-mode."
2037 :tag "Org TODO"
2038 :group 'org)
2040 (defgroup org-progress nil
2041 "Options concerning Progress logging in Org-mode."
2042 :tag "Org Progress"
2043 :group 'org-time)
2045 (defvar org-todo-interpretation-widgets
2046 '((:tag "Sequence (cycling hits every state)" sequence)
2047 (:tag "Type (cycling directly to DONE)" type))
2048 "The available interpretation symbols for customizing `org-todo-keywords'.
2049 Interested libraries should add to this list.")
2051 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2052 "List of TODO entry keyword sequences and their interpretation.
2053 \\<org-mode-map>This is a list of sequences.
2055 Each sequence starts with a symbol, either `sequence' or `type',
2056 indicating if the keywords should be interpreted as a sequence of
2057 action steps, or as different types of TODO items. The first
2058 keywords are states requiring action - these states will select a headline
2059 for inclusion into the global TODO list Org-mode produces. If one of
2060 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2061 signify that no further action is necessary. If \"|\" is not found,
2062 the last keyword is treated as the only DONE state of the sequence.
2064 The command \\[org-todo] cycles an entry through these states, and one
2065 additional state where no keyword is present. For details about this
2066 cycling, see the manual.
2068 TODO keywords and interpretation can also be set on a per-file basis with
2069 the special #+SEQ_TODO and #+TYP_TODO lines.
2071 Each keyword can optionally specify a character for fast state selection
2072 \(in combination with the variable `org-use-fast-todo-selection')
2073 and specifiers for state change logging, using the same syntax
2074 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
2075 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2076 indicates to record a time stamp each time this state is selected.
2078 Each keyword may also specify if a timestamp or a note should be
2079 recorded when entering or leaving the state, by adding additional
2080 characters in the parenthesis after the keyword. This looks like this:
2081 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2082 record only the time of the state change. With X and Y being either
2083 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2084 Y when leaving the state if and only if the *target* state does not
2085 define X. You may omit any of the fast-selection key or X or /Y,
2086 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2088 For backward compatibility, this variable may also be just a list
2089 of keywords - in this case the interpretation (sequence or type) will be
2090 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2091 :group 'org-todo
2092 :group 'org-keywords
2093 :type '(choice
2094 (repeat :tag "Old syntax, just keywords"
2095 (string :tag "Keyword"))
2096 (repeat :tag "New syntax"
2097 (cons
2098 (choice
2099 :tag "Interpretation"
2100 ;;Quick and dirty way to see
2101 ;;`org-todo-interpretations'. This takes the
2102 ;;place of item arguments
2103 :convert-widget
2104 (lambda (widget)
2105 (widget-put widget
2106 :args (mapcar
2107 #'(lambda (x)
2108 (widget-convert
2109 (cons 'const x)))
2110 org-todo-interpretation-widgets))
2111 widget))
2112 (repeat
2113 (string :tag "Keyword"))))))
2115 (defvar org-todo-keywords-1 nil
2116 "All TODO and DONE keywords active in a buffer.")
2117 (make-variable-buffer-local 'org-todo-keywords-1)
2118 (defvar org-todo-keywords-for-agenda nil)
2119 (defvar org-done-keywords-for-agenda nil)
2120 (defvar org-drawers-for-agenda nil)
2121 (defvar org-todo-keyword-alist-for-agenda nil)
2122 (defvar org-tag-alist-for-agenda nil)
2123 (defvar org-agenda-contributing-files nil)
2124 (defvar org-not-done-keywords nil)
2125 (make-variable-buffer-local 'org-not-done-keywords)
2126 (defvar org-done-keywords nil)
2127 (make-variable-buffer-local 'org-done-keywords)
2128 (defvar org-todo-heads nil)
2129 (make-variable-buffer-local 'org-todo-heads)
2130 (defvar org-todo-sets nil)
2131 (make-variable-buffer-local 'org-todo-sets)
2132 (defvar org-todo-log-states nil)
2133 (make-variable-buffer-local 'org-todo-log-states)
2134 (defvar org-todo-kwd-alist nil)
2135 (make-variable-buffer-local 'org-todo-kwd-alist)
2136 (defvar org-todo-key-alist nil)
2137 (make-variable-buffer-local 'org-todo-key-alist)
2138 (defvar org-todo-key-trigger nil)
2139 (make-variable-buffer-local 'org-todo-key-trigger)
2141 (defcustom org-todo-interpretation 'sequence
2142 "Controls how TODO keywords are interpreted.
2143 This variable is in principle obsolete and is only used for
2144 backward compatibility, if the interpretation of todo keywords is
2145 not given already in `org-todo-keywords'. See that variable for
2146 more information."
2147 :group 'org-todo
2148 :group 'org-keywords
2149 :type '(choice (const sequence)
2150 (const type)))
2152 (defcustom org-use-fast-todo-selection t
2153 "Non-nil means use the fast todo selection scheme with C-c C-t.
2154 This variable describes if and under what circumstances the cycling
2155 mechanism for TODO keywords will be replaced by a single-key, direct
2156 selection scheme.
2158 When nil, fast selection is never used.
2160 When the symbol `prefix', it will be used when `org-todo' is called with
2161 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
2162 in an agenda buffer.
2164 When t, fast selection is used by default. In this case, the prefix
2165 argument forces cycling instead.
2167 In all cases, the special interface is only used if access keys have actually
2168 been assigned by the user, i.e. if keywords in the configuration are followed
2169 by a letter in parenthesis, like TODO(t)."
2170 :group 'org-todo
2171 :type '(choice
2172 (const :tag "Never" nil)
2173 (const :tag "By default" t)
2174 (const :tag "Only with C-u C-c C-t" prefix)))
2176 (defcustom org-provide-todo-statistics t
2177 "Non-nil means update todo statistics after insert and toggle.
2178 ALL-HEADLINES means update todo statistics by including headlines
2179 with no TODO keyword as well, counting them as not done.
2180 A list of TODO keywords means the same, but skip keywords that are
2181 not in this list.
2183 When this is set, todo statistics is updated in the parent of the
2184 current entry each time a todo state is changed."
2185 :group 'org-todo
2186 :type '(choice
2187 (const :tag "Yes, only for TODO entries" t)
2188 (const :tag "Yes, including all entries" 'all-headlines)
2189 (repeat :tag "Yes, for TODOs in this list"
2190 (string :tag "TODO keyword"))
2191 (other :tag "No TODO statistics" nil)))
2193 (defcustom org-hierarchical-todo-statistics t
2194 "Non-nil means TODO statistics covers just direct children.
2195 When nil, all entries in the subtree are considered.
2196 This has only an effect if `org-provide-todo-statistics' is set.
2197 To set this to nil for only a single subtree, use a COOKIE_DATA
2198 property and include the word \"recursive\" into the value."
2199 :group 'org-todo
2200 :type 'boolean)
2202 (defcustom org-after-todo-state-change-hook nil
2203 "Hook which is run after the state of a TODO item was changed.
2204 The new state (a string with a TODO keyword, or nil) is available in the
2205 Lisp variable `state'."
2206 :group 'org-todo
2207 :type 'hook)
2209 (defvar org-blocker-hook nil
2210 "Hook for functions that are allowed to block a state change.
2212 Each function gets as its single argument a property list, see
2213 `org-trigger-hook' for more information about this list.
2215 If any of the functions in this hook returns nil, the state change
2216 is blocked.")
2218 (defvar org-trigger-hook nil
2219 "Hook for functions that are triggered by a state change.
2221 Each function gets as its single argument a property list with at least
2222 the following elements:
2224 (:type type-of-change :position pos-at-entry-start
2225 :from old-state :to new-state)
2227 Depending on the type, more properties may be present.
2229 This mechanism is currently implemented for:
2231 TODO state changes
2232 ------------------
2233 :type todo-state-change
2234 :from previous state (keyword as a string), or nil, or a symbol
2235 'todo' or 'done', to indicate the general type of state.
2236 :to new state, like in :from")
2238 (defcustom org-enforce-todo-dependencies nil
2239 "Non-nil means undone TODO entries will block switching the parent to DONE.
2240 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2241 be blocked if any prior sibling is not yet done.
2242 Finally, if the parent is blocked because of ordered siblings of its own,
2243 the child will also be blocked.
2244 This variable needs to be set before org.el is loaded, and you need to
2245 restart Emacs after a change to make the change effective. The only way
2246 to change is while Emacs is running is through the customize interface."
2247 :set (lambda (var val)
2248 (set var val)
2249 (if val
2250 (add-hook 'org-blocker-hook
2251 'org-block-todo-from-children-or-siblings-or-parent)
2252 (remove-hook 'org-blocker-hook
2253 'org-block-todo-from-children-or-siblings-or-parent)))
2254 :group 'org-todo
2255 :type 'boolean)
2257 (defcustom org-enforce-todo-checkbox-dependencies nil
2258 "Non-nil means unchecked boxes will block switching the parent to DONE.
2259 When this is nil, checkboxes have no influence on switching TODO states.
2260 When non-nil, you first need to check off all check boxes before the TODO
2261 entry can be switched to DONE.
2262 This variable needs to be set before org.el is loaded, and you need to
2263 restart Emacs after a change to make the change effective. The only way
2264 to change is while Emacs is running is through the customize interface."
2265 :set (lambda (var val)
2266 (set var val)
2267 (if val
2268 (add-hook 'org-blocker-hook
2269 'org-block-todo-from-checkboxes)
2270 (remove-hook 'org-blocker-hook
2271 'org-block-todo-from-checkboxes)))
2272 :group 'org-todo
2273 :type 'boolean)
2275 (defcustom org-treat-insert-todo-heading-as-state-change nil
2276 "Non-nil means inserting a TODO heading is treated as state change.
2277 So when the command \\[org-insert-todo-heading] is used, state change
2278 logging will apply if appropriate. When nil, the new TODO item will
2279 be inserted directly, and no logging will take place."
2280 :group 'org-todo
2281 :type 'boolean)
2283 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2284 "Non-nil means switching TODO states with S-cursor counts as state change.
2285 This is the default behavior. However, setting this to nil allows a
2286 convenient way to select a TODO state and bypass any logging associated
2287 with that."
2288 :group 'org-todo
2289 :type 'boolean)
2291 (defcustom org-todo-state-tags-triggers nil
2292 "Tag changes that should be triggered by TODO state changes.
2293 This is a list. Each entry is
2295 (state-change (tag . flag) .......)
2297 State-change can be a string with a state, and empty string to indicate the
2298 state that has no TODO keyword, or it can be one of the symbols `todo'
2299 or `done', meaning any not-done or done state, respectively."
2300 :group 'org-todo
2301 :group 'org-tags
2302 :type '(repeat
2303 (cons (choice :tag "When changing to"
2304 (const :tag "Not-done state" todo)
2305 (const :tag "Done state" done)
2306 (string :tag "State"))
2307 (repeat
2308 (cons :tag "Tag action"
2309 (string :tag "Tag")
2310 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2312 (defcustom org-log-done nil
2313 "Information to record when a task moves to the DONE state.
2315 Possible values are:
2317 nil Don't add anything, just change the keyword
2318 time Add a time stamp to the task
2319 note Prompt for a note and add it with template `org-log-note-headings'
2321 This option can also be set with on a per-file-basis with
2323 #+STARTUP: nologdone
2324 #+STARTUP: logdone
2325 #+STARTUP: lognotedone
2327 You can have local logging settings for a subtree by setting the LOGGING
2328 property to one or more of these keywords."
2329 :group 'org-todo
2330 :group 'org-progress
2331 :type '(choice
2332 (const :tag "No logging" nil)
2333 (const :tag "Record CLOSED timestamp" time)
2334 (const :tag "Record CLOSED timestamp with note." note)))
2336 ;; Normalize old uses of org-log-done.
2337 (cond
2338 ((eq org-log-done t) (setq org-log-done 'time))
2339 ((and (listp org-log-done) (memq 'done org-log-done))
2340 (setq org-log-done 'note)))
2342 (defcustom org-log-reschedule nil
2343 "Information to record when the scheduling date of a tasks is modified.
2345 Possible values are:
2347 nil Don't add anything, just change the date
2348 time Add a time stamp to the task
2349 note Prompt for a note and add it with template `org-log-note-headings'
2351 This option can also be set with on a per-file-basis with
2353 #+STARTUP: nologreschedule
2354 #+STARTUP: logreschedule
2355 #+STARTUP: lognotereschedule"
2356 :group 'org-todo
2357 :group 'org-progress
2358 :type '(choice
2359 (const :tag "No logging" nil)
2360 (const :tag "Record timestamp" time)
2361 (const :tag "Record timestamp with note." note)))
2363 (defcustom org-log-redeadline nil
2364 "Information to record when the deadline date of a tasks is modified.
2366 Possible values are:
2368 nil Don't add anything, just change the date
2369 time Add a time stamp to the task
2370 note Prompt for a note and add it with template `org-log-note-headings'
2372 This option can also be set with on a per-file-basis with
2374 #+STARTUP: nologredeadline
2375 #+STARTUP: logredeadline
2376 #+STARTUP: lognoteredeadline
2378 You can have local logging settings for a subtree by setting the LOGGING
2379 property to one or more of these keywords."
2380 :group 'org-todo
2381 :group 'org-progress
2382 :type '(choice
2383 (const :tag "No logging" nil)
2384 (const :tag "Record timestamp" time)
2385 (const :tag "Record timestamp with note." note)))
2387 (defcustom org-log-note-clock-out nil
2388 "Non-nil means record a note when clocking out of an item.
2389 This can also be configured on a per-file basis by adding one of
2390 the following lines anywhere in the buffer:
2392 #+STARTUP: lognoteclock-out
2393 #+STARTUP: nolognoteclock-out"
2394 :group 'org-todo
2395 :group 'org-progress
2396 :type 'boolean)
2398 (defcustom org-log-done-with-time t
2399 "Non-nil means the CLOSED time stamp will contain date and time.
2400 When nil, only the date will be recorded."
2401 :group 'org-progress
2402 :type 'boolean)
2404 (defcustom org-log-note-headings
2405 '((done . "CLOSING NOTE %t")
2406 (state . "State %-12s from %-12S %t")
2407 (note . "Note taken on %t")
2408 (reschedule . "Rescheduled from %S on %t")
2409 (delschedule . "Not scheduled, was %S on %t")
2410 (redeadline . "New deadline from %S on %t")
2411 (deldeadline . "Removed deadline, was %S on %t")
2412 (refile . "Refiled on %t")
2413 (clock-out . ""))
2414 "Headings for notes added to entries.
2415 The value is an alist, with the car being a symbol indicating the note
2416 context, and the cdr is the heading to be used. The heading may also be the
2417 empty string.
2418 %t in the heading will be replaced by a time stamp.
2419 %T will be an active time stamp instead the default inactive one
2420 %d will be replaced by a short-format time stamp.
2421 %D will be replaced by an active short-format time stamp.
2422 %s will be replaced by the new TODO state, in double quotes.
2423 %S will be replaced by the old TODO state, in double quotes.
2424 %u will be replaced by the user name.
2425 %U will be replaced by the full user name.
2427 In fact, it is not a good idea to change the `state' entry, because
2428 agenda log mode depends on the format of these entries."
2429 :group 'org-todo
2430 :group 'org-progress
2431 :type '(list :greedy t
2432 (cons (const :tag "Heading when closing an item" done) string)
2433 (cons (const :tag
2434 "Heading when changing todo state (todo sequence only)"
2435 state) string)
2436 (cons (const :tag "Heading when just taking a note" note) string)
2437 (cons (const :tag "Heading when clocking out" clock-out) string)
2438 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2439 (cons (const :tag "Heading when rescheduling" reschedule) string)
2440 (cons (const :tag "Heading when changing deadline" redeadline) string)
2441 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2442 (cons (const :tag "Heading when refiling" refile) string)))
2444 (unless (assq 'note org-log-note-headings)
2445 (push '(note . "%t") org-log-note-headings))
2447 (defcustom org-log-into-drawer nil
2448 "Non-nil means insert state change notes and time stamps into a drawer.
2449 When nil, state changes notes will be inserted after the headline and
2450 any scheduling and clock lines, but not inside a drawer.
2452 The value of this variable should be the name of the drawer to use.
2453 LOGBOOK is proposed as the default drawer for this purpose, you can
2454 also set this to a string to define the drawer of your choice.
2456 A value of t is also allowed, representing \"LOGBOOK\".
2458 If this variable is set, `org-log-state-notes-insert-after-drawers'
2459 will be ignored.
2461 You can set the property LOG_INTO_DRAWER to overrule this setting for
2462 a subtree."
2463 :group 'org-todo
2464 :group 'org-progress
2465 :type '(choice
2466 (const :tag "Not into a drawer" nil)
2467 (const :tag "LOGBOOK" t)
2468 (string :tag "Other")))
2470 (if (fboundp 'defvaralias)
2471 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2473 (defun org-log-into-drawer ()
2474 "Return the value of `org-log-into-drawer', but let properties overrule.
2475 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2476 used instead of the default value."
2477 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit)))
2478 (cond
2479 ((or (not p) (equal p "nil")) org-log-into-drawer)
2480 ((equal p "t") "LOGBOOK")
2481 (t p))))
2483 (defcustom org-log-state-notes-insert-after-drawers nil
2484 "Non-nil means insert state change notes after any drawers in entry.
2485 Only the drawers that *immediately* follow the headline and the
2486 deadline/scheduled line are skipped.
2487 When nil, insert notes right after the heading and perhaps the line
2488 with deadline/scheduling if present.
2490 This variable will have no effect if `org-log-into-drawer' is
2491 set."
2492 :group 'org-todo
2493 :group 'org-progress
2494 :type 'boolean)
2496 (defcustom org-log-states-order-reversed t
2497 "Non-nil means the latest state note will be directly after heading.
2498 When nil, the state change notes will be ordered according to time."
2499 :group 'org-todo
2500 :group 'org-progress
2501 :type 'boolean)
2503 (defcustom org-todo-repeat-to-state nil
2504 "The TODO state to which a repeater should return the repeating task.
2505 By default this is the first task in a TODO sequence, or the previous state
2506 in a TODO_TYP set. But you can specify another task here.
2507 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2508 :group 'org-todo
2509 :type '(choice (const :tag "Head of sequence" nil)
2510 (string :tag "Specific state")))
2512 (defcustom org-log-repeat 'time
2513 "Non-nil means record moving through the DONE state when triggering repeat.
2514 An auto-repeating task is immediately switched back to TODO when
2515 marked DONE. If you are not logging state changes (by adding \"@\"
2516 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2517 record a closing note, there will be no record of the task moving
2518 through DONE. This variable forces taking a note anyway.
2520 nil Don't force a record
2521 time Record a time stamp
2522 note Record a note
2524 This option can also be set with on a per-file-basis with
2526 #+STARTUP: logrepeat
2527 #+STARTUP: lognoterepeat
2528 #+STARTUP: nologrepeat
2530 You can have local logging settings for a subtree by setting the LOGGING
2531 property to one or more of these keywords."
2532 :group 'org-todo
2533 :group 'org-progress
2534 :type '(choice
2535 (const :tag "Don't force a record" nil)
2536 (const :tag "Force recording the DONE state" time)
2537 (const :tag "Force recording a note with the DONE state" note)))
2540 (defgroup org-priorities nil
2541 "Priorities in Org-mode."
2542 :tag "Org Priorities"
2543 :group 'org-todo)
2545 (defcustom org-enable-priority-commands t
2546 "Non-nil means priority commands are active.
2547 When nil, these commands will be disabled, so that you never accidentally
2548 set a priority."
2549 :group 'org-priorities
2550 :type 'boolean)
2552 (defcustom org-highest-priority ?A
2553 "The highest priority of TODO items. A character like ?A, ?B etc.
2554 Must have a smaller ASCII number than `org-lowest-priority'."
2555 :group 'org-priorities
2556 :type 'character)
2558 (defcustom org-lowest-priority ?C
2559 "The lowest priority of TODO items. A character like ?A, ?B etc.
2560 Must have a larger ASCII number than `org-highest-priority'."
2561 :group 'org-priorities
2562 :type 'character)
2564 (defcustom org-default-priority ?B
2565 "The default priority of TODO items.
2566 This is the priority an item gets if no explicit priority is given.
2567 When starting to cycle on an empty priority the first step in the cycle
2568 depends on `org-priority-start-cycle-with-default'. The resulting first
2569 step priority must not exceed the range from `org-highest-priority' to
2570 `org-lowest-priority' which means that `org-default-priority' has to be
2571 in this range exclusive or inclusive the range boundaries. Else the
2572 first step refuses to set the default and the second will fall back
2573 to (depending on the command used) the highest or lowest priority."
2574 :group 'org-priorities
2575 :type 'character)
2577 (defcustom org-priority-start-cycle-with-default t
2578 "Non-nil means start with default priority when starting to cycle.
2579 When this is nil, the first step in the cycle will be (depending on the
2580 command used) one higher or lower than the default priority.
2581 See also `org-default-priority'."
2582 :group 'org-priorities
2583 :type 'boolean)
2585 (defcustom org-get-priority-function nil
2586 "Function to extract the priority from a string.
2587 The string is normally the headline. If this is nil Org computes the
2588 priority from the priority cookie like [#A] in the headline. It returns
2589 an integer, increasing by 1000 for each priority level.
2590 The user can set a different function here, which should take a string
2591 as an argument and return the numeric priority."
2592 :group 'org-priorities
2593 :type 'function)
2595 (defgroup org-time nil
2596 "Options concerning time stamps and deadlines in Org-mode."
2597 :tag "Org Time"
2598 :group 'org)
2600 (defcustom org-insert-labeled-timestamps-at-point nil
2601 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2602 When nil, these labeled time stamps are forces into the second line of an
2603 entry, just after the headline. When scheduling from the global TODO list,
2604 the time stamp will always be forced into the second line."
2605 :group 'org-time
2606 :type 'boolean)
2608 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2609 "Formats for `format-time-string' which are used for time stamps.
2610 It is not recommended to change this constant.")
2612 (defcustom org-time-stamp-rounding-minutes '(0 5)
2613 "Number of minutes to round time stamps to.
2614 These are two values, the first applies when first creating a time stamp.
2615 The second applies when changing it with the commands `S-up' and `S-down'.
2616 When changing the time stamp, this means that it will change in steps
2617 of N minutes, as given by the second value.
2619 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2620 numbers should be factors of 60, so for example 5, 10, 15.
2622 When this is larger than 1, you can still force an exact time stamp by using
2623 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2624 and by using a prefix arg to `S-up/down' to specify the exact number
2625 of minutes to shift."
2626 :group 'org-time
2627 :get #'(lambda (var) ; Make sure both elements are there
2628 (if (integerp (default-value var))
2629 (list (default-value var) 5)
2630 (default-value var)))
2631 :type '(list
2632 (integer :tag "when inserting times")
2633 (integer :tag "when modifying times")))
2635 ;; Normalize old customizations of this variable.
2636 (when (integerp org-time-stamp-rounding-minutes)
2637 (setq org-time-stamp-rounding-minutes
2638 (list org-time-stamp-rounding-minutes
2639 org-time-stamp-rounding-minutes)))
2641 (defcustom org-display-custom-times nil
2642 "Non-nil means overlay custom formats over all time stamps.
2643 The formats are defined through the variable `org-time-stamp-custom-formats'.
2644 To turn this on on a per-file basis, insert anywhere in the file:
2645 #+STARTUP: customtime"
2646 :group 'org-time
2647 :set 'set-default
2648 :type 'sexp)
2649 (make-variable-buffer-local 'org-display-custom-times)
2651 (defcustom org-time-stamp-custom-formats
2652 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2653 "Custom formats for time stamps. See `format-time-string' for the syntax.
2654 These are overlayed over the default ISO format if the variable
2655 `org-display-custom-times' is set. Time like %H:%M should be at the
2656 end of the second format. The custom formats are also honored by export
2657 commands, if custom time display is turned on at the time of export."
2658 :group 'org-time
2659 :type 'sexp)
2661 (defun org-time-stamp-format (&optional long inactive)
2662 "Get the right format for a time string."
2663 (let ((f (if long (cdr org-time-stamp-formats)
2664 (car org-time-stamp-formats))))
2665 (if inactive
2666 (concat "[" (substring f 1 -1) "]")
2667 f)))
2669 (defcustom org-time-clocksum-format "%d:%02d"
2670 "The format string used when creating CLOCKSUM lines.
2671 This is also used when org-mode generates a time duration."
2672 :group 'org-time
2673 :type 'string)
2675 (defcustom org-time-clocksum-use-fractional nil
2676 "If non-nil, \\[org-clock-display] uses fractional times.
2677 org-mode generates a time duration."
2678 :group 'org-time
2679 :type 'boolean)
2681 (defcustom org-time-clocksum-fractional-format "%.2f"
2682 "The format string used when creating CLOCKSUM lines, or when
2683 org-mode generates a time duration."
2684 :group 'org-time
2685 :type 'string)
2687 (defcustom org-deadline-warning-days 14
2688 "No. of days before expiration during which a deadline becomes active.
2689 This variable governs the display in sparse trees and in the agenda.
2690 When 0 or negative, it means use this number (the absolute value of it)
2691 even if a deadline has a different individual lead time specified.
2693 Custom commands can set this variable in the options section."
2694 :group 'org-time
2695 :group 'org-agenda-daily/weekly
2696 :type 'integer)
2698 (defcustom org-read-date-prefer-future t
2699 "Non-nil means assume future for incomplete date input from user.
2700 This affects the following situations:
2701 1. The user gives a month but not a year.
2702 For example, if it is April and you enter \"feb 2\", this will be read
2703 as Feb 2, *next* year. \"May 5\", however, will be this year.
2704 2. The user gives a day, but no month.
2705 For example, if today is the 15th, and you enter \"3\", Org-mode will
2706 read this as the third of *next* month. However, if you enter \"17\",
2707 it will be considered as *this* month.
2709 If you set this variable to the symbol `time', then also the following
2710 will work:
2712 3. If the user gives a time, but no day. If the time is before now,
2713 to will be interpreted as tomorrow.
2715 Currently none of this works for ISO week specifications.
2717 When this option is nil, the current day, month and year will always be
2718 used as defaults.
2720 See also `org-agenda-jump-prefer-future'."
2721 :group 'org-time
2722 :type '(choice
2723 (const :tag "Never" nil)
2724 (const :tag "Check month and day" t)
2725 (const :tag "Check month, day, and time" time)))
2727 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
2728 "Should the agenda jump command prefer the future for incomplete dates?
2729 The default is to do the same as configured in `org-read-date-prefer-future'.
2730 But you can also set a deviating value here.
2731 This may t or nil, or the symbol `org-read-date-prefer-future'."
2732 :group 'org-agenda
2733 :group 'org-time
2734 :type '(choice
2735 (const :tag "Use org-read-date-prefer-future"
2736 org-read-date-prefer-future)
2737 (const :tag "Never" nil)
2738 (const :tag "Always" t)))
2740 (defcustom org-read-date-force-compatible-dates t
2741 "Should date/time prompt force dates that are guaranteed to work in Emacs?
2743 Depending on the system Emacs is running on, certain dates cannot
2744 be represented with the type used internally to represent time.
2745 Dates between 1970-1-1 and 2038-1-1 can always be represented
2746 correctly. Some systems allow for earlier dates, some for later,
2747 some for both. One way to find out it to insert any date into an
2748 Org buffer, putting the cursor on the year and hitting S-up and
2749 S-down to test the range.
2751 When this variable is set to t, the date/time prompt will not let
2752 you specify dates outside the 1970-2037 range, so it is certain that
2753 these dates will work in whatever version of Emacs you are
2754 running, and also that you can move a file from one Emacs implementation
2755 to another. WHenever Org is forcing the year for you, it will display
2756 a message and beep.
2758 When this variable is nil, Org will check if the date is
2759 representable in the specific Emacs implementation you are using.
2760 If not, it will force a year, usually the current year, and beep
2761 to remind you. Currently this setting is not recommended because
2762 the likelihood that you will open your Org files in an Emacs that
2763 has limited date range is not negligible.
2765 A workaround for this problem is to use diary sexp dates for time
2766 stamps outside of this range."
2767 :group 'org-time
2768 :type 'boolean)
2770 (defcustom org-read-date-display-live t
2771 "Non-nil means display current interpretation of date prompt live.
2772 This display will be in an overlay, in the minibuffer."
2773 :group 'org-time
2774 :type 'boolean)
2776 (defcustom org-read-date-popup-calendar t
2777 "Non-nil means pop up a calendar when prompting for a date.
2778 In the calendar, the date can be selected with mouse-1. However, the
2779 minibuffer will also be active, and you can simply enter the date as well.
2780 When nil, only the minibuffer will be available."
2781 :group 'org-time
2782 :type 'boolean)
2783 (if (fboundp 'defvaralias)
2784 (defvaralias 'org-popup-calendar-for-date-prompt
2785 'org-read-date-popup-calendar))
2787 (defcustom org-read-date-minibuffer-setup-hook nil
2788 "Hook to be used to set up keys for the date/time interface.
2789 Add key definitions to `minibuffer-local-map', which will be a temporary
2790 copy."
2791 :group 'org-time
2792 :type 'hook)
2794 (defcustom org-extend-today-until 0
2795 "The hour when your day really ends. Must be an integer.
2796 This has influence for the following applications:
2797 - When switching the agenda to \"today\". It it is still earlier than
2798 the time given here, the day recognized as TODAY is actually yesterday.
2799 - When a date is read from the user and it is still before the time given
2800 here, the current date and time will be assumed to be yesterday, 23:59.
2801 Also, timestamps inserted in remember templates follow this rule.
2803 IMPORTANT: This is a feature whose implementation is and likely will
2804 remain incomplete. Really, it is only here because past midnight seems to
2805 be the favorite working time of John Wiegley :-)"
2806 :group 'org-time
2807 :type 'integer)
2809 (defcustom org-use-effective-time nil
2810 "If non-nil, consider `org-extend-today-until' when creating timestamps.
2811 For example, if `org-extend-today-until' is 8, and it's 4am, then the
2812 \"effective time\" of any timestamps between midnight and 8am will be
2813 23:59 of the previous day."
2814 :group 'boolean
2815 :type 'integer)
2817 (defcustom org-edit-timestamp-down-means-later nil
2818 "Non-nil means S-down will increase the time in a time stamp.
2819 When nil, S-up will increase."
2820 :group 'org-time
2821 :type 'boolean)
2823 (defcustom org-calendar-follow-timestamp-change t
2824 "Non-nil means make the calendar window follow timestamp changes.
2825 When a timestamp is modified and the calendar window is visible, it will be
2826 moved to the new date."
2827 :group 'org-time
2828 :type 'boolean)
2830 (defgroup org-tags nil
2831 "Options concerning tags in Org-mode."
2832 :tag "Org Tags"
2833 :group 'org)
2835 (defcustom org-tag-alist nil
2836 "List of tags allowed in Org-mode files.
2837 When this list is nil, Org-mode will base TAG input on what is already in the
2838 buffer.
2839 The value of this variable is an alist, the car of each entry must be a
2840 keyword as a string, the cdr may be a character that is used to select
2841 that tag through the fast-tag-selection interface.
2842 See the manual for details."
2843 :group 'org-tags
2844 :type '(repeat
2845 (choice
2846 (cons (string :tag "Tag name")
2847 (character :tag "Access char"))
2848 (list :tag "Start radio group"
2849 (const :startgroup)
2850 (option (string :tag "Group description")))
2851 (list :tag "End radio group"
2852 (const :endgroup)
2853 (option (string :tag "Group description")))
2854 (const :tag "New line" (:newline)))))
2856 (defcustom org-tag-persistent-alist nil
2857 "List of tags that will always appear in all Org-mode files.
2858 This is in addition to any in buffer settings or customizations
2859 of `org-tag-alist'.
2860 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2861 The value of this variable is an alist, the car of each entry must be a
2862 keyword as a string, the cdr may be a character that is used to select
2863 that tag through the fast-tag-selection interface.
2864 See the manual for details.
2865 To disable these tags on a per-file basis, insert anywhere in the file:
2866 #+STARTUP: noptag"
2867 :group 'org-tags
2868 :type '(repeat
2869 (choice
2870 (cons (string :tag "Tag name")
2871 (character :tag "Access char"))
2872 (const :tag "Start radio group" (:startgroup))
2873 (const :tag "End radio group" (:endgroup))
2874 (const :tag "New line" (:newline)))))
2876 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
2877 "If non-nil, always offer completion for all tags of all agenda files.
2878 Instead of customizing this variable directly, you might want to
2879 set it locally for capture buffers, because there no list of
2880 tags in that file can be created dynamically (there are none).
2882 (add-hook 'org-capture-mode-hook
2883 (lambda ()
2884 (set (make-local-variable
2885 'org-complete-tags-always-offer-all-agenda-tags)
2886 t)))"
2887 :group 'org-tags
2888 :type 'boolean)
2890 (defvar org-file-tags nil
2891 "List of tags that can be inherited by all entries in the file.
2892 The tags will be inherited if the variable `org-use-tag-inheritance'
2893 says they should be.
2894 This variable is populated from #+FILETAGS lines.")
2896 (defcustom org-use-fast-tag-selection 'auto
2897 "Non-nil means use fast tag selection scheme.
2898 This is a special interface to select and deselect tags with single keys.
2899 When nil, fast selection is never used.
2900 When the symbol `auto', fast selection is used if and only if selection
2901 characters for tags have been configured, either through the variable
2902 `org-tag-alist' or through a #+TAGS line in the buffer.
2903 When t, fast selection is always used and selection keys are assigned
2904 automatically if necessary."
2905 :group 'org-tags
2906 :type '(choice
2907 (const :tag "Always" t)
2908 (const :tag "Never" nil)
2909 (const :tag "When selection characters are configured" 'auto)))
2911 (defcustom org-fast-tag-selection-single-key nil
2912 "Non-nil means fast tag selection exits after first change.
2913 When nil, you have to press RET to exit it.
2914 During fast tag selection, you can toggle this flag with `C-c'.
2915 This variable can also have the value `expert'. In this case, the window
2916 displaying the tags menu is not even shown, until you press C-c again."
2917 :group 'org-tags
2918 :type '(choice
2919 (const :tag "No" nil)
2920 (const :tag "Yes" t)
2921 (const :tag "Expert" expert)))
2923 (defvar org-fast-tag-selection-include-todo nil
2924 "Non-nil means fast tags selection interface will also offer TODO states.
2925 This is an undocumented feature, you should not rely on it.")
2927 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2928 "The column to which tags should be indented in a headline.
2929 If this number is positive, it specifies the column. If it is negative,
2930 it means that the tags should be flushright to that column. For example,
2931 -80 works well for a normal 80 character screen.
2932 When 0, place tags directly after headline text, with only one space in
2933 between."
2934 :group 'org-tags
2935 :type 'integer)
2937 (defcustom org-auto-align-tags t
2938 "Non-nil keeps tags aligned when modifying headlines.
2939 Some operations (i.e. demoting) change the length of a headline and
2940 therefore shift the tags around. With this option turned on, after
2941 each such operation the tags are again aligned to `org-tags-column'."
2942 :group 'org-tags
2943 :type 'boolean)
2945 (defcustom org-use-tag-inheritance t
2946 "Non-nil means tags in levels apply also for sublevels.
2947 When nil, only the tags directly given in a specific line apply there.
2948 This may also be a list of tags that should be inherited, or a regexp that
2949 matches tags that should be inherited. Additional control is possible
2950 with the variable `org-tags-exclude-from-inheritance' which gives an
2951 explicit list of tags to be excluded from inheritance., even if the value of
2952 `org-use-tag-inheritance' would select it for inheritance.
2954 If this option is t, a match early-on in a tree can lead to a large
2955 number of matches in the subtree when constructing the agenda or creating
2956 a sparse tree. If you only want to see the first match in a tree during
2957 a search, check out the variable `org-tags-match-list-sublevels'."
2958 :group 'org-tags
2959 :type '(choice
2960 (const :tag "Not" nil)
2961 (const :tag "Always" t)
2962 (repeat :tag "Specific tags" (string :tag "Tag"))
2963 (regexp :tag "Tags matched by regexp")))
2965 (defcustom org-tags-exclude-from-inheritance nil
2966 "List of tags that should never be inherited.
2967 This is a way to exclude a few tags from inheritance. For way to do
2968 the opposite, to actively allow inheritance for selected tags,
2969 see the variable `org-use-tag-inheritance'."
2970 :group 'org-tags
2971 :type '(repeat (string :tag "Tag")))
2973 (defun org-tag-inherit-p (tag)
2974 "Check if TAG is one that should be inherited."
2975 (cond
2976 ((member tag org-tags-exclude-from-inheritance) nil)
2977 ((eq org-use-tag-inheritance t) t)
2978 ((not org-use-tag-inheritance) nil)
2979 ((stringp org-use-tag-inheritance)
2980 (string-match org-use-tag-inheritance tag))
2981 ((listp org-use-tag-inheritance)
2982 (member tag org-use-tag-inheritance))
2983 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
2985 (defcustom org-tags-match-list-sublevels t
2986 "Non-nil means list also sublevels of headlines matching a search.
2987 This variable applies to tags/property searches, and also to stuck
2988 projects because this search is based on a tags match as well.
2990 When set to the symbol `indented', sublevels are indented with
2991 leading dots.
2993 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2994 the sublevels of a headline matching a tag search often also match
2995 the same search. Listing all of them can create very long lists.
2996 Setting this variable to nil causes subtrees of a match to be skipped.
2998 This variable is semi-obsolete and probably should always be true. It
2999 is better to limit inheritance to certain tags using the variables
3000 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3001 :group 'org-tags
3002 :type '(choice
3003 (const :tag "No, don't list them" nil)
3004 (const :tag "Yes, do list them" t)
3005 (const :tag "List them, indented with leading dots" indented)))
3007 (defcustom org-tags-sort-function nil
3008 "When set, tags are sorted using this function as a comparator."
3009 :group 'org-tags
3010 :type '(choice
3011 (const :tag "No sorting" nil)
3012 (const :tag "Alphabetical" string<)
3013 (const :tag "Reverse alphabetical" string>)
3014 (function :tag "Custom function" nil)))
3016 (defvar org-tags-history nil
3017 "History of minibuffer reads for tags.")
3018 (defvar org-last-tags-completion-table nil
3019 "The last used completion table for tags.")
3020 (defvar org-after-tags-change-hook nil
3021 "Hook that is run after the tags in a line have changed.")
3023 (defgroup org-properties nil
3024 "Options concerning properties in Org-mode."
3025 :tag "Org Properties"
3026 :group 'org)
3028 (defcustom org-property-format "%-10s %s"
3029 "How property key/value pairs should be formatted by `indent-line'.
3030 When `indent-line' hits a property definition, it will format the line
3031 according to this format, mainly to make sure that the values are
3032 lined-up with respect to each other."
3033 :group 'org-properties
3034 :type 'string)
3036 (defcustom org-properties-postprocess-alist nil
3037 "Alist of properties and functions to adjust inserted values.
3038 Elements of this alist must be of the form
3040 ([string] [function])
3042 where [string] must be a property name and [function] must be a
3043 lambda expression: this lambda expression must take one argument,
3044 the value to adjust, and return the new value as a string.
3046 For example, this element will allow the property \"Remaining\"
3047 to be updated wrt the relation between the \"Effort\" property
3048 and the clock summary:
3050 ((\"Remaining\" (lambda(value)
3051 (let ((clocksum (org-clock-sum-current-item))
3052 (effort (org-duration-string-to-minutes
3053 (org-entry-get (point) \"Effort\"))))
3054 (org-minutes-to-hh:mm-string (- effort clocksum))))))"
3055 :group 'org-properties
3056 :type 'alist)
3058 (defcustom org-use-property-inheritance nil
3059 "Non-nil means properties apply also for sublevels.
3061 This setting is chiefly used during property searches. Turning it on can
3062 cause significant overhead when doing a search, which is why it is not
3063 on by default.
3065 When nil, only the properties directly given in the current entry count.
3066 When t, every property is inherited. The value may also be a list of
3067 properties that should have inheritance, or a regular expression matching
3068 properties that should be inherited.
3070 However, note that some special properties use inheritance under special
3071 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3072 and the properties ending in \"_ALL\" when they are used as descriptor
3073 for valid values of a property.
3075 Note for programmers:
3076 When querying an entry with `org-entry-get', you can control if inheritance
3077 should be used. By default, `org-entry-get' looks only at the local
3078 properties. You can request inheritance by setting the inherit argument
3079 to t (to force inheritance) or to `selective' (to respect the setting
3080 in this variable)."
3081 :group 'org-properties
3082 :type '(choice
3083 (const :tag "Not" nil)
3084 (const :tag "Always" t)
3085 (repeat :tag "Specific properties" (string :tag "Property"))
3086 (regexp :tag "Properties matched by regexp")))
3088 (defun org-property-inherit-p (property)
3089 "Check if PROPERTY is one that should be inherited."
3090 (cond
3091 ((eq org-use-property-inheritance t) t)
3092 ((not org-use-property-inheritance) nil)
3093 ((stringp org-use-property-inheritance)
3094 (string-match org-use-property-inheritance property))
3095 ((listp org-use-property-inheritance)
3096 (member property org-use-property-inheritance))
3097 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3099 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3100 "The default column format, if no other format has been defined.
3101 This variable can be set on the per-file basis by inserting a line
3103 #+COLUMNS: %25ITEM ....."
3104 :group 'org-properties
3105 :type 'string)
3107 (defcustom org-columns-ellipses ".."
3108 "The ellipses to be used when a field in column view is truncated.
3109 When this is the empty string, as many characters as possible are shown,
3110 but then there will be no visual indication that the field has been truncated.
3111 When this is a string of length N, the last N characters of a truncated
3112 field are replaced by this string. If the column is narrower than the
3113 ellipses string, only part of the ellipses string will be shown."
3114 :group 'org-properties
3115 :type 'string)
3117 (defcustom org-columns-modify-value-for-display-function nil
3118 "Function that modifies values for display in column view.
3119 For example, it can be used to cut out a certain part from a time stamp.
3120 The function must take 2 arguments:
3122 column-title The title of the column (*not* the property name)
3123 value The value that should be modified.
3125 The function should return the value that should be displayed,
3126 or nil if the normal value should be used."
3127 :group 'org-properties
3128 :type 'function)
3130 (defcustom org-effort-property "Effort"
3131 "The property that is being used to keep track of effort estimates.
3132 Effort estimates given in this property need to have the format H:MM."
3133 :group 'org-properties
3134 :group 'org-progress
3135 :type '(string :tag "Property"))
3137 (defconst org-global-properties-fixed
3138 '(("VISIBILITY_ALL" . "folded children content all")
3139 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3140 "List of property/value pairs that can be inherited by any entry.
3142 These are fixed values, for the preset properties. The user variable
3143 that can be used to add to this list is `org-global-properties'.
3145 The entries in this list are cons cells where the car is a property
3146 name and cdr is a string with the value. If the value represents
3147 multiple items like an \"_ALL\" property, separate the items by
3148 spaces.")
3150 (defcustom org-global-properties nil
3151 "List of property/value pairs that can be inherited by any entry.
3153 This list will be combined with the constant `org-global-properties-fixed'.
3155 The entries in this list are cons cells where the car is a property
3156 name and cdr is a string with the value.
3158 You can set buffer-local values for the same purpose in the variable
3159 `org-file-properties' this by adding lines like
3161 #+PROPERTY: NAME VALUE"
3162 :group 'org-properties
3163 :type '(repeat
3164 (cons (string :tag "Property")
3165 (string :tag "Value"))))
3167 (defvar org-file-properties nil
3168 "List of property/value pairs that can be inherited by any entry.
3169 Valid for the current buffer.
3170 This variable is populated from #+PROPERTY lines.")
3171 (make-variable-buffer-local 'org-file-properties)
3173 (defgroup org-agenda nil
3174 "Options concerning agenda views in Org-mode."
3175 :tag "Org Agenda"
3176 :group 'org)
3178 (defvar org-category nil
3179 "Variable used by org files to set a category for agenda display.
3180 Such files should use a file variable to set it, for example
3182 # -*- mode: org; org-category: \"ELisp\"
3184 or contain a special line
3186 #+CATEGORY: ELisp
3188 If the file does not specify a category, then file's base name
3189 is used instead.")
3190 (make-variable-buffer-local 'org-category)
3191 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3193 (defcustom org-agenda-files nil
3194 "The files to be used for agenda display.
3195 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3196 \\[org-remove-file]. You can also use customize to edit the list.
3198 If an entry is a directory, all files in that directory that are matched by
3199 `org-agenda-file-regexp' will be part of the file list.
3201 If the value of the variable is not a list but a single file name, then
3202 the list of agenda files is actually stored and maintained in that file, one
3203 agenda file per line. In this file paths can be given relative to
3204 `org-directory'. Tilde expansion and environment variable substitution
3205 are also made."
3206 :group 'org-agenda
3207 :type '(choice
3208 (repeat :tag "List of files and directories" file)
3209 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3211 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3212 "Regular expression to match files for `org-agenda-files'.
3213 If any element in the list in that variable contains a directory instead
3214 of a normal file, all files in that directory that are matched by this
3215 regular expression will be included."
3216 :group 'org-agenda
3217 :type 'regexp)
3219 (defcustom org-agenda-text-search-extra-files nil
3220 "List of extra files to be searched by text search commands.
3221 These files will be search in addition to the agenda files by the
3222 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3223 Note that these files will only be searched for text search commands,
3224 not for the other agenda views like todo lists, tag searches or the weekly
3225 agenda. This variable is intended to list notes and possibly archive files
3226 that should also be searched by these two commands.
3227 In fact, if the first element in the list is the symbol `agenda-archives',
3228 than all archive files of all agenda files will be added to the search
3229 scope."
3230 :group 'org-agenda
3231 :type '(set :greedy t
3232 (const :tag "Agenda Archives" agenda-archives)
3233 (repeat :inline t (file))))
3235 (if (fboundp 'defvaralias)
3236 (defvaralias 'org-agenda-multi-occur-extra-files
3237 'org-agenda-text-search-extra-files))
3239 (defcustom org-agenda-skip-unavailable-files nil
3240 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3241 A nil value means to remove them, after a query, from the list."
3242 :group 'org-agenda
3243 :type 'boolean)
3245 (defcustom org-calendar-to-agenda-key [?c]
3246 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3247 The command `org-calendar-goto-agenda' will be bound to this key. The
3248 default is the character `c' because then `c' can be used to switch back and
3249 forth between agenda and calendar."
3250 :group 'org-agenda
3251 :type 'sexp)
3253 (defcustom org-calendar-agenda-action-key [?k]
3254 "The key to be installed in `calendar-mode-map' for agenda-action.
3255 The command `org-agenda-action' will be bound to this key. The
3256 default is the character `k' because we use the same key in the agenda."
3257 :group 'org-agenda
3258 :type 'sexp)
3260 (defcustom org-calendar-insert-diary-entry-key [?i]
3261 "The key to be installed in `calendar-mode-map' for adding diary entries.
3262 This option is irrelevant until `org-agenda-diary-file' has been configured
3263 to point to an Org-mode file. When that is the case, the command
3264 `org-agenda-diary-entry' will be bound to the key given here, by default
3265 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3266 if you want to continue doing this, you need to change this to a different
3267 key."
3268 :group 'org-agenda
3269 :type 'sexp)
3271 (defcustom org-agenda-diary-file 'diary-file
3272 "File to which to add new entries with the `i' key in agenda and calendar.
3273 When this is the symbol `diary-file', the functionality in the Emacs
3274 calendar will be used to add entries to the `diary-file'. But when this
3275 points to a file, `org-agenda-diary-entry' will be used instead."
3276 :group 'org-agenda
3277 :type '(choice
3278 (const :tag "The standard Emacs diary file" diary-file)
3279 (file :tag "Special Org file diary entries")))
3281 (eval-after-load "calendar"
3282 '(progn
3283 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3284 'org-calendar-goto-agenda)
3285 (org-defkey calendar-mode-map org-calendar-agenda-action-key
3286 'org-agenda-action)
3287 (add-hook 'calendar-mode-hook
3288 (lambda ()
3289 (unless (eq org-agenda-diary-file 'diary-file)
3290 (define-key calendar-mode-map
3291 org-calendar-insert-diary-entry-key
3292 'org-agenda-diary-entry))))))
3294 (defgroup org-latex nil
3295 "Options for embedding LaTeX code into Org-mode."
3296 :tag "Org LaTeX"
3297 :group 'org)
3299 (defcustom org-format-latex-options
3300 '(:foreground default :background default :scale 1.0
3301 :html-foreground "Black" :html-background "Transparent"
3302 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3303 "Options for creating images from LaTeX fragments.
3304 This is a property list with the following properties:
3305 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3306 `default' means use the foreground of the default face.
3307 :background the background color, or \"Transparent\".
3308 `default' means use the background of the default face.
3309 :scale a scaling factor for the size of the images, to get more pixels
3310 :html-foreground, :html-background, :html-scale
3311 the same numbers for HTML export.
3312 :matchers a list indicating which matchers should be used to
3313 find LaTeX fragments. Valid members of this list are:
3314 \"begin\" find environments
3315 \"$1\" find single characters surrounded by $.$
3316 \"$\" find math expressions surrounded by $...$
3317 \"$$\" find math expressions surrounded by $$....$$
3318 \"\\(\" find math expressions surrounded by \\(...\\)
3319 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3320 :group 'org-latex
3321 :type 'plist)
3323 (defcustom org-format-latex-signal-error t
3324 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3325 When nil, just push out a message."
3326 :group 'org-latex
3327 :type 'boolean)
3328 (defcustom org-latex-to-mathml-jar-file nil
3329 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3330 Use this to specify additional executable file say a jar file.
3332 When using MathToWeb as the converter, specify the full-path to
3333 your mathtoweb.jar file."
3334 :group 'org-latex
3335 :type '(choice
3336 (const :tag "None" nil)
3337 (file :tag "JAR file" :must-match t)))
3339 (defcustom org-latex-to-mathml-convert-command nil
3340 "Command to convert LaTeX fragments to MathML.
3341 Replace format-specifiers in the command as noted below and use
3342 `shell-command' to convert LaTeX to MathML.
3343 %j: Executable file in fully expanded form as specified by
3344 `org-latex-to-mathml-jar-file'.
3345 %I: Input LaTeX file in fully expanded form
3346 %o: Output MathML file
3347 This command is used by `org-create-math-formula'.
3349 When using MathToWeb as the converter, set this to
3350 \"java -jar %j -unicode -force -df %o %I\"."
3351 :group 'org-latex
3352 :type '(choice
3353 (const :tag "None" nil)
3354 (string :tag "\nShell command")))
3356 (defun org-format-latex-mathml-available-p ()
3357 "Return t if `org-latex-to-mathml-convert-command' is usable."
3358 (save-match-data
3359 (when (and (boundp 'org-latex-to-mathml-convert-command)
3360 org-latex-to-mathml-convert-command)
3361 (let ((executable (car (split-string
3362 org-latex-to-mathml-convert-command))))
3363 (when (executable-find executable)
3364 (if (string-match
3365 "%j" org-latex-to-mathml-convert-command)
3366 (file-readable-p org-latex-to-mathml-jar-file)
3367 t))))))
3369 (defcustom org-format-latex-header "\\documentclass{article}
3370 \\usepackage[usenames]{color}
3371 \\usepackage{amsmath}
3372 \\usepackage[mathscr]{eucal}
3373 \\pagestyle{empty} % do not remove
3374 \[PACKAGES]
3375 \[DEFAULT-PACKAGES]
3376 % The settings below are copied from fullpage.sty
3377 \\setlength{\\textwidth}{\\paperwidth}
3378 \\addtolength{\\textwidth}{-3cm}
3379 \\setlength{\\oddsidemargin}{1.5cm}
3380 \\addtolength{\\oddsidemargin}{-2.54cm}
3381 \\setlength{\\evensidemargin}{\\oddsidemargin}
3382 \\setlength{\\textheight}{\\paperheight}
3383 \\addtolength{\\textheight}{-\\headheight}
3384 \\addtolength{\\textheight}{-\\headsep}
3385 \\addtolength{\\textheight}{-\\footskip}
3386 \\addtolength{\\textheight}{-3cm}
3387 \\setlength{\\topmargin}{1.5cm}
3388 \\addtolength{\\topmargin}{-2.54cm}"
3389 "The document header used for processing LaTeX fragments.
3390 It is imperative that this header make sure that no page number
3391 appears on the page. The package defined in the variables
3392 `org-export-latex-default-packages-alist' and `org-export-latex-packages-alist'
3393 will either replace the placeholder \"[PACKAGES]\" in this header, or they
3394 will be appended."
3395 :group 'org-latex
3396 :type 'string)
3398 (defvar org-format-latex-header-extra nil)
3400 (defun org-set-packages-alist (var val)
3401 "Set the packages alist and make sure it has 3 elements per entry."
3402 (set var (mapcar (lambda (x)
3403 (if (and (consp x) (= (length x) 2))
3404 (list (car x) (nth 1 x) t)
3406 val)))
3408 (defun org-get-packages-alist (var)
3410 "Get the packages alist and make sure it has 3 elements per entry."
3411 (mapcar (lambda (x)
3412 (if (and (consp x) (= (length x) 2))
3413 (list (car x) (nth 1 x) t)
3415 (default-value var)))
3417 ;; The following variables are defined here because is it also used
3418 ;; when formatting latex fragments. Originally it was part of the
3419 ;; LaTeX exporter, which is why the name includes "export".
3420 (defcustom org-export-latex-default-packages-alist
3421 '(("AUTO" "inputenc" t)
3422 ("T1" "fontenc" t)
3423 ("" "fixltx2e" nil)
3424 ("" "graphicx" t)
3425 ("" "longtable" nil)
3426 ("" "float" nil)
3427 ("" "wrapfig" nil)
3428 ("" "soul" t)
3429 ("" "textcomp" t)
3430 ("" "marvosym" t)
3431 ("" "wasysym" t)
3432 ("" "latexsym" t)
3433 ("" "amssymb" t)
3434 ("" "hyperref" nil)
3435 "\\tolerance=1000"
3437 "Alist of default packages to be inserted in the header.
3438 Change this only if one of the packages here causes an incompatibility
3439 with another package you are using.
3440 The packages in this list are needed by one part or another of Org-mode
3441 to function properly.
3443 - inputenc, fontenc: for basic font and character selection
3444 - textcomp, marvosymb, wasysym, latexsym, amssym: for various symbols used
3445 for interpreting the entities in `org-entities'. You can skip some of these
3446 packages if you don't use any of the symbols in it.
3447 - graphicx: for including images
3448 - float, wrapfig: for figure placement
3449 - longtable: for long tables
3450 - hyperref: for cross references
3452 Therefore you should not modify this variable unless you know what you
3453 are doing. The one reason to change it anyway is that you might be loading
3454 some other package that conflicts with one of the default packages.
3455 Each cell is of the format \( \"options\" \"package\" snippet-flag\).
3456 If SNIPPET-FLAG is t, the package also needs to be included when
3457 compiling LaTeX snippets into images for inclusion into HTML."
3458 :group 'org-export-latex
3459 :set 'org-set-packages-alist
3460 :get 'org-get-packages-alist
3461 :type '(repeat
3462 (choice
3463 (list :tag "options/package pair"
3464 (string :tag "options")
3465 (string :tag "package")
3466 (boolean :tag "Snippet"))
3467 (string :tag "A line of LaTeX"))))
3469 (defcustom org-export-latex-packages-alist nil
3470 "Alist of packages to be inserted in every LaTeX header.
3471 These will be inserted after `org-export-latex-default-packages-alist'.
3472 Each cell is of the format \( \"options\" \"package\" snippet-flag \).
3473 SNIPPET-FLAG, when t, indicates that this package is also needed when
3474 turning LaTeX snippets into images for inclusion into HTML.
3475 Make sure that you only list packages here which:
3476 - you want in every file
3477 - do not conflict with the default packages in
3478 `org-export-latex-default-packages-alist'
3479 - do not conflict with the setup in `org-format-latex-header'."
3480 :group 'org-export-latex
3481 :set 'org-set-packages-alist
3482 :get 'org-get-packages-alist
3483 :type '(repeat
3484 (choice
3485 (list :tag "options/package pair"
3486 (string :tag "options")
3487 (string :tag "package")
3488 (boolean :tag "Snippet"))
3489 (string :tag "A line of LaTeX"))))
3492 (defgroup org-appearance nil
3493 "Settings for Org-mode appearance."
3494 :tag "Org Appearance"
3495 :group 'org)
3497 (defcustom org-level-color-stars-only nil
3498 "Non-nil means fontify only the stars in each headline.
3499 When nil, the entire headline is fontified.
3500 Changing it requires restart of `font-lock-mode' to become effective
3501 also in regions already fontified."
3502 :group 'org-appearance
3503 :type 'boolean)
3505 (defcustom org-hide-leading-stars nil
3506 "Non-nil means hide the first N-1 stars in a headline.
3507 This works by using the face `org-hide' for these stars. This
3508 face is white for a light background, and black for a dark
3509 background. You may have to customize the face `org-hide' to
3510 make this work.
3511 Changing it requires restart of `font-lock-mode' to become effective
3512 also in regions already fontified.
3513 You may also set this on a per-file basis by adding one of the following
3514 lines to the buffer:
3516 #+STARTUP: hidestars
3517 #+STARTUP: showstars"
3518 :group 'org-appearance
3519 :type 'boolean)
3521 (defcustom org-hidden-keywords nil
3522 "List of symbols corresponding to keywords to be hidden the org buffer.
3523 For example, a value '(title) for this list will make the document's title
3524 appear in the buffer without the initial #+TITLE: keyword."
3525 :group 'org-appearance
3526 :type '(set (const :tag "#+AUTHOR" author)
3527 (const :tag "#+DATE" date)
3528 (const :tag "#+EMAIL" email)
3529 (const :tag "#+TITLE" title)))
3531 (defcustom org-fontify-done-headline nil
3532 "Non-nil means change the face of a headline if it is marked DONE.
3533 Normally, only the TODO/DONE keyword indicates the state of a headline.
3534 When this is non-nil, the headline after the keyword is set to the
3535 `org-headline-done' as an additional indication."
3536 :group 'org-appearance
3537 :type 'boolean)
3539 (defcustom org-fontify-emphasized-text t
3540 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3541 Changing this variable requires a restart of Emacs to take effect."
3542 :group 'org-appearance
3543 :type 'boolean)
3545 (defcustom org-fontify-whole-heading-line nil
3546 "Non-nil means fontify the whole line for headings.
3547 This is useful when setting a background color for the
3548 org-level-* faces."
3549 :group 'org-appearance
3550 :type 'boolean)
3552 (defcustom org-highlight-latex-fragments-and-specials nil
3553 "Non-nil means fontify what is treated specially by the exporters."
3554 :group 'org-appearance
3555 :type 'boolean)
3557 (defcustom org-hide-emphasis-markers nil
3558 "Non-nil mean font-lock should hide the emphasis marker characters."
3559 :group 'org-appearance
3560 :type 'boolean)
3562 (defcustom org-pretty-entities nil
3563 "Non-nil means show entities as UTF8 characters.
3564 When nil, the \\name form remains in the buffer."
3565 :group 'org-appearance
3566 :type 'boolean)
3568 (defcustom org-pretty-entities-include-sub-superscripts t
3569 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3570 :group 'org-appearance
3571 :type 'boolean)
3573 (defvar org-emph-re nil
3574 "Regular expression for matching emphasis.
3575 After a match, the match groups contain these elements:
3576 0 The match of the full regular expression, including the characters
3577 before and after the proper match
3578 1 The character before the proper match, or empty at beginning of line
3579 2 The proper match, including the leading and trailing markers
3580 3 The leading marker like * or /, indicating the type of highlighting
3581 4 The text between the emphasis markers, not including the markers
3582 5 The character after the match, empty at the end of a line")
3583 (defvar org-verbatim-re nil
3584 "Regular expression for matching verbatim text.")
3585 (defvar org-emphasis-regexp-components) ; defined just below
3586 (defvar org-emphasis-alist) ; defined just below
3587 (defun org-set-emph-re (var val)
3588 "Set variable and compute the emphasis regular expression."
3589 (set var val)
3590 (when (and (boundp 'org-emphasis-alist)
3591 (boundp 'org-emphasis-regexp-components)
3592 org-emphasis-alist org-emphasis-regexp-components)
3593 (let* ((e org-emphasis-regexp-components)
3594 (pre (car e))
3595 (post (nth 1 e))
3596 (border (nth 2 e))
3597 (body (nth 3 e))
3598 (nl (nth 4 e))
3599 (body1 (concat body "*?"))
3600 (markers (mapconcat 'car org-emphasis-alist ""))
3601 (vmarkers (mapconcat
3602 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3603 org-emphasis-alist "")))
3604 ;; make sure special characters appear at the right position in the class
3605 (if (string-match "\\^" markers)
3606 (setq markers (concat (replace-match "" t t markers) "^")))
3607 (if (string-match "-" markers)
3608 (setq markers (concat (replace-match "" t t markers) "-")))
3609 (if (string-match "\\^" vmarkers)
3610 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3611 (if (string-match "-" vmarkers)
3612 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3613 (if (> nl 0)
3614 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3615 (int-to-string nl) "\\}")))
3616 ;; Make the regexp
3617 (setq org-emph-re
3618 (concat "\\([" pre "]\\|^\\)"
3619 "\\("
3620 "\\([" markers "]\\)"
3621 "\\("
3622 "[^" border "]\\|"
3623 "[^" border "]"
3624 body1
3625 "[^" border "]"
3626 "\\)"
3627 "\\3\\)"
3628 "\\([" post "]\\|$\\)"))
3629 (setq org-verbatim-re
3630 (concat "\\([" pre "]\\|^\\)"
3631 "\\("
3632 "\\([" vmarkers "]\\)"
3633 "\\("
3634 "[^" border "]\\|"
3635 "[^" border "]"
3636 body1
3637 "[^" border "]"
3638 "\\)"
3639 "\\3\\)"
3640 "\\([" post "]\\|$\\)")))))
3642 (defcustom org-emphasis-regexp-components
3643 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
3644 "Components used to build the regular expression for emphasis.
3645 This is a list with five entries. Terminology: In an emphasis string
3646 like \" *strong word* \", we call the initial space PREMATCH, the final
3647 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3648 and \"trong wor\" is the body. The different components in this variable
3649 specify what is allowed/forbidden in each part:
3651 pre Chars allowed as prematch. Beginning of line will be allowed too.
3652 post Chars allowed as postmatch. End of line will be allowed too.
3653 border The chars *forbidden* as border characters.
3654 body-regexp A regexp like \".\" to match a body character. Don't use
3655 non-shy groups here, and don't allow newline here.
3656 newline The maximum number of newlines allowed in an emphasis exp.
3658 Use customize to modify this, or restart Emacs after changing it."
3659 :group 'org-appearance
3660 :set 'org-set-emph-re
3661 :type '(list
3662 (sexp :tag "Allowed chars in pre ")
3663 (sexp :tag "Allowed chars in post ")
3664 (sexp :tag "Forbidden chars in border ")
3665 (sexp :tag "Regexp for body ")
3666 (integer :tag "number of newlines allowed")
3667 (option (boolean :tag "Please ignore this button"))))
3669 (defcustom org-emphasis-alist
3670 `(("*" bold "<b>" "</b>")
3671 ("/" italic "<i>" "</i>")
3672 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
3673 ("=" org-code "<code>" "</code>" verbatim)
3674 ("~" org-verbatim "<code>" "</code>" verbatim)
3675 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
3676 "<del>" "</del>")
3678 "Special syntax for emphasized text.
3679 Text starting and ending with a special character will be emphasized, for
3680 example *bold*, _underlined_ and /italic/. This variable sets the marker
3681 characters, the face to be used by font-lock for highlighting in Org-mode
3682 Emacs buffers, and the HTML tags to be used for this.
3683 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
3684 For DocBook export, see the variable `org-export-docbook-emphasis-alist'.
3685 Use customize to modify this, or restart Emacs after changing it."
3686 :group 'org-appearance
3687 :set 'org-set-emph-re
3688 :type '(repeat
3689 (list
3690 (string :tag "Marker character")
3691 (choice
3692 (face :tag "Font-lock-face")
3693 (plist :tag "Face property list"))
3694 (string :tag "HTML start tag")
3695 (string :tag "HTML end tag")
3696 (option (const verbatim)))))
3698 (defvar org-protecting-blocks
3699 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
3700 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
3701 This is needed for font-lock setup.")
3703 ;;; Miscellaneous options
3705 (defgroup org-completion nil
3706 "Completion in Org-mode."
3707 :tag "Org Completion"
3708 :group 'org)
3710 (defcustom org-completion-use-ido nil
3711 "Non-nil means use ido completion wherever possible.
3712 Note that `ido-mode' must be active for this variable to be relevant.
3713 If you decide to turn this variable on, you might well want to turn off
3714 `org-outline-path-complete-in-steps'.
3715 See also `org-completion-use-iswitchb'."
3716 :group 'org-completion
3717 :type 'boolean)
3719 (defcustom org-completion-use-iswitchb nil
3720 "Non-nil means use iswitchb completion wherever possible.
3721 Note that `iswitchb-mode' must be active for this variable to be relevant.
3722 If you decide to turn this variable on, you might well want to turn off
3723 `org-outline-path-complete-in-steps'.
3724 Note that this variable has only an effect if `org-completion-use-ido' is nil."
3725 :group 'org-completion
3726 :type 'boolean)
3728 (defcustom org-completion-fallback-command 'hippie-expand
3729 "The expansion command called by \\[pcomplete] in normal context.
3730 Normal means, no org-mode-specific context."
3731 :group 'org-completion
3732 :type 'function)
3734 ;;; Functions and variables from their packages
3735 ;; Declared here to avoid compiler warnings
3737 ;; XEmacs only
3738 (defvar outline-mode-menu-heading)
3739 (defvar outline-mode-menu-show)
3740 (defvar outline-mode-menu-hide)
3741 (defvar zmacs-regions) ; XEmacs regions
3743 ;; Emacs only
3744 (defvar mark-active)
3746 ;; Various packages
3747 (declare-function calendar-absolute-from-iso "cal-iso" (date))
3748 (declare-function calendar-forward-day "cal-move" (arg))
3749 (declare-function calendar-goto-date "cal-move" (date))
3750 (declare-function calendar-goto-today "cal-move" ())
3751 (declare-function calendar-iso-from-absolute "cal-iso" (date))
3752 (defvar calc-embedded-close-formula)
3753 (defvar calc-embedded-open-formula)
3754 (declare-function cdlatex-tab "ext:cdlatex" ())
3755 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
3756 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3757 (defvar font-lock-unfontify-region-function)
3758 (declare-function iswitchb-read-buffer "iswitchb"
3759 (prompt &optional default require-match start matches-set))
3760 (defvar iswitchb-temp-buflist)
3761 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
3762 (defvar org-agenda-tags-todo-honor-ignore-options)
3763 (declare-function org-agenda-skip "org-agenda" ())
3764 (declare-function
3765 org-agenda-format-item "org-agenda"
3766 (extra txt &optional category tags dotime noprefix remove-re habitp))
3767 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
3768 (declare-function org-agenda-change-all-lines "org-agenda"
3769 (newhead hdmarker &optional fixface just-this))
3770 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
3771 (declare-function org-agenda-maybe-redo "org-agenda" ())
3772 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
3773 (beg end))
3774 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
3775 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
3776 "org-agenda" (&optional end))
3777 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
3778 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
3779 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
3780 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
3781 (declare-function org-indent-mode "org-indent" (&optional arg))
3782 (declare-function parse-time-string "parse-time" (string))
3783 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
3784 (declare-function org-export-latex-fix-inputenc "org-latex" ())
3785 (declare-function orgtbl-send-table "org-table" (&optional maybe))
3786 (defvar remember-data-file)
3787 (defvar texmathp-why)
3788 (declare-function speedbar-line-directory "speedbar" (&optional depth))
3789 (declare-function table--at-cell-p "table" (position &optional object at-column))
3791 (defvar w3m-current-url)
3792 (defvar w3m-current-title)
3794 (defvar org-latex-regexps)
3796 ;;; Autoload and prepare some org modules
3798 ;; Some table stuff that needs to be defined here, because it is used
3799 ;; by the functions setting up org-mode or checking for table context.
3801 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
3802 "Detect an org-type or table-type table.")
3803 (defconst org-table-line-regexp "^[ \t]*|"
3804 "Detect an org-type table line.")
3805 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
3806 "Detect an org-type table line.")
3807 (defconst org-table-hline-regexp "^[ \t]*|-"
3808 "Detect an org-type table hline.")
3809 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
3810 "Detect a table-type table hline.")
3811 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
3812 "Detect the first line outside a table when searching from within it.
3813 This works for both table types.")
3815 ;; Autoload the functions in org-table.el that are needed by functions here.
3817 (eval-and-compile
3818 (org-autoload "org-table"
3819 '(org-table-align org-table-begin org-table-blank-field
3820 org-table-convert org-table-convert-region org-table-copy-down
3821 org-table-copy-region org-table-create
3822 org-table-create-or-convert-from-region
3823 org-table-create-with-table.el org-table-current-dline
3824 org-table-cut-region org-table-delete-column org-table-edit-field
3825 org-table-edit-formulas org-table-end org-table-eval-formula
3826 org-table-export org-table-field-info
3827 org-table-get-stored-formulas org-table-goto-column
3828 org-table-hline-and-move org-table-import org-table-insert-column
3829 org-table-insert-hline org-table-insert-row org-table-iterate
3830 org-table-justify-field-maybe org-table-kill-row
3831 org-table-maybe-eval-formula org-table-maybe-recalculate-line
3832 org-table-move-column org-table-move-column-left
3833 org-table-move-column-right org-table-move-row
3834 org-table-move-row-down org-table-move-row-up
3835 org-table-next-field org-table-next-row org-table-paste-rectangle
3836 org-table-previous-field org-table-recalculate
3837 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
3838 org-table-toggle-coordinate-overlays
3839 org-table-toggle-formula-debugger org-table-wrap-region
3840 orgtbl-mode turn-on-orgtbl org-table-to-lisp
3841 orgtbl-to-generic orgtbl-to-tsv orgtbl-to-csv orgtbl-to-latex
3842 orgtbl-to-orgtbl orgtbl-to-html orgtbl-to-texinfo)))
3844 (defun org-at-table-p (&optional table-type)
3845 "Return t if the cursor is inside an org-type table.
3846 If TABLE-TYPE is non-nil, also check for table.el-type tables."
3847 (if org-enable-table-editor
3848 (save-excursion
3849 (beginning-of-line 1)
3850 (looking-at (if table-type org-table-any-line-regexp
3851 org-table-line-regexp)))
3852 nil))
3853 (defsubst org-table-p () (org-at-table-p))
3855 (defun org-at-table.el-p ()
3856 "Return t if and only if we are at a table.el table."
3857 (and (org-at-table-p 'any)
3858 (save-excursion
3859 (goto-char (org-table-begin 'any))
3860 (looking-at org-table1-hline-regexp))))
3861 (defun org-table-recognize-table.el ()
3862 "If there is a table.el table nearby, recognize it and move into it."
3863 (if org-table-tab-recognizes-table.el
3864 (if (org-at-table.el-p)
3865 (progn
3866 (beginning-of-line 1)
3867 (if (looking-at org-table-dataline-regexp)
3869 (if (looking-at org-table1-hline-regexp)
3870 (progn
3871 (beginning-of-line 2)
3872 (if (looking-at org-table-any-border-regexp)
3873 (beginning-of-line -1)))))
3874 (if (re-search-forward "|" (org-table-end t) t)
3875 (progn
3876 (require 'table)
3877 (if (table--at-cell-p (point))
3879 (message "recognizing table.el table...")
3880 (table-recognize-table)
3881 (message "recognizing table.el table...done")))
3882 (error "This should not happen"))
3884 nil)
3885 nil))
3887 (defun org-at-table-hline-p ()
3888 "Return t if the cursor is inside a hline in a table."
3889 (if org-enable-table-editor
3890 (save-excursion
3891 (beginning-of-line 1)
3892 (looking-at org-table-hline-regexp))
3893 nil))
3895 (defvar org-table-clean-did-remove-column nil)
3897 (defun org-table-map-tables (function &optional quietly)
3898 "Apply FUNCTION to the start of all tables in the buffer."
3899 (save-excursion
3900 (save-restriction
3901 (widen)
3902 (goto-char (point-min))
3903 (while (re-search-forward org-table-any-line-regexp nil t)
3904 (unless quietly
3905 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
3906 (beginning-of-line 1)
3907 (when (looking-at org-table-line-regexp)
3908 (save-excursion (funcall function))
3909 (or (looking-at org-table-line-regexp)
3910 (forward-char 1)))
3911 (re-search-forward org-table-any-border-regexp nil 1))))
3912 (unless quietly (message "Mapping tables: done")))
3914 ;; Declare and autoload functions from org-exp.el & Co
3916 (declare-function org-default-export-plist "org-exp")
3917 (declare-function org-infile-export-plist "org-exp")
3918 (declare-function org-get-current-options "org-exp")
3919 (eval-and-compile
3920 (org-autoload "org-exp"
3921 '(org-export org-export-visible
3922 org-insert-export-options-template
3923 org-table-clean-before-export))
3924 (org-autoload "org-ascii"
3925 '(org-export-as-ascii org-export-ascii-preprocess
3926 org-export-as-ascii-to-buffer org-replace-region-by-ascii
3927 org-export-region-as-ascii))
3928 (org-autoload "org-latex"
3929 '(org-export-as-latex-batch org-export-as-latex-to-buffer
3930 org-replace-region-by-latex org-export-region-as-latex
3931 org-export-as-latex org-export-as-pdf
3932 org-export-as-pdf-and-open))
3933 (org-autoload "org-html"
3934 '(org-export-as-html-and-open
3935 org-export-as-html-batch org-export-as-html-to-buffer
3936 org-replace-region-by-html org-export-region-as-html
3937 org-export-as-html))
3938 (org-autoload "org-docbook"
3939 '(org-export-as-docbook-batch org-export-as-docbook-to-buffer
3940 org-replace-region-by-docbook org-export-region-as-docbook
3941 org-export-as-docbook-pdf org-export-as-docbook-pdf-and-open
3942 org-export-as-docbook))
3943 (org-autoload "org-icalendar"
3944 '(org-export-icalendar-this-file
3945 org-export-icalendar-all-agenda-files
3946 org-export-icalendar-combine-agenda-files))
3947 (org-autoload "org-xoxo" '(org-export-as-xoxo))
3948 (org-autoload "org-beamer" '(org-beamer-mode org-beamer-sectioning)))
3950 ;; Declare and autoload functions from org-agenda.el
3952 (eval-and-compile
3953 (org-autoload "org-agenda"
3954 '(org-agenda org-agenda-list org-search-view
3955 org-todo-list org-tags-view org-agenda-list-stuck-projects
3956 org-diary org-agenda-to-appt
3957 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
3959 ;; Autoload org-remember
3961 (eval-and-compile
3962 (org-autoload "org-remember"
3963 '(org-remember-insinuate org-remember-annotation
3964 org-remember-apply-template org-remember org-remember-handler)))
3966 (eval-and-compile
3967 (org-autoload "org-capture"
3968 '(org-capture org-capture-insert-template-here
3969 org-capture-import-remember-templates)))
3971 ;; Autoload org-clock.el
3973 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
3974 (beg end))
3975 (declare-function org-clock-update-mode-line "org-clock" ())
3976 (declare-function org-resolve-clocks "org-clock"
3977 (&optional also-non-dangling-p prompt last-valid))
3978 (defvar org-clock-start-time)
3979 (defvar org-clock-marker (make-marker)
3980 "Marker recording the last clock-in.")
3981 (defvar org-clock-hd-marker (make-marker)
3982 "Marker recording the last clock-in, but the headline position.")
3983 (defvar org-clock-heading ""
3984 "The heading of the current clock entry.")
3985 (defun org-clock-is-active ()
3986 "Return non-nil if clock is currently running.
3987 The return value is actually the clock marker."
3988 (marker-buffer org-clock-marker))
3990 (eval-and-compile
3991 (org-autoload
3992 "org-clock"
3993 '(org-clock-in org-clock-out org-clock-cancel
3994 org-clock-goto org-clock-sum org-clock-display
3995 org-clock-remove-overlays org-clock-report
3996 org-clocktable-shift org-dblock-write:clocktable
3997 org-get-clocktable org-resolve-clocks)))
3999 (defun org-clock-update-time-maybe ()
4000 "If this is a CLOCK line, update it and return t.
4001 Otherwise, return nil."
4002 (interactive)
4003 (save-excursion
4004 (beginning-of-line 1)
4005 (skip-chars-forward " \t")
4006 (when (looking-at org-clock-string)
4007 (let ((re (concat "[ \t]*" org-clock-string
4008 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
4009 "\\([ \t]*=>.*\\)?\\)?"))
4010 ts te h m s neg)
4011 (cond
4012 ((not (looking-at re))
4013 nil)
4014 ((not (match-end 2))
4015 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4016 (> org-clock-marker (point))
4017 (<= org-clock-marker (point-at-eol)))
4018 ;; The clock is running here
4019 (setq org-clock-start-time
4020 (apply 'encode-time
4021 (org-parse-time-string (match-string 1))))
4022 (org-clock-update-mode-line)))
4024 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
4025 (end-of-line 1)
4026 (setq ts (match-string 1)
4027 te (match-string 3))
4028 (setq s (- (org-float-time
4029 (apply 'encode-time (org-parse-time-string te)))
4030 (org-float-time
4031 (apply 'encode-time (org-parse-time-string ts))))
4032 neg (< s 0)
4033 s (abs s)
4034 h (floor (/ s 3600))
4035 s (- s (* 3600 h))
4036 m (floor (/ s 60))
4037 s (- s (* 60 s)))
4038 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
4039 t))))))
4041 (defun org-check-running-clock ()
4042 "Check if the current buffer contains the running clock.
4043 If yes, offer to stop it and to save the buffer with the changes."
4044 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4045 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4046 (buffer-name))))
4047 (org-clock-out)
4048 (when (y-or-n-p "Save changed buffer?")
4049 (save-buffer))))
4051 (defun org-clocktable-try-shift (dir n)
4052 "Check if this line starts a clock table, if yes, shift the time block."
4053 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4054 (org-clocktable-shift dir n)))
4056 ;; Autoload org-timer.el
4058 (eval-and-compile
4059 (org-autoload
4060 "org-timer"
4061 '(org-timer-start org-timer org-timer-item
4062 org-timer-change-times-in-region
4063 org-timer-set-timer
4064 org-timer-reset-timers
4065 org-timer-show-remaining-time)))
4067 ;; Autoload org-feed.el
4069 (eval-and-compile
4070 (org-autoload
4071 "org-feed"
4072 '(org-feed-update org-feed-update-all org-feed-goto-inbox)))
4075 ;; Autoload org-indent.el
4077 ;; Define the variable already here, to make sure we have it.
4078 (defvar org-indent-mode nil
4079 "Non-nil if Org-Indent mode is enabled.
4080 Use the command `org-indent-mode' to change this variable.")
4082 (eval-and-compile
4083 (org-autoload
4084 "org-indent"
4085 '(org-indent-mode)))
4087 ;; Autoload org-mobile.el
4089 (eval-and-compile
4090 (org-autoload
4091 "org-mobile"
4092 '(org-mobile-push org-mobile-pull org-mobile-create-sumo-agenda)))
4094 ;; Autoload archiving code
4095 ;; The stuff that is needed for cycling and tags has to be defined here.
4097 (defgroup org-archive nil
4098 "Options concerning archiving in Org-mode."
4099 :tag "Org Archive"
4100 :group 'org-structure)
4102 (defcustom org-archive-location "%s_archive::"
4103 "The location where subtrees should be archived.
4105 The value of this variable is a string, consisting of two parts,
4106 separated by a double-colon. The first part is a filename and
4107 the second part is a headline.
4109 When the filename is omitted, archiving happens in the same file.
4110 %s in the filename will be replaced by the current file
4111 name (without the directory part). Archiving to a different file
4112 is useful to keep archived entries from contributing to the
4113 Org-mode Agenda.
4115 The archived entries will be filed as subtrees of the specified
4116 headline. When the headline is omitted, the subtrees are simply
4117 filed away at the end of the file, as top-level entries. Also in
4118 the heading you can use %s to represent the file name, this can be
4119 useful when using the same archive for a number of different files.
4121 Here are a few examples:
4122 \"%s_archive::\"
4123 If the current file is Projects.org, archive in file
4124 Projects.org_archive, as top-level trees. This is the default.
4126 \"::* Archived Tasks\"
4127 Archive in the current file, under the top-level headline
4128 \"* Archived Tasks\".
4130 \"~/org/archive.org::\"
4131 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4133 \"~/org/archive.org::* From %s\"
4134 Archive in file ~/org/archive.org (absolute path), under headlines
4135 \"From FILENAME\" where file name is the current file name.
4137 \"basement::** Finished Tasks\"
4138 Archive in file ./basement (relative path), as level 3 trees
4139 below the level 2 heading \"** Finished Tasks\".
4141 You may set this option on a per-file basis by adding to the buffer a
4142 line like
4144 #+ARCHIVE: basement::** Finished Tasks
4146 You may also define it locally for a subtree by setting an ARCHIVE property
4147 in the entry. If such a property is found in an entry, or anywhere up
4148 the hierarchy, it will be used."
4149 :group 'org-archive
4150 :type 'string)
4152 (defcustom org-archive-tag "ARCHIVE"
4153 "The tag that marks a subtree as archived.
4154 An archived subtree does not open during visibility cycling, and does
4155 not contribute to the agenda listings.
4156 After changing this, font-lock must be restarted in the relevant buffers to
4157 get the proper fontification."
4158 :group 'org-archive
4159 :group 'org-keywords
4160 :type 'string)
4162 (defcustom org-agenda-skip-archived-trees t
4163 "Non-nil means the agenda will skip any items located in archived trees.
4164 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4165 variable is no longer recommended, you should leave it at the value t.
4166 Instead, use the key `v' to cycle the archives-mode in the agenda."
4167 :group 'org-archive
4168 :group 'org-agenda-skip
4169 :type 'boolean)
4171 (defcustom org-columns-skip-archived-trees t
4172 "Non-nil means ignore archived trees when creating column view."
4173 :group 'org-archive
4174 :group 'org-properties
4175 :type 'boolean)
4177 (defcustom org-cycle-open-archived-trees nil
4178 "Non-nil means `org-cycle' will open archived trees.
4179 An archived tree is a tree marked with the tag ARCHIVE.
4180 When nil, archived trees will stay folded. You can still open them with
4181 normal outline commands like `show-all', but not with the cycling commands."
4182 :group 'org-archive
4183 :group 'org-cycle
4184 :type 'boolean)
4186 (defcustom org-sparse-tree-open-archived-trees nil
4187 "Non-nil means sparse tree construction shows matches in archived trees.
4188 When nil, matches in these trees are highlighted, but the trees are kept in
4189 collapsed state."
4190 :group 'org-archive
4191 :group 'org-sparse-trees
4192 :type 'boolean)
4194 (defun org-cycle-hide-archived-subtrees (state)
4195 "Re-hide all archived subtrees after a visibility state change."
4196 (when (and (not org-cycle-open-archived-trees)
4197 (not (memq state '(overview folded))))
4198 (save-excursion
4199 (let* ((globalp (memq state '(contents all)))
4200 (beg (if globalp (point-min) (point)))
4201 (end (if globalp (point-max) (org-end-of-subtree t))))
4202 (org-hide-archived-subtrees beg end)
4203 (goto-char beg)
4204 (if (looking-at (concat ".*:" org-archive-tag ":"))
4205 (message "%s" (substitute-command-keys
4206 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4208 (defun org-force-cycle-archived ()
4209 "Cycle subtree even if it is archived."
4210 (interactive)
4211 (setq this-command 'org-cycle)
4212 (let ((org-cycle-open-archived-trees t))
4213 (call-interactively 'org-cycle)))
4215 (defun org-hide-archived-subtrees (beg end)
4216 "Re-hide all archived subtrees after a visibility state change."
4217 (save-excursion
4218 (let* ((re (concat ":" org-archive-tag ":")))
4219 (goto-char beg)
4220 (while (re-search-forward re end t)
4221 (when (org-on-heading-p)
4222 (org-flag-subtree t)
4223 (org-end-of-subtree t))))))
4225 (defun org-flag-subtree (flag)
4226 (save-excursion
4227 (org-back-to-heading t)
4228 (outline-end-of-heading)
4229 (outline-flag-region (point)
4230 (progn (org-end-of-subtree t) (point))
4231 flag)))
4233 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4235 (eval-and-compile
4236 (org-autoload "org-archive"
4237 '(org-add-archive-files org-archive-subtree
4238 org-archive-to-archive-sibling org-toggle-archive-tag
4239 org-archive-subtree-default
4240 org-archive-subtree-default-with-confirmation)))
4242 ;; Autoload Column View Code
4244 (declare-function org-columns-number-to-string "org-colview")
4245 (declare-function org-columns-get-format-and-top-level "org-colview")
4246 (declare-function org-columns-compute "org-colview")
4248 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4249 '(org-columns-number-to-string org-columns-get-format-and-top-level
4250 org-columns-compute org-agenda-columns org-columns-remove-overlays
4251 org-columns org-insert-columns-dblock org-dblock-write:columnview))
4253 ;; Autoload ID code
4255 (declare-function org-id-store-link "org-id")
4256 (declare-function org-id-locations-load "org-id")
4257 (declare-function org-id-locations-save "org-id")
4258 (defvar org-id-track-globally)
4259 (org-autoload "org-id"
4260 '(org-id-get-create org-id-new org-id-copy org-id-get
4261 org-id-get-with-outline-path-completion
4262 org-id-get-with-outline-drilling org-id-store-link
4263 org-id-goto org-id-find org-id-store-link))
4265 ;; Autoload Plotting Code
4267 (org-autoload "org-plot"
4268 '(org-plot/gnuplot))
4270 ;;; Variables for pre-computed regular expressions, all buffer local
4272 (defvar org-drawer-regexp nil
4273 "Matches first line of a hidden block.")
4274 (make-variable-buffer-local 'org-drawer-regexp)
4275 (defvar org-todo-regexp nil
4276 "Matches any of the TODO state keywords.")
4277 (make-variable-buffer-local 'org-todo-regexp)
4278 (defvar org-not-done-regexp nil
4279 "Matches any of the TODO state keywords except the last one.")
4280 (make-variable-buffer-local 'org-not-done-regexp)
4281 (defvar org-not-done-heading-regexp nil
4282 "Matches a TODO headline that is not done.")
4283 (make-variable-buffer-local 'org-not-done-regexp)
4284 (defvar org-todo-line-regexp nil
4285 "Matches a headline and puts TODO state into group 2 if present.")
4286 (make-variable-buffer-local 'org-todo-line-regexp)
4287 (defvar org-complex-heading-regexp nil
4288 "Matches a headline and puts everything into groups:
4289 group 1: the stars
4290 group 2: The todo keyword, maybe
4291 group 3: Priority cookie
4292 group 4: True headline
4293 group 5: Tags")
4294 (make-variable-buffer-local 'org-complex-heading-regexp)
4295 (defvar org-complex-heading-regexp-format nil
4296 "Printf format to make regexp to match an exact headline.
4297 This regexp will match the headline of any node which has the
4298 exact headline text that is put into the format, but may have any
4299 TODO state, priority and tags.")
4300 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4301 (defvar org-todo-line-tags-regexp nil
4302 "Matches a headline and puts TODO state into group 2 if present.
4303 Also put tags into group 4 if tags are present.")
4304 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4305 (defvar org-ds-keyword-length 12
4306 "Maximum length of the Deadline and SCHEDULED keywords.")
4307 (make-variable-buffer-local 'org-ds-keyword-length)
4308 (defvar org-deadline-regexp nil
4309 "Matches the DEADLINE keyword.")
4310 (make-variable-buffer-local 'org-deadline-regexp)
4311 (defvar org-deadline-time-regexp nil
4312 "Matches the DEADLINE keyword together with a time stamp.")
4313 (make-variable-buffer-local 'org-deadline-time-regexp)
4314 (defvar org-deadline-line-regexp nil
4315 "Matches the DEADLINE keyword and the rest of the line.")
4316 (make-variable-buffer-local 'org-deadline-line-regexp)
4317 (defvar org-scheduled-regexp nil
4318 "Matches the SCHEDULED keyword.")
4319 (make-variable-buffer-local 'org-scheduled-regexp)
4320 (defvar org-scheduled-time-regexp nil
4321 "Matches the SCHEDULED keyword together with a time stamp.")
4322 (make-variable-buffer-local 'org-scheduled-time-regexp)
4323 (defvar org-closed-time-regexp nil
4324 "Matches the CLOSED keyword together with a time stamp.")
4325 (make-variable-buffer-local 'org-closed-time-regexp)
4327 (defvar org-keyword-time-regexp nil
4328 "Matches any of the 4 keywords, together with the time stamp.")
4329 (make-variable-buffer-local 'org-keyword-time-regexp)
4330 (defvar org-keyword-time-not-clock-regexp nil
4331 "Matches any of the 3 keywords, together with the time stamp.")
4332 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4333 (defvar org-maybe-keyword-time-regexp nil
4334 "Matches a timestamp, possibly preceded by a keyword.")
4335 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4336 (defvar org-planning-or-clock-line-re nil
4337 "Matches a line with planning or clock info.")
4338 (make-variable-buffer-local 'org-planning-or-clock-line-re)
4339 (defvar org-all-time-keywords nil
4340 "List of time keywords.")
4341 (make-variable-buffer-local 'org-all-time-keywords)
4343 (defconst org-plain-time-of-day-regexp
4344 (concat
4345 "\\(\\<[012]?[0-9]"
4346 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4347 "\\(--?"
4348 "\\(\\<[012]?[0-9]"
4349 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4350 "\\)?")
4351 "Regular expression to match a plain time or time range.
4352 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4353 groups carry important information:
4354 0 the full match
4355 1 the first time, range or not
4356 8 the second time, if it is a range.")
4358 (defconst org-plain-time-extension-regexp
4359 (concat
4360 "\\(\\<[012]?[0-9]"
4361 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4362 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4363 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4364 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4365 groups carry important information:
4366 0 the full match
4367 7 hours of duration
4368 9 minutes of duration")
4370 (defconst org-stamp-time-of-day-regexp
4371 (concat
4372 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4373 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4374 "\\(--?"
4375 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4376 "Regular expression to match a timestamp time or time range.
4377 After a match, the following groups carry important information:
4378 0 the full match
4379 1 date plus weekday, for back referencing to make sure both times are on the same day
4380 2 the first time, range or not
4381 4 the second time, if it is a range.")
4383 (defconst org-startup-options
4384 '(("fold" org-startup-folded t)
4385 ("overview" org-startup-folded t)
4386 ("nofold" org-startup-folded nil)
4387 ("showall" org-startup-folded nil)
4388 ("showeverything" org-startup-folded showeverything)
4389 ("content" org-startup-folded content)
4390 ("indent" org-startup-indented t)
4391 ("noindent" org-startup-indented nil)
4392 ("hidestars" org-hide-leading-stars t)
4393 ("showstars" org-hide-leading-stars nil)
4394 ("odd" org-odd-levels-only t)
4395 ("oddeven" org-odd-levels-only nil)
4396 ("align" org-startup-align-all-tables t)
4397 ("noalign" org-startup-align-all-tables nil)
4398 ("inlineimages" org-startup-with-inline-images t)
4399 ("noinlineimages" org-startup-with-inline-images nil)
4400 ("customtime" org-display-custom-times t)
4401 ("logdone" org-log-done time)
4402 ("lognotedone" org-log-done note)
4403 ("nologdone" org-log-done nil)
4404 ("lognoteclock-out" org-log-note-clock-out t)
4405 ("nolognoteclock-out" org-log-note-clock-out nil)
4406 ("logrepeat" org-log-repeat state)
4407 ("lognoterepeat" org-log-repeat note)
4408 ("nologrepeat" org-log-repeat nil)
4409 ("logreschedule" org-log-reschedule time)
4410 ("lognotereschedule" org-log-reschedule note)
4411 ("nologreschedule" org-log-reschedule nil)
4412 ("logredeadline" org-log-redeadline time)
4413 ("lognoteredeadline" org-log-redeadline note)
4414 ("nologredeadline" org-log-redeadline nil)
4415 ("logrefile" org-log-refile time)
4416 ("lognoterefile" org-log-refile note)
4417 ("nologrefile" org-log-refile nil)
4418 ("fninline" org-footnote-define-inline t)
4419 ("nofninline" org-footnote-define-inline nil)
4420 ("fnlocal" org-footnote-section nil)
4421 ("fnauto" org-footnote-auto-label t)
4422 ("fnprompt" org-footnote-auto-label nil)
4423 ("fnconfirm" org-footnote-auto-label confirm)
4424 ("fnplain" org-footnote-auto-label plain)
4425 ("fnadjust" org-footnote-auto-adjust t)
4426 ("nofnadjust" org-footnote-auto-adjust nil)
4427 ("constcgs" constants-unit-system cgs)
4428 ("constSI" constants-unit-system SI)
4429 ("noptag" org-tag-persistent-alist nil)
4430 ("hideblocks" org-hide-block-startup t)
4431 ("nohideblocks" org-hide-block-startup nil)
4432 ("beamer" org-startup-with-beamer-mode t)
4433 ("entitiespretty" org-pretty-entities t)
4434 ("entitiesplain" org-pretty-entities nil))
4435 "Variable associated with STARTUP options for org-mode.
4436 Each element is a list of three items: The startup options as written
4437 in the #+STARTUP line, the corresponding variable, and the value to
4438 set this variable to if the option is found. An optional forth element PUSH
4439 means to push this value onto the list in the variable.")
4441 (defun org-update-property-plist (key val props)
4442 "Update PROPS with KEY and VAL."
4443 (if (string= "+" (substring key (- (length key) 1)))
4444 (let* ((key (substring key 0 (- (length key) 1)))
4445 (previous (cdr (assoc key props))))
4446 (cons (cons key (concat previous " " val))
4447 (org-remove-if (lambda (p) (string= (car p) key)) props)))
4448 (cons (cons key val) props)))
4450 (defun org-set-regexps-and-options ()
4451 "Precompute regular expressions for current buffer."
4452 (when (eq major-mode 'org-mode)
4453 (org-set-local 'org-todo-kwd-alist nil)
4454 (org-set-local 'org-todo-key-alist nil)
4455 (org-set-local 'org-todo-key-trigger nil)
4456 (org-set-local 'org-todo-keywords-1 nil)
4457 (org-set-local 'org-done-keywords nil)
4458 (org-set-local 'org-todo-heads nil)
4459 (org-set-local 'org-todo-sets nil)
4460 (org-set-local 'org-todo-log-states nil)
4461 (org-set-local 'org-file-properties nil)
4462 (org-set-local 'org-file-tags nil)
4463 (let ((re (org-make-options-regexp
4464 '("CATEGORY" "TODO" "COLUMNS"
4465 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
4466 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE" "LATEX_CLASS"
4467 "OPTIONS")
4468 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4469 (splitre "[ \t]+")
4470 (scripts org-use-sub-superscripts)
4471 kwds kws0 kwsa key log value cat arch tags const links hw dws
4472 tail sep kws1 prio props ftags drawers beamer-p
4473 ext-setup-or-nil setup-contents (start 0))
4474 (save-excursion
4475 (save-restriction
4476 (widen)
4477 (goto-char (point-min))
4478 (while (or (and ext-setup-or-nil
4479 (string-match re ext-setup-or-nil start)
4480 (setq start (match-end 0)))
4481 (and (setq ext-setup-or-nil nil start 0)
4482 (re-search-forward re nil t)))
4483 (setq key (upcase (match-string 1 ext-setup-or-nil))
4484 value (org-match-string-no-properties 2 ext-setup-or-nil))
4485 (if (stringp value) (setq value (org-trim value)))
4486 (cond
4487 ((equal key "CATEGORY")
4488 (setq cat value))
4489 ((member key '("SEQ_TODO" "TODO"))
4490 (push (cons 'sequence (org-split-string value splitre)) kwds))
4491 ((equal key "TYP_TODO")
4492 (push (cons 'type (org-split-string value splitre)) kwds))
4493 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4494 ;; general TODO-like setup
4495 (push (cons (intern (downcase (match-string 1 key)))
4496 (org-split-string value splitre)) kwds))
4497 ((equal key "TAGS")
4498 (setq tags (append tags (if tags '("\\n") nil)
4499 (org-split-string value splitre))))
4500 ((equal key "COLUMNS")
4501 (org-set-local 'org-columns-default-format value))
4502 ((equal key "LINK")
4503 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4504 (push (cons (match-string 1 value)
4505 (org-trim (match-string 2 value)))
4506 links)))
4507 ((equal key "PRIORITIES")
4508 (setq prio (org-split-string value " +")))
4509 ((equal key "PROPERTY")
4510 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4511 (setq props (org-update-property-plist (match-string 1 value)
4512 (match-string 2 value)
4513 props))))
4514 ((equal key "FILETAGS")
4515 (when (string-match "\\S-" value)
4516 (setq ftags
4517 (append
4518 ftags
4519 (apply 'append
4520 (mapcar (lambda (x) (org-split-string x ":"))
4521 (org-split-string value)))))))
4522 ((equal key "DRAWERS")
4523 (setq drawers (org-split-string value splitre)))
4524 ((equal key "CONSTANTS")
4525 (setq const (append const (org-split-string value splitre))))
4526 ((equal key "STARTUP")
4527 (let ((opts (org-split-string value splitre))
4528 l var val)
4529 (while (setq l (pop opts))
4530 (when (setq l (assoc l org-startup-options))
4531 (setq var (nth 1 l) val (nth 2 l))
4532 (if (not (nth 3 l))
4533 (set (make-local-variable var) val)
4534 (if (not (listp (symbol-value var)))
4535 (set (make-local-variable var) nil))
4536 (set (make-local-variable var) (symbol-value var))
4537 (add-to-list var val))))))
4538 ((equal key "ARCHIVE")
4539 (setq arch value)
4540 (remove-text-properties 0 (length arch)
4541 '(face t fontified t) arch))
4542 ((equal key "LATEX_CLASS")
4543 (setq beamer-p (equal value "beamer")))
4544 ((equal key "OPTIONS")
4545 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4546 (setq scripts (read (match-string 2 value)))))
4547 ((equal key "SETUPFILE")
4548 (setq setup-contents (org-file-contents
4549 (expand-file-name
4550 (org-remove-double-quotes value))
4551 'noerror))
4552 (if (not ext-setup-or-nil)
4553 (setq ext-setup-or-nil setup-contents start 0)
4554 (setq ext-setup-or-nil
4555 (concat (substring ext-setup-or-nil 0 start)
4556 "\n" setup-contents "\n"
4557 (substring ext-setup-or-nil start)))))))
4558 ;; search for property blocks
4559 (goto-char (point-min))
4560 (while (re-search-forward org-block-regexp nil t)
4561 (when (equal "PROPERTY" (upcase (match-string 1)))
4562 (setq value (replace-regexp-in-string
4563 "[\n\r]" " " (match-string 4)))
4564 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4565 (setq props (org-update-property-plist (match-string 1 value)
4566 (match-string 2 value)
4567 props)))))))
4568 (org-set-local 'org-use-sub-superscripts scripts)
4569 (when cat
4570 (org-set-local 'org-category (intern cat))
4571 (push (cons "CATEGORY" cat) props))
4572 (when prio
4573 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4574 (setq prio (mapcar 'string-to-char prio))
4575 (org-set-local 'org-highest-priority (nth 0 prio))
4576 (org-set-local 'org-lowest-priority (nth 1 prio))
4577 (org-set-local 'org-default-priority (nth 2 prio)))
4578 (and props (org-set-local 'org-file-properties (nreverse props)))
4579 (and ftags (org-set-local 'org-file-tags
4580 (mapcar 'org-add-prop-inherited ftags)))
4581 (and drawers (org-set-local 'org-drawers drawers))
4582 (and arch (org-set-local 'org-archive-location arch))
4583 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4584 ;; Process the TODO keywords
4585 (unless kwds
4586 ;; Use the global values as if they had been given locally.
4587 (setq kwds (default-value 'org-todo-keywords))
4588 (if (stringp (car kwds))
4589 (setq kwds (list (cons org-todo-interpretation
4590 (default-value 'org-todo-keywords)))))
4591 (setq kwds (reverse kwds)))
4592 (setq kwds (nreverse kwds))
4593 (let (inter kws kw)
4594 (while (setq kws (pop kwds))
4595 (let ((kws (or
4596 (run-hook-with-args-until-success
4597 'org-todo-setup-filter-hook kws)
4598 kws)))
4599 (setq inter (pop kws) sep (member "|" kws)
4600 kws0 (delete "|" (copy-sequence kws))
4601 kwsa nil
4602 kws1 (mapcar
4603 (lambda (x)
4604 ;; 1 2
4605 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4606 (progn
4607 (setq kw (match-string 1 x)
4608 key (and (match-end 2) (match-string 2 x))
4609 log (org-extract-log-state-settings x))
4610 (push (cons kw (and key (string-to-char key))) kwsa)
4611 (and log (push log org-todo-log-states))
4613 (error "Invalid TODO keyword %s" x)))
4614 kws0)
4615 kwsa (if kwsa (append '((:startgroup))
4616 (nreverse kwsa)
4617 '((:endgroup))))
4618 hw (car kws1)
4619 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4620 tail (list inter hw (car dws) (org-last dws))))
4621 (add-to-list 'org-todo-heads hw 'append)
4622 (push kws1 org-todo-sets)
4623 (setq org-done-keywords (append org-done-keywords dws nil))
4624 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4625 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4626 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4627 (setq org-todo-sets (nreverse org-todo-sets)
4628 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4629 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4630 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4631 ;; Process the constants
4632 (when const
4633 (let (e cst)
4634 (while (setq e (pop const))
4635 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4636 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4637 (setq org-table-formula-constants-local cst)))
4639 ;; Process the tags.
4640 (when tags
4641 (let (e tgs)
4642 (while (setq e (pop tags))
4643 (cond
4644 ((equal e "{") (push '(:startgroup) tgs))
4645 ((equal e "}") (push '(:endgroup) tgs))
4646 ((equal e "\\n") (push '(:newline) tgs))
4647 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4648 (push (cons (match-string 1 e)
4649 (string-to-char (match-string 2 e)))
4650 tgs))
4651 (t (push (list e) tgs))))
4652 (org-set-local 'org-tag-alist nil)
4653 (while (setq e (pop tgs))
4654 (or (and (stringp (car e))
4655 (assoc (car e) org-tag-alist))
4656 (push e org-tag-alist)))))
4658 ;; Compute the regular expressions and other local variables.
4659 ;; Using `org-outline-regexp-bol' would complicate them much,
4660 ;; because of the fixed white space at the end of that string.
4661 (if (not org-done-keywords)
4662 (setq org-done-keywords (and org-todo-keywords-1
4663 (list (org-last org-todo-keywords-1)))))
4664 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4665 (length org-scheduled-string)
4666 (length org-clock-string)
4667 (length org-closed-string)))
4668 org-drawer-regexp
4669 (concat "^[ \t]*:\\("
4670 (mapconcat 'regexp-quote org-drawers "\\|")
4671 "\\):[ \t]*$")
4672 org-not-done-keywords
4673 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4674 org-todo-regexp
4675 (concat "\\("
4676 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4677 "\\)")
4678 org-not-done-regexp
4679 (concat "\\("
4680 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4681 "\\)")
4682 org-not-done-heading-regexp
4683 (format org-heading-keyword-regexp-format org-not-done-regexp)
4684 org-todo-line-regexp
4685 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
4686 org-complex-heading-regexp
4687 (concat "^\\(\\*+\\)"
4688 "\\(?: +" org-todo-regexp "\\)?"
4689 "\\(?: +\\(\\[#.\\]\\)\\)?"
4690 "\\(?: +\\(.*?\\)\\)?"
4691 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
4692 "[ \t]*$")
4693 org-complex-heading-regexp-format
4694 (concat "^\\(\\*+\\)"
4695 "\\(?: +" org-todo-regexp "\\)?"
4696 "\\(?: +\\(\\[#.\\]\\)\\)?"
4697 "\\(?: +"
4698 ;; Stats cookies can be sticked to body.
4699 "\\(?:\\[[0-9%%/]+\\] *\\)?"
4700 "\\(%s\\)"
4701 "\\(?: *\\[[0-9%%/]+\\]\\)?"
4702 "\\)"
4703 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
4704 "[ \t]*$")
4705 org-todo-line-tags-regexp
4706 (concat "^\\(\\*+\\)"
4707 "\\(?: +" org-todo-regexp "\\)?"
4708 "\\(?: +\\(.*?\\)\\)?"
4709 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
4710 "[ \t]*$")
4711 org-deadline-regexp (concat "\\<" org-deadline-string)
4712 org-deadline-time-regexp
4713 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4714 org-deadline-line-regexp
4715 (concat "\\<\\(" org-deadline-string "\\).*")
4716 org-scheduled-regexp
4717 (concat "\\<" org-scheduled-string)
4718 org-scheduled-time-regexp
4719 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4720 org-closed-time-regexp
4721 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4722 org-keyword-time-regexp
4723 (concat "\\<\\(" org-scheduled-string
4724 "\\|" org-deadline-string
4725 "\\|" org-closed-string
4726 "\\|" org-clock-string "\\)"
4727 " *[[<]\\([^]>]+\\)[]>]")
4728 org-keyword-time-not-clock-regexp
4729 (concat "\\<\\(" org-scheduled-string
4730 "\\|" org-deadline-string
4731 "\\|" org-closed-string
4732 "\\)"
4733 " *[[<]\\([^]>]+\\)[]>]")
4734 org-maybe-keyword-time-regexp
4735 (concat "\\(\\<\\(" org-scheduled-string
4736 "\\|" org-deadline-string
4737 "\\|" org-closed-string
4738 "\\|" org-clock-string "\\)\\)?"
4739 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4740 org-planning-or-clock-line-re
4741 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
4742 "\\|" org-deadline-string
4743 "\\|" org-closed-string "\\|" org-clock-string
4744 "\\)\\>\\)")
4745 org-all-time-keywords
4746 (mapcar (lambda (w) (substring w 0 -1))
4747 (list org-scheduled-string org-deadline-string
4748 org-clock-string org-closed-string))
4750 (org-compute-latex-and-specials-regexp)
4751 (org-set-font-lock-defaults))))
4753 (defun org-file-contents (file &optional noerror)
4754 "Return the contents of FILE, as a string."
4755 (if (or (not file)
4756 (not (file-readable-p file)))
4757 (if noerror
4758 (progn
4759 (message "Cannot read file \"%s\"" file)
4760 (ding) (sit-for 2)
4762 (error "Cannot read file \"%s\"" file))
4763 (with-temp-buffer
4764 (insert-file-contents file)
4765 (buffer-string))))
4767 (defun org-extract-log-state-settings (x)
4768 "Extract the log state setting from a TODO keyword string.
4769 This will extract info from a string like \"WAIT(w@/!)\"."
4770 (let (kw key log1 log2)
4771 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4772 (setq kw (match-string 1 x)
4773 key (and (match-end 2) (match-string 2 x))
4774 log1 (and (match-end 3) (match-string 3 x))
4775 log2 (and (match-end 4) (match-string 4 x)))
4776 (and (or log1 log2)
4777 (list kw
4778 (and log1 (if (equal log1 "!") 'time 'note))
4779 (and log2 (if (equal log2 "!") 'time 'note)))))))
4781 (defun org-remove-keyword-keys (list)
4782 "Remove a pair of parenthesis at the end of each string in LIST."
4783 (mapcar (lambda (x)
4784 (if (string-match "(.*)$" x)
4785 (substring x 0 (match-beginning 0))
4787 list))
4789 (defun org-assign-fast-keys (alist)
4790 "Assign fast keys to a keyword-key alist.
4791 Respect keys that are already there."
4792 (let (new e (alt ?0))
4793 (while (setq e (pop alist))
4794 (if (or (memq (car e) '(:newline :endgroup :startgroup))
4795 (cdr e)) ;; Key already assigned.
4796 (push e new)
4797 (let ((clist (string-to-list (downcase (car e))))
4798 (used (append new alist)))
4799 (when (= (car clist) ?@)
4800 (pop clist))
4801 (while (and clist (rassoc (car clist) used))
4802 (pop clist))
4803 (unless clist
4804 (while (rassoc alt used)
4805 (incf alt)))
4806 (push (cons (car e) (or (car clist) alt)) new))))
4807 (nreverse new)))
4809 ;;; Some variables used in various places
4811 (defvar org-window-configuration nil
4812 "Used in various places to store a window configuration.")
4813 (defvar org-selected-window nil
4814 "Used in various places to store a window configuration.")
4815 (defvar org-finish-function nil
4816 "Function to be called when `C-c C-c' is used.
4817 This is for getting out of special buffers like remember.")
4820 ;; FIXME: Occasionally check by commenting these, to make sure
4821 ;; no other functions uses these, forgetting to let-bind them.
4822 (defvar entry)
4823 (defvar last-state)
4824 (defvar date)
4826 ;; Defined somewhere in this file, but used before definition.
4827 (defvar org-entities) ;; defined in org-entities.el
4828 (defvar org-struct-menu)
4829 (defvar org-org-menu)
4830 (defvar org-tbl-menu)
4832 ;;;; Define the Org-mode
4834 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4835 (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"))
4838 ;; We use a before-change function to check if a table might need
4839 ;; an update.
4840 (defvar org-table-may-need-update t
4841 "Indicates that a table might need an update.
4842 This variable is set by `org-before-change-function'.
4843 `org-table-align' sets it back to nil.")
4844 (defun org-before-change-function (beg end)
4845 "Every change indicates that a table might need an update."
4846 (setq org-table-may-need-update t))
4847 (defvar org-mode-map)
4848 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4849 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
4850 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4851 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
4852 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
4853 (defvar org-table-buffer-is-an nil)
4855 ;; `org-outline-regexp' ought to be a defconst but is let-binding in
4856 ;; some places -- e.g. see the macro org-with-limited-levels.
4858 ;; In Org buffers, the value of `outline-regexp' is that of
4859 ;; `org-outline-regexp'. The only function still directly relying on
4860 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
4861 ;; job when `orgstruct-mode' is active.
4862 (defvar org-outline-regexp "\\*+ "
4863 "Regexp to match Org headlines.")
4864 (defconst org-outline-regexp-bol "^\\*+ "
4865 "Regexp to match Org headlines.
4866 This is similar to `org-outline-regexp' but additionally makes
4867 sure that we are at the beginning of the line.")
4869 (defconst org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4870 "Matches an headline, putting stars and text into groups.
4871 Stars are put in group 1 and the trimmed body in group 2.")
4872 (defconst org-heading-keyword-regexp-format
4873 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4874 "Printf format for a regexp matching an headline with some keyword.
4875 This regexp will match the headline of any node which has the
4876 exact keyword that is put into the format. The keyword isn't in
4877 any group by default, but the stars and the body are.")
4878 (defconst org-heading-keyword-maybe-regexp-format
4879 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4880 "Printf format for a regexp matching an headline, possibly with some keyword.
4881 This regexp can match any headline with the specified keyword, or
4882 without a keyword. The keyword isn't in any group by default,
4883 but the stars and the body are.")
4885 ;;;###autoload
4886 (define-derived-mode org-mode outline-mode "Org"
4887 "Outline-based notes management and organizer, alias
4888 \"Carsten's outline-mode for keeping track of everything.\"
4890 Org-mode develops organizational tasks around a NOTES file which
4891 contains information about projects as plain text. Org-mode is
4892 implemented on top of outline-mode, which is ideal to keep the content
4893 of large files well structured. It supports ToDo items, deadlines and
4894 time stamps, which magically appear in the diary listing of the Emacs
4895 calendar. Tables are easily created with a built-in table editor.
4896 Plain text URL-like links connect to websites, emails (VM), Usenet
4897 messages (Gnus), BBDB entries, and any files related to the project.
4898 For printing and sharing of notes, an Org-mode file (or a part of it)
4899 can be exported as a structured ASCII or HTML file.
4901 The following commands are available:
4903 \\{org-mode-map}"
4905 ;; Get rid of Outline menus, they are not needed
4906 ;; Need to do this here because define-derived-mode sets up
4907 ;; the keymap so late. Still, it is a waste to call this each time
4908 ;; we switch another buffer into org-mode.
4909 (if (featurep 'xemacs)
4910 (when (boundp 'outline-mode-menu-heading)
4911 ;; Assume this is Greg's port, it uses easymenu
4912 (easy-menu-remove outline-mode-menu-heading)
4913 (easy-menu-remove outline-mode-menu-show)
4914 (easy-menu-remove outline-mode-menu-hide))
4915 (define-key org-mode-map [menu-bar headings] 'undefined)
4916 (define-key org-mode-map [menu-bar hide] 'undefined)
4917 (define-key org-mode-map [menu-bar show] 'undefined))
4919 (org-load-modules-maybe)
4920 (easy-menu-add org-org-menu)
4921 (easy-menu-add org-tbl-menu)
4922 (org-install-agenda-files-menu)
4923 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
4924 (add-to-invisibility-spec '(org-cwidth))
4925 (add-to-invisibility-spec '(org-hide-block . t))
4926 (when (featurep 'xemacs)
4927 (org-set-local 'line-move-ignore-invisible t))
4928 (org-set-local 'outline-regexp org-outline-regexp)
4929 (org-set-local 'outline-level 'org-outline-level)
4930 (setq bidi-paragraph-direction 'left-to-right)
4931 (when (and org-ellipsis
4932 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
4933 (fboundp 'make-glyph-code))
4934 (unless org-display-table
4935 (setq org-display-table (make-display-table)))
4936 (set-display-table-slot
4937 org-display-table 4
4938 (vconcat (mapcar
4939 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
4940 org-ellipsis)))
4941 (if (stringp org-ellipsis) org-ellipsis "..."))))
4942 (setq buffer-display-table org-display-table))
4943 (org-set-regexps-and-options)
4944 (when (and org-tag-faces (not org-tags-special-faces-re))
4945 ;; tag faces set outside customize.... force initialization.
4946 (org-set-tag-faces 'org-tag-faces org-tag-faces))
4947 ;; Calc embedded
4948 (org-set-local 'calc-embedded-open-mode "# ")
4949 (modify-syntax-entry ?@ "w")
4950 (if org-startup-truncated (setq truncate-lines t))
4951 (org-set-local 'font-lock-unfontify-region-function
4952 'org-unfontify-region)
4953 ;; Activate before-change-function
4954 (org-set-local 'org-table-may-need-update t)
4955 (org-add-hook 'before-change-functions 'org-before-change-function nil
4956 'local)
4957 ;; Check for running clock before killing a buffer
4958 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
4959 ;; Paragraphs and auto-filling
4960 (org-set-autofill-regexps)
4961 (setq indent-line-function 'org-indent-line-function)
4962 (org-update-radio-target-regexp)
4963 ;; Beginning/end of defun
4964 (org-set-local 'beginning-of-defun-function 'org-beginning-of-defun)
4965 (org-set-local 'end-of-defun-function 'org-end-of-defun)
4966 ;; Next error for sparse trees
4967 (org-set-local 'next-error-function 'org-occur-next-match)
4968 ;; Make sure dependence stuff works reliably, even for users who set it
4969 ;; too late :-(
4970 (if org-enforce-todo-dependencies
4971 (add-hook 'org-blocker-hook
4972 'org-block-todo-from-children-or-siblings-or-parent)
4973 (remove-hook 'org-blocker-hook
4974 'org-block-todo-from-children-or-siblings-or-parent))
4975 (if org-enforce-todo-checkbox-dependencies
4976 (add-hook 'org-blocker-hook
4977 'org-block-todo-from-checkboxes)
4978 (remove-hook 'org-blocker-hook
4979 'org-block-todo-from-checkboxes))
4981 ;; Comment characters
4982 (org-set-local 'comment-start "#")
4983 (org-set-local 'comment-padding " ")
4985 ;; Align options lines
4986 (org-set-local
4987 'align-mode-rules-list
4988 '((org-in-buffer-settings
4989 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
4990 (modes . '(org-mode)))))
4992 ;; Imenu
4993 (org-set-local 'imenu-create-index-function
4994 'org-imenu-get-tree)
4996 ;; Make isearch reveal context
4997 (if (or (featurep 'xemacs)
4998 (not (boundp 'outline-isearch-open-invisible-function)))
4999 ;; Emacs 21 and XEmacs make use of the hook
5000 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5001 ;; Emacs 22 deals with this through a special variable
5002 (org-set-local 'outline-isearch-open-invisible-function
5003 (lambda (&rest ignore) (org-show-context 'isearch))))
5005 ;; Turn on org-beamer-mode?
5006 (and org-startup-with-beamer-mode (org-beamer-mode 1))
5008 ;; Setup the pcomplete hooks
5009 (set (make-local-variable 'pcomplete-command-completion-function)
5010 'org-pcomplete-initial)
5011 (set (make-local-variable 'pcomplete-command-name-function)
5012 'org-command-at-point)
5013 (set (make-local-variable 'pcomplete-default-completion-function)
5014 'ignore)
5015 (set (make-local-variable 'pcomplete-parse-arguments-function)
5016 'org-parse-arguments)
5017 (set (make-local-variable 'pcomplete-termination-string) "")
5018 (set (make-local-variable 'face-remapping-alist)
5019 '((default org-default)))
5021 ;; If empty file that did not turn on org-mode automatically, make it to.
5022 (if (and org-insert-mode-line-in-empty-file
5023 (org-called-interactively-p 'any)
5024 (= (point-min) (point-max)))
5025 (insert "# -*- mode: org -*-\n\n"))
5026 (unless org-inhibit-startup
5027 (when org-startup-align-all-tables
5028 (let ((bmp (buffer-modified-p)))
5029 (org-table-map-tables 'org-table-align 'quietly)
5030 (set-buffer-modified-p bmp)))
5031 (when org-startup-with-inline-images
5032 (org-display-inline-images))
5033 (when org-startup-indented
5034 (require 'org-indent)
5035 (org-indent-mode 1))
5036 (unless org-inhibit-startup-visibility-stuff
5037 (org-set-startup-visibility))))
5039 (when (fboundp 'abbrev-table-put)
5040 (abbrev-table-put org-mode-abbrev-table
5041 :parents (list text-mode-abbrev-table)))
5043 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5045 (defun org-current-time ()
5046 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
5047 (if (> (car org-time-stamp-rounding-minutes) 1)
5048 (let ((r (car org-time-stamp-rounding-minutes))
5049 (time (decode-time)))
5050 (apply 'encode-time
5051 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5052 (nthcdr 2 time))))
5053 (current-time)))
5055 (defun org-today ()
5056 "Return today date, considering `org-extend-today-until'."
5057 (time-to-days
5058 (time-subtract (current-time)
5059 (list 0 (* 3600 org-extend-today-until) 0))))
5061 ;;;; Font-Lock stuff, including the activators
5063 (defvar org-mouse-map (make-sparse-keymap))
5064 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5065 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5066 (when org-mouse-1-follows-link
5067 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5068 (when org-tab-follows-link
5069 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5070 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5072 (require 'font-lock)
5074 (defconst org-non-link-chars "]\t\n\r<>")
5075 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5076 "shell" "elisp" "doi" "message"))
5077 (defvar org-link-types-re nil
5078 "Matches a link that has a url-like prefix like \"http:\"")
5079 (defvar org-link-re-with-space nil
5080 "Matches a link with spaces, optional angular brackets around it.")
5081 (defvar org-link-re-with-space2 nil
5082 "Matches a link with spaces, optional angular brackets around it.")
5083 (defvar org-link-re-with-space3 nil
5084 "Matches a link with spaces, only for internal part in bracket links.")
5085 (defvar org-angle-link-re nil
5086 "Matches link with angular brackets, spaces are allowed.")
5087 (defvar org-plain-link-re nil
5088 "Matches plain link, without spaces.")
5089 (defvar org-bracket-link-regexp nil
5090 "Matches a link in double brackets.")
5091 (defvar org-bracket-link-analytic-regexp nil
5092 "Regular expression used to analyze links.
5093 Here is what the match groups contain after a match:
5094 1: http:
5095 2: http
5096 3: path
5097 4: [desc]
5098 5: desc")
5099 (defvar org-bracket-link-analytic-regexp++ nil
5100 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5101 (defvar org-any-link-re nil
5102 "Regular expression matching any link.")
5104 (defcustom org-match-sexp-depth 3
5105 "Number of stacked braces for sub/superscript matching.
5106 This has to be set before loading org.el to be effective."
5107 :group 'org-export-translation ; ??????????????????????????/
5108 :type 'integer)
5110 (defun org-create-multibrace-regexp (left right n)
5111 "Create a regular expression which will match a balanced sexp.
5112 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5113 as single character strings.
5114 The regexp returned will match the entire expression including the
5115 delimiters. It will also define a single group which contains the
5116 match except for the outermost delimiters. The maximum depth of
5117 stacked delimiters is N. Escaping delimiters is not possible."
5118 (let* ((nothing (concat "[^" left right "]*?"))
5119 (or "\\|")
5120 (re nothing)
5121 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5122 (while (> n 1)
5123 (setq n (1- n)
5124 re (concat re or next)
5125 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5126 (concat left "\\(" re "\\)" right)))
5128 (defvar org-match-substring-regexp
5129 (concat
5130 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5131 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5132 "\\|"
5133 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5134 "\\|"
5135 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5136 "The regular expression matching a sub- or superscript.")
5138 (defvar org-match-substring-with-braces-regexp
5139 (concat
5140 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5141 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5142 "\\)")
5143 "The regular expression matching a sub- or superscript, forcing braces.")
5145 (defun org-make-link-regexps ()
5146 "Update the link regular expressions.
5147 This should be called after the variable `org-link-types' has changed."
5148 (setq org-link-types-re
5149 (concat
5150 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5151 org-link-re-with-space
5152 (concat
5153 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5154 "\\([^" org-non-link-chars " ]"
5155 "[^" org-non-link-chars "]*"
5156 "[^" org-non-link-chars " ]\\)>?")
5157 org-link-re-with-space2
5158 (concat
5159 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5160 "\\([^" org-non-link-chars " ]"
5161 "[^\t\n\r]*"
5162 "[^" org-non-link-chars " ]\\)>?")
5163 org-link-re-with-space3
5164 (concat
5165 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5166 "\\([^" org-non-link-chars " ]"
5167 "[^\t\n\r]*\\)")
5168 org-angle-link-re
5169 (concat
5170 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5171 "\\([^" org-non-link-chars " ]"
5172 "[^" org-non-link-chars "]*"
5173 "\\)>")
5174 org-plain-link-re
5175 (concat
5176 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5177 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5178 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5179 org-bracket-link-regexp
5180 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5181 org-bracket-link-analytic-regexp
5182 (concat
5183 "\\[\\["
5184 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5185 "\\([^]]+\\)"
5186 "\\]"
5187 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5188 "\\]")
5189 org-bracket-link-analytic-regexp++
5190 (concat
5191 "\\[\\["
5192 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5193 "\\([^]]+\\)"
5194 "\\]"
5195 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5196 "\\]")
5197 org-any-link-re
5198 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5199 org-angle-link-re "\\)\\|\\("
5200 org-plain-link-re "\\)")))
5202 (org-make-link-regexps)
5204 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5205 "Regular expression for fast time stamp matching.")
5206 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5207 "Regular expression for fast time stamp matching.")
5208 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5209 "Regular expression matching time strings for analysis.
5210 This one does not require the space after the date, so it can be used
5211 on a string that terminates immediately after the date.")
5212 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5213 "Regular expression matching time strings for analysis.")
5214 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5215 "Regular expression matching time stamps, with groups.")
5216 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5217 "Regular expression matching time stamps (also [..]), with groups.")
5218 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5219 "Regular expression matching a time stamp range.")
5220 (defconst org-tr-regexp-both
5221 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5222 "Regular expression matching a time stamp range.")
5223 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5224 org-ts-regexp "\\)?")
5225 "Regular expression matching a time stamp or time stamp range.")
5226 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5227 org-ts-regexp-both "\\)?")
5228 "Regular expression matching a time stamp or time stamp range.
5229 The time stamps may be either active or inactive.")
5231 (defvar org-emph-face nil)
5233 (defun org-do-emphasis-faces (limit)
5234 "Run through the buffer and add overlays to emphasised strings."
5235 (let (rtn a)
5236 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5237 (if (not (= (char-after (match-beginning 3))
5238 (char-after (match-beginning 4))))
5239 (progn
5240 (setq rtn t)
5241 (setq a (assoc (match-string 3) org-emphasis-alist))
5242 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5243 'face
5244 (nth 1 a))
5245 (and (nth 4 a)
5246 (org-remove-flyspell-overlays-in
5247 (match-beginning 0) (match-end 0)))
5248 (add-text-properties (match-beginning 2) (match-end 2)
5249 '(font-lock-multiline t org-emphasis t))
5250 (when org-hide-emphasis-markers
5251 (add-text-properties (match-end 4) (match-beginning 5)
5252 '(invisible org-link))
5253 (add-text-properties (match-beginning 3) (match-end 3)
5254 '(invisible org-link)))))
5255 (backward-char 1))
5256 rtn))
5258 (defun org-emphasize (&optional char)
5259 "Insert or change an emphasis, i.e. a font like bold or italic.
5260 If there is an active region, change that region to a new emphasis.
5261 If there is no region, just insert the marker characters and position
5262 the cursor between them.
5263 CHAR should be either the marker character, or the first character of the
5264 HTML tag associated with that emphasis. If CHAR is a space, the means
5265 to remove the emphasis of the selected region.
5266 If char is not given (for example in an interactive call) it
5267 will be prompted for."
5268 (interactive)
5269 (let ((eal org-emphasis-alist) e det
5270 (erc org-emphasis-regexp-components)
5271 (prompt "")
5272 (string "") beg end move tag c s)
5273 (if (org-region-active-p)
5274 (setq beg (region-beginning) end (region-end)
5275 string (buffer-substring beg end))
5276 (setq move t))
5278 (while (setq e (pop eal))
5279 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5280 c (aref tag 0))
5281 (push (cons c (string-to-char (car e))) det)
5282 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5283 (substring tag 1)))))
5284 (setq det (nreverse det))
5285 (unless char
5286 (message "%s" (concat "Emphasis marker or tag:" prompt))
5287 (setq char (read-char-exclusive)))
5288 (setq char (or (cdr (assoc char det)) char))
5289 (if (equal char ?\ )
5290 (setq s "" move nil)
5291 (unless (assoc (char-to-string char) org-emphasis-alist)
5292 (error "No such emphasis marker: \"%c\"" char))
5293 (setq s (char-to-string char)))
5294 (while (and (> (length string) 1)
5295 (equal (substring string 0 1) (substring string -1))
5296 (assoc (substring string 0 1) org-emphasis-alist))
5297 (setq string (substring string 1 -1)))
5298 (setq string (concat s string s))
5299 (if beg (delete-region beg end))
5300 (unless (or (bolp)
5301 (string-match (concat "[" (nth 0 erc) "\n]")
5302 (char-to-string (char-before (point)))))
5303 (insert " "))
5304 (unless (or (eobp)
5305 (string-match (concat "[" (nth 1 erc) "\n]")
5306 (char-to-string (char-after (point)))))
5307 (insert " ") (backward-char 1))
5308 (insert string)
5309 (and move (backward-char 1))))
5311 (defconst org-nonsticky-props
5312 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
5314 (defsubst org-rear-nonsticky-at (pos)
5315 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5317 (defun org-activate-plain-links (limit)
5318 "Run through the buffer and add overlays to links."
5319 (catch 'exit
5320 (let (f)
5321 (if (re-search-forward org-plain-link-re limit t)
5322 (progn
5323 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5324 (setq f (get-text-property (match-beginning 0) 'face))
5325 (if (or (eq f 'org-tag)
5326 (and (listp f) (memq 'org-tag f)))
5328 (add-text-properties (match-beginning 0) (match-end 0)
5329 (list 'mouse-face 'highlight
5330 'face 'org-link
5331 'keymap org-mouse-map))
5332 (org-rear-nonsticky-at (match-end 0)))
5333 t)))))
5335 (defun org-activate-code (limit)
5336 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5337 (progn
5338 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5339 (remove-text-properties (match-beginning 0) (match-end 0)
5340 '(display t invisible t intangible t))
5341 t)))
5343 (defcustom org-src-fontify-natively nil
5344 "When non-nil, fontify code in code blocks."
5345 :type 'boolean
5346 :group 'org-appearance
5347 :group 'org-babel)
5349 (defun org-fontify-meta-lines-and-blocks (limit)
5350 (condition-case nil
5351 (org-fontify-meta-lines-and-blocks-1 limit)
5352 (error (message "org-mode fontification error"))))
5354 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5355 "Fontify #+ lines and blocks, in the correct ways."
5356 (let ((case-fold-search t))
5357 (if (re-search-forward
5358 "^\\([ \t]*#\\+\\(\\([a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5359 limit t)
5360 (let ((beg (match-beginning 0))
5361 (block-start (match-end 0))
5362 (block-end nil)
5363 (lang (match-string 7))
5364 (beg1 (line-beginning-position 2))
5365 (dc1 (downcase (match-string 2)))
5366 (dc3 (downcase (match-string 3)))
5367 end end1 quoting block-type ovl)
5368 (cond
5369 ((member dc1 '("html:" "ascii:" "latex:" "docbook:"))
5370 ;; a single line of backend-specific content
5371 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5372 (remove-text-properties (match-beginning 0) (match-end 0)
5373 '(display t invisible t intangible t))
5374 (add-text-properties (match-beginning 1) (match-end 3)
5375 '(font-lock-fontified t face org-meta-line))
5376 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5377 '(font-lock-fontified t face org-block))
5378 ; for backend-specific code
5380 ((and (match-end 4) (equal dc3 "begin"))
5381 ;; Truly a block
5382 (setq block-type (downcase (match-string 5))
5383 quoting (member block-type org-protecting-blocks))
5384 (when (re-search-forward
5385 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5386 nil t) ;; on purpose, we look further than LIMIT
5387 (setq end (match-end 0) end1 (1- (match-beginning 0)))
5388 (setq block-end (match-beginning 0))
5389 (when quoting
5390 (remove-text-properties beg end
5391 '(display t invisible t intangible t)))
5392 (add-text-properties
5393 beg end
5394 '(font-lock-fontified t font-lock-multiline t))
5395 (add-text-properties beg beg1 '(face org-meta-line))
5396 (add-text-properties end1 (min (point-max) (1+ end))
5397 '(face org-meta-line)) ; for end_src
5398 (cond
5399 ((and lang (not (string= lang "")) org-src-fontify-natively)
5400 (org-src-font-lock-fontify-block lang block-start block-end)
5401 ;; remove old background overlays
5402 (mapc (lambda (ov)
5403 (if (eq (overlay-get ov 'face) 'org-block-background)
5404 (delete-overlay ov)))
5405 (overlays-at (/ (+ beg1 block-end) 2)))
5406 ;; add a background overlay
5407 (setq ovl (make-overlay beg1 block-end))
5408 (overlay-put ovl 'face 'org-block-background)
5409 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5410 (quoting
5411 (add-text-properties beg1 (min (point-max) (1+ end1))
5412 '(face org-block))) ; end of source block
5413 ((not org-fontify-quote-and-verse-blocks))
5414 ((string= block-type "quote")
5415 (add-text-properties beg1 (1+ end1) '(face org-quote)))
5416 ((string= block-type "verse")
5417 (add-text-properties beg1 (1+ end1) '(face org-verse))))
5418 (add-text-properties beg beg1 '(face org-block-begin-line))
5419 (add-text-properties (1+ end) (1+ end1) '(face org-block-end-line))
5421 ((member dc1 '("title:" "author:" "email:" "date:"))
5422 (add-text-properties
5423 beg (match-end 3)
5424 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5425 '(font-lock-fontified t invisible t)
5426 '(font-lock-fontified t face org-document-info-keyword)))
5427 (add-text-properties
5428 (match-beginning 6) (match-end 6)
5429 (if (string-equal dc1 "title:")
5430 '(font-lock-fontified t face org-document-title)
5431 '(font-lock-fontified t face org-document-info))))
5432 ((not (member (char-after beg) '(?\ ?\t)))
5433 ;; just any other in-buffer setting, but not indented
5434 (add-text-properties
5435 beg (1+ (match-end 0))
5436 '(font-lock-fontified t face org-meta-line))
5438 ((or (member dc1 '("begin:" "end:" "caption:" "label:"
5439 "orgtbl:" "tblfm:" "tblname:" "results:"
5440 "call:" "header:" "headers:"))
5441 (and (match-end 4) (equal dc3 "attr")))
5442 (add-text-properties
5443 beg (match-end 0)
5444 '(font-lock-fontified t face org-meta-line))
5446 ((member dc3 '(" " ""))
5447 (add-text-properties
5448 beg (match-end 0)
5449 '(font-lock-fontified t face font-lock-comment-face)))
5450 (t nil))))))
5452 (defun org-activate-angle-links (limit)
5453 "Run through the buffer and add overlays to links."
5454 (if (re-search-forward org-angle-link-re limit t)
5455 (progn
5456 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5457 (add-text-properties (match-beginning 0) (match-end 0)
5458 (list 'mouse-face 'highlight
5459 'keymap org-mouse-map))
5460 (org-rear-nonsticky-at (match-end 0))
5461 t)))
5463 (defun org-activate-footnote-links (limit)
5464 "Run through the buffer and add overlays to footnotes."
5465 (let ((fn (org-footnote-next-reference-or-definition limit)))
5466 (when fn
5467 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5468 (org-remove-flyspell-overlays-in beg end)
5469 (add-text-properties beg end
5470 (list 'mouse-face 'highlight
5471 'keymap org-mouse-map
5472 'help-echo
5473 (if (= (point-at-bol) beg)
5474 "Footnote definition"
5475 "Footnote reference")
5476 'font-lock-fontified t
5477 'font-lock-multiline t
5478 'face 'org-footnote))))))
5480 (defun org-activate-bracket-links (limit)
5481 "Run through the buffer and add overlays to bracketed links."
5482 (if (re-search-forward org-bracket-link-regexp limit t)
5483 (let* ((help (concat "LINK: "
5484 (org-match-string-no-properties 1)))
5485 ;; FIXME: above we should remove the escapes.
5486 ;; but that requires another match, protecting match data,
5487 ;; a lot of overhead for font-lock.
5488 (ip (org-maybe-intangible
5489 (list 'invisible 'org-link
5490 'keymap org-mouse-map 'mouse-face 'highlight
5491 'font-lock-multiline t 'help-echo help)))
5492 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5493 'font-lock-multiline t 'help-echo help)))
5494 ;; We need to remove the invisible property here. Table narrowing
5495 ;; may have made some of this invisible.
5496 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5497 (remove-text-properties (match-beginning 0) (match-end 0)
5498 '(invisible nil))
5499 (if (match-end 3)
5500 (progn
5501 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5502 (org-rear-nonsticky-at (match-beginning 3))
5503 (add-text-properties (match-beginning 3) (match-end 3) vp)
5504 (org-rear-nonsticky-at (match-end 3))
5505 (add-text-properties (match-end 3) (match-end 0) ip)
5506 (org-rear-nonsticky-at (match-end 0)))
5507 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5508 (org-rear-nonsticky-at (match-beginning 1))
5509 (add-text-properties (match-beginning 1) (match-end 1) vp)
5510 (org-rear-nonsticky-at (match-end 1))
5511 (add-text-properties (match-end 1) (match-end 0) ip)
5512 (org-rear-nonsticky-at (match-end 0)))
5513 t)))
5515 (defun org-activate-dates (limit)
5516 "Run through the buffer and add overlays to dates."
5517 (if (re-search-forward org-tsr-regexp-both limit t)
5518 (progn
5519 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5520 (add-text-properties (match-beginning 0) (match-end 0)
5521 (list 'mouse-face 'highlight
5522 'keymap org-mouse-map))
5523 (org-rear-nonsticky-at (match-end 0))
5524 (when org-display-custom-times
5525 (if (match-end 3)
5526 (org-display-custom-time (match-beginning 3) (match-end 3)))
5527 (org-display-custom-time (match-beginning 1) (match-end 1)))
5528 t)))
5530 (defvar org-target-link-regexp nil
5531 "Regular expression matching radio targets in plain text.")
5532 (make-variable-buffer-local 'org-target-link-regexp)
5533 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5534 "Regular expression matching a link target.")
5535 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5536 "Regular expression matching a radio target.")
5537 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5538 "Regular expression matching any target.")
5540 (defun org-activate-target-links (limit)
5541 "Run through the buffer and add overlays to target matches."
5542 (when org-target-link-regexp
5543 (let ((case-fold-search t))
5544 (if (re-search-forward org-target-link-regexp limit t)
5545 (progn
5546 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5547 (add-text-properties (match-beginning 0) (match-end 0)
5548 (list 'mouse-face 'highlight
5549 'keymap org-mouse-map
5550 'help-echo "Radio target link"
5551 'org-linked-text t))
5552 (org-rear-nonsticky-at (match-end 0))
5553 t)))))
5555 (defun org-update-radio-target-regexp ()
5556 "Find all radio targets in this file and update the regular expression."
5557 (interactive)
5558 (when (memq 'radio org-activate-links)
5559 (setq org-target-link-regexp
5560 (org-make-target-link-regexp (org-all-targets 'radio)))
5561 (org-restart-font-lock)))
5563 (defun org-hide-wide-columns (limit)
5564 (let (s e)
5565 (setq s (text-property-any (point) (or limit (point-max))
5566 'org-cwidth t))
5567 (when s
5568 (setq e (next-single-property-change s 'org-cwidth))
5569 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5570 (goto-char e)
5571 t)))
5573 (defvar org-latex-and-specials-regexp nil
5574 "Regular expression for highlighting export special stuff.")
5575 (defvar org-match-substring-regexp)
5576 (defvar org-match-substring-with-braces-regexp)
5578 ;; This should be with the exporter code, but we also use if for font-locking
5579 (defconst org-export-html-special-string-regexps
5580 '(("\\\\-" . "&shy;")
5581 ("---\\([^-]\\)" . "&mdash;\\1")
5582 ("--\\([^-]\\)" . "&ndash;\\1")
5583 ("\\.\\.\\." . "&hellip;"))
5584 "Regular expressions for special string conversion.")
5587 (defun org-compute-latex-and-specials-regexp ()
5588 "Compute regular expression for stuff treated specially by exporters."
5589 (if (not org-highlight-latex-fragments-and-specials)
5590 (org-set-local 'org-latex-and-specials-regexp nil)
5591 (require 'org-exp)
5592 (let*
5593 ((matchers (plist-get org-format-latex-options :matchers))
5594 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5595 org-latex-regexps)))
5596 (org-export-allow-BIND nil)
5597 (options (org-combine-plists (org-default-export-plist)
5598 (org-infile-export-plist)))
5599 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5600 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5601 (org-export-with-TeX-macros (plist-get options :TeX-macros))
5602 (org-export-html-expand (plist-get options :expand-quoted-html))
5603 (org-export-with-special-strings (plist-get options :special-strings))
5604 (re-sub
5605 (cond
5606 ((equal org-export-with-sub-superscripts '{})
5607 (list org-match-substring-with-braces-regexp))
5608 (org-export-with-sub-superscripts
5609 (list org-match-substring-regexp))
5610 (t nil)))
5611 (re-latex
5612 (if org-export-with-LaTeX-fragments
5613 (mapcar (lambda (x) (nth 1 x)) latexs)))
5614 (re-macros
5615 (if org-export-with-TeX-macros
5616 (list (concat "\\\\"
5617 (regexp-opt
5618 (append
5620 (delq nil
5621 (mapcar 'car-safe
5622 (append org-entities-user
5623 org-entities)))
5624 (if (boundp 'org-latex-entities)
5625 (mapcar (lambda (x)
5626 (or (car-safe x) x))
5627 org-latex-entities)
5628 nil))
5629 'words))) ; FIXME
5631 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5632 (re-special (if org-export-with-special-strings
5633 (mapcar (lambda (x) (car x))
5634 org-export-html-special-string-regexps)))
5635 (re-rest
5636 (delq nil
5637 (list
5638 (if org-export-html-expand "@<[^>\n]+>")
5639 ))))
5640 (org-set-local
5641 'org-latex-and-specials-regexp
5642 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5643 re-rest) "\\|")))))
5645 (defun org-do-latex-and-special-faces (limit)
5646 "Run through the buffer and add overlays to links."
5647 (when org-latex-and-specials-regexp
5648 (let (rtn d)
5649 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5650 limit t))
5651 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5652 'face))
5653 '(org-code org-verbatim underline)))
5654 (progn
5655 (setq rtn t
5656 d (cond ((member (char-after (1+ (match-beginning 0)))
5657 '(?_ ?^)) 1)
5658 (t 0)))
5659 (font-lock-prepend-text-property
5660 (+ d (match-beginning 0)) (match-end 0)
5661 'face 'org-latex-and-export-specials)
5662 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5663 '(font-lock-multiline t)))))
5664 rtn)))
5666 (defun org-restart-font-lock ()
5667 "Restart `font-lock-mode', to force refontification."
5668 (when (and (boundp 'font-lock-mode) font-lock-mode)
5669 (font-lock-mode -1)
5670 (font-lock-mode 1)))
5672 (defun org-all-targets (&optional radio)
5673 "Return a list of all targets in this file.
5674 With optional argument RADIO, only find radio targets."
5675 (let ((re (if radio org-radio-target-regexp org-target-regexp))
5676 rtn)
5677 (save-excursion
5678 (goto-char (point-min))
5679 (while (re-search-forward re nil t)
5680 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
5681 rtn)))
5683 (defun org-make-target-link-regexp (targets)
5684 "Make regular expression matching all strings in TARGETS.
5685 The regular expression finds the targets also if there is a line break
5686 between words."
5687 (and targets
5688 (concat
5689 "\\<\\("
5690 (mapconcat
5691 (lambda (x)
5692 (setq x (regexp-quote x))
5693 (while (string-match " +" x)
5694 (setq x (replace-match "\\s-+" t t x)))
5696 targets
5697 "\\|")
5698 "\\)\\>")))
5700 (defun org-activate-tags (limit)
5701 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
5702 (progn
5703 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5704 (add-text-properties (match-beginning 1) (match-end 1)
5705 (list 'mouse-face 'highlight
5706 'keymap org-mouse-map))
5707 (org-rear-nonsticky-at (match-end 1))
5708 t)))
5710 (defun org-outline-level ()
5711 "Compute the outline level of the heading at point.
5712 This function assumes that the cursor is at the beginning of a line matched
5713 by `outline-regexp'. Otherwise it returns garbage.
5714 If this is called at a normal headline, the level is the number of stars.
5715 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
5716 (save-excursion
5717 (looking-at org-outline-regexp)
5718 (1- (- (match-end 0) (match-beginning 0)))))
5720 (defvar org-font-lock-keywords nil)
5722 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
5723 "Regular expression matching a property line.")
5725 (defvar org-font-lock-hook nil
5726 "Functions to be called for special font lock stuff.")
5728 (defvar org-font-lock-set-keywords-hook nil
5729 "Functions that can manipulate `org-font-lock-extra-keywords'.
5730 This is calles after `org-font-lock-extra-keywords' is defined, but before
5731 it is installed to be used by font lock. This can be useful if something
5732 needs to be inserted at a specific position in the font-lock sequence.")
5734 (defun org-font-lock-hook (limit)
5735 (run-hook-with-args 'org-font-lock-hook limit))
5737 (defun org-set-font-lock-defaults ()
5738 (let* ((em org-fontify-emphasized-text)
5739 (lk org-activate-links)
5740 (org-font-lock-extra-keywords
5741 (list
5742 ;; Call the hook
5743 '(org-font-lock-hook)
5744 ;; Headlines
5745 `(,(if org-fontify-whole-heading-line
5746 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
5747 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
5748 (1 (org-get-level-face 1))
5749 (2 (org-get-level-face 2))
5750 (3 (org-get-level-face 3)))
5751 ;; Table lines
5752 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5753 (1 'org-table t))
5754 ;; Table internals
5755 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5756 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5757 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5758 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
5759 ;; Drawers
5760 (list org-drawer-regexp '(0 'org-special-keyword t))
5761 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5762 ;; Properties
5763 (list org-property-re
5764 '(1 'org-special-keyword t)
5765 '(3 'org-property-value t))
5766 ;; Links
5767 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5768 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5769 (if (memq 'plain lk) '(org-activate-plain-links))
5770 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5771 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5772 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5773 (if (memq 'footnote lk) '(org-activate-footnote-links))
5774 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5775 '(org-hide-wide-columns (0 nil append))
5776 ;; TODO keyword
5777 (list (format org-heading-keyword-regexp-format
5778 org-todo-regexp)
5779 '(2 (org-get-todo-face 2) t))
5780 ;; DONE
5781 (if org-fontify-done-headline
5782 (list (format org-heading-keyword-regexp-format
5783 (concat
5784 "\\("
5785 (mapconcat 'regexp-quote org-done-keywords "\\|")
5786 "\\)"))
5787 '(2 'org-headline-done t))
5788 nil)
5789 ;; Priorities
5790 '(org-font-lock-add-priority-faces)
5791 ;; Tags
5792 '(org-font-lock-add-tag-faces)
5793 ;; Special keywords
5794 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5795 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5796 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5797 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5798 ;; Emphasis
5799 (if em
5800 (if (featurep 'xemacs)
5801 '(org-do-emphasis-faces (0 nil append))
5802 '(org-do-emphasis-faces)))
5803 ;; Checkboxes
5804 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
5805 1 'org-checkbox prepend)
5806 (if (cdr (assq 'checkbox org-list-automatic-rules))
5807 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5808 (0 (org-get-checkbox-statistics-face) t)))
5809 ;; Description list items
5810 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
5811 1 'bold prepend)
5812 ;; ARCHIVEd headings
5813 (list (concat
5814 org-outline-regexp-bol
5815 "\\(.*:" org-archive-tag ":.*\\)")
5816 '(1 'org-archived prepend))
5817 ;; Specials
5818 '(org-do-latex-and-special-faces)
5819 '(org-fontify-entities)
5820 '(org-raise-scripts)
5821 ;; Code
5822 '(org-activate-code (1 'org-code t))
5823 ;; COMMENT
5824 (list (format org-heading-keyword-regexp-format
5825 (concat "\\("
5826 org-comment-string "\\|" org-quote-string
5827 "\\)"))
5828 '(2 'org-special-keyword t))
5829 '("^#.*" (0 'font-lock-comment-face t))
5830 ;; Blocks and meta lines
5831 '(org-fontify-meta-lines-and-blocks)
5833 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5834 (run-hooks 'org-font-lock-set-keywords-hook)
5835 ;; Now set the full font-lock-keywords
5836 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5837 (org-set-local 'font-lock-defaults
5838 '(org-font-lock-keywords t nil nil backward-paragraph))
5839 (kill-local-variable 'font-lock-keywords) nil))
5841 (defun org-toggle-pretty-entities ()
5842 "Toggle the composition display of entities as UTF8 characters."
5843 (interactive)
5844 (org-set-local 'org-pretty-entities (not org-pretty-entities))
5845 (org-restart-font-lock)
5846 (if org-pretty-entities
5847 (message "Entities are displayed as UTF8 characers")
5848 (save-restriction
5849 (widen)
5850 (org-decompose-region (point-min) (point-max))
5851 (message "Entities are displayed plain"))))
5853 (defun org-fontify-entities (limit)
5854 "Find an entity to fontify."
5855 (let (ee)
5856 (when org-pretty-entities
5857 (catch 'match
5858 (while (re-search-forward
5859 "\\\\\\(frac[13][24]\\|[a-zA-Z]+\\)\\($\\|[^[:alpha:]\n]\\)"
5860 limit t)
5861 (if (and (not (org-in-indented-comment-line))
5862 (setq ee (org-entity-get (match-string 1)))
5863 (= (length (nth 6 ee)) 1))
5864 (progn
5865 (add-text-properties
5866 (match-beginning 0) (match-end 1)
5867 (list 'font-lock-fontified t))
5868 (compose-region (match-beginning 0) (match-end 1)
5869 (nth 6 ee) nil)
5870 (backward-char 1)
5871 (throw 'match t))))
5872 nil))))
5874 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
5875 "Fontify string S like in Org-mode."
5876 (with-temp-buffer
5877 (insert s)
5878 (let ((org-odd-levels-only odd-levels))
5879 (org-mode)
5880 (font-lock-fontify-buffer)
5881 (buffer-string))))
5883 (defvar org-m nil)
5884 (defvar org-l nil)
5885 (defvar org-f nil)
5886 (defun org-get-level-face (n)
5887 "Get the right face for match N in font-lock matching of headlines."
5888 (setq org-l (- (match-end 2) (match-beginning 1) 1))
5889 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
5890 (if org-cycle-level-faces
5891 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
5892 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
5893 (cond
5894 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
5895 ((eq n 2) org-f)
5896 (t (if org-level-color-stars-only nil org-f))))
5899 (defun org-get-todo-face (kwd)
5900 "Get the right face for a TODO keyword KWD.
5901 If KWD is a number, get the corresponding match group."
5902 (if (numberp kwd) (setq kwd (match-string kwd)))
5903 (or (org-face-from-face-or-color
5904 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
5905 (and (member kwd org-done-keywords) 'org-done)
5906 'org-todo))
5908 (defun org-face-from-face-or-color (context inherit face-or-color)
5909 "Create a face list that inherits INHERIT, but sets the foreground color.
5910 When FACE-OR-COLOR is not a string, just return it."
5911 (if (stringp face-or-color)
5912 (list :inherit inherit
5913 (cdr (assoc context org-faces-easy-properties))
5914 face-or-color)
5915 face-or-color))
5917 (defun org-font-lock-add-tag-faces (limit)
5918 "Add the special tag faces."
5919 (when (and org-tag-faces org-tags-special-faces-re)
5920 (while (re-search-forward org-tags-special-faces-re limit t)
5921 (add-text-properties (match-beginning 1) (match-end 1)
5922 (list 'face (org-get-tag-face 1)
5923 'font-lock-fontified t))
5924 (backward-char 1))))
5926 (defun org-font-lock-add-priority-faces (limit)
5927 "Add the special priority faces."
5928 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
5929 (add-text-properties
5930 (match-beginning 0) (match-end 0)
5931 (list 'face (or (org-face-from-face-or-color
5932 'priority 'org-special-keyword
5933 (cdr (assoc (char-after (match-beginning 1))
5934 org-priority-faces)))
5935 'org-special-keyword)
5936 'font-lock-fontified t))))
5938 (defun org-get-tag-face (kwd)
5939 "Get the right face for a TODO keyword KWD.
5940 If KWD is a number, get the corresponding match group."
5941 (if (numberp kwd) (setq kwd (match-string kwd)))
5942 (or (org-face-from-face-or-color
5943 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
5944 'org-tag))
5946 (defun org-unfontify-region (beg end &optional maybe_loudly)
5947 "Remove fontification and activation overlays from links."
5948 (font-lock-default-unfontify-region beg end)
5949 (let* ((buffer-undo-list t)
5950 (inhibit-read-only t) (inhibit-point-motion-hooks t)
5951 (inhibit-modification-hooks t)
5952 deactivate-mark buffer-file-name buffer-file-truename)
5953 (org-decompose-region beg end)
5954 (remove-text-properties beg end
5955 '(mouse-face t keymap t org-linked-text t
5956 invisible t intangible t
5957 org-no-flyspell t org-emphasis t))
5958 (org-remove-font-lock-display-properties beg end)))
5960 (defconst org-script-display '(((raise -0.3) (height 0.7))
5961 ((raise 0.3) (height 0.7))
5962 ((raise -0.5))
5963 ((raise 0.5)))
5964 "Display properties for showing superscripts and subscripts.")
5966 (defun org-remove-font-lock-display-properties (beg end)
5967 "Remove specific display properties that have been added by font lock.
5968 The will remove the raise properties that are used to show superscripts
5969 and subscripts."
5970 (let (next prop)
5971 (while (< beg end)
5972 (setq next (next-single-property-change beg 'display nil end)
5973 prop (get-text-property beg 'display))
5974 (if (member prop org-script-display)
5975 (put-text-property beg next 'display nil))
5976 (setq beg next))))
5978 (defun org-raise-scripts (limit)
5979 "Add raise properties to sub/superscripts."
5980 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
5981 (if (re-search-forward
5982 (if (eq org-use-sub-superscripts t)
5983 org-match-substring-regexp
5984 org-match-substring-with-braces-regexp)
5985 limit t)
5986 (let* ((pos (point)) table-p comment-p
5987 (mpos (match-beginning 3))
5988 (emph-p (get-text-property mpos 'org-emphasis))
5989 (link-p (get-text-property mpos 'mouse-face))
5990 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
5991 (goto-char (point-at-bol))
5992 (setq table-p (org-looking-at-p org-table-dataline-regexp)
5993 comment-p (org-looking-at-p "[ \t]*#"))
5994 (goto-char pos)
5995 ;; FIXME: Should we go back one character here, for a_b^c
5996 ;; (goto-char (1- pos)) ;????????????????????
5997 (if (or comment-p emph-p link-p keyw-p)
5999 (put-text-property (match-beginning 3) (match-end 0)
6000 'display
6001 (if (equal (char-after (match-beginning 2)) ?^)
6002 (nth (if table-p 3 1) org-script-display)
6003 (nth (if table-p 2 0) org-script-display)))
6004 (add-text-properties (match-beginning 2) (match-end 2)
6005 (list 'invisible t
6006 'org-dwidth t 'org-dwidth-n 1))
6007 (if (and (eq (char-after (match-beginning 3)) ?{)
6008 (eq (char-before (match-end 3)) ?}))
6009 (progn
6010 (add-text-properties
6011 (match-beginning 3) (1+ (match-beginning 3))
6012 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6013 (add-text-properties
6014 (1- (match-end 3)) (match-end 3)
6015 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6016 t)))))
6018 ;;;; Visibility cycling, including org-goto and indirect buffer
6020 ;;; Cycling
6022 (defvar org-cycle-global-status nil)
6023 (make-variable-buffer-local 'org-cycle-global-status)
6024 (defvar org-cycle-subtree-status nil)
6025 (make-variable-buffer-local 'org-cycle-subtree-status)
6027 ;;;###autoload
6029 (defvar org-inlinetask-min-level)
6031 (defun org-cycle (&optional arg)
6032 "TAB-action and visibility cycling for Org-mode.
6034 This is the command invoked in Org-mode by the TAB key. Its main purpose
6035 is outline visibility cycling, but it also invokes other actions
6036 in special contexts.
6038 - When this function is called with a prefix argument, rotate the entire
6039 buffer through 3 states (global cycling)
6040 1. OVERVIEW: Show only top-level headlines.
6041 2. CONTENTS: Show all headlines of all levels, but no body text.
6042 3. SHOW ALL: Show everything.
6043 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6044 determined by the variable `org-startup-folded', and by any VISIBILITY
6045 properties in the buffer.
6046 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6047 including any drawers.
6049 - When inside a table, re-align the table and move to the next field.
6051 - When point is at the beginning of a headline, rotate the subtree started
6052 by this line through 3 different states (local cycling)
6053 1. FOLDED: Only the main headline is shown.
6054 2. CHILDREN: The main headline and the direct children are shown.
6055 From this state, you can move to one of the children
6056 and zoom in further.
6057 3. SUBTREE: Show the entire subtree, including body text.
6058 If there is no subtree, switch directly from CHILDREN to FOLDED.
6060 - When point is at the beginning of an empty headline and the variable
6061 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6062 of the headline by demoting and promoting it to likely levels. This
6063 speeds up creation document structure by pressing TAB once or several
6064 times right after creating a new headline.
6066 - When there is a numeric prefix, go up to a heading with level ARG, do
6067 a `show-subtree' and return to the previous cursor position. If ARG
6068 is negative, go up that many levels.
6070 - When point is not at the beginning of a headline, execute the global
6071 binding for TAB, which is re-indenting the line. See the option
6072 `org-cycle-emulate-tab' for details.
6074 - Special case: if point is at the beginning of the buffer and there is
6075 no headline in line 1, this function will act as if called with prefix arg
6076 (C-u TAB, same as S-TAB) also when called without prefix arg.
6077 But only if also the variable `org-cycle-global-at-bob' is t."
6078 (interactive "P")
6079 (org-load-modules-maybe)
6080 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6081 (and org-cycle-level-after-item/entry-creation
6082 (or (org-cycle-level)
6083 (org-cycle-item-indentation))))
6084 (let* ((limit-level
6085 (or org-cycle-max-level
6086 (and (boundp 'org-inlinetask-min-level)
6087 org-inlinetask-min-level
6088 (1- org-inlinetask-min-level))))
6089 (nstars (and limit-level
6090 (if org-odd-levels-only
6091 (and limit-level (1- (* limit-level 2)))
6092 limit-level)))
6093 (org-outline-regexp
6094 (if (not (eq major-mode 'org-mode))
6095 outline-regexp
6096 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6097 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6098 (not (looking-at org-outline-regexp))))
6099 (org-cycle-hook
6100 (if bob-special
6101 (delq 'org-optimize-window-after-visibility-change
6102 (copy-sequence org-cycle-hook))
6103 org-cycle-hook))
6104 (pos (point)))
6106 (if (or bob-special (equal arg '(4)))
6107 ;; special case: use global cycling
6108 (setq arg t))
6110 (cond
6112 ((equal arg '(16))
6113 (setq last-command 'dummy)
6114 (org-set-startup-visibility)
6115 (message "Startup visibility, plus VISIBILITY properties"))
6117 ((equal arg '(64))
6118 (show-all)
6119 (message "Entire buffer visible, including drawers"))
6121 ;; Table: enter it or move to the next field.
6122 ((org-at-table-p 'any)
6123 (if (org-at-table.el-p)
6124 (message "Use C-c ' to edit table.el tables")
6125 (if arg (org-table-edit-field t)
6126 (org-table-justify-field-maybe)
6127 (call-interactively 'org-table-next-field))))
6129 ((run-hook-with-args-until-success
6130 'org-tab-after-check-for-table-hook))
6132 ;; Global cycling: delegate to `org-cycle-internal-global'.
6133 ((eq arg t) (org-cycle-internal-global))
6135 ;; Drawers: delegate to `org-flag-drawer'.
6136 ((and org-drawers org-drawer-regexp
6137 (save-excursion
6138 (beginning-of-line 1)
6139 (looking-at org-drawer-regexp)))
6140 (org-flag-drawer ; toggle block visibility
6141 (not (get-char-property (match-end 0) 'invisible))))
6143 ;; Show-subtree, ARG levels up from here.
6144 ((integerp arg)
6145 (save-excursion
6146 (org-back-to-heading)
6147 (outline-up-heading (if (< arg 0) (- arg)
6148 (- (funcall outline-level) arg)))
6149 (org-show-subtree)))
6151 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6152 ((and (featurep 'org-inlinetask)
6153 (org-inlinetask-at-task-p)
6154 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6155 (org-inlinetask-toggle-visibility))
6157 ((org-try-cdlatex-tab))
6159 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6160 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6161 (save-excursion (beginning-of-line 1)
6162 (looking-at org-outline-regexp)))
6163 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6164 (org-cycle-internal-local))
6166 ;; From there: TAB emulation and template completion.
6167 (buffer-read-only (org-back-to-heading))
6169 ((run-hook-with-args-until-success
6170 'org-tab-after-check-for-cycling-hook))
6172 ((org-try-structure-completion))
6174 ((run-hook-with-args-until-success
6175 'org-tab-before-tab-emulation-hook))
6177 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6178 (or (not (bolp))
6179 (not (looking-at org-outline-regexp))))
6180 (call-interactively (global-key-binding "\t")))
6182 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6183 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6184 (or (and (eq org-cycle-emulate-tab 'white)
6185 (= (match-end 0) (point-at-eol)))
6186 (and (eq org-cycle-emulate-tab 'whitestart)
6187 (>= (match-end 0) pos))))
6189 (eq org-cycle-emulate-tab t))
6190 (call-interactively (global-key-binding "\t")))
6192 (t (save-excursion
6193 (org-back-to-heading)
6194 (org-cycle)))))))
6196 (defun org-cycle-internal-global ()
6197 "Do the global cycling action."
6198 (cond
6199 ((and (eq last-command this-command)
6200 (eq org-cycle-global-status 'overview))
6201 ;; We just created the overview - now do table of contents
6202 ;; This can be slow in very large buffers, so indicate action
6203 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6204 (message "CONTENTS...")
6205 (org-content)
6206 (message "CONTENTS...done")
6207 (setq org-cycle-global-status 'contents)
6208 (run-hook-with-args 'org-cycle-hook 'contents))
6210 ((and (eq last-command this-command)
6211 (eq org-cycle-global-status 'contents))
6212 ;; We just showed the table of contents - now show everything
6213 (run-hook-with-args 'org-pre-cycle-hook 'all)
6214 (show-all)
6215 (message "SHOW ALL")
6216 (setq org-cycle-global-status 'all)
6217 (run-hook-with-args 'org-cycle-hook 'all))
6220 ;; Default action: go to overview
6221 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6222 (org-overview)
6223 (message "OVERVIEW")
6224 (setq org-cycle-global-status 'overview)
6225 (run-hook-with-args 'org-cycle-hook 'overview))))
6227 (defun org-cycle-internal-local ()
6228 "Do the local cycling action."
6229 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6230 ;; First, determine end of headline (EOH), end of subtree or item
6231 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6232 (save-excursion
6233 (if (org-at-item-p)
6234 (progn
6235 (beginning-of-line)
6236 (setq struct (org-list-struct))
6237 (setq eoh (point-at-eol))
6238 (setq eos (org-list-get-item-end-before-blank (point) struct))
6239 (setq has-children (org-list-has-child-p (point) struct)))
6240 (org-back-to-heading)
6241 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6242 (setq eos (save-excursion
6243 (org-end-of-subtree t)
6244 (unless (eobp)
6245 (skip-chars-forward " \t\n"))
6246 (if (eobp) (point) (1- (point)))))
6247 (setq has-children
6248 (or (save-excursion
6249 (let ((level (funcall outline-level)))
6250 (outline-next-heading)
6251 (and (org-at-heading-p t)
6252 (> (funcall outline-level) level))))
6253 (save-excursion
6254 (org-list-search-forward (org-item-beginning-re) eos t)))))
6255 ;; Determine end invisible part of buffer (EOL)
6256 (beginning-of-line 2)
6257 ;; XEmacs doesn't have `next-single-char-property-change'
6258 (if (featurep 'xemacs)
6259 (while (and (not (eobp)) ;; this is like `next-line'
6260 (get-char-property (1- (point)) 'invisible))
6261 (beginning-of-line 2))
6262 (while (and (not (eobp)) ;; this is like `next-line'
6263 (get-char-property (1- (point)) 'invisible))
6264 (goto-char (next-single-char-property-change (point) 'invisible))
6265 (and (eolp) (beginning-of-line 2))))
6266 (setq eol (point)))
6267 ;; Find out what to do next and set `this-command'
6268 (cond
6269 ((= eos eoh)
6270 ;; Nothing is hidden behind this heading
6271 (run-hook-with-args 'org-pre-cycle-hook 'empty)
6272 (message "EMPTY ENTRY")
6273 (setq org-cycle-subtree-status nil)
6274 (save-excursion
6275 (goto-char eos)
6276 (outline-next-heading)
6277 (if (outline-invisible-p) (org-flag-heading nil))))
6278 ((and (or (>= eol eos)
6279 (not (string-match "\\S-" (buffer-substring eol eos))))
6280 (or has-children
6281 (not (setq children-skipped
6282 org-cycle-skip-children-state-if-no-children))))
6283 ;; Entire subtree is hidden in one line: children view
6284 (run-hook-with-args 'org-pre-cycle-hook 'children)
6285 (if (org-at-item-p)
6286 (org-list-set-item-visibility (point-at-bol) struct 'children)
6287 (org-show-entry)
6288 (show-children)
6289 ;; Fold every list in subtree to top-level items.
6290 (when (eq org-cycle-include-plain-lists 'integrate)
6291 (save-excursion
6292 (org-back-to-heading)
6293 (while (org-list-search-forward (org-item-beginning-re) eos t)
6294 (beginning-of-line 1)
6295 (let* ((struct (org-list-struct))
6296 (prevs (org-list-prevs-alist struct))
6297 (end (org-list-get-bottom-point struct)))
6298 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6299 (org-list-get-all-items (point) struct prevs))
6300 (goto-char end))))))
6301 (message "CHILDREN")
6302 (save-excursion
6303 (goto-char eos)
6304 (outline-next-heading)
6305 (if (outline-invisible-p) (org-flag-heading nil)))
6306 (setq org-cycle-subtree-status 'children)
6307 (run-hook-with-args 'org-cycle-hook 'children))
6308 ((or children-skipped
6309 (and (eq last-command this-command)
6310 (eq org-cycle-subtree-status 'children)))
6311 ;; We just showed the children, or no children are there,
6312 ;; now show everything.
6313 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
6314 (outline-flag-region eoh eos nil)
6315 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6316 (setq org-cycle-subtree-status 'subtree)
6317 (run-hook-with-args 'org-cycle-hook 'subtree))
6319 ;; Default action: hide the subtree.
6320 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6321 (outline-flag-region eoh eos t)
6322 (message "FOLDED")
6323 (setq org-cycle-subtree-status 'folded)
6324 (run-hook-with-args 'org-cycle-hook 'folded)))))
6326 ;;;###autoload
6327 (defun org-global-cycle (&optional arg)
6328 "Cycle the global visibility. For details see `org-cycle'.
6329 With \\[universal-argument] prefix arg, switch to startup visibility.
6330 With a numeric prefix, show all headlines up to that level."
6331 (interactive "P")
6332 (let ((org-cycle-include-plain-lists
6333 (if (eq major-mode 'org-mode) org-cycle-include-plain-lists nil)))
6334 (cond
6335 ((integerp arg)
6336 (show-all)
6337 (hide-sublevels arg)
6338 (setq org-cycle-global-status 'contents))
6339 ((equal arg '(4))
6340 (org-set-startup-visibility)
6341 (message "Startup visibility, plus VISIBILITY properties."))
6343 (org-cycle '(4))))))
6345 (defun org-set-startup-visibility ()
6346 "Set the visibility required by startup options and properties."
6347 (cond
6348 ((eq org-startup-folded t)
6349 (org-cycle '(4)))
6350 ((eq org-startup-folded 'content)
6351 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6352 (org-cycle '(4)) (org-cycle '(4)))))
6353 (unless (eq org-startup-folded 'showeverything)
6354 (if org-hide-block-startup (org-hide-block-all))
6355 (org-set-visibility-according-to-property 'no-cleanup)
6356 (org-cycle-hide-archived-subtrees 'all)
6357 (org-cycle-hide-drawers 'all)
6358 (org-cycle-show-empty-lines t)))
6360 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6361 "Switch subtree visibilities according to :VISIBILITY: property."
6362 (interactive)
6363 (let (org-show-entry-below state)
6364 (save-excursion
6365 (goto-char (point-min))
6366 (while (re-search-forward
6367 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6368 nil t)
6369 (setq state (match-string 1))
6370 (save-excursion
6371 (org-back-to-heading t)
6372 (hide-subtree)
6373 (org-reveal)
6374 (cond
6375 ((equal state '("fold" "folded"))
6376 (hide-subtree))
6377 ((equal state "children")
6378 (org-show-hidden-entry)
6379 (show-children))
6380 ((equal state "content")
6381 (save-excursion
6382 (save-restriction
6383 (org-narrow-to-subtree)
6384 (org-content))))
6385 ((member state '("all" "showall"))
6386 (show-subtree)))))
6387 (unless no-cleanup
6388 (org-cycle-hide-archived-subtrees 'all)
6389 (org-cycle-hide-drawers 'all)
6390 (org-cycle-show-empty-lines 'all)))))
6392 ;; This function uses outline-regexp instead of the more fundamental
6393 ;; org-outline-regexp so that org-cycle-global works outside of Org
6394 ;; buffers, where outline-regexp is needed.
6395 (defun org-overview ()
6396 "Switch to overview mode, showing only top-level headlines.
6397 Really, this shows all headlines with level equal or greater than the level
6398 of the first headline in the buffer. This is important, because if the
6399 first headline is not level one, then (hide-sublevels 1) gives confusing
6400 results."
6401 (interactive)
6402 (let ((level (save-excursion
6403 (goto-char (point-min))
6404 (if (re-search-forward (concat "^" outline-regexp) nil t)
6405 (progn
6406 (goto-char (match-beginning 0))
6407 (funcall outline-level))))))
6408 (and level (hide-sublevels level))))
6410 (defun org-content (&optional arg)
6411 "Show all headlines in the buffer, like a table of contents.
6412 With numerical argument N, show content up to level N."
6413 (interactive "P")
6414 (save-excursion
6415 ;; Visit all headings and show their offspring
6416 (and (integerp arg) (org-overview))
6417 (goto-char (point-max))
6418 (catch 'exit
6419 (while (and (progn (condition-case nil
6420 (outline-previous-visible-heading 1)
6421 (error (goto-char (point-min))))
6423 (looking-at org-outline-regexp))
6424 (if (integerp arg)
6425 (show-children (1- arg))
6426 (show-branches))
6427 (if (bobp) (throw 'exit nil))))))
6430 (defun org-optimize-window-after-visibility-change (state)
6431 "Adjust the window after a change in outline visibility.
6432 This function is the default value of the hook `org-cycle-hook'."
6433 (when (get-buffer-window (current-buffer))
6434 (cond
6435 ((eq state 'content) nil)
6436 ((eq state 'all) nil)
6437 ((eq state 'folded) nil)
6438 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6439 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6441 (defun org-remove-empty-overlays-at (pos)
6442 "Remove outline overlays that do not contain non-white stuff."
6443 (mapc
6444 (lambda (o)
6445 (and (eq 'outline (overlay-get o 'invisible))
6446 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6447 (overlay-end o))))
6448 (delete-overlay o)))
6449 (overlays-at pos)))
6451 (defun org-clean-visibility-after-subtree-move ()
6452 "Fix visibility issues after moving a subtree."
6453 ;; First, find a reasonable region to look at:
6454 ;; Start two siblings above, end three below
6455 (let* ((beg (save-excursion
6456 (and (org-get-last-sibling)
6457 (org-get-last-sibling))
6458 (point)))
6459 (end (save-excursion
6460 (and (org-get-next-sibling)
6461 (org-get-next-sibling)
6462 (org-get-next-sibling))
6463 (if (org-at-heading-p)
6464 (point-at-eol)
6465 (point))))
6466 (level (looking-at "\\*+"))
6467 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6468 (save-excursion
6469 (save-restriction
6470 (narrow-to-region beg end)
6471 (when re
6472 ;; Properly fold already folded siblings
6473 (goto-char (point-min))
6474 (while (re-search-forward re nil t)
6475 (if (and (not (outline-invisible-p))
6476 (save-excursion
6477 (goto-char (point-at-eol)) (outline-invisible-p)))
6478 (hide-entry))))
6479 (org-cycle-show-empty-lines 'overview)
6480 (org-cycle-hide-drawers 'overview)))))
6482 (defun org-cycle-show-empty-lines (state)
6483 "Show empty lines above all visible headlines.
6484 The region to be covered depends on STATE when called through
6485 `org-cycle-hook'. Lisp program can use t for STATE to get the
6486 entire buffer covered. Note that an empty line is only shown if there
6487 are at least `org-cycle-separator-lines' empty lines before the headline."
6488 (when (not (= org-cycle-separator-lines 0))
6489 (save-excursion
6490 (let* ((n (abs org-cycle-separator-lines))
6491 (re (cond
6492 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6493 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6494 (t (let ((ns (number-to-string (- n 2))))
6495 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6496 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6497 beg end b e)
6498 (cond
6499 ((memq state '(overview contents t))
6500 (setq beg (point-min) end (point-max)))
6501 ((memq state '(children folded))
6502 (setq beg (point) end (progn (org-end-of-subtree t t)
6503 (beginning-of-line 2)
6504 (point)))))
6505 (when beg
6506 (goto-char beg)
6507 (while (re-search-forward re end t)
6508 (unless (get-char-property (match-end 1) 'invisible)
6509 (setq e (match-end 1))
6510 (if (< org-cycle-separator-lines 0)
6511 (setq b (save-excursion
6512 (goto-char (match-beginning 0))
6513 (org-back-over-empty-lines)
6514 (if (save-excursion
6515 (goto-char (max (point-min) (1- (point))))
6516 (org-on-heading-p))
6517 (1- (point))
6518 (point))))
6519 (setq b (match-beginning 1)))
6520 (outline-flag-region b e nil)))))))
6521 ;; Never hide empty lines at the end of the file.
6522 (save-excursion
6523 (goto-char (point-max))
6524 (outline-previous-heading)
6525 (outline-end-of-heading)
6526 (if (and (looking-at "[ \t\n]+")
6527 (= (match-end 0) (point-max)))
6528 (outline-flag-region (point) (match-end 0) nil))))
6530 (defun org-show-empty-lines-in-parent ()
6531 "Move to the parent and re-show empty lines before visible headlines."
6532 (save-excursion
6533 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6534 (org-cycle-show-empty-lines context))))
6536 (defun org-files-list ()
6537 "Return `org-agenda-files' list, plus all open org-mode files.
6538 This is useful for operations that need to scan all of a user's
6539 open and agenda-wise Org files."
6540 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6541 (dolist (buf (buffer-list))
6542 (with-current-buffer buf
6543 (if (and (eq major-mode 'org-mode) (buffer-file-name))
6544 (let ((file (expand-file-name (buffer-file-name))))
6545 (unless (member file files)
6546 (push file files))))))
6547 files))
6549 (defsubst org-entry-beginning-position ()
6550 "Return the beginning position of the current entry."
6551 (save-excursion (outline-back-to-heading t) (point)))
6553 (defsubst org-entry-end-position ()
6554 "Return the end position of the current entry."
6555 (save-excursion (outline-next-heading) (point)))
6557 (defun org-cycle-hide-drawers (state)
6558 "Re-hide all drawers after a visibility state change."
6559 (when (and (eq major-mode 'org-mode)
6560 (not (memq state '(overview folded contents))))
6561 (save-excursion
6562 (let* ((globalp (memq state '(contents all)))
6563 (beg (if globalp (point-min) (point)))
6564 (end (if globalp (point-max)
6565 (if (eq state 'children)
6566 (save-excursion (outline-next-heading) (point))
6567 (org-end-of-subtree t)))))
6568 (goto-char beg)
6569 (while (re-search-forward org-drawer-regexp end t)
6570 (org-flag-drawer t))))))
6572 (defun org-flag-drawer (flag)
6573 (save-excursion
6574 (beginning-of-line 1)
6575 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6576 (let ((b (match-end 0)))
6577 (if (re-search-forward
6578 "^[ \t]*:END:"
6579 (save-excursion (outline-next-heading) (point)) t)
6580 (outline-flag-region b (point-at-eol) flag)
6581 (error ":END: line missing at position %s" b))))))
6583 (defun org-subtree-end-visible-p ()
6584 "Is the end of the current subtree visible?"
6585 (pos-visible-in-window-p
6586 (save-excursion (org-end-of-subtree t) (point))))
6588 (defun org-first-headline-recenter (&optional N)
6589 "Move cursor to the first headline and recenter the headline.
6590 Optional argument N means put the headline into the Nth line of the window."
6591 (goto-char (point-min))
6592 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
6593 (beginning-of-line)
6594 (recenter (prefix-numeric-value N))))
6596 ;;; Saving and restoring visibility
6598 (defun org-outline-overlay-data (&optional use-markers)
6599 "Return a list of the locations of all outline overlays.
6600 These are overlays with the `invisible' property value `outline'.
6601 The return value is a list of cons cells, with start and stop
6602 positions for each overlay.
6603 If USE-MARKERS is set, return the positions as markers."
6604 (let (beg end)
6605 (save-excursion
6606 (save-restriction
6607 (widen)
6608 (delq nil
6609 (mapcar (lambda (o)
6610 (when (eq (overlay-get o 'invisible) 'outline)
6611 (setq beg (overlay-start o)
6612 end (overlay-end o))
6613 (and beg end (> end beg)
6614 (if use-markers
6615 (cons (move-marker (make-marker) beg)
6616 (move-marker (make-marker) end))
6617 (cons beg end)))))
6618 (overlays-in (point-min) (point-max))))))))
6620 (defun org-set-outline-overlay-data (data)
6621 "Create visibility overlays for all positions in DATA.
6622 DATA should have been made by `org-outline-overlay-data'."
6623 (let (o)
6624 (save-excursion
6625 (save-restriction
6626 (widen)
6627 (show-all)
6628 (mapc (lambda (c)
6629 (outline-flag-region (car c) (cdr c) t))
6630 data)))))
6632 ;;; Folding of blocks
6634 (defconst org-block-regexp
6635 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
6636 "Regular expression for hiding blocks.")
6638 (defvar org-hide-block-overlays nil
6639 "Overlays hiding blocks.")
6640 (make-variable-buffer-local 'org-hide-block-overlays)
6642 (defun org-block-map (function &optional start end)
6643 "Call FUNCTION at the head of all source blocks in the current buffer.
6644 Optional arguments START and END can be used to limit the range."
6645 (let ((start (or start (point-min)))
6646 (end (or end (point-max))))
6647 (save-excursion
6648 (goto-char start)
6649 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
6650 (save-excursion
6651 (save-match-data
6652 (goto-char (match-beginning 0))
6653 (funcall function)))))))
6655 (defun org-hide-block-toggle-all ()
6656 "Toggle the visibility of all blocks in the current buffer."
6657 (org-block-map #'org-hide-block-toggle))
6659 (defun org-hide-block-all ()
6660 "Fold all blocks in the current buffer."
6661 (interactive)
6662 (org-show-block-all)
6663 (org-block-map #'org-hide-block-toggle-maybe))
6665 (defun org-show-block-all ()
6666 "Unfold all blocks in the current buffer."
6667 (interactive)
6668 (mapc 'delete-overlay org-hide-block-overlays)
6669 (setq org-hide-block-overlays nil))
6671 (defun org-hide-block-toggle-maybe ()
6672 "Toggle visibility of block at point."
6673 (interactive)
6674 (let ((case-fold-search t))
6675 (if (save-excursion
6676 (beginning-of-line 1)
6677 (looking-at org-block-regexp))
6678 (progn (org-hide-block-toggle)
6679 t) ;; to signal that we took action
6680 nil))) ;; to signal that we did not
6682 (defun org-hide-block-toggle (&optional force)
6683 "Toggle the visibility of the current block."
6684 (interactive)
6685 (save-excursion
6686 (beginning-of-line)
6687 (if (re-search-forward org-block-regexp nil t)
6688 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
6689 (end (match-end 0)) ;; end of entire body
6691 (if (memq t (mapcar (lambda (overlay)
6692 (eq (overlay-get overlay 'invisible)
6693 'org-hide-block))
6694 (overlays-at start)))
6695 (if (or (not force) (eq force 'off))
6696 (mapc (lambda (ov)
6697 (when (member ov org-hide-block-overlays)
6698 (setq org-hide-block-overlays
6699 (delq ov org-hide-block-overlays)))
6700 (when (eq (overlay-get ov 'invisible)
6701 'org-hide-block)
6702 (delete-overlay ov)))
6703 (overlays-at start)))
6704 (setq ov (make-overlay start end))
6705 (overlay-put ov 'invisible 'org-hide-block)
6706 ;; make the block accessible to isearch
6707 (overlay-put
6708 ov 'isearch-open-invisible
6709 (lambda (ov)
6710 (when (member ov org-hide-block-overlays)
6711 (setq org-hide-block-overlays
6712 (delq ov org-hide-block-overlays)))
6713 (when (eq (overlay-get ov 'invisible)
6714 'org-hide-block)
6715 (delete-overlay ov))))
6716 (push ov org-hide-block-overlays)))
6717 (error "Not looking at a source block"))))
6719 ;; org-tab-after-check-for-cycling-hook
6720 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
6721 ;; Remove overlays when changing major mode
6722 (add-hook 'org-mode-hook
6723 (lambda () (org-add-hook 'change-major-mode-hook
6724 'org-show-block-all 'append 'local)))
6726 ;;; Org-goto
6728 (defvar org-goto-window-configuration nil)
6729 (defvar org-goto-marker nil)
6730 (defvar org-goto-map
6731 (let ((map (make-sparse-keymap)))
6732 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
6733 (while (setq cmd (pop cmds))
6734 (substitute-key-definition cmd cmd map global-map)))
6735 (suppress-keymap map)
6736 (org-defkey map "\C-m" 'org-goto-ret)
6737 (org-defkey map [(return)] 'org-goto-ret)
6738 (org-defkey map [(left)] 'org-goto-left)
6739 (org-defkey map [(right)] 'org-goto-right)
6740 (org-defkey map [(control ?g)] 'org-goto-quit)
6741 (org-defkey map "\C-i" 'org-cycle)
6742 (org-defkey map [(tab)] 'org-cycle)
6743 (org-defkey map [(down)] 'outline-next-visible-heading)
6744 (org-defkey map [(up)] 'outline-previous-visible-heading)
6745 (if org-goto-auto-isearch
6746 (if (fboundp 'define-key-after)
6747 (define-key-after map [t] 'org-goto-local-auto-isearch)
6748 nil)
6749 (org-defkey map "q" 'org-goto-quit)
6750 (org-defkey map "n" 'outline-next-visible-heading)
6751 (org-defkey map "p" 'outline-previous-visible-heading)
6752 (org-defkey map "f" 'outline-forward-same-level)
6753 (org-defkey map "b" 'outline-backward-same-level)
6754 (org-defkey map "u" 'outline-up-heading))
6755 (org-defkey map "/" 'org-occur)
6756 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
6757 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
6758 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
6759 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
6760 (org-defkey map "\C-c\C-u" 'outline-up-heading)
6761 map))
6763 (defconst org-goto-help
6764 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
6765 RET=jump to location [Q]uit and return to previous location
6766 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
6768 (defvar org-goto-start-pos) ; dynamically scoped parameter
6770 ;; FIXME: Docstring does not mention both interfaces
6771 (defun org-goto (&optional alternative-interface)
6772 "Look up a different location in the current file, keeping current visibility.
6774 When you want look-up or go to a different location in a document, the
6775 fastest way is often to fold the entire buffer and then dive into the tree.
6776 This method has the disadvantage, that the previous location will be folded,
6777 which may not be what you want.
6779 This command works around this by showing a copy of the current buffer
6780 in an indirect buffer, in overview mode. You can dive into the tree in
6781 that copy, use org-occur and incremental search to find a location.
6782 When pressing RET or `Q', the command returns to the original buffer in
6783 which the visibility is still unchanged. After RET is will also jump to
6784 the location selected in the indirect buffer and expose the headline
6785 hierarchy above."
6786 (interactive "P")
6787 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
6788 (org-refile-use-outline-path t)
6789 (org-refile-target-verify-function nil)
6790 (interface
6791 (if (not alternative-interface)
6792 org-goto-interface
6793 (if (eq org-goto-interface 'outline)
6794 'outline-path-completion
6795 'outline)))
6796 (org-goto-start-pos (point))
6797 (selected-point
6798 (if (eq interface 'outline)
6799 (car (org-get-location (current-buffer) org-goto-help))
6800 (let ((pa (org-refile-get-location "Goto")))
6801 (org-refile-check-position pa)
6802 (nth 3 pa)))))
6803 (if selected-point
6804 (progn
6805 (org-mark-ring-push org-goto-start-pos)
6806 (goto-char selected-point)
6807 (if (or (outline-invisible-p) (org-invisible-p2))
6808 (org-show-context 'org-goto)))
6809 (message "Quit"))))
6811 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
6812 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
6813 (defvar org-goto-local-auto-isearch-map) ; defined below
6815 (defun org-get-location (buf help)
6816 "Let the user select a location in the Org-mode buffer BUF.
6817 This function uses a recursive edit. It returns the selected position
6818 or nil."
6819 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
6820 (isearch-hide-immediately nil)
6821 (isearch-search-fun-function
6822 (lambda () 'org-goto-local-search-headings))
6823 (org-goto-selected-point org-goto-exit-command)
6824 (pop-up-frames nil)
6825 (special-display-buffer-names nil)
6826 (special-display-regexps nil)
6827 (special-display-function nil))
6828 (save-excursion
6829 (save-window-excursion
6830 (delete-other-windows)
6831 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
6832 (org-pop-to-buffer-same-window
6833 (condition-case nil
6834 (make-indirect-buffer (current-buffer) "*org-goto*")
6835 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
6836 (with-output-to-temp-buffer "*Help*"
6837 (princ help))
6838 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
6839 (setq buffer-read-only nil)
6840 (let ((org-startup-truncated t)
6841 (org-startup-folded nil)
6842 (org-startup-align-all-tables nil))
6843 (org-mode)
6844 (org-overview))
6845 (setq buffer-read-only t)
6846 (if (and (boundp 'org-goto-start-pos)
6847 (integer-or-marker-p org-goto-start-pos))
6848 (let ((org-show-hierarchy-above t)
6849 (org-show-siblings t)
6850 (org-show-following-heading t))
6851 (goto-char org-goto-start-pos)
6852 (and (outline-invisible-p) (org-show-context)))
6853 (goto-char (point-min)))
6854 (let (org-special-ctrl-a/e) (org-beginning-of-line))
6855 (message "Select location and press RET")
6856 (use-local-map org-goto-map)
6857 (recursive-edit)
6859 (kill-buffer "*org-goto*")
6860 (cons org-goto-selected-point org-goto-exit-command)))
6862 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
6863 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
6864 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
6865 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
6867 (defun org-goto-local-search-headings (string bound noerror)
6868 "Search and make sure that any matches are in headlines."
6869 (catch 'return
6870 (while (if isearch-forward
6871 (search-forward string bound noerror)
6872 (search-backward string bound noerror))
6873 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
6874 (and (member :headline context)
6875 (not (member :tags context))))
6876 (throw 'return (point))))))
6878 (defun org-goto-local-auto-isearch ()
6879 "Start isearch."
6880 (interactive)
6881 (goto-char (point-min))
6882 (let ((keys (this-command-keys)))
6883 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
6884 (isearch-mode t)
6885 (isearch-process-search-char (string-to-char keys)))))
6887 (defun org-goto-ret (&optional arg)
6888 "Finish `org-goto' by going to the new location."
6889 (interactive "P")
6890 (setq org-goto-selected-point (point)
6891 org-goto-exit-command 'return)
6892 (throw 'exit nil))
6894 (defun org-goto-left ()
6895 "Finish `org-goto' by going to the new location."
6896 (interactive)
6897 (if (org-on-heading-p)
6898 (progn
6899 (beginning-of-line 1)
6900 (setq org-goto-selected-point (point)
6901 org-goto-exit-command 'left)
6902 (throw 'exit nil))
6903 (error "Not on a heading")))
6905 (defun org-goto-right ()
6906 "Finish `org-goto' by going to the new location."
6907 (interactive)
6908 (if (org-on-heading-p)
6909 (progn
6910 (setq org-goto-selected-point (point)
6911 org-goto-exit-command 'right)
6912 (throw 'exit nil))
6913 (error "Not on a heading")))
6915 (defun org-goto-quit ()
6916 "Finish `org-goto' without cursor motion."
6917 (interactive)
6918 (setq org-goto-selected-point nil)
6919 (setq org-goto-exit-command 'quit)
6920 (throw 'exit nil))
6922 ;;; Indirect buffer display of subtrees
6924 (defvar org-indirect-dedicated-frame nil
6925 "This is the frame being used for indirect tree display.")
6926 (defvar org-last-indirect-buffer nil)
6928 (defun org-tree-to-indirect-buffer (&optional arg)
6929 "Create indirect buffer and narrow it to current subtree.
6930 With numerical prefix ARG, go up to this level and then take that tree.
6931 If ARG is negative, go up that many levels.
6932 If `org-indirect-buffer-display' is not `new-frame', the command removes the
6933 indirect buffer previously made with this command, to avoid proliferation of
6934 indirect buffers. However, when you call the command with a \
6935 \\[universal-argument] prefix, or
6936 when `org-indirect-buffer-display' is `new-frame', the last buffer
6937 is kept so that you can work with several indirect buffers at the same time.
6938 If `org-indirect-buffer-display' is `dedicated-frame', the \
6939 \\[universal-argument] prefix also
6940 requests that a new frame be made for the new buffer, so that the dedicated
6941 frame is not changed."
6942 (interactive "P")
6943 (let ((cbuf (current-buffer))
6944 (cwin (selected-window))
6945 (pos (point))
6946 beg end level heading ibuf)
6947 (save-excursion
6948 (org-back-to-heading t)
6949 (when (numberp arg)
6950 (setq level (org-outline-level))
6951 (if (< arg 0) (setq arg (+ level arg)))
6952 (while (> (setq level (org-outline-level)) arg)
6953 (outline-up-heading 1 t)))
6954 (setq beg (point)
6955 heading (org-get-heading))
6956 (org-end-of-subtree t t)
6957 (if (org-on-heading-p) (backward-char 1))
6958 (setq end (point)))
6959 (if (and (buffer-live-p org-last-indirect-buffer)
6960 (not (eq org-indirect-buffer-display 'new-frame))
6961 (not arg))
6962 (kill-buffer org-last-indirect-buffer))
6963 (setq ibuf (org-get-indirect-buffer cbuf)
6964 org-last-indirect-buffer ibuf)
6965 (cond
6966 ((or (eq org-indirect-buffer-display 'new-frame)
6967 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
6968 (select-frame (make-frame))
6969 (delete-other-windows)
6970 (org-pop-to-buffer-same-window ibuf)
6971 (org-set-frame-title heading))
6972 ((eq org-indirect-buffer-display 'dedicated-frame)
6973 (raise-frame
6974 (select-frame (or (and org-indirect-dedicated-frame
6975 (frame-live-p org-indirect-dedicated-frame)
6976 org-indirect-dedicated-frame)
6977 (setq org-indirect-dedicated-frame (make-frame)))))
6978 (delete-other-windows)
6979 (org-pop-to-buffer-same-window ibuf)
6980 (org-set-frame-title (concat "Indirect: " heading)))
6981 ((eq org-indirect-buffer-display 'current-window)
6982 (org-pop-to-buffer-same-window ibuf))
6983 ((eq org-indirect-buffer-display 'other-window)
6984 (pop-to-buffer ibuf))
6985 (t (error "Invalid value")))
6986 (if (featurep 'xemacs)
6987 (save-excursion (org-mode) (turn-on-font-lock)))
6988 (narrow-to-region beg end)
6989 (show-all)
6990 (goto-char pos)
6991 (run-hook-with-args 'org-cycle-hook 'all)
6992 (and (window-live-p cwin) (select-window cwin))))
6994 (defun org-get-indirect-buffer (&optional buffer)
6995 (setq buffer (or buffer (current-buffer)))
6996 (let ((n 1) (base (buffer-name buffer)) bname)
6997 (while (buffer-live-p
6998 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
6999 (setq n (1+ n)))
7000 (condition-case nil
7001 (make-indirect-buffer buffer bname 'clone)
7002 (error (make-indirect-buffer buffer bname)))))
7004 (defun org-set-frame-title (title)
7005 "Set the title of the current frame to the string TITLE."
7006 ;; FIXME: how to name a single frame in XEmacs???
7007 (unless (featurep 'xemacs)
7008 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7010 ;;;; Structure editing
7012 ;;; Inserting headlines
7014 (defun org-previous-line-empty-p ()
7015 (save-excursion
7016 (and (not (bobp))
7017 (or (beginning-of-line 0) t)
7018 (save-match-data
7019 (looking-at "[ \t]*$")))))
7021 (defun org-insert-heading (&optional force-heading invisible-ok)
7022 "Insert a new heading or item with same depth at point.
7023 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
7024 If point is at the beginning of a headline, insert a sibling before the
7025 current headline. If point is not at the beginning, split the line,
7026 create the new headline with the text in the current line after point
7027 \(but see also the variable `org-M-RET-may-split-line').
7029 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7030 This is important for non-interactive uses of the command."
7031 (interactive "P")
7032 (if (or (= (buffer-size) 0)
7033 (and (not (save-excursion
7034 (and (ignore-errors (org-back-to-heading invisible-ok))
7035 (org-on-heading-p))))
7036 (or force-heading (not (org-in-item-p)))))
7037 (progn
7038 (insert "\n* ")
7039 (run-hooks 'org-insert-heading-hook))
7040 (when (or force-heading (not (org-insert-item)))
7041 (let* ((empty-line-p nil)
7042 (level nil)
7043 (on-heading (org-on-heading-p))
7044 (head (save-excursion
7045 (condition-case nil
7046 (progn
7047 (org-back-to-heading invisible-ok)
7048 (when (and (not on-heading)
7049 (featurep 'org-inlinetask)
7050 (integerp org-inlinetask-min-level)
7051 (>= (length (match-string 0))
7052 org-inlinetask-min-level))
7053 ;; Find a heading level before the inline task
7054 (while (and (setq level (org-up-heading-safe))
7055 (>= level org-inlinetask-min-level)))
7056 (if (org-on-heading-p)
7057 (org-back-to-heading invisible-ok)
7058 (error "This should not happen")))
7059 (setq empty-line-p (org-previous-line-empty-p))
7060 (match-string 0))
7061 (error "*"))))
7062 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7063 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7064 pos hide-previous previous-pos)
7065 (cond
7066 ((and (org-on-heading-p) (bolp)
7067 (or (bobp)
7068 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
7069 ;; insert before the current line
7070 (open-line (if blank 2 1)))
7071 ((and (bolp)
7072 (not org-insert-heading-respect-content)
7073 (or (bobp)
7074 (save-excursion
7075 (backward-char 1) (not (outline-invisible-p)))))
7076 ;; insert right here
7077 nil)
7079 ;; somewhere in the line
7080 (save-excursion
7081 (setq previous-pos (point-at-bol))
7082 (end-of-line)
7083 (setq hide-previous (outline-invisible-p)))
7084 (and org-insert-heading-respect-content (org-show-subtree))
7085 (let ((split
7086 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
7087 (save-excursion
7088 (let ((p (point)))
7089 (goto-char (point-at-bol))
7090 (and (looking-at org-complex-heading-regexp)
7091 (match-beginning 4)
7092 (> p (match-beginning 4)))))))
7093 tags pos)
7094 (cond
7095 (org-insert-heading-respect-content
7096 (org-end-of-subtree nil t)
7097 (when (featurep 'org-inlinetask)
7098 (while (and (not (eobp))
7099 (looking-at "\\(\\*+\\)[ \t]+")
7100 (>= (length (match-string 1))
7101 org-inlinetask-min-level))
7102 (org-end-of-subtree nil t)))
7103 (or (bolp) (newline))
7104 (or (org-previous-line-empty-p)
7105 (and blank (newline)))
7106 (open-line 1))
7107 ((org-on-heading-p)
7108 (when hide-previous
7109 (show-children)
7110 (org-show-entry))
7111 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7112 (setq tags (and (match-end 2) (match-string 2)))
7113 (and (match-end 1)
7114 (delete-region (match-beginning 1) (match-end 1)))
7115 (setq pos (point-at-bol))
7116 (or split (end-of-line 1))
7117 (delete-horizontal-space)
7118 (if (string-match "\\`\\*+\\'"
7119 (buffer-substring (point-at-bol) (point)))
7120 (insert " "))
7121 (newline (if blank 2 1))
7122 (when tags
7123 (save-excursion
7124 (goto-char pos)
7125 (end-of-line 1)
7126 (insert " " tags)
7127 (org-set-tags nil 'align))))
7129 (or split (end-of-line 1))
7130 (newline (if blank 2 1)))))))
7131 (insert head) (just-one-space)
7132 (setq pos (point))
7133 (end-of-line 1)
7134 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7135 (when (and org-insert-heading-respect-content hide-previous)
7136 (save-excursion
7137 (goto-char previous-pos)
7138 (hide-subtree)))
7139 (run-hooks 'org-insert-heading-hook)))))
7141 (defun org-get-heading (&optional no-tags no-todo)
7142 "Return the heading of the current entry, without the stars.
7143 When NO-TAGS is non-nil, don't include tags.
7144 When NO-TODO is non-nil, don't include TODO keywords."
7145 (save-excursion
7146 (org-back-to-heading t)
7147 (cond
7148 ((and no-tags no-todo)
7149 (looking-at org-complex-heading-regexp)
7150 (match-string 4))
7151 (no-tags
7152 (looking-at (concat org-outline-regexp
7153 "\\(.*?\\)"
7154 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7155 (match-string 1))
7156 (no-todo
7157 (looking-at org-todo-line-regexp)
7158 (match-string 3))
7159 (t (looking-at org-heading-regexp)
7160 (match-string 2)))))
7162 (defun org-heading-components ()
7163 "Return the components of the current heading.
7164 This is a list with the following elements:
7165 - the level as an integer
7166 - the reduced level, different if `org-odd-levels-only' is set.
7167 - the TODO keyword, or nil
7168 - the priority character, like ?A, or nil if no priority is given
7169 - the headline text itself, or the tags string if no headline text
7170 - the tags string, or nil."
7171 (save-excursion
7172 (org-back-to-heading t)
7173 (if (let (case-fold-search) (looking-at org-complex-heading-regexp))
7174 (list (length (match-string 1))
7175 (org-reduced-level (length (match-string 1)))
7176 (org-match-string-no-properties 2)
7177 (and (match-end 3) (aref (match-string 3) 2))
7178 (org-match-string-no-properties 4)
7179 (org-match-string-no-properties 5)))))
7181 (defun org-get-entry ()
7182 "Get the entry text, after heading, entire subtree."
7183 (save-excursion
7184 (org-back-to-heading t)
7185 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7187 (defun org-insert-heading-after-current ()
7188 "Insert a new heading with same level as current, after current subtree."
7189 (interactive)
7190 (org-back-to-heading)
7191 (org-insert-heading)
7192 (org-move-subtree-down)
7193 (end-of-line 1))
7195 (defun org-insert-heading-respect-content ()
7196 (interactive)
7197 (let ((org-insert-heading-respect-content t))
7198 (org-insert-heading t)))
7200 (defun org-insert-todo-heading-respect-content (&optional force-state)
7201 (interactive "P")
7202 (let ((org-insert-heading-respect-content t))
7203 (org-insert-todo-heading force-state t)))
7205 (defun org-insert-todo-heading (arg &optional force-heading)
7206 "Insert a new heading with the same level and TODO state as current heading.
7207 If the heading has no TODO state, or if the state is DONE, use the first
7208 state (TODO by default). Also with prefix arg, force first state."
7209 (interactive "P")
7210 (when (or force-heading (not (org-insert-item 'checkbox)))
7211 (org-insert-heading force-heading)
7212 (save-excursion
7213 (org-back-to-heading)
7214 (outline-previous-heading)
7215 (looking-at org-todo-line-regexp))
7216 (let*
7217 ((new-mark-x
7218 (if (or arg
7219 (not (match-beginning 2))
7220 (member (match-string 2) org-done-keywords))
7221 (car org-todo-keywords-1)
7222 (match-string 2)))
7223 (new-mark
7225 (run-hook-with-args-until-success
7226 'org-todo-get-default-hook new-mark-x nil)
7227 new-mark-x)))
7228 (beginning-of-line 1)
7229 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7230 (if org-treat-insert-todo-heading-as-state-change
7231 (org-todo new-mark)
7232 (insert new-mark " "))))
7233 (when org-provide-todo-statistics
7234 (org-update-parent-todo-statistics))))
7236 (defun org-insert-subheading (arg)
7237 "Insert a new subheading and demote it.
7238 Works for outline headings and for plain lists alike."
7239 (interactive "P")
7240 (org-insert-heading arg)
7241 (cond
7242 ((org-on-heading-p) (org-do-demote))
7243 ((org-at-item-p) (org-indent-item))))
7245 (defun org-insert-todo-subheading (arg)
7246 "Insert a new subheading with TODO keyword or checkbox and demote it.
7247 Works for outline headings and for plain lists alike."
7248 (interactive "P")
7249 (org-insert-todo-heading arg)
7250 (cond
7251 ((org-on-heading-p) (org-do-demote))
7252 ((org-at-item-p) (org-indent-item))))
7254 ;;; Promotion and Demotion
7256 (defvar org-after-demote-entry-hook nil
7257 "Hook run after an entry has been demoted.
7258 The cursor will be at the beginning of the entry.
7259 When a subtree is being demoted, the hook will be called for each node.")
7261 (defvar org-after-promote-entry-hook nil
7262 "Hook run after an entry has been promoted.
7263 The cursor will be at the beginning of the entry.
7264 When a subtree is being promoted, the hook will be called for each node.")
7266 (defun org-promote-subtree ()
7267 "Promote the entire subtree.
7268 See also `org-promote'."
7269 (interactive)
7270 (save-excursion
7271 (org-with-limited-levels (org-map-tree 'org-promote)))
7272 (org-fix-position-after-promote))
7274 (defun org-demote-subtree ()
7275 "Demote the entire subtree. See `org-demote'.
7276 See also `org-promote'."
7277 (interactive)
7278 (save-excursion
7279 (org-with-limited-levels (org-map-tree 'org-demote)))
7280 (org-fix-position-after-promote))
7283 (defun org-do-promote ()
7284 "Promote the current heading higher up the tree.
7285 If the region is active in `transient-mark-mode', promote all headings
7286 in the region."
7287 (interactive)
7288 (save-excursion
7289 (if (org-region-active-p)
7290 (org-map-region 'org-promote (region-beginning) (region-end))
7291 (org-promote)))
7292 (org-fix-position-after-promote))
7294 (defun org-do-demote ()
7295 "Demote the current heading lower down the tree.
7296 If the region is active in `transient-mark-mode', demote all headings
7297 in the region."
7298 (interactive)
7299 (save-excursion
7300 (if (org-region-active-p)
7301 (org-map-region 'org-demote (region-beginning) (region-end))
7302 (org-demote)))
7303 (org-fix-position-after-promote))
7305 (defun org-fix-position-after-promote ()
7306 "Make sure that after pro/demotion cursor position is right."
7307 (let ((pos (point)))
7308 (when (save-excursion
7309 (beginning-of-line 1)
7310 (looking-at org-todo-line-regexp)
7311 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7312 (cond ((eobp) (insert " "))
7313 ((eolp) (insert " "))
7314 ((equal (char-after) ?\ ) (forward-char 1))))))
7316 (defun org-current-level ()
7317 "Return the level of the current entry, or nil if before the first headline.
7318 The level is the number of stars at the beginning of the headline."
7319 (save-excursion
7320 (org-with-limited-levels
7321 (if (ignore-errors (org-back-to-heading t))
7322 (funcall outline-level)))))
7324 (defun org-get-previous-line-level ()
7325 "Return the outline depth of the last headline before the current line.
7326 Returns 0 for the first headline in the buffer, and nil if before the
7327 first headline."
7328 (let ((current-level (org-current-level))
7329 (prev-level (when (> (line-number-at-pos) 1)
7330 (save-excursion
7331 (beginning-of-line 0)
7332 (org-current-level)))))
7333 (cond ((null current-level) nil) ; Before first headline
7334 ((null prev-level) 0) ; At first headline
7335 (prev-level))))
7337 (defun org-reduced-level (l)
7338 "Compute the effective level of a heading.
7339 This takes into account the setting of `org-odd-levels-only'."
7340 (cond
7341 ((zerop l) 0)
7342 (org-odd-levels-only (1+ (floor (/ l 2))))
7343 (t l)))
7345 (defun org-level-increment ()
7346 "Return the number of stars that will be added or removed at a
7347 time to headlines when structure editing, based on the value of
7348 `org-odd-levels-only'."
7349 (if org-odd-levels-only 2 1))
7351 (defun org-get-valid-level (level &optional change)
7352 "Rectify a level change under the influence of `org-odd-levels-only'
7353 LEVEL is a current level, CHANGE is by how much the level should be
7354 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7355 even level numbers will become the next higher odd number."
7356 (if org-odd-levels-only
7357 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7358 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7359 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7360 (max 1 (+ level (or change 0)))))
7362 (if (boundp 'define-obsolete-function-alias)
7363 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7364 (define-obsolete-function-alias 'org-get-legal-level
7365 'org-get-valid-level)
7366 (define-obsolete-function-alias 'org-get-legal-level
7367 'org-get-valid-level "23.1")))
7369 (defun org-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 (org-back-to-heading t)
7374 (let* ((level (save-match-data (funcall outline-level)))
7375 (after-change-functions (remove 'flyspell-after-change-function
7376 after-change-functions))
7377 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7378 (diff (abs (- level (length up-head) -1))))
7379 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
7380 (replace-match up-head nil t)
7381 ;; Fixup tag positioning
7382 (and org-auto-align-tags (org-set-tags nil t))
7383 (if org-adapt-indentation (org-fixup-indentation (- diff)))
7384 (run-hooks 'org-after-promote-entry-hook)))
7386 (defun org-demote ()
7387 "Demote the current heading lower down the tree.
7388 If the region is active in `transient-mark-mode', demote all headings
7389 in the region."
7390 (org-back-to-heading t)
7391 (let* ((level (save-match-data (funcall outline-level)))
7392 (after-change-functions (remove 'flyspell-after-change-function
7393 after-change-functions))
7394 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7395 (diff (abs (- level (length down-head) -1))))
7396 (replace-match down-head nil t)
7397 ;; Fixup tag positioning
7398 (and org-auto-align-tags (org-set-tags nil t))
7399 (if org-adapt-indentation (org-fixup-indentation diff))
7400 (run-hooks 'org-after-demote-entry-hook)))
7402 (defun org-cycle-level ()
7403 "Cycle the level of an empty headline through possible states.
7404 This goes first to child, then to parent, level, then up the hierarchy.
7405 After top level, it switches back to sibling level."
7406 (interactive)
7407 (let ((org-adapt-indentation nil))
7408 (when (org-point-at-end-of-empty-headline)
7409 (setq this-command 'org-cycle-level) ; Only needed for caching
7410 (let ((cur-level (org-current-level))
7411 (prev-level (org-get-previous-line-level)))
7412 (cond
7413 ;; If first headline in file, promote to top-level.
7414 ((= prev-level 0)
7415 (loop repeat (/ (- cur-level 1) (org-level-increment))
7416 do (org-do-promote)))
7417 ;; If same level as prev, demote one.
7418 ((= prev-level cur-level)
7419 (org-do-demote))
7420 ;; If parent is top-level, promote to top level if not already.
7421 ((= prev-level 1)
7422 (loop repeat (/ (- cur-level 1) (org-level-increment))
7423 do (org-do-promote)))
7424 ;; If top-level, return to prev-level.
7425 ((= cur-level 1)
7426 (loop repeat (/ (- prev-level 1) (org-level-increment))
7427 do (org-do-demote)))
7428 ;; If less than prev-level, promote one.
7429 ((< cur-level prev-level)
7430 (org-do-promote))
7431 ;; If deeper than prev-level, promote until higher than
7432 ;; prev-level.
7433 ((> cur-level prev-level)
7434 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7435 do (org-do-promote))))
7436 t))))
7438 (defun org-map-tree (fun)
7439 "Call FUN for every heading underneath the current one."
7440 (org-back-to-heading)
7441 (let ((level (funcall outline-level)))
7442 (save-excursion
7443 (funcall fun)
7444 (while (and (progn
7445 (outline-next-heading)
7446 (> (funcall outline-level) level))
7447 (not (eobp)))
7448 (funcall fun)))))
7450 (defun org-map-region (fun beg end)
7451 "Call FUN for every heading between BEG and END."
7452 (let ((org-ignore-region t))
7453 (save-excursion
7454 (setq end (copy-marker end))
7455 (goto-char beg)
7456 (if (and (re-search-forward org-outline-regexp-bol nil t)
7457 (< (point) end))
7458 (funcall fun))
7459 (while (and (progn
7460 (outline-next-heading)
7461 (< (point) end))
7462 (not (eobp)))
7463 (funcall fun)))))
7465 (defvar org-property-end-re) ; silence byte-compiler
7466 (defun org-fixup-indentation (diff)
7467 "Change the indentation in the current entry by DIFF.
7468 However, if any line in the current entry has no indentation, or if it
7469 would end up with no indentation after the change, nothing at all is done."
7470 (save-excursion
7471 (let ((end (save-excursion (outline-next-heading)
7472 (point-marker)))
7473 (prohibit (if (> diff 0)
7474 "^\\S-"
7475 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7476 col)
7477 (unless (save-excursion (end-of-line 1)
7478 (re-search-forward prohibit end t))
7479 (while (and (< (point) end)
7480 (re-search-forward "^[ \t]+" end t))
7481 (goto-char (match-end 0))
7482 (setq col (current-column))
7483 (if (< diff 0) (replace-match ""))
7484 (org-indent-to-column (+ diff col))))
7485 (move-marker end nil))))
7487 (defun org-convert-to-odd-levels ()
7488 "Convert an org-mode file with all levels allowed to one with odd levels.
7489 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7490 level 5 etc."
7491 (interactive)
7492 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7493 (let ((outline-level 'org-outline-level)
7494 (org-odd-levels-only nil) n)
7495 (save-excursion
7496 (goto-char (point-min))
7497 (while (re-search-forward "^\\*\\*+ " nil t)
7498 (setq n (- (length (match-string 0)) 2))
7499 (while (>= (setq n (1- n)) 0)
7500 (org-demote))
7501 (end-of-line 1))))))
7503 (defun org-convert-to-oddeven-levels ()
7504 "Convert an org-mode file with only odd levels to one with odd/even levels.
7505 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7506 file contains a section with an even level, conversion would
7507 destroy the structure of the file. An error is signaled in this
7508 case."
7509 (interactive)
7510 (goto-char (point-min))
7511 ;; First check if there are no even levels
7512 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7513 (org-show-context t)
7514 (error "Not all levels are odd in this file. Conversion not possible"))
7515 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
7516 (let ((outline-regexp org-outline-regexp)
7517 (outline-level 'org-outline-level)
7518 (org-odd-levels-only nil) n)
7519 (save-excursion
7520 (goto-char (point-min))
7521 (while (re-search-forward "^\\*\\*+ " nil t)
7522 (setq n (/ (1- (length (match-string 0))) 2))
7523 (while (>= (setq n (1- n)) 0)
7524 (org-promote))
7525 (end-of-line 1))))))
7527 (defun org-tr-level (n)
7528 "Make N odd if required."
7529 (if org-odd-levels-only (1+ (/ n 2)) n))
7531 ;;; Vertical tree motion, cutting and pasting of subtrees
7533 (defun org-move-subtree-up (&optional arg)
7534 "Move the current subtree up past ARG headlines of the same level."
7535 (interactive "p")
7536 (org-move-subtree-down (- (prefix-numeric-value arg))))
7538 (defun org-move-subtree-down (&optional arg)
7539 "Move the current subtree down past ARG headlines of the same level."
7540 (interactive "p")
7541 (setq arg (prefix-numeric-value arg))
7542 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
7543 'org-get-last-sibling))
7544 (ins-point (make-marker))
7545 (cnt (abs arg))
7546 (col (current-column))
7547 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
7548 ;; Select the tree
7549 (org-back-to-heading)
7550 (setq beg0 (point))
7551 (save-excursion
7552 (setq ne-beg (org-back-over-empty-lines))
7553 (setq beg (point)))
7554 (save-match-data
7555 (save-excursion (outline-end-of-heading)
7556 (setq folded (outline-invisible-p)))
7557 (outline-end-of-subtree))
7558 (outline-next-heading)
7559 (setq ne-end (org-back-over-empty-lines))
7560 (setq end (point))
7561 (goto-char beg0)
7562 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
7563 ;; include less whitespace
7564 (save-excursion
7565 (goto-char beg)
7566 (forward-line (- ne-beg ne-end))
7567 (setq beg (point))))
7568 ;; Find insertion point, with error handling
7569 (while (> cnt 0)
7570 (or (and (funcall movfunc) (looking-at org-outline-regexp))
7571 (progn (goto-char beg0)
7572 (error "Cannot move past superior level or buffer limit")))
7573 (setq cnt (1- cnt)))
7574 (if (> arg 0)
7575 ;; Moving forward - still need to move over subtree
7576 (progn (org-end-of-subtree t t)
7577 (save-excursion
7578 (org-back-over-empty-lines)
7579 (or (bolp) (newline)))))
7580 (setq ne-ins (org-back-over-empty-lines))
7581 (move-marker ins-point (point))
7582 (setq txt (buffer-substring beg end))
7583 (org-save-markers-in-region beg end)
7584 (delete-region beg end)
7585 (org-remove-empty-overlays-at beg)
7586 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
7587 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
7588 (and (not (bolp)) (looking-at "\n") (forward-char 1))
7589 (let ((bbb (point)))
7590 (insert-before-markers txt)
7591 (org-reinstall-markers-in-region bbb)
7592 (move-marker ins-point bbb))
7593 (or (bolp) (insert "\n"))
7594 (setq ins-end (point))
7595 (goto-char ins-point)
7596 (org-skip-whitespace)
7597 (when (and (< arg 0)
7598 (org-first-sibling-p)
7599 (> ne-ins ne-beg))
7600 ;; Move whitespace back to beginning
7601 (save-excursion
7602 (goto-char ins-end)
7603 (let ((kill-whole-line t))
7604 (kill-line (- ne-ins ne-beg)) (point)))
7605 (insert (make-string (- ne-ins ne-beg) ?\n)))
7606 (move-marker ins-point nil)
7607 (if folded
7608 (hide-subtree)
7609 (org-show-entry)
7610 (show-children)
7611 (org-cycle-hide-drawers 'children))
7612 (org-clean-visibility-after-subtree-move)
7613 ;; move back to the initial column we were at
7614 (move-to-column col)))
7616 (defvar org-subtree-clip ""
7617 "Clipboard for cut and paste of subtrees.
7618 This is actually only a copy of the kill, because we use the normal kill
7619 ring. We need it to check if the kill was created by `org-copy-subtree'.")
7621 (defvar org-subtree-clip-folded nil
7622 "Was the last copied subtree folded?
7623 This is used to fold the tree back after pasting.")
7625 (defun org-cut-subtree (&optional n)
7626 "Cut the current subtree into the clipboard.
7627 With prefix arg N, cut this many sequential subtrees.
7628 This is a short-hand for marking the subtree and then cutting it."
7629 (interactive "p")
7630 (org-copy-subtree n 'cut))
7632 (defun org-copy-subtree (&optional n cut force-store-markers)
7633 "Cut the current subtree into the clipboard.
7634 With prefix arg N, cut this many sequential subtrees.
7635 This is a short-hand for marking the subtree and then copying it.
7636 If CUT is non-nil, actually cut the subtree.
7637 If FORCE-STORE-MARKERS is non-nil, store the relative locations
7638 of some markers in the region, even if CUT is non-nil. This is
7639 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
7640 (interactive "p")
7641 (let (beg end folded (beg0 (point)))
7642 (if (org-called-interactively-p 'any)
7643 (org-back-to-heading nil) ; take what looks like a subtree
7644 (org-back-to-heading t)) ; take what is really there
7645 (org-back-over-empty-lines)
7646 (setq beg (point))
7647 (skip-chars-forward " \t\r\n")
7648 (save-match-data
7649 (save-excursion (outline-end-of-heading)
7650 (setq folded (outline-invisible-p)))
7651 (condition-case nil
7652 (org-forward-same-level (1- n) t)
7653 (error nil))
7654 (org-end-of-subtree t t))
7655 (org-back-over-empty-lines)
7656 (setq end (point))
7657 (goto-char beg0)
7658 (when (> end beg)
7659 (setq org-subtree-clip-folded folded)
7660 (when (or cut force-store-markers)
7661 (org-save-markers-in-region beg end))
7662 (if cut (kill-region beg end) (copy-region-as-kill beg end))
7663 (setq org-subtree-clip (current-kill 0))
7664 (message "%s: Subtree(s) with %d characters"
7665 (if cut "Cut" "Copied")
7666 (length org-subtree-clip)))))
7668 (defun org-paste-subtree (&optional level tree for-yank)
7669 "Paste the clipboard as a subtree, with modification of headline level.
7670 The entire subtree is promoted or demoted in order to match a new headline
7671 level.
7673 If the cursor is at the beginning of a headline, the same level as
7674 that headline is used to paste the tree
7676 If not, the new level is derived from the *visible* headings
7677 before and after the insertion point, and taken to be the inferior headline
7678 level of the two. So if the previous visible heading is level 3 and the
7679 next is level 4 (or vice versa), level 4 will be used for insertion.
7680 This makes sure that the subtree remains an independent subtree and does
7681 not swallow low level entries.
7683 You can also force a different level, either by using a numeric prefix
7684 argument, or by inserting the heading marker by hand. For example, if the
7685 cursor is after \"*****\", then the tree will be shifted to level 5.
7687 If optional TREE is given, use this text instead of the kill ring.
7689 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
7690 move back over whitespace before inserting, and move point to the end of
7691 the inserted text when done."
7692 (interactive "P")
7693 (setq tree (or tree (and kill-ring (current-kill 0))))
7694 (unless (org-kill-is-subtree-p tree)
7695 (error "%s"
7696 (substitute-command-keys
7697 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
7698 (org-with-limited-levels
7699 (let* ((visp (not (outline-invisible-p)))
7700 (txt tree)
7701 (^re_ "\\(\\*+\\)[ \t]*")
7702 (old-level (if (string-match org-outline-regexp-bol txt)
7703 (- (match-end 0) (match-beginning 0) 1)
7704 -1))
7705 (force-level (cond (level (prefix-numeric-value level))
7706 ((and (looking-at "[ \t]*$")
7707 (string-match
7708 "^\\*+$" (buffer-substring
7709 (point-at-bol) (point))))
7710 (- (match-end 1) (match-beginning 1)))
7711 ((and (bolp)
7712 (looking-at org-outline-regexp))
7713 (- (match-end 0) (point) 1))
7714 (t nil)))
7715 (previous-level (save-excursion
7716 (condition-case nil
7717 (progn
7718 (outline-previous-visible-heading 1)
7719 (if (looking-at ^re_)
7720 (- (match-end 0) (match-beginning 0) 1)
7722 (error 1))))
7723 (next-level (save-excursion
7724 (condition-case nil
7725 (progn
7726 (or (looking-at org-outline-regexp)
7727 (outline-next-visible-heading 1))
7728 (if (looking-at ^re_)
7729 (- (match-end 0) (match-beginning 0) 1)
7731 (error 1))))
7732 (new-level (or force-level (max previous-level next-level)))
7733 (shift (if (or (= old-level -1)
7734 (= new-level -1)
7735 (= old-level new-level))
7737 (- new-level old-level)))
7738 (delta (if (> shift 0) -1 1))
7739 (func (if (> shift 0) 'org-demote 'org-promote))
7740 (org-odd-levels-only nil)
7741 beg end newend)
7742 ;; Remove the forced level indicator
7743 (if force-level
7744 (delete-region (point-at-bol) (point)))
7745 ;; Paste
7746 (beginning-of-line (if (bolp) 1 2))
7747 (unless for-yank (org-back-over-empty-lines))
7748 (setq beg (point))
7749 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
7750 (insert-before-markers txt)
7751 (unless (string-match "\n\\'" txt) (insert "\n"))
7752 (setq newend (point))
7753 (org-reinstall-markers-in-region beg)
7754 (setq end (point))
7755 (goto-char beg)
7756 (skip-chars-forward " \t\n\r")
7757 (setq beg (point))
7758 (if (and (outline-invisible-p) visp)
7759 (save-excursion (outline-show-heading)))
7760 ;; Shift if necessary
7761 (unless (= shift 0)
7762 (save-restriction
7763 (narrow-to-region beg end)
7764 (while (not (= shift 0))
7765 (org-map-region func (point-min) (point-max))
7766 (setq shift (+ delta shift)))
7767 (goto-char (point-min))
7768 (setq newend (point-max))))
7769 (when (or (org-called-interactively-p 'interactive) for-yank)
7770 (message "Clipboard pasted as level %d subtree" new-level))
7771 (if (and (not for-yank) ; in this case, org-yank will decide about folding
7772 kill-ring
7773 (eq org-subtree-clip (current-kill 0))
7774 org-subtree-clip-folded)
7775 ;; The tree was folded before it was killed/copied
7776 (hide-subtree))
7777 (and for-yank (goto-char newend)))))
7779 (defun org-kill-is-subtree-p (&optional txt)
7780 "Check if the current kill is an outline subtree, or a set of trees.
7781 Returns nil if kill does not start with a headline, or if the first
7782 headline level is not the largest headline level in the tree.
7783 So this will actually accept several entries of equal levels as well,
7784 which is OK for `org-paste-subtree'.
7785 If optional TXT is given, check this string instead of the current kill."
7786 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
7787 (re (org-get-limited-outline-regexp))
7788 (^re (concat "^" re))
7789 (start-level (and kill
7790 (string-match
7791 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
7792 kill)
7793 (- (match-end 2) (match-beginning 2) 1)))
7794 (start (1+ (or (match-beginning 2) -1))))
7795 (if (not start-level)
7796 (progn
7797 nil) ;; does not even start with a heading
7798 (catch 'exit
7799 (while (setq start (string-match ^re kill (1+ start)))
7800 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
7801 (throw 'exit nil)))
7802 t))))
7804 (defvar org-markers-to-move nil
7805 "Markers that should be moved with a cut-and-paste operation.
7806 Those markers are stored together with their positions relative to
7807 the start of the region.")
7809 (defun org-save-markers-in-region (beg end)
7810 "Check markers in region.
7811 If these markers are between BEG and END, record their position relative
7812 to BEG, so that after moving the block of text, we can put the markers back
7813 into place.
7814 This function gets called just before an entry or tree gets cut from the
7815 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
7816 called immediately, to move the markers with the entries."
7817 (setq org-markers-to-move nil)
7818 (when (featurep 'org-clock)
7819 (org-clock-save-markers-for-cut-and-paste beg end))
7820 (when (featurep 'org-agenda)
7821 (org-agenda-save-markers-for-cut-and-paste beg end)))
7823 (defun org-check-and-save-marker (marker beg end)
7824 "Check if MARKER is between BEG and END.
7825 If yes, remember the marker and the distance to BEG."
7826 (when (and (marker-buffer marker)
7827 (equal (marker-buffer marker) (current-buffer)))
7828 (if (and (>= marker beg) (< marker end))
7829 (push (cons marker (- marker beg)) org-markers-to-move))))
7831 (defun org-reinstall-markers-in-region (beg)
7832 "Move all remembered markers to their position relative to BEG."
7833 (mapc (lambda (x)
7834 (move-marker (car x) (+ beg (cdr x))))
7835 org-markers-to-move)
7836 (setq org-markers-to-move nil))
7838 (defun org-narrow-to-subtree ()
7839 "Narrow buffer to the current subtree."
7840 (interactive)
7841 (save-excursion
7842 (save-match-data
7843 (org-with-limited-levels
7844 (narrow-to-region
7845 (progn (org-back-to-heading t) (point))
7846 (progn (org-end-of-subtree t t)
7847 (if (and (org-on-heading-p) (not (eobp))) (backward-char 1))
7848 (point)))))))
7850 (defun org-narrow-to-block ()
7851 "Narrow buffer to the current block."
7852 (interactive)
7853 (let* ((case-fold-search t)
7854 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
7855 "^[ \t]*#\\+end_.*")))
7856 (if blockp
7857 (narrow-to-region (car blockp) (cdr blockp))
7858 (error "Not in a block"))))
7860 (eval-when-compile
7861 (defvar org-property-drawer-re))
7863 (defvar org-property-start-re) ;; defined below
7864 (defun org-clone-subtree-with-time-shift (n &optional shift)
7865 "Clone the task (subtree) at point N times.
7866 The clones will be inserted as siblings.
7868 In interactive use, the user will be prompted for the number of
7869 clones to be produced, and for a time SHIFT, which may be a
7870 repeater as used in time stamps, for example `+3d'.
7872 When a valid repeater is given and the entry contains any time
7873 stamps, the clones will become a sequence in time, with time
7874 stamps in the subtree shifted for each clone produced. If SHIFT
7875 is nil or the empty string, time stamps will be left alone. The
7876 ID property of the original subtree is removed.
7878 If the original subtree did contain time stamps with a repeater,
7879 the following will happen:
7880 - the repeater will be removed in each clone
7881 - an additional clone will be produced, with the current, unshifted
7882 date(s) in the entry.
7883 - the original entry will be placed *after* all the clones, with
7884 repeater intact.
7885 - the start days in the repeater in the original entry will be shifted
7886 to past the last clone.
7887 I this way you can spell out a number of instances of a repeating task,
7888 and still retain the repeater to cover future instances of the task."
7889 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
7890 (let (beg end template task idprop
7891 shift-n shift-what doshift nmin nmax (n-no-remove -1))
7892 (if (not (and (integerp n) (> n 0)))
7893 (error "Invalid number of replications %s" n))
7894 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
7895 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
7896 shift)))
7897 (error "Invalid shift specification %s" shift))
7898 (when doshift
7899 (setq shift-n (string-to-number (match-string 1 shift))
7900 shift-what (cdr (assoc (match-string 2 shift)
7901 '(("d" . day) ("w" . week)
7902 ("m" . month) ("y" . year))))))
7903 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
7904 (setq nmin 1 nmax n)
7905 (org-back-to-heading t)
7906 (setq beg (point))
7907 (setq idprop (org-entry-get nil "ID"))
7908 (org-end-of-subtree t t)
7909 (or (bolp) (insert "\n"))
7910 (setq end (point))
7911 (setq template (buffer-substring beg end))
7912 ;; Remove clocks and empty drawers
7913 (with-temp-buffer
7914 (insert template)
7915 (goto-char (point-min))
7916 (while (re-search-forward
7917 "^[ \t]*CLOCK:.*$" (save-excursion (org-end-of-subtree t t)) t)
7918 (replace-match "")
7919 (kill-whole-line))
7920 (goto-char (point-min))
7921 (while (re-search-forward
7922 (concat "^[ \t]*:" (regexp-opt org-drawers) ":[ \t]*$") nil t)
7923 (mapc (lambda(d) (org-remove-empty-drawer-at d (point))) org-drawers))
7924 (setq template (buffer-substring (point-min) (point-max))))
7925 (when (and doshift
7926 (string-match "<[^<>\n]+ \\+[0-9]+[dwmy][^<>\n]*>" template))
7927 (delete-region beg end)
7928 (setq end beg)
7929 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
7930 (goto-char end)
7931 (loop for n from nmin to nmax do
7932 ;; prepare clone
7933 (with-temp-buffer
7934 (insert template)
7935 (org-mode)
7936 (goto-char (point-min))
7937 (and idprop (if org-clone-delete-id
7938 (org-entry-delete nil "ID")
7939 (org-id-get-create t)))
7940 (while (re-search-forward org-property-start-re nil t)
7941 (org-remove-empty-drawer-at "PROPERTIES" (point)))
7942 (goto-char (point-min))
7943 (when doshift
7944 (while (re-search-forward org-ts-regexp-both nil t)
7945 (org-timestamp-change (* n shift-n) shift-what))
7946 (unless (= n n-no-remove)
7947 (goto-char (point-min))
7948 (while (re-search-forward org-ts-regexp nil t)
7949 (save-excursion
7950 (goto-char (match-beginning 0))
7951 (if (looking-at "<[^<>\n]+\\( +\\+[0-9]+[dwmy]\\)")
7952 (delete-region (match-beginning 1) (match-end 1)))))))
7953 (setq task (buffer-string)))
7954 (insert task))
7955 (goto-char beg)))
7957 ;;; Outline Sorting
7959 (defun org-sort (with-case)
7960 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
7961 Optional argument WITH-CASE means sort case-sensitively.
7962 With a double prefix argument, also remove duplicate entries."
7963 (interactive "P")
7964 (cond
7965 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
7966 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
7968 (org-call-with-arg 'org-sort-entries with-case))))
7970 (defun org-sort-remove-invisible (s)
7971 (remove-text-properties 0 (length s) org-rm-props s)
7972 (while (string-match org-bracket-link-regexp s)
7973 (setq s (replace-match (if (match-end 2)
7974 (match-string 3 s)
7975 (match-string 1 s)) t t s)))
7978 (defvar org-priority-regexp) ; defined later in the file
7980 (defvar org-after-sorting-entries-or-items-hook nil
7981 "Hook that is run after a bunch of entries or items have been sorted.
7982 When children are sorted, the cursor is in the parent line when this
7983 hook gets called. When a region or a plain list is sorted, the cursor
7984 will be in the first entry of the sorted region/list.")
7986 (defun org-sort-entries
7987 (&optional with-case sorting-type getkey-func compare-func property)
7988 "Sort entries on a certain level of an outline tree.
7989 If there is an active region, the entries in the region are sorted.
7990 Else, if the cursor is before the first entry, sort the top-level items.
7991 Else, the children of the entry at point are sorted.
7993 Sorting can be alphabetically, numerically, by date/time as given by
7994 a time stamp, by a property or by priority.
7996 The command prompts for the sorting type unless it has been given to the
7997 function through the SORTING-TYPE argument, which needs to be a character,
7998 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F). Here is the
7999 precise meaning of each character:
8001 n Numerically, by converting the beginning of the entry/item to a number.
8002 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8003 t By date/time, either the first active time stamp in the entry, or, if
8004 none exist, by the first inactive one.
8005 s By the scheduled date/time.
8006 d By deadline date/time.
8007 c By creation time, which is assumed to be the first inactive time stamp
8008 at the beginning of a line.
8009 p By priority according to the cookie.
8010 r By the value of a property.
8012 Capital letters will reverse the sort order.
8014 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8015 called with point at the beginning of the record. It must return either
8016 a string or a number that should serve as the sorting key for that record.
8018 Comparing entries ignores case by default. However, with an optional argument
8019 WITH-CASE, the sorting considers case as well."
8020 (interactive "P")
8021 (let ((case-func (if with-case 'identity 'downcase))
8022 start beg end stars re re2
8023 txt what tmp)
8024 ;; Find beginning and end of region to sort
8025 (cond
8026 ((org-region-active-p)
8027 ;; we will sort the region
8028 (setq end (region-end)
8029 what "region")
8030 (goto-char (region-beginning))
8031 (if (not (org-on-heading-p)) (outline-next-heading))
8032 (setq start (point)))
8033 ((or (org-on-heading-p)
8034 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8035 ;; we will sort the children of the current headline
8036 (org-back-to-heading)
8037 (setq start (point)
8038 end (progn (org-end-of-subtree t t)
8039 (or (bolp) (insert "\n"))
8040 (org-back-over-empty-lines)
8041 (point))
8042 what "children")
8043 (goto-char start)
8044 (show-subtree)
8045 (outline-next-heading))
8047 ;; we will sort the top-level entries in this file
8048 (goto-char (point-min))
8049 (or (org-on-heading-p) (outline-next-heading))
8050 (setq start (point))
8051 (goto-char (point-max))
8052 (beginning-of-line 1)
8053 (when (looking-at ".*?\\S-")
8054 ;; File ends in a non-white line
8055 (end-of-line 1)
8056 (insert "\n"))
8057 (setq end (point-max))
8058 (setq what "top-level")
8059 (goto-char start)
8060 (show-all)))
8062 (setq beg (point))
8063 (if (>= beg end) (error "Nothing to sort"))
8065 (looking-at "\\(\\*+\\)")
8066 (setq stars (match-string 1)
8067 re (concat "^" (regexp-quote stars) " +")
8068 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8069 txt (buffer-substring beg end))
8070 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8071 (if (and (not (equal stars "*")) (string-match re2 txt))
8072 (error "Region to sort contains a level above the first entry"))
8074 (unless sorting-type
8075 (message
8076 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8077 [t]ime [s]cheduled [d]eadline [c]reated
8078 A/N/T/S/D/C/P/O/F means reversed:"
8079 what)
8080 (setq sorting-type (read-char-exclusive))
8082 (and (= (downcase sorting-type) ?f)
8083 (setq getkey-func
8084 (org-icompleting-read "Sort using function: "
8085 obarray 'fboundp t nil nil))
8086 (setq getkey-func (intern getkey-func)))
8088 (and (= (downcase sorting-type) ?r)
8089 (setq property
8090 (org-icompleting-read "Property: "
8091 (mapcar 'list (org-buffer-property-keys t))
8092 nil t))))
8094 (message "Sorting entries...")
8096 (save-restriction
8097 (narrow-to-region start end)
8098 (let ((dcst (downcase sorting-type))
8099 (case-fold-search nil)
8100 (now (current-time)))
8101 (sort-subr
8102 (/= dcst sorting-type)
8103 ;; This function moves to the beginning character of the "record" to
8104 ;; be sorted.
8105 (lambda nil
8106 (if (re-search-forward re nil t)
8107 (goto-char (match-beginning 0))
8108 (goto-char (point-max))))
8109 ;; This function moves to the last character of the "record" being
8110 ;; sorted.
8111 (lambda nil
8112 (save-match-data
8113 (condition-case nil
8114 (outline-forward-same-level 1)
8115 (error
8116 (goto-char (point-max))))))
8117 ;; This function returns the value that gets sorted against.
8118 (lambda nil
8119 (cond
8120 ((= dcst ?n)
8121 (if (looking-at org-complex-heading-regexp)
8122 (string-to-number (match-string 4))
8123 nil))
8124 ((= dcst ?a)
8125 (if (looking-at org-complex-heading-regexp)
8126 (funcall case-func (match-string 4))
8127 nil))
8128 ((= dcst ?t)
8129 (let ((end (save-excursion (outline-next-heading) (point))))
8130 (if (or (re-search-forward org-ts-regexp end t)
8131 (re-search-forward org-ts-regexp-both end t))
8132 (org-time-string-to-seconds (match-string 0))
8133 (org-float-time now))))
8134 ((= dcst ?c)
8135 (let ((end (save-excursion (outline-next-heading) (point))))
8136 (if (re-search-forward
8137 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8138 end t)
8139 (org-time-string-to-seconds (match-string 0))
8140 (org-float-time now))))
8141 ((= dcst ?s)
8142 (let ((end (save-excursion (outline-next-heading) (point))))
8143 (if (re-search-forward org-scheduled-time-regexp end t)
8144 (org-time-string-to-seconds (match-string 1))
8145 (org-float-time now))))
8146 ((= dcst ?d)
8147 (let ((end (save-excursion (outline-next-heading) (point))))
8148 (if (re-search-forward org-deadline-time-regexp end t)
8149 (org-time-string-to-seconds (match-string 1))
8150 (org-float-time now))))
8151 ((= dcst ?p)
8152 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8153 (string-to-char (match-string 2))
8154 org-default-priority))
8155 ((= dcst ?r)
8156 (or (org-entry-get nil property) ""))
8157 ((= dcst ?o)
8158 (if (looking-at org-complex-heading-regexp)
8159 (- 9999 (length (member (match-string 2)
8160 org-todo-keywords-1)))))
8161 ((= dcst ?f)
8162 (if getkey-func
8163 (progn
8164 (setq tmp (funcall getkey-func))
8165 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8166 tmp)
8167 (error "Invalid key function `%s'" getkey-func)))
8168 (t (error "Invalid sorting type `%c'" sorting-type))))
8170 (cond
8171 ((= dcst ?a) 'string<)
8172 ((= dcst ?f) compare-func)
8173 ((member dcst '(?p ?t ?s ?d ?c)) '<)
8174 (t nil)))))
8175 (run-hooks 'org-after-sorting-entries-or-items-hook)
8176 (message "Sorting entries...done")))
8178 (defun org-do-sort (table what &optional with-case sorting-type)
8179 "Sort TABLE of WHAT according to SORTING-TYPE.
8180 The user will be prompted for the SORTING-TYPE if the call to this
8181 function does not specify it. WHAT is only for the prompt, to indicate
8182 what is being sorted. The sorting key will be extracted from
8183 the car of the elements of the table.
8184 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8185 (unless sorting-type
8186 (message
8187 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
8188 what)
8189 (setq sorting-type (read-char-exclusive)))
8190 (let ((dcst (downcase sorting-type))
8191 extractfun comparefun)
8192 ;; Define the appropriate functions
8193 (cond
8194 ((= dcst ?n)
8195 (setq extractfun 'string-to-number
8196 comparefun (if (= dcst sorting-type) '< '>)))
8197 ((= dcst ?a)
8198 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8199 (lambda(x) (downcase (org-sort-remove-invisible x))))
8200 comparefun (if (= dcst sorting-type)
8201 'string<
8202 (lambda (a b) (and (not (string< a b))
8203 (not (string= a b)))))))
8204 ((= dcst ?t)
8205 (setq extractfun
8206 (lambda (x)
8207 (if (or (string-match org-ts-regexp x)
8208 (string-match org-ts-regexp-both x))
8209 (org-float-time
8210 (org-time-string-to-time (match-string 0 x)))
8212 comparefun (if (= dcst sorting-type) '< '>)))
8213 (t (error "Invalid sorting type `%c'" sorting-type)))
8215 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8216 table)
8217 (lambda (a b) (funcall comparefun (car a) (car b))))))
8220 ;;; The orgstruct minor mode
8222 ;; Define a minor mode which can be used in other modes in order to
8223 ;; integrate the org-mode structure editing commands.
8225 ;; This is really a hack, because the org-mode structure commands use
8226 ;; keys which normally belong to the major mode. Here is how it
8227 ;; works: The minor mode defines all the keys necessary to operate the
8228 ;; structure commands, but wraps the commands into a function which
8229 ;; tests if the cursor is currently at a headline or a plain list
8230 ;; item. If that is the case, the structure command is used,
8231 ;; temporarily setting many Org-mode variables like regular
8232 ;; expressions for filling etc. However, when any of those keys is
8233 ;; used at a different location, function uses `key-binding' to look
8234 ;; up if the key has an associated command in another currently active
8235 ;; keymap (minor modes, major mode, global), and executes that
8236 ;; command. There might be problems if any of the keys is otherwise
8237 ;; used as a prefix key.
8239 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
8240 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
8241 ;; addresses this by checking explicitly for both bindings.
8243 (defvar orgstruct-mode-map (make-sparse-keymap)
8244 "Keymap for the minor `orgstruct-mode'.")
8246 (defvar org-local-vars nil
8247 "List of local variables, for use by `orgstruct-mode'.")
8249 ;;;###autoload
8250 (define-minor-mode orgstruct-mode
8251 "Toggle the minor mode `orgstruct-mode'.
8252 This mode is for using Org-mode structure commands in other
8253 modes. The following keys behave as if Org-mode were active, if
8254 the cursor is on a headline, or on a plain list item (both as
8255 defined by Org-mode).
8257 M-up Move entry/item up
8258 M-down Move entry/item down
8259 M-left Promote
8260 M-right Demote
8261 M-S-up Move entry/item up
8262 M-S-down Move entry/item down
8263 M-S-left Promote subtree
8264 M-S-right Demote subtree
8265 M-q Fill paragraph and items like in Org-mode
8266 C-c ^ Sort entries
8267 C-c - Cycle list bullet
8268 TAB Cycle item visibility
8269 M-RET Insert new heading/item
8270 S-M-RET Insert new TODO heading / Checkbox item
8271 C-c C-c Set tags / toggle checkbox"
8272 nil " OrgStruct" nil
8273 (org-load-modules-maybe)
8274 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
8276 ;;;###autoload
8277 (defun turn-on-orgstruct ()
8278 "Unconditionally turn on `orgstruct-mode'."
8279 (orgstruct-mode 1))
8281 (defun orgstruct++-mode (&optional arg)
8282 "Toggle `orgstruct-mode', the enhanced version of it.
8283 In addition to setting orgstruct-mode, this also exports all indentation
8284 and autofilling variables from org-mode into the buffer. It will also
8285 recognize item context in multiline items.
8286 Note that turning off orgstruct-mode will *not* remove the
8287 indentation/paragraph settings. This can only be done by refreshing the
8288 major mode, for example with \\[normal-mode]."
8289 (interactive "P")
8290 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8291 (if (< arg 1)
8292 (orgstruct-mode -1)
8293 (orgstruct-mode 1)
8294 (let (var val)
8295 (mapc
8296 (lambda (x)
8297 (when (string-match
8298 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
8299 (symbol-name (car x)))
8300 (setq var (car x) val (nth 1 x))
8301 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8302 org-local-vars)
8303 (org-set-local 'orgstruct-is-++ t))))
8305 (defvar orgstruct-is-++ nil
8306 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8307 (make-variable-buffer-local 'orgstruct-is-++)
8309 ;;;###autoload
8310 (defun turn-on-orgstruct++ ()
8311 "Unconditionally turn on `orgstruct++-mode'."
8312 (orgstruct++-mode 1))
8314 (defun orgstruct-error ()
8315 "Error when there is no default binding for a structure key."
8316 (interactive)
8317 (error "This key has no function outside structure elements"))
8319 (defun orgstruct-setup ()
8320 "Setup orgstruct keymaps."
8321 (let ((nfunc 0)
8322 (bindings
8323 (list
8324 '([(meta up)] org-metaup)
8325 '([(meta down)] org-metadown)
8326 '([(meta left)] org-metaleft)
8327 '([(meta right)] org-metaright)
8328 '([(meta shift up)] org-shiftmetaup)
8329 '([(meta shift down)] org-shiftmetadown)
8330 '([(meta shift left)] org-shiftmetaleft)
8331 '([(meta shift right)] org-shiftmetaright)
8332 '([?\e (up)] org-metaup)
8333 '([?\e (down)] org-metadown)
8334 '([?\e (left)] org-metaleft)
8335 '([?\e (right)] org-metaright)
8336 '([?\e (shift up)] org-shiftmetaup)
8337 '([?\e (shift down)] org-shiftmetadown)
8338 '([?\e (shift left)] org-shiftmetaleft)
8339 '([?\e (shift right)] org-shiftmetaright)
8340 '([(shift up)] org-shiftup)
8341 '([(shift down)] org-shiftdown)
8342 '([(shift left)] org-shiftleft)
8343 '([(shift right)] org-shiftright)
8344 '("\C-c\C-c" org-ctrl-c-ctrl-c)
8345 '("\M-q" fill-paragraph)
8346 '("\C-c^" org-sort)
8347 '("\C-c-" org-cycle-list-bullet)))
8348 elt key fun cmd)
8349 (while (setq elt (pop bindings))
8350 (setq nfunc (1+ nfunc))
8351 (setq key (org-key (car elt))
8352 fun (nth 1 elt)
8353 cmd (orgstruct-make-binding fun nfunc key))
8354 (org-defkey orgstruct-mode-map key cmd))
8356 ;; Special treatment needed for TAB and RET
8357 (org-defkey orgstruct-mode-map [(tab)]
8358 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
8359 (org-defkey orgstruct-mode-map "\C-i"
8360 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
8362 (org-defkey orgstruct-mode-map "\M-\C-m"
8363 (orgstruct-make-binding 'org-insert-heading 105
8364 "\M-\C-m" [(meta return)]))
8365 (org-defkey orgstruct-mode-map [(meta return)]
8366 (orgstruct-make-binding 'org-insert-heading 106
8367 [(meta return)] "\M-\C-m"))
8369 (org-defkey orgstruct-mode-map [(shift meta return)]
8370 (orgstruct-make-binding 'org-insert-todo-heading 107
8371 [(meta return)] "\M-\C-m"))
8373 (org-defkey orgstruct-mode-map "\e\C-m"
8374 (orgstruct-make-binding 'org-insert-heading 108
8375 "\e\C-m" [?\e (return)]))
8376 (org-defkey orgstruct-mode-map [?\e (return)]
8377 (orgstruct-make-binding 'org-insert-heading 109
8378 [?\e (return)] "\e\C-m"))
8379 (org-defkey orgstruct-mode-map [?\e (shift return)]
8380 (orgstruct-make-binding 'org-insert-todo-heading 110
8381 [?\e (return)] "\e\C-m"))
8383 (unless org-local-vars
8384 (setq org-local-vars (org-get-local-variables)))
8388 (defun orgstruct-make-binding (fun n &rest keys)
8389 "Create a function for binding in the structure minor mode.
8390 FUN is the command to call inside a table. N is used to create a unique
8391 command name. KEYS are keys that should be checked in for a command
8392 to execute outside of tables."
8393 (eval
8394 (list 'defun
8395 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
8396 '(arg)
8397 (concat "In Structure, run `" (symbol-name fun) "'.\n"
8398 "Outside of structure, run the binding of `"
8399 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
8400 "'.")
8401 '(interactive "p")
8402 (list 'if
8403 `(org-context-p 'headline 'item
8404 (and orgstruct-is-++
8405 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
8406 'item-body))
8407 (list 'org-run-like-in-org-mode (list 'quote fun))
8408 (list 'let '(orgstruct-mode)
8409 (list 'call-interactively
8410 (append '(or)
8411 (mapcar (lambda (k)
8412 (list 'key-binding k))
8413 keys)
8414 '('orgstruct-error))))))))
8416 (defun org-context-p (&rest contexts)
8417 "Check if local context is any of CONTEXTS.
8418 Possible values in the list of contexts are `table', `headline', and `item'."
8419 (let ((pos (point)))
8420 (goto-char (point-at-bol))
8421 (prog1 (or (and (memq 'table contexts)
8422 (looking-at "[ \t]*|"))
8423 (and (memq 'headline contexts)
8424 (looking-at org-outline-regexp))
8425 (and (memq 'item contexts)
8426 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
8427 (and (memq 'item-body contexts)
8428 (org-in-item-p)))
8429 (goto-char pos))))
8431 (defun org-get-local-variables ()
8432 "Return a list of all local variables in an org-mode buffer."
8433 (let (varlist)
8434 (with-current-buffer (get-buffer-create "*Org tmp*")
8435 (erase-buffer)
8436 (org-mode)
8437 (setq varlist (buffer-local-variables)))
8438 (kill-buffer "*Org tmp*")
8439 (delq nil
8440 (mapcar
8441 (lambda (x)
8442 (setq x
8443 (if (symbolp x)
8444 (list x)
8445 (list (car x) (list 'quote (cdr x)))))
8446 (if (string-match
8447 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
8448 (symbol-name (car x)))
8449 x nil))
8450 varlist))))
8452 (defun org-clone-local-variables (from-buffer &optional regexp)
8453 "Clone local variables from FROM-BUFFER.
8454 Optional argument REGEXP selects variables to clone."
8455 (mapc
8456 (lambda (pair)
8457 (and (symbolp (car pair))
8458 (or (null regexp)
8459 (string-match regexp (symbol-name (car pair))))
8460 (set (make-local-variable (car pair))
8461 (cdr pair))))
8462 (buffer-local-variables from-buffer)))
8464 ;;;###autoload
8465 (defun org-run-like-in-org-mode (cmd)
8466 "Run a command, pretending that the current buffer is in Org-mode.
8467 This will temporarily bind local variables that are typically bound in
8468 Org-mode to the values they have in Org-mode, and then interactively
8469 call CMD."
8470 (org-load-modules-maybe)
8471 (unless org-local-vars
8472 (setq org-local-vars (org-get-local-variables)))
8473 (eval (list 'let org-local-vars
8474 (list 'call-interactively (list 'quote cmd)))))
8476 ;;;; Archiving
8478 (defun org-get-category (&optional pos force-refresh)
8479 "Get the category applying to position POS."
8480 (if force-refresh (org-refresh-category-properties))
8481 (let ((pos (or pos (point))))
8482 (or (get-text-property pos 'org-category)
8483 (progn (org-refresh-category-properties)
8484 (get-text-property pos 'org-category)))))
8486 (defun org-refresh-category-properties ()
8487 "Refresh category text properties in the buffer."
8488 (let ((def-cat (cond
8489 ((null org-category)
8490 (if buffer-file-name
8491 (file-name-sans-extension
8492 (file-name-nondirectory buffer-file-name))
8493 "???"))
8494 ((symbolp org-category) (symbol-name org-category))
8495 (t org-category)))
8496 beg end cat pos optionp)
8497 (org-unmodified
8498 (save-excursion
8499 (save-restriction
8500 (widen)
8501 (goto-char (point-min))
8502 (put-text-property (point) (point-max) 'org-category def-cat)
8503 (while (re-search-forward
8504 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8505 (setq pos (match-end 0)
8506 optionp (equal (char-after (match-beginning 0)) ?#)
8507 cat (org-trim (match-string 2)))
8508 (if optionp
8509 (setq beg (point-at-bol) end (point-max))
8510 (org-back-to-heading t)
8511 (setq beg (point) end (org-end-of-subtree t t)))
8512 (put-text-property beg end 'org-category cat)
8513 (put-text-property beg end 'org-category-position beg)
8514 (goto-char pos)))))))
8517 ;;;; Link Stuff
8519 ;;; Link abbreviations
8521 (defun org-link-expand-abbrev (link)
8522 "Apply replacements as defined in `org-link-abbrev-alist."
8523 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
8524 (let* ((key (match-string 1 link))
8525 (as (or (assoc key org-link-abbrev-alist-local)
8526 (assoc key org-link-abbrev-alist)))
8527 (tag (and (match-end 2) (match-string 3 link)))
8528 rpl)
8529 (if (not as)
8530 link
8531 (setq rpl (cdr as))
8532 (cond
8533 ((symbolp rpl) (funcall rpl tag))
8534 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
8535 ((string-match "%h" rpl)
8536 (replace-match (url-hexify-string (or tag "")) t t rpl))
8537 (t (concat rpl tag)))))
8538 link))
8540 ;;; Storing and inserting links
8542 (defvar org-insert-link-history nil
8543 "Minibuffer history for links inserted with `org-insert-link'.")
8545 (defvar org-stored-links nil
8546 "Contains the links stored with `org-store-link'.")
8548 (defvar org-store-link-plist nil
8549 "Plist with info about the most recently link created with `org-store-link'.")
8551 (defvar org-link-protocols nil
8552 "Link protocols added to Org-mode using `org-add-link-type'.")
8554 (defvar org-store-link-functions nil
8555 "List of functions that are called to create and store a link.
8556 Each function will be called in turn until one returns a non-nil
8557 value. Each function should check if it is responsible for creating
8558 this link (for example by looking at the major mode).
8559 If not, it must exit and return nil.
8560 If yes, it should return a non-nil value after a calling
8561 `org-store-link-props' with a list of properties and values.
8562 Special properties are:
8564 :type The link prefix, like \"http\". This must be given.
8565 :link The link, like \"http://www.astro.uva.nl/~dominik\".
8566 This is obligatory as well.
8567 :description Optional default description for the second pair
8568 of brackets in an Org-mode link. The user can still change
8569 this when inserting this link into an Org-mode buffer.
8571 In addition to these, any additional properties can be specified
8572 and then used in remember templates.")
8574 (defun org-add-link-type (type &optional follow export)
8575 "Add TYPE to the list of `org-link-types'.
8576 Re-compute all regular expressions depending on `org-link-types'
8578 FOLLOW and EXPORT are two functions.
8580 FOLLOW should take the link path as the single argument and do whatever
8581 is necessary to follow the link, for example find a file or display
8582 a mail message.
8584 EXPORT should format the link path for export to one of the export formats.
8585 It should be a function accepting three arguments:
8587 path the path of the link, the text after the prefix (like \"http:\")
8588 desc the description of the link, if any, or a description added by
8589 org-export-normalize-links if there is none
8590 format the export format, a symbol like `html' or `latex' or `ascii'..
8592 The function may use the FORMAT information to return different values
8593 depending on the format. The return value will be put literally into
8594 the exported file. If the return value is nil, this means Org should
8595 do what it normally does with links which do not have EXPORT defined.
8597 Org-mode has a built-in default for exporting links. If you are happy with
8598 this default, there is no need to define an export function for the link
8599 type. For a simple example of an export function, see `org-bbdb.el'."
8600 (add-to-list 'org-link-types type t)
8601 (org-make-link-regexps)
8602 (if (assoc type org-link-protocols)
8603 (setcdr (assoc type org-link-protocols) (list follow export))
8604 (push (list type follow export) org-link-protocols)))
8606 (defvar org-agenda-buffer-name)
8608 ;;;###autoload
8609 (defun org-store-link (arg)
8610 "\\<org-mode-map>Store an org-link to the current location.
8611 This link is added to `org-stored-links' and can later be inserted
8612 into an org-buffer with \\[org-insert-link].
8614 For some link types, a prefix arg is interpreted:
8615 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
8616 For file links, arg negates `org-context-in-file-links'."
8617 (interactive "P")
8618 (org-load-modules-maybe)
8619 (setq org-store-link-plist nil) ; reset
8620 (org-with-limited-levels
8621 (let (link cpltxt desc description search txt custom-id agenda-link)
8622 (cond
8624 ((run-hook-with-args-until-success 'org-store-link-functions)
8625 (setq link (plist-get org-store-link-plist :link)
8626 desc (or (plist-get org-store-link-plist :description) link)))
8628 ((equal (buffer-name) "*Org Edit Src Example*")
8629 (let (label gc)
8630 (while (or (not label)
8631 (save-excursion
8632 (save-restriction
8633 (widen)
8634 (goto-char (point-min))
8635 (re-search-forward
8636 (regexp-quote (format org-coderef-label-format label))
8637 nil t))))
8638 (when label (message "Label exists already") (sit-for 2))
8639 (setq label (read-string "Code line label: " label)))
8640 (end-of-line 1)
8641 (setq link (format org-coderef-label-format label))
8642 (setq gc (- 79 (length link)))
8643 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
8644 (insert link)
8645 (setq link (concat "(" label ")") desc nil)))
8647 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
8648 ;; We are in the agenda, link to referenced location
8649 (let ((m (or (get-text-property (point) 'org-hd-marker)
8650 (get-text-property (point) 'org-marker))))
8651 (when m
8652 (org-with-point-at m
8653 (setq agenda-link
8654 (if (org-called-interactively-p 'any)
8655 (call-interactively 'org-store-link)
8656 (org-store-link nil)))))))
8658 ((eq major-mode 'calendar-mode)
8659 (let ((cd (calendar-cursor-to-date)))
8660 (setq link
8661 (format-time-string
8662 (car org-time-stamp-formats)
8663 (apply 'encode-time
8664 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
8665 nil nil nil))))
8666 (org-store-link-props :type "calendar" :date cd)))
8668 ((eq major-mode 'w3-mode)
8669 (setq cpltxt (if (and (buffer-name)
8670 (not (string-match "Untitled" (buffer-name))))
8671 (buffer-name)
8672 (url-view-url t))
8673 link (org-make-link (url-view-url t)))
8674 (org-store-link-props :type "w3" :url (url-view-url t)))
8676 ((eq major-mode 'w3m-mode)
8677 (setq cpltxt (or w3m-current-title w3m-current-url)
8678 link (org-make-link w3m-current-url))
8679 (org-store-link-props :type "w3m" :url (url-view-url t)))
8681 ((setq search (run-hook-with-args-until-success
8682 'org-create-file-search-functions))
8683 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
8684 "::" search))
8685 (setq cpltxt (or description link)))
8687 ((eq major-mode 'image-mode)
8688 (setq cpltxt (concat "file:"
8689 (abbreviate-file-name buffer-file-name))
8690 link (org-make-link cpltxt))
8691 (org-store-link-props :type "image" :file buffer-file-name))
8693 ((eq major-mode 'dired-mode)
8694 ;; link to the file in the current line
8695 (let ((file (dired-get-filename nil t)))
8696 (setq file (if file
8697 (abbreviate-file-name
8698 (expand-file-name (dired-get-filename nil t)))
8699 ;; otherwise, no file so use current directory.
8700 default-directory))
8701 (setq cpltxt (concat "file:" file)
8702 link (org-make-link cpltxt))))
8704 ((and (buffer-file-name (buffer-base-buffer)) (eq major-mode 'org-mode))
8705 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
8706 (cond
8707 ((org-in-regexp "<<\\(.*?\\)>>")
8708 (setq cpltxt
8709 (concat "file:"
8710 (abbreviate-file-name
8711 (buffer-file-name (buffer-base-buffer)))
8712 "::" (match-string 1))
8713 link (org-make-link cpltxt)))
8714 ((and (featurep 'org-id)
8715 (or (eq org-link-to-org-use-id t)
8716 (and (eq org-link-to-org-use-id 'create-if-interactive)
8717 (org-called-interactively-p 'any))
8718 (and (eq org-link-to-org-use-id
8719 'create-if-interactive-and-no-custom-id)
8720 (org-called-interactively-p 'any)
8721 (not custom-id))
8722 (and org-link-to-org-use-id
8723 (org-entry-get nil "ID"))))
8724 ;; We can make a link using the ID.
8725 (setq link (condition-case nil
8726 (prog1 (org-id-store-link)
8727 (setq desc (plist-get org-store-link-plist
8728 :description)))
8729 (error
8730 ;; probably before first headline, link to file only
8731 (concat "file:"
8732 (abbreviate-file-name
8733 (buffer-file-name (buffer-base-buffer))))))))
8735 ;; Just link to current headline
8736 (setq cpltxt (concat "file:"
8737 (abbreviate-file-name
8738 (buffer-file-name (buffer-base-buffer)))))
8739 ;; Add a context search string
8740 (when (org-xor org-context-in-file-links arg)
8741 (setq txt (cond
8742 ((org-on-heading-p) nil)
8743 ((org-region-active-p)
8744 (buffer-substring (region-beginning) (region-end)))
8745 (t nil)))
8746 (when (or (null txt) (string-match "\\S-" txt))
8747 (setq cpltxt
8748 (concat cpltxt "::"
8749 (condition-case nil
8750 (org-make-org-heading-search-string txt)
8751 (error "")))
8752 desc (or (nth 4 (ignore-errors
8753 (org-heading-components))) "NONE"))))
8754 (if (string-match "::\\'" cpltxt)
8755 (setq cpltxt (substring cpltxt 0 -2)))
8756 (setq link (org-make-link cpltxt)))))
8758 ((buffer-file-name (buffer-base-buffer))
8759 ;; Just link to this file here.
8760 (setq cpltxt (concat "file:"
8761 (abbreviate-file-name
8762 (buffer-file-name (buffer-base-buffer)))))
8763 ;; Add a context string
8764 (when (org-xor org-context-in-file-links arg)
8765 (setq txt (if (org-region-active-p)
8766 (buffer-substring (region-beginning) (region-end))
8767 (buffer-substring (point-at-bol) (point-at-eol))))
8768 ;; Only use search option if there is some text.
8769 (when (string-match "\\S-" txt)
8770 (setq cpltxt
8771 (concat cpltxt "::" (org-make-org-heading-search-string txt))
8772 desc "NONE")))
8773 (setq link (org-make-link cpltxt)))
8775 ((org-called-interactively-p 'interactive)
8776 (error "Cannot link to a buffer which is not visiting a file"))
8778 (t (setq link nil)))
8780 (if (consp link) (setq cpltxt (car link) link (cdr link)))
8781 (setq link (or link cpltxt)
8782 desc (or desc cpltxt))
8783 (if (equal desc "NONE") (setq desc nil))
8785 (if (and (or (org-called-interactively-p 'any) executing-kbd-macro) link)
8786 (progn
8787 (setq org-stored-links
8788 (cons (list link desc) org-stored-links))
8789 (message "Stored: %s" (or desc link))
8790 (when custom-id
8791 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
8792 "::#" custom-id))
8793 (setq org-stored-links
8794 (cons (list link desc) org-stored-links))))
8795 (or agenda-link (and link (org-make-link-string link desc)))))))
8797 (defun org-store-link-props (&rest plist)
8798 "Store link properties, extract names and addresses."
8799 (let (x adr)
8800 (when (setq x (plist-get plist :from))
8801 (setq adr (mail-extract-address-components x))
8802 (setq plist (plist-put plist :fromname (car adr)))
8803 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
8804 (when (setq x (plist-get plist :to))
8805 (setq adr (mail-extract-address-components x))
8806 (setq plist (plist-put plist :toname (car adr)))
8807 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
8808 (let ((from (plist-get plist :from))
8809 (to (plist-get plist :to)))
8810 (when (and from to org-from-is-user-regexp)
8811 (setq plist
8812 (plist-put plist :fromto
8813 (if (string-match org-from-is-user-regexp from)
8814 (concat "to %t")
8815 (concat "from %f"))))))
8816 (setq org-store-link-plist plist))
8818 (defun org-add-link-props (&rest plist)
8819 "Add these properties to the link property list."
8820 (let (key value)
8821 (while plist
8822 (setq key (pop plist) value (pop plist))
8823 (setq org-store-link-plist
8824 (plist-put org-store-link-plist key value)))))
8826 (defun org-email-link-description (&optional fmt)
8827 "Return the description part of an email link.
8828 This takes information from `org-store-link-plist' and formats it
8829 according to FMT (default from `org-email-link-description-format')."
8830 (setq fmt (or fmt org-email-link-description-format))
8831 (let* ((p org-store-link-plist)
8832 (to (plist-get p :toaddress))
8833 (from (plist-get p :fromaddress))
8834 (table
8835 (list
8836 (cons "%c" (plist-get p :fromto))
8837 (cons "%F" (plist-get p :from))
8838 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
8839 (cons "%T" (plist-get p :to))
8840 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
8841 (cons "%s" (plist-get p :subject))
8842 (cons "%d" (plist-get p :date))
8843 (cons "%m" (plist-get p :message-id)))))
8844 (when (string-match "%c" fmt)
8845 ;; Check if the user wrote this message
8846 (if (and org-from-is-user-regexp from to
8847 (save-match-data (string-match org-from-is-user-regexp from)))
8848 (setq fmt (replace-match "to %t" t t fmt))
8849 (setq fmt (replace-match "from %f" t t fmt))))
8850 (org-replace-escapes fmt table)))
8852 (defun org-make-org-heading-search-string (&optional string heading)
8853 "Make search string for STRING or current headline."
8854 (interactive)
8855 (let ((s (or string (org-get-heading)))
8856 (lines org-context-in-file-links))
8857 (unless (and string (not heading))
8858 ;; We are using a headline, clean up garbage in there.
8859 (if (string-match org-todo-regexp s)
8860 (setq s (replace-match "" t t s)))
8861 (if (string-match (org-re ":[[:alnum:]_@#%:]+:[ \t]*$") s)
8862 (setq s (replace-match "" t t s)))
8863 (setq s (org-trim s))
8864 (if (string-match (concat "^\\(" org-quote-string "\\|"
8865 org-comment-string "\\)") s)
8866 (setq s (replace-match "" t t s)))
8867 (while (string-match org-ts-regexp s)
8868 (setq s (replace-match "" t t s))))
8869 (or string (setq s (concat "*" s))) ; Add * for headlines
8870 (when (and string (integerp lines) (> lines 0))
8871 (let ((slines (org-split-string s "\n")))
8872 (when (< lines (length slines))
8873 (setq s (mapconcat
8874 'identity
8875 (reverse (nthcdr (- (length slines) lines)
8876 (reverse slines))) "\n")))))
8877 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
8879 (defun org-make-link (&rest strings)
8880 "Concatenate STRINGS."
8881 (apply 'concat strings))
8883 (defun org-make-link-string (link &optional description)
8884 "Make a link with brackets, consisting of LINK and DESCRIPTION."
8885 (unless (string-match "\\S-" link)
8886 (error "Empty link"))
8887 (when (and description
8888 (stringp description)
8889 (not (string-match "\\S-" description)))
8890 (setq description nil))
8891 (when (stringp description)
8892 ;; Remove brackets from the description, they are fatal.
8893 (while (string-match "\\[" description)
8894 (setq description (replace-match "{" t t description)))
8895 (while (string-match "\\]" description)
8896 (setq description (replace-match "}" t t description))))
8897 (when (equal link description)
8898 ;; No description needed, it is identical
8899 (setq description nil))
8900 (when (and (not description)
8901 (not (string-match (org-image-file-name-regexp) link))
8902 (not (equal link (org-link-escape link))))
8903 (setq description (org-extract-attributes link)))
8904 (setq link
8905 (cond ((string-match (org-image-file-name-regexp) link) link)
8906 ((string-match org-link-types-re link)
8907 (concat (match-string 1 link)
8908 (org-link-escape (substring link (match-end 1)))))
8909 (t (org-link-escape link))))
8910 (concat "[[" link "]"
8911 (if description (concat "[" description "]") "")
8912 "]"))
8914 (defconst org-link-escape-chars
8915 '(?\ ?\[ ?\] ?\; ?\= ?\+)
8916 "List of characters that should be escaped in link.
8917 This is the list that is used for internal purposes.")
8919 (defvar org-url-encoding-use-url-hexify nil)
8921 (defconst org-link-escape-chars-browser
8922 '(?\ )
8923 "List of escapes for characters that are problematic in links.
8924 This is the list that is used before handing over to the browser.")
8926 (defun org-link-escape (text &optional table merge)
8927 "Return percent escaped representation of TEXT.
8928 TEXT is a string with the text to escape.
8929 Optional argument TABLE is a list with characters that should be
8930 escaped. When nil, `org-link-escape-chars' is used.
8931 If optional argument MERGE is set, merge TABLE into
8932 `org-link-escape-chars'."
8933 (if (and org-url-encoding-use-url-hexify (not table))
8934 (url-hexify-string text)
8935 (cond
8936 ((and table merge)
8937 (mapc (lambda (defchr)
8938 (unless (member defchr table)
8939 (setq table (cons defchr table)))) org-link-escape-chars))
8940 ((null table)
8941 (setq table org-link-escape-chars)))
8942 (mapconcat
8943 (lambda (char)
8944 (if (or (member char table)
8945 (< char 32) (= char 37) (> char 126))
8946 (mapconcat (lambda (sequence-element)
8947 (format "%%%.2X" sequence-element))
8948 (or (encode-coding-char char 'utf-8)
8949 (error "Unable to percent escape character: %s"
8950 (char-to-string char))) "")
8951 (char-to-string char))) text "")))
8953 (defun org-link-unescape (str)
8954 "Unhex hexified unicode strings as returned from the JavaScript function
8955 encodeURIComponent. E.g. `%C3%B6' is the german Umlaut `ö'."
8956 (unless (and (null str) (string= "" str))
8957 (let ((pos 0) (case-fold-search t) unhexed)
8958 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
8959 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
8960 (setq str (replace-match unhexed t t str))
8961 (setq pos (+ pos (length unhexed))))))
8962 str)
8964 (defun org-link-unescape-compound (hex)
8965 "Unhexify unicode hex-chars. E.g. `%C3%B6' is the German Umlaut `ö'.
8966 Note: this function also decodes single byte encodings like
8967 `%E1' (\"á\") if not followed by another `%[A-F0-9]{2}' group."
8968 (save-match-data
8969 (let* ((bytes (cdr (split-string hex "%")))
8970 (ret "")
8971 (eat 0)
8972 (sum 0))
8973 (while bytes
8974 (let* ((val (string-to-number (pop bytes) 16))
8975 (shift-xor
8976 (if (= 0 eat)
8977 (cond
8978 ((>= val 252) (cons 6 252))
8979 ((>= val 248) (cons 5 248))
8980 ((>= val 240) (cons 4 240))
8981 ((>= val 224) (cons 3 224))
8982 ((>= val 192) (cons 2 192))
8983 (t (cons 0 0)))
8984 (cons 6 128))))
8985 (if (>= val 192) (setq eat (car shift-xor)))
8986 (setq val (logxor val (cdr shift-xor)))
8987 (setq sum (+ (lsh sum (car shift-xor)) val))
8988 (if (> eat 0) (setq eat (- eat 1)))
8989 (cond
8990 ((= 0 eat) ;multi byte
8991 (setq ret (concat ret (org-char-to-string sum)))
8992 (setq sum 0))
8993 ((not bytes) ; single byte(s)
8994 (setq ret (org-link-unescape-single-byte-sequence hex))))
8995 )) ;; end (while bytes
8996 ret )))
8998 (defun org-link-unescape-single-byte-sequence (hex)
8999 "Unhexify hex-encoded single byte character sequences."
9000 (mapconcat (lambda (byte)
9001 (char-to-string (string-to-number byte 16)))
9002 (cdr (split-string hex "%")) ""))
9004 (defun org-xor (a b)
9005 "Exclusive or."
9006 (if a (not b) b))
9008 (defun org-fixup-message-id-for-http (s)
9009 "Replace special characters in a message id, so it can be used in an http query."
9010 (when (string-match "%" s)
9011 (setq s (mapconcat (lambda (c)
9012 (if (eq c ?%)
9013 "%25"
9014 (char-to-string c)))
9015 s "")))
9016 (while (string-match "<" s)
9017 (setq s (replace-match "%3C" t t s)))
9018 (while (string-match ">" s)
9019 (setq s (replace-match "%3E" t t s)))
9020 (while (string-match "@" s)
9021 (setq s (replace-match "%40" t t s)))
9024 ;;;###autoload
9025 (defun org-insert-link-global ()
9026 "Insert a link like Org-mode does.
9027 This command can be called in any mode to insert a link in Org-mode syntax."
9028 (interactive)
9029 (org-load-modules-maybe)
9030 (org-run-like-in-org-mode 'org-insert-link))
9032 (defun org-insert-link (&optional complete-file link-location default-description)
9033 "Insert a link. At the prompt, enter the link.
9035 Completion can be used to insert any of the link protocol prefixes like
9036 http or ftp in use.
9038 The history can be used to select a link previously stored with
9039 `org-store-link'. When the empty string is entered (i.e. if you just
9040 press RET at the prompt), the link defaults to the most recently
9041 stored link. As SPC triggers completion in the minibuffer, you need to
9042 use M-SPC or C-q SPC to force the insertion of a space character.
9044 You will also be prompted for a description, and if one is given, it will
9045 be displayed in the buffer instead of the link.
9047 If there is already a link at point, this command will allow you to edit link
9048 and description parts.
9050 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9051 be selected using completion. The path to the file will be relative to the
9052 current directory if the file is in the current directory or a subdirectory.
9053 Otherwise, the link will be the absolute path as completed in the minibuffer
9054 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9055 option `org-link-file-path-type'.
9057 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9058 the current directory or below.
9060 With three \\[universal-argument] prefixes, negate the meaning of
9061 `org-keep-stored-link-after-insertion'.
9063 If `org-make-link-description-function' is non-nil, this function will be
9064 called with the link target, and the result will be the default
9065 link description.
9067 If the LINK-LOCATION parameter is non-nil, this value will be
9068 used as the link location instead of reading one interactively.
9070 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9071 be used as the default description."
9072 (interactive "P")
9073 (let* ((wcf (current-window-configuration))
9074 (region (if (org-region-active-p)
9075 (buffer-substring (region-beginning) (region-end))))
9076 (remove (and region (list (region-beginning) (region-end))))
9077 (desc region)
9078 tmphist ; byte-compile incorrectly complains about this
9079 (link link-location)
9080 entry file all-prefixes)
9081 (cond
9082 (link-location) ; specified by arg, just use it.
9083 ((org-in-regexp org-bracket-link-regexp 1)
9084 ;; We do have a link at point, and we are going to edit it.
9085 (setq remove (list (match-beginning 0) (match-end 0)))
9086 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9087 (setq link (read-string "Link: "
9088 (org-link-unescape
9089 (org-match-string-no-properties 1)))))
9090 ((or (org-in-regexp org-angle-link-re)
9091 (org-in-regexp org-plain-link-re))
9092 ;; Convert to bracket link
9093 (setq remove (list (match-beginning 0) (match-end 0))
9094 link (read-string "Link: "
9095 (org-remove-angle-brackets (match-string 0)))))
9096 ((member complete-file '((4) (16)))
9097 ;; Completing read for file names.
9098 (setq link (org-file-complete-link complete-file)))
9100 ;; Read link, with completion for stored links.
9101 (with-output-to-temp-buffer "*Org Links*"
9102 (princ "Insert a link.
9103 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9104 (when org-stored-links
9105 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9106 (princ (mapconcat
9107 (lambda (x)
9108 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
9109 (reverse org-stored-links) "\n"))))
9110 (let ((cw (selected-window)))
9111 (select-window (get-buffer-window "*Org Links*" 'visible))
9112 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9113 (unless (pos-visible-in-window-p (point-max))
9114 (org-fit-window-to-buffer))
9115 (and (window-live-p cw) (select-window cw)))
9116 ;; Fake a link history, containing the stored links.
9117 (setq tmphist (append (mapcar 'car org-stored-links)
9118 org-insert-link-history))
9119 (setq all-prefixes (append (mapcar 'car org-link-abbrev-alist-local)
9120 (mapcar 'car org-link-abbrev-alist)
9121 org-link-types))
9122 (unwind-protect
9123 (progn
9124 (setq link
9125 (let ((org-completion-use-ido nil)
9126 (org-completion-use-iswitchb nil))
9127 (org-completing-read
9128 "Link: "
9129 (append
9130 (mapcar (lambda (x) (list (concat x ":")))
9131 all-prefixes)
9132 (mapcar 'car org-stored-links))
9133 nil nil nil
9134 'tmphist
9135 (car (car org-stored-links)))))
9136 (if (not (string-match "\\S-" link))
9137 (error "No link selected"))
9138 (if (or (member link all-prefixes)
9139 (and (equal ":" (substring link -1))
9140 (member (substring link 0 -1) all-prefixes)
9141 (setq link (substring link 0 -1))))
9142 (setq link (org-link-try-special-completion link))))
9143 (set-window-configuration wcf)
9144 (kill-buffer "*Org Links*"))
9145 (setq entry (assoc link org-stored-links))
9146 (or entry (push link org-insert-link-history))
9147 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9148 (not org-keep-stored-link-after-insertion))
9149 (setq org-stored-links (delq (assoc link org-stored-links)
9150 org-stored-links)))
9151 (setq desc (or desc (nth 1 entry)))))
9153 (if (string-match org-plain-link-re link)
9154 ;; URL-like link, normalize the use of angular brackets.
9155 (setq link (org-make-link (org-remove-angle-brackets link))))
9157 ;; Check if we are linking to the current file with a search option
9158 ;; If yes, simplify the link by using only the search option.
9159 (when (and buffer-file-name
9160 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
9161 (let* ((path (match-string 1 link))
9162 (case-fold-search nil)
9163 (search (match-string 2 link)))
9164 (save-match-data
9165 (if (equal (file-truename buffer-file-name) (file-truename path))
9166 ;; We are linking to this same file, with a search option
9167 (setq link search)))))
9169 ;; Check if we can/should use a relative path. If yes, simplify the link
9170 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
9171 (let* ((type (match-string 1 link))
9172 (path (match-string 2 link))
9173 (origpath path)
9174 (case-fold-search nil))
9175 (cond
9176 ((or (eq org-link-file-path-type 'absolute)
9177 (equal complete-file '(16)))
9178 (setq path (abbreviate-file-name (expand-file-name path))))
9179 ((eq org-link-file-path-type 'noabbrev)
9180 (setq path (expand-file-name path)))
9181 ((eq org-link-file-path-type 'relative)
9182 (setq path (file-relative-name path)))
9184 (save-match-data
9185 (if (string-match (concat "^" (regexp-quote
9186 (expand-file-name
9187 (file-name-as-directory
9188 default-directory))))
9189 (expand-file-name path))
9190 ;; We are linking a file with relative path name.
9191 (setq path (substring (expand-file-name path)
9192 (match-end 0)))
9193 (setq path (abbreviate-file-name (expand-file-name path)))))))
9194 (setq link (concat type path))
9195 (if (equal desc origpath)
9196 (setq desc path))))
9198 (if org-make-link-description-function
9199 (setq desc (funcall org-make-link-description-function link desc))
9200 (if default-description (setq desc default-description)))
9202 (setq desc (read-string "Description: " desc))
9203 (unless (string-match "\\S-" desc) (setq desc nil))
9204 (if remove (apply 'delete-region remove))
9205 (insert (org-make-link-string link desc))))
9207 (defun org-link-try-special-completion (type)
9208 "If there is completion support for link type TYPE, offer it."
9209 (let ((fun (intern (concat "org-" type "-complete-link"))))
9210 (if (functionp fun)
9211 (funcall fun)
9212 (read-string "Link (no completion support): " (concat type ":")))))
9214 (defun org-file-complete-link (&optional arg)
9215 "Create a file link using completion."
9216 (let (file link)
9217 (setq file (read-file-name "File: "))
9218 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9219 (pwd1 (file-name-as-directory (abbreviate-file-name
9220 (expand-file-name ".")))))
9221 (cond
9222 ((equal arg '(16))
9223 (setq link (org-make-link
9224 "file:"
9225 (abbreviate-file-name (expand-file-name file)))))
9226 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9227 (setq link (org-make-link "file:" (match-string 1 file))))
9228 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9229 (expand-file-name file))
9230 (setq link (org-make-link
9231 "file:" (match-string 1 (expand-file-name file)))))
9232 (t (setq link (org-make-link "file:" file)))))
9233 link))
9235 (defun org-completing-read (&rest args)
9236 "Completing-read with SPACE being a normal character."
9237 (let ((enable-recursive-minibuffers t)
9238 (minibuffer-local-completion-map
9239 (copy-keymap minibuffer-local-completion-map)))
9240 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
9241 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
9242 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
9243 (apply 'org-icompleting-read args)))
9245 (defun org-completing-read-no-i (&rest args)
9246 (let (org-completion-use-ido org-completion-use-iswitchb)
9247 (apply 'org-completing-read args)))
9249 (defun org-iswitchb-completing-read (prompt choices &rest args)
9250 "Use iswitch as a completing-read replacement to choose from choices.
9251 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
9252 from."
9253 (let* ((iswitchb-use-virtual-buffers nil)
9254 (iswitchb-make-buflist-hook
9255 (lambda ()
9256 (setq iswitchb-temp-buflist choices))))
9257 (iswitchb-read-buffer prompt)))
9259 (defun org-icompleting-read (&rest args)
9260 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
9261 (org-without-partial-completion
9262 (if (and org-completion-use-ido
9263 (fboundp 'ido-completing-read)
9264 (boundp 'ido-mode) ido-mode
9265 (listp (second args)))
9266 (let ((ido-enter-matching-directory nil))
9267 (apply 'ido-completing-read (concat (car args))
9268 (if (consp (car (nth 1 args)))
9269 (mapcar 'car (nth 1 args))
9270 (nth 1 args))
9271 (cddr args)))
9272 (if (and org-completion-use-iswitchb
9273 (boundp 'iswitchb-mode) iswitchb-mode
9274 (listp (second args)))
9275 (apply 'org-iswitchb-completing-read (concat (car args))
9276 (if (consp (car (nth 1 args)))
9277 (mapcar 'car (nth 1 args))
9278 (nth 1 args))
9279 (cddr args))
9280 (apply 'completing-read args)))))
9282 (defun org-extract-attributes (s)
9283 "Extract the attributes cookie from a string and set as text property."
9284 (let (a attr (start 0) key value)
9285 (save-match-data
9286 (when (string-match "{{\\([^}]+\\)}}$" s)
9287 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
9288 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
9289 (setq key (match-string 1 a) value (match-string 2 a)
9290 start (match-end 0)
9291 attr (plist-put attr (intern key) value))))
9292 (org-add-props s nil 'org-attr attr))
9295 (defun org-extract-attributes-from-string (tag)
9296 (let (key value attr)
9297 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
9298 (setq key (match-string 1 tag) value (match-string 2 tag)
9299 tag (replace-match "" t t tag)
9300 attr (plist-put attr (intern key) value)))
9301 (cons tag attr)))
9303 (defun org-attributes-to-string (plist)
9304 "Format a property list into an HTML attribute list."
9305 (let ((s "") key value)
9306 (while plist
9307 (setq key (pop plist) value (pop plist))
9308 (and value
9309 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
9312 ;;; Opening/following a link
9314 (defvar org-link-search-failed nil)
9316 (defvar org-open-link-functions nil
9317 "Hook for functions finding a plain text link.
9318 These functions must take a single argument, the link content.
9319 They will be called for links that look like [[link text][description]]
9320 when LINK TEXT does not have a protocol like \"http:\" and does not look
9321 like a filename (e.g. \"./blue.png\").
9323 These functions will be called *before* Org attempts to resolve the
9324 link by doing text searches in the current buffer - so if you want a
9325 link \"[[target]]\" to still find \"<<target>>\", your function should
9326 handle this as a special case.
9328 When the function does handle the link, it must return a non-nil value.
9329 If it decides that it is not responsible for this link, it must return
9330 nil to indicate that that Org-mode can continue with other options
9331 like exact and fuzzy text search.")
9333 (defun org-next-link ()
9334 "Move forward to the next link.
9335 If the link is in hidden text, expose it."
9336 (interactive)
9337 (when (and org-link-search-failed (eq this-command last-command))
9338 (goto-char (point-min))
9339 (message "Link search wrapped back to beginning of buffer"))
9340 (setq org-link-search-failed nil)
9341 (let* ((pos (point))
9342 (ct (org-context))
9343 (a (assoc :link ct)))
9344 (if a (goto-char (nth 2 a)))
9345 (if (re-search-forward org-any-link-re nil t)
9346 (progn
9347 (goto-char (match-beginning 0))
9348 (if (outline-invisible-p) (org-show-context)))
9349 (goto-char pos)
9350 (setq org-link-search-failed t)
9351 (error "No further link found"))))
9353 (defun org-previous-link ()
9354 "Move backward to the previous link.
9355 If the link is in hidden text, expose it."
9356 (interactive)
9357 (when (and org-link-search-failed (eq this-command last-command))
9358 (goto-char (point-max))
9359 (message "Link search wrapped back to end of buffer"))
9360 (setq org-link-search-failed nil)
9361 (let* ((pos (point))
9362 (ct (org-context))
9363 (a (assoc :link ct)))
9364 (if a (goto-char (nth 1 a)))
9365 (if (re-search-backward org-any-link-re nil t)
9366 (progn
9367 (goto-char (match-beginning 0))
9368 (if (outline-invisible-p) (org-show-context)))
9369 (goto-char pos)
9370 (setq org-link-search-failed t)
9371 (error "No further link found"))))
9373 (defun org-translate-link (s)
9374 "Translate a link string if a translation function has been defined."
9375 (if (and org-link-translation-function
9376 (fboundp org-link-translation-function)
9377 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
9378 (progn
9379 (setq s (funcall org-link-translation-function
9380 (match-string 1) (match-string 2)))
9381 (concat (car s) ":" (cdr s)))
9384 (defun org-translate-link-from-planner (type path)
9385 "Translate a link from Emacs Planner syntax so that Org can follow it.
9386 This is still an experimental function, your mileage may vary."
9387 (cond
9388 ((member type '("http" "https" "news" "ftp"))
9389 ;; standard Internet links are the same.
9390 nil)
9391 ((and (equal type "irc") (string-match "^//" path))
9392 ;; Planner has two / at the beginning of an irc link, we have 1.
9393 ;; We should have zero, actually....
9394 (setq path (substring path 1)))
9395 ((and (equal type "lisp") (string-match "^/" path))
9396 ;; Planner has a slash, we do not.
9397 (setq type "elisp" path (substring path 1)))
9398 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9399 ;; A typical message link. Planner has the id after the final slash,
9400 ;; we separate it with a hash mark
9401 (setq path (concat (match-string 1 path) "#"
9402 (org-remove-angle-brackets (match-string 2 path)))))
9404 (cons type path))
9406 (defun org-find-file-at-mouse (ev)
9407 "Open file link or URL at mouse."
9408 (interactive "e")
9409 (mouse-set-point ev)
9410 (org-open-at-point 'in-emacs))
9412 (defun org-open-at-mouse (ev)
9413 "Open file link or URL at mouse.
9414 See the docstring of `org-open-file' for details."
9415 (interactive "e")
9416 (mouse-set-point ev)
9417 (if (eq major-mode 'org-agenda-mode)
9418 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
9419 (org-open-at-point))
9421 (defvar org-window-config-before-follow-link nil
9422 "The window configuration before following a link.
9423 This is saved in case the need arises to restore it.")
9425 (defvar org-open-link-marker (make-marker)
9426 "Marker pointing to the location where `org-open-at-point; was called.")
9428 ;;;###autoload
9429 (defun org-open-at-point-global ()
9430 "Follow a link like Org-mode does.
9431 This command can be called in any mode to follow a link that has
9432 Org-mode syntax."
9433 (interactive)
9434 (org-run-like-in-org-mode 'org-open-at-point))
9436 ;;;###autoload
9437 (defun org-open-link-from-string (s &optional arg reference-buffer)
9438 "Open a link in the string S, as if it was in Org-mode."
9439 (interactive "sLink: \nP")
9440 (let ((reference-buffer (or reference-buffer (current-buffer))))
9441 (with-temp-buffer
9442 (let ((org-inhibit-startup t))
9443 (org-mode)
9444 (insert s)
9445 (goto-char (point-min))
9446 (when reference-buffer
9447 (setq org-link-abbrev-alist-local
9448 (with-current-buffer reference-buffer
9449 org-link-abbrev-alist-local)))
9450 (org-open-at-point arg reference-buffer)))))
9452 (defvar org-open-at-point-functions nil
9453 "Hook that is run when following a link at point.
9455 Functions in this hook must return t if they identify and follow
9456 a link at point. If they don't find anything interesting at point,
9457 they must return nil.")
9459 (defun org-open-at-point (&optional arg reference-buffer)
9460 "Open link at or after point.
9461 If there is no link at point, this function will search forward up to
9462 the end of the current line.
9463 Normally, files will be opened by an appropriate application. If the
9464 optional prefix argument ARG is non-nil, Emacs will visit the file.
9465 With a double prefix argument, try to open outside of Emacs, in the
9466 application the system uses for this file type."
9467 (interactive "P")
9468 ;; if in a code block, then open the block's results
9469 (unless (call-interactively #'org-babel-open-src-block-result)
9470 (org-load-modules-maybe)
9471 (move-marker org-open-link-marker (point))
9472 (setq org-window-config-before-follow-link (current-window-configuration))
9473 (org-remove-occur-highlights nil nil t)
9474 (cond
9475 ((and (org-on-heading-p)
9476 (not (org-in-regexp
9477 (concat org-plain-link-re "\\|"
9478 org-bracket-link-regexp "\\|"
9479 org-angle-link-re "\\|"
9480 "[ \t]:[^ \t\n]+:[ \t]*$")))
9481 (not (get-text-property (point) 'org-linked-text)))
9482 (or (org-offer-links-in-entry arg)
9483 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
9484 ((run-hook-with-args-until-success 'org-open-at-point-functions))
9485 ((org-at-timestamp-p t) (org-follow-timestamp-link))
9486 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
9487 (not (org-in-regexp org-bracket-link-regexp)))
9488 (org-footnote-action))
9490 (let (type path link line search (pos (point)))
9491 (catch 'match
9492 (save-excursion
9493 (skip-chars-forward "^]\n\r")
9494 (when (org-in-regexp org-bracket-link-regexp 1)
9495 (setq link (org-extract-attributes
9496 (org-link-unescape (org-match-string-no-properties 1))))
9497 (while (string-match " *\n *" link)
9498 (setq link (replace-match " " t t link)))
9499 (setq link (org-link-expand-abbrev link))
9500 (cond
9501 ((or (file-name-absolute-p link)
9502 (string-match "^\\.\\.?/" link))
9503 (setq type "file" path link))
9504 ((string-match org-link-re-with-space3 link)
9505 (setq type (match-string 1 link) path (match-string 2 link)))
9506 (t (setq type "thisfile" path link)))
9507 (throw 'match t)))
9509 (when (get-text-property (point) 'org-linked-text)
9510 (setq type "thisfile"
9511 pos (if (get-text-property (1+ (point)) 'org-linked-text)
9512 (1+ (point)) (point))
9513 path (buffer-substring
9514 (or (previous-single-property-change pos 'org-linked-text)
9515 (point-min))
9516 (or (next-single-property-change pos 'org-linked-text)
9517 (point-max))))
9518 (throw 'match t))
9520 (save-excursion
9521 (when (or (org-in-regexp org-angle-link-re)
9522 (org-in-regexp org-plain-link-re))
9523 (setq type (match-string 1)
9524 path (org-link-unescape (match-string 2)))
9525 (throw 'match t)))
9526 (save-excursion
9527 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
9528 (setq type "tags"
9529 path (match-string 1))
9530 (while (string-match ":" path)
9531 (setq path (replace-match "+" t t path)))
9532 (throw 'match t)))
9533 (when (org-in-regexp "<\\([^><\n]+\\)>")
9534 (setq type "tree-match"
9535 path (match-string 1))
9536 (throw 'match t)))
9537 (unless path
9538 (error "No link found"))
9540 ;; switch back to reference buffer
9541 ;; needed when if called in a temporary buffer through
9542 ;; org-open-link-from-string
9543 (with-current-buffer (or reference-buffer (current-buffer))
9545 ;; Remove any trailing spaces in path
9546 (if (string-match " +\\'" path)
9547 (setq path (replace-match "" t t path)))
9548 (if (and org-link-translation-function
9549 (fboundp org-link-translation-function))
9550 ;; Check if we need to translate the link
9551 (let ((tmp (funcall org-link-translation-function type path)))
9552 (setq type (car tmp) path (cdr tmp))))
9554 (cond
9556 ((assoc type org-link-protocols)
9557 (funcall (nth 1 (assoc type org-link-protocols)) path))
9559 ((equal type "mailto")
9560 (let ((cmd (car org-link-mailto-program))
9561 (args (cdr org-link-mailto-program)) args1
9562 (address path) (subject "") a)
9563 (if (string-match "\\(.*\\)::\\(.*\\)" path)
9564 (setq address (match-string 1 path)
9565 subject (org-link-escape (match-string 2 path))))
9566 (while args
9567 (cond
9568 ((not (stringp (car args))) (push (pop args) args1))
9569 (t (setq a (pop args))
9570 (if (string-match "%a" a)
9571 (setq a (replace-match address t t a)))
9572 (if (string-match "%s" a)
9573 (setq a (replace-match subject t t a)))
9574 (push a args1))))
9575 (apply cmd (nreverse args1))))
9577 ((member type '("http" "https" "ftp" "news"))
9578 (browse-url (concat type ":" (org-link-escape
9579 path org-link-escape-chars-browser))))
9581 ((string= type "doi")
9582 (browse-url (concat "http://dx.doi.org/"
9583 (org-link-escape
9584 path org-link-escape-chars-browser))))
9586 ((member type '("message"))
9587 (browse-url (concat type ":" path)))
9589 ((string= type "tags")
9590 (org-tags-view arg path))
9592 ((string= type "tree-match")
9593 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
9595 ((string= type "file")
9596 (if (string-match "::\\([0-9]+\\)\\'" path)
9597 (setq line (string-to-number (match-string 1 path))
9598 path (substring path 0 (match-beginning 0)))
9599 (if (string-match "::\\(.+\\)\\'" path)
9600 (setq search (match-string 1 path)
9601 path (substring path 0 (match-beginning 0)))))
9602 (if (string-match "[*?{]" (file-name-nondirectory path))
9603 (dired path)
9604 (org-open-file path arg line search)))
9606 ((string= type "shell")
9607 (let ((cmd path))
9608 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
9609 (string-match org-confirm-shell-link-not-regexp cmd))
9610 (not org-confirm-shell-link-function)
9611 (funcall org-confirm-shell-link-function
9612 (format "Execute \"%s\" in shell? "
9613 (org-add-props cmd nil
9614 'face 'org-warning))))
9615 (progn
9616 (message "Executing %s" cmd)
9617 (shell-command cmd))
9618 (error "Abort"))))
9620 ((string= type "elisp")
9621 (let ((cmd path))
9622 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
9623 (string-match org-confirm-elisp-link-not-regexp cmd))
9624 (not org-confirm-elisp-link-function)
9625 (funcall org-confirm-elisp-link-function
9626 (format "Execute \"%s\" as elisp? "
9627 (org-add-props cmd nil
9628 'face 'org-warning))))
9629 (message "%s => %s" cmd
9630 (if (equal (string-to-char cmd) ?\()
9631 (eval (read cmd))
9632 (call-interactively (read cmd))))
9633 (error "Abort"))))
9635 ((and (string= type "thisfile")
9636 (run-hook-with-args-until-success
9637 'org-open-link-functions path)))
9639 ((string= type "thisfile")
9640 (if arg
9641 (switch-to-buffer-other-window
9642 (org-get-buffer-for-internal-link (current-buffer)))
9643 (org-mark-ring-push))
9644 (let ((cmd `(org-link-search
9645 ,path
9646 ,(cond ((equal arg '(4)) ''occur)
9647 ((equal arg '(16)) ''org-occur)
9648 (t nil))
9649 ,pos)))
9650 (condition-case nil (let ((org-link-search-inhibit-query t))
9651 (eval cmd))
9652 (error (progn (widen) (eval cmd))))))
9655 (browse-url-at-point)))))))
9656 (move-marker org-open-link-marker nil)
9657 (run-hook-with-args 'org-follow-link-hook)))
9659 (defun org-offer-links-in-entry (&optional nth zero)
9660 "Offer links in the current entry and follow the selected link.
9661 If there is only one link, follow it immediately as well.
9662 If NTH is an integer, immediately pick the NTH link found.
9663 If ZERO is a string, check also this string for a link, and if
9664 there is one, offer it as link number zero."
9665 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
9666 "\\(" org-angle-link-re "\\)\\|"
9667 "\\(" org-plain-link-re "\\)"))
9668 (cnt ?0)
9669 (in-emacs (if (integerp nth) nil nth))
9670 have-zero end links link c)
9671 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
9672 (push (match-string 0 zero) links)
9673 (setq cnt (1- cnt) have-zero t))
9674 (save-excursion
9675 (org-back-to-heading t)
9676 (setq end (save-excursion (outline-next-heading) (point)))
9677 (while (re-search-forward re end t)
9678 (push (match-string 0) links))
9679 (setq links (org-uniquify (reverse links))))
9681 (cond
9682 ((null links)
9683 (message "No links"))
9684 ((equal (length links) 1)
9685 (setq link (list (car links))))
9686 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
9687 (setq link (nth (if have-zero nth (1- nth)) links)))
9688 (t ; we have to select a link
9689 (save-excursion
9690 (save-window-excursion
9691 (delete-other-windows)
9692 (with-output-to-temp-buffer "*Select Link*"
9693 (mapc (lambda (l)
9694 (if (not (string-match org-bracket-link-regexp l))
9695 (princ (format "[%c] %s\n" (incf cnt)
9696 (org-remove-angle-brackets l)))
9697 (if (match-end 3)
9698 (princ (format "[%c] %s (%s)\n" (incf cnt)
9699 (match-string 3 l) (match-string 1 l)))
9700 (princ (format "[%c] %s\n" (incf cnt)
9701 (match-string 1 l))))))
9702 links))
9703 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
9704 (message "Select link to open, RET to open all:")
9705 (setq c (read-char-exclusive))
9706 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
9707 (when (equal c ?q) (error "Abort"))
9708 (if (equal c ?\C-m)
9709 (setq link links)
9710 (setq nth (- c ?0))
9711 (if have-zero (setq nth (1+ nth)))
9712 (unless (and (integerp nth) (>= (length links) nth))
9713 (error "Invalid link selection"))
9714 (setq link (list (nth (1- nth) links))))))
9715 (if link
9716 (let ((buf (current-buffer)))
9717 (dolist (l link)
9718 (org-open-link-from-string l in-emacs buf))
9720 nil)))
9722 ;; Add special file links that specify the way of opening
9724 (org-add-link-type "file+sys" 'org-open-file-with-system)
9725 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
9726 (defun org-open-file-with-system (path)
9727 "Open file at PATH using the system way of opening it."
9728 (org-open-file path 'system))
9729 (defun org-open-file-with-emacs (path)
9730 "Open file at PATH in Emacs."
9731 (org-open-file path 'emacs))
9732 (defun org-remove-file-link-modifiers ()
9733 "Remove the file link modifiers in `file+sys:' and `file+emacs:' links."
9734 (goto-char (point-min))
9735 (while (re-search-forward "\\<file\\+\\(sys\\|emacs\\):" nil t)
9736 (org-if-unprotected
9737 (replace-match "file:" t t))))
9738 (eval-after-load "org-exp"
9739 '(add-hook 'org-export-preprocess-before-normalizing-links-hook
9740 'org-remove-file-link-modifiers))
9742 ;;;; Time estimates
9744 (defun org-get-effort (&optional pom)
9745 "Get the effort estimate for the current entry."
9746 (org-entry-get pom org-effort-property))
9748 ;;; File search
9750 (defvar org-create-file-search-functions nil
9751 "List of functions to construct the right search string for a file link.
9752 These functions are called in turn with point at the location to
9753 which the link should point.
9755 A function in the hook should first test if it would like to
9756 handle this file type, for example by checking the `major-mode'
9757 or the file extension. If it decides not to handle this file, it
9758 should just return nil to give other functions a chance. If it
9759 does handle the file, it must return the search string to be used
9760 when following the link. The search string will be part of the
9761 file link, given after a double colon, and `org-open-at-point'
9762 will automatically search for it. If special measures must be
9763 taken to make the search successful, another function should be
9764 added to the companion hook `org-execute-file-search-functions',
9765 which see.
9767 A function in this hook may also use `setq' to set the variable
9768 `description' to provide a suggestion for the descriptive text to
9769 be used for this link when it gets inserted into an Org-mode
9770 buffer with \\[org-insert-link].")
9772 (defvar org-execute-file-search-functions nil
9773 "List of functions to execute a file search triggered by a link.
9775 Functions added to this hook must accept a single argument, the
9776 search string that was part of the file link, the part after the
9777 double colon. The function must first check if it would like to
9778 handle this search, for example by checking the `major-mode' or
9779 the file extension. If it decides not to handle this search, it
9780 should just return nil to give other functions a chance. If it
9781 does handle the search, it must return a non-nil value to keep
9782 other functions from trying.
9784 Each function can access the current prefix argument through the
9785 variable `current-prefix-argument'. Note that a single prefix is
9786 used to force opening a link in Emacs, so it may be good to only
9787 use a numeric or double prefix to guide the search function.
9789 In case this is needed, a function in this hook can also restore
9790 the window configuration before `org-open-at-point' was called using:
9792 (set-window-configuration org-window-config-before-follow-link)")
9794 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
9795 (defun org-link-search (s &optional type avoid-pos stealth)
9796 "Search for a link search option.
9797 If S is surrounded by forward slashes, it is interpreted as a
9798 regular expression. In org-mode files, this will create an `org-occur'
9799 sparse tree. In ordinary files, `occur' will be used to list matches.
9800 If the current buffer is in `dired-mode', grep will be used to search
9801 in all files. If AVOID-POS is given, ignore matches near that position.
9803 When optional argument STEALTH is non-nil, do not modify
9804 visibility around point, thus ignoring
9805 `org-show-hierarchy-above', `org-show-following-heading' and
9806 `org-show-siblings' variables."
9807 (let ((case-fold-search t)
9808 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
9809 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
9810 (append '(("") (" ") ("\t") ("\n"))
9811 org-emphasis-alist)
9812 "\\|") "\\)"))
9813 (pos (point))
9814 (pre nil) (post nil)
9815 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
9816 (cond
9817 ;; First check if there are any special search functions
9818 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
9819 ;; Now try the builtin stuff
9820 ((and (equal (string-to-char s0) ?#)
9821 (> (length s0) 1)
9822 (save-excursion
9823 (goto-char (point-min))
9824 (and
9825 (re-search-forward
9826 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
9827 (setq type 'dedicated
9828 pos (match-beginning 0))))
9829 ;; There is an exact target for this
9830 (goto-char pos)
9831 (org-back-to-heading t)))
9832 ((save-excursion
9833 (goto-char (point-min))
9834 (and
9835 (re-search-forward
9836 (concat "<<" (regexp-quote s0) ">>") nil t)
9837 (setq type 'dedicated
9838 pos (match-beginning 0))))
9839 ;; There is an exact target for this
9840 (goto-char pos))
9841 ((and (string-match "^(\\(.*\\))$" s0)
9842 (save-excursion
9843 (goto-char (point-min))
9844 (and
9845 (re-search-forward
9846 (concat "[^[]" (regexp-quote
9847 (format org-coderef-label-format
9848 (match-string 1 s0))))
9849 nil t)
9850 (setq type 'dedicated
9851 pos (1+ (match-beginning 0))))))
9852 ;; There is a coderef target for this
9853 (goto-char pos))
9854 ((string-match "^/\\(.*\\)/$" s)
9855 ;; A regular expression
9856 (cond
9857 ((eq major-mode 'org-mode)
9858 (org-occur (match-string 1 s)))
9859 ;;((eq major-mode 'dired-mode)
9860 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
9861 (t (org-do-occur (match-string 1 s)))))
9862 ((and (eq major-mode 'org-mode) org-link-search-must-match-exact-headline)
9863 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
9864 (goto-char (point-min))
9865 (cond
9866 ((let (case-fold-search)
9867 (re-search-forward (format org-complex-heading-regexp-format
9868 (regexp-quote s))
9869 nil t))
9870 ;; OK, found a match
9871 (setq type 'dedicated)
9872 (goto-char (match-beginning 0)))
9873 ((and (not org-link-search-inhibit-query)
9874 (eq org-link-search-must-match-exact-headline 'query-to-create)
9875 (y-or-n-p "No match - create this as a new heading? "))
9876 (goto-char (point-max))
9877 (or (bolp) (newline))
9878 (insert "* " s "\n")
9879 (beginning-of-line 0))
9881 (goto-char pos)
9882 (error "No match"))))
9884 ;; A normal search string
9885 (when (equal (string-to-char s) ?*)
9886 ;; Anchor on headlines, post may include tags.
9887 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
9888 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
9889 s (substring s 1)))
9890 (remove-text-properties
9891 0 (length s)
9892 '(face nil mouse-face nil keymap nil fontified nil) s)
9893 ;; Make a series of regular expressions to find a match
9894 (setq words (org-split-string s "[ \n\r\t]+")
9896 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
9897 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
9898 "\\)" markers)
9899 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
9900 re2a (concat "[ \t\r\n]" re2a_)
9901 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
9902 re4 (concat "[^a-zA-Z_]" re4_)
9904 re1 (concat pre re2 post)
9905 re3 (concat pre (if pre re4_ re4) post)
9906 re5 (concat pre ".*" re4)
9907 re2 (concat pre re2)
9908 re2a (concat pre (if pre re2a_ re2a))
9909 re4 (concat pre (if pre re4_ re4))
9910 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
9911 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
9912 re5 "\\)"
9914 (cond
9915 ((eq type 'org-occur) (org-occur reall))
9916 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
9917 (t (goto-char (point-min))
9918 (setq type 'fuzzy)
9919 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
9920 (org-search-not-self 1 re1 nil t)
9921 (org-search-not-self 1 re2 nil t)
9922 (org-search-not-self 1 re2a nil t)
9923 (org-search-not-self 1 re3 nil t)
9924 (org-search-not-self 1 re4 nil t)
9925 (org-search-not-self 1 re5 nil t)
9927 (goto-char (match-beginning 1))
9928 (goto-char pos)
9929 (error "No match"))))))
9930 (and (eq major-mode 'org-mode)
9931 (not stealth)
9932 (org-show-context 'link-search))
9933 type))
9935 (defun org-search-not-self (group &rest args)
9936 "Execute `re-search-forward', but only accept matches that do not
9937 enclose the position of `org-open-link-marker'."
9938 (let ((m org-open-link-marker))
9939 (catch 'exit
9940 (while (apply 're-search-forward args)
9941 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
9942 (goto-char (match-end group))
9943 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
9944 (> (match-beginning 0) (marker-position m))
9945 (< (match-end 0) (marker-position m)))
9946 (save-match-data
9947 (or (not (org-in-regexp
9948 org-bracket-link-analytic-regexp 1))
9949 (not (match-end 4)) ; no description
9950 (and (<= (match-beginning 4) (point))
9951 (>= (match-end 4) (point))))))
9952 (throw 'exit (point))))))))
9954 (defun org-get-buffer-for-internal-link (buffer)
9955 "Return a buffer to be used for displaying the link target of internal links."
9956 (cond
9957 ((not org-display-internal-link-with-indirect-buffer)
9958 buffer)
9959 ((string-match "(Clone)$" (buffer-name buffer))
9960 (message "Buffer is already a clone, not making another one")
9961 ;; we also do not modify visibility in this case
9962 buffer)
9963 (t ; make a new indirect buffer for displaying the link
9964 (let* ((bn (buffer-name buffer))
9965 (ibn (concat bn "(Clone)"))
9966 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
9967 (with-current-buffer ib (org-overview))
9968 ib))))
9970 (defun org-do-occur (regexp &optional cleanup)
9971 "Call the Emacs command `occur'.
9972 If CLEANUP is non-nil, remove the printout of the regular expression
9973 in the *Occur* buffer. This is useful if the regex is long and not useful
9974 to read."
9975 (occur regexp)
9976 (when cleanup
9977 (let ((cwin (selected-window)) win beg end)
9978 (when (setq win (get-buffer-window "*Occur*"))
9979 (select-window win))
9980 (goto-char (point-min))
9981 (when (re-search-forward "match[a-z]+" nil t)
9982 (setq beg (match-end 0))
9983 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
9984 (setq end (1- (match-beginning 0)))))
9985 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
9986 (goto-char (point-min))
9987 (select-window cwin))))
9989 ;;; The mark ring for links jumps
9991 (defvar org-mark-ring nil
9992 "Mark ring for positions before jumps in Org-mode.")
9993 (defvar org-mark-ring-last-goto nil
9994 "Last position in the mark ring used to go back.")
9995 ;; Fill and close the ring
9996 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
9997 (loop for i from 1 to org-mark-ring-length do
9998 (push (make-marker) org-mark-ring))
9999 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10000 org-mark-ring)
10002 (defun org-mark-ring-push (&optional pos buffer)
10003 "Put the current position or POS into the mark ring and rotate it."
10004 (interactive)
10005 (setq pos (or pos (point)))
10006 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10007 (move-marker (car org-mark-ring)
10008 (or pos (point))
10009 (or buffer (current-buffer)))
10010 (message "%s"
10011 (substitute-command-keys
10012 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10014 (defun org-mark-ring-goto (&optional n)
10015 "Jump to the previous position in the mark ring.
10016 With prefix arg N, jump back that many stored positions. When
10017 called several times in succession, walk through the entire ring.
10018 Org-mode commands jumping to a different position in the current file,
10019 or to another Org-mode file, automatically push the old position
10020 onto the ring."
10021 (interactive "p")
10022 (let (p m)
10023 (if (eq last-command this-command)
10024 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10025 (setq p org-mark-ring))
10026 (setq org-mark-ring-last-goto p)
10027 (setq m (car p))
10028 (org-pop-to-buffer-same-window (marker-buffer m))
10029 (goto-char m)
10030 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10032 (defun org-remove-angle-brackets (s)
10033 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10034 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10036 (defun org-add-angle-brackets (s)
10037 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10038 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10040 (defun org-remove-double-quotes (s)
10041 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10042 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10045 ;;; Following specific links
10047 (defun org-follow-timestamp-link ()
10048 (cond
10049 ((org-at-date-range-p t)
10050 (let ((org-agenda-start-on-weekday)
10051 (t1 (match-string 1))
10052 (t2 (match-string 2)))
10053 (setq t1 (time-to-days (org-time-string-to-time t1))
10054 t2 (time-to-days (org-time-string-to-time t2)))
10055 (org-agenda-list nil t1 (1+ (- t2 t1)))))
10056 ((org-at-timestamp-p t)
10057 (org-agenda-list nil (time-to-days (org-time-string-to-time
10058 (substring (match-string 1) 0 10)))
10060 (t (error "This should not happen"))))
10063 ;;; Following file links
10064 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10065 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10066 (declare-function mailcap-mime-info
10067 "mailcap" (string &optional request no-decode))
10068 (defvar org-wait nil)
10069 (defun org-open-file (path &optional in-emacs line search)
10070 "Open the file at PATH.
10071 First, this expands any special file name abbreviations. Then the
10072 configuration variable `org-file-apps' is checked if it contains an
10073 entry for this file type, and if yes, the corresponding command is launched.
10075 If no application is found, Emacs simply visits the file.
10077 With optional prefix argument IN-EMACS, Emacs will visit the file.
10078 With a double \\[universal-argument] \\[universal-argument] \
10079 prefix arg, Org tries to avoid opening in Emacs
10080 and to use an external application to visit the file.
10082 Optional LINE specifies a line to go to, optional SEARCH a string
10083 to search for. If LINE or SEARCH is given, the file will be
10084 opened in Emacs, unless an entry from org-file-apps that makes
10085 use of groups in a regexp matches.
10087 If you want to change the way frames are used when following a
10088 link, please customize `org-link-frame-setup'.
10090 If the file does not exist, an error is thrown."
10091 (let* ((file (if (equal path "")
10092 buffer-file-name
10093 (substitute-in-file-name (expand-file-name path))))
10094 (file-apps (append org-file-apps (org-default-apps)))
10095 (apps (org-remove-if
10096 'org-file-apps-entry-match-against-dlink-p file-apps))
10097 (apps-dlink (org-remove-if-not
10098 'org-file-apps-entry-match-against-dlink-p file-apps))
10099 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10100 (dirp (if remp nil (file-directory-p file)))
10101 (file (if (and dirp org-open-directory-means-index-dot-org)
10102 (concat (file-name-as-directory file) "index.org")
10103 file))
10104 (a-m-a-p (assq 'auto-mode apps))
10105 (dfile (downcase file))
10106 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10107 (link (cond ((and (eq line nil)
10108 (eq search nil))
10109 file)
10110 (line
10111 (concat file "::" (number-to-string line)))
10112 (search
10113 (concat file "::" search))))
10114 (dlink (downcase link))
10115 (old-buffer (current-buffer))
10116 (old-pos (point))
10117 (old-mode major-mode)
10118 ext cmd link-match-data)
10119 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10120 (setq ext (match-string 1 dfile))
10121 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10122 (setq ext (match-string 1 dfile))))
10123 (cond
10124 ((member in-emacs '((16) system))
10125 (setq cmd (cdr (assoc 'system apps))))
10126 (in-emacs (setq cmd 'emacs))
10128 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10129 (and dirp (cdr (assoc 'directory apps)))
10130 ; first, try matching against apps-dlink
10131 ; if we get a match here, store the match data for later
10132 (let ((match (assoc-default dlink apps-dlink
10133 'string-match)))
10134 (if match
10135 (progn (setq link-match-data (match-data))
10136 match)
10137 (progn (setq in-emacs (or in-emacs line search))
10138 nil))) ; if we have no match in apps-dlink,
10139 ; always open the file in emacs if line or search
10140 ; is given (for backwards compatibility)
10141 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10142 'string-match)
10143 (cdr (assoc ext apps))
10144 (cdr (assoc t apps))))))
10145 (when (eq cmd 'system)
10146 (setq cmd (cdr (assoc 'system apps))))
10147 (when (eq cmd 'default)
10148 (setq cmd (cdr (assoc t apps))))
10149 (when (eq cmd 'mailcap)
10150 (require 'mailcap)
10151 (mailcap-parse-mailcaps)
10152 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10153 (command (mailcap-mime-info mime-type)))
10154 (if (stringp command)
10155 (setq cmd command)
10156 (setq cmd 'emacs))))
10157 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10158 (not (file-exists-p file))
10159 (not org-open-non-existing-files))
10160 (error "No such file: %s" file))
10161 (cond
10162 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10163 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10164 (while (string-match "['\"]%s['\"]" cmd)
10165 (setq cmd (replace-match "%s" t t cmd)))
10166 (while (string-match "%s" cmd)
10167 (setq cmd (replace-match
10168 (save-match-data
10169 (shell-quote-argument
10170 (convert-standard-filename file)))
10171 t t cmd)))
10173 ;; Replace "%1", "%2" etc. in command with group matches from regex
10174 (save-match-data
10175 (let ((match-index 1)
10176 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10177 (set-match-data link-match-data)
10178 (while (<= match-index number-of-groups)
10179 (let ((regex (concat "%" (number-to-string match-index)))
10180 (replace-with (match-string match-index dlink)))
10181 (while (string-match regex cmd)
10182 (setq cmd (replace-match replace-with t t cmd))))
10183 (setq match-index (+ match-index 1)))))
10185 (save-window-excursion
10186 (start-process-shell-command cmd nil cmd)
10187 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
10189 ((or (stringp cmd)
10190 (eq cmd 'emacs))
10191 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10192 (widen)
10193 (if line (org-goto-line line)
10194 (if search (org-link-search search))))
10195 ((consp cmd)
10196 (let ((file (convert-standard-filename file)))
10197 (save-match-data
10198 (set-match-data link-match-data)
10199 (eval cmd))))
10200 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10201 (and (eq major-mode 'org-mode) (eq old-mode 'org-mode)
10202 (or (not (equal old-buffer (current-buffer)))
10203 (not (equal old-pos (point))))
10204 (org-mark-ring-push old-pos old-buffer))))
10206 (defun org-file-apps-entry-match-against-dlink-p (entry)
10207 "This function returns non-nil if `entry' uses a regular
10208 expression which should be matched against the whole link by
10209 org-open-file.
10211 It assumes that is the case when the entry uses a regular
10212 expression which has at least one grouping construct and the
10213 action is either a lisp form or a command string containing
10214 '%1', i.e. using at least one subexpression match as a
10215 parameter."
10216 (let ((selector (car entry))
10217 (action (cdr entry)))
10218 (if (stringp selector)
10219 (and (> (regexp-opt-depth selector) 0)
10220 (or (and (stringp action)
10221 (string-match "%[0-9]" action))
10222 (consp action)))
10223 nil)))
10225 (defun org-default-apps ()
10226 "Return the default applications for this operating system."
10227 (cond
10228 ((eq system-type 'darwin)
10229 org-file-apps-defaults-macosx)
10230 ((eq system-type 'windows-nt)
10231 org-file-apps-defaults-windowsnt)
10232 (t org-file-apps-defaults-gnu)))
10234 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10235 "Convert extensions to regular expressions in the cars of LIST.
10236 Also, weed out any non-string entries, because the return value is used
10237 only for regexp matching.
10238 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10239 point to the symbol `emacs', indicating that the file should
10240 be opened in Emacs."
10241 (append
10242 (delq nil
10243 (mapcar (lambda (x)
10244 (if (not (stringp (car x)))
10246 (if (string-match "\\W" (car x))
10248 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10249 list))
10250 (if add-auto-mode
10251 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10253 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10254 (defun org-file-remote-p (file)
10255 "Test whether FILE specifies a location on a remote system.
10256 Return non-nil if the location is indeed remote.
10258 For example, the filename \"/user@host:/foo\" specifies a location
10259 on the system \"/user@host:\"."
10260 (cond ((fboundp 'file-remote-p)
10261 (file-remote-p file))
10262 ((fboundp 'tramp-handle-file-remote-p)
10263 (tramp-handle-file-remote-p file))
10264 ((and (boundp 'ange-ftp-name-format)
10265 (string-match (car ange-ftp-name-format) file))
10267 (t nil)))
10270 ;;;; Refiling
10272 (defun org-get-org-file ()
10273 "Read a filename, with default directory `org-directory'."
10274 (let ((default (or org-default-notes-file remember-data-file)))
10275 (read-file-name (format "File name [%s]: " default)
10276 (file-name-as-directory org-directory)
10277 default)))
10279 (defun org-notes-order-reversed-p ()
10280 "Check if the current file should receive notes in reversed order."
10281 (cond
10282 ((not org-reverse-note-order) nil)
10283 ((eq t org-reverse-note-order) t)
10284 ((not (listp org-reverse-note-order)) nil)
10285 (t (catch 'exit
10286 (let ((all org-reverse-note-order)
10287 entry)
10288 (while (setq entry (pop all))
10289 (if (string-match (car entry) buffer-file-name)
10290 (throw 'exit (cdr entry))))
10291 nil)))))
10293 (defvar org-refile-target-table nil
10294 "The list of refile targets, created by `org-refile'.")
10296 (defvar org-agenda-new-buffers nil
10297 "Buffers created to visit agenda files.")
10299 (defvar org-refile-cache nil
10300 "Cache for refile targets.")
10302 (defvar org-refile-markers nil
10303 "All the markers used for caching refile locations.")
10305 (defun org-refile-marker (pos)
10306 "Get a new refile marker, but only if caching is in use."
10307 (if (not org-refile-use-cache)
10309 (let ((m (make-marker)))
10310 (move-marker m pos)
10311 (push m org-refile-markers)
10312 m)))
10314 (defun org-refile-cache-clear ()
10315 "Clear the refile cache and disable all the markers."
10316 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
10317 (setq org-refile-markers nil)
10318 (setq org-refile-cache nil)
10319 (message "Refile cache has been cleared"))
10321 (defun org-refile-cache-check-set (set)
10322 "Check if all the markers in the cache still have live buffers."
10323 (let (marker)
10324 (catch 'exit
10325 (while (and set (setq marker (nth 3 (pop set))))
10326 ;; if org-refile-use-outline-path is 'file, marker may be nil
10327 (when (and marker (null (marker-buffer marker)))
10328 (message "not found") (sit-for 3)
10329 (throw 'exit nil)))
10330 t)))
10332 (defun org-refile-cache-put (set &rest identifiers)
10333 "Push the refile targets SET into the cache, under IDENTIFIERS."
10334 (let* ((key (sha1 (prin1-to-string identifiers)))
10335 (entry (assoc key org-refile-cache)))
10336 (if entry
10337 (setcdr entry set)
10338 (push (cons key set) org-refile-cache))))
10340 (defun org-refile-cache-get (&rest identifiers)
10341 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10342 (cond
10343 ((not org-refile-cache) nil)
10344 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10346 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10347 org-refile-cache))))
10348 (and set (org-refile-cache-check-set set) set)))))
10350 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
10351 "Produce a table with refile targets."
10352 (let ((case-fold-search nil)
10353 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10354 (entries (or org-refile-targets '((nil . (:level . 1)))))
10355 targets tgs txt re files f desc descre fast-path-p level pos0)
10356 (message "Getting targets...")
10357 (with-current-buffer (or default-buffer (current-buffer))
10358 (while (setq entry (pop entries))
10359 (setq files (car entry) desc (cdr entry))
10360 (setq fast-path-p nil)
10361 (cond
10362 ((null files) (setq files (list (current-buffer))))
10363 ((eq files 'org-agenda-files)
10364 (setq files (org-agenda-files 'unrestricted)))
10365 ((and (symbolp files) (fboundp files))
10366 (setq files (funcall files)))
10367 ((and (symbolp files) (boundp files))
10368 (setq files (symbol-value files))))
10369 (if (stringp files) (setq files (list files)))
10370 (cond
10371 ((eq (car desc) :tag)
10372 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
10373 ((eq (car desc) :todo)
10374 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
10375 ((eq (car desc) :regexp)
10376 (setq descre (cdr desc)))
10377 ((eq (car desc) :level)
10378 (setq descre (concat "^\\*\\{" (number-to-string
10379 (if org-odd-levels-only
10380 (1- (* 2 (cdr desc)))
10381 (cdr desc)))
10382 "\\}[ \t]")))
10383 ((eq (car desc) :maxlevel)
10384 (setq fast-path-p t)
10385 (setq descre (concat "^\\*\\{1," (number-to-string
10386 (if org-odd-levels-only
10387 (1- (* 2 (cdr desc)))
10388 (cdr desc)))
10389 "\\}[ \t]")))
10390 (t (error "Bad refiling target description %s" desc)))
10391 (while (setq f (pop files))
10392 (with-current-buffer
10393 (if (bufferp f) f (org-get-agenda-file-buffer f))
10395 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
10396 (progn
10397 (if (bufferp f) (setq f (buffer-file-name
10398 (buffer-base-buffer f))))
10399 (setq f (and f (expand-file-name f)))
10400 (if (eq org-refile-use-outline-path 'file)
10401 (push (list (file-name-nondirectory f) f nil nil) tgs))
10402 (save-excursion
10403 (save-restriction
10404 (widen)
10405 (goto-char (point-min))
10406 (while (re-search-forward descre nil t)
10407 (goto-char (setq pos0 (point-at-bol)))
10408 (catch 'next
10409 (when org-refile-target-verify-function
10410 (save-match-data
10411 (or (funcall org-refile-target-verify-function)
10412 (throw 'next t))))
10413 (when (and (looking-at org-complex-heading-regexp)
10414 (not (member (match-string 4) excluded-entries)))
10415 (setq level (org-reduced-level
10416 (- (match-end 1) (match-beginning 1)))
10417 txt (org-link-display-format (match-string 4))
10418 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
10419 re (format org-complex-heading-regexp-format
10420 (regexp-quote (match-string 4))))
10421 (when org-refile-use-outline-path
10422 (setq txt (mapconcat
10423 'org-protect-slash
10424 (append
10425 (if (eq org-refile-use-outline-path
10426 'file)
10427 (list (file-name-nondirectory
10428 (buffer-file-name
10429 (buffer-base-buffer))))
10430 (if (eq org-refile-use-outline-path
10431 'full-file-path)
10432 (list (buffer-file-name
10433 (buffer-base-buffer)))))
10434 (org-get-outline-path fast-path-p
10435 level txt)
10436 (list txt))
10437 "/")))
10438 (push (list txt f re (org-refile-marker (point)))
10439 tgs)))
10440 (when (= (point) pos0)
10441 ;; verification function has not moved point
10442 (goto-char (point-at-eol))))))))
10443 (when org-refile-use-cache
10444 (org-refile-cache-put tgs (buffer-file-name) descre))
10445 (setq targets (append tgs targets))
10446 ))))
10447 (message "Getting targets...done")
10448 (nreverse targets)))
10450 (defun org-protect-slash (s)
10451 (while (string-match "/" s)
10452 (setq s (replace-match "\\" t t s)))
10455 (defvar org-olpa (make-vector 20 nil))
10457 (defun org-get-outline-path (&optional fastp level heading)
10458 "Return the outline path to the current entry, as a list.
10460 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
10461 routine which makes outline path derivations for an entire file,
10462 avoiding backtracing. Refile target collection makes use of that."
10463 (if fastp
10464 (progn
10465 (if (> level 19)
10466 (error "Outline path failure, more than 19 levels"))
10467 (loop for i from level upto 19 do
10468 (aset org-olpa i nil))
10469 (prog1
10470 (delq nil (append org-olpa nil))
10471 (aset org-olpa level heading)))
10472 (let (rtn case-fold-search)
10473 (save-excursion
10474 (save-restriction
10475 (widen)
10476 (while (org-up-heading-safe)
10477 (when (looking-at org-complex-heading-regexp)
10478 (push (org-match-string-no-properties 4) rtn)))
10479 rtn)))))
10481 (defun org-format-outline-path (path &optional width prefix)
10482 "Format the outline path PATH for display.
10483 Width is the maximum number of characters that is available.
10484 Prefix is a prefix to be included in the returned string,
10485 such as the file name."
10486 (setq width (or width 79))
10487 (if prefix (setq width (- width (length prefix))))
10488 (if (not path)
10489 (or prefix "")
10490 (let* ((nsteps (length path))
10491 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
10492 (maxwidth (if (<= total-width width)
10493 10000 ;; everything fits
10494 ;; we need to shorten the level headings
10495 (/ (- width nsteps) nsteps)))
10496 (org-odd-levels-only nil)
10497 (n 0)
10498 (total (1+ (length prefix))))
10499 (setq maxwidth (max maxwidth 10))
10500 (concat prefix
10501 (mapconcat
10502 (lambda (h)
10503 (setq n (1+ n))
10504 (if (and (= n nsteps) (< maxwidth 10000))
10505 (setq maxwidth (- total-width total)))
10506 (if (< (length h) maxwidth)
10507 (progn (setq total (+ total (length h) 1)) h)
10508 (setq h (substring h 0 (- maxwidth 2))
10509 total (+ total maxwidth 1))
10510 (if (string-match "[ \t]+\\'" h)
10511 (setq h (substring h 0 (match-beginning 0))))
10512 (setq h (concat h "..")))
10513 (org-add-props h nil 'face
10514 (nth (% (1- n) org-n-level-faces)
10515 org-level-faces))
10517 path "/")))))
10519 (defun org-display-outline-path (&optional file current)
10520 "Display the current outline path in the echo area."
10521 (interactive "P")
10522 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
10523 (case-fold-search nil)
10524 (path (and (eq major-mode 'org-mode) (org-get-outline-path))))
10525 (if current (setq path (append path
10526 (save-excursion
10527 (org-back-to-heading t)
10528 (if (looking-at org-complex-heading-regexp)
10529 (list (match-string 4)))))))
10530 (message "%s"
10531 (org-format-outline-path
10532 path
10533 (1- (frame-width))
10534 (and file bfn (concat (file-name-nondirectory bfn) "/"))))))
10536 (defvar org-refile-history nil
10537 "History for refiling operations.")
10539 (defvar org-after-refile-insert-hook nil
10540 "Hook run after `org-refile' has inserted its stuff at the new location.
10541 Note that this is still *before* the stuff will be removed from
10542 the *old* location.")
10544 (defvar org-capture-last-stored-marker)
10545 (defun org-refile (&optional goto default-buffer rfloc)
10546 "Move the entry or entries at point to another heading.
10547 The list of target headings is compiled using the information in
10548 `org-refile-targets', which see.
10550 At the target location, the entry is filed as a subitem of the target
10551 heading. Depending on `org-reverse-note-order', the new subitem will
10552 either be the first or the last subitem.
10554 If there is an active region, all entries in that region will be moved.
10555 However, the region must fulfill the requirement that the first heading
10556 is the first one sets the top-level of the moved text - at most siblings
10557 below it are allowed.
10559 With prefix arg GOTO, the command will only visit the target location
10560 and not actually move anything.
10562 With a double prefix arg \\[universal-argument] \\[universal-argument], \
10563 go to the location where the last refiling operation has put the subtree.
10564 With a prefix argument of `2', refile to the running clock.
10566 RFLOC can be a refile location obtained in a different way.
10568 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
10570 If you are using target caching (see `org-refile-use-cache'),
10571 You have to clear the target cache in order to find new targets.
10572 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
10573 prefix argument (`C-u C-u C-u C-c C-w')."
10575 (interactive "P")
10576 (if (member goto '(0 (64)))
10577 (org-refile-cache-clear)
10578 (let* ((cbuf (current-buffer))
10579 (regionp (org-region-active-p))
10580 (region-start (and regionp (region-beginning)))
10581 (region-end (and regionp (region-end)))
10582 (region-length (and regionp (- region-end region-start)))
10583 (filename (buffer-file-name (buffer-base-buffer cbuf)))
10584 pos it nbuf file re level reversed)
10585 (setq last-command nil)
10586 (when regionp
10587 (goto-char region-start)
10588 (or (bolp) (goto-char (point-at-bol)))
10589 (setq region-start (point))
10590 (unless (or (org-kill-is-subtree-p
10591 (buffer-substring region-start region-end))
10592 (prog1 org-refile-active-region-within-subtree
10593 (org-toggle-heading)))
10594 (error "The region is not a (sequence of) subtree(s)")))
10595 (if (equal goto '(16))
10596 (org-refile-goto-last-stored)
10597 (when (or
10598 (and (equal goto 2)
10599 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
10600 (prog1
10601 (setq it (list (or org-clock-heading "running clock")
10602 (buffer-file-name
10603 (marker-buffer org-clock-hd-marker))
10605 (marker-position org-clock-hd-marker)))
10606 (setq goto nil)))
10607 (setq it (or rfloc
10608 (let (heading-text)
10609 (save-excursion
10610 (unless goto
10611 (org-back-to-heading t)
10612 (setq heading-text
10613 (nth 4 (org-heading-components))))
10614 (org-refile-get-location
10615 (cond (goto "Goto")
10616 (regionp "Refile region to")
10617 (t (concat "Refile subtree \""
10618 heading-text "\" to")))
10619 default-buffer
10620 org-refile-allow-creating-parent-nodes
10621 goto))))))
10622 (setq file (nth 1 it)
10623 re (nth 2 it)
10624 pos (nth 3 it))
10625 (if (and (not goto)
10627 (equal (buffer-file-name) file)
10628 (if regionp
10629 (and (>= pos region-start)
10630 (<= pos region-end))
10631 (and (>= pos (point))
10632 (< pos (save-excursion
10633 (org-end-of-subtree t t))))))
10634 (error "Cannot refile to position inside the tree or region"))
10636 (setq nbuf (or (find-buffer-visiting file)
10637 (find-file-noselect file)))
10638 (if goto
10639 (progn
10640 (org-pop-to-buffer-same-window nbuf)
10641 (goto-char pos)
10642 (org-show-context 'org-goto))
10643 (if regionp
10644 (progn
10645 (org-kill-new (buffer-substring region-start region-end))
10646 (org-save-markers-in-region region-start region-end))
10647 (org-copy-subtree 1 nil t))
10648 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
10649 (find-file-noselect file)))
10650 (setq reversed (org-notes-order-reversed-p))
10651 (save-excursion
10652 (save-restriction
10653 (widen)
10654 (if pos
10655 (progn
10656 (goto-char pos)
10657 (looking-at org-outline-regexp)
10658 (setq level (org-get-valid-level (funcall outline-level) 1))
10659 (goto-char
10660 (if reversed
10661 (or (outline-next-heading) (point-max))
10662 (or (save-excursion (org-get-next-sibling))
10663 (org-end-of-subtree t t)
10664 (point-max)))))
10665 (setq level 1)
10666 (if (not reversed)
10667 (goto-char (point-max))
10668 (goto-char (point-min))
10669 (or (outline-next-heading) (goto-char (point-max)))))
10670 (if (not (bolp)) (newline))
10671 (org-paste-subtree level)
10672 (when org-log-refile
10673 (org-add-log-setup 'refile nil nil 'findpos
10674 org-log-refile)
10675 (unless (eq org-log-refile 'note)
10676 (save-excursion (org-add-log-note))))
10677 (and org-auto-align-tags (org-set-tags nil t))
10678 (bookmark-set "org-refile-last-stored")
10679 ;; If we are refiling for capture, make sure that the
10680 ;; last-capture pointers point here
10681 (when (org-bound-and-true-p org-refile-for-capture)
10682 (bookmark-set "org-capture-last-stored-marker")
10683 (move-marker org-capture-last-stored-marker (point)))
10684 (if (fboundp 'deactivate-mark) (deactivate-mark))
10685 (run-hooks 'org-after-refile-insert-hook))))
10686 (if regionp
10687 (delete-region (point) (+ (point) region-length))
10688 (org-cut-subtree))
10689 (when (featurep 'org-inlinetask)
10690 (org-inlinetask-remove-END-maybe))
10691 (setq org-markers-to-move nil)
10692 (message "Refiled to \"%s\" in file %s" (car it) file)))))))
10694 (defun org-refile-goto-last-stored ()
10695 "Go to the location where the last refile was stored."
10696 (interactive)
10697 (bookmark-jump "org-refile-last-stored")
10698 (message "This is the location of the last refile"))
10700 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
10701 no-exclude)
10702 "Prompt the user for a refile location, using PROMPT.
10703 PROMPT should not be suffixed with a colon and a space, because
10704 this function appends the default value from
10705 `org-refile-history' automatically, if that is not empty.
10706 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
10707 this is used for the GOTO interface."
10708 (let ((org-refile-targets org-refile-targets)
10709 (org-refile-use-outline-path org-refile-use-outline-path)
10710 excluded-entries)
10711 (when (and (eq major-mode 'org-mode)
10712 (not org-refile-use-cache)
10713 (not no-exclude))
10714 (org-map-tree
10715 (lambda()
10716 (setq excluded-entries
10717 (append excluded-entries (list (org-get-heading t t)))))))
10718 (setq org-refile-target-table
10719 (org-refile-get-targets default-buffer excluded-entries)))
10720 (unless org-refile-target-table
10721 (error "No refile targets"))
10722 (let* ((prompt (concat prompt
10723 (and (car org-refile-history)
10724 (concat " (default " (car org-refile-history) ")"))
10725 ": "))
10726 (cbuf (current-buffer))
10727 (partial-completion-mode nil)
10728 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
10729 (cfunc (if (and org-refile-use-outline-path
10730 org-outline-path-complete-in-steps)
10731 'org-olpath-completing-read
10732 'org-icompleting-read))
10733 (extra (if org-refile-use-outline-path "/" ""))
10734 (filename (and cfn (expand-file-name cfn)))
10735 (tbl (mapcar
10736 (lambda (x)
10737 (if (and (not (member org-refile-use-outline-path
10738 '(file full-file-path)))
10739 (not (equal filename (nth 1 x))))
10740 (cons (concat (car x) extra " ("
10741 (file-name-nondirectory (nth 1 x)) ")")
10742 (cdr x))
10743 (cons (concat (car x) extra) (cdr x))))
10744 org-refile-target-table))
10745 (completion-ignore-case t)
10746 pa answ parent-target child parent old-hist)
10747 (setq old-hist org-refile-history)
10748 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
10749 nil 'org-refile-history (car org-refile-history)))
10750 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
10751 (org-refile-check-position pa)
10752 (if pa
10753 (progn
10754 (when (or (not org-refile-history)
10755 (not (eq old-hist org-refile-history))
10756 (not (equal (car pa) (car org-refile-history))))
10757 (setq org-refile-history
10758 (cons (car pa) (if (assoc (car org-refile-history) tbl)
10759 org-refile-history
10760 (cdr org-refile-history))))
10761 (if (equal (car org-refile-history) (nth 1 org-refile-history))
10762 (pop org-refile-history)))
10764 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
10765 (progn
10766 (setq parent (match-string 1 answ)
10767 child (match-string 2 answ))
10768 (setq parent-target (or (assoc parent tbl)
10769 (assoc (concat parent "/") tbl)))
10770 (when (and parent-target
10771 (or (eq new-nodes t)
10772 (and (eq new-nodes 'confirm)
10773 (y-or-n-p (format "Create new node \"%s\"? "
10774 child)))))
10775 (org-refile-new-child parent-target child)))
10776 (error "Invalid target location")))))
10778 (defun org-refile-check-position (refile-pointer)
10779 "Check if the refile pointer matches the readline to which it points."
10780 (let* ((file (nth 1 refile-pointer))
10781 (re (nth 2 refile-pointer))
10782 (pos (nth 3 refile-pointer))
10783 buffer)
10784 (when (org-string-nw-p re)
10785 (setq buffer (if (markerp pos)
10786 (marker-buffer pos)
10787 (or (find-buffer-visiting file)
10788 (find-file-noselect file))))
10789 (with-current-buffer buffer
10790 (save-excursion
10791 (save-restriction
10792 (widen)
10793 (goto-char pos)
10794 (beginning-of-line 1)
10795 (unless (org-looking-at-p re)
10796 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
10798 (defun org-refile-new-child (parent-target child)
10799 "Use refile target PARENT-TARGET to add new CHILD below it."
10800 (unless parent-target
10801 (error "Cannot find parent for new node"))
10802 (let ((file (nth 1 parent-target))
10803 (pos (nth 3 parent-target))
10804 level)
10805 (with-current-buffer (or (find-buffer-visiting file)
10806 (find-file-noselect file))
10807 (save-excursion
10808 (save-restriction
10809 (widen)
10810 (if pos
10811 (goto-char pos)
10812 (goto-char (point-max))
10813 (if (not (bolp)) (newline)))
10814 (when (looking-at org-outline-regexp)
10815 (setq level (funcall outline-level))
10816 (org-end-of-subtree t t))
10817 (org-back-over-empty-lines)
10818 (insert "\n" (make-string
10819 (if pos (org-get-valid-level level 1) 1) ?*)
10820 " " child "\n")
10821 (beginning-of-line 0)
10822 (list (concat (car parent-target) "/" child) file "" (point)))))))
10824 (defun org-olpath-completing-read (prompt collection &rest args)
10825 "Read an outline path like a file name."
10826 (let ((thetable collection)
10827 (org-completion-use-ido nil) ; does not work with ido.
10828 (org-completion-use-iswitchb nil)) ; or iswitchb
10829 (apply
10830 'org-icompleting-read prompt
10831 (lambda (string predicate &optional flag)
10832 (let (rtn r f (l (length string)))
10833 (cond
10834 ((eq flag nil)
10835 ;; try completion
10836 (try-completion string thetable))
10837 ((eq flag t)
10838 ;; all-completions
10839 (setq rtn (all-completions string thetable predicate))
10840 (mapcar
10841 (lambda (x)
10842 (setq r (substring x l))
10843 (if (string-match " ([^)]*)$" x)
10844 (setq f (match-string 0 x))
10845 (setq f ""))
10846 (if (string-match "/" r)
10847 (concat string (substring r 0 (match-end 0)) f)
10849 rtn))
10850 ((eq flag 'lambda)
10851 ;; exact match?
10852 (assoc string thetable)))
10854 args)))
10856 ;;;; Dynamic blocks
10858 (defun org-find-dblock (name)
10859 "Find the first dynamic block with name NAME in the buffer.
10860 If not found, stay at current position and return nil."
10861 (let (pos)
10862 (save-excursion
10863 (goto-char (point-min))
10864 (setq pos (and (re-search-forward (concat "^[ \t]*#\\+BEGIN:[ \t]+" name "\\>")
10865 nil t)
10866 (match-beginning 0))))
10867 (if pos (goto-char pos))
10868 pos))
10870 (defconst org-dblock-start-re
10871 "^[ \t]*#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
10872 "Matches the start line of a dynamic block, with parameters.")
10874 (defconst org-dblock-end-re "^[ \t]*#\\+END\\([: \t\r\n]\\|$\\)"
10875 "Matches the end of a dynamic block.")
10877 (defun org-create-dblock (plist)
10878 "Create a dynamic block section, with parameters taken from PLIST.
10879 PLIST must contain a :name entry which is used as name of the block."
10880 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
10881 (end-of-line 1)
10882 (newline))
10883 (let ((col (current-column))
10884 (name (plist-get plist :name)))
10885 (insert "#+BEGIN: " name)
10886 (while plist
10887 (if (eq (car plist) :name)
10888 (setq plist (cddr plist))
10889 (insert " " (prin1-to-string (pop plist)))))
10890 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
10891 (beginning-of-line -2)))
10893 (defun org-prepare-dblock ()
10894 "Prepare dynamic block for refresh.
10895 This empties the block, puts the cursor at the insert position and returns
10896 the property list including an extra property :name with the block name."
10897 (unless (looking-at org-dblock-start-re)
10898 (error "Not at a dynamic block"))
10899 (let* ((begdel (1+ (match-end 0)))
10900 (name (org-no-properties (match-string 1)))
10901 (params (append (list :name name)
10902 (read (concat "(" (match-string 3) ")")))))
10903 (save-excursion
10904 (beginning-of-line 1)
10905 (skip-chars-forward " \t")
10906 (setq params (plist-put params :indentation-column (current-column))))
10907 (unless (re-search-forward org-dblock-end-re nil t)
10908 (error "Dynamic block not terminated"))
10909 (setq params
10910 (append params
10911 (list :content (buffer-substring
10912 begdel (match-beginning 0)))))
10913 (delete-region begdel (match-beginning 0))
10914 (goto-char begdel)
10915 (open-line 1)
10916 params))
10918 (defun org-map-dblocks (&optional command)
10919 "Apply COMMAND to all dynamic blocks in the current buffer.
10920 If COMMAND is not given, use `org-update-dblock'."
10921 (let ((cmd (or command 'org-update-dblock)))
10922 (save-excursion
10923 (goto-char (point-min))
10924 (while (re-search-forward org-dblock-start-re nil t)
10925 (goto-char (match-beginning 0))
10926 (save-excursion
10927 (condition-case nil
10928 (funcall cmd)
10929 (error (message "Error during update of dynamic block"))))
10930 (unless (re-search-forward org-dblock-end-re nil t)
10931 (error "Dynamic block not terminated"))))))
10933 (defun org-dblock-update (&optional arg)
10934 "User command for updating dynamic blocks.
10935 Update the dynamic block at point. With prefix ARG, update all dynamic
10936 blocks in the buffer."
10937 (interactive "P")
10938 (if arg
10939 (org-update-all-dblocks)
10940 (or (looking-at org-dblock-start-re)
10941 (org-beginning-of-dblock))
10942 (org-update-dblock)))
10944 (defun org-update-dblock ()
10945 "Update the dynamic block at point.
10946 This means to empty the block, parse for parameters and then call
10947 the correct writing function."
10948 (interactive)
10949 (save-window-excursion
10950 (let* ((pos (point))
10951 (line (org-current-line))
10952 (params (org-prepare-dblock))
10953 (name (plist-get params :name))
10954 (indent (plist-get params :indentation-column))
10955 (cmd (intern (concat "org-dblock-write:" name))))
10956 (message "Updating dynamic block `%s' at line %d..." name line)
10957 (funcall cmd params)
10958 (message "Updating dynamic block `%s' at line %d...done" name line)
10959 (goto-char pos)
10960 (when (and indent (> indent 0))
10961 (setq indent (make-string indent ?\ ))
10962 (save-excursion
10963 (org-beginning-of-dblock)
10964 (forward-line 1)
10965 (while (not (looking-at org-dblock-end-re))
10966 (insert indent)
10967 (beginning-of-line 2))
10968 (when (looking-at org-dblock-end-re)
10969 (and (looking-at "[ \t]+")
10970 (replace-match ""))
10971 (insert indent)))))))
10973 (defun org-beginning-of-dblock ()
10974 "Find the beginning of the dynamic block at point.
10975 Error if there is no such block at point."
10976 (let ((pos (point))
10977 beg)
10978 (end-of-line 1)
10979 (if (and (re-search-backward org-dblock-start-re nil t)
10980 (setq beg (match-beginning 0))
10981 (re-search-forward org-dblock-end-re nil t)
10982 (> (match-end 0) pos))
10983 (goto-char beg)
10984 (goto-char pos)
10985 (error "Not in a dynamic block"))))
10987 (defun org-update-all-dblocks ()
10988 "Update all dynamic blocks in the buffer.
10989 This function can be used in a hook."
10990 (interactive)
10991 (when (eq major-mode 'org-mode)
10992 (org-map-dblocks 'org-update-dblock)))
10995 ;;;; Completion
10997 (defconst org-additional-option-like-keywords
10998 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML:"
10999 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook:"
11000 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"
11001 "LATEX_CLASS:" "LATEX_CLASS_OPTIONS:" "ATTR_LaTeX:"
11002 "BEGIN:" "END:"
11003 "ORGTBL" "TBLFM:" "TBLNAME:"
11004 "BEGIN_EXAMPLE" "END_EXAMPLE"
11005 "BEGIN_QUOTE" "END_QUOTE"
11006 "BEGIN_VERSE" "END_VERSE"
11007 "BEGIN_CENTER" "END_CENTER"
11008 "BEGIN_SRC" "END_SRC"
11009 "BEGIN_RESULT" "END_RESULT"
11010 "NAME:" "RESULTS:"
11011 "HEADER:" "HEADERS:"
11012 "CATEGORY:" "COLUMNS:" "PROPERTY:"
11013 "CAPTION:" "LABEL:"
11014 "SETUPFILE:"
11015 "INCLUDE:"
11016 "BIND:"
11017 "MACRO:"))
11019 (defcustom org-structure-template-alist
11021 ("s" "#+begin_src ?\n\n#+end_src"
11022 "<src lang=\"?\">\n\n</src>")
11023 ("e" "#+begin_example\n?\n#+end_example"
11024 "<example>\n?\n</example>")
11025 ("q" "#+begin_quote\n?\n#+end_quote"
11026 "<quote>\n?\n</quote>")
11027 ("v" "#+begin_verse\n?\n#+end_verse"
11028 "<verse>\n?\n/verse>")
11029 ("c" "#+begin_center\n?\n#+end_center"
11030 "<center>\n?\n/center>")
11031 ("l" "#+begin_latex\n?\n#+end_latex"
11032 "<literal style=\"latex\">\n?\n</literal>")
11033 ("L" "#+latex: "
11034 "<literal style=\"latex\">?</literal>")
11035 ("h" "#+begin_html\n?\n#+end_html"
11036 "<literal style=\"html\">\n?\n</literal>")
11037 ("H" "#+html: "
11038 "<literal style=\"html\">?</literal>")
11039 ("a" "#+begin_ascii\n?\n#+end_ascii")
11040 ("A" "#+ascii: ")
11041 ("i" "#+index: ?"
11042 "#+index: ?")
11043 ("I" "#+include %file ?"
11044 "<include file=%file markup=\"?\">")
11046 "Structure completion elements.
11047 This is a list of abbreviation keys and values. The value gets inserted
11048 if you type `<' followed by the key and then press the completion key,
11049 usually `M-TAB'. %file will be replaced by a file name after prompting
11050 for the file using completion. The cursor will be placed at the position
11051 of the `?` in the template.
11052 There are two templates for each key, the first uses the original Org syntax,
11053 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11054 the default when the /org-mtags.el/ module has been loaded. See also the
11055 variable `org-mtags-prefer-muse-templates'.
11056 This is an experimental feature, it is undecided if it is going to stay in."
11057 :group 'org-completion
11058 :type '(repeat
11059 (string :tag "Key")
11060 (string :tag "Template")
11061 (string :tag "Muse Template")))
11063 (defun org-try-structure-completion ()
11064 "Try to complete a structure template before point.
11065 This looks for strings like \"<e\" on an otherwise empty line and
11066 expands them."
11067 (let ((l (buffer-substring (point-at-bol) (point)))
11069 (when (and (looking-at "[ \t]*$")
11070 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
11071 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
11072 (org-complete-expand-structure-template (+ -1 (point-at-bol)
11073 (match-beginning 1)) a)
11074 t)))
11076 (defun org-complete-expand-structure-template (start cell)
11077 "Expand a structure template."
11078 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
11079 (rpl (nth (if musep 2 1) cell))
11080 (ind ""))
11081 (delete-region start (point))
11082 (when (string-match "\\`#\\+" rpl)
11083 (cond
11084 ((bolp))
11085 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
11086 (setq ind (buffer-substring (point-at-bol) (point))))
11087 (t (newline))))
11088 (setq start (point))
11089 (if (string-match "%file" rpl)
11090 (setq rpl (replace-match
11091 (concat
11092 "\""
11093 (save-match-data
11094 (abbreviate-file-name (read-file-name "Include file: ")))
11095 "\"")
11096 t t rpl)))
11097 (setq rpl (mapconcat 'identity (split-string rpl "\n")
11098 (concat "\n" ind)))
11099 (insert rpl)
11100 (if (re-search-backward "\\?" start t) (delete-char 1))))
11102 ;;;; TODO, DEADLINE, Comments
11104 (defun org-toggle-comment ()
11105 "Change the COMMENT state of an entry."
11106 (interactive)
11107 (save-excursion
11108 (org-back-to-heading)
11109 (let (case-fold-search)
11110 (cond
11111 ((looking-at (format org-heading-keyword-regexp-format
11112 org-comment-string))
11113 (goto-char (match-end 1))
11114 (looking-at (concat " +" org-comment-string))
11115 (replace-match "" t t)
11116 (when (eolp) (insert " ")))
11117 ((looking-at org-outline-regexp)
11118 (goto-char (match-end 0))
11119 (insert org-comment-string " "))))))
11121 (defvar org-last-todo-state-is-todo nil
11122 "This is non-nil when the last TODO state change led to a TODO state.
11123 If the last change removed the TODO tag or switched to DONE, then
11124 this is nil.")
11126 (defvar org-setting-tags nil) ; dynamically skipped
11128 (defvar org-todo-setup-filter-hook nil
11129 "Hook for functions that pre-filter todo specs.
11130 Each function takes a todo spec and returns either nil or the spec
11131 transformed into canonical form." )
11133 (defvar org-todo-get-default-hook nil
11134 "Hook for functions that get a default item for todo.
11135 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11136 nil or a string to be used for the todo mark." )
11138 (defvar org-agenda-headline-snapshot-before-repeat)
11140 (defun org-current-effective-time ()
11141 "Return current time adjusted for `org-extend-today-until' variable"
11142 (let* ((ct (org-current-time))
11143 (dct (decode-time ct))
11144 (ct1
11145 (if (and org-use-effective-time
11146 (< (nth 2 dct) org-extend-today-until))
11147 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct))
11148 ct)))
11149 ct1))
11151 (defun org-todo-yesterday (&optional arg)
11152 "Like `org-todo' but the time of change will be 23:59 of yesterday"
11153 (interactive "P")
11154 (let* ((hour (third (decode-time
11155 (org-current-time))))
11156 (org-extend-today-until (1+ hour)))
11157 (org-todo arg)))
11159 (defun org-todo (&optional arg)
11160 "Change the TODO state of an item.
11161 The state of an item is given by a keyword at the start of the heading,
11162 like
11163 *** TODO Write paper
11164 *** DONE Call mom
11166 The different keywords are specified in the variable `org-todo-keywords'.
11167 By default the available states are \"TODO\" and \"DONE\".
11168 So for this example: when the item starts with TODO, it is changed to DONE.
11169 When it starts with DONE, the DONE is removed. And when neither TODO nor
11170 DONE are present, add TODO at the beginning of the heading.
11172 With \\[universal-argument] prefix arg, use completion to determine the new \
11173 state.
11174 With numeric prefix arg, switch to that state.
11175 With a double \\[universal-argument] prefix, switch to the next set of TODO \
11176 keywords (nextset).
11177 With a triple \\[universal-argument] prefix, circumvent any state blocking.
11178 With a numeric prefix arg of 0, inhibit note taking for the change.
11180 For calling through lisp, arg is also interpreted in the following way:
11181 'none -> empty state
11182 \"\"(empty string) -> switch to empty state
11183 'done -> switch to DONE
11184 'nextset -> switch to the next set of keywords
11185 'previousset -> switch to the previous set of keywords
11186 \"WAITING\" -> switch to the specified keyword, but only if it
11187 really is a member of `org-todo-keywords'."
11188 (interactive "P")
11189 (if (equal arg '(16)) (setq arg 'nextset))
11190 (let ((org-blocker-hook org-blocker-hook)
11191 (case-fold-search nil))
11192 (when (equal arg '(64))
11193 (setq arg nil org-blocker-hook nil))
11194 (when (and org-blocker-hook
11195 (or org-inhibit-blocking
11196 (org-entry-get nil "NOBLOCKING")))
11197 (setq org-blocker-hook nil))
11198 (save-excursion
11199 (catch 'exit
11200 (org-back-to-heading t)
11201 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
11202 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
11203 (looking-at "\\(?: *\\|[ \t]*$\\)"))
11204 (let* ((match-data (match-data))
11205 (startpos (point-at-bol))
11206 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
11207 (org-log-done org-log-done)
11208 (org-log-repeat org-log-repeat)
11209 (org-todo-log-states org-todo-log-states)
11210 (org-inhibit-logging
11211 (if (equal arg 0)
11212 (progn (setq arg nil) 'note) org-inhibit-logging))
11213 (this (match-string 1))
11214 (hl-pos (match-beginning 0))
11215 (head (org-get-todo-sequence-head this))
11216 (ass (assoc head org-todo-kwd-alist))
11217 (interpret (nth 1 ass))
11218 (done-word (nth 3 ass))
11219 (final-done-word (nth 4 ass))
11220 (last-state (or this ""))
11221 (completion-ignore-case t)
11222 (member (member this org-todo-keywords-1))
11223 (tail (cdr member))
11224 (state (cond
11225 ((and org-todo-key-trigger
11226 (or (and (equal arg '(4))
11227 (eq org-use-fast-todo-selection 'prefix))
11228 (and (not arg) org-use-fast-todo-selection
11229 (not (eq org-use-fast-todo-selection
11230 'prefix)))))
11231 ;; Use fast selection
11232 (org-fast-todo-selection))
11233 ((and (equal arg '(4))
11234 (or (not org-use-fast-todo-selection)
11235 (not org-todo-key-trigger)))
11236 ;; Read a state with completion
11237 (org-icompleting-read
11238 "State: " (mapcar (lambda(x) (list x))
11239 org-todo-keywords-1)
11240 nil t))
11241 ((eq arg 'right)
11242 (if this
11243 (if tail (car tail) nil)
11244 (car org-todo-keywords-1)))
11245 ((eq arg 'left)
11246 (if (equal member org-todo-keywords-1)
11248 (if this
11249 (nth (- (length org-todo-keywords-1)
11250 (length tail) 2)
11251 org-todo-keywords-1)
11252 (org-last org-todo-keywords-1))))
11253 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
11254 (setq arg nil))) ; hack to fall back to cycling
11255 (arg
11256 ;; user or caller requests a specific state
11257 (cond
11258 ((equal arg "") nil)
11259 ((eq arg 'none) nil)
11260 ((eq arg 'done) (or done-word (car org-done-keywords)))
11261 ((eq arg 'nextset)
11262 (or (car (cdr (member head org-todo-heads)))
11263 (car org-todo-heads)))
11264 ((eq arg 'previousset)
11265 (let ((org-todo-heads (reverse org-todo-heads)))
11266 (or (car (cdr (member head org-todo-heads)))
11267 (car org-todo-heads))))
11268 ((car (member arg org-todo-keywords-1)))
11269 ((stringp arg)
11270 (error "State `%s' not valid in this file" arg))
11271 ((nth (1- (prefix-numeric-value arg))
11272 org-todo-keywords-1))))
11273 ((null member) (or head (car org-todo-keywords-1)))
11274 ((equal this final-done-word) nil) ;; -> make empty
11275 ((null tail) nil) ;; -> first entry
11276 ((memq interpret '(type priority))
11277 (if (eq this-command last-command)
11278 (car tail)
11279 (if (> (length tail) 0)
11280 (or done-word (car org-done-keywords))
11281 nil)))
11283 (car tail))))
11284 (state (or
11285 (run-hook-with-args-until-success
11286 'org-todo-get-default-hook state last-state)
11287 state))
11288 (next (if state (concat " " state " ") " "))
11289 (change-plist (list :type 'todo-state-change :from this :to state
11290 :position startpos))
11291 dolog now-done-p)
11292 (when org-blocker-hook
11293 (setq org-last-todo-state-is-todo
11294 (not (member this org-done-keywords)))
11295 (unless (save-excursion
11296 (save-match-data
11297 (org-with-wide-buffer
11298 (run-hook-with-args-until-failure
11299 'org-blocker-hook change-plist))))
11300 (if (org-called-interactively-p 'interactive)
11301 (error "TODO state change from %s to %s blocked" this state)
11302 ;; fail silently
11303 (message "TODO state change from %s to %s blocked" this state)
11304 (throw 'exit nil))))
11305 (store-match-data match-data)
11306 (replace-match next t t)
11307 (unless (pos-visible-in-window-p hl-pos)
11308 (message "TODO state changed to %s" (org-trim next)))
11309 (unless head
11310 (setq head (org-get-todo-sequence-head state)
11311 ass (assoc head org-todo-kwd-alist)
11312 interpret (nth 1 ass)
11313 done-word (nth 3 ass)
11314 final-done-word (nth 4 ass)))
11315 (when (memq arg '(nextset previousset))
11316 (message "Keyword-Set %d/%d: %s"
11317 (- (length org-todo-sets) -1
11318 (length (memq (assoc state org-todo-sets) org-todo-sets)))
11319 (length org-todo-sets)
11320 (mapconcat 'identity (assoc state org-todo-sets) " ")))
11321 (setq org-last-todo-state-is-todo
11322 (not (member state org-done-keywords)))
11323 (setq now-done-p (and (member state org-done-keywords)
11324 (not (member this org-done-keywords))))
11325 (and logging (org-local-logging logging))
11326 (when (and (or org-todo-log-states org-log-done)
11327 (not (eq org-inhibit-logging t))
11328 (not (memq arg '(nextset previousset))))
11329 ;; we need to look at recording a time and note
11330 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
11331 (nth 2 (assoc this org-todo-log-states))))
11332 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
11333 (setq dolog 'time))
11334 (when (and state
11335 (member state org-not-done-keywords)
11336 (not (member this org-not-done-keywords)))
11337 ;; This is now a todo state and was not one before
11338 ;; If there was a CLOSED time stamp, get rid of it.
11339 (org-add-planning-info nil nil 'closed))
11340 (when (and now-done-p org-log-done)
11341 ;; It is now done, and it was not done before
11342 (org-add-planning-info 'closed (org-current-effective-time))
11343 (if (and (not dolog) (eq 'note org-log-done))
11344 (org-add-log-setup 'done state this 'findpos 'note)))
11345 (when (and state dolog)
11346 ;; This is a non-nil state, and we need to log it
11347 (org-add-log-setup 'state state this 'findpos dolog)))
11348 ;; Fixup tag positioning
11349 (org-todo-trigger-tag-changes state)
11350 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
11351 (when org-provide-todo-statistics
11352 (org-update-parent-todo-statistics))
11353 (run-hooks 'org-after-todo-state-change-hook)
11354 (if (and arg (not (member state org-done-keywords)))
11355 (setq head (org-get-todo-sequence-head state)))
11356 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
11357 ;; Do we need to trigger a repeat?
11358 (when now-done-p
11359 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
11360 ;; This is for the agenda, take a snapshot of the headline.
11361 (save-match-data
11362 (setq org-agenda-headline-snapshot-before-repeat
11363 (org-get-heading))))
11364 (org-auto-repeat-maybe state))
11365 ;; Fixup cursor location if close to the keyword
11366 (if (and (outline-on-heading-p)
11367 (not (bolp))
11368 (save-excursion (beginning-of-line 1)
11369 (looking-at org-todo-line-regexp))
11370 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
11371 (progn
11372 (goto-char (or (match-end 2) (match-end 1)))
11373 (and (looking-at " ") (just-one-space))))
11374 (when org-trigger-hook
11375 (save-excursion
11376 (run-hook-with-args 'org-trigger-hook change-plist))))))))
11378 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
11379 "Block turning an entry into a TODO, using the hierarchy.
11380 This checks whether the current task should be blocked from state
11381 changes. Such blocking occurs when:
11383 1. The task has children which are not all in a completed state.
11385 2. A task has a parent with the property :ORDERED:, and there
11386 are siblings prior to the current task with incomplete
11387 status.
11389 3. The parent of the task is blocked because it has siblings that should
11390 be done first, or is child of a block grandparent TODO entry."
11392 (if (not org-enforce-todo-dependencies)
11393 t ; if locally turned off don't block
11394 (catch 'dont-block
11395 ;; If this is not a todo state change, or if this entry is already DONE,
11396 ;; do not block
11397 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11398 (member (plist-get change-plist :from)
11399 (cons 'done org-done-keywords))
11400 (member (plist-get change-plist :to)
11401 (cons 'todo org-not-done-keywords))
11402 (not (plist-get change-plist :to)))
11403 (throw 'dont-block t))
11404 ;; If this task has children, and any are undone, it's blocked
11405 (save-excursion
11406 (org-back-to-heading t)
11407 (let ((this-level (funcall outline-level)))
11408 (outline-next-heading)
11409 (let ((child-level (funcall outline-level)))
11410 (while (and (not (eobp))
11411 (> child-level this-level))
11412 ;; this todo has children, check whether they are all
11413 ;; completed
11414 (if (and (not (org-entry-is-done-p))
11415 (org-entry-is-todo-p))
11416 (throw 'dont-block nil))
11417 (outline-next-heading)
11418 (setq child-level (funcall outline-level))))))
11419 ;; Otherwise, if the task's parent has the :ORDERED: property, and
11420 ;; any previous siblings are undone, it's blocked
11421 (save-excursion
11422 (org-back-to-heading t)
11423 (let* ((pos (point))
11424 (parent-pos (and (org-up-heading-safe) (point))))
11425 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11426 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11427 (forward-line 1)
11428 (re-search-forward org-not-done-heading-regexp pos t))
11429 (throw 'dont-block nil)) ; block, there is an older sibling not done.
11430 ;; Search further up the hierarchy, to see if an anchestor is blocked
11431 (while t
11432 (goto-char parent-pos)
11433 (if (not (looking-at org-not-done-heading-regexp))
11434 (throw 'dont-block t)) ; do not block, parent is not a TODO
11435 (setq pos (point))
11436 (setq parent-pos (and (org-up-heading-safe) (point)))
11437 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11438 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11439 (forward-line 1)
11440 (re-search-forward org-not-done-heading-regexp pos t))
11441 (throw 'dont-block nil)))))))) ; block, older sibling not done.
11443 (defcustom org-track-ordered-property-with-tag nil
11444 "Should the ORDERED property also be shown as a tag?
11445 The ORDERED property decides if an entry should require subtasks to be
11446 completed in sequence. Since a property is not very visible, setting
11447 this option means that toggling the ORDERED property with the command
11448 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
11449 not relevant for the behavior, but it makes things more visible.
11451 Note that toggling the tag with tags commands will not change the property
11452 and therefore not influence behavior!
11454 This can be t, meaning the tag ORDERED should be used, It can also be a
11455 string to select a different tag for this task."
11456 :group 'org-todo
11457 :type '(choice
11458 (const :tag "No tracking" nil)
11459 (const :tag "Track with ORDERED tag" t)
11460 (string :tag "Use other tag")))
11462 (defun org-toggle-ordered-property ()
11463 "Toggle the ORDERED property of the current entry.
11464 For better visibility, you can track the value of this property with a tag.
11465 See variable `org-track-ordered-property-with-tag'."
11466 (interactive)
11467 (let* ((t1 org-track-ordered-property-with-tag)
11468 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
11469 (save-excursion
11470 (org-back-to-heading)
11471 (if (org-entry-get nil "ORDERED")
11472 (progn
11473 (org-delete-property "ORDERED")
11474 (and tag (org-toggle-tag tag 'off))
11475 (message "Subtasks can be completed in arbitrary order"))
11476 (org-entry-put nil "ORDERED" "t")
11477 (and tag (org-toggle-tag tag 'on))
11478 (message "Subtasks must be completed in sequence")))))
11480 (defvar org-blocked-by-checkboxes) ; dynamically scoped
11481 (defun org-block-todo-from-checkboxes (change-plist)
11482 "Block turning an entry into a TODO, using checkboxes.
11483 This checks whether the current task should be blocked from state
11484 changes because there are unchecked boxes in this entry."
11485 (if (not org-enforce-todo-checkbox-dependencies)
11486 t ; if locally turned off don't block
11487 (catch 'dont-block
11488 ;; If this is not a todo state change, or if this entry is already DONE,
11489 ;; do not block
11490 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11491 (member (plist-get change-plist :from)
11492 (cons 'done org-done-keywords))
11493 (member (plist-get change-plist :to)
11494 (cons 'todo org-not-done-keywords))
11495 (not (plist-get change-plist :to)))
11496 (throw 'dont-block t))
11497 ;; If this task has checkboxes that are not checked, it's blocked
11498 (save-excursion
11499 (org-back-to-heading t)
11500 (let ((beg (point)) end)
11501 (outline-next-heading)
11502 (setq end (point))
11503 (goto-char beg)
11504 (if (org-list-search-forward
11505 (concat (org-item-beginning-re)
11506 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
11507 "\\[[- ]\\]")
11508 end t)
11509 (progn
11510 (if (boundp 'org-blocked-by-checkboxes)
11511 (setq org-blocked-by-checkboxes t))
11512 (throw 'dont-block nil)))))
11513 t))) ; do not block
11515 (defun org-entry-blocked-p ()
11516 "Is the current entry blocked?"
11517 (if (org-entry-get nil "NOBLOCKING")
11518 nil ;; Never block this entry
11519 (not
11520 (run-hook-with-args-until-failure
11521 'org-blocker-hook
11522 (list :type 'todo-state-change
11523 :position (point)
11524 :from 'todo
11525 :to 'done)))))
11527 (defun org-update-statistics-cookies (all)
11528 "Update the statistics cookie, either from TODO or from checkboxes.
11529 This should be called with the cursor in a line with a statistics cookie."
11530 (interactive "P")
11531 (if all
11532 (progn
11533 (org-update-checkbox-count 'all)
11534 (org-map-entries 'org-update-parent-todo-statistics))
11535 (if (not (org-on-heading-p))
11536 (org-update-checkbox-count)
11537 (let ((pos (move-marker (make-marker) (point)))
11538 end l1 l2)
11539 (ignore-errors (org-back-to-heading t))
11540 (if (not (org-on-heading-p))
11541 (org-update-checkbox-count)
11542 (setq l1 (org-outline-level))
11543 (setq end (save-excursion
11544 (outline-next-heading)
11545 (if (org-on-heading-p) (setq l2 (org-outline-level)))
11546 (point)))
11547 (if (and (save-excursion
11548 (re-search-forward
11549 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
11550 (not (save-excursion (re-search-forward
11551 ":COOKIE_DATA:.*\\<todo\\>" end t))))
11552 (org-update-checkbox-count)
11553 (if (and l2 (> l2 l1))
11554 (progn
11555 (goto-char end)
11556 (org-update-parent-todo-statistics))
11557 (goto-char pos)
11558 (beginning-of-line 1)
11559 (while (re-search-forward
11560 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
11561 (point-at-eol) t)
11562 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
11563 (goto-char pos)
11564 (move-marker pos nil)))))
11566 (defvar org-entry-property-inherited-from) ;; defined below
11567 (defun org-update-parent-todo-statistics ()
11568 "Update any statistics cookie in the parent of the current headline.
11569 When `org-hierarchical-todo-statistics' is nil, statistics will cover
11570 the entire subtree and this will travel up the hierarchy and update
11571 statistics everywhere."
11572 (let* ((prop (save-excursion (org-up-heading-safe)
11573 (org-entry-get nil "COOKIE_DATA" 'inherit)))
11574 (recursive (or (not org-hierarchical-todo-statistics)
11575 (and prop (string-match "\\<recursive\\>" prop))))
11576 (lim (or (and prop (marker-position org-entry-property-inherited-from))
11578 (first t)
11579 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
11580 level ltoggle l1 new ndel
11581 (cnt-all 0) (cnt-done 0) is-percent kwd
11582 checkbox-beg ov ovs ove cookie-present)
11583 (catch 'exit
11584 (save-excursion
11585 (beginning-of-line 1)
11586 (setq ltoggle (funcall outline-level))
11587 ;; Three situations are to consider:
11589 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
11590 ;; to the top-level ancestor on the headline;
11592 ;; 2. If parent has "recursive" property, repeat up to the
11593 ;; headline setting that property, taking inheritance into
11594 ;; account;
11596 ;; 3. Else, move up to direct parent and proceed only once.
11597 (while (and (setq level (org-up-heading-safe))
11598 (or recursive first)
11599 (>= (point) lim))
11600 (setq first nil cookie-present nil)
11601 (unless (and level
11602 (not (string-match
11603 "\\<checkbox\\>"
11604 (downcase (or (org-entry-get nil "COOKIE_DATA")
11605 "")))))
11606 (throw 'exit nil))
11607 (while (re-search-forward box-re (point-at-eol) t)
11608 (setq cnt-all 0 cnt-done 0 cookie-present t)
11609 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
11610 (save-match-data
11611 (unless (outline-next-heading) (throw 'exit nil))
11612 (while (and (looking-at org-complex-heading-regexp)
11613 (> (setq l1 (length (match-string 1))) level))
11614 (setq kwd (and (or recursive (= l1 ltoggle))
11615 (match-string 2)))
11616 (if (or (eq org-provide-todo-statistics 'all-headlines)
11617 (and (listp org-provide-todo-statistics)
11618 (or (member kwd org-provide-todo-statistics)
11619 (member kwd org-done-keywords))))
11620 (setq cnt-all (1+ cnt-all))
11621 (if (eq org-provide-todo-statistics t)
11622 (and kwd (setq cnt-all (1+ cnt-all)))))
11623 (and (member kwd org-done-keywords)
11624 (setq cnt-done (1+ cnt-done)))
11625 (outline-next-heading)))
11626 (setq new
11627 (if is-percent
11628 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
11629 (format "[%d/%d]" cnt-done cnt-all))
11630 ndel (- (match-end 0) checkbox-beg))
11631 ;; handle overlays when updating cookie from column view
11632 (when (setq ov (car (overlays-at checkbox-beg)))
11633 (setq ovs (overlay-start ov) ove (overlay-end ov))
11634 (delete-overlay ov))
11635 (goto-char checkbox-beg)
11636 (insert new)
11637 (delete-region (point) (+ (point) ndel))
11638 (when org-auto-align-tags (org-fix-tags-on-the-fly))
11639 (when ov (move-overlay ov ovs ove)))
11640 (when cookie-present
11641 (run-hook-with-args 'org-after-todo-statistics-hook
11642 cnt-done (- cnt-all cnt-done))))))
11643 (run-hooks 'org-todo-statistics-hook)))
11645 (defvar org-after-todo-statistics-hook nil
11646 "Hook that is called after a TODO statistics cookie has been updated.
11647 Each function is called with two arguments: the number of not-done entries
11648 and the number of done entries.
11650 For example, the following function, when added to this hook, will switch
11651 an entry to DONE when all children are done, and back to TODO when new
11652 entries are set to a TODO status. Note that this hook is only called
11653 when there is a statistics cookie in the headline!
11655 (defun org-summary-todo (n-done n-not-done)
11656 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
11657 (let (org-log-done org-log-states) ; turn off logging
11658 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
11661 (defvar org-todo-statistics-hook nil
11662 "Hook that is run whenever Org thinks TODO statistics should be updated.
11663 This hook runs even if there is no statistics cookie present, in which case
11664 `org-after-todo-statistics-hook' would not run.")
11666 (defun org-todo-trigger-tag-changes (state)
11667 "Apply the changes defined in `org-todo-state-tags-triggers'."
11668 (let ((l org-todo-state-tags-triggers)
11669 changes)
11670 (when (or (not state) (equal state ""))
11671 (setq changes (append changes (cdr (assoc "" l)))))
11672 (when (and (stringp state) (> (length state) 0))
11673 (setq changes (append changes (cdr (assoc state l)))))
11674 (when (member state org-not-done-keywords)
11675 (setq changes (append changes (cdr (assoc 'todo l)))))
11676 (when (member state org-done-keywords)
11677 (setq changes (append changes (cdr (assoc 'done l)))))
11678 (dolist (c changes)
11679 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
11681 (defun org-local-logging (value)
11682 "Get logging settings from a property VALUE."
11683 (let* (words w a)
11684 ;; directly set the variables, they are already local.
11685 (setq org-log-done nil
11686 org-log-repeat nil
11687 org-todo-log-states nil)
11688 (setq words (org-split-string value))
11689 (while (setq w (pop words))
11690 (cond
11691 ((setq a (assoc w org-startup-options))
11692 (and (member (nth 1 a) '(org-log-done org-log-repeat))
11693 (set (nth 1 a) (nth 2 a))))
11694 ((setq a (org-extract-log-state-settings w))
11695 (and (member (car a) org-todo-keywords-1)
11696 (push a org-todo-log-states)))))))
11698 (defun org-get-todo-sequence-head (kwd)
11699 "Return the head of the TODO sequence to which KWD belongs.
11700 If KWD is not set, check if there is a text property remembering the
11701 right sequence."
11702 (let (p)
11703 (cond
11704 ((not kwd)
11705 (or (get-text-property (point-at-bol) 'org-todo-head)
11706 (progn
11707 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
11708 nil (point-at-eol)))
11709 (get-text-property p 'org-todo-head))))
11710 ((not (member kwd org-todo-keywords-1))
11711 (car org-todo-keywords-1))
11712 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
11714 (defun org-fast-todo-selection ()
11715 "Fast TODO keyword selection with single keys.
11716 Returns the new TODO keyword, or nil if no state change should occur."
11717 (let* ((fulltable org-todo-key-alist)
11718 (done-keywords org-done-keywords) ;; needed for the faces.
11719 (maxlen (apply 'max (mapcar
11720 (lambda (x)
11721 (if (stringp (car x)) (string-width (car x)) 0))
11722 fulltable)))
11723 (expert nil)
11724 (fwidth (+ maxlen 3 1 3))
11725 (ncol (/ (- (window-width) 4) fwidth))
11726 tg cnt e c tbl
11727 groups ingroup)
11728 (save-excursion
11729 (save-window-excursion
11730 (if expert
11731 (set-buffer (get-buffer-create " *Org todo*"))
11732 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
11733 (erase-buffer)
11734 (org-set-local 'org-done-keywords done-keywords)
11735 (setq tbl fulltable cnt 0)
11736 (while (setq e (pop tbl))
11737 (cond
11738 ((equal e '(:startgroup))
11739 (push '() groups) (setq ingroup t)
11740 (when (not (= cnt 0))
11741 (setq cnt 0)
11742 (insert "\n"))
11743 (insert "{ "))
11744 ((equal e '(:endgroup))
11745 (setq ingroup nil cnt 0)
11746 (insert "}\n"))
11747 ((equal e '(:newline))
11748 (when (not (= cnt 0))
11749 (setq cnt 0)
11750 (insert "\n")
11751 (setq e (car tbl))
11752 (while (equal (car tbl) '(:newline))
11753 (insert "\n")
11754 (setq tbl (cdr tbl)))))
11756 (setq tg (car e) c (cdr e))
11757 (if ingroup (push tg (car groups)))
11758 (setq tg (org-add-props tg nil 'face
11759 (org-get-todo-face tg)))
11760 (if (and (= cnt 0) (not ingroup)) (insert " "))
11761 (insert "[" c "] " tg (make-string
11762 (- fwidth 4 (length tg)) ?\ ))
11763 (when (= (setq cnt (1+ cnt)) ncol)
11764 (insert "\n")
11765 (if ingroup (insert " "))
11766 (setq cnt 0)))))
11767 (insert "\n")
11768 (goto-char (point-min))
11769 (if (not expert) (org-fit-window-to-buffer))
11770 (message "[a-z..]:Set [SPC]:clear")
11771 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
11772 (cond
11773 ((or (= c ?\C-g)
11774 (and (= c ?q) (not (rassoc c fulltable))))
11775 (setq quit-flag t))
11776 ((= c ?\ ) nil)
11777 ((setq e (rassoc c fulltable) tg (car e))
11779 (t (setq quit-flag t)))))))
11781 (defun org-entry-is-todo-p ()
11782 (member (org-get-todo-state) org-not-done-keywords))
11784 (defun org-entry-is-done-p ()
11785 (member (org-get-todo-state) org-done-keywords))
11787 (defun org-get-todo-state ()
11788 (save-excursion
11789 (org-back-to-heading t)
11790 (and (looking-at org-todo-line-regexp)
11791 (match-end 2)
11792 (match-string 2))))
11794 (defun org-at-date-range-p (&optional inactive-ok)
11795 "Is the cursor inside a date range?"
11796 (interactive)
11797 (save-excursion
11798 (catch 'exit
11799 (let ((pos (point)))
11800 (skip-chars-backward "^[<\r\n")
11801 (skip-chars-backward "<[")
11802 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
11803 (>= (match-end 0) pos)
11804 (throw 'exit t))
11805 (skip-chars-backward "^<[\r\n")
11806 (skip-chars-backward "<[")
11807 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
11808 (>= (match-end 0) pos)
11809 (throw 'exit t)))
11810 nil)))
11812 (defun org-get-repeat (&optional tagline)
11813 "Check if there is a deadline/schedule with repeater in this entry."
11814 (save-match-data
11815 (save-excursion
11816 (org-back-to-heading t)
11817 (and (re-search-forward (if tagline
11818 (concat tagline "\\s-*" org-repeat-re)
11819 org-repeat-re)
11820 (org-entry-end-position) t)
11821 (match-string-no-properties 1)))))
11823 (defvar org-last-changed-timestamp)
11824 (defvar org-last-inserted-timestamp)
11825 (defvar org-log-post-message)
11826 (defvar org-log-note-purpose)
11827 (defvar org-log-note-how)
11828 (defvar org-log-note-extra)
11829 (defun org-auto-repeat-maybe (done-word)
11830 "Check if the current headline contains a repeated deadline/schedule.
11831 If yes, set TODO state back to what it was and change the base date
11832 of repeating deadline/scheduled time stamps to new date.
11833 This function is run automatically after each state change to a DONE state."
11834 ;; last-state is dynamically scoped into this function
11835 (let* ((repeat (org-get-repeat))
11836 (aa (assoc last-state org-todo-kwd-alist))
11837 (interpret (nth 1 aa))
11838 (head (nth 2 aa))
11839 (whata '(("d" . day) ("m" . month) ("y" . year)))
11840 (msg "Entry repeats: ")
11841 (org-log-done nil)
11842 (org-todo-log-states nil)
11843 re type n what ts time to-state)
11844 (when repeat
11845 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
11846 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
11847 org-todo-repeat-to-state))
11848 (unless (and to-state (member to-state org-todo-keywords-1))
11849 (setq to-state (if (eq interpret 'type) last-state head)))
11850 (org-todo to-state)
11851 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
11852 (org-entry-put nil "LAST_REPEAT" (format-time-string
11853 (org-time-stamp-format t t))))
11854 (when org-log-repeat
11855 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
11856 (memq 'org-add-log-note post-command-hook))
11857 ;; OK, we are already setup for some record
11858 (if (eq org-log-repeat 'note)
11859 ;; make sure we take a note, not only a time stamp
11860 (setq org-log-note-how 'note))
11861 ;; Set up for taking a record
11862 (org-add-log-setup 'state (or done-word (car org-done-keywords))
11863 last-state
11864 'findpos org-log-repeat)))
11865 (org-back-to-heading t)
11866 (org-add-planning-info nil nil 'closed)
11867 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
11868 org-deadline-time-regexp "\\)\\|\\("
11869 org-ts-regexp "\\)"))
11870 (while (re-search-forward
11871 re (save-excursion (outline-next-heading) (point)) t)
11872 (setq type (if (match-end 1) org-scheduled-string
11873 (if (match-end 3) org-deadline-string "Plain:"))
11874 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
11875 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
11876 (setq n (string-to-number (match-string 2 ts))
11877 what (match-string 3 ts))
11878 (if (equal what "w") (setq n (* n 7) what "d"))
11879 ;; Preparation, see if we need to modify the start date for the change
11880 (when (match-end 1)
11881 (setq time (save-match-data (org-time-string-to-time ts)))
11882 (cond
11883 ((equal (match-string 1 ts) ".")
11884 ;; Shift starting date to today
11885 (org-timestamp-change
11886 (- (org-today) (time-to-days time))
11887 'day))
11888 ((equal (match-string 1 ts) "+")
11889 (let ((nshiftmax 10) (nshift 0))
11890 (while (or (= nshift 0)
11891 (<= (time-to-days time)
11892 (time-to-days (current-time))))
11893 (when (= (incf nshift) nshiftmax)
11894 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
11895 (error "Abort")))
11896 (org-timestamp-change n (cdr (assoc what whata)))
11897 (org-at-timestamp-p t)
11898 (setq ts (match-string 1))
11899 (setq time (save-match-data (org-time-string-to-time ts)))))
11900 (org-timestamp-change (- n) (cdr (assoc what whata)))
11901 ;; rematch, so that we have everything in place for the real shift
11902 (org-at-timestamp-p t)
11903 (setq ts (match-string 1))
11904 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
11905 (org-timestamp-change n (cdr (assoc what whata)))
11906 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
11907 (setq org-log-post-message msg)
11908 (message "%s" msg))))
11910 (defun org-show-todo-tree (arg)
11911 "Make a compact tree which shows all headlines marked with TODO.
11912 The tree will show the lines where the regexp matches, and all higher
11913 headlines above the match.
11914 With a \\[universal-argument] prefix, prompt for a regexp to match.
11915 With a numeric prefix N, construct a sparse tree for the Nth element
11916 of `org-todo-keywords-1'."
11917 (interactive "P")
11918 (let ((case-fold-search nil)
11919 (kwd-re
11920 (cond ((null arg) org-not-done-regexp)
11921 ((equal arg '(4))
11922 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
11923 (mapcar 'list org-todo-keywords-1))))
11924 (concat "\\("
11925 (mapconcat 'identity (org-split-string kwd "|") "\\|")
11926 "\\)\\>")))
11927 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
11928 (regexp-quote (nth (1- (prefix-numeric-value arg))
11929 org-todo-keywords-1)))
11930 (t (error "Invalid prefix argument: %s" arg)))))
11931 (message "%d TODO entries found"
11932 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
11934 (defun org-deadline (&optional remove time)
11935 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
11936 With argument REMOVE, remove any deadline from the item.
11937 With argument TIME, set the deadline at the corresponding date. TIME
11938 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
11939 (interactive "P")
11940 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11941 (let (org-loop-over-headlines-in-active-region)
11942 (org-map-entries
11943 `(org-deadline ',remove ,time) org-loop-over-headlines-in-active-region 'region (if (outline-invisible-p) (org-end-of-subtree nil t))))
11944 (let* ((old-date (org-entry-get nil "DEADLINE"))
11945 (repeater (and old-date
11946 (string-match
11947 "\\([.+-]+[0-9]+[dwmy]\\(?:[/ ][-+]?[0-9]+[dwmy]\\)?\\) ?"
11948 old-date)
11949 (match-string 1 old-date))))
11950 (if remove
11951 (progn
11952 (when (and old-date org-log-redeadline)
11953 (org-add-log-setup 'deldeadline nil old-date 'findpos
11954 org-log-redeadline))
11955 (org-remove-timestamp-with-keyword org-deadline-string)
11956 (message "Item no longer has a deadline."))
11957 (org-add-planning-info 'deadline time 'closed)
11958 (when (and old-date org-log-redeadline
11959 (not (equal old-date
11960 (substring org-last-inserted-timestamp 1 -1))))
11961 (org-add-log-setup 'redeadline nil old-date 'findpos
11962 org-log-redeadline))
11963 (when repeater
11964 (save-excursion
11965 (org-back-to-heading t)
11966 (when (re-search-forward (concat org-deadline-string " "
11967 org-last-inserted-timestamp)
11968 (save-excursion
11969 (outline-next-heading) (point)) t)
11970 (goto-char (1- (match-end 0)))
11971 (insert " " repeater)
11972 (setq org-last-inserted-timestamp
11973 (concat (substring org-last-inserted-timestamp 0 -1)
11974 " " repeater
11975 (substring org-last-inserted-timestamp -1))))))
11976 (message "Deadline on %s" org-last-inserted-timestamp)))))
11978 (defun org-schedule (&optional remove time)
11979 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
11980 With argument REMOVE, remove any scheduling date from the item.
11981 With argument TIME, scheduled at the corresponding date. TIME can
11982 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
11983 (interactive "P")
11984 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11985 (let (org-loop-over-headlines-in-active-region)
11986 (org-map-entries
11987 `(org-schedule ',remove ,time) org-loop-over-headlines-in-active-region 'region (if (outline-invisible-p) (org-end-of-subtree nil t))))
11988 (let* ((old-date (org-entry-get nil "SCHEDULED"))
11989 (repeater (and old-date
11990 (string-match
11991 "\\([.+-]+[0-9]+[dwmy]\\(?:[/ ][-+]?[0-9]+[dwmy]\\)?\\) ?"
11992 old-date)
11993 (match-string 1 old-date))))
11994 (if remove
11995 (progn
11996 (when (and old-date org-log-reschedule)
11997 (org-add-log-setup 'delschedule nil old-date 'findpos
11998 org-log-reschedule))
11999 (org-remove-timestamp-with-keyword org-scheduled-string)
12000 (message "Item is no longer scheduled."))
12001 (org-add-planning-info 'scheduled time 'closed)
12002 (when (and old-date org-log-reschedule
12003 (not (equal old-date
12004 (substring org-last-inserted-timestamp 1 -1))))
12005 (org-add-log-setup 'reschedule nil old-date 'findpos
12006 org-log-reschedule))
12007 (when repeater
12008 (save-excursion
12009 (org-back-to-heading t)
12010 (when (re-search-forward (concat org-scheduled-string " "
12011 org-last-inserted-timestamp)
12012 (save-excursion
12013 (outline-next-heading) (point)) t)
12014 (goto-char (1- (match-end 0)))
12015 (insert " " repeater)
12016 (setq org-last-inserted-timestamp
12017 (concat (substring org-last-inserted-timestamp 0 -1)
12018 " " repeater
12019 (substring org-last-inserted-timestamp -1))))))
12020 (message "Scheduled to %s" org-last-inserted-timestamp)))))
12022 (defun org-get-scheduled-time (pom &optional inherit)
12023 "Get the scheduled time as a time tuple, of a format suitable
12024 for calling org-schedule with, or if there is no scheduling,
12025 returns nil."
12026 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12027 (when time
12028 (apply 'encode-time (org-parse-time-string time)))))
12030 (defun org-get-deadline-time (pom &optional inherit)
12031 "Get the deadline as a time tuple, of a format suitable for
12032 calling org-deadline with, or if there is no scheduling, returns
12033 nil."
12034 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12035 (when time
12036 (apply 'encode-time (org-parse-time-string time)))))
12038 (defun org-remove-timestamp-with-keyword (keyword)
12039 "Remove all time stamps with KEYWORD in the current entry."
12040 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12041 beg)
12042 (save-excursion
12043 (org-back-to-heading t)
12044 (setq beg (point))
12045 (outline-next-heading)
12046 (while (re-search-backward re beg t)
12047 (replace-match "")
12048 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12049 (equal (char-before) ?\ ))
12050 (backward-delete-char 1)
12051 (if (string-match "^[ \t]*$" (buffer-substring
12052 (point-at-bol) (point-at-eol)))
12053 (delete-region (point-at-bol)
12054 (min (point-max) (1+ (point-at-eol))))))))))
12056 (defun org-add-planning-info (what &optional time &rest remove)
12057 "Insert new timestamp with keyword in the line directly after the headline.
12058 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
12059 If non is given, the user is prompted for a date.
12060 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
12061 be removed."
12062 (interactive)
12063 (let (org-time-was-given org-end-time-was-given ts
12064 end default-time default-input)
12066 (catch 'exit
12067 (when (and (memq what '(scheduled deadline))
12068 (or (not time)
12069 (and (stringp time)
12070 (string-match "^[-+]+[0-9]" time))))
12071 ;; Try to get a default date/time from existing timestamp
12072 (save-excursion
12073 (org-back-to-heading t)
12074 (setq end (save-excursion (outline-next-heading) (point)))
12075 (when (re-search-forward (if (eq what 'scheduled)
12076 org-scheduled-time-regexp
12077 org-deadline-time-regexp)
12078 end t)
12079 (setq ts (match-string 1)
12080 default-time
12081 (apply 'encode-time (org-parse-time-string ts))
12082 default-input (and ts (org-get-compact-tod ts))))))
12083 (when what
12084 (setq time
12085 (if (and (stringp time)
12086 (string-match "^[-+]+[0-9]" time))
12087 ;; This is a relative time, set the proper date
12088 (apply 'encode-time
12089 (org-read-date-analyze
12090 time default-time (decode-time default-time)))
12091 ;; If necessary, get the time from the user
12092 (or time (org-read-date nil 'to-time nil nil
12093 default-time default-input)))))
12095 (when (and org-insert-labeled-timestamps-at-point
12096 (member what '(scheduled deadline)))
12097 (insert
12098 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
12099 (org-insert-time-stamp time org-time-was-given
12100 nil nil nil (list org-end-time-was-given))
12101 (setq what nil))
12102 (save-excursion
12103 (save-restriction
12104 (let (col list elt ts buffer-invisibility-spec)
12105 (org-back-to-heading t)
12106 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
12107 (goto-char (match-end 1))
12108 (setq col (current-column))
12109 (goto-char (match-end 0))
12110 (if (eobp) (insert "\n") (forward-char 1))
12111 (when (and (not what)
12112 (not (looking-at
12113 (concat "[ \t]*"
12114 org-keyword-time-not-clock-regexp))))
12115 ;; Nothing to add, nothing to remove...... :-)
12116 (throw 'exit nil))
12117 (if (and (not (looking-at org-outline-regexp))
12118 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
12119 "[^\r\n]*"))
12120 (not (equal (match-string 1) org-clock-string)))
12121 (narrow-to-region (match-beginning 0) (match-end 0))
12122 (insert-before-markers "\n")
12123 (backward-char 1)
12124 (narrow-to-region (point) (point))
12125 (and org-adapt-indentation (org-indent-to-column col)))
12126 ;; Check if we have to remove something.
12127 (setq list (cons what remove))
12128 (while list
12129 (setq elt (pop list))
12130 (when (or (and (eq elt 'scheduled)
12131 (re-search-forward org-scheduled-time-regexp nil t))
12132 (and (eq elt 'deadline)
12133 (re-search-forward org-deadline-time-regexp nil t))
12134 (and (eq elt 'closed)
12135 (re-search-forward org-closed-time-regexp nil t)))
12136 (replace-match "")
12137 (if (looking-at "--+<[^>]+>") (replace-match ""))))
12138 (and (looking-at "[ \t]+") (replace-match ""))
12139 (and org-adapt-indentation (bolp) (org-indent-to-column col))
12140 (when what
12141 (insert
12142 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
12143 (cond ((eq what 'scheduled) org-scheduled-string)
12144 ((eq what 'deadline) org-deadline-string)
12145 ((eq what 'closed) org-closed-string))
12146 " ")
12147 (setq ts (org-insert-time-stamp
12148 time
12149 (or org-time-was-given
12150 (and (eq what 'closed) org-log-done-with-time))
12151 (eq what 'closed)
12152 nil nil (list org-end-time-was-given)))
12153 (insert
12154 (if (not (or (bolp) (eq (char-before) ?\ )
12155 (memq (char-after) '(32 10))
12156 (eobp))) " " ""))
12157 (end-of-line 1))
12158 (goto-char (point-min))
12159 (widen)
12160 (if (and (looking-at "[ \t]*\n")
12161 (equal (char-before) ?\n))
12162 (delete-region (1- (point)) (point-at-eol)))
12163 ts))))))
12165 (defvar org-log-note-marker (make-marker))
12166 (defvar org-log-note-purpose nil)
12167 (defvar org-log-note-state nil)
12168 (defvar org-log-note-previous-state nil)
12169 (defvar org-log-note-how nil)
12170 (defvar org-log-note-extra nil)
12171 (defvar org-log-note-window-configuration nil)
12172 (defvar org-log-note-return-to (make-marker))
12173 (defvar org-log-note-effective-time nil
12174 "Remembered current time so that dynamically scoped
12175 `org-extend-today-until' affects tha timestamps in state change
12176 log")
12178 (defvar org-log-post-message nil
12179 "Message to be displayed after a log note has been stored.
12180 The auto-repeater uses this.")
12182 (defun org-add-note ()
12183 "Add a note to the current entry.
12184 This is done in the same way as adding a state change note."
12185 (interactive)
12186 (org-add-log-setup 'note nil nil 'findpos nil))
12188 (defvar org-property-end-re)
12189 (defun org-add-log-setup (&optional purpose state prev-state
12190 findpos how extra)
12191 "Set up the post command hook to take a note.
12192 If this is about to TODO state change, the new state is expected in STATE.
12193 When FINDPOS is non-nil, find the correct position for the note in
12194 the current entry. If not, assume that it can be inserted at point.
12195 HOW is an indicator what kind of note should be created.
12196 EXTRA is additional text that will be inserted into the notes buffer."
12197 (let* ((org-log-into-drawer (org-log-into-drawer))
12198 (drawer (cond ((stringp org-log-into-drawer)
12199 org-log-into-drawer)
12200 (org-log-into-drawer "LOGBOOK")
12201 (t nil))))
12202 (save-restriction
12203 (save-excursion
12204 (when findpos
12205 (org-back-to-heading t)
12206 (narrow-to-region (point) (save-excursion
12207 (outline-next-heading) (point)))
12208 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
12209 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
12210 "[^\r\n]*\\)?"))
12211 (goto-char (match-end 0))
12212 (cond
12213 (drawer
12214 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
12215 nil t)
12216 (progn
12217 (goto-char (match-end 0))
12218 (or org-log-states-order-reversed
12219 (and (re-search-forward org-property-end-re nil t)
12220 (goto-char (1- (match-beginning 0))))))
12221 (insert "\n:" drawer ":\n:END:")
12222 (beginning-of-line 0)
12223 (org-indent-line-function)
12224 (beginning-of-line 2)
12225 (org-indent-line-function)
12226 (end-of-line 0)))
12227 ((and org-log-state-notes-insert-after-drawers
12228 (save-excursion
12229 (forward-line) (looking-at org-drawer-regexp)))
12230 (forward-line)
12231 (while (looking-at org-drawer-regexp)
12232 (goto-char (match-end 0))
12233 (re-search-forward org-property-end-re (point-max) t)
12234 (forward-line))
12235 (forward-line -1)))
12236 (unless org-log-states-order-reversed
12237 (and (= (char-after) ?\n) (forward-char 1))
12238 (org-skip-over-state-notes)
12239 (skip-chars-backward " \t\n\r")))
12240 (move-marker org-log-note-marker (point))
12241 (setq org-log-note-purpose purpose
12242 org-log-note-state state
12243 org-log-note-previous-state prev-state
12244 org-log-note-how how
12245 org-log-note-extra extra
12246 org-log-note-effective-time (org-current-effective-time))
12247 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
12249 (defun org-skip-over-state-notes ()
12250 "Skip past the list of State notes in an entry."
12251 (if (looking-at "\n[ \t]*- State") (forward-char 1))
12252 (when (ignore-errors (goto-char (org-in-item-p)))
12253 (let* ((struct (org-list-struct))
12254 (prevs (org-list-prevs-alist struct)))
12255 (while (looking-at "[ \t]*- State")
12256 (goto-char (or (org-list-get-next-item (point) struct prevs)
12257 (org-list-get-item-end (point) struct)))))))
12259 (defun org-add-log-note (&optional purpose)
12260 "Pop up a window for taking a note, and add this note later at point."
12261 (remove-hook 'post-command-hook 'org-add-log-note)
12262 (setq org-log-note-window-configuration (current-window-configuration))
12263 (delete-other-windows)
12264 (move-marker org-log-note-return-to (point))
12265 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
12266 (goto-char org-log-note-marker)
12267 (org-switch-to-buffer-other-window "*Org Note*")
12268 (erase-buffer)
12269 (if (memq org-log-note-how '(time state))
12270 (let (current-prefix-arg) (org-store-log-note))
12271 (let ((org-inhibit-startup t)) (org-mode))
12272 (insert (format "# Insert note for %s.
12273 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
12274 (cond
12275 ((eq org-log-note-purpose 'clock-out) "stopped clock")
12276 ((eq org-log-note-purpose 'done) "closed todo item")
12277 ((eq org-log-note-purpose 'state)
12278 (format "state change from \"%s\" to \"%s\""
12279 (or org-log-note-previous-state "")
12280 (or org-log-note-state "")))
12281 ((eq org-log-note-purpose 'reschedule)
12282 "rescheduling")
12283 ((eq org-log-note-purpose 'delschedule)
12284 "no longer scheduled")
12285 ((eq org-log-note-purpose 'redeadline)
12286 "changing deadline")
12287 ((eq org-log-note-purpose 'deldeadline)
12288 "removing deadline")
12289 ((eq org-log-note-purpose 'refile)
12290 "refiling")
12291 ((eq org-log-note-purpose 'note)
12292 "this entry")
12293 (t (error "This should not happen")))))
12294 (if org-log-note-extra (insert org-log-note-extra))
12295 (org-set-local 'org-finish-function 'org-store-log-note)
12296 (run-hooks 'org-log-buffer-setup-hook)))
12298 (defvar org-note-abort nil) ; dynamically scoped
12299 (defun org-store-log-note ()
12300 "Finish taking a log note, and insert it to where it belongs."
12301 (let ((txt (buffer-string))
12302 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
12303 lines ind bul)
12304 (kill-buffer (current-buffer))
12305 (while (string-match "\\`#.*\n[ \t\n]*" txt)
12306 (setq txt (replace-match "" t t txt)))
12307 (if (string-match "\\s-+\\'" txt)
12308 (setq txt (replace-match "" t t txt)))
12309 (setq lines (org-split-string txt "\n"))
12310 (when (and note (string-match "\\S-" note))
12311 (setq note
12312 (org-replace-escapes
12313 note
12314 (list (cons "%u" (user-login-name))
12315 (cons "%U" user-full-name)
12316 (cons "%t" (format-time-string
12317 (org-time-stamp-format 'long 'inactive)
12318 org-log-note-effective-time))
12319 (cons "%T" (format-time-string
12320 (org-time-stamp-format 'long nil)
12321 org-log-note-effective-time))
12322 (cons "%d" (format-time-string
12323 (org-time-stamp-format nil 'inactive)
12324 org-log-note-effective-time))
12325 (cons "%D" (format-time-string
12326 (org-time-stamp-format nil nil)
12327 org-log-note-effective-time))
12328 (cons "%s" (if org-log-note-state
12329 (concat "\"" org-log-note-state "\"")
12330 ""))
12331 (cons "%S" (if org-log-note-previous-state
12332 (concat "\"" org-log-note-previous-state "\"")
12333 "\"\"")))))
12334 (if lines (setq note (concat note " \\\\")))
12335 (push note lines))
12336 (when (or current-prefix-arg org-note-abort)
12337 (when org-log-into-drawer
12338 (org-remove-empty-drawer-at
12339 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
12340 org-log-note-marker))
12341 (setq lines nil))
12342 (when lines
12343 (with-current-buffer (marker-buffer org-log-note-marker)
12344 (save-excursion
12345 (goto-char org-log-note-marker)
12346 (move-marker org-log-note-marker nil)
12347 (end-of-line 1)
12348 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
12349 (setq ind (save-excursion
12350 (if (ignore-errors (goto-char (org-in-item-p)))
12351 (let ((struct (org-list-struct)))
12352 (org-list-get-ind
12353 (org-list-get-top-point struct) struct))
12354 (skip-chars-backward " \r\t\n")
12355 (cond
12356 ((and (org-at-heading-p)
12357 org-adapt-indentation)
12358 (1+ (org-current-level)))
12359 ((org-at-heading-p) 0)
12360 (t (org-get-indentation))))))
12361 (setq bul (org-list-bullet-string "-"))
12362 (org-indent-line-to ind)
12363 (insert bul (pop lines))
12364 (let ((ind-body (+ (length bul) ind)))
12365 (while lines
12366 (insert "\n")
12367 (org-indent-line-to ind-body)
12368 (insert (pop lines))))
12369 (message "Note stored")
12370 (org-back-to-heading t)
12371 (org-cycle-hide-drawers 'children)))))
12372 (set-window-configuration org-log-note-window-configuration)
12373 (with-current-buffer (marker-buffer org-log-note-return-to)
12374 (goto-char org-log-note-return-to))
12375 (move-marker org-log-note-return-to nil)
12376 (and org-log-post-message (message "%s" org-log-post-message)))
12378 (defun org-remove-empty-drawer-at (drawer pos)
12379 "Remove an empty drawer DRAWER at position POS.
12380 POS may also be a marker."
12381 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
12382 (save-excursion
12383 (save-restriction
12384 (widen)
12385 (goto-char pos)
12386 (if (org-in-regexp
12387 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
12388 (replace-match ""))))))
12390 (defun org-sparse-tree (&optional arg)
12391 "Create a sparse tree, prompt for the details.
12392 This command can create sparse trees. You first need to select the type
12393 of match used to create the tree:
12395 t Show all TODO entries.
12396 T Show entries with a specific TODO keyword.
12397 m Show entries selected by a tags/property match.
12398 p Enter a property name and its value (both with completion on existing
12399 names/values) and show entries with that property.
12400 r Show entries matching a regular expression (`/' can be used as well)
12401 d Show deadlines due within `org-deadline-warning-days'.
12402 b Show deadlines and scheduled items before a date.
12403 a Show deadlines and scheduled items after a date."
12404 (interactive "P")
12405 (let (ans kwd value)
12406 (message "Sparse tree: [r]egexp [/]regexp [t]odo [T]odo-kwd [m]atch [p]roperty\n [d]eadlines [b]efore-date [a]fter-date")
12407 (setq ans (read-char-exclusive))
12408 (cond
12409 ((equal ans ?d)
12410 (call-interactively 'org-check-deadlines))
12411 ((equal ans ?b)
12412 (call-interactively 'org-check-before-date))
12413 ((equal ans ?a)
12414 (call-interactively 'org-check-after-date))
12415 ((equal ans ?t)
12416 (org-show-todo-tree nil))
12417 ((equal ans ?T)
12418 (org-show-todo-tree '(4)))
12419 ((member ans '(?T ?m))
12420 (call-interactively 'org-match-sparse-tree))
12421 ((member ans '(?p ?P))
12422 (setq kwd (org-icompleting-read "Property: "
12423 (mapcar 'list (org-buffer-property-keys))))
12424 (setq value (org-icompleting-read "Value: "
12425 (mapcar 'list (org-property-values kwd))))
12426 (unless (string-match "\\`{.*}\\'" value)
12427 (setq value (concat "\"" value "\"")))
12428 (org-match-sparse-tree arg (concat kwd "=" value)))
12429 ((member ans '(?r ?R ?/))
12430 (call-interactively 'org-occur))
12431 (t (error "No such sparse tree command \"%c\"" ans)))))
12433 (defvar org-occur-highlights nil
12434 "List of overlays used for occur matches.")
12435 (make-variable-buffer-local 'org-occur-highlights)
12436 (defvar org-occur-parameters nil
12437 "Parameters of the active org-occur calls.
12438 This is a list, each call to org-occur pushes as cons cell,
12439 containing the regular expression and the callback, onto the list.
12440 The list can contain several entries if `org-occur' has been called
12441 several time with the KEEP-PREVIOUS argument. Otherwise, this list
12442 will only contain one set of parameters. When the highlights are
12443 removed (for example with `C-c C-c', or with the next edit (depending
12444 on `org-remove-highlights-with-change'), this variable is emptied
12445 as well.")
12446 (make-variable-buffer-local 'org-occur-parameters)
12448 (defun org-occur (regexp &optional keep-previous callback)
12449 "Make a compact tree which shows all matches of REGEXP.
12450 The tree will show the lines where the regexp matches, and all higher
12451 headlines above the match. It will also show the heading after the match,
12452 to make sure editing the matching entry is easy.
12453 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
12454 call to `org-occur' will be kept, to allow stacking of calls to this
12455 command.
12456 If CALLBACK is non-nil, it is a function which is called to confirm
12457 that the match should indeed be shown."
12458 (interactive "sRegexp: \nP")
12459 (when (equal regexp "")
12460 (error "Regexp cannot be empty"))
12461 (unless keep-previous
12462 (org-remove-occur-highlights nil nil t))
12463 (push (cons regexp callback) org-occur-parameters)
12464 (let ((cnt 0))
12465 (save-excursion
12466 (goto-char (point-min))
12467 (if (or (not keep-previous) ; do not want to keep
12468 (not org-occur-highlights)) ; no previous matches
12469 ;; hide everything
12470 (org-overview))
12471 (while (re-search-forward regexp nil t)
12472 (when (or (not callback)
12473 (save-match-data (funcall callback)))
12474 (setq cnt (1+ cnt))
12475 (when org-highlight-sparse-tree-matches
12476 (org-highlight-new-match (match-beginning 0) (match-end 0)))
12477 (org-show-context 'occur-tree))))
12478 (when org-remove-highlights-with-change
12479 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
12480 nil 'local))
12481 (unless org-sparse-tree-open-archived-trees
12482 (org-hide-archived-subtrees (point-min) (point-max)))
12483 (run-hooks 'org-occur-hook)
12484 (if (org-called-interactively-p 'interactive)
12485 (message "%d match(es) for regexp %s" cnt regexp))
12486 cnt))
12488 (defun org-occur-next-match (&optional n reset)
12489 "Function for `next-error-function' to find sparse tree matches.
12490 N is the number of matches to move, when negative move backwards.
12491 RESET is entirely ignored - this function always goes back to the
12492 starting point when no match is found."
12493 (let* ((limit (if (< n 0) (point-min) (point-max)))
12494 (search-func (if (< n 0)
12495 'previous-single-char-property-change
12496 'next-single-char-property-change))
12497 (n (abs n))
12498 (pos (point))
12500 (catch 'exit
12501 (while (setq p1 (funcall search-func (point) 'org-type))
12502 (when (equal p1 limit)
12503 (goto-char pos)
12504 (error "No more matches"))
12505 (when (equal (get-char-property p1 'org-type) 'org-occur)
12506 (setq n (1- n))
12507 (when (= n 0)
12508 (goto-char p1)
12509 (throw 'exit (point))))
12510 (goto-char p1))
12511 (goto-char p1)
12512 (error "No more matches"))))
12514 (defun org-show-context (&optional key)
12515 "Make sure point and context are visible.
12516 How much context is shown depends upon the variables
12517 `org-show-hierarchy-above', `org-show-following-heading'. and
12518 `org-show-siblings'."
12519 (let ((heading-p (org-on-heading-p t))
12520 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
12521 (following-p (org-get-alist-option org-show-following-heading key))
12522 (entry-p (org-get-alist-option org-show-entry-below key))
12523 (siblings-p (org-get-alist-option org-show-siblings key)))
12524 (catch 'exit
12525 ;; Show heading or entry text
12526 (if (and heading-p (not entry-p))
12527 (org-flag-heading nil) ; only show the heading
12528 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
12529 (org-show-hidden-entry))) ; show entire entry
12530 (when following-p
12531 ;; Show next sibling, or heading below text
12532 (save-excursion
12533 (and (if heading-p (org-goto-sibling) (outline-next-heading))
12534 (org-flag-heading nil))))
12535 (when siblings-p (org-show-siblings))
12536 (when hierarchy-p
12537 ;; show all higher headings, possibly with siblings
12538 (save-excursion
12539 (while (and (condition-case nil
12540 (progn (org-up-heading-all 1) t)
12541 (error nil))
12542 (not (bobp)))
12543 (org-flag-heading nil)
12544 (when siblings-p (org-show-siblings))))))))
12546 (defvar org-reveal-start-hook nil
12547 "Hook run before revealing a location.")
12549 (defun org-reveal (&optional siblings)
12550 "Show current entry, hierarchy above it, and the following headline.
12551 This can be used to show a consistent set of context around locations
12552 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
12553 not t for the search context.
12555 With optional argument SIBLINGS, on each level of the hierarchy all
12556 siblings are shown. This repairs the tree structure to what it would
12557 look like when opened with hierarchical calls to `org-cycle'.
12558 With double optional argument \\[universal-argument] \\[universal-argument], \
12559 go to the parent and show the
12560 entire tree."
12561 (interactive "P")
12562 (run-hooks 'org-reveal-start-hook)
12563 (let ((org-show-hierarchy-above t)
12564 (org-show-following-heading t)
12565 (org-show-siblings (if siblings t org-show-siblings)))
12566 (org-show-context nil))
12567 (when (equal siblings '(16))
12568 (save-excursion
12569 (when (org-up-heading-safe)
12570 (org-show-subtree)
12571 (run-hook-with-args 'org-cycle-hook 'subtree)))))
12573 (defun org-highlight-new-match (beg end)
12574 "Highlight from BEG to END and mark the highlight is an occur headline."
12575 (let ((ov (make-overlay beg end)))
12576 (overlay-put ov 'face 'secondary-selection)
12577 (overlay-put ov 'org-type 'org-occur)
12578 (push ov org-occur-highlights)))
12580 (defun org-remove-occur-highlights (&optional beg end noremove)
12581 "Remove the occur highlights from the buffer.
12582 BEG and END are ignored. If NOREMOVE is nil, remove this function
12583 from the `before-change-functions' in the current buffer."
12584 (interactive)
12585 (unless org-inhibit-highlight-removal
12586 (mapc 'delete-overlay org-occur-highlights)
12587 (setq org-occur-highlights nil)
12588 (setq org-occur-parameters nil)
12589 (unless noremove
12590 (remove-hook 'before-change-functions
12591 'org-remove-occur-highlights 'local))))
12593 ;;;; Priorities
12595 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
12596 "Regular expression matching the priority indicator.")
12598 (defvar org-remove-priority-next-time nil)
12600 (defun org-priority-up ()
12601 "Increase the priority of the current item."
12602 (interactive)
12603 (org-priority 'up))
12605 (defun org-priority-down ()
12606 "Decrease the priority of the current item."
12607 (interactive)
12608 (org-priority 'down))
12610 (defun org-priority (&optional action)
12611 "Change the priority of an item by ARG.
12612 ACTION can be `set', `up', `down', or a character."
12613 (interactive)
12614 (unless org-enable-priority-commands
12615 (error "Priority commands are disabled"))
12616 (setq action (or action 'set))
12617 (let (current new news have remove)
12618 (save-excursion
12619 (org-back-to-heading t)
12620 (if (looking-at org-priority-regexp)
12621 (setq current (string-to-char (match-string 2))
12622 have t))
12623 (cond
12624 ((eq action 'remove)
12625 (setq remove t new ?\ ))
12626 ((or (eq action 'set)
12627 (if (featurep 'xemacs) (characterp action) (integerp action)))
12628 (if (not (eq action 'set))
12629 (setq new action)
12630 (message "Priority %c-%c, SPC to remove: "
12631 org-highest-priority org-lowest-priority)
12632 (save-match-data
12633 (setq new (read-char-exclusive))))
12634 (if (and (= (upcase org-highest-priority) org-highest-priority)
12635 (= (upcase org-lowest-priority) org-lowest-priority))
12636 (setq new (upcase new)))
12637 (cond ((equal new ?\ ) (setq remove t))
12638 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
12639 (error "Priority must be between `%c' and `%c'"
12640 org-highest-priority org-lowest-priority))))
12641 ((eq action 'up)
12642 (setq new (if have
12643 (1- current) ; normal cycling
12644 ;; last priority was empty
12645 (if (eq last-command this-command)
12646 org-lowest-priority ; wrap around empty to lowest
12647 ;; default
12648 (if org-priority-start-cycle-with-default
12649 org-default-priority
12650 (1- org-default-priority))))))
12651 ((eq action 'down)
12652 (setq new (if have
12653 (1+ current) ; normal cycling
12654 ;; last priority was empty
12655 (if (eq last-command this-command)
12656 org-highest-priority ; wrap around empty to highest
12657 ;; default
12658 (if org-priority-start-cycle-with-default
12659 org-default-priority
12660 (1+ org-default-priority))))))
12661 (t (error "Invalid action")))
12662 (if (or (< (upcase new) org-highest-priority)
12663 (> (upcase new) org-lowest-priority))
12664 (if (and (memq action '(up down))
12665 (not have) (not (eq last-command this-command)))
12666 ;; `new' is from default priority
12667 (error
12668 "The default can not be set, see `org-default-priority' why")
12669 ;; normal cycling: `new' is beyond highest/lowest priority
12670 ;; and is wrapped around to the empty priority
12671 (setq remove t)))
12672 (setq news (format "%c" new))
12673 (if have
12674 (if remove
12675 (replace-match "" t t nil 1)
12676 (replace-match news t t nil 2))
12677 (if remove
12678 (error "No priority cookie found in line")
12679 (let ((case-fold-search nil))
12680 (looking-at org-todo-line-regexp))
12681 (if (match-end 2)
12682 (progn
12683 (goto-char (match-end 2))
12684 (insert " [#" news "]"))
12685 (goto-char (match-beginning 3))
12686 (insert "[#" news "] "))))
12687 (org-preserve-lc (org-set-tags nil 'align)))
12688 (if remove
12689 (message "Priority removed")
12690 (message "Priority of current item set to %s" news))))
12692 (defun org-get-priority (s)
12693 "Find priority cookie and return priority."
12694 (if (functionp org-get-priority-function)
12695 (funcall org-get-priority-function)
12696 (save-match-data
12697 (if (not (string-match org-priority-regexp s))
12698 (* 1000 (- org-lowest-priority org-default-priority))
12699 (* 1000 (- org-lowest-priority
12700 (string-to-char (match-string 2 s))))))))
12702 ;;;; Tags
12704 (defvar org-agenda-archives-mode)
12705 (defvar org-map-continue-from nil
12706 "Position from where mapping should continue.
12707 Can be set by the action argument to `org-scan-tag's and `org-map-entries'.")
12709 (defvar org-scanner-tags nil
12710 "The current tag list while the tags scanner is running.")
12711 (defvar org-trust-scanner-tags nil
12712 "Should `org-get-tags-at' use the tags for the scanner.
12713 This is for internal dynamical scoping only.
12714 When this is non-nil, the function `org-get-tags-at' will return the value
12715 of `org-scanner-tags' instead of building the list by itself. This
12716 can lead to large speed-ups when the tags scanner is used in a file with
12717 many entries, and when the list of tags is retrieved, for example to
12718 obtain a list of properties. Building the tags list for each entry in such
12719 a file becomes an N^2 operation - but with this variable set, it scales
12720 as N.")
12722 (defun org-scan-tags (action matcher &optional todo-only)
12723 "Scan headline tags with inheritance and produce output ACTION.
12725 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
12726 or `agenda' to produce an entry list for an agenda view. It can also be
12727 a Lisp form or a function that should be called at each matched headline, in
12728 this case the return value is a list of all return values from these calls.
12730 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
12731 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
12732 only lines with a TODO keyword are included in the output."
12733 (require 'org-agenda)
12734 (let* ((re (concat "^" org-outline-regexp " *\\(\\<\\("
12735 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
12736 (org-re
12737 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
12738 (props (list 'face 'default
12739 'done-face 'org-agenda-done
12740 'undone-face 'default
12741 'mouse-face 'highlight
12742 'org-not-done-regexp org-not-done-regexp
12743 'org-todo-regexp org-todo-regexp
12744 'org-complex-heading-regexp org-complex-heading-regexp
12745 'help-echo
12746 (format "mouse-2 or RET jump to org file %s"
12747 (abbreviate-file-name
12748 (or (buffer-file-name (buffer-base-buffer))
12749 (buffer-name (buffer-base-buffer)))))))
12750 (case-fold-search nil)
12751 (org-map-continue-from nil)
12752 lspos tags tags-list
12753 (tags-alist (list (cons 0 org-file-tags)))
12754 (llast 0) rtn rtn1 level category i txt
12755 todo marker entry priority)
12756 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
12757 (setq action (list 'lambda nil action)))
12758 (save-excursion
12759 (goto-char (point-min))
12760 (when (eq action 'sparse-tree)
12761 (org-overview)
12762 (org-remove-occur-highlights))
12763 (while (re-search-forward re nil t)
12764 (catch :skip
12765 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
12766 tags (if (match-end 4) (org-match-string-no-properties 4)))
12767 (goto-char (setq lspos (match-beginning 0)))
12768 (setq level (org-reduced-level (funcall outline-level))
12769 category (org-get-category))
12770 (setq i llast llast level)
12771 ;; remove tag lists from same and sublevels
12772 (while (>= i level)
12773 (when (setq entry (assoc i tags-alist))
12774 (setq tags-alist (delete entry tags-alist)))
12775 (setq i (1- i)))
12776 ;; add the next tags
12777 (when tags
12778 (setq tags (org-split-string tags ":")
12779 tags-alist
12780 (cons (cons level tags) tags-alist)))
12781 ;; compile tags for current headline
12782 (setq tags-list
12783 (if org-use-tag-inheritance
12784 (apply 'append (mapcar 'cdr (reverse tags-alist)))
12785 tags)
12786 org-scanner-tags tags-list)
12787 (when org-use-tag-inheritance
12788 (setcdr (car tags-alist)
12789 (mapcar (lambda (x)
12790 (setq x (copy-sequence x))
12791 (org-add-prop-inherited x))
12792 (cdar tags-alist))))
12793 (when (and tags org-use-tag-inheritance
12794 (or (not (eq t org-use-tag-inheritance))
12795 org-tags-exclude-from-inheritance))
12796 ;; selective inheritance, remove uninherited ones
12797 (setcdr (car tags-alist)
12798 (org-remove-uninherited-tags (cdar tags-alist))))
12799 (when (and
12801 ;; eval matcher only when the todo condition is OK
12802 (and (or (not todo-only) (member todo org-not-done-keywords))
12803 (let ((case-fold-search t)) (eval matcher)))
12805 ;; Call the skipper, but return t if it does not skip,
12806 ;; so that the `and' form continues evaluating
12807 (progn
12808 (unless (eq action 'sparse-tree) (org-agenda-skip))
12811 ;; Check if timestamps are deselecting this entry
12812 (or (not todo-only)
12813 (and (member todo org-not-done-keywords)
12814 (or (not org-agenda-tags-todo-honor-ignore-options)
12815 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
12817 ;; Extra check for the archive tag
12818 ;; FIXME: Does the skipper already do this????
12820 (not (member org-archive-tag tags-list))
12821 ;; we have an archive tag, should we use this anyway?
12822 (or (not org-agenda-skip-archived-trees)
12823 (and (eq action 'agenda) org-agenda-archives-mode))))
12825 ;; select this headline
12827 (cond
12828 ((eq action 'sparse-tree)
12829 (and org-highlight-sparse-tree-matches
12830 (org-get-heading) (match-end 0)
12831 (org-highlight-new-match
12832 (match-beginning 0) (match-beginning 1)))
12833 (org-show-context 'tags-tree))
12834 ((eq action 'agenda)
12835 (setq txt (org-agenda-format-item
12837 (concat
12838 (if (eq org-tags-match-list-sublevels 'indented)
12839 (make-string (1- level) ?.) "")
12840 (org-get-heading))
12841 category
12842 tags-list
12844 priority (org-get-priority txt))
12845 (goto-char lspos)
12846 (setq marker (org-agenda-new-marker))
12847 (org-add-props txt props
12848 'org-marker marker 'org-hd-marker marker 'org-category category
12849 'todo-state todo
12850 'priority priority 'type "tagsmatch")
12851 (push txt rtn))
12852 ((functionp action)
12853 (setq org-map-continue-from nil)
12854 (save-excursion
12855 (setq rtn1 (funcall action))
12856 (push rtn1 rtn)))
12857 (t (error "Invalid action")))
12859 ;; if we are to skip sublevels, jump to end of subtree
12860 (unless org-tags-match-list-sublevels
12861 (org-end-of-subtree t)
12862 (backward-char 1))))
12863 ;; Get the correct position from where to continue
12864 (if org-map-continue-from
12865 (goto-char org-map-continue-from)
12866 (and (= (point) lspos) (end-of-line 1)))))
12867 (when (and (eq action 'sparse-tree)
12868 (not org-sparse-tree-open-archived-trees))
12869 (org-hide-archived-subtrees (point-min) (point-max)))
12870 (nreverse rtn)))
12872 (defun org-remove-uninherited-tags (tags)
12873 "Remove all tags that are not inherited from the list TAGS."
12874 (cond
12875 ((eq org-use-tag-inheritance t)
12876 (if org-tags-exclude-from-inheritance
12877 (org-delete-all org-tags-exclude-from-inheritance tags)
12878 tags))
12879 ((not org-use-tag-inheritance) nil)
12880 ((stringp org-use-tag-inheritance)
12881 (delq nil (mapcar
12882 (lambda (x)
12883 (if (and (string-match org-use-tag-inheritance x)
12884 (not (member x org-tags-exclude-from-inheritance)))
12885 x nil))
12886 tags)))
12887 ((listp org-use-tag-inheritance)
12888 (delq nil (mapcar
12889 (lambda (x)
12890 (if (member x org-use-tag-inheritance) x nil))
12891 tags)))))
12893 (defvar todo-only) ;; dynamically scoped
12895 (defun org-match-sparse-tree (&optional todo-only match)
12896 "Create a sparse tree according to tags string MATCH.
12897 MATCH can contain positive and negative selection of tags, like
12898 \"+WORK+URGENT-WITHBOSS\".
12899 If optional argument TODO-ONLY is non-nil, only select lines that are
12900 also TODO lines."
12901 (interactive "P")
12902 (org-prepare-agenda-buffers (list (current-buffer)))
12903 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
12905 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
12907 (defvar org-cached-props nil)
12908 (defun org-cached-entry-get (pom property)
12909 (if (or (eq t org-use-property-inheritance)
12910 (and (stringp org-use-property-inheritance)
12911 (string-match org-use-property-inheritance property))
12912 (and (listp org-use-property-inheritance)
12913 (member property org-use-property-inheritance)))
12914 ;; Caching is not possible, check it directly
12915 (org-entry-get pom property 'inherit)
12916 ;; Get all properties, so that we can do complicated checks easily
12917 (cdr (assoc property (or org-cached-props
12918 (setq org-cached-props
12919 (org-entry-properties pom)))))))
12921 (defun org-global-tags-completion-table (&optional files)
12922 "Return the list of all tags in all agenda buffer/files.
12923 Optional FILES argument is a list of files to which can be used
12924 instead of the agenda files."
12925 (save-excursion
12926 (org-uniquify
12927 (delq nil
12928 (apply 'append
12929 (mapcar
12930 (lambda (file)
12931 (set-buffer (find-file-noselect file))
12932 (append (org-get-buffer-tags)
12933 (mapcar (lambda (x) (if (stringp (car-safe x))
12934 (list (car-safe x)) nil))
12935 org-tag-alist)))
12936 (if (and files (car files))
12937 files
12938 (org-agenda-files))))))))
12940 (defun org-make-tags-matcher (match)
12941 "Create the TAGS/TODO matcher form for the selection string MATCH."
12942 ;; todo-only is scoped dynamically into this function, and the function
12943 ;; may change it if the matcher asks for it.
12944 (unless match
12945 ;; Get a new match request, with completion
12946 (let ((org-last-tags-completion-table
12947 (org-global-tags-completion-table)))
12948 (setq match (org-completing-read-no-i
12949 "Match: " 'org-tags-completion-function nil nil nil
12950 'org-tags-history))))
12952 ;; Parse the string and create a lisp form
12953 (let ((match0 match)
12954 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
12955 minus tag mm
12956 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
12957 orterms term orlist re-p str-p level-p level-op time-p
12958 prop-p pn pv po gv rest)
12959 (if (string-match "/+" match)
12960 ;; match contains also a todo-matching request
12961 (progn
12962 (setq tagsmatch (substring match 0 (match-beginning 0))
12963 todomatch (substring match (match-end 0)))
12964 (if (string-match "^!" todomatch)
12965 (setq todo-only t todomatch (substring todomatch 1)))
12966 (if (string-match "^\\s-*$" todomatch)
12967 (setq todomatch nil)))
12968 ;; only matching tags
12969 (setq tagsmatch match todomatch nil))
12971 ;; Make the tags matcher
12972 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
12973 (setq tagsmatcher t)
12974 (setq orterms (org-split-string tagsmatch "|") orlist nil)
12975 (while (setq term (pop orterms))
12976 (while (and (equal (substring term -1) "\\") orterms)
12977 (setq term (concat term "|" (pop orterms)))) ; repair bad split
12978 (while (string-match re term)
12979 (setq rest (substring term (match-end 0))
12980 minus (and (match-end 1)
12981 (equal (match-string 1 term) "-"))
12982 tag (save-match-data (replace-regexp-in-string
12983 "\\\\-" "-"
12984 (match-string 2 term)))
12985 re-p (equal (string-to-char tag) ?{)
12986 level-p (match-end 4)
12987 prop-p (match-end 5)
12988 mm (cond
12989 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
12990 (level-p
12991 (setq level-op (org-op-to-function (match-string 3 term)))
12992 `(,level-op level ,(string-to-number
12993 (match-string 4 term))))
12994 (prop-p
12995 (setq pn (match-string 5 term)
12996 po (match-string 6 term)
12997 pv (match-string 7 term)
12998 re-p (equal (string-to-char pv) ?{)
12999 str-p (equal (string-to-char pv) ?\")
13000 time-p (save-match-data
13001 (string-match "^\"[[<].*[]>]\"$" pv))
13002 pv (if (or re-p str-p) (substring pv 1 -1) pv))
13003 (if time-p (setq pv (org-matcher-time pv)))
13004 (setq po (org-op-to-function po (if time-p 'time str-p)))
13005 (cond
13006 ((equal pn "CATEGORY")
13007 (setq gv '(get-text-property (point) 'org-category)))
13008 ((equal pn "TODO")
13009 (setq gv 'todo))
13011 (setq gv `(org-cached-entry-get nil ,pn))))
13012 (if re-p
13013 (if (eq po 'org<>)
13014 `(not (string-match ,pv (or ,gv "")))
13015 `(string-match ,pv (or ,gv "")))
13016 (if str-p
13017 `(,po (or ,gv "") ,pv)
13018 `(,po (string-to-number (or ,gv ""))
13019 ,(string-to-number pv) ))))
13020 (t `(member ,tag tags-list)))
13021 mm (if minus (list 'not mm) mm)
13022 term rest)
13023 (push mm tagsmatcher))
13024 (push (if (> (length tagsmatcher) 1)
13025 (cons 'and tagsmatcher)
13026 (car tagsmatcher))
13027 orlist)
13028 (setq tagsmatcher nil))
13029 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
13030 (setq tagsmatcher
13031 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
13032 ;; Make the todo matcher
13033 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
13034 (setq todomatcher t)
13035 (setq orterms (org-split-string todomatch "|") orlist nil)
13036 (while (setq term (pop orterms))
13037 (while (string-match re term)
13038 (setq minus (and (match-end 1)
13039 (equal (match-string 1 term) "-"))
13040 kwd (match-string 2 term)
13041 re-p (equal (string-to-char kwd) ?{)
13042 term (substring term (match-end 0))
13043 mm (if re-p
13044 `(string-match ,(substring kwd 1 -1) todo)
13045 (list 'equal 'todo kwd))
13046 mm (if minus (list 'not mm) mm))
13047 (push mm todomatcher))
13048 (push (if (> (length todomatcher) 1)
13049 (cons 'and todomatcher)
13050 (car todomatcher))
13051 orlist)
13052 (setq todomatcher nil))
13053 (setq todomatcher (if (> (length orlist) 1)
13054 (cons 'or orlist) (car orlist))))
13056 ;; Return the string and lisp forms of the matcher
13057 (setq matcher (if todomatcher
13058 (list 'and tagsmatcher todomatcher)
13059 tagsmatcher))
13060 (cons match0 matcher)))
13062 (defun org-op-to-function (op &optional stringp)
13063 "Turn an operator into the appropriate function."
13064 (setq op
13065 (cond
13066 ((equal op "<" ) '(< string< org-time<))
13067 ((equal op ">" ) '(> org-string> org-time>))
13068 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
13069 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
13070 ((member op '("=" "==")) '(= string= org-time=))
13071 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
13072 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
13074 (defun org<> (a b) (not (= a b)))
13075 (defun org-string<= (a b) (or (string= a b) (string< a b)))
13076 (defun org-string>= (a b) (not (string< a b)))
13077 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
13078 (defun org-string<> (a b) (not (string= a b)))
13079 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
13080 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
13081 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
13082 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
13083 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
13084 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
13085 (defun org-2ft (s)
13086 "Convert S to a floating point time.
13087 If S is already a number, just return it. If it is a string, parse
13088 it as a time string and apply `float-time' to it. If S is nil, just return 0."
13089 (cond
13090 ((numberp s) s)
13091 ((stringp s)
13092 (condition-case nil
13093 (float-time (apply 'encode-time (org-parse-time-string s)))
13094 (error 0.)))
13095 (t 0.)))
13097 (defun org-time-today ()
13098 "Time in seconds today at 0:00.
13099 Returns the float number of seconds since the beginning of the
13100 epoch to the beginning of today (00:00)."
13101 (float-time (apply 'encode-time
13102 (append '(0 0 0) (nthcdr 3 (decode-time))))))
13104 (defun org-matcher-time (s)
13105 "Interpret a time comparison value."
13106 (save-match-data
13107 (cond
13108 ((string= s "<now>") (float-time))
13109 ((string= s "<today>") (org-time-today))
13110 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
13111 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
13112 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
13113 (+ (org-time-today)
13114 (* (string-to-number (match-string 1 s))
13115 (cdr (assoc (match-string 2 s)
13116 '(("d" . 86400.0) ("w" . 604800.0)
13117 ("m" . 2678400.0) ("y" . 31557600.0)))))))
13118 (t (org-2ft s)))))
13120 (defun org-match-any-p (re list)
13121 "Does re match any element of list?"
13122 (setq list (mapcar (lambda (x) (string-match re x)) list))
13123 (delq nil list))
13125 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
13126 (defvar org-tags-overlay (make-overlay 1 1))
13127 (org-detach-overlay org-tags-overlay)
13129 (defun org-get-local-tags-at (&optional pos)
13130 "Get a list of tags defined in the current headline."
13131 (org-get-tags-at pos 'local))
13133 (defun org-get-local-tags ()
13134 "Get a list of tags defined in the current headline."
13135 (org-get-tags-at nil 'local))
13137 (defun org-get-tags-at (&optional pos local)
13138 "Get a list of all headline tags applicable at POS.
13139 POS defaults to point. If tags are inherited, the list contains
13140 the targets in the same sequence as the headlines appear, i.e.
13141 the tags of the current headline come last.
13142 When LOCAL is non-nil, only return tags from the current headline,
13143 ignore inherited ones."
13144 (interactive)
13145 (if (and org-trust-scanner-tags
13146 (or (not pos) (equal pos (point)))
13147 (not local))
13148 org-scanner-tags
13149 (let (tags ltags lastpos parent)
13150 (save-excursion
13151 (save-restriction
13152 (widen)
13153 (goto-char (or pos (point)))
13154 (save-match-data
13155 (catch 'done
13156 (condition-case nil
13157 (progn
13158 (org-back-to-heading t)
13159 (while (not (equal lastpos (point)))
13160 (setq lastpos (point))
13161 (when (looking-at
13162 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
13163 (setq ltags (org-split-string
13164 (org-match-string-no-properties 1) ":"))
13165 (when parent
13166 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
13167 (setq tags (append
13168 (if parent
13169 (org-remove-uninherited-tags ltags)
13170 ltags)
13171 tags)))
13172 (or org-use-tag-inheritance (throw 'done t))
13173 (if local (throw 'done t))
13174 (or (org-up-heading-safe) (error nil))
13175 (setq parent t)))
13176 (error nil)))))
13177 (if local
13178 tags
13179 (append (org-remove-uninherited-tags org-file-tags) tags))))))
13181 (defun org-add-prop-inherited (s)
13182 (add-text-properties 0 (length s) '(inherited t) s)
13185 (defun org-toggle-tag (tag &optional onoff)
13186 "Toggle the tag TAG for the current line.
13187 If ONOFF is `on' or `off', don't toggle but set to this state."
13188 (let (res current)
13189 (save-excursion
13190 (org-back-to-heading t)
13191 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
13192 (point-at-eol) t)
13193 (progn
13194 (setq current (match-string 1))
13195 (replace-match ""))
13196 (setq current ""))
13197 (setq current (nreverse (org-split-string current ":")))
13198 (cond
13199 ((eq onoff 'on)
13200 (setq res t)
13201 (or (member tag current) (push tag current)))
13202 ((eq onoff 'off)
13203 (or (not (member tag current)) (setq current (delete tag current))))
13204 (t (if (member tag current)
13205 (setq current (delete tag current))
13206 (setq res t)
13207 (push tag current))))
13208 (end-of-line 1)
13209 (if current
13210 (progn
13211 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
13212 (org-set-tags nil t))
13213 (delete-horizontal-space))
13214 (run-hooks 'org-after-tags-change-hook))
13215 res))
13217 (defun org-align-tags-here (to-col)
13218 ;; Assumes that this is a headline
13219 (let ((pos (point)) (col (current-column)) ncol tags-l p)
13220 (beginning-of-line 1)
13221 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13222 (< pos (match-beginning 2)))
13223 (progn
13224 (setq tags-l (- (match-end 2) (match-beginning 2)))
13225 (goto-char (match-beginning 1))
13226 (insert " ")
13227 (delete-region (point) (1+ (match-beginning 2)))
13228 (setq ncol (max (current-column)
13229 (1+ col)
13230 (if (> to-col 0)
13231 to-col
13232 (- (abs to-col) tags-l))))
13233 (setq p (point))
13234 (insert (make-string (- ncol (current-column)) ?\ ))
13235 (setq ncol (current-column))
13236 (when indent-tabs-mode (tabify p (point-at-eol)))
13237 (org-move-to-column (min ncol col) t))
13238 (goto-char pos))))
13240 (defun org-set-tags-command (&optional arg just-align)
13241 "Call the set-tags command for the current entry."
13242 (interactive "P")
13243 (if (org-on-heading-p)
13244 (org-set-tags arg just-align)
13245 (save-excursion
13246 (org-back-to-heading t)
13247 (org-set-tags arg just-align))))
13249 (defun org-set-tags-to (data)
13250 "Set the tags of the current entry to DATA, replacing the current tags.
13251 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
13252 If DATA is nil or the empty string, any tags will be removed."
13253 (interactive "sTags: ")
13254 (setq data
13255 (cond
13256 ((eq data nil) "")
13257 ((equal data "") "")
13258 ((stringp data)
13259 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
13260 ":"))
13261 ((listp data)
13262 (concat ":" (mapconcat 'identity data ":") ":"))
13263 (t nil)))
13264 (when data
13265 (save-excursion
13266 (org-back-to-heading t)
13267 (when (looking-at org-complex-heading-regexp)
13268 (if (match-end 5)
13269 (progn
13270 (goto-char (match-beginning 5))
13271 (insert data)
13272 (delete-region (point) (point-at-eol))
13273 (org-set-tags nil 'align))
13274 (goto-char (point-at-eol))
13275 (insert " " data)
13276 (org-set-tags nil 'align)))
13277 (beginning-of-line 1)
13278 (if (looking-at ".*?\\([ \t]+\\)$")
13279 (delete-region (match-beginning 1) (match-end 1))))))
13281 (defun org-align-all-tags ()
13282 "Align the tags i all headings."
13283 (interactive)
13284 (save-excursion
13285 (or (ignore-errors (org-back-to-heading t))
13286 (outline-next-heading))
13287 (if (org-on-heading-p)
13288 (org-set-tags t)
13289 (message "No headings"))))
13291 (defvar org-indent-indentation-per-level)
13292 (defun org-set-tags (&optional arg just-align)
13293 "Set the tags for the current headline.
13294 With prefix ARG, realign all tags in headings in the current buffer."
13295 (interactive "P")
13296 (let* ((re org-outline-regexp-bol)
13297 (current (org-get-tags-string))
13298 (col (current-column))
13299 (org-setting-tags t)
13300 table current-tags inherited-tags ; computed below when needed
13301 tags p0 c0 c1 rpl di tc level)
13302 (if arg
13303 (save-excursion
13304 (goto-char (point-min))
13305 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
13306 (while (re-search-forward re nil t)
13307 (org-set-tags nil t)
13308 (end-of-line 1)))
13309 (message "All tags realigned to column %d" org-tags-column))
13310 (if just-align
13311 (setq tags current)
13312 ;; Get a new set of tags from the user
13313 (save-excursion
13314 (setq table (append org-tag-persistent-alist
13315 (or org-tag-alist (org-get-buffer-tags))
13316 (and
13317 org-complete-tags-always-offer-all-agenda-tags
13318 (org-global-tags-completion-table
13319 (org-agenda-files))))
13320 org-last-tags-completion-table table
13321 current-tags (org-split-string current ":")
13322 inherited-tags (nreverse
13323 (nthcdr (length current-tags)
13324 (nreverse (org-get-tags-at))))
13325 tags
13326 (if (or (eq t org-use-fast-tag-selection)
13327 (and org-use-fast-tag-selection
13328 (delq nil (mapcar 'cdr table))))
13329 (org-fast-tag-selection
13330 current-tags inherited-tags table
13331 (if org-fast-tag-selection-include-todo
13332 org-todo-key-alist))
13333 (let ((org-add-colon-after-tag-completion t))
13334 (org-trim
13335 (org-icompleting-read "Tags: "
13336 'org-tags-completion-function
13337 nil nil current 'org-tags-history))))))
13338 (while (string-match "[-+&]+" tags)
13339 ;; No boolean logic, just a list
13340 (setq tags (replace-match ":" t t tags))))
13342 (setq tags (replace-regexp-in-string "[,]" ":" tags))
13344 (if org-tags-sort-function
13345 (setq tags (mapconcat 'identity
13346 (sort (org-split-string
13347 tags (org-re "[^[:alnum:]_@#%]+"))
13348 org-tags-sort-function) ":")))
13350 (if (string-match "\\`[\t ]*\\'" tags)
13351 (setq tags "")
13352 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
13353 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
13355 ;; Insert new tags at the correct column
13356 (beginning-of-line 1)
13357 (setq level (or (and (looking-at org-outline-regexp)
13358 (- (match-end 0) (point) 1))
13360 (cond
13361 ((and (equal current "") (equal tags "")))
13362 ((re-search-forward
13363 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
13364 (point-at-eol) t)
13365 (if (equal tags "")
13366 (setq rpl "")
13367 (goto-char (match-beginning 0))
13368 (setq c0 (current-column)
13369 ;; compute offset for the case of org-indent-mode active
13370 di (if org-indent-mode
13371 (* (1- org-indent-indentation-per-level) (1- level))
13373 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
13374 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
13375 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
13376 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
13377 (replace-match rpl t t)
13378 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
13379 tags)
13380 (t (error "Tags alignment failed")))
13381 (org-move-to-column col)
13382 (unless just-align
13383 (run-hooks 'org-after-tags-change-hook)))))
13385 (defun org-change-tag-in-region (beg end tag off)
13386 "Add or remove TAG for each entry in the region.
13387 This works in the agenda, and also in an org-mode buffer."
13388 (interactive
13389 (list (region-beginning) (region-end)
13390 (let ((org-last-tags-completion-table
13391 (if (eq major-mode 'org-mode)
13392 (org-get-buffer-tags)
13393 (org-global-tags-completion-table))))
13394 (org-icompleting-read
13395 "Tag: " 'org-tags-completion-function nil nil nil
13396 'org-tags-history))
13397 (progn
13398 (message "[s]et or [r]emove? ")
13399 (equal (read-char-exclusive) ?r))))
13400 (if (fboundp 'deactivate-mark) (deactivate-mark))
13401 (let ((agendap (equal major-mode 'org-agenda-mode))
13402 l1 l2 m buf pos newhead (cnt 0))
13403 (goto-char end)
13404 (setq l2 (1- (org-current-line)))
13405 (goto-char beg)
13406 (setq l1 (org-current-line))
13407 (loop for l from l1 to l2 do
13408 (org-goto-line l)
13409 (setq m (get-text-property (point) 'org-hd-marker))
13410 (when (or (and (eq major-mode 'org-mode) (org-on-heading-p))
13411 (and agendap m))
13412 (setq buf (if agendap (marker-buffer m) (current-buffer))
13413 pos (if agendap m (point)))
13414 (with-current-buffer buf
13415 (save-excursion
13416 (save-restriction
13417 (goto-char pos)
13418 (setq cnt (1+ cnt))
13419 (org-toggle-tag tag (if off 'off 'on))
13420 (setq newhead (org-get-heading)))))
13421 (and agendap (org-agenda-change-all-lines newhead m))))
13422 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
13424 (defun org-tags-completion-function (string predicate &optional flag)
13425 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
13426 (confirm (lambda (x) (stringp (car x)))))
13427 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
13428 (setq s1 (match-string 1 string)
13429 s2 (match-string 2 string))
13430 (setq s1 "" s2 string))
13431 (cond
13432 ((eq flag nil)
13433 ;; try completion
13434 (setq rtn (try-completion s2 ctable confirm))
13435 (if (stringp rtn)
13436 (setq rtn
13437 (concat s1 s2 (substring rtn (length s2))
13438 (if (and org-add-colon-after-tag-completion
13439 (assoc rtn ctable))
13440 ":" ""))))
13441 rtn)
13442 ((eq flag t)
13443 ;; all-completions
13444 (all-completions s2 ctable confirm)
13446 ((eq flag 'lambda)
13447 ;; exact match?
13448 (assoc s2 ctable)))
13451 (defun org-fast-tag-insert (kwd tags face &optional end)
13452 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
13453 (insert (format "%-12s" (concat kwd ":"))
13454 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
13455 (or end "")))
13457 (defun org-fast-tag-show-exit (flag)
13458 (save-excursion
13459 (org-goto-line 3)
13460 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
13461 (replace-match ""))
13462 (when flag
13463 (end-of-line 1)
13464 (org-move-to-column (- (window-width) 19) t)
13465 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
13467 (defun org-set-current-tags-overlay (current prefix)
13468 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
13469 (if (featurep 'xemacs)
13470 (org-overlay-display org-tags-overlay (concat prefix s)
13471 'secondary-selection)
13472 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
13473 (org-overlay-display org-tags-overlay (concat prefix s)))))
13475 (defvar org-last-tag-selection-key nil)
13476 (defun org-fast-tag-selection (current inherited table &optional todo-table)
13477 "Fast tag selection with single keys.
13478 CURRENT is the current list of tags in the headline, INHERITED is the
13479 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
13480 possibly with grouping information. TODO-TABLE is a similar table with
13481 TODO keywords, should these have keys assigned to them.
13482 If the keys are nil, a-z are automatically assigned.
13483 Returns the new tags string, or nil to not change the current settings."
13484 (let* ((fulltable (append table todo-table))
13485 (maxlen (apply 'max (mapcar
13486 (lambda (x)
13487 (if (stringp (car x)) (string-width (car x)) 0))
13488 fulltable)))
13489 (buf (current-buffer))
13490 (expert (eq org-fast-tag-selection-single-key 'expert))
13491 (buffer-tags nil)
13492 (fwidth (+ maxlen 3 1 3))
13493 (ncol (/ (- (window-width) 4) fwidth))
13494 (i-face 'org-done)
13495 (c-face 'org-todo)
13496 tg cnt e c char c1 c2 ntable tbl rtn
13497 ov-start ov-end ov-prefix
13498 (exit-after-next org-fast-tag-selection-single-key)
13499 (done-keywords org-done-keywords)
13500 groups ingroup)
13501 (save-excursion
13502 (beginning-of-line 1)
13503 (if (looking-at
13504 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13505 (setq ov-start (match-beginning 1)
13506 ov-end (match-end 1)
13507 ov-prefix "")
13508 (setq ov-start (1- (point-at-eol))
13509 ov-end (1+ ov-start))
13510 (skip-chars-forward "^\n\r")
13511 (setq ov-prefix
13512 (concat
13513 (buffer-substring (1- (point)) (point))
13514 (if (> (current-column) org-tags-column)
13516 (make-string (- org-tags-column (current-column)) ?\ ))))))
13517 (move-overlay org-tags-overlay ov-start ov-end)
13518 (save-window-excursion
13519 (if expert
13520 (set-buffer (get-buffer-create " *Org tags*"))
13521 (delete-other-windows)
13522 (split-window-vertically)
13523 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
13524 (erase-buffer)
13525 (org-set-local 'org-done-keywords done-keywords)
13526 (org-fast-tag-insert "Inherited" inherited i-face "\n")
13527 (org-fast-tag-insert "Current" current c-face "\n\n")
13528 (org-fast-tag-show-exit exit-after-next)
13529 (org-set-current-tags-overlay current ov-prefix)
13530 (setq tbl fulltable char ?a cnt 0)
13531 (while (setq e (pop tbl))
13532 (cond
13533 ((equal (car e) :startgroup)
13534 (push '() groups) (setq ingroup t)
13535 (when (not (= cnt 0))
13536 (setq cnt 0)
13537 (insert "\n"))
13538 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
13539 ((equal (car e) :endgroup)
13540 (setq ingroup nil cnt 0)
13541 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
13542 ((equal e '(:newline))
13543 (when (not (= cnt 0))
13544 (setq cnt 0)
13545 (insert "\n")
13546 (setq e (car tbl))
13547 (while (equal (car tbl) '(:newline))
13548 (insert "\n")
13549 (setq tbl (cdr tbl)))))
13551 (setq tg (copy-sequence (car e)) c2 nil)
13552 (if (cdr e)
13553 (setq c (cdr e))
13554 ;; automatically assign a character.
13555 (setq c1 (string-to-char
13556 (downcase (substring
13557 tg (if (= (string-to-char tg) ?@) 1 0)))))
13558 (if (or (rassoc c1 ntable) (rassoc c1 table))
13559 (while (or (rassoc char ntable) (rassoc char table))
13560 (setq char (1+ char)))
13561 (setq c2 c1))
13562 (setq c (or c2 char)))
13563 (if ingroup (push tg (car groups)))
13564 (setq tg (org-add-props tg nil 'face
13565 (cond
13566 ((not (assoc tg table))
13567 (org-get-todo-face tg))
13568 ((member tg current) c-face)
13569 ((member tg inherited) i-face)
13570 (t nil))))
13571 (if (and (= cnt 0) (not ingroup)) (insert " "))
13572 (insert "[" c "] " tg (make-string
13573 (- fwidth 4 (length tg)) ?\ ))
13574 (push (cons tg c) ntable)
13575 (when (= (setq cnt (1+ cnt)) ncol)
13576 (insert "\n")
13577 (if ingroup (insert " "))
13578 (setq cnt 0)))))
13579 (setq ntable (nreverse ntable))
13580 (insert "\n")
13581 (goto-char (point-min))
13582 (if (not expert) (org-fit-window-to-buffer))
13583 (setq rtn
13584 (catch 'exit
13585 (while t
13586 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
13587 (if (not groups) "no " "")
13588 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
13589 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13590 (setq org-last-tag-selection-key c)
13591 (cond
13592 ((= c ?\r) (throw 'exit t))
13593 ((= c ?!)
13594 (setq groups (not groups))
13595 (goto-char (point-min))
13596 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
13597 ((= c ?\C-c)
13598 (if (not expert)
13599 (org-fast-tag-show-exit
13600 (setq exit-after-next (not exit-after-next)))
13601 (setq expert nil)
13602 (delete-other-windows)
13603 (set-window-buffer (split-window-vertically) " *Org tags*")
13604 (org-switch-to-buffer-other-window " *Org tags*")
13605 (org-fit-window-to-buffer)))
13606 ((or (= c ?\C-g)
13607 (and (= c ?q) (not (rassoc c ntable))))
13608 (org-detach-overlay org-tags-overlay)
13609 (setq quit-flag t))
13610 ((= c ?\ )
13611 (setq current nil)
13612 (if exit-after-next (setq exit-after-next 'now)))
13613 ((= c ?\t)
13614 (condition-case nil
13615 (setq tg (org-icompleting-read
13616 "Tag: "
13617 (or buffer-tags
13618 (with-current-buffer buf
13619 (org-get-buffer-tags)))))
13620 (quit (setq tg "")))
13621 (when (string-match "\\S-" tg)
13622 (add-to-list 'buffer-tags (list tg))
13623 (if (member tg current)
13624 (setq current (delete tg current))
13625 (push tg current)))
13626 (if exit-after-next (setq exit-after-next 'now)))
13627 ((setq e (rassoc c todo-table) tg (car e))
13628 (with-current-buffer buf
13629 (save-excursion (org-todo tg)))
13630 (if exit-after-next (setq exit-after-next 'now)))
13631 ((setq e (rassoc c ntable) tg (car e))
13632 (if (member tg current)
13633 (setq current (delete tg current))
13634 (loop for g in groups do
13635 (if (member tg g)
13636 (mapc (lambda (x)
13637 (setq current (delete x current)))
13638 g)))
13639 (push tg current))
13640 (if exit-after-next (setq exit-after-next 'now))))
13642 ;; Create a sorted list
13643 (setq current
13644 (sort current
13645 (lambda (a b)
13646 (assoc b (cdr (memq (assoc a ntable) ntable))))))
13647 (if (eq exit-after-next 'now) (throw 'exit t))
13648 (goto-char (point-min))
13649 (beginning-of-line 2)
13650 (delete-region (point) (point-at-eol))
13651 (org-fast-tag-insert "Current" current c-face)
13652 (org-set-current-tags-overlay current ov-prefix)
13653 (while (re-search-forward
13654 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
13655 (setq tg (match-string 1))
13656 (add-text-properties
13657 (match-beginning 1) (match-end 1)
13658 (list 'face
13659 (cond
13660 ((member tg current) c-face)
13661 ((member tg inherited) i-face)
13662 (t (get-text-property (match-beginning 1) 'face))))))
13663 (goto-char (point-min)))))
13664 (org-detach-overlay org-tags-overlay)
13665 (if rtn
13666 (mapconcat 'identity current ":")
13667 nil))))
13669 (defun org-get-tags-string ()
13670 "Get the TAGS string in the current headline."
13671 (unless (org-on-heading-p t)
13672 (error "Not on a heading"))
13673 (save-excursion
13674 (beginning-of-line 1)
13675 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13676 (org-match-string-no-properties 1)
13677 "")))
13679 (defun org-get-tags ()
13680 "Get the list of tags specified in the current headline."
13681 (org-split-string (org-get-tags-string) ":"))
13683 (defun org-get-buffer-tags ()
13684 "Get a table of all tags used in the buffer, for completion."
13685 (let (tags)
13686 (save-excursion
13687 (goto-char (point-min))
13688 (while (re-search-forward
13689 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
13690 (when (equal (char-after (point-at-bol 0)) ?*)
13691 (mapc (lambda (x) (add-to-list 'tags x))
13692 (org-split-string (org-match-string-no-properties 1) ":")))))
13693 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
13694 (mapcar 'list tags)))
13696 ;;;; The mapping API
13698 ;;;###autoload
13699 (defun org-map-entries (func &optional match scope &rest skip)
13700 "Call FUNC at each headline selected by MATCH in SCOPE.
13702 FUNC is a function or a lisp form. The function will be called without
13703 arguments, with the cursor positioned at the beginning of the headline.
13704 The return values of all calls to the function will be collected and
13705 returned as a list.
13707 The call to FUNC will be wrapped into a save-excursion form, so FUNC
13708 does not need to preserve point. After evaluation, the cursor will be
13709 moved to the end of the line (presumably of the headline of the
13710 processed entry) and search continues from there. Under some
13711 circumstances, this may not produce the wanted results. For example,
13712 if you have removed (e.g. archived) the current (sub)tree it could
13713 mean that the next entry will be skipped entirely. In such cases, you
13714 can specify the position from where search should continue by making
13715 FUNC set the variable `org-map-continue-from' to the desired buffer
13716 position.
13718 MATCH is a tags/property/todo match as it is used in the agenda tags view.
13719 Only headlines that are matched by this query will be considered during
13720 the iteration. When MATCH is nil or t, all headlines will be
13721 visited by the iteration.
13723 SCOPE determines the scope of this command. It can be any of:
13725 nil The current buffer, respecting the restriction if any
13726 tree The subtree started with the entry at point
13727 region The entries within the active region, if any
13728 file The current buffer, without restriction
13729 file-with-archives
13730 The current buffer, and any archives associated with it
13731 agenda All agenda files
13732 agenda-with-archives
13733 All agenda files with any archive files associated with them
13734 \(file1 file2 ...)
13735 If this is a list, all files in the list will be scanned
13737 The remaining args are treated as settings for the skipping facilities of
13738 the scanner. The following items can be given here:
13740 archive skip trees with the archive tag.
13741 comment skip trees with the COMMENT keyword
13742 function or Emacs Lisp form:
13743 will be used as value for `org-agenda-skip-function', so whenever
13744 the function returns t, FUNC will not be called for that
13745 entry and search will continue from the point where the
13746 function leaves it.
13748 If your function needs to retrieve the tags including inherited tags
13749 at the *current* entry, you can use the value of the variable
13750 `org-scanner-tags' which will be much faster than getting the value
13751 with `org-get-tags-at'. If your function gets properties with
13752 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
13753 to t around the call to `org-entry-properties' to get the same speedup.
13754 Note that if your function moves around to retrieve tags and properties at
13755 a *different* entry, you cannot use these techniques."
13756 (unless (and (eq scope 'region) (not (org-region-active-p)))
13757 (let* ((org-agenda-archives-mode nil) ; just to make sure
13758 (org-agenda-skip-archived-trees (memq 'archive skip))
13759 (org-agenda-skip-comment-trees (memq 'comment skip))
13760 (org-agenda-skip-function
13761 (car (org-delete-all '(comment archive) skip)))
13762 (org-tags-match-list-sublevels t)
13763 matcher file res
13764 org-todo-keywords-for-agenda
13765 org-done-keywords-for-agenda
13766 org-todo-keyword-alist-for-agenda
13767 org-drawers-for-agenda
13768 org-tag-alist-for-agenda)
13770 (cond
13771 ((eq match t) (setq matcher t))
13772 ((eq match nil) (setq matcher t))
13773 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
13775 (save-excursion
13776 (save-restriction
13777 (cond ((eq scope 'tree)
13778 (org-back-to-heading t)
13779 (org-narrow-to-subtree)
13780 (setq scope nil))
13781 ((and (eq scope 'region) (org-region-active-p))
13782 (narrow-to-region (region-beginning)
13783 (save-excursion
13784 (goto-char (region-end))
13785 (unless (and (bolp) (org-at-heading-p))
13786 (outline-next-heading))
13787 (point)))
13788 (setq scope nil)))
13790 (if (not scope)
13791 (progn
13792 (org-prepare-agenda-buffers
13793 (list (buffer-file-name (current-buffer))))
13794 (setq res (org-scan-tags func matcher)))
13795 ;; Get the right scope
13796 (cond
13797 ((and scope (listp scope) (symbolp (car scope)))
13798 (setq scope (eval scope)))
13799 ((eq scope 'agenda)
13800 (setq scope (org-agenda-files t)))
13801 ((eq scope 'agenda-with-archives)
13802 (setq scope (org-agenda-files t))
13803 (setq scope (org-add-archive-files scope)))
13804 ((eq scope 'file)
13805 (setq scope (list (buffer-file-name))))
13806 ((eq scope 'file-with-archives)
13807 (setq scope (org-add-archive-files (list (buffer-file-name))))))
13808 (org-prepare-agenda-buffers scope)
13809 (while (setq file (pop scope))
13810 (with-current-buffer (org-find-base-buffer-visiting file)
13811 (save-excursion
13812 (save-restriction
13813 (widen)
13814 (goto-char (point-min))
13815 (setq res (append res (org-scan-tags func matcher))))))))))
13816 res)))
13818 ;;;; Properties
13820 ;;; Setting and retrieving properties
13822 (defconst org-special-properties
13823 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
13824 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM")
13825 "The special properties valid in Org-mode.
13827 These are properties that are not defined in the property drawer,
13828 but in some other way.")
13830 (defconst org-default-properties
13831 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
13832 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
13833 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
13834 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
13835 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
13836 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
13837 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
13838 "Some properties that are used by Org-mode for various purposes.
13839 Being in this list makes sure that they are offered for completion.")
13841 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
13842 "Regular expression matching the first line of a property drawer.")
13844 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
13845 "Regular expression matching the last line of a property drawer.")
13847 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
13848 "Regular expression matching the first line of a property drawer.")
13850 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
13851 "Regular expression matching the first line of a property drawer.")
13853 (defconst org-property-drawer-re
13854 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
13855 org-property-end-re "\\)\n?")
13856 "Matches an entire property drawer.")
13858 (defconst org-clock-drawer-re
13859 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
13860 org-property-end-re "\\)\n?")
13861 "Matches an entire clock drawer.")
13863 (defsubst org-re-property (property)
13864 "Return a regexp matching PROPERTY.
13865 Match group 1 will be set to the value "
13866 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
13868 (defun org-property-action ()
13869 "Do an action on properties."
13870 (interactive)
13871 (let (c)
13872 (org-at-property-p)
13873 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
13874 (setq c (read-char-exclusive))
13875 (cond
13876 ((equal c ?s)
13877 (call-interactively 'org-set-property))
13878 ((equal c ?d)
13879 (call-interactively 'org-delete-property))
13880 ((equal c ?D)
13881 (call-interactively 'org-delete-property-globally))
13882 ((equal c ?c)
13883 (call-interactively 'org-compute-property-at-point))
13884 (t (error "No such property action %c" c)))))
13886 (defun org-set-effort (&optional value)
13887 "Set the effort property of the current entry.
13888 With numerical prefix arg, use the nth allowed value, 0 stands for the 10th
13889 allowed value."
13890 (interactive "P")
13891 (if (equal value 0) (setq value 10))
13892 (let* ((completion-ignore-case t)
13893 (prop org-effort-property)
13894 (cur (org-entry-get nil prop))
13895 (allowed (org-property-get-allowed-values nil prop 'table))
13896 (existing (mapcar 'list (org-property-values prop)))
13898 (val (cond
13899 ((stringp value) value)
13900 ((and allowed (integerp value))
13901 (or (car (nth (1- value) allowed))
13902 (car (org-last allowed))))
13903 (allowed
13904 (message "Select 1-9,0, [RET%s]: %s"
13905 (if cur (concat "=" cur) "")
13906 (mapconcat 'car allowed " "))
13907 (setq rpl (read-char-exclusive))
13908 (if (equal rpl ?\r)
13910 (setq rpl (- rpl ?0))
13911 (if (equal rpl 0) (setq rpl 10))
13912 (if (and (> rpl 0) (<= rpl (length allowed)))
13913 (car (nth (1- rpl) allowed))
13914 (org-completing-read "Effort: " allowed nil))))
13916 (let (org-completion-use-ido org-completion-use-iswitchb)
13917 (org-completing-read
13918 (concat "Effort " (if (and cur (string-match "\\S-" cur))
13919 (concat "[" cur "]") "")
13920 ": ")
13921 existing nil nil "" nil cur))))))
13922 (unless (equal (org-entry-get nil prop) val)
13923 (org-entry-put nil prop val))
13924 (message "%s is now %s" prop val)))
13926 (defun org-at-property-p ()
13927 "Is cursor inside a property drawer?"
13928 (save-excursion
13929 (beginning-of-line 1)
13930 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
13931 (save-match-data ;; Used by calling procedures
13932 (let ((p (point))
13933 (range (unless (org-before-first-heading-p)
13934 (org-get-property-block))))
13935 (and range (<= (car range) p) (< p (cdr range))))))))
13937 (defun org-get-property-block (&optional beg end force)
13938 "Return the (beg . end) range of the body of the property drawer.
13939 BEG and END can be beginning and end of subtree, if not given
13940 they will be found.
13941 If the drawer does not exist and FORCE is non-nil, create the drawer."
13942 (catch 'exit
13943 (save-excursion
13944 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
13945 (end (or end (progn (outline-next-heading) (point)))))
13946 (goto-char beg)
13947 (if (re-search-forward org-property-start-re end t)
13948 (setq beg (1+ (match-end 0)))
13949 (if force
13950 (save-excursion
13951 (org-insert-property-drawer)
13952 (setq end (progn (outline-next-heading) (point))))
13953 (throw 'exit nil))
13954 (goto-char beg)
13955 (if (re-search-forward org-property-start-re end t)
13956 (setq beg (1+ (match-end 0)))))
13957 (if (re-search-forward org-property-end-re end t)
13958 (setq end (match-beginning 0))
13959 (or force (throw 'exit nil))
13960 (goto-char beg)
13961 (setq end beg)
13962 (org-indent-line-function)
13963 (insert ":END:\n"))
13964 (cons beg end)))))
13966 (defun org-entry-properties (&optional pom which specific)
13967 "Get all properties of the entry at point-or-marker POM.
13968 This includes the TODO keyword, the tags, time strings for deadline,
13969 scheduled, and clocking, and any additional properties defined in the
13970 entry. The return value is an alist, keys may occur multiple times
13971 if the property key was used several times.
13972 POM may also be nil, in which case the current entry is used.
13973 If WHICH is nil or `all', get all properties. If WHICH is
13974 `special' or `standard', only get that subclass. If WHICH
13975 is a string only get exactly this property. SPECIFIC can be a string, the
13976 specific property we are interested in. Specifying it can speed
13977 things up because then unnecessary parsing is avoided."
13978 (setq which (or which 'all))
13979 (org-with-point-at pom
13980 (let ((clockstr (substring org-clock-string 0 -1))
13981 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
13982 (case-fold-search nil)
13983 beg end range props sum-props key key1 value string clocksum)
13984 (save-excursion
13985 (when (condition-case nil
13986 (and (eq major-mode 'org-mode) (org-back-to-heading t))
13987 (error nil))
13988 (setq beg (point))
13989 (setq sum-props (get-text-property (point) 'org-summaries))
13990 (setq clocksum (get-text-property (point) :org-clock-minutes))
13991 (outline-next-heading)
13992 (setq end (point))
13993 (when (memq which '(all special))
13994 ;; Get the special properties, like TODO and tags
13995 (goto-char beg)
13996 (when (and (or (not specific) (string= specific "TODO"))
13997 (looking-at org-todo-line-regexp) (match-end 2))
13998 (push (cons "TODO" (org-match-string-no-properties 2)) props))
13999 (when (and (or (not specific) (string= specific "PRIORITY"))
14000 (looking-at org-priority-regexp))
14001 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
14002 (when (or (not specific) (string= specific "FILE"))
14003 (push (cons "FILE" buffer-file-name) props))
14004 (when (and (or (not specific) (string= specific "TAGS"))
14005 (setq value (org-get-tags-string))
14006 (string-match "\\S-" value))
14007 (push (cons "TAGS" value) props))
14008 (when (and (or (not specific) (string= specific "ALLTAGS"))
14009 (setq value (org-get-tags-at)))
14010 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
14011 ":"))
14012 props))
14013 (when (or (not specific) (string= specific "BLOCKED"))
14014 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
14015 (when (or (not specific)
14016 (member specific
14017 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
14018 "TIMESTAMP" "TIMESTAMP_IA")))
14019 (catch 'match
14020 (while (re-search-forward org-maybe-keyword-time-regexp end t)
14021 (setq key (if (match-end 1)
14022 (substring (org-match-string-no-properties 1)
14023 0 -1))
14024 string (if (equal key clockstr)
14025 (org-no-properties
14026 (org-trim
14027 (buffer-substring
14028 (match-beginning 3) (goto-char
14029 (point-at-eol)))))
14030 (substring (org-match-string-no-properties 3)
14031 1 -1)))
14032 ;; Get the correct property name from the key. This is
14033 ;; necessary if the user has configured time keywords.
14034 (setq key1 (concat key ":"))
14035 (cond
14036 ((not key)
14037 (setq key
14038 (if (= (char-after (match-beginning 3)) ?\[)
14039 "TIMESTAMP_IA" "TIMESTAMP")))
14040 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
14041 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
14042 ((equal key1 org-closed-string) (setq key "CLOSED"))
14043 ((equal key1 org-clock-string) (setq key "CLOCK")))
14044 (if (and specific (equal key specific) (not (equal key "CLOCK")))
14045 (progn
14046 (push (cons key string) props)
14047 ;; no need to search further if match is found
14048 (throw 'match t))
14049 (when (or (equal key "CLOCK") (not (assoc key props)))
14050 (push (cons key string) props))))))
14053 (when (memq which '(all standard))
14054 ;; Get the standard properties, like :PROP: ...
14055 (setq range (org-get-property-block beg end))
14056 (when range
14057 (goto-char (car range))
14058 (while (re-search-forward
14059 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
14060 (cdr range) t)
14061 (setq key (org-match-string-no-properties 1)
14062 value (org-trim (or (org-match-string-no-properties 2) "")))
14063 (unless (member key excluded)
14064 (push (cons key (or value "")) props)))))
14065 (if clocksum
14066 (push (cons "CLOCKSUM"
14067 (org-columns-number-to-string (/ (float clocksum) 60.)
14068 'add_times))
14069 props))
14070 (unless (assoc "CATEGORY" props)
14071 (push (cons "CATEGORY" (org-get-category)) props))
14072 (append sum-props (nreverse props)))))))
14074 (defun org-entry-get (pom property &optional inherit literal-nil)
14075 "Get value of PROPERTY for entry at point-or-marker POM.
14076 If INHERIT is non-nil and the entry does not have the property,
14077 then also check higher levels of the hierarchy.
14078 If INHERIT is the symbol `selective', use inheritance only if the setting
14079 in `org-use-property-inheritance' selects PROPERTY for inheritance.
14080 If the property is present but empty, the return value is the empty string.
14081 If the property is not present at all, nil is returned.
14083 If LITERAL-NIL is set, return the string value \"nil\" as a string,
14084 do not interpret it as the list atom nil. This is used for inheritance
14085 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
14086 (org-with-point-at pom
14087 (if (and inherit (if (eq inherit 'selective)
14088 (org-property-inherit-p property)
14090 (org-entry-get-with-inheritance property literal-nil)
14091 (if (member property org-special-properties)
14092 ;; We need a special property. Use `org-entry-properties' to
14093 ;; retrieve it, but specify the wanted property
14094 (cdr (assoc property (org-entry-properties nil 'special property)))
14095 (let ((range (unless (org-before-first-heading-p)
14096 (org-get-property-block))))
14097 (when (and range (goto-char (car range)))
14098 ((lambda (val) (when val (if literal-nil val (org-not-nil val))))
14099 (cond
14100 ((re-search-forward
14101 (org-re-property property) (cdr range) t)
14102 (if (match-end 1) (org-match-string-no-properties 1) ""))
14103 ((re-search-forward
14104 (org-re-property (concat property "+")) (cdr range) t)
14105 (cdr (assoc
14106 property
14107 (org-update-property-plist
14108 (concat property "+")
14109 (if (match-end 1) (org-match-string-no-properties 1) "")
14110 (list (or (assoc property org-file-properties)
14111 (assoc property org-global-properties)
14112 (assoc property org-global-properties-fixed)
14113 ))))))))))))))
14115 (defun org-property-or-variable-value (var &optional inherit)
14116 "Check if there is a property fixing the value of VAR.
14117 If yes, return this value. If not, return the current value of the variable."
14118 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14119 (if (and prop (stringp prop) (string-match "\\S-" prop))
14120 (read prop)
14121 (symbol-value var))))
14123 (defun org-entry-delete (pom property)
14124 "Delete the property PROPERTY from entry at point-or-marker POM."
14125 (org-with-point-at pom
14126 (if (member property org-special-properties)
14127 nil ; cannot delete these properties.
14128 (let ((range (org-get-property-block)))
14129 (if (and range
14130 (goto-char (car range))
14131 (re-search-forward
14132 (org-re-property property)
14133 (cdr range) t))
14134 (progn
14135 (delete-region (match-beginning 0) (1+ (point-at-eol)))
14137 nil)))))
14139 ;; Multi-values properties are properties that contain multiple values
14140 ;; These values are assumed to be single words, separated by whitespace.
14141 (defun org-entry-add-to-multivalued-property (pom property value)
14142 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
14143 (let* ((old (org-entry-get pom property))
14144 (values (and old (org-split-string old "[ \t]"))))
14145 (setq value (org-entry-protect-space value))
14146 (unless (member value values)
14147 (setq values (cons value values))
14148 (org-entry-put pom property
14149 (mapconcat 'identity values " ")))))
14151 (defun org-entry-remove-from-multivalued-property (pom property value)
14152 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
14153 (let* ((old (org-entry-get pom property))
14154 (values (and old (org-split-string old "[ \t]"))))
14155 (setq value (org-entry-protect-space value))
14156 (when (member value values)
14157 (setq values (delete value values))
14158 (org-entry-put pom property
14159 (mapconcat 'identity values " ")))))
14161 (defun org-entry-member-in-multivalued-property (pom property value)
14162 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
14163 (let* ((old (org-entry-get pom property))
14164 (values (and old (org-split-string old "[ \t]"))))
14165 (setq value (org-entry-protect-space value))
14166 (member value values)))
14168 (defun org-entry-get-multivalued-property (pom property)
14169 "Return a list of values in a multivalued property."
14170 (let* ((value (org-entry-get pom property))
14171 (values (and value (org-split-string value "[ \t]"))))
14172 (mapcar 'org-entry-restore-space values)))
14174 (defun org-entry-put-multivalued-property (pom property &rest values)
14175 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
14176 VALUES should be a list of strings. Spaces will be protected."
14177 (org-entry-put pom property
14178 (mapconcat 'org-entry-protect-space values " "))
14179 (let* ((value (org-entry-get pom property))
14180 (values (and value (org-split-string value "[ \t]"))))
14181 (mapcar 'org-entry-restore-space values)))
14183 (defun org-entry-protect-space (s)
14184 "Protect spaces and newline in string S."
14185 (while (string-match " " s)
14186 (setq s (replace-match "%20" t t s)))
14187 (while (string-match "\n" s)
14188 (setq s (replace-match "%0A" t t s)))
14191 (defun org-entry-restore-space (s)
14192 "Restore spaces and newline in string S."
14193 (while (string-match "%20" s)
14194 (setq s (replace-match " " t t s)))
14195 (while (string-match "%0A" s)
14196 (setq s (replace-match "\n" t t s)))
14199 (defvar org-entry-property-inherited-from (make-marker)
14200 "Marker pointing to the entry from where a property was inherited.
14201 Each call to `org-entry-get-with-inheritance' will set this marker to the
14202 location of the entry where the inheritance search matched. If there was
14203 no match, the marker will point nowhere.
14204 Note that also `org-entry-get' calls this function, if the INHERIT flag
14205 is set.")
14207 (defun org-entry-get-with-inheritance (property &optional literal-nil)
14208 "Get entry property, and search higher levels if not present.
14209 The search will stop at the first ancestor which has the property defined.
14210 If the value found is \"nil\", return nil to show that the property
14211 should be considered as undefined (this is the meaning of nil here).
14212 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
14213 (move-marker org-entry-property-inherited-from nil)
14214 (let (tmp)
14215 (unless (org-before-first-heading-p)
14216 (save-excursion
14217 (save-restriction
14218 (widen)
14219 (catch 'ex
14220 (while t
14221 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
14222 (org-back-to-heading t)
14223 (move-marker org-entry-property-inherited-from (point))
14224 (throw 'ex tmp))
14225 (or (org-up-heading-safe) (throw 'ex nil)))))))
14226 (setq tmp (or tmp
14227 (cdr (assoc property org-file-properties))
14228 (cdr (assoc property org-global-properties))
14229 (cdr (assoc property org-global-properties-fixed))))
14230 (if literal-nil tmp (org-not-nil tmp))))
14232 (defvar org-property-changed-functions nil
14233 "Hook called when the value of a property has changed.
14234 Each hook function should accept two arguments, the name of the property
14235 and the new value.")
14237 (defun org-entry-put (pom property value)
14238 "Set PROPERTY to VALUE for entry at point-or-marker POM."
14239 (org-with-point-at pom
14240 (org-back-to-heading t)
14241 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
14242 range)
14243 (cond
14244 ((equal property "TODO")
14245 (when (and (stringp value) (string-match "\\S-" value)
14246 (not (member value org-todo-keywords-1)))
14247 (error "\"%s\" is not a valid TODO state" value))
14248 (if (or (not value)
14249 (not (string-match "\\S-" value)))
14250 (setq value 'none))
14251 (org-todo value)
14252 (org-set-tags nil 'align))
14253 ((equal property "PRIORITY")
14254 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
14255 (string-to-char value) ?\ ))
14256 (org-set-tags nil 'align))
14257 ((equal property "SCHEDULED")
14258 (if (re-search-forward org-scheduled-time-regexp end t)
14259 (cond
14260 ((eq value 'earlier) (org-timestamp-change -1 'day))
14261 ((eq value 'later) (org-timestamp-change 1 'day))
14262 (t (call-interactively 'org-schedule)))
14263 (call-interactively 'org-schedule)))
14264 ((equal property "DEADLINE")
14265 (if (re-search-forward org-deadline-time-regexp end t)
14266 (cond
14267 ((eq value 'earlier) (org-timestamp-change -1 'day))
14268 ((eq value 'later) (org-timestamp-change 1 'day))
14269 (t (call-interactively 'org-deadline)))
14270 (call-interactively 'org-deadline)))
14271 ((member property org-special-properties)
14272 (error "The %s property can not yet be set with `org-entry-put'"
14273 property))
14274 (t ; a non-special property
14275 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
14276 (setq range (org-get-property-block beg end 'force))
14277 (goto-char (car range))
14278 (if (re-search-forward
14279 (org-re-property property) (cdr range) t)
14280 (progn
14281 (delete-region (match-beginning 0) (match-end 0))
14282 (goto-char (match-beginning 0)))
14283 (goto-char (cdr range))
14284 (insert "\n")
14285 (backward-char 1)
14286 (org-indent-line-function))
14287 (insert ":" property ":")
14288 (and value (insert " " value))
14289 (org-indent-line-function)))))
14290 (run-hook-with-args 'org-property-changed-functions property value)))
14292 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
14293 "Get all property keys in the current buffer.
14294 With INCLUDE-SPECIALS, also list the special properties that reflect things
14295 like tags and TODO state.
14296 With INCLUDE-DEFAULTS, also include properties that has special meaning
14297 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
14298 and others.
14299 With INCLUDE-COLUMNS, also include property names given in COLUMN
14300 formats in the current buffer."
14301 (let (rtn range cfmt s p)
14302 (save-excursion
14303 (save-restriction
14304 (widen)
14305 (goto-char (point-min))
14306 (while (re-search-forward org-property-start-re nil t)
14307 (setq range (org-get-property-block))
14308 (goto-char (car range))
14309 (while (re-search-forward
14310 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
14311 (cdr range) t)
14312 (add-to-list 'rtn (org-match-string-no-properties 1)))
14313 (outline-next-heading))))
14315 (when include-specials
14316 (setq rtn (append org-special-properties rtn)))
14318 (when include-defaults
14319 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
14320 (add-to-list 'rtn org-effort-property))
14322 (when include-columns
14323 (save-excursion
14324 (save-restriction
14325 (widen)
14326 (goto-char (point-min))
14327 (while (re-search-forward
14328 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
14329 nil t)
14330 (setq cfmt (match-string 2) s 0)
14331 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
14332 cfmt s)
14333 (setq s (match-end 0)
14334 p (match-string 1 cfmt))
14335 (unless (or (equal p "ITEM")
14336 (member p org-special-properties))
14337 (add-to-list 'rtn (match-string 1 cfmt))))))))
14339 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
14341 (defun org-property-values (key)
14342 "Return a list of all values of property KEY in the current buffer."
14343 (save-excursion
14344 (save-restriction
14345 (widen)
14346 (goto-char (point-min))
14347 (let ((re (org-re-property key))
14348 values)
14349 (while (re-search-forward re nil t)
14350 (add-to-list 'values (org-trim (match-string 1))))
14351 (delete "" values)))))
14353 (defun org-insert-property-drawer ()
14354 "Insert a property drawer into the current entry."
14355 (interactive)
14356 (org-back-to-heading t)
14357 (looking-at org-outline-regexp)
14358 (let ((indent (if org-adapt-indentation
14359 (- (match-end 0)(match-beginning 0))
14361 (beg (point))
14362 (re (concat "^[ \t]*" org-keyword-time-regexp))
14363 end hiddenp)
14364 (outline-next-heading)
14365 (setq end (point))
14366 (goto-char beg)
14367 (while (re-search-forward re end t))
14368 (setq hiddenp (outline-invisible-p))
14369 (end-of-line 1)
14370 (and (equal (char-after) ?\n) (forward-char 1))
14371 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
14372 (if (member (match-string 1) '("CLOCK:" ":END:"))
14373 ;; just skip this line
14374 (beginning-of-line 2)
14375 ;; Drawer start, find the end
14376 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
14377 (beginning-of-line 1)))
14378 (org-skip-over-state-notes)
14379 (skip-chars-backward " \t\n\r")
14380 (if (eq (char-before) ?*) (forward-char 1))
14381 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
14382 (beginning-of-line 0)
14383 (org-indent-to-column indent)
14384 (beginning-of-line 2)
14385 (org-indent-to-column indent)
14386 (beginning-of-line 0)
14387 (if hiddenp
14388 (save-excursion
14389 (org-back-to-heading t)
14390 (hide-entry))
14391 (org-flag-drawer t))))
14393 (defvar org-property-set-functions-alist nil
14394 "Property set function alist.
14395 Each entry should have the following format:
14397 (PROPERTY . READ-FUNCTION)
14399 The read function will be called with the same argument as
14400 `org-completing-read'.")
14402 (defun org-set-property-function (property)
14403 "Get the function that should be used to set PROPERTY.
14404 This is computed according to `org-property-set-functions-alist'."
14405 (or (cdr (assoc property org-property-set-functions-alist))
14406 'org-completing-read))
14408 (defun org-read-property-value (property)
14409 "Read PROPERTY value from user."
14410 (let* ((completion-ignore-case t)
14411 (allowed (org-property-get-allowed-values nil property 'table))
14412 (cur (org-entry-get nil property))
14413 (prompt (concat property " value"
14414 (if (and cur (string-match "\\S-" cur))
14415 (concat " [" cur "]") "") ": "))
14416 (set-function (org-set-property-function property))
14417 (val (if allowed
14418 (funcall set-function prompt allowed nil
14419 (not (get-text-property 0 'org-unrestricted
14420 (caar allowed))))
14421 (let (org-completion-use-ido org-completion-use-iswitchb)
14422 (funcall set-function prompt
14423 (mapcar 'list (org-property-values property))
14424 nil nil "" nil cur)))))
14425 (if (equal val "")
14427 val)))
14429 (defvar org-last-set-property nil)
14430 (defun org-read-property-name ()
14431 "Read a property name."
14432 (let* ((completion-ignore-case t)
14433 (keys (org-buffer-property-keys nil t t))
14434 (default-prop (or (save-excursion
14435 (save-match-data
14436 (beginning-of-line)
14437 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
14438 (null (string= (match-string 1) "END"))
14439 (match-string 1))))
14440 org-last-set-property))
14441 (property (org-icompleting-read
14442 (concat "Property"
14443 (if default-prop (concat " [" default-prop "]") "")
14444 ": ")
14445 (mapcar 'list keys)
14446 nil nil nil nil
14447 default-prop
14449 (if (member property keys)
14450 property
14451 (or (cdr (assoc (downcase property)
14452 (mapcar (lambda (x) (cons (downcase x) x))
14453 keys)))
14454 property))))
14456 (defun org-set-property (property value)
14457 "In the current entry, set PROPERTY to VALUE.
14458 When called interactively, this will prompt for a property name, offering
14459 completion on existing and default properties. And then it will prompt
14460 for a value, offering completion either on allowed values (via an inherited
14461 xxx_ALL property) or on existing values in other instances of this property
14462 in the current file."
14463 (interactive (list nil nil))
14464 (let* ((property (or property (org-read-property-name)))
14465 (value (or value (org-read-property-value property)))
14466 (fn (assoc property org-properties-postprocess-alist)))
14467 (setq org-last-set-property property)
14468 ;; Possibly postprocess the inserted value:
14469 (when fn (setq value (funcall (cadr fn) value)))
14470 (unless (equal (org-entry-get nil property) value)
14471 (org-entry-put nil property value))))
14473 (defun org-delete-property (property)
14474 "In the current entry, delete PROPERTY."
14475 (interactive
14476 (let* ((completion-ignore-case t)
14477 (prop (org-icompleting-read "Property: "
14478 (org-entry-properties nil 'standard))))
14479 (list prop)))
14480 (message "Property %s %s" property
14481 (if (org-entry-delete nil property)
14482 "deleted"
14483 "was not present in the entry")))
14485 (defun org-delete-property-globally (property)
14486 "Remove PROPERTY globally, from all entries."
14487 (interactive
14488 (let* ((completion-ignore-case t)
14489 (prop (org-icompleting-read
14490 "Globally remove property: "
14491 (mapcar 'list (org-buffer-property-keys)))))
14492 (list prop)))
14493 (save-excursion
14494 (save-restriction
14495 (widen)
14496 (goto-char (point-min))
14497 (let ((cnt 0))
14498 (while (re-search-forward
14499 (org-re-property property)
14500 nil t)
14501 (setq cnt (1+ cnt))
14502 (replace-match ""))
14503 (message "Property \"%s\" removed from %d entries" property cnt)))))
14505 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
14507 (defun org-compute-property-at-point ()
14508 "Compute the property at point.
14509 This looks for an enclosing column format, extracts the operator and
14510 then applies it to the property in the column format's scope."
14511 (interactive)
14512 (unless (org-at-property-p)
14513 (error "Not at a property"))
14514 (let ((prop (org-match-string-no-properties 2)))
14515 (org-columns-get-format-and-top-level)
14516 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
14517 (error "No operator defined for property %s" prop))
14518 (org-columns-compute prop)))
14520 (defvar org-property-allowed-value-functions nil
14521 "Hook for functions supplying allowed values for a specific property.
14522 The functions must take a single argument, the name of the property, and
14523 return a flat list of allowed values. If \":ETC\" is one of
14524 the values, this means that these values are intended as defaults for
14525 completion, but that other values should be allowed too.
14526 The functions must return nil if they are not responsible for this
14527 property.")
14529 (defun org-property-get-allowed-values (pom property &optional table)
14530 "Get allowed values for the property PROPERTY.
14531 When TABLE is non-nil, return an alist that can directly be used for
14532 completion."
14533 (let (vals)
14534 (cond
14535 ((equal property "TODO")
14536 (setq vals (org-with-point-at pom
14537 (append org-todo-keywords-1 '("")))))
14538 ((equal property "PRIORITY")
14539 (let ((n org-lowest-priority))
14540 (while (>= n org-highest-priority)
14541 (push (char-to-string n) vals)
14542 (setq n (1- n)))))
14543 ((member property org-special-properties))
14544 ((setq vals (run-hook-with-args-until-success
14545 'org-property-allowed-value-functions property)))
14547 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
14548 (when (and vals (string-match "\\S-" vals))
14549 (setq vals (car (read-from-string (concat "(" vals ")"))))
14550 (setq vals (mapcar (lambda (x)
14551 (cond ((stringp x) x)
14552 ((numberp x) (number-to-string x))
14553 ((symbolp x) (symbol-name x))
14554 (t "???")))
14555 vals)))))
14556 (when (member ":ETC" vals)
14557 (setq vals (remove ":ETC" vals))
14558 (org-add-props (car vals) '(org-unrestricted t)))
14559 (if table (mapcar 'list vals) vals)))
14561 (defun org-property-previous-allowed-value (&optional previous)
14562 "Switch to the next allowed value for this property."
14563 (interactive)
14564 (org-property-next-allowed-value t))
14566 (defun org-property-next-allowed-value (&optional previous)
14567 "Switch to the next allowed value for this property."
14568 (interactive)
14569 (unless (org-at-property-p)
14570 (error "Not at a property"))
14571 (let* ((key (match-string 2))
14572 (value (match-string 3))
14573 (allowed (or (org-property-get-allowed-values (point) key)
14574 (and (member value '("[ ]" "[-]" "[X]"))
14575 '("[ ]" "[X]"))))
14576 nval)
14577 (unless allowed
14578 (error "Allowed values for this property have not been defined"))
14579 (if previous (setq allowed (reverse allowed)))
14580 (if (member value allowed)
14581 (setq nval (car (cdr (member value allowed)))))
14582 (setq nval (or nval (car allowed)))
14583 (if (equal nval value)
14584 (error "Only one allowed value for this property"))
14585 (org-at-property-p)
14586 (replace-match (concat " :" key ": " nval) t t)
14587 (org-indent-line-function)
14588 (beginning-of-line 1)
14589 (skip-chars-forward " \t")
14590 (run-hook-with-args 'org-property-changed-functions key nval)))
14592 (defun org-find-olp (path &optional this-buffer)
14593 "Return a marker pointing to the entry at outline path OLP.
14594 If anything goes wrong, throw an error.
14595 You can wrap this call to catch the error like this:
14597 (condition-case msg
14598 (org-mobile-locate-entry (match-string 4))
14599 (error (nth 1 msg)))
14601 The return value will then be either a string with the error message,
14602 or a marker if everything is OK.
14604 If THIS-BUFFER is set, the outline path does not contain a file,
14605 only headings."
14606 (let* ((file (if this-buffer buffer-file-name (pop path)))
14607 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
14608 (level 1)
14609 (lmin 1)
14610 (lmax 1)
14611 limit re end found pos heading cnt flevel)
14612 (unless buffer (error "File not found :%s" file))
14613 (with-current-buffer buffer
14614 (save-excursion
14615 (save-restriction
14616 (widen)
14617 (setq limit (point-max))
14618 (goto-char (point-min))
14619 (while (setq heading (pop path))
14620 (setq re (format org-complex-heading-regexp-format
14621 (regexp-quote heading)))
14622 (setq cnt 0 pos (point))
14623 (while (re-search-forward re end t)
14624 (setq level (- (match-end 1) (match-beginning 1)))
14625 (if (and (>= level lmin) (<= level lmax))
14626 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
14627 (when (= cnt 0) (error "Heading not found on level %d: %s"
14628 lmax heading))
14629 (when (> cnt 1) (error "Heading not unique on level %d: %s"
14630 lmax heading))
14631 (goto-char found)
14632 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
14633 (setq end (save-excursion (org-end-of-subtree t t))))
14634 (when (org-on-heading-p)
14635 (move-marker (make-marker) (point))))))))
14637 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
14638 "Find node HEADING in BUFFER.
14639 Return a marker to the heading if it was found, or nil if not.
14640 If POS-ONLY is set, return just the position instead of a marker.
14642 The heading text must match exact, but it may have a TODO keyword,
14643 a priority cookie and tags in the standard locations."
14644 (with-current-buffer (or buffer (current-buffer))
14645 (save-excursion
14646 (save-restriction
14647 (widen)
14648 (goto-char (point-min))
14649 (let (case-fold-search)
14650 (if (re-search-forward
14651 (format org-complex-heading-regexp-format
14652 (regexp-quote heading)) nil t)
14653 (if pos-only
14654 (match-beginning 0)
14655 (move-marker (make-marker) (match-beginning 0)))))))))
14657 (defun org-find-exact-heading-in-directory (heading &optional dir)
14658 "Find Org node headline HEADING in all .org files in directory DIR.
14659 When the target headline is found, return a marker to this location."
14660 (let ((files (directory-files (or dir default-directory)
14661 nil "\\`[^.#].*\\.org\\'"))
14662 file visiting m buffer)
14663 (catch 'found
14664 (while (setq file (pop files))
14665 (message "trying %s" file)
14666 (setq visiting (org-find-base-buffer-visiting file))
14667 (setq buffer (or visiting (find-file-noselect file)))
14668 (setq m (org-find-exact-headline-in-buffer
14669 heading buffer))
14670 (when (and (not m) (not visiting)) (kill-buffer buffer))
14671 (and m (throw 'found m))))))
14673 (defun org-find-entry-with-id (ident)
14674 "Locate the entry that contains the ID property with exact value IDENT.
14675 IDENT can be a string, a symbol or a number, this function will search for
14676 the string representation of it.
14677 Return the position where this entry starts, or nil if there is no such entry."
14678 (interactive "sID: ")
14679 (let ((id (cond
14680 ((stringp ident) ident)
14681 ((symbol-name ident) (symbol-name ident))
14682 ((numberp ident) (number-to-string ident))
14683 (t (error "IDENT %s must be a string, symbol or number" ident))))
14684 (case-fold-search nil))
14685 (save-excursion
14686 (save-restriction
14687 (widen)
14688 (goto-char (point-min))
14689 (when (re-search-forward
14690 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
14691 nil t)
14692 (org-back-to-heading t)
14693 (point))))))
14695 ;;;; Timestamps
14697 (defvar org-last-changed-timestamp nil)
14698 (defvar org-last-inserted-timestamp nil
14699 "The last time stamp inserted with `org-insert-time-stamp'.")
14700 (defvar org-time-was-given) ; dynamically scoped parameter
14701 (defvar org-end-time-was-given) ; dynamically scoped parameter
14702 (defvar org-ts-what) ; dynamically scoped parameter
14704 (defun org-time-stamp (arg &optional inactive)
14705 "Prompt for a date/time and insert a time stamp.
14706 If the user specifies a time like HH:MM, or if this command is called
14707 with a prefix argument, the time stamp will contain date and time.
14708 Otherwise, only the date will be included. All parts of a date not
14709 specified by the user will be filled in from the current date/time.
14710 So if you press just return without typing anything, the time stamp
14711 will represent the current date/time. If there is already a timestamp
14712 at the cursor, it will be modified."
14713 (interactive "P")
14714 (let* ((ts nil)
14715 (default-time
14716 ;; Default time is either today, or, when entering a range,
14717 ;; the range start.
14718 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
14719 (save-excursion
14720 (re-search-backward
14721 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
14722 (- (point) 20) t)))
14723 (apply 'encode-time (org-parse-time-string (match-string 1)))
14724 (current-time)))
14725 (default-input (and ts (org-get-compact-tod ts)))
14726 (repeater (save-excursion
14727 (save-match-data
14728 (beginning-of-line)
14729 (when (re-search-forward
14730 "\\([.+-]+[0-9]+[dwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[dwmy]\\)?\\) ?"
14731 (save-excursion (progn (end-of-line) (point))) t)
14732 (match-string 0)))))
14733 org-time-was-given org-end-time-was-given time)
14734 (cond
14735 ((and (org-at-timestamp-p t)
14736 (memq last-command '(org-time-stamp org-time-stamp-inactive))
14737 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
14738 (insert "--")
14739 (setq time (let ((this-command this-command))
14740 (org-read-date arg 'totime nil nil
14741 default-time default-input)))
14742 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
14743 ((org-at-timestamp-p t)
14744 (setq time (let ((this-command this-command))
14745 (org-read-date arg 'totime nil nil default-time default-input)))
14746 (when (org-at-timestamp-p t) ; just to get the match data
14747 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
14748 (replace-match "")
14749 (setq org-last-changed-timestamp
14750 (org-insert-time-stamp
14751 time (or org-time-was-given arg)
14752 inactive nil nil (list org-end-time-was-given)))
14753 (when repeater (goto-char (1- (point))) (insert " " repeater)
14754 (setq org-last-changed-timestamp
14755 (concat (substring org-last-inserted-timestamp 0 -1)
14756 " " repeater ">"))))
14757 (message "Timestamp updated"))
14759 (setq time (let ((this-command this-command))
14760 (org-read-date arg 'totime nil nil default-time default-input)))
14761 (org-insert-time-stamp time (or org-time-was-given arg) inactive
14762 nil nil (list org-end-time-was-given))))))
14764 ;; FIXME: can we use this for something else, like computing time differences?
14765 (defun org-get-compact-tod (s)
14766 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
14767 (let* ((t1 (match-string 1 s))
14768 (h1 (string-to-number (match-string 2 s)))
14769 (m1 (string-to-number (match-string 3 s)))
14770 (t2 (and (match-end 4) (match-string 5 s)))
14771 (h2 (and t2 (string-to-number (match-string 6 s))))
14772 (m2 (and t2 (string-to-number (match-string 7 s))))
14773 dh dm)
14774 (if (not t2)
14776 (setq dh (- h2 h1) dm (- m2 m1))
14777 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
14778 (concat t1 "+" (number-to-string dh)
14779 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
14781 (defun org-time-stamp-inactive (&optional arg)
14782 "Insert an inactive time stamp.
14783 An inactive time stamp is enclosed in square brackets instead of angle
14784 brackets. It is inactive in the sense that it does not trigger agenda entries,
14785 does not link to the calendar and cannot be changed with the S-cursor keys.
14786 So these are more for recording a certain time/date."
14787 (interactive "P")
14788 (org-time-stamp arg 'inactive))
14790 (defvar org-date-ovl (make-overlay 1 1))
14791 (overlay-put org-date-ovl 'face 'org-warning)
14792 (org-detach-overlay org-date-ovl)
14794 (defvar org-ans1) ; dynamically scoped parameter
14795 (defvar org-ans2) ; dynamically scoped parameter
14797 (defvar org-plain-time-of-day-regexp) ; defined below
14799 (defvar org-overriding-default-time nil) ; dynamically scoped
14800 (defvar org-read-date-overlay nil)
14801 (defvar org-dcst nil) ; dynamically scoped
14802 (defvar org-read-date-history nil)
14803 (defvar org-read-date-final-answer nil)
14804 (defvar org-read-date-analyze-futurep nil)
14805 (defvar org-read-date-analyze-forced-year nil)
14807 (defun org-read-date (&optional with-time to-time from-string prompt
14808 default-time default-input)
14809 "Read a date, possibly a time, and make things smooth for the user.
14810 The prompt will suggest to enter an ISO date, but you can also enter anything
14811 which will at least partially be understood by `parse-time-string'.
14812 Unrecognized parts of the date will default to the current day, month, year,
14813 hour and minute. If this command is called to replace a timestamp at point,
14814 of to enter the second timestamp of a range, the default time is taken
14815 from the existing stamp. Furthermore, the command prefers the future,
14816 so if you are giving a date where the year is not given, and the day-month
14817 combination is already past in the current year, it will assume you
14818 mean next year. For details, see the manual. A few examples:
14820 3-2-5 --> 2003-02-05
14821 feb 15 --> currentyear-02-15
14822 2/15 --> currentyear-02-15
14823 sep 12 9 --> 2009-09-12
14824 12:45 --> today 12:45
14825 22 sept 0:34 --> currentyear-09-22 0:34
14826 12 --> currentyear-currentmonth-12
14827 Fri --> nearest Friday (today or later)
14828 etc.
14830 Furthermore you can specify a relative date by giving, as the *first* thing
14831 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
14832 change in days weeks, months, years.
14833 With a single plus or minus, the date is relative to today. With a double
14834 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
14835 +4d --> four days from today
14836 +4 --> same as above
14837 +2w --> two weeks from today
14838 ++5 --> five days from default date
14840 The function understands only English month and weekday abbreviations,
14841 but this can be configured with the variables `parse-time-months' and
14842 `parse-time-weekdays'.
14844 While prompting, a calendar is popped up - you can also select the
14845 date with the mouse (button 1). The calendar shows a period of three
14846 months. To scroll it to other months, use the keys `>' and `<'.
14847 If you don't like the calendar, turn it off with
14848 \(setq org-read-date-popup-calendar nil)
14850 With optional argument TO-TIME, the date will immediately be converted
14851 to an internal time.
14852 With an optional argument WITH-TIME, the prompt will suggest to also
14853 insert a time. Note that when WITH-TIME is not set, you can still
14854 enter a time, and this function will inform the calling routine about
14855 this change. The calling routine may then choose to change the format
14856 used to insert the time stamp into the buffer to include the time.
14857 With optional argument FROM-STRING, read from this string instead from
14858 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
14859 the time/date that is used for everything that is not specified by the
14860 user."
14861 (require 'parse-time)
14862 (let* ((org-time-stamp-rounding-minutes
14863 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
14864 (org-dcst org-display-custom-times)
14865 (ct (org-current-time))
14866 (def (or org-overriding-default-time default-time ct))
14867 (defdecode (decode-time def))
14868 (dummy (progn
14869 (when (< (nth 2 defdecode) org-extend-today-until)
14870 (setcar (nthcdr 2 defdecode) -1)
14871 (setcar (nthcdr 1 defdecode) 59)
14872 (setq def (apply 'encode-time defdecode)
14873 defdecode (decode-time def)))))
14874 (calendar-frame-setup nil)
14875 (calendar-setup nil)
14876 (calendar-move-hook nil)
14877 (calendar-view-diary-initially-flag nil)
14878 (calendar-view-holidays-initially-flag nil)
14879 (timestr (format-time-string
14880 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
14881 (prompt (concat (if prompt (concat prompt " ") "")
14882 (format "Date+time [%s]: " timestr)))
14883 ans (org-ans0 "") org-ans1 org-ans2 final)
14885 (cond
14886 (from-string (setq ans from-string))
14887 (org-read-date-popup-calendar
14888 (save-excursion
14889 (save-window-excursion
14890 (calendar)
14891 (unwind-protect
14892 (progn
14893 (calendar-forward-day (- (time-to-days def)
14894 (calendar-absolute-from-gregorian
14895 (calendar-current-date))))
14896 (org-eval-in-calendar nil t)
14897 (let* ((old-map (current-local-map))
14898 (map (copy-keymap calendar-mode-map))
14899 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
14900 (org-defkey map (kbd "RET") 'org-calendar-select)
14901 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
14902 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
14903 (org-defkey minibuffer-local-map [(meta shift left)]
14904 (lambda () (interactive)
14905 (org-eval-in-calendar '(calendar-backward-month 1))))
14906 (org-defkey minibuffer-local-map [(meta shift right)]
14907 (lambda () (interactive)
14908 (org-eval-in-calendar '(calendar-forward-month 1))))
14909 (org-defkey minibuffer-local-map [(meta shift up)]
14910 (lambda () (interactive)
14911 (org-eval-in-calendar '(calendar-backward-year 1))))
14912 (org-defkey minibuffer-local-map [(meta shift down)]
14913 (lambda () (interactive)
14914 (org-eval-in-calendar '(calendar-forward-year 1))))
14915 (org-defkey minibuffer-local-map [?\e (shift left)]
14916 (lambda () (interactive)
14917 (org-eval-in-calendar '(calendar-backward-month 1))))
14918 (org-defkey minibuffer-local-map [?\e (shift right)]
14919 (lambda () (interactive)
14920 (org-eval-in-calendar '(calendar-forward-month 1))))
14921 (org-defkey minibuffer-local-map [?\e (shift up)]
14922 (lambda () (interactive)
14923 (org-eval-in-calendar '(calendar-backward-year 1))))
14924 (org-defkey minibuffer-local-map [?\e (shift down)]
14925 (lambda () (interactive)
14926 (org-eval-in-calendar '(calendar-forward-year 1))))
14927 (org-defkey minibuffer-local-map [(shift up)]
14928 (lambda () (interactive)
14929 (org-eval-in-calendar '(calendar-backward-week 1))))
14930 (org-defkey minibuffer-local-map [(shift down)]
14931 (lambda () (interactive)
14932 (org-eval-in-calendar '(calendar-forward-week 1))))
14933 (org-defkey minibuffer-local-map [(shift left)]
14934 (lambda () (interactive)
14935 (org-eval-in-calendar '(calendar-backward-day 1))))
14936 (org-defkey minibuffer-local-map [(shift right)]
14937 (lambda () (interactive)
14938 (org-eval-in-calendar '(calendar-forward-day 1))))
14939 (org-defkey minibuffer-local-map ">"
14940 (lambda () (interactive)
14941 (org-eval-in-calendar '(scroll-calendar-left 1))))
14942 (org-defkey minibuffer-local-map "<"
14943 (lambda () (interactive)
14944 (org-eval-in-calendar '(scroll-calendar-right 1))))
14945 (org-defkey minibuffer-local-map "\C-v"
14946 (lambda () (interactive)
14947 (org-eval-in-calendar
14948 '(calendar-scroll-left-three-months 1))))
14949 (org-defkey minibuffer-local-map "\M-v"
14950 (lambda () (interactive)
14951 (org-eval-in-calendar
14952 '(calendar-scroll-right-three-months 1))))
14953 (run-hooks 'org-read-date-minibuffer-setup-hook)
14954 (unwind-protect
14955 (progn
14956 (use-local-map map)
14957 (add-hook 'post-command-hook 'org-read-date-display)
14958 (setq org-ans0 (read-string prompt default-input
14959 'org-read-date-history nil))
14960 ;; org-ans0: from prompt
14961 ;; org-ans1: from mouse click
14962 ;; org-ans2: from calendar motion
14963 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
14964 (remove-hook 'post-command-hook 'org-read-date-display)
14965 (use-local-map old-map)
14966 (when org-read-date-overlay
14967 (delete-overlay org-read-date-overlay)
14968 (setq org-read-date-overlay nil)))))
14969 (bury-buffer "*Calendar*")))))
14971 (t ; Naked prompt only
14972 (unwind-protect
14973 (setq ans (read-string prompt default-input
14974 'org-read-date-history timestr))
14975 (when org-read-date-overlay
14976 (delete-overlay org-read-date-overlay)
14977 (setq org-read-date-overlay nil)))))
14979 (setq final (org-read-date-analyze ans def defdecode))
14981 (when org-read-date-analyze-forced-year
14982 (message "Year was forced into %s"
14983 (if org-read-date-force-compatible-dates
14984 "compatible range (1970-2037)"
14985 "range representable on this machine"))
14986 (ding))
14988 ;; One round trip to get rid of 34th of August and stuff like that....
14989 (setq final (decode-time (apply 'encode-time final)))
14991 (setq org-read-date-final-answer ans)
14993 (if to-time
14994 (apply 'encode-time final)
14995 (if (and (boundp 'org-time-was-given) org-time-was-given)
14996 (format "%04d-%02d-%02d %02d:%02d"
14997 (nth 5 final) (nth 4 final) (nth 3 final)
14998 (nth 2 final) (nth 1 final))
14999 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
15001 (defvar def)
15002 (defvar defdecode)
15003 (defvar with-time)
15004 (defun org-read-date-display ()
15005 "Display the current date prompt interpretation in the minibuffer."
15006 (when org-read-date-display-live
15007 (when org-read-date-overlay
15008 (delete-overlay org-read-date-overlay))
15009 (let ((p (point)))
15010 (end-of-line 1)
15011 (while (not (equal (buffer-substring
15012 (max (point-min) (- (point) 4)) (point))
15013 " "))
15014 (insert " "))
15015 (goto-char p))
15016 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
15017 " " (or org-ans1 org-ans2)))
15018 (org-end-time-was-given nil)
15019 (f (org-read-date-analyze ans def defdecode))
15020 (fmts (if org-dcst
15021 org-time-stamp-custom-formats
15022 org-time-stamp-formats))
15023 (fmt (if (or with-time
15024 (and (boundp 'org-time-was-given) org-time-was-given))
15025 (cdr fmts)
15026 (car fmts)))
15027 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
15028 (when (and org-end-time-was-given
15029 (string-match org-plain-time-of-day-regexp txt))
15030 (setq txt (concat (substring txt 0 (match-end 0)) "-"
15031 org-end-time-was-given
15032 (substring txt (match-end 0)))))
15033 (when org-read-date-analyze-futurep
15034 (setq txt (concat txt " (=>F)")))
15035 (setq org-read-date-overlay
15036 (make-overlay (1- (point-at-eol)) (point-at-eol)))
15037 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
15039 (defun org-read-date-analyze (ans def defdecode)
15040 "Analyze the combined answer of the date prompt."
15041 ;; FIXME: cleanup and comment
15042 (let ((nowdecode (decode-time (current-time)))
15043 delta deltan deltaw deltadef year month day
15044 hour minute second wday pm h2 m2 tl wday1
15045 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
15046 (setq org-read-date-analyze-futurep nil
15047 org-read-date-analyze-forced-year nil)
15048 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
15049 (setq ans "+0"))
15051 (when (setq delta (org-read-date-get-relative ans (current-time) def))
15052 (setq ans (replace-match "" t t ans)
15053 deltan (car delta)
15054 deltaw (nth 1 delta)
15055 deltadef (nth 2 delta)))
15057 ;; Check if there is an iso week date in there
15058 ;; If yes, store the info and postpone interpreting it until the rest
15059 ;; of the parsing is done
15060 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
15061 (setq iso-year (if (match-end 1)
15062 (org-small-year-to-year
15063 (string-to-number (match-string 1 ans))))
15064 iso-weekday (if (match-end 3)
15065 (string-to-number (match-string 3 ans)))
15066 iso-week (string-to-number (match-string 2 ans)))
15067 (setq ans (replace-match "" t t ans)))
15069 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
15070 (when (string-match
15071 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
15072 (setq year (if (match-end 2)
15073 (string-to-number (match-string 2 ans))
15074 (progn (setq kill-year t)
15075 (string-to-number (format-time-string "%Y"))))
15076 month (string-to-number (match-string 3 ans))
15077 day (string-to-number (match-string 4 ans)))
15078 (if (< year 100) (setq year (+ 2000 year)))
15079 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15080 t nil ans)))
15082 ;; Help matching dottet european dates
15083 (when (string-match
15084 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\. ?\\([1-9][0-9][0-9][0-9]\\)?" ans)
15085 (setq year (if (match-end 3)
15086 (string-to-number (match-string 3 ans))
15087 (progn (setq kill-year t)
15088 (string-to-number (format-time-string "%Y"))))
15089 day (string-to-number (match-string 1 ans))
15090 month (string-to-number (match-string 2 ans))
15091 ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15092 t nil ans)))
15094 ;; Help matching american dates, like 5/30 or 5/30/7
15095 (when (string-match
15096 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
15097 (setq year (if (match-end 4)
15098 (string-to-number (match-string 4 ans))
15099 (progn (setq kill-year t)
15100 (string-to-number (format-time-string "%Y"))))
15101 month (string-to-number (match-string 1 ans))
15102 day (string-to-number (match-string 2 ans)))
15103 (if (< year 100) (setq year (+ 2000 year)))
15104 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15105 t nil ans)))
15106 ;; Help matching am/pm times, because `parse-time-string' does not do that.
15107 ;; If there is a time with am/pm, and *no* time without it, we convert
15108 ;; so that matching will be successful.
15109 (loop for i from 1 to 2 do ; twice, for end time as well
15110 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
15111 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
15112 (setq hour (string-to-number (match-string 1 ans))
15113 minute (if (match-end 3)
15114 (string-to-number (match-string 3 ans))
15116 pm (equal ?p
15117 (string-to-char (downcase (match-string 4 ans)))))
15118 (if (and (= hour 12) (not pm))
15119 (setq hour 0)
15120 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
15121 (setq ans (replace-match (format "%02d:%02d" hour minute)
15122 t t ans))))
15124 ;; Check if a time range is given as a duration
15125 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
15126 (setq hour (string-to-number (match-string 1 ans))
15127 h2 (+ hour (string-to-number (match-string 3 ans)))
15128 minute (string-to-number (match-string 2 ans))
15129 m2 (+ minute (if (match-end 5) (string-to-number
15130 (match-string 5 ans))0)))
15131 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
15132 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
15133 t t ans)))
15135 ;; Check if there is a time range
15136 (when (boundp 'org-end-time-was-given)
15137 (setq org-time-was-given nil)
15138 (when (and (string-match org-plain-time-of-day-regexp ans)
15139 (match-end 8))
15140 (setq org-end-time-was-given (match-string 8 ans))
15141 (setq ans (concat (substring ans 0 (match-beginning 7))
15142 (substring ans (match-end 7))))))
15144 (setq tl (parse-time-string ans)
15145 day (or (nth 3 tl) (nth 3 defdecode))
15146 month (or (nth 4 tl)
15147 (if (and org-read-date-prefer-future
15148 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
15149 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
15150 (nth 4 defdecode)))
15151 year (or (and (not kill-year) (nth 5 tl))
15152 (if (and org-read-date-prefer-future
15153 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
15154 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
15155 (nth 5 defdecode)))
15156 hour (or (nth 2 tl) (nth 2 defdecode))
15157 minute (or (nth 1 tl) (nth 1 defdecode))
15158 second (or (nth 0 tl) 0)
15159 wday (nth 6 tl))
15161 (when (and (eq org-read-date-prefer-future 'time)
15162 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
15163 (equal day (nth 3 nowdecode))
15164 (equal month (nth 4 nowdecode))
15165 (equal year (nth 5 nowdecode))
15166 (nth 2 tl)
15167 (or (< (nth 2 tl) (nth 2 nowdecode))
15168 (and (= (nth 2 tl) (nth 2 nowdecode))
15169 (nth 1 tl)
15170 (< (nth 1 tl) (nth 1 nowdecode)))))
15171 (setq day (1+ day)
15172 futurep t))
15174 ;; Special date definitions below
15175 (cond
15176 (iso-week
15177 ;; There was an iso week
15178 (require 'cal-iso)
15179 (setq futurep nil)
15180 (setq year (or iso-year year)
15181 day (or iso-weekday wday 1)
15182 wday nil ; to make sure that the trigger below does not match
15183 iso-date (calendar-gregorian-from-absolute
15184 (calendar-absolute-from-iso
15185 (list iso-week day year))))
15186 ; FIXME: Should we also push ISO weeks into the future?
15187 ; (when (and org-read-date-prefer-future
15188 ; (not iso-year)
15189 ; (< (calendar-absolute-from-gregorian iso-date)
15190 ; (time-to-days (current-time))))
15191 ; (setq year (1+ year)
15192 ; iso-date (calendar-gregorian-from-absolute
15193 ; (calendar-absolute-from-iso
15194 ; (list iso-week day year)))))
15195 (setq month (car iso-date)
15196 year (nth 2 iso-date)
15197 day (nth 1 iso-date)))
15198 (deltan
15199 (setq futurep nil)
15200 (unless deltadef
15201 (let ((now (decode-time (current-time))))
15202 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
15203 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
15204 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
15205 ((equal deltaw "m") (setq month (+ month deltan)))
15206 ((equal deltaw "y") (setq year (+ year deltan)))))
15207 ((and wday (not (nth 3 tl)))
15208 (setq futurep nil)
15209 ;; Weekday was given, but no day, so pick that day in the week
15210 ;; on or after the derived date.
15211 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
15212 (unless (equal wday wday1)
15213 (setq day (+ day (% (- wday wday1 -7) 7))))))
15214 (if (and (boundp 'org-time-was-given)
15215 (nth 2 tl))
15216 (setq org-time-was-given t))
15217 (if (< year 100) (setq year (+ 2000 year)))
15218 ;; Check of the date is representable
15219 (if org-read-date-force-compatible-dates
15220 (progn
15221 (if (< year 1970)
15222 (setq year 1970 org-read-date-analyze-forced-year t))
15223 (if (> year 2037)
15224 (setq year 2037 org-read-date-analyze-forced-year t)))
15225 (condition-case nil
15226 (ignore (encode-time second minute hour day month year))
15227 (error
15228 (setq year (nth 5 defdecode))
15229 (setq org-read-date-analyze-forced-year t))))
15230 (setq org-read-date-analyze-futurep futurep)
15231 (list second minute hour day month year)))
15233 (defvar parse-time-weekdays)
15235 (defun org-read-date-get-relative (s today default)
15236 "Check string S for special relative date string.
15237 TODAY and DEFAULT are internal times, for today and for a default.
15238 Return shift list (N what def-flag)
15239 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
15240 N is the number of WHATs to shift.
15241 DEF-FLAG is t when a double ++ or -- indicates shift relative to
15242 the DEFAULT date rather than TODAY."
15243 (require 'parse-time)
15244 (when (and
15245 (string-match
15246 (concat
15247 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
15248 "\\([0-9]+\\)?"
15249 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
15250 "\\([ \t]\\|$\\)") s)
15251 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
15252 (let* ((dir (if (> (match-end 1) (match-beginning 1))
15253 (string-to-char (substring (match-string 1 s) -1))
15254 ?+))
15255 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
15256 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
15257 (what (if (match-end 3) (match-string 3 s) "d"))
15258 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
15259 (date (if rel default today))
15260 (wday (nth 6 (decode-time date)))
15261 delta)
15262 (if wday1
15263 (progn
15264 (setq delta (mod (+ 7 (- wday1 wday)) 7))
15265 (if (= dir ?-) (setq delta (- delta 7)))
15266 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
15267 (list delta "d" rel))
15268 (list (* n (if (= dir ?-) -1 1)) what rel)))))
15270 (defun org-order-calendar-date-args (arg1 arg2 arg3)
15271 "Turn a user-specified date into the internal representation.
15272 The internal representation needed by the calendar is (month day year).
15273 This is a wrapper to handle the brain-dead convention in calendar that
15274 user function argument order change dependent on argument order."
15275 (if (boundp 'calendar-date-style)
15276 (cond
15277 ((eq calendar-date-style 'american)
15278 (list arg1 arg2 arg3))
15279 ((eq calendar-date-style 'european)
15280 (list arg2 arg1 arg3))
15281 ((eq calendar-date-style 'iso)
15282 (list arg2 arg3 arg1)))
15283 (with-no-warnings ;; european-calendar-style is obsolete as of version 23.1
15284 (if (org-bound-and-true-p european-calendar-style)
15285 (list arg2 arg1 arg3)
15286 (list arg1 arg2 arg3)))))
15288 (defun org-eval-in-calendar (form &optional keepdate)
15289 "Eval FORM in the calendar window and return to current window.
15290 Also, store the cursor date in variable org-ans2."
15291 (let ((sf (selected-frame))
15292 (sw (selected-window)))
15293 (select-window (get-buffer-window "*Calendar*" t))
15294 (eval form)
15295 (when (and (not keepdate) (calendar-cursor-to-date))
15296 (let* ((date (calendar-cursor-to-date))
15297 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15298 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
15299 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
15300 (select-window sw)
15301 (org-select-frame-set-input-focus sf)))
15303 (defun org-calendar-select ()
15304 "Return to `org-read-date' with the date currently selected.
15305 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15306 (interactive)
15307 (when (calendar-cursor-to-date)
15308 (let* ((date (calendar-cursor-to-date))
15309 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15310 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15311 (if (active-minibuffer-window) (exit-minibuffer))))
15313 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
15314 "Insert a date stamp for the date given by the internal TIME.
15315 WITH-HM means use the stamp format that includes the time of the day.
15316 INACTIVE means use square brackets instead of angular ones, so that the
15317 stamp will not contribute to the agenda.
15318 PRE and POST are optional strings to be inserted before and after the
15319 stamp.
15320 The command returns the inserted time stamp."
15321 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
15322 stamp)
15323 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
15324 (insert-before-markers (or pre ""))
15325 (when (listp extra)
15326 (setq extra (car extra))
15327 (if (and (stringp extra)
15328 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
15329 (setq extra (format "-%02d:%02d"
15330 (string-to-number (match-string 1 extra))
15331 (string-to-number (match-string 2 extra))))
15332 (setq extra nil)))
15333 (when extra
15334 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
15335 (insert-before-markers (setq stamp (format-time-string fmt time)))
15336 (insert-before-markers (or post ""))
15337 (setq org-last-inserted-timestamp stamp)))
15339 (defun org-toggle-time-stamp-overlays ()
15340 "Toggle the use of custom time stamp formats."
15341 (interactive)
15342 (setq org-display-custom-times (not org-display-custom-times))
15343 (unless org-display-custom-times
15344 (let ((p (point-min)) (bmp (buffer-modified-p)))
15345 (while (setq p (next-single-property-change p 'display))
15346 (if (and (get-text-property p 'display)
15347 (eq (get-text-property p 'face) 'org-date))
15348 (remove-text-properties
15349 p (setq p (next-single-property-change p 'display))
15350 '(display t))))
15351 (set-buffer-modified-p bmp)))
15352 (if (featurep 'xemacs)
15353 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
15354 (org-restart-font-lock)
15355 (setq org-table-may-need-update t)
15356 (if org-display-custom-times
15357 (message "Time stamps are overlayed with custom format")
15358 (message "Time stamp overlays removed")))
15360 (defun org-display-custom-time (beg end)
15361 "Overlay modified time stamp format over timestamp between BEG and END."
15362 (let* ((ts (buffer-substring beg end))
15363 t1 w1 with-hm tf time str w2 (off 0))
15364 (save-match-data
15365 (setq t1 (org-parse-time-string ts t))
15366 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)?\\'" ts)
15367 (setq off (- (match-end 0) (match-beginning 0)))))
15368 (setq end (- end off))
15369 (setq w1 (- end beg)
15370 with-hm (and (nth 1 t1) (nth 2 t1))
15371 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
15372 time (org-fix-decoded-time t1)
15373 str (org-add-props
15374 (format-time-string
15375 (substring tf 1 -1) (apply 'encode-time time))
15376 nil 'mouse-face 'highlight)
15377 w2 (length str))
15378 (if (not (= w2 w1))
15379 (add-text-properties (1+ beg) (+ 2 beg)
15380 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
15381 (if (featurep 'xemacs)
15382 (progn
15383 (put-text-property beg end 'invisible t)
15384 (put-text-property beg end 'end-glyph (make-glyph str)))
15385 (put-text-property beg end 'display str))))
15387 (defun org-translate-time (string)
15388 "Translate all timestamps in STRING to custom format.
15389 But do this only if the variable `org-display-custom-times' is set."
15390 (when org-display-custom-times
15391 (save-match-data
15392 (let* ((start 0)
15393 (re org-ts-regexp-both)
15394 t1 with-hm inactive tf time str beg end)
15395 (while (setq start (string-match re string start))
15396 (setq beg (match-beginning 0)
15397 end (match-end 0)
15398 t1 (save-match-data
15399 (org-parse-time-string (substring string beg end) t))
15400 with-hm (and (nth 1 t1) (nth 2 t1))
15401 inactive (equal (substring string beg (1+ beg)) "[")
15402 tf (funcall (if with-hm 'cdr 'car)
15403 org-time-stamp-custom-formats)
15404 time (org-fix-decoded-time t1)
15405 str (format-time-string
15406 (concat
15407 (if inactive "[" "<") (substring tf 1 -1)
15408 (if inactive "]" ">"))
15409 (apply 'encode-time time))
15410 string (replace-match str t t string)
15411 start (+ start (length str)))))))
15412 string)
15414 (defun org-fix-decoded-time (time)
15415 "Set 0 instead of nil for the first 6 elements of time.
15416 Don't touch the rest."
15417 (let ((n 0))
15418 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
15420 (defun org-days-to-time (timestamp-string)
15421 "Difference between TIMESTAMP-STRING and now in days."
15422 (- (time-to-days (org-time-string-to-time timestamp-string))
15423 (time-to-days (current-time))))
15425 (defun org-deadline-close (timestamp-string &optional ndays)
15426 "Is the time in TIMESTAMP-STRING close to the current date?"
15427 (setq ndays (or ndays (org-get-wdays timestamp-string)))
15428 (and (< (org-days-to-time timestamp-string) ndays)
15429 (not (org-entry-is-done-p))))
15431 (defun org-get-wdays (ts)
15432 "Get the deadline lead time appropriate for timestring TS."
15433 (cond
15434 ((<= org-deadline-warning-days 0)
15435 ;; 0 or negative, enforce this value no matter what
15436 (- org-deadline-warning-days))
15437 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\| \\)" ts)
15438 ;; lead time is specified.
15439 (floor (* (string-to-number (match-string 1 ts))
15440 (cdr (assoc (match-string 2 ts)
15441 '(("d" . 1) ("w" . 7)
15442 ("m" . 30.4) ("y" . 365.25)))))))
15443 ;; go for the default.
15444 (t org-deadline-warning-days)))
15446 (defun org-calendar-select-mouse (ev)
15447 "Return to `org-read-date' with the date currently selected.
15448 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15449 (interactive "e")
15450 (mouse-set-point ev)
15451 (when (calendar-cursor-to-date)
15452 (let* ((date (calendar-cursor-to-date))
15453 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15454 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15455 (if (active-minibuffer-window) (exit-minibuffer))))
15457 (defun org-check-deadlines (ndays)
15458 "Check if there are any deadlines due or past due.
15459 A deadline is considered due if it happens within `org-deadline-warning-days'
15460 days from today's date. If the deadline appears in an entry marked DONE,
15461 it is not shown. The prefix arg NDAYS can be used to test that many
15462 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
15463 (interactive "P")
15464 (let* ((org-warn-days
15465 (cond
15466 ((equal ndays '(4)) 100000)
15467 (ndays (prefix-numeric-value ndays))
15468 (t (abs org-deadline-warning-days))))
15469 (case-fold-search nil)
15470 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
15471 (callback
15472 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
15474 (message "%d deadlines past-due or due within %d days"
15475 (org-occur regexp nil callback)
15476 org-warn-days)))
15478 (defun org-check-before-date (date)
15479 "Check if there are deadlines or scheduled entries before DATE."
15480 (interactive (list (org-read-date)))
15481 (let ((case-fold-search nil)
15482 (regexp (concat "\\<\\(" org-deadline-string
15483 "\\|" org-scheduled-string
15484 "\\) *<\\([^>]+\\)>"))
15485 (callback
15486 (lambda () (time-less-p
15487 (org-time-string-to-time (match-string 2))
15488 (org-time-string-to-time date)))))
15489 (message "%d entries before %s"
15490 (org-occur regexp nil callback) date)))
15492 (defun org-check-after-date (date)
15493 "Check if there are deadlines or scheduled entries after DATE."
15494 (interactive (list (org-read-date)))
15495 (let ((case-fold-search nil)
15496 (regexp (concat "\\<\\(" org-deadline-string
15497 "\\|" org-scheduled-string
15498 "\\) *<\\([^>]+\\)>"))
15499 (callback
15500 (lambda () (not
15501 (time-less-p
15502 (org-time-string-to-time (match-string 2))
15503 (org-time-string-to-time date))))))
15504 (message "%d entries after %s"
15505 (org-occur regexp nil callback) date)))
15507 (defun org-evaluate-time-range (&optional to-buffer)
15508 "Evaluate a time range by computing the difference between start and end.
15509 Normally the result is just printed in the echo area, but with prefix arg
15510 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
15511 If the time range is actually in a table, the result is inserted into the
15512 next column.
15513 For time difference computation, a year is assumed to be exactly 365
15514 days in order to avoid rounding problems."
15515 (interactive "P")
15517 (org-clock-update-time-maybe)
15518 (save-excursion
15519 (unless (org-at-date-range-p t)
15520 (goto-char (point-at-bol))
15521 (re-search-forward org-tr-regexp-both (point-at-eol) t))
15522 (if (not (org-at-date-range-p t))
15523 (error "Not at a time-stamp range, and none found in current line")))
15524 (let* ((ts1 (match-string 1))
15525 (ts2 (match-string 2))
15526 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
15527 (match-end (match-end 0))
15528 (time1 (org-time-string-to-time ts1))
15529 (time2 (org-time-string-to-time ts2))
15530 (t1 (org-float-time time1))
15531 (t2 (org-float-time time2))
15532 (diff (abs (- t2 t1)))
15533 (negative (< (- t2 t1) 0))
15534 ;; (ys (floor (* 365 24 60 60)))
15535 (ds (* 24 60 60))
15536 (hs (* 60 60))
15537 (fy "%dy %dd %02d:%02d")
15538 (fy1 "%dy %dd")
15539 (fd "%dd %02d:%02d")
15540 (fd1 "%dd")
15541 (fh "%02d:%02d")
15542 y d h m align)
15543 (if havetime
15544 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
15546 d (floor (/ diff ds)) diff (mod diff ds)
15547 h (floor (/ diff hs)) diff (mod diff hs)
15548 m (floor (/ diff 60)))
15549 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
15551 d (floor (+ (/ diff ds) 0.5))
15552 h 0 m 0))
15553 (if (not to-buffer)
15554 (message "%s" (org-make-tdiff-string y d h m))
15555 (if (org-at-table-p)
15556 (progn
15557 (goto-char match-end)
15558 (setq align t)
15559 (and (looking-at " *|") (goto-char (match-end 0))))
15560 (goto-char match-end))
15561 (if (looking-at
15562 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
15563 (replace-match ""))
15564 (if negative (insert " -"))
15565 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
15566 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
15567 (insert " " (format fh h m))))
15568 (if align (org-table-align))
15569 (message "Time difference inserted")))))
15571 (defun org-make-tdiff-string (y d h m)
15572 (let ((fmt "")
15573 (l nil))
15574 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
15575 l (push y l)))
15576 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
15577 l (push d l)))
15578 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
15579 l (push h l)))
15580 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
15581 l (push m l)))
15582 (apply 'format fmt (nreverse l))))
15584 (defun org-time-string-to-time (s &optional buffer pos)
15585 (condition-case errdata
15586 (apply 'encode-time (org-parse-time-string s))
15587 (error (error "Bad timestamp `%s'%s\nError was: %s"
15588 s (if (not (and buffer pos))
15590 (format " at %d in buffer `%s'" pos buffer))
15591 (cdr errdata)))))
15593 (defun org-time-string-to-seconds (s)
15594 (org-float-time (org-time-string-to-time s)))
15596 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
15597 "Convert a time stamp to an absolute day number.
15598 If there is a specifier for a cyclic time stamp, get the closest date to
15599 DAYNR.
15600 PREFER and SHOW-ALL are passed through to `org-closest-date'.
15601 The variable date is bound by the calendar when this is called."
15602 (cond
15603 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
15604 (if (org-diary-sexp-entry (match-string 1 s) "" date)
15605 daynr
15606 (+ daynr 1000)))
15607 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
15608 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
15609 (time-to-days (current-time))) (match-string 0 s)
15610 prefer show-all))
15611 (t (time-to-days
15612 (condition-case errdata
15613 (apply 'encode-time (org-parse-time-string s))
15614 (error (error "Bad timestamp `%s'%s\nError was: %s"
15615 s (if (not (and buffer pos))
15617 (format " at %d in buffer `%s'" pos buffer))
15618 (cdr errdata))))))))
15620 (defun org-days-to-iso-week (days)
15621 "Return the iso week number."
15622 (require 'cal-iso)
15623 (car (calendar-iso-from-absolute days)))
15625 (defun org-small-year-to-year (year)
15626 "Convert 2-digit years into 4-digit years.
15627 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
15628 The year 2000 cannot be abbreviated. Any year larger than 99
15629 is returned unchanged."
15630 (if (< year 38)
15631 (setq year (+ 2000 year))
15632 (if (< year 100)
15633 (setq year (+ 1900 year))))
15634 year)
15636 (defun org-time-from-absolute (d)
15637 "Return the time corresponding to date D.
15638 D may be an absolute day number, or a calendar-type list (month day year)."
15639 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
15640 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
15642 (defun org-calendar-holiday ()
15643 "List of holidays, for Diary display in Org-mode."
15644 (require 'holidays)
15645 (let ((hl (funcall
15646 (if (fboundp 'calendar-check-holidays)
15647 'calendar-check-holidays 'check-calendar-holidays) date)))
15648 (if hl (mapconcat 'identity hl "; "))))
15650 (defun org-diary-sexp-entry (sexp entry date)
15651 "Process a SEXP diary ENTRY for DATE."
15652 (require 'diary-lib)
15653 (let ((result (if calendar-debug-sexp
15654 (let ((stack-trace-on-error t))
15655 (eval (car (read-from-string sexp))))
15656 (condition-case nil
15657 (eval (car (read-from-string sexp)))
15658 (error
15659 (beep)
15660 (message "Bad sexp at line %d in %s: %s"
15661 (org-current-line)
15662 (buffer-file-name) sexp)
15663 (sleep-for 2))))))
15664 (cond ((stringp result) (split-string result "; "))
15665 ((and (consp result)
15666 (not (consp (cdr result)))
15667 (stringp (cdr result))) (cdr result))
15668 ((and (consp result)
15669 (stringp (car result))) result)
15670 (result entry)
15671 (t nil))))
15673 (defun org-diary-to-ical-string (frombuf)
15674 "Get iCalendar entries from diary entries in buffer FROMBUF.
15675 This uses the icalendar.el library."
15676 (let* ((tmpdir (if (featurep 'xemacs)
15677 (temp-directory)
15678 temporary-file-directory))
15679 (tmpfile (make-temp-name
15680 (expand-file-name "orgics" tmpdir)))
15681 buf rtn b e)
15682 (with-current-buffer frombuf
15683 (icalendar-export-region (point-min) (point-max) tmpfile)
15684 (setq buf (find-buffer-visiting tmpfile))
15685 (set-buffer buf)
15686 (goto-char (point-min))
15687 (if (re-search-forward "^BEGIN:VEVENT" nil t)
15688 (setq b (match-beginning 0)))
15689 (goto-char (point-max))
15690 (if (re-search-backward "^END:VEVENT" nil t)
15691 (setq e (match-end 0)))
15692 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
15693 (kill-buffer buf)
15694 (delete-file tmpfile)
15695 rtn))
15697 (defun org-closest-date (start current change prefer show-all)
15698 "Find the date closest to CURRENT that is consistent with START and CHANGE.
15699 When PREFER is `past', return a date that is either CURRENT or past.
15700 When PREFER is `future', return a date that is either CURRENT or future.
15701 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
15702 ;; Make the proper lists from the dates
15703 (catch 'exit
15704 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
15705 dn dw sday cday n1 n2 n0
15706 d m y y1 y2 date1 date2 nmonths nm ny m2)
15708 (setq start (org-date-to-gregorian start)
15709 current (org-date-to-gregorian
15710 (if show-all
15711 current
15712 (time-to-days (current-time))))
15713 sday (calendar-absolute-from-gregorian start)
15714 cday (calendar-absolute-from-gregorian current))
15716 (if (<= cday sday) (throw 'exit sday))
15718 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
15719 (setq dn (string-to-number (match-string 1 change))
15720 dw (cdr (assoc (match-string 2 change) a1)))
15721 (error "Invalid change specifier: %s" change))
15722 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
15723 (cond
15724 ((eq dw 'day)
15725 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
15726 n2 (+ n1 dn)))
15727 ((eq dw 'year)
15728 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
15729 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
15730 (setq date1 (list m d y1)
15731 n1 (calendar-absolute-from-gregorian date1)
15732 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
15733 n2 (calendar-absolute-from-gregorian date2)))
15734 ((eq dw 'month)
15735 ;; approx number of month between the two dates
15736 (setq nmonths (floor (/ (- cday sday) 30.436875)))
15737 ;; How often does dn fit in there?
15738 (setq d (nth 1 start) m (car start) y (nth 2 start)
15739 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
15740 m (+ m nm)
15741 ny (floor (/ m 12))
15742 y (+ y ny)
15743 m (- m (* ny 12)))
15744 (while (> m 12) (setq m (- m 12) y (1+ y)))
15745 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
15746 (setq m2 (+ m dn) y2 y)
15747 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
15748 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
15749 (while (<= n2 cday)
15750 (setq n1 n2 m m2 y y2)
15751 (setq m2 (+ m dn) y2 y)
15752 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
15753 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
15754 ;; Make sure n1 is the earlier date
15755 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
15756 (if show-all
15757 (cond
15758 ((eq prefer 'past) (if (= cday n2) n2 n1))
15759 ((eq prefer 'future) (if (= cday n1) n1 n2))
15760 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
15761 (cond
15762 ((eq prefer 'past) (if (= cday n2) n2 n1))
15763 ((eq prefer 'future) (if (= cday n1) n1 n2))
15764 (t (if (= cday n1) n1 n2)))))))
15766 (defun org-date-to-gregorian (date)
15767 "Turn any specification of DATE into a Gregorian date for the calendar."
15768 (cond ((integerp date) (calendar-gregorian-from-absolute date))
15769 ((and (listp date) (= (length date) 3)) date)
15770 ((stringp date)
15771 (setq date (org-parse-time-string date))
15772 (list (nth 4 date) (nth 3 date) (nth 5 date)))
15773 ((listp date)
15774 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
15776 (defun org-parse-time-string (s &optional nodefault)
15777 "Parse the standard Org-mode time string.
15778 This should be a lot faster than the normal `parse-time-string'.
15779 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
15780 hour and minute fields will be nil if not given."
15781 (if (string-match org-ts-regexp0 s)
15782 (list 0
15783 (if (or (match-beginning 8) (not nodefault))
15784 (string-to-number (or (match-string 8 s) "0")))
15785 (if (or (match-beginning 7) (not nodefault))
15786 (string-to-number (or (match-string 7 s) "0")))
15787 (string-to-number (match-string 4 s))
15788 (string-to-number (match-string 3 s))
15789 (string-to-number (match-string 2 s))
15790 nil nil nil)
15791 (error "Not a standard Org-mode time string: %s" s)))
15793 (defun org-timestamp-up (&optional arg)
15794 "Increase the date item at the cursor by one.
15795 If the cursor is on the year, change the year. If it is on the month,
15796 the day or the time, change that.
15797 With prefix ARG, change by that many units."
15798 (interactive "p")
15799 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
15801 (defun org-timestamp-down (&optional arg)
15802 "Decrease the date item at the cursor by one.
15803 If the cursor is on the year, change the year. If it is on the month,
15804 the day or the time, change that.
15805 With prefix ARG, change by that many units."
15806 (interactive "p")
15807 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
15809 (defun org-timestamp-up-day (&optional arg)
15810 "Increase the date in the time stamp by one day.
15811 With prefix ARG, change that many days."
15812 (interactive "p")
15813 (if (and (not (org-at-timestamp-p t))
15814 (org-on-heading-p))
15815 (org-todo 'up)
15816 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
15818 (defun org-timestamp-down-day (&optional arg)
15819 "Decrease the date in the time stamp by one day.
15820 With prefix ARG, change that many days."
15821 (interactive "p")
15822 (if (and (not (org-at-timestamp-p t))
15823 (org-on-heading-p))
15824 (org-todo 'down)
15825 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
15827 (defun org-at-timestamp-p (&optional inactive-ok)
15828 "Determine if the cursor is in or at a timestamp."
15829 (interactive)
15830 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
15831 (pos (point))
15832 (ans (or (looking-at tsr)
15833 (save-excursion
15834 (skip-chars-backward "^[<\n\r\t")
15835 (if (> (point) (point-min)) (backward-char 1))
15836 (and (looking-at tsr)
15837 (> (- (match-end 0) pos) -1))))))
15838 (and ans
15839 (boundp 'org-ts-what)
15840 (setq org-ts-what
15841 (cond
15842 ((= pos (match-beginning 0)) 'bracket)
15843 ;; Point is considered to be "on the bracket" whether
15844 ;; it's really on it or right after it.
15845 ((or (= pos (1- (match-end 0)))
15846 (= pos (match-end 0))) 'bracket)
15847 ((org-pos-in-match-range pos 2) 'year)
15848 ((org-pos-in-match-range pos 3) 'month)
15849 ((org-pos-in-match-range pos 7) 'hour)
15850 ((org-pos-in-match-range pos 8) 'minute)
15851 ((or (org-pos-in-match-range pos 4)
15852 (org-pos-in-match-range pos 5)) 'day)
15853 ((and (> pos (or (match-end 8) (match-end 5)))
15854 (< pos (match-end 0)))
15855 (- pos (or (match-end 8) (match-end 5))))
15856 (t 'day))))
15857 ans))
15859 (defun org-toggle-timestamp-type ()
15860 "Toggle the type (<active> or [inactive]) of a time stamp."
15861 (interactive)
15862 (when (org-at-timestamp-p t)
15863 (let ((beg (match-beginning 0)) (end (match-end 0))
15864 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
15865 (save-excursion
15866 (goto-char beg)
15867 (while (re-search-forward "[][<>]" end t)
15868 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
15869 t t)))
15870 (message "Timestamp is now %sactive"
15871 (if (equal (char-after beg) ?<) "" "in")))))
15873 (defun org-timestamp-change (n &optional what updown)
15874 "Change the date in the time stamp at point.
15875 The date will be changed by N times WHAT. WHAT can be `day', `month',
15876 `year', `minute', `second'. If WHAT is not given, the cursor position
15877 in the timestamp determines what will be changed."
15878 (let ((origin (point)) origin-cat
15879 with-hm inactive
15880 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
15881 org-ts-what
15882 extra rem
15883 ts time time0)
15884 (if (not (org-at-timestamp-p t))
15885 (error "Not at a timestamp"))
15886 (if (and (not what) (eq org-ts-what 'bracket))
15887 (org-toggle-timestamp-type)
15888 ;; Point isn't on brackets. Remember the part of the time-stamp
15889 ;; the point was in. Indeed, size of time-stamps may change,
15890 ;; but point must be kept in the same category nonetheless.
15891 (setq origin-cat org-ts-what)
15892 (if (and (not what) (not (eq org-ts-what 'day))
15893 org-display-custom-times
15894 (get-text-property (point) 'display)
15895 (not (get-text-property (1- (point)) 'display)))
15896 (setq org-ts-what 'day))
15897 (setq org-ts-what (or what org-ts-what)
15898 inactive (= (char-after (match-beginning 0)) ?\[)
15899 ts (match-string 0))
15900 (replace-match "")
15901 (if (string-match
15902 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)*\\)[]>]"
15904 (setq extra (match-string 1 ts)))
15905 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
15906 (setq with-hm t))
15907 (setq time0 (org-parse-time-string ts))
15908 (when (and updown
15909 (eq org-ts-what 'minute)
15910 (not current-prefix-arg))
15911 ;; This looks like s-up and s-down. Change by one rounding step.
15912 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
15913 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
15914 (setcar (cdr time0) (+ (nth 1 time0)
15915 (if (> n 0) (- rem) (- dm rem))))))
15916 (setq time
15917 (encode-time (or (car time0) 0)
15918 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
15919 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
15920 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
15921 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
15922 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
15923 (nthcdr 6 time0)))
15924 (when (and (member org-ts-what '(hour minute))
15925 extra
15926 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
15927 (setq extra (org-modify-ts-extra
15928 extra
15929 (if (eq org-ts-what 'hour) 2 5)
15930 n dm)))
15931 (when (integerp org-ts-what)
15932 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
15933 (if (eq what 'calendar)
15934 (let ((cal-date (org-get-date-from-calendar)))
15935 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
15936 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
15937 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
15938 (setcar time0 (or (car time0) 0))
15939 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
15940 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
15941 (setq time (apply 'encode-time time0))))
15942 ;; Insert the new time-stamp, and ensure point stays in the same
15943 ;; category as before (i.e. not after the last position in that
15944 ;; category).
15945 (let ((pos (point)))
15946 ;; Stay before inserted string. `save-excursion' is of no use.
15947 (setq org-last-changed-timestamp
15948 (org-insert-time-stamp time with-hm inactive nil nil extra))
15949 (goto-char pos))
15950 (save-match-data
15951 (looking-at org-ts-regexp3)
15952 (goto-char (cond
15953 ;; `day' category ends before `hour' if any, or at
15954 ;; the end of the day name.
15955 ((eq origin-cat 'day)
15956 (min (or (match-beginning 7) (1- (match-end 5))) origin))
15957 ((eq origin-cat 'hour) (min (match-end 7) origin))
15958 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
15959 ((integerp origin-cat) (min (1- (match-end 0)) origin))
15960 ;; `year' and `month' have both fixed size: point
15961 ;; couldn't have moved into another part.
15962 (t origin))))
15963 ;; Update clock if on a CLOCK line.
15964 (org-clock-update-time-maybe)
15965 ;; Try to recenter the calendar window, if any.
15966 (if (and org-calendar-follow-timestamp-change
15967 (get-buffer-window "*Calendar*" t)
15968 (memq org-ts-what '(day month year)))
15969 (org-recenter-calendar (time-to-days time))))))
15971 (defun org-modify-ts-extra (s pos n dm)
15972 "Change the different parts of the lead-time and repeat fields in timestamp."
15973 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
15974 ng h m new rem)
15975 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
15976 (cond
15977 ((or (org-pos-in-match-range pos 2)
15978 (org-pos-in-match-range pos 3))
15979 (setq m (string-to-number (match-string 3 s))
15980 h (string-to-number (match-string 2 s)))
15981 (if (org-pos-in-match-range pos 2)
15982 (setq h (+ h n))
15983 (setq n (* dm (org-no-warnings (signum n))))
15984 (when (not (= 0 (setq rem (% m dm))))
15985 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
15986 (setq m (+ m n)))
15987 (if (< m 0) (setq m (+ m 60) h (1- h)))
15988 (if (> m 59) (setq m (- m 60) h (1+ h)))
15989 (setq h (min 24 (max 0 h)))
15990 (setq ng 1 new (format "-%02d:%02d" h m)))
15991 ((org-pos-in-match-range pos 6)
15992 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
15993 ((org-pos-in-match-range pos 5)
15994 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
15996 ((org-pos-in-match-range pos 9)
15997 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
15998 ((org-pos-in-match-range pos 8)
15999 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
16001 (when ng
16002 (setq s (concat
16003 (substring s 0 (match-beginning ng))
16005 (substring s (match-end ng))))))
16008 (defun org-recenter-calendar (date)
16009 "If the calendar is visible, recenter it to DATE."
16010 (let* ((win (selected-window))
16011 (cwin (get-buffer-window "*Calendar*" t))
16012 (calendar-move-hook nil))
16013 (when cwin
16014 (select-window cwin)
16015 (calendar-goto-date (if (listp date) date
16016 (calendar-gregorian-from-absolute date)))
16017 (select-window win))))
16019 (defun org-goto-calendar (&optional arg)
16020 "Go to the Emacs calendar at the current date.
16021 If there is a time stamp in the current line, go to that date.
16022 A prefix ARG can be used to force the current date."
16023 (interactive "P")
16024 (let ((tsr org-ts-regexp) diff
16025 (calendar-move-hook nil)
16026 (calendar-view-holidays-initially-flag nil)
16027 (calendar-view-diary-initially-flag nil))
16028 (if (or (org-at-timestamp-p)
16029 (save-excursion
16030 (beginning-of-line 1)
16031 (looking-at (concat ".*" tsr))))
16032 (let ((d1 (time-to-days (current-time)))
16033 (d2 (time-to-days
16034 (org-time-string-to-time (match-string 1)))))
16035 (setq diff (- d2 d1))))
16036 (calendar)
16037 (calendar-goto-today)
16038 (if (and diff (not arg)) (calendar-forward-day diff))))
16040 (defun org-get-date-from-calendar ()
16041 "Return a list (month day year) of date at point in calendar."
16042 (with-current-buffer "*Calendar*"
16043 (save-match-data
16044 (calendar-cursor-to-date))))
16046 (defun org-date-from-calendar ()
16047 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
16048 If there is already a time stamp at the cursor position, update it."
16049 (interactive)
16050 (if (org-at-timestamp-p t)
16051 (org-timestamp-change 0 'calendar)
16052 (let ((cal-date (org-get-date-from-calendar)))
16053 (org-insert-time-stamp
16054 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
16056 (defun org-minutes-to-hh:mm-string (m)
16057 "Compute H:MM from a number of minutes."
16058 (let ((h (/ m 60)))
16059 (setq m (- m (* 60 h)))
16060 (format org-time-clocksum-format h m)))
16062 (defun org-hh:mm-string-to-minutes (s)
16063 "Convert a string H:MM to a number of minutes.
16064 If the string is just a number, interpret it as minutes.
16065 In fact, the first hh:mm or number in the string will be taken,
16066 there can be extra stuff in the string.
16067 If no number is found, the return value is 0."
16068 (cond
16069 ((integerp s) s)
16070 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
16071 (+ (* (string-to-number (match-string 1 s)) 60)
16072 (string-to-number (match-string 2 s))))
16073 ((string-match "\\([0-9]+\\)" s)
16074 (string-to-number (match-string 1 s)))
16075 (t 0)))
16077 (defcustom org-effort-durations
16078 `(("h" . 60)
16079 ("d" . ,(* 60 8))
16080 ("w" . ,(* 60 8 5))
16081 ("m" . ,(* 60 8 5 4))
16082 ("y" . ,(* 60 8 5 40)))
16083 "Conversion factor to minutes for an effort modifier.
16085 Each entry has the form (MODIFIER . MINUTES).
16087 In an effort string, a number followed by MODIFIER is multiplied
16088 by the specified number of MINUTES to obtain an effort in
16089 minutes.
16091 For example, if the value of this variable is ((\"hours\" . 60)), then an
16092 effort string \"2hours\" is equivalent to 120 minutes."
16093 :group 'org-agenda
16094 :type '(alist :key-type (string :tag "Modifier")
16095 :value-type (number :tag "Minutes")))
16097 (defun org-duration-string-to-minutes (s)
16098 "Convert a duration string S to minutes.
16100 A bare number is interpreted as minutes, modifiers can be set by
16101 customizing `org-effort-durations' (which see).
16103 Entries containing a colon are interpreted as H:MM by
16104 `org-hh:mm-string-to-minutes'."
16105 (let ((result 0)
16106 (re (concat "\\([0-9]+\\) *\\("
16107 (regexp-opt (mapcar 'car org-effort-durations))
16108 "\\)")))
16109 (while (string-match re s)
16110 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
16111 (string-to-number (match-string 1 s))))
16112 (setq s (replace-match "" nil t s)))
16113 (incf result (org-hh:mm-string-to-minutes s))
16114 result))
16116 ;;;; Files
16118 (defun org-save-all-org-buffers ()
16119 "Save all Org-mode buffers without user confirmation."
16120 (interactive)
16121 (message "Saving all Org-mode buffers...")
16122 (save-some-buffers t (lambda () (eq major-mode 'org-mode)))
16123 (when (featurep 'org-id) (org-id-locations-save))
16124 (message "Saving all Org-mode buffers... done"))
16126 (defun org-revert-all-org-buffers ()
16127 "Revert all Org-mode buffers.
16128 Prompt for confirmation when there are unsaved changes.
16129 Be sure you know what you are doing before letting this function
16130 overwrite your changes.
16132 This function is useful in a setup where one tracks org files
16133 with a version control system, to revert on one machine after pulling
16134 changes from another. I believe the procedure must be like this:
16136 1. M-x org-save-all-org-buffers
16137 2. Pull changes from the other machine, resolve conflicts
16138 3. M-x org-revert-all-org-buffers"
16139 (interactive)
16140 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
16141 (error "Abort"))
16142 (save-excursion
16143 (save-window-excursion
16144 (mapc
16145 (lambda (b)
16146 (when (and (with-current-buffer b (eq major-mode 'org-mode))
16147 (with-current-buffer b buffer-file-name))
16148 (org-pop-to-buffer-same-window b)
16149 (revert-buffer t 'no-confirm)))
16150 (buffer-list))
16151 (when (and (featurep 'org-id) org-id-track-globally)
16152 (org-id-locations-load)))))
16154 ;;;; Agenda files
16156 ;;;###autoload
16157 (defun org-switchb (&optional arg)
16158 "Switch between Org buffers.
16159 With one prefix argument, restrict available buffers to files.
16160 With two prefix arguments, restrict available buffers to agenda files.
16162 Defaults to `iswitchb' for buffer name completion.
16163 Set `org-completion-use-ido' to make it use ido instead."
16164 (interactive "P")
16165 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
16166 ((equal arg '(16)) (org-buffer-list 'agenda))
16167 (t (org-buffer-list))))
16168 (org-completion-use-iswitchb org-completion-use-iswitchb)
16169 (org-completion-use-ido org-completion-use-ido))
16170 (unless (or org-completion-use-ido org-completion-use-iswitchb)
16171 (setq org-completion-use-iswitchb t))
16172 (org-pop-to-buffer-same-window
16173 (org-icompleting-read "Org buffer: "
16174 (mapcar 'list (mapcar 'buffer-name blist))
16175 nil t))))
16177 ;;; Define some older names previously used for this functionality
16178 ;;;###autoload
16179 (defalias 'org-ido-switchb 'org-switchb)
16180 ;;;###autoload
16181 (defalias 'org-iswitchb 'org-switchb)
16183 (defun org-buffer-list (&optional predicate exclude-tmp)
16184 "Return a list of Org buffers.
16185 PREDICATE can be `export', `files' or `agenda'.
16187 export restrict the list to Export buffers.
16188 files restrict the list to buffers visiting Org files.
16189 agenda restrict the list to buffers visiting agenda files.
16191 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
16192 (let* ((bfn nil)
16193 (agenda-files (and (eq predicate 'agenda)
16194 (mapcar 'file-truename (org-agenda-files t))))
16195 (filter
16196 (cond
16197 ((eq predicate 'files)
16198 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
16199 ((eq predicate 'export)
16200 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
16201 ((eq predicate 'agenda)
16202 (lambda (b)
16203 (with-current-buffer b
16204 (and (eq major-mode 'org-mode)
16205 (setq bfn (buffer-file-name b))
16206 (member (file-truename bfn) agenda-files)))))
16207 (t (lambda (b) (with-current-buffer b
16208 (or (eq major-mode 'org-mode)
16209 (string-match "\*Org .*Export"
16210 (buffer-name b)))))))))
16211 (delq nil
16212 (mapcar
16213 (lambda(b)
16214 (if (and (funcall filter b)
16215 (or (not exclude-tmp)
16216 (not (string-match "tmp" (buffer-name b)))))
16218 nil))
16219 (buffer-list)))))
16221 (defun org-agenda-files (&optional unrestricted archives)
16222 "Get the list of agenda files.
16223 Optional UNRESTRICTED means return the full list even if a restriction
16224 is currently in place.
16225 When ARCHIVES is t, include all archive files that are really being
16226 used by the agenda files. If ARCHIVE is `ifmode', do this only if
16227 `org-agenda-archives-mode' is t."
16228 (let ((files
16229 (cond
16230 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
16231 ((stringp org-agenda-files) (org-read-agenda-file-list))
16232 ((listp org-agenda-files) org-agenda-files)
16233 (t (error "Invalid value of `org-agenda-files'")))))
16234 (setq files (apply 'append
16235 (mapcar (lambda (f)
16236 (if (file-directory-p f)
16237 (directory-files
16238 f t org-agenda-file-regexp)
16239 (list f)))
16240 files)))
16241 (when org-agenda-skip-unavailable-files
16242 (setq files (delq nil
16243 (mapcar (function
16244 (lambda (file)
16245 (and (file-readable-p file) file)))
16246 files))))
16247 (when (or (eq archives t)
16248 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
16249 (setq files (org-add-archive-files files)))
16250 files))
16252 (defun org-agenda-file-p (&optional file)
16253 "Return non-nil, if FILE is an agenda file.
16254 If FILE is omitted, use the file associated with the current
16255 buffer."
16256 (member (or file (buffer-file-name))
16257 (org-agenda-files t)))
16259 (defun org-edit-agenda-file-list ()
16260 "Edit the list of agenda files.
16261 Depending on setup, this either uses customize to edit the variable
16262 `org-agenda-files', or it visits the file that is holding the list. In the
16263 latter case, the buffer is set up in a way that saving it automatically kills
16264 the buffer and restores the previous window configuration."
16265 (interactive)
16266 (if (stringp org-agenda-files)
16267 (let ((cw (current-window-configuration)))
16268 (find-file org-agenda-files)
16269 (org-set-local 'org-window-configuration cw)
16270 (org-add-hook 'after-save-hook
16271 (lambda ()
16272 (set-window-configuration
16273 (prog1 org-window-configuration
16274 (kill-buffer (current-buffer))))
16275 (org-install-agenda-files-menu)
16276 (message "New agenda file list installed"))
16277 nil 'local)
16278 (message "%s" (substitute-command-keys
16279 "Edit list and finish with \\[save-buffer]")))
16280 (customize-variable 'org-agenda-files)))
16282 (defun org-store-new-agenda-file-list (list)
16283 "Set new value for the agenda file list and save it correctly."
16284 (if (stringp org-agenda-files)
16285 (let ((fe (org-read-agenda-file-list t)) b u)
16286 (while (setq b (find-buffer-visiting org-agenda-files))
16287 (kill-buffer b))
16288 (with-temp-file org-agenda-files
16289 (insert
16290 (mapconcat
16291 (lambda (f) ;; Keep un-expanded entries.
16292 (if (setq u (assoc f fe))
16293 (cdr u)
16295 list "\n")
16296 "\n")))
16297 (let ((org-mode-hook nil) (org-inhibit-startup t)
16298 (org-insert-mode-line-in-empty-file nil))
16299 (setq org-agenda-files list)
16300 (customize-save-variable 'org-agenda-files org-agenda-files))))
16302 (defun org-read-agenda-file-list (&optional pair-with-expansion)
16303 "Read the list of agenda files from a file.
16304 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
16305 filenames, used by `org-store-new-agenda-file-list' to write back
16306 un-expanded file names."
16307 (when (file-directory-p org-agenda-files)
16308 (error "`org-agenda-files' cannot be a single directory"))
16309 (when (stringp org-agenda-files)
16310 (with-temp-buffer
16311 (insert-file-contents org-agenda-files)
16312 (mapcar
16313 (lambda (f)
16314 (let ((e (expand-file-name (substitute-in-file-name f)
16315 org-directory)))
16316 (if pair-with-expansion
16317 (cons e f)
16318 e)))
16319 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
16321 ;;;###autoload
16322 (defun org-cycle-agenda-files ()
16323 "Cycle through the files in `org-agenda-files'.
16324 If the current buffer visits an agenda file, find the next one in the list.
16325 If the current buffer does not, find the first agenda file."
16326 (interactive)
16327 (let* ((fs (org-agenda-files t))
16328 (files (append fs (list (car fs))))
16329 (tcf (if buffer-file-name (file-truename buffer-file-name)))
16330 file)
16331 (unless files (error "No agenda files"))
16332 (catch 'exit
16333 (while (setq file (pop files))
16334 (if (equal (file-truename file) tcf)
16335 (when (car files)
16336 (find-file (car files))
16337 (throw 'exit t))))
16338 (find-file (car fs)))
16339 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
16341 (defun org-agenda-file-to-front (&optional to-end)
16342 "Move/add the current file to the top of the agenda file list.
16343 If the file is not present in the list, it is added to the front. If it is
16344 present, it is moved there. With optional argument TO-END, add/move to the
16345 end of the list."
16346 (interactive "P")
16347 (let ((org-agenda-skip-unavailable-files nil)
16348 (file-alist (mapcar (lambda (x)
16349 (cons (file-truename x) x))
16350 (org-agenda-files t)))
16351 (ctf (file-truename buffer-file-name))
16352 x had)
16353 (setq x (assoc ctf file-alist) had x)
16355 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
16356 (if to-end
16357 (setq file-alist (append (delq x file-alist) (list x)))
16358 (setq file-alist (cons x (delq x file-alist))))
16359 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
16360 (org-install-agenda-files-menu)
16361 (message "File %s to %s of agenda file list"
16362 (if had "moved" "added") (if to-end "end" "front"))))
16364 (defun org-remove-file (&optional file)
16365 "Remove current file from the list of files in variable `org-agenda-files'.
16366 These are the files which are being checked for agenda entries.
16367 Optional argument FILE means use this file instead of the current."
16368 (interactive)
16369 (let* ((org-agenda-skip-unavailable-files nil)
16370 (file (or file buffer-file-name))
16371 (true-file (file-truename file))
16372 (afile (abbreviate-file-name file))
16373 (files (delq nil (mapcar
16374 (lambda (x)
16375 (if (equal true-file
16376 (file-truename x))
16377 nil x))
16378 (org-agenda-files t)))))
16379 (if (not (= (length files) (length (org-agenda-files t))))
16380 (progn
16381 (org-store-new-agenda-file-list files)
16382 (org-install-agenda-files-menu)
16383 (message "Removed file: %s" afile))
16384 (message "File was not in list: %s (not removed)" afile))))
16386 (defun org-file-menu-entry (file)
16387 (vector file (list 'find-file file) t))
16389 (defun org-check-agenda-file (file)
16390 "Make sure FILE exists. If not, ask user what to do."
16391 (when (not (file-exists-p file))
16392 (message "non-existent agenda file %s. [R]emove from list or [A]bort?"
16393 (abbreviate-file-name file))
16394 (let ((r (downcase (read-char-exclusive))))
16395 (cond
16396 ((equal r ?r)
16397 (org-remove-file file)
16398 (throw 'nextfile t))
16399 (t (error "Abort"))))))
16401 (defun org-get-agenda-file-buffer (file)
16402 "Get a buffer visiting FILE. If the buffer needs to be created, add
16403 it to the list of buffers which might be released later."
16404 (let ((buf (org-find-base-buffer-visiting file)))
16405 (if buf
16406 buf ; just return it
16407 ;; Make a new buffer and remember it
16408 (setq buf (find-file-noselect file))
16409 (if buf (push buf org-agenda-new-buffers))
16410 buf)))
16412 (defun org-release-buffers (blist)
16413 "Release all buffers in list, asking the user for confirmation when needed.
16414 When a buffer is unmodified, it is just killed. When modified, it is saved
16415 \(if the user agrees) and then killed."
16416 (let (buf file)
16417 (while (setq buf (pop blist))
16418 (setq file (buffer-file-name buf))
16419 (when (and (buffer-modified-p buf)
16420 file
16421 (y-or-n-p (format "Save file %s? " file)))
16422 (with-current-buffer buf (save-buffer)))
16423 (kill-buffer buf))))
16425 (defun org-prepare-agenda-buffers (files)
16426 "Create buffers for all agenda files, protect archived trees and comments."
16427 (interactive)
16428 (let ((pa '(:org-archived t))
16429 (pc '(:org-comment t))
16430 (pall '(:org-archived t :org-comment t))
16431 (inhibit-read-only t)
16432 (rea (concat ":" org-archive-tag ":"))
16433 bmp file re)
16434 (save-excursion
16435 (save-restriction
16436 (while (setq file (pop files))
16437 (catch 'nextfile
16438 (if (bufferp file)
16439 (set-buffer file)
16440 (org-check-agenda-file file)
16441 (set-buffer (org-get-agenda-file-buffer file)))
16442 (widen)
16443 (setq bmp (buffer-modified-p))
16444 (org-refresh-category-properties)
16445 (setq org-todo-keywords-for-agenda
16446 (append org-todo-keywords-for-agenda org-todo-keywords-1))
16447 (setq org-done-keywords-for-agenda
16448 (append org-done-keywords-for-agenda org-done-keywords))
16449 (setq org-todo-keyword-alist-for-agenda
16450 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
16451 (setq org-drawers-for-agenda
16452 (append org-drawers-for-agenda org-drawers))
16453 (setq org-tag-alist-for-agenda
16454 (append org-tag-alist-for-agenda org-tag-alist))
16456 (save-excursion
16457 (remove-text-properties (point-min) (point-max) pall)
16458 (when org-agenda-skip-archived-trees
16459 (goto-char (point-min))
16460 (while (re-search-forward rea nil t)
16461 (if (org-on-heading-p t)
16462 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
16463 (goto-char (point-min))
16464 (setq re (format org-heading-keyword-regexp-format
16465 org-comment-string))
16466 (while (re-search-forward re nil t)
16467 (add-text-properties
16468 (match-beginning 0) (org-end-of-subtree t) pc)))
16469 (set-buffer-modified-p bmp)))))
16470 (setq org-todo-keywords-for-agenda
16471 (org-uniquify org-todo-keywords-for-agenda))
16472 (setq org-todo-keyword-alist-for-agenda
16473 (org-uniquify org-todo-keyword-alist-for-agenda)
16474 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
16476 ;;;; Embedded LaTeX
16478 (defvar org-cdlatex-mode-map (make-sparse-keymap)
16479 "Keymap for the minor `org-cdlatex-mode'.")
16481 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
16482 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
16483 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
16484 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
16485 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
16487 (defvar org-cdlatex-texmathp-advice-is-done nil
16488 "Flag remembering if we have applied the advice to texmathp already.")
16490 (define-minor-mode org-cdlatex-mode
16491 "Toggle the minor `org-cdlatex-mode'.
16492 This mode supports entering LaTeX environment and math in LaTeX fragments
16493 in Org-mode.
16494 \\{org-cdlatex-mode-map}"
16495 nil " OCDL" nil
16496 (when org-cdlatex-mode
16497 (require 'cdlatex)
16498 (run-hooks 'cdlatex-mode-hook)
16499 (cdlatex-compute-tables))
16500 (unless org-cdlatex-texmathp-advice-is-done
16501 (setq org-cdlatex-texmathp-advice-is-done t)
16502 (defadvice texmathp (around org-math-always-on activate)
16503 "Always return t in org-mode buffers.
16504 This is because we want to insert math symbols without dollars even outside
16505 the LaTeX math segments. If Orgmode thinks that point is actually inside
16506 an embedded LaTeX fragment, let texmathp do its job.
16507 \\[org-cdlatex-mode-map]"
16508 (interactive)
16509 (let (p)
16510 (cond
16511 ((not (eq major-mode 'org-mode)) ad-do-it)
16512 ((eq this-command 'cdlatex-math-symbol)
16513 (setq ad-return-value t
16514 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
16516 (let ((p (org-inside-LaTeX-fragment-p)))
16517 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
16518 (setq ad-return-value t
16519 texmathp-why '("Org-mode embedded math" . 0))
16520 (if p ad-do-it)))))))))
16522 (defun turn-on-org-cdlatex ()
16523 "Unconditionally turn on `org-cdlatex-mode'."
16524 (org-cdlatex-mode 1))
16526 (defun org-inside-LaTeX-fragment-p ()
16527 "Test if point is inside a LaTeX fragment.
16528 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
16529 sequence appearing also before point.
16530 Even though the matchers for math are configurable, this function assumes
16531 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
16532 delimiters are skipped when they have been removed by customization.
16533 The return value is nil, or a cons cell with the delimiter and the
16534 position of this delimiter.
16536 This function does a reasonably good job, but can locally be fooled by
16537 for example currency specifications. For example it will assume being in
16538 inline math after \"$22.34\". The LaTeX fragment formatter will only format
16539 fragments that are properly closed, but during editing, we have to live
16540 with the uncertainty caused by missing closing delimiters. This function
16541 looks only before point, not after."
16542 (catch 'exit
16543 (let ((pos (point))
16544 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
16545 (lim (progn
16546 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
16547 (point)))
16548 dd-on str (start 0) m re)
16549 (goto-char pos)
16550 (when dodollar
16551 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
16552 re (nth 1 (assoc "$" org-latex-regexps)))
16553 (while (string-match re str start)
16554 (cond
16555 ((= (match-end 0) (length str))
16556 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
16557 ((= (match-end 0) (- (length str) 5))
16558 (throw 'exit nil))
16559 (t (setq start (match-end 0))))))
16560 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
16561 (goto-char pos)
16562 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
16563 (and (match-beginning 2) (throw 'exit nil))
16564 ;; count $$
16565 (while (re-search-backward "\\$\\$" lim t)
16566 (setq dd-on (not dd-on)))
16567 (goto-char pos)
16568 (if dd-on (cons "$$" m))))))
16570 (defun org-inside-latex-macro-p ()
16571 "Is point inside a LaTeX macro or its arguments?"
16572 (save-match-data
16573 (org-in-regexp
16574 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
16576 (defun org-try-cdlatex-tab ()
16577 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
16578 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
16579 - inside a LaTeX fragment, or
16580 - after the first word in a line, where an abbreviation expansion could
16581 insert a LaTeX environment."
16582 (when org-cdlatex-mode
16583 (cond
16584 ;; Before any word on the line: No expansion possible.
16585 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
16586 ;; Just after first word on the line: Expand it. Make sure it
16587 ;; cannot happen on headlines, though.
16588 ((save-excursion
16589 (skip-chars-backward "a-zA-Z0-9*")
16590 (skip-chars-backward " \t")
16591 (and (bolp) (not (org-at-heading-p))))
16592 (cdlatex-tab) t)
16593 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
16595 (defun org-cdlatex-underscore-caret (&optional arg)
16596 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
16597 Revert to the normal definition outside of these fragments."
16598 (interactive "P")
16599 (if (org-inside-LaTeX-fragment-p)
16600 (call-interactively 'cdlatex-sub-superscript)
16601 (let (org-cdlatex-mode)
16602 (call-interactively (key-binding (vector last-input-event))))))
16604 (defun org-cdlatex-math-modify (&optional arg)
16605 "Execute `cdlatex-math-modify' in LaTeX fragments.
16606 Revert to the normal definition outside of these fragments."
16607 (interactive "P")
16608 (if (org-inside-LaTeX-fragment-p)
16609 (call-interactively 'cdlatex-math-modify)
16610 (let (org-cdlatex-mode)
16611 (call-interactively (key-binding (vector last-input-event))))))
16613 (defvar org-latex-fragment-image-overlays nil
16614 "List of overlays carrying the images of latex fragments.")
16615 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
16617 (defun org-remove-latex-fragment-image-overlays ()
16618 "Remove all overlays with LaTeX fragment images in current buffer."
16619 (mapc 'delete-overlay org-latex-fragment-image-overlays)
16620 (setq org-latex-fragment-image-overlays nil))
16622 (defun org-preview-latex-fragment (&optional subtree)
16623 "Preview the LaTeX fragment at point, or all locally or globally.
16624 If the cursor is in a LaTeX fragment, create the image and overlay
16625 it over the source code. If there is no fragment at point, display
16626 all fragments in the current text, from one headline to the next. With
16627 prefix SUBTREE, display all fragments in the current subtree. With a
16628 double prefix arg \\[universal-argument] \\[universal-argument], or when \
16629 the cursor is before the first headline,
16630 display all fragments in the buffer.
16631 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
16632 (interactive "P")
16633 (org-remove-latex-fragment-image-overlays)
16634 (save-excursion
16635 (save-restriction
16636 (let (beg end at msg)
16637 (cond
16638 ((or (equal subtree '(16))
16639 (not (save-excursion
16640 (re-search-backward org-outline-regexp-bol nil t))))
16641 (setq beg (point-min) end (point-max)
16642 msg "Creating images for buffer...%s"))
16643 ((equal subtree '(4))
16644 (org-back-to-heading)
16645 (setq beg (point) end (org-end-of-subtree t)
16646 msg "Creating images for subtree...%s"))
16648 (if (setq at (org-inside-LaTeX-fragment-p))
16649 (goto-char (max (point-min) (- (cdr at) 2)))
16650 (org-back-to-heading))
16651 (setq beg (point) end (progn (outline-next-heading) (point))
16652 msg (if at "Creating image...%s"
16653 "Creating images for entry...%s"))))
16654 (message msg "")
16655 (narrow-to-region beg end)
16656 (goto-char beg)
16657 (org-format-latex
16658 (concat "ltxpng/" (file-name-sans-extension
16659 (file-name-nondirectory
16660 buffer-file-name)))
16661 default-directory 'overlays msg at 'forbuffer 'dvipng)
16662 (message msg "done. Use `C-c C-c' to remove images.")))))
16664 (defvar org-latex-regexps
16665 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
16666 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
16667 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
16668 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
16669 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
16670 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
16671 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
16672 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
16673 "Regular expressions for matching embedded LaTeX.")
16675 (defvar org-export-have-math nil) ;; dynamic scoping
16676 (defun org-format-latex (prefix &optional dir overlays msg at
16677 forbuffer processing-type)
16678 "Replace LaTeX fragments with links to an image, and produce images.
16679 Some of the options can be changed using the variable
16680 `org-format-latex-options'."
16681 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
16682 (let* ((prefixnodir (file-name-nondirectory prefix))
16683 (absprefix (expand-file-name prefix dir))
16684 (todir (file-name-directory absprefix))
16685 (opt org-format-latex-options)
16686 (matchers (plist-get opt :matchers))
16687 (re-list org-latex-regexps)
16688 (org-format-latex-header-extra
16689 (plist-get (org-infile-export-plist) :latex-header-extra))
16690 (cnt 0) txt hash link beg end re e checkdir
16691 executables-checked string
16692 m n block-type block linkfile movefile ov)
16693 ;; Check the different regular expressions
16694 (while (setq e (pop re-list))
16695 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
16696 block (if block-type "\n\n" ""))
16697 (when (member m matchers)
16698 (goto-char (point-min))
16699 (while (re-search-forward re nil t)
16700 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
16701 (not (get-text-property (match-beginning n)
16702 'org-protected))
16703 (or (not overlays)
16704 (not (eq (get-char-property (match-beginning n)
16705 'org-overlay-type)
16706 'org-latex-overlay))))
16707 (setq org-export-have-math t)
16708 (cond
16709 ((eq processing-type 'verbatim)
16710 ;; Leave the text verbatim, just protect it
16711 (add-text-properties (match-beginning n) (match-end n)
16712 '(org-protected t)))
16713 ((eq processing-type 'mathjax)
16714 ;; Prepare for MathJax processing
16715 (setq string (match-string n))
16716 (if (member m '("$" "$1"))
16717 (save-excursion
16718 (delete-region (match-beginning n) (match-end n))
16719 (goto-char (match-beginning n))
16720 (insert (org-add-props (concat "\\(" (substring string 1 -1)
16721 "\\)")
16722 '(org-protected t))))
16723 (add-text-properties (match-beginning n) (match-end n)
16724 '(org-protected t))))
16725 ((eq processing-type 'dvipng)
16726 ;; Process to an image
16727 (setq txt (match-string n)
16728 beg (match-beginning n) end (match-end n)
16729 cnt (1+ cnt))
16730 (let (print-length print-level) ; make sure full list is printed
16731 (setq hash (sha1 (prin1-to-string
16732 (list org-format-latex-header
16733 org-format-latex-header-extra
16734 org-export-latex-default-packages-alist
16735 org-export-latex-packages-alist
16736 org-format-latex-options
16737 forbuffer txt)))
16738 linkfile (format "%s_%s.png" prefix hash)
16739 movefile (format "%s_%s.png" absprefix hash)))
16740 (setq link (concat block "[[file:" linkfile "]]" block))
16741 (if msg (message msg cnt))
16742 (goto-char beg)
16743 (unless checkdir ; make sure the directory exists
16744 (setq checkdir t)
16745 (or (file-directory-p todir) (make-directory todir t)))
16747 (unless executables-checked
16748 (org-check-external-command
16749 "latex" "needed to convert LaTeX fragments to images")
16750 (org-check-external-command
16751 "dvipng" "needed to convert LaTeX fragments to images")
16752 (setq executables-checked t))
16754 (unless (file-exists-p movefile)
16755 (org-create-formula-image
16756 txt movefile opt forbuffer))
16757 (if overlays
16758 (progn
16759 (mapc (lambda (o)
16760 (if (eq (overlay-get o 'org-overlay-type)
16761 'org-latex-overlay)
16762 (delete-overlay o)))
16763 (overlays-in beg end))
16764 (setq ov (make-overlay beg end))
16765 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
16766 (if (featurep 'xemacs)
16767 (progn
16768 (overlay-put ov 'invisible t)
16769 (overlay-put
16770 ov 'end-glyph
16771 (make-glyph (vector 'png :file movefile))))
16772 (overlay-put
16773 ov 'display
16774 (list 'image :type 'png :file movefile :ascent 'center)))
16775 (push ov org-latex-fragment-image-overlays)
16776 (goto-char end))
16777 (delete-region beg end)
16778 (insert (org-add-props link
16779 (list 'org-latex-src
16780 (replace-regexp-in-string
16781 "\"" "" txt)
16782 'org-latex-src-embed-type
16783 (if block-type 'paragraph 'character))))))
16784 ((eq processing-type 'mathml)
16785 ;; Process to MathML
16786 (unless executables-checked
16787 (unless (save-match-data (org-format-latex-mathml-available-p))
16788 (error "LaTeX to MathML converter not configured"))
16789 (setq executables-checked t))
16790 (setq txt (match-string n)
16791 beg (match-beginning n) end (match-end n)
16792 cnt (1+ cnt))
16793 (if msg (message msg cnt))
16794 (goto-char beg)
16795 (delete-region beg end)
16796 (insert (org-format-latex-as-mathml
16797 txt block-type prefix dir)))
16799 (error "Unknown conversion type %s for latex fragments"
16800 processing-type)))))))))
16802 (defun org-create-math-formula (latex-frag &optional mathml-file)
16803 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
16804 Use `org-latex-to-mathml-convert-command'. If the conversion is
16805 sucessful, return the portion between \"<math...> </math>\"
16806 elements otherwise return nil. When MATHML-FILE is specified,
16807 write the results in to that file. When invoked as an
16808 interactive command, prompt for LATEX-FRAG, with initial value
16809 set to the current active region and echo the results for user
16810 inspection."
16811 (interactive (list (let ((frag (when (region-active-p)
16812 (buffer-substring-no-properties
16813 (region-beginning) (region-end)))))
16814 (read-string "LaTeX Fragment: " frag nil frag))))
16815 (unless latex-frag (error "Invalid latex-frag"))
16816 (let* ((tmp-in-file (file-relative-name
16817 (make-temp-name (expand-file-name "ltxmathml-in"))))
16818 (ignore (write-region latex-frag nil tmp-in-file))
16819 (tmp-out-file (file-relative-name
16820 (make-temp-name (expand-file-name "ltxmathml-out"))))
16821 (cmd (format-spec
16822 org-latex-to-mathml-convert-command
16823 `((?j . ,(shell-quote-argument
16824 (expand-file-name org-latex-to-mathml-jar-file)))
16825 (?I . ,(shell-quote-argument tmp-in-file))
16826 (?o . ,(shell-quote-argument tmp-out-file)))))
16827 mathml shell-command-output)
16828 (when (org-called-interactively-p 'any)
16829 (unless (org-format-latex-mathml-available-p)
16830 (error "LaTeX to MathML converter not configured")))
16831 (message "Running %s" cmd)
16832 (setq shell-command-output (shell-command-to-string cmd))
16833 (setq mathml
16834 (when (file-readable-p tmp-out-file)
16835 (with-current-buffer (find-file-noselect tmp-out-file t)
16836 (goto-char (point-min))
16837 (when (re-search-forward
16838 (concat
16839 (regexp-quote
16840 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
16841 "\\(.\\|\n\\)*"
16842 (regexp-quote "</math>")) nil t)
16843 (prog1 (match-string 0) (kill-buffer))))))
16844 (cond
16845 (mathml
16846 (setq mathml
16847 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
16848 (when mathml-file
16849 (write-region mathml nil mathml-file))
16850 (when (org-called-interactively-p 'any)
16851 (message mathml)))
16852 ((message "LaTeX to MathML conversion failed")
16853 (message shell-command-output)))
16854 (delete-file tmp-in-file)
16855 (when (file-exists-p tmp-out-file)
16856 (delete-file tmp-out-file))
16857 mathml))
16859 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
16860 prefix &optional dir)
16861 "Use `org-create-math-formula' but check local cache first."
16862 (let* ((absprefix (expand-file-name prefix dir))
16863 (print-length nil) (print-level nil)
16864 (formula-id (concat
16865 "formula-"
16866 (sha1
16867 (prin1-to-string
16868 (list latex-frag
16869 org-latex-to-mathml-convert-command)))))
16870 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
16871 (formula-cache-dir (file-name-directory formula-cache)))
16873 (unless (file-directory-p formula-cache-dir)
16874 (make-directory formula-cache-dir t))
16876 (unless (file-exists-p formula-cache)
16877 (org-create-math-formula latex-frag formula-cache))
16879 (if (file-exists-p formula-cache)
16880 ;; Successful conversion. Return the link to MathML file.
16881 (org-add-props
16882 (format "[[file:%s]]" (file-relative-name formula-cache dir))
16883 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
16884 'org-latex-src-embed-type (if latex-frag-type
16885 'paragraph 'character)))
16886 ;; Failed conversion. Return the LaTeX fragment verbatim
16887 (add-text-properties
16888 0 (1- (length latex-frag)) '(org-protected t) latex-frag)
16889 latex-frag)))
16891 ;; This function borrows from Ganesh Swami's latex2png.el
16892 (defun org-create-formula-image (string tofile options buffer)
16893 "This calls dvipng."
16894 (require 'org-latex)
16895 (let* ((tmpdir (if (featurep 'xemacs)
16896 (temp-directory)
16897 temporary-file-directory))
16898 (texfilebase (make-temp-name
16899 (expand-file-name "orgtex" tmpdir)))
16900 (texfile (concat texfilebase ".tex"))
16901 (dvifile (concat texfilebase ".dvi"))
16902 (pngfile (concat texfilebase ".png"))
16903 (fnh (if (featurep 'xemacs)
16904 (font-height (get-face-font 'default))
16905 (face-attribute 'default :height nil)))
16906 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
16907 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
16908 (fg (or (plist-get options (if buffer :foreground :html-foreground))
16909 "Black"))
16910 (bg (or (plist-get options (if buffer :background :html-background))
16911 "Transparent")))
16912 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
16913 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
16914 (with-temp-file texfile
16915 (insert (org-splice-latex-header
16916 org-format-latex-header
16917 org-export-latex-default-packages-alist
16918 org-export-latex-packages-alist t
16919 org-format-latex-header-extra))
16920 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")
16921 (require 'org-latex)
16922 (org-export-latex-fix-inputenc))
16923 (let ((dir default-directory))
16924 (condition-case nil
16925 (progn
16926 (cd tmpdir)
16927 (call-process "latex" nil nil nil texfile))
16928 (error nil))
16929 (cd dir))
16930 (if (not (file-exists-p dvifile))
16931 (progn (message "Failed to create dvi file from %s" texfile) nil)
16932 (condition-case nil
16933 (call-process "dvipng" nil nil nil
16934 "-fg" fg "-bg" bg
16935 "-D" dpi
16936 ;;"-x" scale "-y" scale
16937 "-T" "tight"
16938 "-o" pngfile
16939 dvifile)
16940 (error nil))
16941 (if (not (file-exists-p pngfile))
16942 (if org-format-latex-signal-error
16943 (error "Failed to create png file from %s" texfile)
16944 (message "Failed to create png file from %s" texfile)
16945 nil)
16946 ;; Use the requested file name and clean up
16947 (copy-file pngfile tofile 'replace)
16948 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
16949 (delete-file (concat texfilebase e)))
16950 pngfile))))
16952 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
16953 "Fill a LaTeX header template TPL.
16954 In the template, the following place holders will be recognized:
16956 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
16957 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
16958 [PACKAGES] \\usepackage statements for PKG
16959 [NO-PACKAGES] do not include PKG
16960 [EXTRA] the string EXTRA
16961 [NO-EXTRA] do not include EXTRA
16963 For backward compatibility, if both the positive and the negative place
16964 holder is missing, the positive one (without the \"NO-\") will be
16965 assumed to be present at the end of the template.
16966 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
16967 EXTRA is a string.
16968 SNIPPETS-P indicates if this is run to create snippet images for HTML."
16969 (let (rpl (end ""))
16970 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
16971 (setq rpl (if (or (match-end 1) (not def-pkg))
16972 "" (org-latex-packages-to-string def-pkg snippets-p t))
16973 tpl (replace-match rpl t t tpl))
16974 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
16976 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
16977 (setq rpl (if (or (match-end 1) (not pkg))
16978 "" (org-latex-packages-to-string pkg snippets-p t))
16979 tpl (replace-match rpl t t tpl))
16980 (if pkg (setq end
16981 (concat end "\n"
16982 (org-latex-packages-to-string pkg snippets-p)))))
16984 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
16985 (setq rpl (if (or (match-end 1) (not extra))
16986 "" (concat extra "\n"))
16987 tpl (replace-match rpl t t tpl))
16988 (if (and extra (string-match "\\S-" extra))
16989 (setq end (concat end "\n" extra))))
16991 (if (string-match "\\S-" end)
16992 (concat tpl "\n" end)
16993 tpl)))
16995 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
16996 "Turn an alist of packages into a string with the \\usepackage macros."
16997 (setq pkg (mapconcat (lambda(p)
16998 (cond
16999 ((stringp p) p)
17000 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
17001 (format "%% Package %s omitted" (cadr p)))
17002 ((equal "" (car p))
17003 (format "\\usepackage{%s}" (cadr p)))
17005 (format "\\usepackage[%s]{%s}"
17006 (car p) (cadr p)))))
17008 "\n"))
17009 (if newline (concat pkg "\n") pkg))
17011 (defun org-dvipng-color (attr)
17012 "Return an rgb color specification for dvipng."
17013 (apply 'format "rgb %s %s %s"
17014 (mapcar 'org-normalize-color
17015 (color-values (face-attribute 'default attr nil)))))
17017 (defun org-normalize-color (value)
17018 "Return string to be used as color value for an RGB component."
17019 (format "%g" (/ value 65535.0)))
17021 ;; Image display
17024 (defvar org-inline-image-overlays nil)
17025 (make-variable-buffer-local 'org-inline-image-overlays)
17027 (defun org-toggle-inline-images (&optional include-linked)
17028 "Toggle the display of inline images.
17029 INCLUDE-LINKED is passed to `org-display-inline-images'."
17030 (interactive "P")
17031 (if org-inline-image-overlays
17032 (progn
17033 (org-remove-inline-images)
17034 (message "Inline image display turned off"))
17035 (org-display-inline-images include-linked)
17036 (if org-inline-image-overlays
17037 (message "%d images displayed inline"
17038 (length org-inline-image-overlays))
17039 (message "No images to display inline"))))
17041 (defun org-display-inline-images (&optional include-linked refresh beg end)
17042 "Display inline images.
17043 Normally only links without a description part are inlined, because this
17044 is how it will work for export. When INCLUDE-LINKED is set, also links
17045 with a description part will be inlined. This can be nice for a quick
17046 look at those images, but it does not reflect what exported files will look
17047 like.
17048 When REFRESH is set, refresh existing images between BEG and END.
17049 This will create new image displays only if necessary.
17050 BEG and END default to the buffer boundaries."
17051 (interactive "P")
17052 (unless refresh
17053 (org-remove-inline-images)
17054 (if (fboundp 'clear-image-cache) (clear-image-cache)))
17055 (save-excursion
17056 (save-restriction
17057 (widen)
17058 (setq beg (or beg (point-min)) end (or end (point-max)))
17059 (goto-char (point-min))
17060 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
17061 (substring (org-image-file-name-regexp) 0 -2)
17062 "\\)\\]" (if include-linked "" "\\]")))
17063 old file ov img)
17064 (while (re-search-forward re end t)
17065 (setq old (get-char-property-and-overlay (match-beginning 1)
17066 'org-image-overlay))
17067 (setq file (expand-file-name
17068 (concat (or (match-string 3) "") (match-string 4))))
17069 (when (file-exists-p file)
17070 (if (and (car-safe old) refresh)
17071 (image-refresh (overlay-get (cdr old) 'display))
17072 (setq img (save-match-data (create-image file)))
17073 (when img
17074 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
17075 (overlay-put ov 'display img)
17076 (overlay-put ov 'face 'default)
17077 (overlay-put ov 'org-image-overlay t)
17078 (overlay-put ov 'modification-hooks
17079 (list 'org-display-inline-modification-hook))
17080 (push ov org-inline-image-overlays)))))))))
17082 (defun org-display-inline-modification-hook (ov after beg end &optional len)
17083 "Remove inline-display overlay if a corresponding region is modified."
17084 (let ((inhibit-modification-hooks t))
17085 (when (and ov after)
17086 (delete ov org-inline-image-overlays)
17087 (delete-overlay ov))))
17089 (defun org-remove-inline-images ()
17090 "Remove inline display of images."
17091 (interactive)
17092 (mapc 'delete-overlay org-inline-image-overlays)
17093 (setq org-inline-image-overlays nil))
17095 ;;;; Key bindings
17097 ;; Remap outline keys
17098 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
17099 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
17101 ;; Make `C-c C-x' a prefix key
17102 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
17104 ;; TAB key with modifiers
17105 (org-defkey org-mode-map "\C-i" 'org-cycle)
17106 (org-defkey org-mode-map [(tab)] 'org-cycle)
17107 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
17108 (org-defkey org-mode-map [(meta tab)] 'pcomplete)
17109 (org-defkey org-mode-map "\M-\t" 'pcomplete)
17110 (org-defkey org-mode-map "\M-\C-i" 'pcomplete)
17111 ;; The following line is necessary under Suse GNU/Linux
17112 (unless (featurep 'xemacs)
17113 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
17114 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
17115 (define-key org-mode-map [backtab] 'org-shifttab)
17117 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
17118 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
17119 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
17121 ;; Cursor keys with modifiers
17122 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
17123 (org-defkey org-mode-map [(meta right)] 'org-metaright)
17124 (org-defkey org-mode-map [(meta up)] 'org-metaup)
17125 (org-defkey org-mode-map [(meta down)] 'org-metadown)
17127 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
17128 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
17129 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
17130 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
17132 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
17133 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
17134 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
17135 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
17137 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
17138 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
17139 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
17140 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
17142 ;; Babel keys
17143 (define-key org-mode-map org-babel-key-prefix org-babel-map)
17144 (mapc (lambda (pair)
17145 (define-key org-babel-map (car pair) (cdr pair)))
17146 org-babel-key-bindings)
17148 ;;; Extra keys for tty access.
17149 ;; We only set them when really needed because otherwise the
17150 ;; menus don't show the simple keys
17152 (when (or org-use-extra-keys
17153 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
17154 (not window-system))
17155 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
17156 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
17157 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
17158 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
17159 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
17160 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
17161 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
17162 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
17163 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
17164 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
17165 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
17166 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
17167 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
17168 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
17169 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
17170 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
17171 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
17172 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
17173 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
17174 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
17175 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
17176 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
17177 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
17178 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
17179 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
17180 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
17181 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
17182 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
17184 ;; All the other keys
17186 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
17187 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
17188 (if (boundp 'narrow-map)
17189 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
17190 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
17191 (if (boundp 'narrow-map)
17192 (org-defkey narrow-map "b" 'org-narrow-to-block)
17193 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
17194 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-same-level)
17195 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-same-level)
17196 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
17197 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
17198 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
17199 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
17200 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
17201 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
17202 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
17203 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
17204 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
17205 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
17206 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
17207 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
17208 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
17209 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
17210 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
17211 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
17212 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
17213 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
17214 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
17215 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
17216 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
17217 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
17218 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
17219 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
17220 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
17221 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
17222 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
17223 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
17224 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
17225 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
17226 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
17227 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
17228 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
17229 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
17230 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
17231 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
17232 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
17233 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
17234 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
17235 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
17236 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
17237 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
17238 (org-defkey org-mode-map "\C-c^" 'org-sort)
17239 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
17240 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
17241 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
17242 (org-defkey org-mode-map "\C-m" 'org-return)
17243 (org-defkey org-mode-map "\C-j" 'org-return-indent)
17244 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
17245 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
17246 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
17247 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
17248 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
17249 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
17250 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
17251 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
17252 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
17253 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
17254 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
17255 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
17256 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
17257 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
17258 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
17259 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
17260 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
17261 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
17262 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
17263 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
17264 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
17266 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
17267 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
17268 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
17269 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
17271 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
17272 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
17273 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
17274 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
17275 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
17276 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
17277 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
17278 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
17279 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
17280 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
17281 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
17282 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
17283 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
17284 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
17285 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
17286 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
17287 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
17288 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
17290 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
17291 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
17292 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
17293 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
17294 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
17296 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
17298 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
17300 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
17301 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
17303 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
17306 (when (featurep 'xemacs)
17307 (org-defkey org-mode-map 'button3 'popup-mode-menu))
17310 (defconst org-speed-commands-default
17312 ("Outline Navigation")
17313 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
17314 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
17315 ("f" . (org-speed-move-safe 'org-forward-same-level))
17316 ("b" . (org-speed-move-safe 'org-backward-same-level))
17317 ("u" . (org-speed-move-safe 'outline-up-heading))
17318 ("j" . org-goto)
17319 ("g" . (org-refile t))
17320 ("Outline Visibility")
17321 ("c" . org-cycle)
17322 ("C" . org-shifttab)
17323 (" " . org-display-outline-path)
17324 ("Outline Structure Editing")
17325 ("U" . org-shiftmetaup)
17326 ("D" . org-shiftmetadown)
17327 ("r" . org-metaright)
17328 ("l" . org-metaleft)
17329 ("R" . org-shiftmetaright)
17330 ("L" . org-shiftmetaleft)
17331 ("i" . (progn (forward-char 1) (call-interactively
17332 'org-insert-heading-respect-content)))
17333 ("^" . org-sort)
17334 ("w" . org-refile)
17335 ("a" . org-archive-subtree-default-with-confirmation)
17336 ("." . org-mark-subtree)
17337 ("Clock Commands")
17338 ("I" . org-clock-in)
17339 ("O" . org-clock-out)
17340 ("Meta Data Editing")
17341 ("t" . org-todo)
17342 ("0" . (org-priority ?\ ))
17343 ("1" . (org-priority ?A))
17344 ("2" . (org-priority ?B))
17345 ("3" . (org-priority ?C))
17346 (";" . org-set-tags-command)
17347 ("e" . org-set-effort)
17348 ("Agenda Views etc")
17349 ("v" . org-agenda)
17350 ("/" . org-sparse-tree)
17351 ("Misc")
17352 ("o" . org-open-at-point)
17353 ("?" . org-speed-command-help)
17354 ("<" . (org-agenda-set-restriction-lock 'subtree))
17355 (">" . (org-agenda-remove-restriction-lock))
17357 "The default speed commands.")
17359 (defun org-print-speed-command (e)
17360 (if (> (length (car e)) 1)
17361 (progn
17362 (princ "\n")
17363 (princ (car e))
17364 (princ "\n")
17365 (princ (make-string (length (car e)) ?-))
17366 (princ "\n"))
17367 (princ (car e))
17368 (princ " ")
17369 (if (symbolp (cdr e))
17370 (princ (symbol-name (cdr e)))
17371 (prin1 (cdr e)))
17372 (princ "\n")))
17374 (defun org-speed-command-help ()
17375 "Show the available speed commands."
17376 (interactive)
17377 (if (not org-use-speed-commands)
17378 (error "Speed commands are not activated, customize `org-use-speed-commands'")
17379 (with-output-to-temp-buffer "*Help*"
17380 (princ "User-defined Speed commands\n===========================\n")
17381 (mapc 'org-print-speed-command org-speed-commands-user)
17382 (princ "\n")
17383 (princ "Built-in Speed commands\n=======================\n")
17384 (mapc 'org-print-speed-command org-speed-commands-default))
17385 (with-current-buffer "*Help*"
17386 (setq truncate-lines t))))
17388 (defun org-speed-move-safe (cmd)
17389 "Execute CMD, but make sure that the cursor always ends up in a headline.
17390 If not, return to the original position and throw an error."
17391 (interactive)
17392 (let ((pos (point)))
17393 (call-interactively cmd)
17394 (unless (and (bolp) (org-on-heading-p))
17395 (goto-char pos)
17396 (error "Boundary reached while executing %s" cmd))))
17398 (defvar org-self-insert-command-undo-counter 0)
17400 (defvar org-table-auto-blank-field) ; defined in org-table.el
17401 (defvar org-speed-command nil)
17403 (defun org-speed-command-default-hook (keys)
17404 "Hook for activating single-letter speed commands.
17405 `org-speed-commands-default' specifies a minimal command set.
17406 Use `org-speed-commands-user' for further customization."
17407 (when (or (and (bolp) (looking-at org-outline-regexp))
17408 (and (functionp org-use-speed-commands)
17409 (funcall org-use-speed-commands)))
17410 (cdr (assoc keys (append org-speed-commands-user
17411 org-speed-commands-default)))))
17413 (defun org-babel-speed-command-hook (keys)
17414 "Hook for activating single-letter code block commands."
17415 (when (and (bolp) (looking-at org-babel-src-block-regexp))
17416 (cdr (assoc keys org-babel-key-bindings))))
17418 (defcustom org-speed-command-hook
17419 '(org-speed-command-default-hook org-babel-speed-command-hook)
17420 "Hook for activating speed commands at strategic locations.
17421 Hook functions are called in sequence until a valid handler is
17422 found.
17424 Each hook takes a single argument, a user-pressed command key
17425 which is also a `self-insert-command' from the global map.
17427 Within the hook, examine the cursor position and the command key
17428 and return nil or a valid handler as appropriate. Handler could
17429 be one of an interactive command, a function, or a form.
17431 Set `org-use-speed-commands' to non-nil value to enable this
17432 hook. The default setting is `org-speed-command-default-hook'."
17433 :group 'org-structure
17434 :type 'hook)
17436 (defun org-self-insert-command (N)
17437 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
17438 If the cursor is in a table looking at whitespace, the whitespace is
17439 overwritten, and the table is not marked as requiring realignment."
17440 (interactive "p")
17441 (org-check-before-invisible-edit 'insert)
17442 (cond
17443 ((and org-use-speed-commands
17444 (setq org-speed-command
17445 (run-hook-with-args-until-success
17446 'org-speed-command-hook (this-command-keys))))
17447 (cond
17448 ((commandp org-speed-command)
17449 (setq this-command org-speed-command)
17450 (call-interactively org-speed-command))
17451 ((functionp org-speed-command)
17452 (funcall org-speed-command))
17453 ((and org-speed-command (listp org-speed-command))
17454 (eval org-speed-command))
17455 (t (let (org-use-speed-commands)
17456 (call-interactively 'org-self-insert-command)))))
17457 ((and
17458 (org-table-p)
17459 (progn
17460 ;; check if we blank the field, and if that triggers align
17461 (and (featurep 'org-table) org-table-auto-blank-field
17462 (member last-command
17463 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
17464 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
17465 ;; got extra space, this field does not determine column width
17466 (let (org-table-may-need-update) (org-table-blank-field))
17467 ;; no extra space, this field may determine column width
17468 (org-table-blank-field)))
17470 (eq N 1)
17471 (looking-at "[^|\n]* |"))
17472 (let (org-table-may-need-update)
17473 (goto-char (1- (match-end 0)))
17474 (delete-char -1)
17475 (goto-char (match-beginning 0))
17476 (self-insert-command N)))
17478 (setq org-table-may-need-update t)
17479 (self-insert-command N)
17480 (org-fix-tags-on-the-fly)
17481 (if org-self-insert-cluster-for-undo
17482 (if (not (eq last-command 'org-self-insert-command))
17483 (setq org-self-insert-command-undo-counter 1)
17484 (if (>= org-self-insert-command-undo-counter 20)
17485 (setq org-self-insert-command-undo-counter 1)
17486 (and (> org-self-insert-command-undo-counter 0)
17487 buffer-undo-list (listp buffer-undo-list)
17488 (not (cadr buffer-undo-list)) ; remove nil entry
17489 (setcdr buffer-undo-list (cddr buffer-undo-list)))
17490 (setq org-self-insert-command-undo-counter
17491 (1+ org-self-insert-command-undo-counter))))))))
17493 (defun org-check-before-invisible-edit (kind)
17494 "Check is editing if kind KIND would be dangerous with invisible text around.
17495 The detailed reaction depends on the user option `org-catch-invisible-edits'."
17496 ;; First, try to get out of here as quickly as possible, to reduce overhead
17497 (if (and org-catch-invisible-edits
17498 (or (not (boundp 'visible-mode)) (not visible-mode))
17499 (or (get-char-property (point) 'invisible)
17500 (get-char-property (max (point-min) (1- (point))) 'invisible)))
17501 ;; OK, we need to take a closer look
17502 (let* ((invisible-at-point (get-char-property (point) 'invisible))
17503 (invisible-before-point (if (bobp) nil (get-char-property
17504 (1- (point)) 'invisible)))
17505 (border-and-ok-direction
17507 ;; Check if we are acting predictably before invisible text
17508 (and invisible-at-point (not invisible-before-point)
17509 (memq kind '(insert delete-backward)))
17510 ;; Check if we are acting predictably after invisible text
17511 ;; This works not well, and I have turned it off. It seems
17512 ;; better to always show and stop after invisible text.
17513 ;; (and (not invisible-at-point) invisible-before-point
17514 ;; (memq kind '(insert delete)))
17517 (when (or (memq invisible-at-point '(outline org-hide-block))
17518 (memq invisible-before-point '(outline org-hide-block)))
17519 (if (eq org-catch-invisible-edits 'error)
17520 (error "Editing in invisible areas is prohibited - make visible first"))
17521 ;; Make the area visible
17522 (save-excursion
17523 (if invisible-before-point
17524 (goto-char (previous-single-char-property-change
17525 (point) 'invisible)))
17526 (org-cycle))
17527 (cond
17528 ((eq org-catch-invisible-edits 'show)
17529 ;; That's it, we do the edit after showing
17530 (message
17531 "Unfolding invisible region around point before editing")
17532 (sit-for 1))
17533 ((and (eq org-catch-invisible-edits 'smart)
17534 border-and-ok-direction)
17535 (message "Unfolding invisible region around point before editing"))
17537 ;; Don't do the edit, make the user repeat it in full visibility
17538 (error "Edit in invisible region aborted, repeat to confirm with text visible")))))))
17540 (defun org-fix-tags-on-the-fly ()
17541 (when (and (equal (char-after (point-at-bol)) ?*)
17542 (org-on-heading-p))
17543 (org-align-tags-here org-tags-column)))
17545 (defun org-delete-backward-char (N)
17546 "Like `delete-backward-char', insert whitespace at field end in tables.
17547 When deleting backwards, in tables this function will insert whitespace in
17548 front of the next \"|\" separator, to keep the table aligned. The table will
17549 still be marked for re-alignment if the field did fill the entire column,
17550 because, in this case the deletion might narrow the column."
17551 (interactive "p")
17552 (org-check-before-invisible-edit 'delete-backward)
17553 (if (and (org-table-p)
17554 (eq N 1)
17555 (string-match "|" (buffer-substring (point-at-bol) (point)))
17556 (looking-at ".*?|"))
17557 (let ((pos (point))
17558 (noalign (looking-at "[^|\n\r]* |"))
17559 (c org-table-may-need-update))
17560 (backward-delete-char N)
17561 (if (not overwrite-mode)
17562 (progn
17563 (skip-chars-forward "^|")
17564 (insert " ")
17565 (goto-char (1- pos))))
17566 ;; noalign: if there were two spaces at the end, this field
17567 ;; does not determine the width of the column.
17568 (if noalign (setq org-table-may-need-update c)))
17569 (backward-delete-char N)
17570 (org-fix-tags-on-the-fly)))
17572 (defun org-delete-char (N)
17573 "Like `delete-char', but insert whitespace at field end in tables.
17574 When deleting characters, in tables this function will insert whitespace in
17575 front of the next \"|\" separator, to keep the table aligned. The table will
17576 still be marked for re-alignment if the field did fill the entire column,
17577 because, in this case the deletion might narrow the column."
17578 (interactive "p")
17579 (org-check-before-invisible-edit 'delete)
17580 (if (and (org-table-p)
17581 (not (bolp))
17582 (not (= (char-after) ?|))
17583 (eq N 1))
17584 (if (looking-at ".*?|")
17585 (let ((pos (point))
17586 (noalign (looking-at "[^|\n\r]* |"))
17587 (c org-table-may-need-update))
17588 (replace-match (concat
17589 (substring (match-string 0) 1 -1)
17590 " |"))
17591 (goto-char pos)
17592 ;; noalign: if there were two spaces at the end, this field
17593 ;; does not determine the width of the column.
17594 (if noalign (setq org-table-may-need-update c)))
17595 (delete-char N))
17596 (delete-char N)
17597 (org-fix-tags-on-the-fly)))
17599 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
17600 (put 'org-self-insert-command 'delete-selection t)
17601 (put 'orgtbl-self-insert-command 'delete-selection t)
17602 (put 'org-delete-char 'delete-selection 'supersede)
17603 (put 'org-delete-backward-char 'delete-selection 'supersede)
17604 (put 'org-yank 'delete-selection 'yank)
17606 ;; Make `flyspell-mode' delay after some commands
17607 (put 'org-self-insert-command 'flyspell-delayed t)
17608 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
17609 (put 'org-delete-char 'flyspell-delayed t)
17610 (put 'org-delete-backward-char 'flyspell-delayed t)
17612 ;; Make pabbrev-mode expand after org-mode commands
17613 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
17614 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
17616 ;; How to do this: Measure non-white length of current string
17617 ;; If equal to column width, we should realign.
17619 (defun org-remap (map &rest commands)
17620 "In MAP, remap the functions given in COMMANDS.
17621 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
17622 (let (new old)
17623 (while commands
17624 (setq old (pop commands) new (pop commands))
17625 (if (fboundp 'command-remapping)
17626 (org-defkey map (vector 'remap old) new)
17627 (substitute-key-definition old new map global-map)))))
17629 (when (eq org-enable-table-editor 'optimized)
17630 ;; If the user wants maximum table support, we need to hijack
17631 ;; some standard editing functions
17632 (org-remap org-mode-map
17633 'self-insert-command 'org-self-insert-command
17634 'delete-char 'org-delete-char
17635 'delete-backward-char 'org-delete-backward-char)
17636 (org-defkey org-mode-map "|" 'org-force-self-insert))
17638 (defvar org-ctrl-c-ctrl-c-hook nil
17639 "Hook for functions attaching themselves to `C-c C-c'.
17641 This can be used to add additional functionality to the C-c C-c
17642 key which executes context-dependent commands. This hook is run
17643 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
17644 run after the last test.
17646 Each function will be called with no arguments. The function
17647 must check if the context is appropriate for it to act. If yes,
17648 it should do its thing and then return a non-nil value. If the
17649 context is wrong, just do nothing and return nil.")
17651 (defvar org-ctrl-c-ctrl-c-final-hook nil
17652 "Hook for functions attaching themselves to `C-c C-c'.
17654 This can be used to add additional functionality to the C-c C-c
17655 key which executes context-dependent commands. This hook is run
17656 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
17657 before the first test.
17659 Each function will be called with no arguments. The function
17660 must check if the context is appropriate for it to act. If yes,
17661 it should do its thing and then return a non-nil value. If the
17662 context is wrong, just do nothing and return nil.")
17664 (defvar org-tab-first-hook nil
17665 "Hook for functions to attach themselves to TAB.
17666 See `org-ctrl-c-ctrl-c-hook' for more information.
17667 This hook runs as the first action when TAB is pressed, even before
17668 `org-cycle' messes around with the `outline-regexp' to cater for
17669 inline tasks and plain list item folding.
17670 If any function in this hook returns t, any other actions that
17671 would have been caused by TAB (such as table field motion or visibility
17672 cycling) will not occur.")
17674 (defvar org-tab-after-check-for-table-hook nil
17675 "Hook for functions to attach themselves to TAB.
17676 See `org-ctrl-c-ctrl-c-hook' for more information.
17677 This hook runs after it has been established that the cursor is not in a
17678 table, but before checking if the cursor is in a headline or if global cycling
17679 should be done.
17680 If any function in this hook returns t, not other actions like visibility
17681 cycling will be done.")
17683 (defvar org-tab-after-check-for-cycling-hook nil
17684 "Hook for functions to attach themselves to TAB.
17685 See `org-ctrl-c-ctrl-c-hook' for more information.
17686 This hook runs after it has been established that not table field motion and
17687 not visibility should be done because of current context. This is probably
17688 the place where a package like yasnippets can hook in.")
17690 (defvar org-tab-before-tab-emulation-hook nil
17691 "Hook for functions to attach themselves to TAB.
17692 See `org-ctrl-c-ctrl-c-hook' for more information.
17693 This hook runs after every other options for TAB have been exhausted, but
17694 before indentation and \t insertion takes place.")
17696 (defvar org-metaleft-hook nil
17697 "Hook for functions attaching themselves to `M-left'.
17698 See `org-ctrl-c-ctrl-c-hook' for more information.")
17699 (defvar org-metaright-hook nil
17700 "Hook for functions attaching themselves to `M-right'.
17701 See `org-ctrl-c-ctrl-c-hook' for more information.")
17702 (defvar org-metaup-hook nil
17703 "Hook for functions attaching themselves to `M-up'.
17704 See `org-ctrl-c-ctrl-c-hook' for more information.")
17705 (defvar org-metadown-hook nil
17706 "Hook for functions attaching themselves to `M-down'.
17707 See `org-ctrl-c-ctrl-c-hook' for more information.")
17708 (defvar org-shiftmetaleft-hook nil
17709 "Hook for functions attaching themselves to `M-S-left'.
17710 See `org-ctrl-c-ctrl-c-hook' for more information.")
17711 (defvar org-shiftmetaright-hook nil
17712 "Hook for functions attaching themselves to `M-S-right'.
17713 See `org-ctrl-c-ctrl-c-hook' for more information.")
17714 (defvar org-shiftmetaup-hook nil
17715 "Hook for functions attaching themselves to `M-S-up'.
17716 See `org-ctrl-c-ctrl-c-hook' for more information.")
17717 (defvar org-shiftmetadown-hook nil
17718 "Hook for functions attaching themselves to `M-S-down'.
17719 See `org-ctrl-c-ctrl-c-hook' for more information.")
17720 (defvar org-metareturn-hook nil
17721 "Hook for functions attaching themselves to `M-RET'.
17722 See `org-ctrl-c-ctrl-c-hook' for more information.")
17723 (defvar org-shiftup-hook nil
17724 "Hook for functions attaching themselves to `S-up'.
17725 See `org-ctrl-c-ctrl-c-hook' for more information.")
17726 (defvar org-shiftup-final-hook nil
17727 "Hook for functions attaching themselves to `S-up'.
17728 This one runs after all other options except shift-select have been excluded.
17729 See `org-ctrl-c-ctrl-c-hook' for more information.")
17730 (defvar org-shiftdown-hook nil
17731 "Hook for functions attaching themselves to `S-down'.
17732 See `org-ctrl-c-ctrl-c-hook' for more information.")
17733 (defvar org-shiftdown-final-hook nil
17734 "Hook for functions attaching themselves to `S-down'.
17735 This one runs after all other options except shift-select have been excluded.
17736 See `org-ctrl-c-ctrl-c-hook' for more information.")
17737 (defvar org-shiftleft-hook nil
17738 "Hook for functions attaching themselves to `S-left'.
17739 See `org-ctrl-c-ctrl-c-hook' for more information.")
17740 (defvar org-shiftleft-final-hook nil
17741 "Hook for functions attaching themselves to `S-left'.
17742 This one runs after all other options except shift-select have been excluded.
17743 See `org-ctrl-c-ctrl-c-hook' for more information.")
17744 (defvar org-shiftright-hook nil
17745 "Hook for functions attaching themselves to `S-right'.
17746 See `org-ctrl-c-ctrl-c-hook' for more information.")
17747 (defvar org-shiftright-final-hook nil
17748 "Hook for functions attaching themselves to `S-right'.
17749 This one runs after all other options except shift-select have been excluded.
17750 See `org-ctrl-c-ctrl-c-hook' for more information.")
17752 (defun org-modifier-cursor-error ()
17753 "Throw an error, a modified cursor command was applied in wrong context."
17754 (error "This command is active in special context like tables, headlines or items"))
17756 (defun org-shiftselect-error ()
17757 "Throw an error because Shift-Cursor command was applied in wrong context."
17758 (if (and (boundp 'shift-select-mode) shift-select-mode)
17759 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
17760 (error "This command works only in special context like headlines or timestamps")))
17762 (defun org-call-for-shift-select (cmd)
17763 (let ((this-command-keys-shift-translated t))
17764 (call-interactively cmd)))
17766 (defun org-shifttab (&optional arg)
17767 "Global visibility cycling or move to previous table field.
17768 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
17769 on context.
17770 See the individual commands for more information."
17771 (interactive "P")
17772 (cond
17773 ((org-at-table-p) (call-interactively 'org-table-previous-field))
17774 ((integerp arg)
17775 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
17776 (message "Content view to level: %d" arg)
17777 (org-content (prefix-numeric-value arg2))
17778 (setq org-cycle-global-status 'overview)))
17779 (t (call-interactively 'org-global-cycle))))
17781 (defun org-shiftmetaleft ()
17782 "Promote subtree or delete table column.
17783 Calls `org-promote-subtree', `org-outdent-item',
17784 or `org-table-delete-column', depending on context.
17785 See the individual commands for more information."
17786 (interactive)
17787 (cond
17788 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
17789 ((org-at-table-p) (call-interactively 'org-table-delete-column))
17790 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
17791 ((org-at-item-p) (call-interactively 'org-outdent-item-tree))
17792 (t (org-modifier-cursor-error))))
17794 (defun org-shiftmetaright ()
17795 "Demote subtree or insert table column.
17796 Calls `org-demote-subtree', `org-indent-item',
17797 or `org-table-insert-column', depending on context.
17798 See the individual commands for more information."
17799 (interactive)
17800 (cond
17801 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
17802 ((org-at-table-p) (call-interactively 'org-table-insert-column))
17803 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
17804 ((org-at-item-p) (call-interactively 'org-indent-item-tree))
17805 (t (org-modifier-cursor-error))))
17807 (defun org-shiftmetaup (&optional arg)
17808 "Move subtree up or kill table row.
17809 Calls `org-move-subtree-up' or `org-table-kill-row' or
17810 `org-move-item-up' depending on context. See the individual commands
17811 for more information."
17812 (interactive "P")
17813 (cond
17814 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
17815 ((org-at-table-p) (call-interactively 'org-table-kill-row))
17816 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
17817 ((org-at-item-p) (call-interactively 'org-move-item-up))
17818 (t (org-modifier-cursor-error))))
17820 (defun org-shiftmetadown (&optional arg)
17821 "Move subtree down or insert table row.
17822 Calls `org-move-subtree-down' or `org-table-insert-row' or
17823 `org-move-item-down', depending on context. See the individual
17824 commands for more information."
17825 (interactive "P")
17826 (cond
17827 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
17828 ((org-at-table-p) (call-interactively 'org-table-insert-row))
17829 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
17830 ((org-at-item-p) (call-interactively 'org-move-item-down))
17831 (t (org-modifier-cursor-error))))
17833 (defsubst org-hidden-tree-error ()
17834 (error
17835 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
17837 (defun org-metaleft (&optional arg)
17838 "Promote heading or move table column to left.
17839 Calls `org-do-promote' or `org-table-move-column', depending on context.
17840 With no specific context, calls the Emacs default `backward-word'.
17841 See the individual commands for more information."
17842 (interactive "P")
17843 (cond
17844 ((run-hook-with-args-until-success 'org-metaleft-hook))
17845 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
17846 ((org-with-limited-levels
17847 (or (org-on-heading-p)
17848 (and (org-region-active-p)
17849 (save-excursion
17850 (goto-char (region-beginning))
17851 (org-on-heading-p)))))
17852 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
17853 (call-interactively 'org-do-promote))
17854 ;; At an inline task.
17855 ((org-on-heading-p)
17856 (call-interactively 'org-inlinetask-promote))
17857 ((or (org-at-item-p)
17858 (and (org-region-active-p)
17859 (save-excursion
17860 (goto-char (region-beginning))
17861 (org-at-item-p))))
17862 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
17863 (call-interactively 'org-outdent-item))
17864 (t (call-interactively 'backward-word))))
17866 (defun org-metaright (&optional arg)
17867 "Demote subtree or move table column to right.
17868 Calls `org-do-demote' or `org-table-move-column', depending on context.
17869 With no specific context, calls the Emacs default `forward-word'.
17870 See the individual commands for more information."
17871 (interactive "P")
17872 (cond
17873 ((run-hook-with-args-until-success 'org-metaright-hook))
17874 ((org-at-table-p) (call-interactively 'org-table-move-column))
17875 ((org-with-limited-levels
17876 (or (org-on-heading-p)
17877 (and (org-region-active-p)
17878 (save-excursion
17879 (goto-char (region-beginning))
17880 (org-on-heading-p)))))
17881 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
17882 (call-interactively 'org-do-demote))
17883 ;; At an inline task.
17884 ((org-on-heading-p)
17885 (call-interactively 'org-inlinetask-demote))
17886 ((or (org-at-item-p)
17887 (and (org-region-active-p)
17888 (save-excursion
17889 (goto-char (region-beginning))
17890 (org-at-item-p))))
17891 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
17892 (call-interactively 'org-indent-item))
17893 (t (call-interactively 'forward-word))))
17895 (defun org-check-for-hidden (what)
17896 "Check if there are hidden headlines/items in the current visual line.
17897 WHAT can be either `headlines' or `items'. If the current line is
17898 an outline or item heading and it has a folded subtree below it,
17899 this function returns t, nil otherwise."
17900 (let ((re (cond
17901 ((eq what 'headlines) org-outline-regexp-bol)
17902 ((eq what 'items) (org-item-beginning-re))
17903 (t (error "This should not happen"))))
17904 beg end)
17905 (save-excursion
17906 (catch 'exit
17907 (unless (org-region-active-p)
17908 (setq beg (point-at-bol))
17909 (beginning-of-line 2)
17910 (while (and (not (eobp)) ;; this is like `next-line'
17911 (get-char-property (1- (point)) 'invisible))
17912 (beginning-of-line 2))
17913 (setq end (point))
17914 (goto-char beg)
17915 (goto-char (point-at-eol))
17916 (setq end (max end (point)))
17917 (while (re-search-forward re end t)
17918 (if (get-char-property (match-beginning 0) 'invisible)
17919 (throw 'exit t))))
17920 nil))))
17922 (defun org-metaup (&optional arg)
17923 "Move subtree up or move table row up.
17924 Calls `org-move-subtree-up' or `org-table-move-row' or
17925 `org-move-item-up', depending on context. See the individual commands
17926 for more information."
17927 (interactive "P")
17928 (cond
17929 ((run-hook-with-args-until-success 'org-metaup-hook))
17930 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
17931 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
17932 ((org-at-item-p) (call-interactively 'org-move-item-up))
17933 (t (transpose-lines 1) (beginning-of-line -1))))
17935 (defun org-metadown (&optional arg)
17936 "Move subtree down or move table row down.
17937 Calls `org-move-subtree-down' or `org-table-move-row' or
17938 `org-move-item-down', depending on context. See the individual
17939 commands for more information."
17940 (interactive "P")
17941 (cond
17942 ((run-hook-with-args-until-success 'org-metadown-hook))
17943 ((org-at-table-p) (call-interactively 'org-table-move-row))
17944 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
17945 ((org-at-item-p) (call-interactively 'org-move-item-down))
17946 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
17948 (defun org-shiftup (&optional arg)
17949 "Increase item in timestamp or increase priority of current headline.
17950 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
17951 depending on context. See the individual commands for more information."
17952 (interactive "P")
17953 (cond
17954 ((run-hook-with-args-until-success 'org-shiftup-hook))
17955 ((and org-support-shift-select (org-region-active-p))
17956 (org-call-for-shift-select 'previous-line))
17957 ((org-at-timestamp-p t)
17958 (call-interactively (if org-edit-timestamp-down-means-later
17959 'org-timestamp-down 'org-timestamp-up)))
17960 ((and (not (eq org-support-shift-select 'always))
17961 org-enable-priority-commands
17962 (org-on-heading-p))
17963 (call-interactively 'org-priority-up))
17964 ((and (not org-support-shift-select) (org-at-item-p))
17965 (call-interactively 'org-previous-item))
17966 ((org-clocktable-try-shift 'up arg))
17967 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
17968 (org-support-shift-select
17969 (org-call-for-shift-select 'previous-line))
17970 (t (org-shiftselect-error))))
17972 (defun org-shiftdown (&optional arg)
17973 "Decrease item in timestamp or decrease priority of current headline.
17974 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
17975 depending on context. See the individual commands for more information."
17976 (interactive "P")
17977 (cond
17978 ((run-hook-with-args-until-success 'org-shiftdown-hook))
17979 ((and org-support-shift-select (org-region-active-p))
17980 (org-call-for-shift-select 'next-line))
17981 ((org-at-timestamp-p t)
17982 (call-interactively (if org-edit-timestamp-down-means-later
17983 'org-timestamp-up 'org-timestamp-down)))
17984 ((and (not (eq org-support-shift-select 'always))
17985 org-enable-priority-commands
17986 (org-on-heading-p))
17987 (call-interactively 'org-priority-down))
17988 ((and (not org-support-shift-select) (org-at-item-p))
17989 (call-interactively 'org-next-item))
17990 ((org-clocktable-try-shift 'down arg))
17991 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
17992 (org-support-shift-select
17993 (org-call-for-shift-select 'next-line))
17994 (t (org-shiftselect-error))))
17996 (defun org-shiftright (&optional arg)
17997 "Cycle the thing at point or in the current line, depending on context.
17998 Depending on context, this does one of the following:
18000 - switch a timestamp at point one day into the future
18001 - on a headline, switch to the next TODO keyword.
18002 - on an item, switch entire list to the next bullet type
18003 - on a property line, switch to the next allowed value
18004 - on a clocktable definition line, move time block into the future"
18005 (interactive "P")
18006 (cond
18007 ((run-hook-with-args-until-success 'org-shiftright-hook))
18008 ((and org-support-shift-select (org-region-active-p))
18009 (org-call-for-shift-select 'forward-char))
18010 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
18011 ((and (not (eq org-support-shift-select 'always))
18012 (org-on-heading-p))
18013 (let ((org-inhibit-logging
18014 (not org-treat-S-cursor-todo-selection-as-state-change))
18015 (org-inhibit-blocking
18016 (not org-treat-S-cursor-todo-selection-as-state-change)))
18017 (org-call-with-arg 'org-todo 'right)))
18018 ((or (and org-support-shift-select
18019 (not (eq org-support-shift-select 'always))
18020 (org-at-item-bullet-p))
18021 (and (not org-support-shift-select) (org-at-item-p)))
18022 (org-call-with-arg 'org-cycle-list-bullet nil))
18023 ((and (not (eq org-support-shift-select 'always))
18024 (org-at-property-p))
18025 (call-interactively 'org-property-next-allowed-value))
18026 ((org-clocktable-try-shift 'right arg))
18027 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
18028 (org-support-shift-select
18029 (org-call-for-shift-select 'forward-char))
18030 (t (org-shiftselect-error))))
18032 (defun org-shiftleft (&optional arg)
18033 "Cycle the thing at point or in the current line, depending on context.
18034 Depending on context, this does one of the following:
18036 - switch a timestamp at point one day into the past
18037 - on a headline, switch to the previous TODO keyword.
18038 - on an item, switch entire list to the previous bullet type
18039 - on a property line, switch to the previous allowed value
18040 - on a clocktable definition line, move time block into the past"
18041 (interactive "P")
18042 (cond
18043 ((run-hook-with-args-until-success 'org-shiftleft-hook))
18044 ((and org-support-shift-select (org-region-active-p))
18045 (org-call-for-shift-select 'backward-char))
18046 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
18047 ((and (not (eq org-support-shift-select 'always))
18048 (org-on-heading-p))
18049 (let ((org-inhibit-logging
18050 (not org-treat-S-cursor-todo-selection-as-state-change))
18051 (org-inhibit-blocking
18052 (not org-treat-S-cursor-todo-selection-as-state-change)))
18053 (org-call-with-arg 'org-todo 'left)))
18054 ((or (and org-support-shift-select
18055 (not (eq org-support-shift-select 'always))
18056 (org-at-item-bullet-p))
18057 (and (not org-support-shift-select) (org-at-item-p)))
18058 (org-call-with-arg 'org-cycle-list-bullet 'previous))
18059 ((and (not (eq org-support-shift-select 'always))
18060 (org-at-property-p))
18061 (call-interactively 'org-property-previous-allowed-value))
18062 ((org-clocktable-try-shift 'left arg))
18063 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
18064 (org-support-shift-select
18065 (org-call-for-shift-select 'backward-char))
18066 (t (org-shiftselect-error))))
18068 (defun org-shiftcontrolright ()
18069 "Switch to next TODO set."
18070 (interactive)
18071 (cond
18072 ((and org-support-shift-select (org-region-active-p))
18073 (org-call-for-shift-select 'forward-word))
18074 ((and (not (eq org-support-shift-select 'always))
18075 (org-on-heading-p))
18076 (org-call-with-arg 'org-todo 'nextset))
18077 (org-support-shift-select
18078 (org-call-for-shift-select 'forward-word))
18079 (t (org-shiftselect-error))))
18081 (defun org-shiftcontrolleft ()
18082 "Switch to previous TODO set."
18083 (interactive)
18084 (cond
18085 ((and org-support-shift-select (org-region-active-p))
18086 (org-call-for-shift-select 'backward-word))
18087 ((and (not (eq org-support-shift-select 'always))
18088 (org-on-heading-p))
18089 (org-call-with-arg 'org-todo 'previousset))
18090 (org-support-shift-select
18091 (org-call-for-shift-select 'backward-word))
18092 (t (org-shiftselect-error))))
18094 (defun org-shiftcontrolup ()
18095 "Change timestamps synchronously up in CLOCK log lines."
18096 (interactive)
18097 (cond ((and (not org-support-shift-select)
18098 (org-at-clock-log-p)
18099 (org-at-timestamp-p t))
18100 (org-clock-timestamps-up))
18101 (t (org-shiftselect-error))))
18103 (defun org-shiftcontroldown ()
18104 "Change timestamps synchronously down in CLOCK log lines."
18105 (interactive)
18106 (cond ((and (not org-support-shift-select)
18107 (org-at-clock-log-p)
18108 (org-at-timestamp-p t))
18109 (org-clock-timestamps-down))
18110 (t (org-shiftselect-error))))
18112 (defun org-ctrl-c-ret ()
18113 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
18114 (interactive)
18115 (cond
18116 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
18117 (t (call-interactively 'org-insert-heading))))
18119 (defun org-find-visible ()
18120 (let ((s (point)))
18121 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
18122 (get-char-property s 'invisible)))
18124 (defun org-find-invisible ()
18125 (let ((s (point)))
18126 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
18127 (not (get-char-property s 'invisible))))
18130 (defun org-copy-visible (beg end)
18131 "Copy the visible parts of the region."
18132 (interactive "r")
18133 (let (snippets s)
18134 (save-excursion
18135 (save-restriction
18136 (narrow-to-region beg end)
18137 (setq s (goto-char (point-min)))
18138 (while (not (= (point) (point-max)))
18139 (goto-char (org-find-invisible))
18140 (push (buffer-substring s (point)) snippets)
18141 (setq s (goto-char (org-find-visible))))))
18142 (kill-new (apply 'concat (nreverse snippets)))))
18144 (defun org-copy-special ()
18145 "Copy region in table or copy current subtree.
18146 Calls `org-table-copy' or `org-copy-subtree', depending on context.
18147 See the individual commands for more information."
18148 (interactive)
18149 (call-interactively
18150 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
18152 (defun org-cut-special ()
18153 "Cut region in table or cut current subtree.
18154 Calls `org-table-copy' or `org-cut-subtree', depending on context.
18155 See the individual commands for more information."
18156 (interactive)
18157 (call-interactively
18158 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
18160 (defun org-paste-special (arg)
18161 "Paste rectangular region into table, or past subtree relative to level.
18162 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
18163 See the individual commands for more information."
18164 (interactive "P")
18165 (if (org-at-table-p)
18166 (org-table-paste-rectangle)
18167 (org-paste-subtree arg)))
18169 (defun org-edit-special (&optional arg)
18170 "Call a special editor for the stuff at point.
18171 When at a table, call the formula editor with `org-table-edit-formulas'.
18172 When at the first line of an src example, call `org-edit-src-code'.
18173 When in an #+include line, visit the include file. Otherwise call
18174 `ffap' to visit the file at point."
18175 (interactive)
18176 ;; possibly prep session before editing source
18177 (when arg
18178 (let* ((info (org-babel-get-src-block-info))
18179 (lang (nth 0 info))
18180 (params (nth 2 info))
18181 (session (cdr (assoc :session params))))
18182 (when (and info session) ;; we are in a source-code block with a session
18183 (funcall
18184 (intern (concat "org-babel-prep-session:" lang)) session params))))
18185 (cond ;; proceed with `org-edit-special'
18186 ((save-excursion
18187 (beginning-of-line 1)
18188 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
18189 (find-file (org-trim (match-string 1))))
18190 ((org-edit-src-code))
18191 ((org-edit-fixed-width-region))
18192 ((org-at-table.el-p)
18193 (org-edit-src-code))
18194 ((or (org-at-table-p)
18195 (save-excursion
18196 (beginning-of-line 1)
18197 (looking-at "[ \t]*#\\+TBLFM:")))
18198 (call-interactively 'org-table-edit-formulas))
18199 (t (call-interactively 'ffap))))
18201 (defvar org-table-coordinate-overlays) ; defined in org-table.el
18202 (defun org-ctrl-c-ctrl-c (&optional arg)
18203 "Set tags in headline, or update according to changed information at point.
18205 This command does many different things, depending on context:
18207 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
18208 this is what we do.
18210 - If the cursor is on a statistics cookie, update it.
18212 - If the cursor is in a headline, prompt for tags and insert them
18213 into the current line, aligned to `org-tags-column'. When called
18214 with prefix arg, realign all tags in the current buffer.
18216 - If the cursor is in one of the special #+KEYWORD lines, this
18217 triggers scanning the buffer for these lines and updating the
18218 information.
18220 - If the cursor is inside a table, realign the table. This command
18221 works even if the automatic table editor has been turned off.
18223 - If the cursor is on a #+TBLFM line, re-apply the formulas to
18224 the entire table.
18226 - If the cursor is at a footnote reference or definition, jump to
18227 the corresponding definition or references, respectively.
18229 - If the cursor is a the beginning of a dynamic block, update it.
18231 - If the current buffer is a capture buffer, close note and file it.
18233 - If the cursor is on a <<<target>>>, update radio targets and
18234 corresponding links in this buffer.
18236 - If the cursor is on a numbered item in a plain list, renumber the
18237 ordered list.
18239 - If the cursor is on a checkbox, toggle it.
18241 - If the cursor is on a code block, evaluate it. The variable
18242 `org-confirm-babel-evaluate' can be used to control prompting
18243 before code block evaluation, by default every code block
18244 evaluation requires confirmation. Code block evaluation can be
18245 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
18246 (interactive "P")
18247 (let ((org-enable-table-editor t))
18248 (cond
18249 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
18250 org-occur-highlights
18251 org-latex-fragment-image-overlays)
18252 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
18253 (org-remove-occur-highlights)
18254 (org-remove-latex-fragment-image-overlays)
18255 (message "Temporary highlights/overlays removed from current buffer"))
18256 ((and (local-variable-p 'org-finish-function (current-buffer))
18257 (fboundp org-finish-function))
18258 (funcall org-finish-function))
18259 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
18260 ((org-in-regexp org-ts-regexp-both)
18261 (org-timestamp-change 0 'day))
18262 ((or (looking-at org-property-start-re)
18263 (org-at-property-p))
18264 (call-interactively 'org-property-action))
18265 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
18266 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
18267 (or (org-on-heading-p) (org-at-item-p)))
18268 (call-interactively 'org-update-statistics-cookies))
18269 ((org-on-heading-p) (call-interactively 'org-set-tags))
18270 ((org-at-table.el-p)
18271 (message "Use C-c ' to edit table.el tables"))
18272 ((org-at-table-p)
18273 (org-table-maybe-eval-formula)
18274 (if arg
18275 (call-interactively 'org-table-recalculate)
18276 (org-table-maybe-recalculate-line))
18277 (call-interactively 'org-table-align)
18278 (orgtbl-send-table 'maybe))
18279 ((or (org-footnote-at-reference-p)
18280 (org-footnote-at-definition-p))
18281 (call-interactively 'org-footnote-action))
18282 ((org-at-item-checkbox-p)
18283 ;; Cursor at a checkbox: repair list and update checkboxes. Send
18284 ;; list only if at top item.
18285 (let* ((cbox (match-string 1))
18286 (struct (org-list-struct))
18287 (old-struct (copy-tree struct))
18288 (parents (org-list-parents-alist struct))
18289 (orderedp (org-entry-get nil "ORDERED"))
18290 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
18291 block-item)
18292 ;; Use a light version of `org-toggle-checkbox' to avoid
18293 ;; computing list structure twice.
18294 (org-list-set-checkbox (point-at-bol) struct
18295 (cond
18296 ((equal arg '(16)) "[-]")
18297 ((equal arg '(4)) nil)
18298 ((equal "[X]" cbox) "[ ]")
18299 (t "[X]")))
18300 ;; Replicate `org-list-write-struct', while grabbing a return
18301 ;; value from `org-list-struct-fix-box'.
18302 (org-list-struct-fix-ind struct parents 2)
18303 (org-list-struct-fix-item-end struct)
18304 (let ((prevs (org-list-prevs-alist struct)))
18305 (org-list-struct-fix-bul struct prevs)
18306 (org-list-struct-fix-ind struct parents)
18307 (setq block-item
18308 (org-list-struct-fix-box struct parents prevs orderedp)))
18309 (org-list-struct-apply-struct struct old-struct)
18310 (org-update-checkbox-count-maybe)
18311 (when block-item
18312 (message
18313 "Checkboxes were removed due to unchecked box at line %d"
18314 (org-current-line block-item)))
18315 (when firstp (org-list-send-list 'maybe))))
18316 ((org-at-item-p)
18317 ;; Cursor at an item: repair list. Do checkbox related actions
18318 ;; only if function was called with an argument. Send list only
18319 ;; if at top item.
18320 (let* ((struct (org-list-struct))
18321 (firstp (= (org-list-get-top-point struct) (point-at-bol))))
18322 (when arg (org-list-set-checkbox (point-at-bol) struct "[ ]"))
18323 (org-list-write-struct struct (org-list-parents-alist struct))
18324 (when arg (org-update-checkbox-count-maybe))
18325 (when firstp (org-list-send-list 'maybe))))
18326 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
18327 ;; Dynamic block
18328 (beginning-of-line 1)
18329 (save-excursion (org-update-dblock)))
18330 ((save-excursion
18331 (beginning-of-line 1)
18332 (looking-at "[ \t]*#\\+\\([A-Z]+\\)"))
18333 (cond
18334 ((equal (match-string 1) "TBLFM")
18335 ;; Recalculate the table before this line
18336 (save-excursion
18337 (beginning-of-line 1)
18338 (skip-chars-backward " \r\n\t")
18339 (if (org-at-table-p)
18340 (org-call-with-arg 'org-table-recalculate (or arg t)))))
18342 (let ((org-inhibit-startup-visibility-stuff t)
18343 (org-startup-align-all-tables nil))
18344 (when (boundp 'org-table-coordinate-overlays)
18345 (mapc 'delete-overlay org-table-coordinate-overlays)
18346 (setq org-table-coordinate-overlays nil))
18347 (org-save-outline-visibility 'use-markers (org-mode-restart)))
18348 (message "Local setup has been refreshed"))))
18349 ((org-clock-update-time-maybe))
18351 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
18352 (error "C-c C-c can do nothing useful at this location"))))))
18354 (defun org-mode-restart ()
18355 "Restart Org-mode, to scan again for special lines.
18356 Also updates the keyword regular expressions."
18357 (interactive)
18358 (org-mode)
18359 (message "Org-mode restarted"))
18361 (defun org-kill-note-or-show-branches ()
18362 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
18363 (interactive)
18364 (if (not org-finish-function)
18365 (progn
18366 (hide-subtree)
18367 (call-interactively 'show-branches))
18368 (let ((org-note-abort t))
18369 (funcall org-finish-function))))
18371 (defun org-return (&optional indent)
18372 "Goto next table row or insert a newline.
18373 Calls `org-table-next-row' or `newline', depending on context.
18374 See the individual commands for more information."
18375 (interactive)
18376 (cond
18377 ((bobp) (if indent (newline-and-indent) (newline)))
18378 ((org-at-table-p)
18379 (org-table-justify-field-maybe)
18380 (call-interactively 'org-table-next-row))
18381 ;; when `newline-and-indent' is called within a list, make sure
18382 ;; text moved stays inside the item.
18383 ((and (org-in-item-p) indent)
18384 (if (and (org-at-item-p) (>= (point) (match-end 0)))
18385 (progn
18386 (save-match-data (newline))
18387 (org-indent-line-to (length (match-string 0))))
18388 (let ((ind (org-get-indentation)))
18389 (newline)
18390 (if (org-looking-back org-list-end-re)
18391 (org-indent-line-function)
18392 (org-indent-line-to ind)))))
18393 ((and org-return-follows-link
18394 (let ((tprop (get-text-property (point) 'face)))
18395 (or (eq tprop 'org-link)
18396 (and (listp tprop) (memq 'org-link tprop)))))
18397 (call-interactively 'org-open-at-point))
18398 ((and (org-at-heading-p)
18399 (looking-at
18400 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
18401 (org-show-entry)
18402 (end-of-line 1)
18403 (newline))
18404 (t (if indent (newline-and-indent) (newline)))))
18406 (defun org-return-indent ()
18407 "Goto next table row or insert a newline and indent.
18408 Calls `org-table-next-row' or `newline-and-indent', depending on
18409 context. See the individual commands for more information."
18410 (interactive)
18411 (org-return t))
18413 (defun org-ctrl-c-star ()
18414 "Compute table, or change heading status of lines.
18415 Calls `org-table-recalculate' or `org-toggle-heading',
18416 depending on context."
18417 (interactive)
18418 (cond
18419 ((org-at-table-p)
18420 (call-interactively 'org-table-recalculate))
18422 ;; Convert all lines in region to list items
18423 (call-interactively 'org-toggle-heading))))
18425 (defun org-ctrl-c-minus ()
18426 "Insert separator line in table or modify bullet status of line.
18427 Also turns a plain line or a region of lines into list items.
18428 Calls `org-table-insert-hline', `org-toggle-item', or
18429 `org-cycle-list-bullet', depending on context."
18430 (interactive)
18431 (cond
18432 ((org-at-table-p)
18433 (call-interactively 'org-table-insert-hline))
18434 ((org-region-active-p)
18435 (call-interactively 'org-toggle-item))
18436 ((org-in-item-p)
18437 (call-interactively 'org-cycle-list-bullet))
18439 (call-interactively 'org-toggle-item))))
18441 (defun org-toggle-item (arg)
18442 "Convert headings or normal lines to items, items to normal lines.
18443 If there is no active region, only the current line is considered.
18445 If the first non blank line in the region is an headline, convert
18446 all headlines to items, shifting text accordingly.
18448 If it is an item, convert all items to normal lines.
18450 If it is normal text, change region into an item. With a prefix
18451 argument ARG, change each line in region into an item."
18452 (interactive "P")
18453 (let ((shift-text
18454 (function
18455 ;; Shift text in current section to IND, from point to END.
18456 ;; The function leaves point to END line.
18457 (lambda (ind end)
18458 (let ((min-i 1000) (end (copy-marker end)))
18459 ;; First determine the minimum indentation (MIN-I) of
18460 ;; the text.
18461 (save-excursion
18462 (catch 'exit
18463 (while (< (point) end)
18464 (let ((i (org-get-indentation)))
18465 (cond
18466 ;; Skip blank lines and inline tasks.
18467 ((looking-at "^[ \t]*$"))
18468 ((looking-at org-outline-regexp-bol))
18469 ;; We can't find less than 0 indentation.
18470 ((zerop i) (throw 'exit (setq min-i 0)))
18471 ((< i min-i) (setq min-i i))))
18472 (forward-line))))
18473 ;; Then indent each line so that a line indented to
18474 ;; MIN-I becomes indented to IND. Ignore blank lines
18475 ;; and inline tasks in the process.
18476 (let ((delta (- ind min-i)))
18477 (while (< (point) end)
18478 (unless (or (looking-at "^[ \t]*$")
18479 (looking-at org-outline-regexp-bol))
18480 (org-indent-line-to (+ (org-get-indentation) delta)))
18481 (forward-line)))))))
18482 (skip-blanks
18483 (function
18484 ;; Return beginning of first non-blank line, starting from
18485 ;; line at POS.
18486 (lambda (pos)
18487 (save-excursion
18488 (goto-char pos)
18489 (skip-chars-forward " \r\t\n")
18490 (point-at-bol)))))
18491 beg end)
18492 ;; Determine boundaries of changes.
18493 (if (org-region-active-p)
18494 (setq beg (funcall skip-blanks (region-beginning))
18495 end (copy-marker (region-end)))
18496 (setq beg (funcall skip-blanks (point-at-bol))
18497 end (copy-marker (point-at-eol))))
18498 ;; Depending on the starting line, choose an action on the text
18499 ;; between BEG and END.
18500 (org-with-limited-levels
18501 (save-excursion
18502 (goto-char beg)
18503 (cond
18504 ;; Case 1. Start at an item: de-itemize. Note that it only
18505 ;; happens when a region is active: `org-ctrl-c-minus'
18506 ;; would call `org-cycle-list-bullet' otherwise.
18507 ((org-at-item-p)
18508 (while (< (point) end)
18509 (when (org-at-item-p)
18510 (skip-chars-forward " \t")
18511 (delete-region (point) (match-end 0)))
18512 (forward-line)))
18513 ;; Case 2. Start at an heading: convert to items.
18514 ((org-on-heading-p)
18515 (let* ((bul (org-list-bullet-string "-"))
18516 (bul-len (length bul))
18517 ;; Indentation of the first heading. It should be
18518 ;; relative to the indentation of its parent, if any.
18519 (start-ind (save-excursion
18520 (cond
18521 ((not org-adapt-indentation) 0)
18522 ((not (outline-previous-heading)) 0)
18523 (t (length (match-string 0))))))
18524 ;; Level of first heading. Further headings will be
18525 ;; compared to it to determine hierarchy in the list.
18526 (ref-level (org-reduced-level (org-outline-level))))
18527 (while (< (point) end)
18528 (let* ((level (org-reduced-level (org-outline-level)))
18529 (delta (max 0 (- level ref-level))))
18530 ;; If current headline is less indented than the first
18531 ;; one, set it as reference, in order to preserve
18532 ;; subtrees.
18533 (when (< level ref-level) (setq ref-level level))
18534 (replace-match bul t t)
18535 (org-indent-line-to (+ start-ind (* delta bul-len)))
18536 ;; Ensure all text down to END (or SECTION-END) belongs
18537 ;; to the newly created item.
18538 (let ((section-end (save-excursion
18539 (or (outline-next-heading) (point)))))
18540 (forward-line)
18541 (funcall shift-text
18542 (+ start-ind (* (1+ delta) bul-len))
18543 (min end section-end)))))))
18544 ;; Case 3. Normal line with ARG: turn each non-item line into
18545 ;; an item.
18546 (arg
18547 (while (< (point) end)
18548 (unless (or (org-on-heading-p) (org-at-item-p))
18549 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
18550 (replace-match
18551 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
18552 (forward-line)))
18553 ;; Case 4. Normal line without ARG: make the first line of
18554 ;; region an item, and shift indentation of others
18555 ;; lines to set them as item's body.
18556 (t (let* ((bul (org-list-bullet-string "-"))
18557 (bul-len (length bul))
18558 (ref-ind (org-get-indentation)))
18559 (skip-chars-forward " \t")
18560 (insert bul)
18561 (forward-line)
18562 (while (< (point) end)
18563 ;; Ensure that lines less indented than first one
18564 ;; still get included in item body.
18565 (funcall shift-text
18566 (+ ref-ind bul-len)
18567 (min end (save-excursion (or (outline-next-heading)
18568 (point)))))
18569 (forward-line)))))))))
18571 (defun org-toggle-heading (&optional nstars)
18572 "Convert headings to normal text, or items or text to headings.
18573 If there is no active region, only the current line is considered.
18575 If the first non blank line is an headline, remove the stars from
18576 all headlines in the region.
18578 If it is a plain list item, turn all plain list items into headings.
18580 If it is a normal line, turn each and every normal line (i.e. not
18581 an heading or an item) in the region into a heading.
18583 When converting a line into a heading, the number of stars is chosen
18584 such that the lines become children of the current entry. However,
18585 when a prefix argument is given, its value determines the number of
18586 stars to add."
18587 (interactive "P")
18588 (let ((skip-blanks
18589 (function
18590 ;; Return beginning of first non-blank line, starting from
18591 ;; line at POS.
18592 (lambda (pos)
18593 (save-excursion
18594 (goto-char pos)
18595 (skip-chars-forward " \r\t\n")
18596 (point-at-bol)))))
18597 beg end)
18598 ;; Determine boundaries of changes. If region ends at a bol, do
18599 ;; not consider the last line to be in the region.
18600 (if (org-region-active-p)
18601 (setq beg (funcall skip-blanks (region-beginning))
18602 end (copy-marker (save-excursion
18603 (goto-char (region-end))
18604 (if (bolp) (point) (point-at-eol)))))
18605 (setq beg (funcall skip-blanks (point-at-bol))
18606 end (copy-marker (point-at-eol))))
18607 ;; Ensure inline tasks don't count as headings.
18608 (org-with-limited-levels
18609 (save-excursion
18610 (goto-char beg)
18611 (cond
18612 ;; Case 1. Started at an heading: de-star headings.
18613 ((org-on-heading-p)
18614 (while (< (point) end)
18615 (when (org-on-heading-p t)
18616 (looking-at org-outline-regexp) (replace-match ""))
18617 (forward-line)))
18618 ;; Case 2. Started at an item: change items into headlines.
18619 ;; One star will be added by `org-list-to-subtree'.
18620 ((org-at-item-p)
18621 (let* ((stars (make-string
18622 (if nstars
18623 ;; subtract the star that will be added again by
18624 ;; `org-list-to-subtree'
18625 (1- (prefix-numeric-value current-prefix-arg))
18626 (or (org-current-level) 0))
18627 ?*))
18628 (add-stars
18629 (cond (nstars "") ; stars from prefix only
18630 ((equal stars "") "") ; before first heading
18631 (org-odd-levels-only "*") ; inside heading, odd
18632 (t "")))) ; inside heading, oddeven
18633 (while (< (point) end)
18634 (when (org-at-item-p)
18635 ;; Pay attention to cases when region ends before list.
18636 (let* ((struct (org-list-struct))
18637 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
18638 (save-restriction
18639 (narrow-to-region (point) list-end)
18640 (insert
18641 (org-list-to-subtree
18642 (org-list-parse-list t)
18643 '(:istart (concat stars add-stars (funcall get-stars depth))
18644 :icount (concat stars add-stars (funcall get-stars depth))))))))
18645 (forward-line))))
18646 ;; Case 3. Started at normal text: make every line an heading,
18647 ;; skipping headlines and items.
18648 (t (let* ((stars (make-string
18649 (if nstars
18650 (prefix-numeric-value current-prefix-arg)
18651 (or (org-current-level) 0))
18652 ?*))
18653 (add-stars
18654 (cond (nstars "") ; stars from prefix only
18655 ((equal stars "") "*") ; before first heading
18656 (org-odd-levels-only "**") ; inside heading, odd
18657 (t "*"))) ; inside heading, oddeven
18658 (rpl (concat stars add-stars " ")))
18659 (while (< (point) end)
18660 (when (and (not (org-on-heading-p)) (not (org-at-item-p))
18661 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
18662 (replace-match (concat rpl (match-string 2))))
18663 (forward-line)))))))))
18665 (defun org-meta-return (&optional arg)
18666 "Insert a new heading or wrap a region in a table.
18667 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
18668 See the individual commands for more information."
18669 (interactive "P")
18670 (cond
18671 ((run-hook-with-args-until-success 'org-metareturn-hook))
18672 ((org-at-table-p)
18673 (call-interactively 'org-table-wrap-region))
18674 (t (call-interactively 'org-insert-heading))))
18676 ;;; Menu entries
18678 ;; Define the Org-mode menus
18679 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
18680 '("Tbl"
18681 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
18682 ["Next Field" org-cycle (org-at-table-p)]
18683 ["Previous Field" org-shifttab (org-at-table-p)]
18684 ["Next Row" org-return (org-at-table-p)]
18685 "--"
18686 ["Blank Field" org-table-blank-field (org-at-table-p)]
18687 ["Edit Field" org-table-edit-field (org-at-table-p)]
18688 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
18689 "--"
18690 ("Column"
18691 ["Move Column Left" org-metaleft (org-at-table-p)]
18692 ["Move Column Right" org-metaright (org-at-table-p)]
18693 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
18694 ["Insert Column" org-shiftmetaright (org-at-table-p)])
18695 ("Row"
18696 ["Move Row Up" org-metaup (org-at-table-p)]
18697 ["Move Row Down" org-metadown (org-at-table-p)]
18698 ["Delete Row" org-shiftmetaup (org-at-table-p)]
18699 ["Insert Row" org-shiftmetadown (org-at-table-p)]
18700 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
18701 "--"
18702 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
18703 ("Rectangle"
18704 ["Copy Rectangle" org-copy-special (org-at-table-p)]
18705 ["Cut Rectangle" org-cut-special (org-at-table-p)]
18706 ["Paste Rectangle" org-paste-special (org-at-table-p)]
18707 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
18708 "--"
18709 ("Calculate"
18710 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
18711 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
18712 ["Edit Formulas" org-edit-special (org-at-table-p)]
18713 "--"
18714 ["Recalculate line" org-table-recalculate (org-at-table-p)]
18715 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
18716 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
18717 "--"
18718 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
18719 "--"
18720 ["Sum Column/Rectangle" org-table-sum
18721 (or (org-at-table-p) (org-region-active-p))]
18722 ["Which Column?" org-table-current-column (org-at-table-p)])
18723 ["Debug Formulas"
18724 org-table-toggle-formula-debugger
18725 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
18726 ["Show Col/Row Numbers"
18727 org-table-toggle-coordinate-overlays
18728 :style toggle
18729 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
18730 "--"
18731 ["Create" org-table-create (and (not (org-at-table-p))
18732 org-enable-table-editor)]
18733 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
18734 ["Import from File" org-table-import (not (org-at-table-p))]
18735 ["Export to File" org-table-export (org-at-table-p)]
18736 "--"
18737 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
18739 (easy-menu-define org-org-menu org-mode-map "Org menu"
18740 '("Org"
18741 ("Show/Hide"
18742 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
18743 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
18744 ["Sparse Tree..." org-sparse-tree t]
18745 ["Reveal Context" org-reveal t]
18746 ["Show All" show-all t]
18747 "--"
18748 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
18749 "--"
18750 ["New Heading" org-insert-heading t]
18751 ("Navigate Headings"
18752 ["Up" outline-up-heading t]
18753 ["Next" outline-next-visible-heading t]
18754 ["Previous" outline-previous-visible-heading t]
18755 ["Next Same Level" outline-forward-same-level t]
18756 ["Previous Same Level" outline-backward-same-level t]
18757 "--"
18758 ["Jump" org-goto t])
18759 ("Edit Structure"
18760 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
18761 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
18762 "--"
18763 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
18764 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
18765 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
18766 "--"
18767 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
18768 "--"
18769 ["Copy visible text" org-copy-visible t]
18770 "--"
18771 ["Promote Heading" org-metaleft (not (org-at-table-p))]
18772 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
18773 ["Demote Heading" org-metaright (not (org-at-table-p))]
18774 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
18775 "--"
18776 ["Sort Region/Children" org-sort (not (org-at-table-p))]
18777 "--"
18778 ["Convert to odd levels" org-convert-to-odd-levels t]
18779 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
18780 ("Editing"
18781 ["Emphasis..." org-emphasize t]
18782 ["Edit Source Example" org-edit-special t]
18783 "--"
18784 ["Footnote new/jump" org-footnote-action t]
18785 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
18786 ("Archive"
18787 ["Archive (default method)" org-archive-subtree-default t]
18788 "--"
18789 ["Move Subtree to Archive file" org-advertized-archive-subtree t]
18790 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
18791 ["Move subtree to Archive sibling" org-archive-to-archive-sibling t]
18793 "--"
18794 ("Hyperlinks"
18795 ["Store Link (Global)" org-store-link t]
18796 ["Find existing link to here" org-occur-link-in-agenda-files t]
18797 ["Insert Link" org-insert-link t]
18798 ["Follow Link" org-open-at-point t]
18799 "--"
18800 ["Next link" org-next-link t]
18801 ["Previous link" org-previous-link t]
18802 "--"
18803 ["Descriptive Links"
18804 org-toggle-link-display
18805 :style radio
18806 :selected org-descriptive-links
18808 ["Literal Links"
18809 org-toggle-link-display
18810 :style radio
18811 :selected (not org-descriptive-links)])
18812 "--"
18813 ("TODO Lists"
18814 ["TODO/DONE/-" org-todo t]
18815 ("Select keyword"
18816 ["Next keyword" org-shiftright (org-on-heading-p)]
18817 ["Previous keyword" org-shiftleft (org-on-heading-p)]
18818 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
18819 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
18820 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
18821 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
18822 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
18823 "--"
18824 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
18825 :selected org-enforce-todo-dependencies :style toggle :active t]
18826 "Settings for tree at point"
18827 ["Do Children sequentially" org-toggle-ordered-property :style radio
18828 :selected (org-entry-get nil "ORDERED")
18829 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
18830 ["Do Children parallel" org-toggle-ordered-property :style radio
18831 :selected (not (org-entry-get nil "ORDERED"))
18832 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
18833 "--"
18834 ["Set Priority" org-priority t]
18835 ["Priority Up" org-shiftup t]
18836 ["Priority Down" org-shiftdown t]
18837 "--"
18838 ["Get news from all feeds" org-feed-update-all t]
18839 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
18840 ["Customize feeds" (customize-variable 'org-feed-alist) t])
18841 ("TAGS and Properties"
18842 ["Set Tags" org-set-tags-command t]
18843 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
18844 "--"
18845 ["Set property" org-set-property t]
18846 ["Column view of properties" org-columns t]
18847 ["Insert Column View DBlock" org-insert-columns-dblock t])
18848 ("Dates and Scheduling"
18849 ["Timestamp" org-time-stamp t]
18850 ["Timestamp (inactive)" org-time-stamp-inactive t]
18851 ("Change Date"
18852 ["1 Day Later" org-shiftright t]
18853 ["1 Day Earlier" org-shiftleft t]
18854 ["1 ... Later" org-shiftup t]
18855 ["1 ... Earlier" org-shiftdown t])
18856 ["Compute Time Range" org-evaluate-time-range t]
18857 ["Schedule Item" org-schedule t]
18858 ["Deadline" org-deadline t]
18859 "--"
18860 ["Custom time format" org-toggle-time-stamp-overlays
18861 :style radio :selected org-display-custom-times]
18862 "--"
18863 ["Goto Calendar" org-goto-calendar t]
18864 ["Date from Calendar" org-date-from-calendar t]
18865 "--"
18866 ["Start/Restart Timer" org-timer-start t]
18867 ["Pause/Continue Timer" org-timer-pause-or-continue t]
18868 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
18869 ["Insert Timer String" org-timer t]
18870 ["Insert Timer Item" org-timer-item t])
18871 ("Logging work"
18872 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
18873 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
18874 ["Clock out" org-clock-out t]
18875 ["Clock cancel" org-clock-cancel t]
18876 "--"
18877 ["Mark as default task" org-clock-mark-default-task t]
18878 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
18879 ["Goto running clock" org-clock-goto t]
18880 "--"
18881 ["Display times" org-clock-display t]
18882 ["Create clock table" org-clock-report t]
18883 "--"
18884 ["Record DONE time"
18885 (progn (setq org-log-done (not org-log-done))
18886 (message "Switching to %s will %s record a timestamp"
18887 (car org-done-keywords)
18888 (if org-log-done "automatically" "not")))
18889 :style toggle :selected org-log-done])
18890 "--"
18891 ["Agenda Command..." org-agenda t]
18892 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
18893 ("File List for Agenda")
18894 ("Special views current file"
18895 ["TODO Tree" org-show-todo-tree t]
18896 ["Check Deadlines" org-check-deadlines t]
18897 ["Timeline" org-timeline t]
18898 ["Tags/Property tree" org-match-sparse-tree t])
18899 "--"
18900 ["Export/Publish..." org-export t]
18901 ("LaTeX"
18902 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
18903 :selected org-cdlatex-mode]
18904 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
18905 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
18906 ["Modify math symbol" org-cdlatex-math-modify
18907 (org-inside-LaTeX-fragment-p)]
18908 ["Insert citation" org-reftex-citation t]
18909 "--"
18910 ["Template for BEAMER" org-insert-beamer-options-template t])
18911 "--"
18912 ("MobileOrg"
18913 ["Push Files and Views" org-mobile-push t]
18914 ["Get Captured and Flagged" org-mobile-pull t]
18915 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
18916 "--"
18917 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
18918 "--"
18919 ("Documentation"
18920 ["Show Version" org-version t]
18921 ["Info Documentation" org-info t])
18922 ("Customize"
18923 ["Browse Org Group" org-customize t]
18924 "--"
18925 ["Expand This Menu" org-create-customize-menu
18926 (fboundp 'customize-menu-create)])
18927 ["Send bug report" org-submit-bug-report t]
18928 "--"
18929 ("Refresh/Reload"
18930 ["Refresh setup current buffer" org-mode-restart t]
18931 ["Reload Org (after update)" org-reload t]
18932 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
18935 (defun org-info (&optional node)
18936 "Read documentation for Org-mode in the info system.
18937 With optional NODE, go directly to that node."
18938 (interactive)
18939 (info (format "(org)%s" (or node ""))))
18941 ;;;###autoload
18942 (defun org-submit-bug-report ()
18943 "Submit a bug report on Org-mode via mail.
18945 Don't hesitate to report any problems or inaccurate documentation.
18947 If you don't have setup sending mail from (X)Emacs, please copy the
18948 output buffer into your mail program, as it gives us important
18949 information about your Org-mode version and configuration."
18950 (interactive)
18951 (require 'reporter)
18952 (org-load-modules-maybe)
18953 (org-require-autoloaded-modules)
18954 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
18955 (reporter-submit-bug-report
18956 "emacs-orgmode@gnu.org"
18957 (org-version)
18958 (let (list)
18959 (save-window-excursion
18960 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
18961 (delete-other-windows)
18962 (erase-buffer)
18963 (insert "You are about to submit a bug report to the Org-mode mailing list.
18965 We would like to add your full Org-mode and Outline configuration to the
18966 bug report. This greatly simplifies the work of the maintainer and
18967 other experts on the mailing list.
18969 HOWEVER, some variables you have customized may contain private
18970 information. The names of customers, colleagues, or friends, might
18971 appear in the form of file names, tags, todo states, or search strings.
18972 If you answer yes to the prompt, you might want to check and remove
18973 such private information before sending the email.")
18974 (add-text-properties (point-min) (point-max) '(face org-warning))
18975 (when (yes-or-no-p "Include your Org-mode configuration ")
18976 (mapatoms
18977 (lambda (v)
18978 (and (boundp v)
18979 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
18980 (or (and (symbol-value v)
18981 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
18982 (and
18983 (get v 'custom-type) (get v 'standard-value)
18984 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
18985 (push v list)))))
18986 (kill-buffer (get-buffer "*Warn about privacy*"))
18987 list))
18988 nil nil
18989 "Remember to cover the basics, that is, what you expected to happen and
18990 what in fact did happen. You don't know how to make a good report? See
18992 http://orgmode.org/manual/Feedback.html#Feedback
18994 Your bug report will be posted to the Org-mode mailing list.
18995 ------------------------------------------------------------------------")
18996 (save-excursion
18997 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
18998 (replace-match "\\1Bug: \\3 [\\2]")))))
19001 (defun org-install-agenda-files-menu ()
19002 (let ((bl (buffer-list)))
19003 (save-excursion
19004 (while bl
19005 (set-buffer (pop bl))
19006 (if (eq major-mode 'org-mode) (setq bl nil)))
19007 (when (eq major-mode 'org-mode)
19008 (easy-menu-change
19009 '("Org") "File List for Agenda"
19010 (append
19011 (list
19012 ["Edit File List" (org-edit-agenda-file-list) t]
19013 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
19014 ["Remove Current File from List" org-remove-file t]
19015 ["Cycle through agenda files" org-cycle-agenda-files t]
19016 ["Occur in all agenda files" org-occur-in-agenda-files t]
19017 "--")
19018 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
19020 ;;;; Documentation
19022 ;;;###autoload
19023 (defun org-require-autoloaded-modules ()
19024 (interactive)
19025 (mapc 'require
19026 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
19027 org-docbook org-exp org-html org-icalendar
19028 org-id org-latex
19029 org-publish org-remember org-table
19030 org-timer org-xoxo)))
19032 ;;;###autoload
19033 (defun org-reload (&optional uncompiled)
19034 "Reload all org lisp files.
19035 With prefix arg UNCOMPILED, load the uncompiled versions."
19036 (interactive "P")
19037 (require 'find-func)
19038 (let* ((file-re "^\\(org\\|orgtbl\\)\\(\\.el\\|-.*\\.el\\)")
19039 (dir-org (file-name-directory (org-find-library-name "org")))
19040 (dir-org-contrib (ignore-errors
19041 (file-name-directory
19042 (org-find-library-name "org-contribdir"))))
19043 (babel-files
19044 (mapcar (lambda (el) (concat "ob" (when el (format "-%s" el)) ".el"))
19045 (append (list nil "comint" "eval" "exp" "keys"
19046 "lob" "ref" "table" "tangle")
19047 (delq nil
19048 (mapcar
19049 (lambda (lang)
19050 (when (cdr lang) (symbol-name (car lang))))
19051 org-babel-load-languages)))))
19052 (files
19053 (append (directory-files dir-org t file-re)
19054 babel-files
19055 (and dir-org-contrib
19056 (directory-files dir-org-contrib t file-re))))
19057 (remove-re (concat (if (featurep 'xemacs)
19058 "org-colview" "org-colview-xemacs")
19059 "\\'")))
19060 (setq files (mapcar 'file-name-sans-extension files))
19061 (setq files (mapcar
19062 (lambda (x) (if (string-match remove-re x) nil x))
19063 files))
19064 (setq files (delq nil files))
19065 (mapc
19066 (lambda (f)
19067 (when (featurep (intern (file-name-nondirectory f)))
19068 (if (and (not uncompiled)
19069 (file-exists-p (concat f ".elc")))
19070 (load (concat f ".elc") nil nil t)
19071 (load (concat f ".el") nil nil t))))
19072 files))
19073 (org-version))
19075 ;;;###autoload
19076 (defun org-customize ()
19077 "Call the customize function with org as argument."
19078 (interactive)
19079 (org-load-modules-maybe)
19080 (org-require-autoloaded-modules)
19081 (customize-browse 'org))
19083 (defun org-create-customize-menu ()
19084 "Create a full customization menu for Org-mode, insert it into the menu."
19085 (interactive)
19086 (org-load-modules-maybe)
19087 (org-require-autoloaded-modules)
19088 (if (fboundp 'customize-menu-create)
19089 (progn
19090 (easy-menu-change
19091 '("Org") "Customize"
19092 `(["Browse Org group" org-customize t]
19093 "--"
19094 ,(customize-menu-create 'org)
19095 ["Set" Custom-set t]
19096 ["Save" Custom-save t]
19097 ["Reset to Current" Custom-reset-current t]
19098 ["Reset to Saved" Custom-reset-saved t]
19099 ["Reset to Standard Settings" Custom-reset-standard t]))
19100 (message "\"Org\"-menu now contains full customization menu"))
19101 (error "Cannot expand menu (outdated version of cus-edit.el)")))
19103 ;;;; Miscellaneous stuff
19105 ;;; Generally useful functions
19107 (defun org-get-at-bol (property)
19108 "Get text property PROPERTY at beginning of line."
19109 (get-text-property (point-at-bol) property))
19111 (defun org-find-text-property-in-string (prop s)
19112 "Return the first non-nil value of property PROP in string S."
19113 (or (get-text-property 0 prop s)
19114 (get-text-property (or (next-single-property-change 0 prop s) 0)
19115 prop s)))
19117 (defun org-display-warning (message) ;; Copied from Emacs-Muse
19118 "Display the given MESSAGE as a warning."
19119 (if (fboundp 'display-warning)
19120 (display-warning 'org message
19121 (if (featurep 'xemacs) 'warning :warning))
19122 (let ((buf (get-buffer-create "*Org warnings*")))
19123 (with-current-buffer buf
19124 (goto-char (point-max))
19125 (insert "Warning (Org): " message)
19126 (unless (bolp)
19127 (newline)))
19128 (display-buffer buf)
19129 (sit-for 0))))
19131 (defun org-eval (form)
19132 "Eval FORM and return result."
19133 (condition-case error
19134 (eval form)
19135 (error (format "%%![Error: %s]" error))))
19137 (defun org-in-commented-line ()
19138 "Is point in a line starting with `#'?"
19139 (equal (char-after (point-at-bol)) ?#))
19141 (defun org-in-indented-comment-line ()
19142 "Is point in a line starting with `#' after some white space?"
19143 (save-excursion
19144 (save-match-data
19145 (goto-char (point-at-bol))
19146 (looking-at "[ \t]*#"))))
19148 (defun org-in-verbatim-emphasis ()
19149 (save-match-data
19150 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
19152 (defun org-goto-marker-or-bmk (marker &optional bookmark)
19153 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
19154 (if (and marker (marker-buffer marker)
19155 (buffer-live-p (marker-buffer marker)))
19156 (progn
19157 (org-pop-to-buffer-same-window (marker-buffer marker))
19158 (if (or (> marker (point-max)) (< marker (point-min)))
19159 (widen))
19160 (goto-char marker)
19161 (org-show-context 'org-goto))
19162 (if bookmark
19163 (bookmark-jump bookmark)
19164 (error "Cannot find location"))))
19166 (defun org-quote-csv-field (s)
19167 "Quote field for inclusion in CSV material."
19168 (if (string-match "[\",]" s)
19169 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
19172 (defun org-force-self-insert (N)
19173 "Needed to enforce self-insert under remapping."
19174 (interactive "p")
19175 (self-insert-command N))
19177 (defun org-string-width (s)
19178 "Compute width of string, ignoring invisible characters.
19179 This ignores character with invisibility property `org-link', and also
19180 characters with property `org-cwidth', because these will become invisible
19181 upon the next fontification round."
19182 (let (b l)
19183 (when (or (eq t buffer-invisibility-spec)
19184 (assq 'org-link buffer-invisibility-spec))
19185 (while (setq b (text-property-any 0 (length s)
19186 'invisible 'org-link s))
19187 (setq s (concat (substring s 0 b)
19188 (substring s (or (next-single-property-change
19189 b 'invisible s) (length s)))))))
19190 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
19191 (setq s (concat (substring s 0 b)
19192 (substring s (or (next-single-property-change
19193 b 'org-cwidth s) (length s))))))
19194 (setq l (string-width s) b -1)
19195 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
19196 (setq l (- l (get-text-property b 'org-dwidth-n s))))
19199 (defun org-shorten-string (s maxlength)
19200 "Shorten string S so tht it is no longer than MAXLENGTH characters.
19201 If the string is shorter or has length MAXLENGTH, just return the
19202 original string. If it is longer, the functions finds a space in the
19203 string, breaks this string off at that locations and adds three dots
19204 as ellipsis. Including the ellipsis, the string will not be longer
19205 than MAXLENGTH. If finding a good breaking point in the string does
19206 not work, the string is just chopped off in the middle of a word
19207 if necessary."
19208 (if (<= (length s) maxlength)
19210 (let* ((n (max (- maxlength 4) 1))
19211 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
19212 (if (string-match re s)
19213 (concat (match-string 1 s) "...")
19214 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
19216 (defun org-get-indentation (&optional line)
19217 "Get the indentation of the current line, interpreting tabs.
19218 When LINE is given, assume it represents a line and compute its indentation."
19219 (if line
19220 (if (string-match "^ *" (org-remove-tabs line))
19221 (match-end 0))
19222 (save-excursion
19223 (beginning-of-line 1)
19224 (skip-chars-forward " \t")
19225 (current-column))))
19227 (defun org-get-string-indentation (s)
19228 "What indentation has S due to SPACE and TAB at the beginning of the string?"
19229 (let ((n -1) (i 0) (w tab-width) c)
19230 (catch 'exit
19231 (while (< (setq n (1+ n)) (length s))
19232 (setq c (aref s n))
19233 (cond ((= c ?\ ) (setq i (1+ i)))
19234 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
19235 (t (throw 'exit t)))))
19238 (defun org-remove-tabs (s &optional width)
19239 "Replace tabulators in S with spaces.
19240 Assumes that s is a single line, starting in column 0."
19241 (setq width (or width tab-width))
19242 (while (string-match "\t" s)
19243 (setq s (replace-match
19244 (make-string
19245 (- (* width (/ (+ (match-beginning 0) width) width))
19246 (match-beginning 0)) ?\ )
19247 t t s)))
19250 (defun org-fix-indentation (line ind)
19251 "Fix indentation in LINE.
19252 IND is a cons cell with target and minimum indentation.
19253 If the current indentation in LINE is smaller than the minimum,
19254 leave it alone. If it is larger than ind, set it to the target."
19255 (let* ((l (org-remove-tabs line))
19256 (i (org-get-indentation l))
19257 (i1 (car ind)) (i2 (cdr ind)))
19258 (if (>= i i2) (setq l (substring line i2)))
19259 (if (> i1 0)
19260 (concat (make-string i1 ?\ ) l)
19261 l)))
19263 (defun org-remove-indentation (code &optional n)
19264 "Remove the maximum common indentation from the lines in CODE.
19265 N may optionally be the number of spaces to remove."
19266 (with-temp-buffer
19267 (insert code)
19268 (org-do-remove-indentation n)
19269 (buffer-string)))
19271 (defun org-do-remove-indentation (&optional n)
19272 "Remove the maximum common indentation from the buffer."
19273 (untabify (point-min) (point-max))
19274 (let ((min 10000) re)
19275 (if n
19276 (setq min n)
19277 (goto-char (point-min))
19278 (while (re-search-forward "^ *[^ \n]" nil t)
19279 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
19280 (unless (or (= min 0) (= min 10000))
19281 (setq re (format "^ \\{%d\\}" min))
19282 (goto-char (point-min))
19283 (while (re-search-forward re nil t)
19284 (replace-match "")
19285 (end-of-line 1))
19286 min)))
19288 (defun org-fill-template (template alist)
19289 "Find each %key of ALIST in TEMPLATE and replace it."
19290 (let ((case-fold-search nil)
19291 entry key value)
19292 (setq alist (sort (copy-sequence alist)
19293 (lambda (a b) (< (length (car a)) (length (car b))))))
19294 (while (setq entry (pop alist))
19295 (setq template
19296 (replace-regexp-in-string
19297 (concat "%" (regexp-quote (car entry)))
19298 (cdr entry) template t t)))
19299 template))
19301 (defun org-base-buffer (buffer)
19302 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
19303 (if (not buffer)
19304 buffer
19305 (or (buffer-base-buffer buffer)
19306 buffer)))
19308 (defun org-trim (s)
19309 "Remove whitespace at beginning and end of string."
19310 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
19311 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
19314 (defun org-wrap (string &optional width lines)
19315 "Wrap string to either a number of lines, or a width in characters.
19316 If WIDTH is non-nil, the string is wrapped to that width, however many lines
19317 that costs. If there is a word longer than WIDTH, the text is actually
19318 wrapped to the length of that word.
19319 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
19320 many lines, whatever width that takes.
19321 The return value is a list of lines, without newlines at the end."
19322 (let* ((words (org-split-string string "[ \t\n]+"))
19323 (maxword (apply 'max (mapcar 'org-string-width words)))
19324 w ll)
19325 (cond (width
19326 (org-do-wrap words (max maxword width)))
19327 (lines
19328 (setq w maxword)
19329 (setq ll (org-do-wrap words maxword))
19330 (if (<= (length ll) lines)
19332 (setq ll words)
19333 (while (> (length ll) lines)
19334 (setq w (1+ w))
19335 (setq ll (org-do-wrap words w)))
19336 ll))
19337 (t (error "Cannot wrap this")))))
19339 (defun org-do-wrap (words width)
19340 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
19341 (let (lines line)
19342 (while words
19343 (setq line (pop words))
19344 (while (and words (< (+ (length line) (length (car words))) width))
19345 (setq line (concat line " " (pop words))))
19346 (setq lines (push line lines)))
19347 (nreverse lines)))
19349 (defun org-split-string (string &optional separators)
19350 "Splits STRING into substrings at SEPARATORS.
19351 No empty strings are returned if there are matches at the beginning
19352 and end of string."
19353 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
19354 (start 0)
19355 notfirst
19356 (list nil))
19357 (while (and (string-match rexp string
19358 (if (and notfirst
19359 (= start (match-beginning 0))
19360 (< start (length string)))
19361 (1+ start) start))
19362 (< (match-beginning 0) (length string)))
19363 (setq notfirst t)
19364 (or (eq (match-beginning 0) 0)
19365 (and (eq (match-beginning 0) (match-end 0))
19366 (eq (match-beginning 0) start))
19367 (setq list
19368 (cons (substring string start (match-beginning 0))
19369 list)))
19370 (setq start (match-end 0)))
19371 (or (eq start (length string))
19372 (setq list
19373 (cons (substring string start)
19374 list)))
19375 (nreverse list)))
19377 (defun org-quote-vert (s)
19378 "Replace \"|\" with \"\\vert\"."
19379 (while (string-match "|" s)
19380 (setq s (replace-match "\\vert" t t s)))
19383 (defun org-uuidgen-p (s)
19384 "Is S an ID created by UUIDGEN?"
19385 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
19387 (defun org-context ()
19388 "Return a list of contexts of the current cursor position.
19389 If several contexts apply, all are returned.
19390 Each context entry is a list with a symbol naming the context, and
19391 two positions indicating start and end of the context. Possible
19392 contexts are:
19394 :headline anywhere in a headline
19395 :headline-stars on the leading stars in a headline
19396 :todo-keyword on a TODO keyword (including DONE) in a headline
19397 :tags on the TAGS in a headline
19398 :priority on the priority cookie in a headline
19399 :item on the first line of a plain list item
19400 :item-bullet on the bullet/number of a plain list item
19401 :checkbox on the checkbox in a plain list item
19402 :table in an org-mode table
19403 :table-special on a special filed in a table
19404 :table-table in a table.el table
19405 :link on a hyperlink
19406 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
19407 :target on a <<target>>
19408 :radio-target on a <<<radio-target>>>
19409 :latex-fragment on a LaTeX fragment
19410 :latex-preview on a LaTeX fragment with overlayed preview image
19412 This function expects the position to be visible because it uses font-lock
19413 faces as a help to recognize the following contexts: :table-special, :link,
19414 and :keyword."
19415 (let* ((f (get-text-property (point) 'face))
19416 (faces (if (listp f) f (list f)))
19417 (p (point)) clist o)
19418 ;; First the large context
19419 (cond
19420 ((org-on-heading-p t)
19421 (push (list :headline (point-at-bol) (point-at-eol)) clist)
19422 (when (progn
19423 (beginning-of-line 1)
19424 (looking-at org-todo-line-tags-regexp))
19425 (push (org-point-in-group p 1 :headline-stars) clist)
19426 (push (org-point-in-group p 2 :todo-keyword) clist)
19427 (push (org-point-in-group p 4 :tags) clist))
19428 (goto-char p)
19429 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
19430 (if (looking-at "\\[#[A-Z0-9]\\]")
19431 (push (org-point-in-group p 0 :priority) clist)))
19433 ((org-at-item-p)
19434 (push (org-point-in-group p 2 :item-bullet) clist)
19435 (push (list :item (point-at-bol)
19436 (save-excursion (org-end-of-item) (point)))
19437 clist)
19438 (and (org-at-item-checkbox-p)
19439 (push (org-point-in-group p 0 :checkbox) clist)))
19441 ((org-at-table-p)
19442 (push (list :table (org-table-begin) (org-table-end)) clist)
19443 (if (memq 'org-formula faces)
19444 (push (list :table-special
19445 (previous-single-property-change p 'face)
19446 (next-single-property-change p 'face)) clist)))
19447 ((org-at-table-p 'any)
19448 (push (list :table-table) clist)))
19449 (goto-char p)
19451 ;; Now the small context
19452 (cond
19453 ((org-at-timestamp-p)
19454 (push (org-point-in-group p 0 :timestamp) clist))
19455 ((memq 'org-link faces)
19456 (push (list :link
19457 (previous-single-property-change p 'face)
19458 (next-single-property-change p 'face)) clist))
19459 ((memq 'org-special-keyword faces)
19460 (push (list :keyword
19461 (previous-single-property-change p 'face)
19462 (next-single-property-change p 'face)) clist))
19463 ((org-on-target-p)
19464 (push (org-point-in-group p 0 :target) clist)
19465 (goto-char (1- (match-beginning 0)))
19466 (if (looking-at org-radio-target-regexp)
19467 (push (org-point-in-group p 0 :radio-target) clist))
19468 (goto-char p))
19469 ((setq o (car (delq nil
19470 (mapcar
19471 (lambda (x)
19472 (if (memq x org-latex-fragment-image-overlays) x))
19473 (overlays-at (point))))))
19474 (push (list :latex-fragment
19475 (overlay-start o) (overlay-end o)) clist)
19476 (push (list :latex-preview
19477 (overlay-start o) (overlay-end o)) clist))
19478 ((org-inside-LaTeX-fragment-p)
19479 ;; FIXME: positions wrong.
19480 (push (list :latex-fragment (point) (point)) clist)))
19482 (setq clist (nreverse (delq nil clist)))
19483 clist))
19485 ;; FIXME: Compare with at-regexp-p Do we need both?
19486 (defun org-in-regexp (re &optional nlines visually)
19487 "Check if point is inside a match of regexp.
19488 Normally only the current line is checked, but you can include NLINES extra
19489 lines both before and after point into the search.
19490 If VISUALLY is set, require that the cursor is not after the match but
19491 really on, so that the block visually is on the match."
19492 (catch 'exit
19493 (let ((pos (point))
19494 (eol (point-at-eol (+ 1 (or nlines 0))))
19495 (inc (if visually 1 0)))
19496 (save-excursion
19497 (beginning-of-line (- 1 (or nlines 0)))
19498 (while (re-search-forward re eol t)
19499 (if (and (<= (match-beginning 0) pos)
19500 (>= (+ inc (match-end 0)) pos))
19501 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
19503 (defun org-at-regexp-p (regexp)
19504 "Is point inside a match of REGEXP in the current line?"
19505 (catch 'exit
19506 (save-excursion
19507 (let ((pos (point)) (end (point-at-eol)))
19508 (beginning-of-line 1)
19509 (while (re-search-forward regexp end t)
19510 (if (and (<= (match-beginning 0) pos)
19511 (>= (match-end 0) pos))
19512 (throw 'exit t)))
19513 nil))))
19515 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
19516 "Non-nil when point is between matches of START-RE and END-RE.
19518 Also return a non-nil value when point is on one of the matches.
19520 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
19521 buffer positions. Default values are the positions of headlines
19522 surrounding the point.
19524 The functions returns a cons cell whose car (resp. cdr) is the
19525 position before START-RE (resp. after END-RE)."
19526 (save-match-data
19527 (let ((pos (point))
19528 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
19529 (limit-down (or lim-down (save-excursion (outline-next-heading))))
19530 beg end)
19531 (save-excursion
19532 ;; Point is on a block when on START-RE or if START-RE can be
19533 ;; found before it...
19534 (and (or (org-at-regexp-p start-re)
19535 (re-search-backward start-re limit-up t))
19536 (setq beg (match-beginning 0))
19537 ;; ... and END-RE after it...
19538 (goto-char (match-end 0))
19539 (re-search-forward end-re limit-down t)
19540 (> (setq end (match-end 0)) pos)
19541 ;; ... without another START-RE in-between.
19542 (goto-char (match-beginning 0))
19543 (not (re-search-backward start-re (1+ beg) t))
19544 ;; Return value.
19545 (cons beg end))))))
19547 (defun org-in-block-p (names)
19548 "Non-nil when point belongs to a block whose name belongs to NAMES.
19550 NAMES is a list of strings containing names of blocks.
19552 Return first block name matched, or nil. Beware that in case of
19553 nested blocks, the returned name may not belong to the closest
19554 block from point."
19555 (save-match-data
19556 (catch 'exit
19557 (let ((case-fold-search t)
19558 (lim-up (save-excursion (outline-previous-heading)))
19559 (lim-down (save-excursion (outline-next-heading))))
19560 (mapc (lambda (name)
19561 (let ((n (regexp-quote name)))
19562 (when (org-between-regexps-p
19563 (concat "^[ \t]*#\\+begin_" n)
19564 (concat "^[ \t]*#\\+end_" n)
19565 lim-up lim-down)
19566 (throw 'exit n))))
19567 names))
19568 nil)))
19570 (defun org-occur-in-agenda-files (regexp &optional nlines)
19571 "Call `multi-occur' with buffers for all agenda files."
19572 (interactive "sOrg-files matching: \np")
19573 (let* ((files (org-agenda-files))
19574 (tnames (mapcar 'file-truename files))
19575 (extra org-agenda-text-search-extra-files)
19577 (when (eq (car extra) 'agenda-archives)
19578 (setq extra (cdr extra))
19579 (setq files (org-add-archive-files files)))
19580 (while (setq f (pop extra))
19581 (unless (member (file-truename f) tnames)
19582 (add-to-list 'files f 'append)
19583 (add-to-list 'tnames (file-truename f) 'append)))
19584 (multi-occur
19585 (mapcar (lambda (x)
19586 (with-current-buffer
19587 (or (get-file-buffer x) (find-file-noselect x))
19588 (widen)
19589 (current-buffer)))
19590 files)
19591 regexp)))
19593 (if (boundp 'occur-mode-find-occurrence-hook)
19594 ;; Emacs 23
19595 (add-hook 'occur-mode-find-occurrence-hook
19596 (lambda ()
19597 (when (eq major-mode 'org-mode)
19598 (org-reveal))))
19599 ;; Emacs 22
19600 (defadvice occur-mode-goto-occurrence
19601 (after org-occur-reveal activate)
19602 (and (eq major-mode 'org-mode) (org-reveal)))
19603 (defadvice occur-mode-goto-occurrence-other-window
19604 (after org-occur-reveal activate)
19605 (and (eq major-mode 'org-mode) (org-reveal)))
19606 (defadvice occur-mode-display-occurrence
19607 (after org-occur-reveal activate)
19608 (when (eq major-mode 'org-mode)
19609 (let ((pos (occur-mode-find-occurrence)))
19610 (with-current-buffer (marker-buffer pos)
19611 (save-excursion
19612 (goto-char pos)
19613 (org-reveal)))))))
19615 (defun org-occur-link-in-agenda-files ()
19616 "Create a link and search for it in the agendas.
19617 The link is not stored in `org-stored-links', it is just created
19618 for the search purpose."
19619 (interactive)
19620 (let ((link (condition-case nil
19621 (org-store-link nil)
19622 (error "Unable to create a link to here"))))
19623 (org-occur-in-agenda-files (regexp-quote link))))
19625 (defun org-uniquify (list)
19626 "Remove duplicate elements from LIST."
19627 (let (res)
19628 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
19629 res))
19631 (defun org-delete-all (elts list)
19632 "Remove all elements in ELTS from LIST."
19633 (while elts
19634 (setq list (delete (pop elts) list)))
19635 list)
19637 (defun org-count (cl-item cl-seq)
19638 "Count the number of occurrences of ITEM in SEQ.
19639 Taken from `count' in cl-seq.el with all keyword arguments removed."
19640 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
19641 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
19642 (while (< cl-start cl-end)
19643 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
19644 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
19645 (setq cl-start (1+ cl-start)))
19646 cl-count))
19648 (defun org-remove-if (predicate seq)
19649 "Remove everything from SEQ that fulfills PREDICATE."
19650 (let (res e)
19651 (while seq
19652 (setq e (pop seq))
19653 (if (not (funcall predicate e)) (push e res)))
19654 (nreverse res)))
19656 (defun org-remove-if-not (predicate seq)
19657 "Remove everything from SEQ that does not fulfill PREDICATE."
19658 (let (res e)
19659 (while seq
19660 (setq e (pop seq))
19661 (if (funcall predicate e) (push e res)))
19662 (nreverse res)))
19664 (defun org-back-over-empty-lines ()
19665 "Move backwards over whitespace, to the beginning of the first empty line.
19666 Returns the number of empty lines passed."
19667 (let ((pos (point)))
19668 (if (cdr (assoc 'heading org-blank-before-new-entry))
19669 (skip-chars-backward " \t\n\r")
19670 (unless (eobp)
19671 (forward-line -1)))
19672 (beginning-of-line 2)
19673 (goto-char (min (point) pos))
19674 (count-lines (point) pos)))
19676 (defun org-skip-whitespace ()
19677 (skip-chars-forward " \t\n\r"))
19679 (defun org-point-in-group (point group &optional context)
19680 "Check if POINT is in match-group GROUP.
19681 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
19682 match. If the match group does not exist or point is not inside it,
19683 return nil."
19684 (and (match-beginning group)
19685 (>= point (match-beginning group))
19686 (<= point (match-end group))
19687 (if context
19688 (list context (match-beginning group) (match-end group))
19689 t)))
19691 (defun org-switch-to-buffer-other-window (&rest args)
19692 "Switch to buffer in a second window on the current frame.
19693 In particular, do not allow pop-up frames.
19694 Returns the newly created buffer."
19695 (let (pop-up-frames special-display-buffer-names special-display-regexps
19696 special-display-function)
19697 (apply 'switch-to-buffer-other-window args)))
19699 (defun org-combine-plists (&rest plists)
19700 "Create a single property list from all plists in PLISTS.
19701 The process starts by copying the first list, and then setting properties
19702 from the other lists. Settings in the last list are the most significant
19703 ones and overrule settings in the other lists."
19704 (let ((rtn (copy-sequence (pop plists)))
19705 p v ls)
19706 (while plists
19707 (setq ls (pop plists))
19708 (while ls
19709 (setq p (pop ls) v (pop ls))
19710 (setq rtn (plist-put rtn p v))))
19711 rtn))
19713 (defun org-move-line-down (arg)
19714 "Move the current line down. With prefix argument, move it past ARG lines."
19715 (interactive "p")
19716 (let ((col (current-column))
19717 beg end pos)
19718 (beginning-of-line 1) (setq beg (point))
19719 (beginning-of-line 2) (setq end (point))
19720 (beginning-of-line (+ 1 arg))
19721 (setq pos (move-marker (make-marker) (point)))
19722 (insert (delete-and-extract-region beg end))
19723 (goto-char pos)
19724 (org-move-to-column col)))
19726 (defun org-move-line-up (arg)
19727 "Move the current line up. With prefix argument, move it past ARG lines."
19728 (interactive "p")
19729 (let ((col (current-column))
19730 beg end pos)
19731 (beginning-of-line 1) (setq beg (point))
19732 (beginning-of-line 2) (setq end (point))
19733 (beginning-of-line (- arg))
19734 (setq pos (move-marker (make-marker) (point)))
19735 (insert (delete-and-extract-region beg end))
19736 (goto-char pos)
19737 (org-move-to-column col)))
19739 (defun org-replace-escapes (string table)
19740 "Replace %-escapes in STRING with values in TABLE.
19741 TABLE is an association list with keys like \"%a\" and string values.
19742 The sequences in STRING may contain normal field width and padding information,
19743 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
19744 so values can contain further %-escapes if they are define later in TABLE."
19745 (let ((tbl (copy-alist table))
19746 (case-fold-search nil)
19747 (pchg 0)
19748 e re rpl)
19749 (while (setq e (pop tbl))
19750 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
19751 (when (and (cdr e) (string-match re (cdr e)))
19752 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
19753 (safe "SREF"))
19754 (add-text-properties 0 3 (list 'sref sref) safe)
19755 (setcdr e (replace-match safe t t (cdr e)))))
19756 (while (string-match re string)
19757 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
19758 (cdr e)))
19759 (setq string (replace-match rpl t t string))))
19760 (while (setq pchg (next-property-change pchg string))
19761 (let ((sref (get-text-property pchg 'sref string)))
19762 (when (and sref (string-match "SREF" string pchg))
19763 (setq string (replace-match sref t t string)))))
19764 string))
19766 (defun org-sublist (list start end)
19767 "Return a section of LIST, from START to END.
19768 Counting starts at 1."
19769 (let (rtn (c start))
19770 (setq list (nthcdr (1- start) list))
19771 (while (and list (<= c end))
19772 (push (pop list) rtn)
19773 (setq c (1+ c)))
19774 (nreverse rtn)))
19776 (defun org-find-base-buffer-visiting (file)
19777 "Like `find-buffer-visiting' but always return the base buffer and
19778 not an indirect buffer."
19779 (let ((buf (or (get-file-buffer file)
19780 (find-buffer-visiting file))))
19781 (if buf
19782 (or (buffer-base-buffer buf) buf)
19783 nil)))
19785 (defun org-image-file-name-regexp (&optional extensions)
19786 "Return regexp matching the file names of images.
19787 If EXTENSIONS is given, only match these."
19788 (if (and (not extensions) (fboundp 'image-file-name-regexp))
19789 (image-file-name-regexp)
19790 (let ((image-file-name-extensions
19791 (or extensions
19792 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
19793 "xbm" "xpm" "pbm" "pgm" "ppm"))))
19794 (concat "\\."
19795 (regexp-opt (nconc (mapcar 'upcase
19796 image-file-name-extensions)
19797 image-file-name-extensions)
19799 "\\'"))))
19801 (defun org-file-image-p (file &optional extensions)
19802 "Return non-nil if FILE is an image."
19803 (save-match-data
19804 (string-match (org-image-file-name-regexp extensions) file)))
19806 (defun org-get-cursor-date ()
19807 "Return the date at cursor in as a time.
19808 This works in the calendar and in the agenda, anywhere else it just
19809 returns the current time."
19810 (let (date day defd)
19811 (cond
19812 ((eq major-mode 'calendar-mode)
19813 (setq date (calendar-cursor-to-date)
19814 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
19815 ((eq major-mode 'org-agenda-mode)
19816 (setq day (get-text-property (point) 'day))
19817 (if day
19818 (setq date (calendar-gregorian-from-absolute day)
19819 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
19820 (nth 2 date))))))
19821 (or defd (current-time))))
19823 (defvar org-agenda-action-marker (make-marker)
19824 "Marker pointing to the entry for the next agenda action.")
19826 (defun org-mark-entry-for-agenda-action ()
19827 "Mark the current entry as target of an agenda action.
19828 Agenda actions are actions executed from the agenda with the key `k',
19829 which make use of the date at the cursor."
19830 (interactive)
19831 (move-marker org-agenda-action-marker
19832 (save-excursion (org-back-to-heading t) (point))
19833 (current-buffer))
19834 (message
19835 "Entry marked for action; press `k' at desired date in agenda or calendar"))
19837 (defun org-mark-subtree ()
19838 "Mark the current subtree.
19839 This puts point at the start of the current subtree, and mark at the end.
19841 If point is in an inline task, mark that task instead."
19842 (interactive)
19843 (let ((inline-task-p
19844 (and (featurep 'org-inlinetask)
19845 (org-inlinetask-in-task-p)))
19846 (beg))
19847 ;; Get beginning of subtree
19848 (cond
19849 (inline-task-p (org-inlinetask-goto-beginning))
19850 ((org-at-heading-p) (beginning-of-line))
19851 (t (org-with-limited-levels (outline-previous-visible-heading 1))))
19852 (setq beg (point))
19853 ;; Get end of it
19854 (if inline-task-p
19855 (org-inlinetask-goto-end)
19856 (org-end-of-subtree))
19857 ;; Mark zone
19858 (push-mark (point) nil t)
19859 (goto-char beg)))
19861 ;;; Paragraph filling stuff.
19862 ;; We want this to be just right, so use the full arsenal.
19864 (defun org-indent-line-function ()
19865 "Indent line depending on context."
19866 (interactive)
19867 (let* ((pos (point))
19868 (itemp (org-at-item-p))
19869 (case-fold-search t)
19870 (org-drawer-regexp (or org-drawer-regexp "\000"))
19871 (inline-task-p (and (featurep 'org-inlinetask)
19872 (org-inlinetask-in-task-p)))
19873 (inline-re (and inline-task-p
19874 (org-inlinetask-outline-regexp)))
19875 column)
19876 (beginning-of-line 1)
19877 (cond
19878 ;; Comments
19879 ((looking-at "# ") (setq column 0))
19880 ;; Headings
19881 ((looking-at org-outline-regexp) (setq column 0))
19882 ;; Included files
19883 ((looking-at "#\\+include:") (setq column 0))
19884 ;; Footnote definition
19885 ((looking-at org-footnote-definition-re) (setq column 0))
19886 ;; Literal examples
19887 ((looking-at "[ \t]*:\\( \\|$\\)")
19888 (setq column (org-get-indentation))) ; do nothing
19889 ;; Lists
19890 ((ignore-errors (goto-char (org-in-item-p)))
19891 (setq column (if itemp
19892 (org-get-indentation)
19893 (org-list-item-body-column (point))))
19894 (goto-char pos))
19895 ;; Drawers
19896 ((and (looking-at "[ \t]*:END:")
19897 (save-excursion (re-search-backward org-drawer-regexp nil t)))
19898 (save-excursion
19899 (goto-char (1- (match-beginning 1)))
19900 (setq column (current-column))))
19901 ;; Special blocks
19902 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
19903 (save-excursion
19904 (re-search-backward
19905 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
19906 (setq column (org-get-indentation (match-string 0))))
19907 ((and (not (looking-at "[ \t]*#\\+begin_"))
19908 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
19909 (save-excursion
19910 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
19911 (setq column
19912 (cond ((equal (downcase (match-string 1)) "src")
19913 ;; src blocks: let `org-edit-src-exit' handle them
19914 (org-get-indentation))
19915 ((equal (downcase (match-string 1)) "example")
19916 (max (org-get-indentation)
19917 (org-get-indentation (match-string 0))))
19919 (org-get-indentation (match-string 0))))))
19920 ;; This line has nothing special, look at the previous relevant
19921 ;; line to compute indentation
19923 (beginning-of-line 0)
19924 (while (and (not (bobp))
19925 (not (looking-at org-drawer-regexp))
19926 ;; When point started in an inline task, do not move
19927 ;; above task starting line.
19928 (not (and inline-task-p (looking-at inline-re)))
19929 ;; Skip drawers, blocks, empty lines, verbatim,
19930 ;; comments, tables, footnotes definitions, lists,
19931 ;; inline tasks.
19932 (or (and (looking-at "[ \t]*:END:")
19933 (re-search-backward org-drawer-regexp nil t))
19934 (and (looking-at "[ \t]*#\\+end_")
19935 (re-search-backward "[ \t]*#\\+begin_"nil t))
19936 (looking-at "[ \t]*[\n:#|]")
19937 (looking-at org-footnote-definition-re)
19938 (and (ignore-errors (goto-char (org-in-item-p)))
19939 (goto-char
19940 (org-list-get-top-point (org-list-struct))))
19941 (and (not inline-task-p)
19942 (featurep 'org-inlinetask)
19943 (org-inlinetask-in-task-p)
19944 (or (org-inlinetask-goto-beginning) t))))
19945 (beginning-of-line 0))
19946 (cond
19947 ;; There was an heading above.
19948 ((looking-at "\\*+[ \t]+")
19949 (if (not org-adapt-indentation)
19950 (setq column 0)
19951 (goto-char (match-end 0))
19952 (setq column (current-column))))
19953 ;; A drawer had started and is unfinished
19954 ((looking-at org-drawer-regexp)
19955 (goto-char (1- (match-beginning 1)))
19956 (setq column (current-column)))
19957 ;; Else, nothing noticeable found: get indentation and go on.
19958 (t (setq column (org-get-indentation))))))
19959 ;; Now apply indentation and move cursor accordingly
19960 (goto-char pos)
19961 (if (<= (current-column) (current-indentation))
19962 (org-indent-line-to column)
19963 (save-excursion (org-indent-line-to column)))
19964 ;; Special polishing for properties, see `org-property-format'
19965 (setq column (current-column))
19966 (beginning-of-line 1)
19967 (if (looking-at
19968 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
19969 (replace-match (concat (match-string 1)
19970 (format org-property-format
19971 (match-string 2) (match-string 3)))
19972 t t))
19973 (org-move-to-column column)))
19975 (defvar org-adaptive-fill-regexp-backup adaptive-fill-regexp
19976 "Variable to store copy of `adaptive-fill-regexp'.
19977 Since `adaptive-fill-regexp' is set to never match, we need to
19978 store a backup of its value before entering `org-mode' so that
19979 the functionality can be provided as a fall-back.")
19981 (defun org-set-autofill-regexps ()
19982 (interactive)
19983 ;; In the paragraph separator we include headlines, because filling
19984 ;; text in a line directly attached to a headline would otherwise
19985 ;; fill the headline as well.
19986 (org-set-local 'comment-start-skip "^#+[ \t]*")
19987 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|#]")
19988 ;; The paragraph starter includes hand-formatted lists.
19989 (org-set-local
19990 'paragraph-start
19991 (concat
19992 "\f" "\\|"
19993 "[ ]*$" "\\|"
19994 org-outline-regexp "\\|"
19995 "[ \t]*#" "\\|"
19996 (org-item-re) "\\|"
19997 "[ \t]*[:|]" "\\|"
19998 "\\$\\$" "\\|"
19999 "\\\\\\(begin\\|end\\|[][]\\)"))
20000 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
20001 ;; But only if the user has not turned off tables or fixed-width regions
20002 (org-set-local
20003 'auto-fill-inhibit-regexp
20004 (concat org-outline-regexp
20005 "\\|#\\+"
20006 "\\|[ \t]*" org-keyword-time-regexp
20007 (if (or org-enable-table-editor org-enable-fixed-width-editor)
20008 (concat
20009 "\\|[ \t]*["
20010 (if org-enable-table-editor "|" "")
20011 (if org-enable-fixed-width-editor ":" "")
20012 "]"))))
20013 ;; We use our own fill-paragraph function, to make sure that tables
20014 ;; and fixed-width regions are not wrapped. That function will pass
20015 ;; through to `fill-paragraph' when appropriate.
20016 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
20017 ;; Prevent auto-fill from inserting unwanted new items.
20018 (if (boundp 'fill-nobreak-predicate)
20019 (org-set-local 'fill-nobreak-predicate
20020 (if (memq 'org-fill-item-nobreak-p fill-nobreak-predicate)
20021 fill-nobreak-predicate
20022 (cons 'org-fill-item-nobreak-p fill-nobreak-predicate))))
20023 ;; Adaptive filling: To get full control, first make sure that
20024 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
20025 (unless (local-variable-p 'adaptive-fill-regexp (current-buffer))
20026 (org-set-local 'org-adaptive-fill-regexp-backup
20027 adaptive-fill-regexp))
20028 (org-set-local 'adaptive-fill-regexp "\000")
20029 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
20030 (org-set-local 'adaptive-fill-function
20031 'org-adaptive-fill-function)
20032 (org-set-local
20033 'align-mode-rules-list
20034 '((org-in-buffer-settings
20035 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
20036 (modes . '(org-mode))))))
20038 (defun org-fill-item-nobreak-p ()
20039 "Non-nil when a line break at point would insert a new item."
20040 (and (looking-at (org-item-re)) (org-list-in-valid-context-p)))
20042 (defun org-fill-paragraph (&optional justify)
20043 "Re-align a table, pass through to fill-paragraph if no table."
20044 (let ((table-p (org-at-table-p))
20045 (table.el-p (org-at-table.el-p))
20046 (itemp (org-in-item-p)))
20047 (cond ((and (equal (char-after (point-at-bol)) ?*)
20048 (save-excursion (goto-char (point-at-bol))
20049 (looking-at org-outline-regexp)))
20050 t) ; skip headlines
20051 (table.el-p t) ; skip table.el tables
20052 (table-p (org-table-align) t) ; align Org tables
20053 (itemp ; align text in items
20054 (let* ((struct (save-excursion (goto-char itemp)
20055 (org-list-struct)))
20056 (parents (org-list-parents-alist struct))
20057 (children (org-list-get-children itemp struct parents))
20058 beg end prev next prefix)
20059 ;; Determine in which part of item point is: before
20060 ;; first child, after last child, between two
20061 ;; sub-lists, or simply in item if there's no child.
20062 (cond
20063 ((not children)
20064 (setq prefix (make-string (org-list-item-body-column itemp) ?\ )
20065 beg itemp
20066 end (org-list-get-item-end itemp struct)))
20067 ((< (point) (setq next (car children)))
20068 (setq prefix (make-string (org-list-item-body-column itemp) ?\ )
20069 beg itemp
20070 end next))
20071 ((> (point) (setq prev (car (last children))))
20072 (setq beg (org-list-get-item-end prev struct)
20073 end (org-list-get-item-end itemp struct)
20074 prefix (save-excursion
20075 (goto-char beg)
20076 (skip-chars-forward " \t")
20077 (make-string (current-column) ?\ ))))
20078 (t (catch 'exit
20079 (while (setq next (pop children))
20080 (if (> (point) next)
20081 (setq prev next)
20082 (setq beg (org-list-get-item-end prev struct)
20083 end next
20084 prefix (save-excursion
20085 (goto-char beg)
20086 (skip-chars-forward " \t")
20087 (make-string (current-column) ?\ )))
20088 (throw 'exit nil))))))
20089 ;; Use `fill-paragraph' with buffer narrowed to item
20090 ;; without any child, and with our computed PREFIX.
20091 (flet ((fill-context-prefix (from to &optional flr) prefix))
20092 (save-restriction
20093 (narrow-to-region beg end)
20094 (save-excursion (fill-paragraph justify)))) t))
20095 ;; Special case where point is not in a list but is on
20096 ;; a paragraph adjacent to a list: make sure this paragraph
20097 ;; doesn't get merged with the end of the list by narrowing
20098 ;; buffer first.
20099 ((save-excursion (forward-paragraph -1)
20100 (setq itemp (org-in-item-p)))
20101 (let ((struct (save-excursion (goto-char itemp)
20102 (org-list-struct))))
20103 (save-restriction
20104 (narrow-to-region (org-list-get-bottom-point struct)
20105 (save-excursion (forward-paragraph 1)
20106 (point)))
20107 (fill-paragraph justify) t)))
20108 ;; Else simply call `fill-paragraph'.
20109 (t nil))))
20111 ;; For reference, this is the default value of adaptive-fill-regexp
20112 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
20114 (defun org-adaptive-fill-function ()
20115 "Return a fill prefix for org-mode files."
20116 (let (itemp)
20117 (save-excursion
20118 (cond
20119 ;; Comment line
20120 ((looking-at "#[ \t]+")
20121 (match-string-no-properties 0))
20122 ;; Plain list item
20123 ((org-at-item-p)
20124 (make-string (org-list-item-body-column (point-at-bol)) ?\ ))
20125 ;; Point is in a list after `backward-paragraph': original
20126 ;; point wasn't in the list, or filling would have been taken
20127 ;; care of by `org-auto-fill-function', but the list and the
20128 ;; real paragraph are not separated by a blank line. Thus, move
20129 ;; point after the list to go back to real paragraph and
20130 ;; determine fill-prefix.
20131 ((setq itemp (org-in-item-p))
20132 (goto-char itemp)
20133 (let* ((struct (org-list-struct))
20134 (bottom (org-list-get-bottom-point struct)))
20135 (goto-char bottom)
20136 (make-string (org-get-indentation) ?\ )))
20137 ;; Other text
20138 ((looking-at org-adaptive-fill-regexp-backup)
20139 (match-string-no-properties 0))))))
20141 (defun org-auto-fill-function ()
20142 "Auto-fill function."
20143 (let (itemp prefix)
20144 ;; When in a list, compute an appropriate fill-prefix and make
20145 ;; sure it will be used by `do-auto-fill'.
20146 (if (setq itemp (org-in-item-p))
20147 (progn
20148 (setq prefix (make-string (org-list-item-body-column itemp) ?\ ))
20149 (flet ((fill-context-prefix (from to &optional flr) prefix))
20150 (do-auto-fill)))
20151 ;; Else just use `do-auto-fill'.
20152 (do-auto-fill))))
20154 ;;; Other stuff.
20156 (defun org-toggle-fixed-width-section (arg)
20157 "Toggle the fixed-width export.
20158 If there is no active region, the QUOTE keyword at the current headline is
20159 inserted or removed. When present, it causes the text between this headline
20160 and the next to be exported as fixed-width text, and unmodified.
20161 If there is an active region, this command adds or removes a colon as the
20162 first character of this line. If the first character of a line is a colon,
20163 this line is also exported in fixed-width font."
20164 (interactive "P")
20165 (let* ((cc 0)
20166 (regionp (org-region-active-p))
20167 (beg (if regionp (region-beginning) (point)))
20168 (end (if regionp (region-end)))
20169 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
20170 (case-fold-search nil)
20171 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
20172 off)
20173 (if regionp
20174 (save-excursion
20175 (goto-char beg)
20176 (setq cc (current-column))
20177 (beginning-of-line 1)
20178 (setq off (looking-at re))
20179 (while (> nlines 0)
20180 (setq nlines (1- nlines))
20181 (beginning-of-line 1)
20182 (cond
20183 (arg
20184 (org-move-to-column cc t)
20185 (insert ": \n")
20186 (forward-line -1))
20187 ((and off (looking-at re))
20188 (replace-match "" t t nil 1))
20189 ((not off) (org-move-to-column cc t) (insert ": ")))
20190 (forward-line 1)))
20191 (save-excursion
20192 (org-back-to-heading)
20193 (cond
20194 ((looking-at (format org-heading-keyword-regexp-format
20195 org-quote-string))
20196 (goto-char (match-end 1))
20197 (looking-at (concat " +" org-quote-string))
20198 (replace-match "" t t)
20199 (when (eolp) (insert " ")))
20200 ((looking-at org-outline-regexp)
20201 (goto-char (match-end 0))
20202 (insert org-quote-string " ")))))))
20204 (defun org-reftex-citation ()
20205 "Use reftex-citation to insert a citation into the buffer.
20206 This looks for a line like
20208 #+BIBLIOGRAPHY: foo plain option:-d
20210 and derives from it that foo.bib is the bibliography file relevant
20211 for this document. It then installs the necessary environment for RefTeX
20212 to work in this buffer and calls `reftex-citation' to insert a citation
20213 into the buffer.
20215 Export of such citations to both LaTeX and HTML is handled by the contributed
20216 package org-exp-bibtex by Taru Karttunen."
20217 (interactive)
20218 (let ((reftex-docstruct-symbol 'rds)
20219 (reftex-cite-format "\\cite{%l}")
20220 rds bib)
20221 (save-excursion
20222 (save-restriction
20223 (widen)
20224 (let ((case-fold-search t)
20225 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
20226 (if (not (save-excursion
20227 (or (re-search-forward re nil t)
20228 (re-search-backward re nil t))))
20229 (error "No bibliography defined in file")
20230 (setq bib (concat (match-string 1) ".bib")
20231 rds (list (list 'bib bib)))))))
20232 (call-interactively 'reftex-citation)))
20234 ;;;; Functions extending outline functionality
20236 (defun org-beginning-of-line (&optional arg)
20237 "Go to the beginning of the current line. If that is invisible, continue
20238 to a visible line beginning. This makes the function of C-a more intuitive.
20239 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
20240 first attempt, and only move to after the tags when the cursor is already
20241 beyond the end of the headline."
20242 (interactive "P")
20243 (let ((pos (point))
20244 (special (if (consp org-special-ctrl-a/e)
20245 (car org-special-ctrl-a/e)
20246 org-special-ctrl-a/e))
20247 refpos)
20248 (if (org-bound-and-true-p line-move-visual)
20249 (beginning-of-visual-line 1)
20250 (beginning-of-line 1))
20251 (if (and arg (fboundp 'move-beginning-of-line))
20252 (call-interactively 'move-beginning-of-line)
20253 (if (bobp)
20255 (backward-char 1)
20256 (if (org-truely-invisible-p)
20257 (while (and (not (bobp)) (org-truely-invisible-p))
20258 (backward-char 1)
20259 (beginning-of-line 1))
20260 (forward-char 1))))
20261 (when special
20262 (cond
20263 ((and (looking-at org-complex-heading-regexp)
20264 (= (char-after (match-end 1)) ?\ ))
20265 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
20266 (point-at-eol)))
20267 (goto-char
20268 (if (eq special t)
20269 (cond ((> pos refpos) refpos)
20270 ((= pos (point)) refpos)
20271 (t (point)))
20272 (cond ((> pos (point)) (point))
20273 ((not (eq last-command this-command)) (point))
20274 (t refpos)))))
20275 ((org-at-item-p)
20276 (goto-char
20277 (if (eq special t)
20278 (cond ((> pos (match-end 0)) (match-end 0))
20279 ((= pos (point)) (match-end 0))
20280 (t (point)))
20281 (cond ((> pos (point)) (point))
20282 ((not (eq last-command this-command)) (point))
20283 (t (match-end 0))))))))
20284 (org-no-warnings
20285 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
20287 (defun org-end-of-line (&optional arg)
20288 "Go to the end of the line.
20289 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
20290 first attempt, and only move to after the tags when the cursor is already
20291 beyond the end of the headline."
20292 (interactive "P")
20293 (let ((special (if (consp org-special-ctrl-a/e)
20294 (cdr org-special-ctrl-a/e)
20295 org-special-ctrl-a/e)))
20296 (cond
20297 ((or (not special) arg
20298 (not (or (org-on-heading-p) (org-at-item-p))))
20299 (call-interactively
20300 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
20301 ((fboundp 'move-end-of-line) 'move-end-of-line)
20302 (t 'end-of-line))))
20303 ((org-on-heading-p)
20304 (let ((pos (point)))
20305 (beginning-of-line 1)
20306 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
20307 (if (eq special t)
20308 (if (or (< pos (match-beginning 1))
20309 (= pos (match-end 0)))
20310 (goto-char (match-beginning 1))
20311 (goto-char (match-end 0)))
20312 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
20313 (goto-char (match-end 0))
20314 (goto-char (match-beginning 1))))
20315 (call-interactively (if (fboundp 'move-end-of-line)
20316 'move-end-of-line
20317 'end-of-line)))))
20318 ;; At an item: Move before any hidden text.
20319 (t (call-interactively 'end-of-line)))
20320 (org-no-warnings
20321 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
20323 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
20324 (define-key org-mode-map "\C-e" 'org-end-of-line)
20326 (defun org-backward-sentence (&optional arg)
20327 "Go to beginning of sentence, or beginning of table field.
20328 This will call `backward-sentence' or `org-table-beginning-of-field',
20329 depending on context."
20330 (interactive "P")
20331 (cond
20332 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
20333 (t (call-interactively 'backward-sentence))))
20335 (defun org-forward-sentence (&optional arg)
20336 "Go to end of sentence, or end of table field.
20337 This will call `forward-sentence' or `org-table-end-of-field',
20338 depending on context."
20339 (interactive "P")
20340 (cond
20341 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
20342 (t (call-interactively 'forward-sentence))))
20344 (define-key org-mode-map "\M-a" 'org-backward-sentence)
20345 (define-key org-mode-map "\M-e" 'org-forward-sentence)
20347 (defun org-kill-line (&optional arg)
20348 "Kill line, to tags or end of line."
20349 (interactive "P")
20350 (cond
20351 ((or (not org-special-ctrl-k)
20352 (bolp)
20353 (not (org-on-heading-p)))
20354 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
20355 org-ctrl-k-protect-subtree)
20356 (if (or (eq org-ctrl-k-protect-subtree 'error)
20357 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
20358 (error "C-k aborted - would kill hidden subtree")))
20359 (call-interactively 'kill-line))
20360 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
20361 (kill-region (point) (match-beginning 1))
20362 (org-set-tags nil t))
20363 (t (kill-region (point) (point-at-eol)))))
20365 (define-key org-mode-map "\C-k" 'org-kill-line)
20367 (defun org-yank (&optional arg)
20368 "Yank. If the kill is a subtree, treat it specially.
20369 This command will look at the current kill and check if is a single
20370 subtree, or a series of subtrees[1]. If it passes the test, and if the
20371 cursor is at the beginning of a line or after the stars of a currently
20372 empty headline, then the yank is handled specially. How exactly depends
20373 on the value of the following variables, both set by default.
20375 org-yank-folded-subtrees
20376 When set, the subtree(s) will be folded after insertion, but only
20377 if doing so would now swallow text after the yanked text.
20379 org-yank-adjusted-subtrees
20380 When set, the subtree will be promoted or demoted in order to
20381 fit into the local outline tree structure, which means that the level
20382 will be adjusted so that it becomes the smaller one of the two
20383 *visible* surrounding headings.
20385 Any prefix to this command will cause `yank' to be called directly with
20386 no special treatment. In particular, a simple \\[universal-argument] prefix \
20387 will just
20388 plainly yank the text as it is.
20390 \[1] The test checks if the first non-white line is a heading
20391 and if there are no other headings with fewer stars."
20392 (interactive "P")
20393 (org-yank-generic 'yank arg))
20395 (defun org-yank-generic (command arg)
20396 "Perform some yank-like command.
20398 This function implements the behavior described in the `org-yank'
20399 documentation. However, it has been generalized to work for any
20400 interactive command with similar behavior."
20402 ;; pretend to be command COMMAND
20403 (setq this-command command)
20405 (if arg
20406 (call-interactively command)
20408 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
20409 (and (org-kill-is-subtree-p)
20410 (or (bolp)
20411 (and (looking-at "[ \t]*$")
20412 (string-match
20413 "\\`\\*+\\'"
20414 (buffer-substring (point-at-bol) (point)))))))
20415 swallowp)
20416 (cond
20417 ((and subtreep org-yank-folded-subtrees)
20418 (let ((beg (point))
20419 end)
20420 (if (and subtreep org-yank-adjusted-subtrees)
20421 (org-paste-subtree nil nil 'for-yank)
20422 (call-interactively command))
20424 (setq end (point))
20425 (goto-char beg)
20426 (when (and (bolp) subtreep
20427 (not (setq swallowp
20428 (org-yank-folding-would-swallow-text beg end))))
20429 (org-with-limited-levels
20430 (or (looking-at org-outline-regexp)
20431 (re-search-forward org-outline-regexp-bol end t))
20432 (while (and (< (point) end) (looking-at org-outline-regexp))
20433 (hide-subtree)
20434 (org-cycle-show-empty-lines 'folded)
20435 (condition-case nil
20436 (outline-forward-same-level 1)
20437 (error (goto-char end))))))
20438 (when swallowp
20439 (message
20440 "Inserted text not folded because that would swallow text"))
20442 (goto-char end)
20443 (skip-chars-forward " \t\n\r")
20444 (beginning-of-line 1)
20445 (push-mark beg 'nomsg)))
20446 ((and subtreep org-yank-adjusted-subtrees)
20447 (let ((beg (point-at-bol)))
20448 (org-paste-subtree nil nil 'for-yank)
20449 (push-mark beg 'nomsg)))
20451 (call-interactively command))))))
20453 (defun org-yank-folding-would-swallow-text (beg end)
20454 "Would hide-subtree at BEG swallow any text after END?"
20455 (let (level)
20456 (org-with-limited-levels
20457 (save-excursion
20458 (goto-char beg)
20459 (when (or (looking-at org-outline-regexp)
20460 (re-search-forward org-outline-regexp-bol end t))
20461 (setq level (org-outline-level)))
20462 (goto-char end)
20463 (skip-chars-forward " \t\r\n\v\f")
20464 (if (or (eobp)
20465 (and (bolp) (looking-at org-outline-regexp)
20466 (<= (org-outline-level) level)))
20467 nil ; Nothing would be swallowed
20468 t))))) ; something would swallow
20470 (define-key org-mode-map "\C-y" 'org-yank)
20472 (defun org-truely-invisible-p ()
20473 "Check if point is at a character currently not visible.
20474 This version does not only check the character property, but also
20475 `visible-mode'."
20476 ;; Early versions of noutline don't have `outline-invisible-p'.
20477 (if (org-bound-and-true-p visible-mode)
20479 (outline-invisible-p)))
20481 (defun org-invisible-p2 ()
20482 "Check if point is at a character currently not visible."
20483 (save-excursion
20484 (if (and (eolp) (not (bobp))) (backward-char 1))
20485 ;; Early versions of noutline don't have `outline-invisible-p'.
20486 (outline-invisible-p)))
20488 (defun org-back-to-heading (&optional invisible-ok)
20489 "Call `outline-back-to-heading', but provide a better error message."
20490 (condition-case nil
20491 (outline-back-to-heading invisible-ok)
20492 (error (error "Before first headline at position %d in buffer %s"
20493 (point) (current-buffer)))))
20495 (defun org-beginning-of-defun ()
20496 "Go to the beginning of the subtree, i.e. back to the heading."
20497 (org-back-to-heading))
20498 (defun org-end-of-defun ()
20499 "Go to the end of the subtree."
20500 (org-end-of-subtree nil t))
20502 (defun org-before-first-heading-p ()
20503 "Before first heading?"
20504 (save-excursion
20505 (end-of-line)
20506 (null (re-search-backward org-outline-regexp-bol nil t))))
20508 (defun org-on-heading-p (&optional ignored)
20509 (outline-on-heading-p t))
20510 (defun org-at-heading-p (&optional ignored)
20511 (outline-on-heading-p t))
20513 (defun org-point-at-end-of-empty-headline ()
20514 "If point is at the end of an empty headline, return t, else nil.
20515 If the heading only contains a TODO keyword, it is still still considered
20516 empty."
20517 (and (looking-at "[ \t]*$")
20518 (save-excursion
20519 (beginning-of-line 1)
20520 (let ((case-fold-search nil))
20521 (looking-at org-todo-line-regexp)))
20522 (string= (match-string 3) "")))
20524 (defun org-at-heading-or-item-p ()
20525 (or (org-on-heading-p) (org-at-item-p)))
20527 (defun org-on-target-p ()
20528 (or (org-in-regexp org-radio-target-regexp)
20529 (org-in-regexp org-target-regexp)))
20531 (defun org-up-heading-all (arg)
20532 "Move to the heading line of which the present line is a subheading.
20533 This function considers both visible and invisible heading lines.
20534 With argument, move up ARG levels."
20535 (if (fboundp 'outline-up-heading-all)
20536 (outline-up-heading-all arg) ; emacs 21 version of outline.el
20537 (outline-up-heading arg t))) ; emacs 22 version of outline.el
20539 (defun org-up-heading-safe ()
20540 "Move to the heading line of which the present line is a subheading.
20541 This version will not throw an error. It will return the level of the
20542 headline found, or nil if no higher level is found.
20544 Also, this function will be a lot faster than `outline-up-heading',
20545 because it relies on stars being the outline starters. This can really
20546 make a significant difference in outlines with very many siblings."
20547 (let (start-level re)
20548 (org-back-to-heading t)
20549 (setq start-level (funcall outline-level))
20550 (if (equal start-level 1)
20552 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
20553 (if (re-search-backward re nil t)
20554 (funcall outline-level)))))
20556 (defun org-first-sibling-p ()
20557 "Is this heading the first child of its parents?"
20558 (interactive)
20559 (let ((re org-outline-regexp-bol)
20560 level l)
20561 (unless (org-at-heading-p t)
20562 (error "Not at a heading"))
20563 (setq level (funcall outline-level))
20564 (save-excursion
20565 (if (not (re-search-backward re nil t))
20567 (setq l (funcall outline-level))
20568 (< l level)))))
20570 (defun org-goto-sibling (&optional previous)
20571 "Goto the next sibling, even if it is invisible.
20572 When PREVIOUS is set, go to the previous sibling instead. Returns t
20573 when a sibling was found. When none is found, return nil and don't
20574 move point."
20575 (let ((fun (if previous 're-search-backward 're-search-forward))
20576 (pos (point))
20577 (re org-outline-regexp-bol)
20578 level l)
20579 (when (condition-case nil (org-back-to-heading t) (error nil))
20580 (setq level (funcall outline-level))
20581 (catch 'exit
20582 (or previous (forward-char 1))
20583 (while (funcall fun re nil t)
20584 (setq l (funcall outline-level))
20585 (when (< l level) (goto-char pos) (throw 'exit nil))
20586 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
20587 (goto-char pos)
20588 nil))))
20590 (defun org-show-siblings ()
20591 "Show all siblings of the current headline."
20592 (save-excursion
20593 (while (org-goto-sibling) (org-flag-heading nil)))
20594 (save-excursion
20595 (while (org-goto-sibling 'previous)
20596 (org-flag-heading nil))))
20598 (defun org-goto-first-child ()
20599 "Goto the first child, even if it is invisible.
20600 Return t when a child was found. Otherwise don't move point and
20601 return nil."
20602 (let (level (pos (point)) (re org-outline-regexp-bol))
20603 (when (condition-case nil (org-back-to-heading t) (error nil))
20604 (setq level (outline-level))
20605 (forward-char 1)
20606 (if (and (re-search-forward re nil t) (> (outline-level) level))
20607 (progn (goto-char (match-beginning 0)) t)
20608 (goto-char pos) nil))))
20610 (defun org-show-hidden-entry ()
20611 "Show an entry where even the heading is hidden."
20612 (save-excursion
20613 (org-show-entry)))
20615 (defun org-flag-heading (flag &optional entry)
20616 "Flag the current heading. FLAG non-nil means make invisible.
20617 When ENTRY is non-nil, show the entire entry."
20618 (save-excursion
20619 (org-back-to-heading t)
20620 ;; Check if we should show the entire entry
20621 (if entry
20622 (progn
20623 (org-show-entry)
20624 (save-excursion
20625 (and (outline-next-heading)
20626 (org-flag-heading nil))))
20627 (outline-flag-region (max (point-min) (1- (point)))
20628 (save-excursion (outline-end-of-heading) (point))
20629 flag))))
20631 (defun org-get-next-sibling ()
20632 "Move to next heading of the same level, and return point.
20633 If there is no such heading, return nil.
20634 This is like outline-next-sibling, but invisible headings are ok."
20635 (let ((level (funcall outline-level)))
20636 (outline-next-heading)
20637 (while (and (not (eobp)) (> (funcall outline-level) level))
20638 (outline-next-heading))
20639 (if (or (eobp) (< (funcall outline-level) level))
20641 (point))))
20643 (defun org-get-last-sibling ()
20644 "Move to previous heading of the same level, and return point.
20645 If there is no such heading, return nil."
20646 (let ((opoint (point))
20647 (level (funcall outline-level)))
20648 (outline-previous-heading)
20649 (when (and (/= (point) opoint) (outline-on-heading-p t))
20650 (while (and (> (funcall outline-level) level)
20651 (not (bobp)))
20652 (outline-previous-heading))
20653 (if (< (funcall outline-level) level)
20655 (point)))))
20657 (defun org-end-of-subtree (&optional invisible-OK to-heading)
20658 ;; This contains an exact copy of the original function, but it uses
20659 ;; `org-back-to-heading', to make it work also in invisible
20660 ;; trees. And is uses an invisible-OK argument.
20661 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
20662 ;; Furthermore, when used inside Org, finding the end of a large subtree
20663 ;; with many children and grandchildren etc, this can be much faster
20664 ;; than the outline version.
20665 (org-back-to-heading invisible-OK)
20666 (let ((first t)
20667 (level (funcall outline-level)))
20668 (if (and (eq major-mode 'org-mode) (< level 1000))
20669 ;; A true heading (not a plain list item), in Org-mode
20670 ;; This means we can easily find the end by looking
20671 ;; only for the right number of stars. Using a regexp to do
20672 ;; this is so much faster than using a Lisp loop.
20673 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
20674 (forward-char 1)
20675 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
20676 ;; something else, do it the slow way
20677 (while (and (not (eobp))
20678 (or first (> (funcall outline-level) level)))
20679 (setq first nil)
20680 (outline-next-heading)))
20681 (unless to-heading
20682 (if (memq (preceding-char) '(?\n ?\^M))
20683 (progn
20684 ;; Go to end of line before heading
20685 (forward-char -1)
20686 (if (memq (preceding-char) '(?\n ?\^M))
20687 ;; leave blank line before heading
20688 (forward-char -1))))))
20689 (point))
20691 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
20692 "Use Org version in org-mode, for dramatic speed-up."
20693 (if (eq major-mode 'org-mode)
20694 (progn
20695 (org-end-of-subtree nil t)
20696 (unless (eobp) (backward-char 1)))
20697 ad-do-it))
20699 (defun org-end-of-meta-data-and-drawers ()
20700 "Jump to the first text after meta data and drawers in the current entry.
20701 This will move over empty lines, lines with planning time stamps,
20702 clocking lines, and drawers."
20703 (org-back-to-heading t)
20704 (let ((end (save-excursion (outline-next-heading) (point)))
20705 (re (concat "\\(" org-drawer-regexp "\\)"
20706 "\\|" "[ \t]*" org-keyword-time-regexp)))
20707 (forward-line 1)
20708 (while (re-search-forward re end t)
20709 (if (not (match-end 1))
20710 ;; empty or planning line
20711 (forward-line 1)
20712 ;; a drawer, find the end
20713 (re-search-forward "^[ \t]*:END:" end 'move)
20714 (forward-line 1)))
20715 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
20716 (point)))
20718 (defun org-forward-same-level (arg &optional invisible-ok)
20719 "Move forward to the arg'th subheading at same level as this one.
20720 Stop at the first and last subheadings of a superior heading.
20721 Normally this only looks at visible headings, but when INVISIBLE-OK is non-nil
20722 it wil also look at invisible ones."
20723 (interactive "p")
20724 (org-back-to-heading invisible-ok)
20725 (org-on-heading-p)
20726 (let* ((level (- (match-end 0) (match-beginning 0) 1))
20727 (re (format "^\\*\\{1,%d\\} " level))
20729 (forward-char 1)
20730 (while (> arg 0)
20731 (while (and (re-search-forward re nil 'move)
20732 (setq l (- (match-end 0) (match-beginning 0) 1))
20733 (= l level)
20734 (not invisible-ok)
20735 (progn (backward-char 1) (outline-invisible-p)))
20736 (if (< l level) (setq arg 1)))
20737 (setq arg (1- arg)))
20738 (beginning-of-line 1)))
20740 (defun org-backward-same-level (arg &optional invisible-ok)
20741 "Move backward to the arg'th subheading at same level as this one.
20742 Stop at the first and last subheadings of a superior heading."
20743 (interactive "p")
20744 (org-back-to-heading)
20745 (org-on-heading-p)
20746 (let* ((level (- (match-end 0) (match-beginning 0) 1))
20747 (re (format "^\\*\\{1,%d\\} " level))
20749 (while (> arg 0)
20750 (while (and (re-search-backward re nil 'move)
20751 (setq l (- (match-end 0) (match-beginning 0) 1))
20752 (= l level)
20753 (not invisible-ok)
20754 (outline-invisible-p))
20755 (if (< l level) (setq arg 1)))
20756 (setq arg (1- arg)))))
20758 (defun org-show-subtree ()
20759 "Show everything after this heading at deeper levels."
20760 (outline-flag-region
20761 (point)
20762 (save-excursion
20763 (org-end-of-subtree t t))
20764 nil))
20766 (defun org-show-entry ()
20767 "Show the body directly following this heading.
20768 Show the heading too, if it is currently invisible."
20769 (interactive)
20770 (save-excursion
20771 (condition-case nil
20772 (progn
20773 (org-back-to-heading t)
20774 (outline-flag-region
20775 (max (point-min) (1- (point)))
20776 (save-excursion
20777 (if (re-search-forward
20778 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
20779 (match-beginning 1)
20780 (point-max)))
20781 nil)
20782 (org-cycle-hide-drawers 'children))
20783 (error nil))))
20785 (defun org-make-options-regexp (kwds &optional extra)
20786 "Make a regular expression for keyword lines."
20787 (concat
20789 "#?[ \t]*\\+\\("
20790 (mapconcat 'regexp-quote kwds "\\|")
20791 (if extra (concat "\\|" extra))
20792 "\\):[ \t]*"
20793 "\\(.*\\)"))
20795 ;; Make isearch reveal the necessary context
20796 (defun org-isearch-end ()
20797 "Reveal context after isearch exits."
20798 (when isearch-success ; only if search was successful
20799 (if (featurep 'xemacs)
20800 ;; Under XEmacs, the hook is run in the correct place,
20801 ;; we directly show the context.
20802 (org-show-context 'isearch)
20803 ;; In Emacs the hook runs *before* restoring the overlays.
20804 ;; So we have to use a one-time post-command-hook to do this.
20805 ;; (Emacs 22 has a special variable, see function `org-mode')
20806 (unless (and (boundp 'isearch-mode-end-hook-quit)
20807 isearch-mode-end-hook-quit)
20808 ;; Only when the isearch was not quitted.
20809 (org-add-hook 'post-command-hook 'org-isearch-post-command
20810 'append 'local)))))
20812 (defun org-isearch-post-command ()
20813 "Remove self from hook, and show context."
20814 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
20815 (org-show-context 'isearch))
20818 ;;;; Integration with and fixes for other packages
20820 ;;; Imenu support
20822 (defvar org-imenu-markers nil
20823 "All markers currently used by Imenu.")
20824 (make-variable-buffer-local 'org-imenu-markers)
20826 (defun org-imenu-new-marker (&optional pos)
20827 "Return a new marker for use by Imenu, and remember the marker."
20828 (let ((m (make-marker)))
20829 (move-marker m (or pos (point)))
20830 (push m org-imenu-markers)
20833 (defun org-imenu-get-tree ()
20834 "Produce the index for Imenu."
20835 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
20836 (setq org-imenu-markers nil)
20837 (let* ((n org-imenu-depth)
20838 (re (concat "^" (org-get-limited-outline-regexp)))
20839 (subs (make-vector (1+ n) nil))
20840 (last-level 0)
20841 m level head)
20842 (save-excursion
20843 (save-restriction
20844 (widen)
20845 (goto-char (point-max))
20846 (while (re-search-backward re nil t)
20847 (setq level (org-reduced-level (funcall outline-level)))
20848 (when (<= level n)
20849 (looking-at org-complex-heading-regexp)
20850 (setq head (org-link-display-format
20851 (org-match-string-no-properties 4))
20852 m (org-imenu-new-marker))
20853 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
20854 (if (>= level last-level)
20855 (push (cons head m) (aref subs level))
20856 (push (cons head (aref subs (1+ level))) (aref subs level))
20857 (loop for i from (1+ level) to n do (aset subs i nil)))
20858 (setq last-level level)))))
20859 (aref subs 1)))
20861 (eval-after-load "imenu"
20862 '(progn
20863 (add-hook 'imenu-after-jump-hook
20864 (lambda ()
20865 (if (eq major-mode 'org-mode)
20866 (org-show-context 'org-goto))))))
20868 (defun org-link-display-format (link)
20869 "Replace a link with either the description, or the link target
20870 if no description is present"
20871 (save-match-data
20872 (if (string-match org-bracket-link-analytic-regexp link)
20873 (replace-match (if (match-end 5)
20874 (match-string 5 link)
20875 (concat (match-string 1 link)
20876 (match-string 3 link)))
20877 nil t link)
20878 link)))
20880 (defun org-toggle-link-display ()
20881 "Toggle the literal or descriptive display of links."
20882 (interactive)
20883 (if org-descriptive-links
20884 (progn (org-remove-from-invisibility-spec '(org-link))
20885 (org-restart-font-lock)
20886 (setq org-descriptive-links nil))
20887 (progn (add-to-invisibility-spec '(org-link))
20888 (org-restart-font-lock)
20889 (setq org-descriptive-links t))))
20891 ;; Speedbar support
20893 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
20894 "Overlay marking the agenda restriction line in speedbar.")
20895 (overlay-put org-speedbar-restriction-lock-overlay
20896 'face 'org-agenda-restriction-lock)
20897 (overlay-put org-speedbar-restriction-lock-overlay
20898 'help-echo "Agendas are currently limited to this item.")
20899 (org-detach-overlay org-speedbar-restriction-lock-overlay)
20901 (defun org-speedbar-set-agenda-restriction ()
20902 "Restrict future agenda commands to the location at point in speedbar.
20903 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
20904 (interactive)
20905 (require 'org-agenda)
20906 (let (p m tp np dir txt)
20907 (cond
20908 ((setq p (text-property-any (point-at-bol) (point-at-eol)
20909 'org-imenu t))
20910 (setq m (get-text-property p 'org-imenu-marker))
20911 (with-current-buffer (marker-buffer m)
20912 (goto-char m)
20913 (org-agenda-set-restriction-lock 'subtree)))
20914 ((setq p (text-property-any (point-at-bol) (point-at-eol)
20915 'speedbar-function 'speedbar-find-file))
20916 (setq tp (previous-single-property-change
20917 (1+ p) 'speedbar-function)
20918 np (next-single-property-change
20919 tp 'speedbar-function)
20920 dir (speedbar-line-directory)
20921 txt (buffer-substring-no-properties (or tp (point-min))
20922 (or np (point-max))))
20923 (with-current-buffer (find-file-noselect
20924 (let ((default-directory dir))
20925 (expand-file-name txt)))
20926 (unless (eq major-mode 'org-mode)
20927 (error "Cannot restrict to non-Org-mode file"))
20928 (org-agenda-set-restriction-lock 'file)))
20929 (t (error "Don't know how to restrict Org-mode's agenda")))
20930 (move-overlay org-speedbar-restriction-lock-overlay
20931 (point-at-bol) (point-at-eol))
20932 (setq current-prefix-arg nil)
20933 (org-agenda-maybe-redo)))
20935 (eval-after-load "speedbar"
20936 '(progn
20937 (speedbar-add-supported-extension ".org")
20938 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
20939 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
20940 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
20941 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
20942 (add-hook 'speedbar-visiting-tag-hook
20943 (lambda () (and (eq major-mode 'org-mode) (org-show-context 'org-goto))))))
20945 ;;; Fixes and Hacks for problems with other packages
20947 ;; Make flyspell not check words in links, to not mess up our keymap
20948 (defun org-mode-flyspell-verify ()
20949 "Don't let flyspell put overlays at active buttons, or on
20950 {todo,all-time,additional-option-like}-keywords."
20951 (let ((pos (max (1- (point)) (point-min)))
20952 (word (thing-at-point 'word)))
20953 (and (not (get-text-property pos 'keymap))
20954 (not (get-text-property pos 'org-no-flyspell))
20955 (not (member word org-todo-keywords-1))
20956 (not (member word org-all-time-keywords))
20957 (not (member word org-additional-option-like-keywords)))))
20959 (defun org-remove-flyspell-overlays-in (beg end)
20960 "Remove flyspell overlays in region."
20961 (and (org-bound-and-true-p flyspell-mode)
20962 (fboundp 'flyspell-delete-region-overlays)
20963 (flyspell-delete-region-overlays beg end))
20964 (add-text-properties beg end '(org-no-flyspell t)))
20966 ;; Make `bookmark-jump' shows the jump location if it was hidden.
20967 (eval-after-load "bookmark"
20968 '(if (boundp 'bookmark-after-jump-hook)
20969 ;; We can use the hook
20970 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
20971 ;; Hook not available, use advice
20972 (defadvice bookmark-jump (after org-make-visible activate)
20973 "Make the position visible."
20974 (org-bookmark-jump-unhide))))
20976 ;; Make sure saveplace shows the location if it was hidden
20977 (eval-after-load "saveplace"
20978 '(defadvice save-place-find-file-hook (after org-make-visible activate)
20979 "Make the position visible."
20980 (org-bookmark-jump-unhide)))
20982 ;; Make sure ecb shows the location if it was hidden
20983 (eval-after-load "ecb"
20984 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
20985 "Make hierarchy visible when jumping into location from ECB tree buffer."
20986 (if (eq major-mode 'org-mode)
20987 (org-show-context))))
20989 (defun org-bookmark-jump-unhide ()
20990 "Unhide the current position, to show the bookmark location."
20991 (and (eq major-mode 'org-mode)
20992 (or (outline-invisible-p)
20993 (save-excursion (goto-char (max (point-min) (1- (point))))
20994 (outline-invisible-p)))
20995 (org-show-context 'bookmark-jump)))
20997 ;; Make session.el ignore our circular variable
20998 (eval-after-load "session"
20999 '(add-to-list 'session-globals-exclude 'org-mark-ring))
21001 ;;;; Experimental code
21003 (defun org-closed-in-range ()
21004 "Sparse tree of items closed in a certain time range.
21005 Still experimental, may disappear in the future."
21006 (interactive)
21007 ;; Get the time interval from the user.
21008 (let* ((time1 (org-float-time
21009 (org-read-date nil 'to-time nil "Starting date: ")))
21010 (time2 (org-float-time
21011 (org-read-date nil 'to-time nil "End date:")))
21012 ;; callback function
21013 (callback (lambda ()
21014 (let ((time
21015 (org-float-time
21016 (apply 'encode-time
21017 (org-parse-time-string
21018 (match-string 1))))))
21019 ;; check if time in interval
21020 (and (>= time time1) (<= time time2))))))
21021 ;; make tree, check each match with the callback
21022 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
21024 ;;;; Finish up
21026 (provide 'org)
21028 (run-hooks 'org-load-hook)
21030 ;;; org.el ends here