org.el: tiny docstring fix.
[org-mode.git] / lisp / org.el
blobd57845aeffde56efa6222261e8e3cb93e8b7d3fc
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 "Gnuplot" gnuplot)
168 (const :tag "Haskell" haskell)
169 (const :tag "Java" java)
170 (const :tag "Javascript" js)
171 (const :tag "Latex" latex)
172 (const :tag "Ledger" ledger)
173 (const :tag "Lilypond" lilypond)
174 (const :tag "Maxima" maxima)
175 (const :tag "Matlab" matlab)
176 (const :tag "Mscgen" mscgen)
177 (const :tag "Ocaml" ocaml)
178 (const :tag "Octave" octave)
179 (const :tag "Org" org)
180 (const :tag "Perl" perl)
181 (const :tag "PlantUML" plantuml)
182 (const :tag "Python" python)
183 (const :tag "Ruby" ruby)
184 (const :tag "Sass" sass)
185 (const :tag "Scheme" scheme)
186 (const :tag "Screen" screen)
187 (const :tag "Shell Script" sh)
188 (const :tag "Sql" sql)
189 (const :tag "Sqlite" sqlite))
190 :value-type (boolean :tag "Activate" :value t)))
192 ;;;; Customization variables
193 (defcustom org-clone-delete-id nil
194 "Remove ID property of clones of a subtree.
195 When non-nil, clones of a subtree don't inherit the ID property.
196 Otherwise they inherit the ID property with a new unique
197 identifier."
198 :type 'boolean
199 :group 'org-id)
201 ;;; Version
203 (defconst org-version "7.7"
204 "The version number of the file org.el.")
206 (defun org-version (&optional here)
207 "Show the org-mode version in the echo area.
208 With prefix arg HERE, insert it at point."
209 (interactive "P")
210 (let* ((origin default-directory)
211 (version org-version)
212 (git-version)
213 (dir (concat (file-name-directory (locate-library "org")) "../" )))
214 (when (and (file-exists-p (expand-file-name ".git" dir))
215 (executable-find "git"))
216 (unwind-protect
217 (progn
218 (cd dir)
219 (when (eql 0 (shell-command "git describe --abbrev=4 HEAD"))
220 (with-current-buffer "*Shell Command Output*"
221 (goto-char (point-min))
222 (setq git-version (buffer-substring (point) (point-at-eol))))
223 (subst-char-in-string ?- ?. git-version t)
224 (when (string-match "\\S-"
225 (shell-command-to-string
226 "git diff-index --name-only HEAD --"))
227 (setq git-version (concat git-version ".dirty")))
228 (setq version (concat version " (" git-version ")"))))
229 (cd origin)))
230 (setq version (format "Org-mode version %s" version))
231 (if here (insert version))
232 (message version)))
234 ;;; Compatibility constants
236 ;;; The custom variables
238 (defgroup org nil
239 "Outline-based notes management and organizer."
240 :tag "Org"
241 :group 'outlines
242 :group 'calendar)
244 (defcustom org-mode-hook nil
245 "Mode hook for Org-mode, run after the mode was turned on."
246 :group 'org
247 :type 'hook)
249 (defcustom org-load-hook nil
250 "Hook that is run after org.el has been loaded."
251 :group 'org
252 :type 'hook)
254 (defcustom org-log-buffer-setup-hook nil
255 "Hook that is run after an Org log buffer is created."
256 :group 'org
257 :type 'hook)
259 (defvar org-modules) ; defined below
260 (defvar org-modules-loaded nil
261 "Have the modules been loaded already?")
263 (defun org-load-modules-maybe (&optional force)
264 "Load all extensions listed in `org-modules'."
265 (when (or force (not org-modules-loaded))
266 (mapc (lambda (ext)
267 (condition-case nil (require ext)
268 (error (message "Problems while trying to load feature `%s'" ext))))
269 org-modules)
270 (setq org-modules-loaded t)))
272 (defun org-set-modules (var value)
273 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
274 (set var value)
275 (when (featurep 'org)
276 (org-load-modules-maybe 'force)))
278 (when (org-bound-and-true-p org-modules)
279 (let ((a (member 'org-infojs org-modules)))
280 (and a (setcar a 'org-jsinfo))))
282 (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)
283 "Modules that should always be loaded together with org.el.
284 If a description starts with <C>, the file is not part of Emacs
285 and loading it will require that you have downloaded and properly installed
286 the org-mode distribution.
288 You can also use this system to load external packages (i.e. neither Org
289 core modules, nor modules from the CONTRIB directory). Just add symbols
290 to the end of the list. If the package is called org-xyz.el, then you need
291 to add the symbol `xyz', and the package must have a call to
293 (provide 'org-xyz)"
294 :group 'org
295 :set 'org-set-modules
296 :type
297 '(set :greedy t
298 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
299 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
300 (const :tag " crypt: Encryption of subtrees" org-crypt)
301 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
302 (const :tag " docview: Links to doc-view buffers" org-docview)
303 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
304 (const :tag " id: Global IDs for identifying entries" org-id)
305 (const :tag " info: Links to Info nodes" org-info)
306 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
307 (const :tag " habit: Track your consistency with habits" org-habit)
308 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
309 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
310 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
311 (const :tag " mew Links to Mew folders/messages" org-mew)
312 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
313 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
314 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
315 (const :tag " special-blocks: Turn blocks into LaTeX envs and HTML divs" org-special-blocks)
316 (const :tag " vm: Links to VM folders/messages" org-vm)
317 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
318 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
319 (const :tag " mouse: Additional mouse support" org-mouse)
320 (const :tag " TaskJuggler: Export tasks to a TaskJuggler project" org-taskjuggler)
322 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
323 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
324 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
325 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
326 (const :tag "C collector: Collect properties into tables" org-collector)
327 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
328 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
329 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
330 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
331 (const :tag "C eval: Include command output as text" org-eval)
332 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
333 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
334 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
335 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
336 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
338 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
340 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
341 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
342 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
343 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
344 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
345 (const :tag "C mac-link-grabber Grab links and URLs from various Mac applications" org-mac-link-grabber)
346 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
347 (const :tag "C mtags: Support for muse-like tags" org-mtags)
348 (const :tag "C odt: OpenDocumentText exporter for Org-mode" org-odt)
349 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
350 (const :tag "C registry: A registry for Org-mode links" org-registry)
351 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
352 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
353 (const :tag "C secretary: Team management with org-mode" org-secretary)
354 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
355 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
356 (const :tag "C track: Keep up with Org-mode development" org-track)
357 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
358 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
359 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
361 (defcustom org-support-shift-select nil
362 "Non-nil means make shift-cursor commands select text when possible.
364 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
365 start selecting a region, or enlarge regions started in this way.
366 In Org-mode, in special contexts, these same keys are used for
367 other purposes, important enough to compete with shift selection.
368 Org tries to balance these needs by supporting `shift-select-mode'
369 outside these special contexts, under control of this variable.
371 The default of this variable is nil, to avoid confusing behavior. Shifted
372 cursor keys will then execute Org commands in the following contexts:
373 - on a headline, changing TODO state (left/right) and priority (up/down)
374 - on a time stamp, changing the time
375 - in a plain list item, changing the bullet type
376 - in a property definition line, switching between allowed values
377 - in the BEGIN line of a clock table (changing the time block).
378 Outside these contexts, the commands will throw an error.
380 When this variable is t and the cursor is not in a special
381 context, Org-mode will support shift-selection for making and
382 enlarging regions. To make this more effective, the bullet
383 cycling will no longer happen anywhere in an item line, but only
384 if the cursor is exactly on the bullet.
386 If you set this variable to the symbol `always', then the keys
387 will not be special in headlines, property lines, and item lines,
388 to make shift selection work there as well. If this is what you
389 want, you can use the following alternative commands: `C-c C-t'
390 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
391 can be used to switch TODO sets, `C-c -' to cycle item bullet
392 types, and properties can be edited by hand or in column view.
394 However, when the cursor is on a timestamp, shift-cursor commands
395 will still edit the time stamp - this is just too good to give up.
397 XEmacs user should have this variable set to nil, because
398 `shift-select-mode' is in Emacs 23 or later only."
399 :group 'org
400 :type '(choice
401 (const :tag "Never" nil)
402 (const :tag "When outside special context" t)
403 (const :tag "Everywhere except timestamps" always)))
405 (defgroup org-startup nil
406 "Options concerning startup of Org-mode."
407 :tag "Org Startup"
408 :group 'org)
410 (defcustom org-startup-folded t
411 "Non-nil means entering Org-mode will switch to OVERVIEW.
412 This can also be configured on a per-file basis by adding one of
413 the following lines anywhere in the buffer:
415 #+STARTUP: fold (or `overview', this is equivalent)
416 #+STARTUP: nofold (or `showall', this is equivalent)
417 #+STARTUP: content
418 #+STARTUP: showeverything"
419 :group 'org-startup
420 :type '(choice
421 (const :tag "nofold: show all" nil)
422 (const :tag "fold: overview" t)
423 (const :tag "content: all headlines" content)
424 (const :tag "show everything, even drawers" showeverything)))
426 (defcustom org-startup-truncated t
427 "Non-nil means entering Org-mode will set `truncate-lines'.
428 This is useful since some lines containing links can be very long and
429 uninteresting. Also tables look terrible when wrapped."
430 :group 'org-startup
431 :type 'boolean)
433 (defcustom org-startup-indented nil
434 "Non-nil means turn on `org-indent-mode' on startup.
435 This can also be configured on a per-file basis by adding one of
436 the following lines anywhere in the buffer:
438 #+STARTUP: indent
439 #+STARTUP: noindent"
440 :group 'org-structure
441 :type '(choice
442 (const :tag "Not" nil)
443 (const :tag "Globally (slow on startup in large files)" t)))
445 (defcustom org-use-sub-superscripts t
446 "Non-nil means interpret \"_\" and \"^\" for export.
447 When this option is turned on, you can use TeX-like syntax for sub- and
448 superscripts. Several characters after \"_\" or \"^\" will be
449 considered as a single item - so grouping with {} is normally not
450 needed. For example, the following things will be parsed as single
451 sub- or superscripts.
453 10^24 or 10^tau several digits will be considered 1 item.
454 10^-12 or 10^-tau a leading sign with digits or a word
455 x^2-y^3 will be read as x^2 - y^3, because items are
456 terminated by almost any nonword/nondigit char.
457 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
459 Still, ambiguity is possible - so when in doubt use {} to enclose the
460 sub/superscript. If you set this variable to the symbol `{}',
461 the braces are *required* in order to trigger interpretations as
462 sub/superscript. This can be helpful in documents that need \"_\"
463 frequently in plain text.
465 Not all export backends support this, but HTML does.
467 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
468 :group 'org-startup
469 :group 'org-export-translation
470 :type '(choice
471 (const :tag "Always interpret" t)
472 (const :tag "Only with braces" {})
473 (const :tag "Never interpret" nil)))
475 (if (fboundp 'defvaralias)
476 (defvaralias 'org-export-with-sub-superscripts 'org-use-sub-superscripts))
479 (defcustom org-startup-with-beamer-mode nil
480 "Non-nil means turn on `org-beamer-mode' on startup.
481 This can also be configured on a per-file basis by adding one of
482 the following lines anywhere in the buffer:
484 #+STARTUP: beamer"
485 :group 'org-startup
486 :type 'boolean)
488 (defcustom org-startup-align-all-tables nil
489 "Non-nil means align all tables when visiting a file.
490 This is useful when the column width in tables is forced with <N> cookies
491 in table fields. Such tables will look correct only after the first re-align.
492 This can also be configured on a per-file basis by adding one of
493 the following lines anywhere in the buffer:
494 #+STARTUP: align
495 #+STARTUP: noalign"
496 :group 'org-startup
497 :type 'boolean)
499 (defcustom org-startup-with-inline-images nil
500 "Non-nil means show inline images when loading a new Org file.
501 This can also be configured on a per-file basis by adding one of
502 the following lines anywhere in the buffer:
503 #+STARTUP: inlineimages
504 #+STARTUP: noinlineimages"
505 :group 'org-startup
506 :type 'boolean)
508 (defcustom org-insert-mode-line-in-empty-file nil
509 "Non-nil means insert the first line setting Org-mode in empty files.
510 When the function `org-mode' is called interactively in an empty file, this
511 normally means that the file name does not automatically trigger Org-mode.
512 To ensure that the file will always be in Org-mode in the future, a
513 line enforcing Org-mode will be inserted into the buffer, if this option
514 has been set."
515 :group 'org-startup
516 :type 'boolean)
518 (defcustom org-replace-disputed-keys nil
519 "Non-nil means use alternative key bindings for some keys.
520 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
521 These keys are also used by other packages like shift-selection-mode'
522 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
523 If you want to use Org-mode together with one of these other modes,
524 or more generally if you would like to move some Org-mode commands to
525 other keys, set this variable and configure the keys with the variable
526 `org-disputed-keys'.
528 This option is only relevant at load-time of Org-mode, and must be set
529 *before* org.el is loaded. Changing it requires a restart of Emacs to
530 become effective."
531 :group 'org-startup
532 :type 'boolean)
534 (defcustom org-use-extra-keys nil
535 "Non-nil means use extra key sequence definitions for certain commands.
536 This happens automatically if you run XEmacs or if `window-system'
537 is nil. This variable lets you do the same manually. You must
538 set it before loading org.
540 Example: on Carbon Emacs 22 running graphically, with an external
541 keyboard on a Powerbook, the default way of setting M-left might
542 not work for either Alt or ESC. Setting this variable will make
543 it work for ESC."
544 :group 'org-startup
545 :type 'boolean)
547 (if (fboundp 'defvaralias)
548 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
550 (defcustom org-disputed-keys
551 '(([(shift up)] . [(meta p)])
552 ([(shift down)] . [(meta n)])
553 ([(shift left)] . [(meta -)])
554 ([(shift right)] . [(meta +)])
555 ([(control shift right)] . [(meta shift +)])
556 ([(control shift left)] . [(meta shift -)]))
557 "Keys for which Org-mode and other modes compete.
558 This is an alist, cars are the default keys, second element specifies
559 the alternative to use when `org-replace-disputed-keys' is t.
561 Keys can be specified in any syntax supported by `define-key'.
562 The value of this option takes effect only at Org-mode's startup,
563 therefore you'll have to restart Emacs to apply it after changing."
564 :group 'org-startup
565 :type 'alist)
567 (defun org-key (key)
568 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
569 Or return the original if not disputed.
570 Also apply the translations defined in `org-xemacs-key-equivalents'."
571 (when org-replace-disputed-keys
572 (let* ((nkey (key-description key))
573 (x (org-find-if (lambda (x)
574 (equal (key-description (car x)) nkey))
575 org-disputed-keys)))
576 (setq key (if x (cdr x) key))))
577 (when (featurep 'xemacs)
578 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
579 key)
581 (defun org-find-if (predicate seq)
582 (catch 'exit
583 (while seq
584 (if (funcall predicate (car seq))
585 (throw 'exit (car seq))
586 (pop seq)))))
588 (defun org-defkey (keymap key def)
589 "Define a key, possibly translated, as returned by `org-key'."
590 (define-key keymap (org-key key) def))
592 (defcustom org-ellipsis nil
593 "The ellipsis to use in the Org-mode outline.
594 When nil, just use the standard three dots. When a string, use that instead,
595 When a face, use the standard 3 dots, but with the specified face.
596 The change affects only Org-mode (which will then use its own display table).
597 Changing this requires executing `M-x org-mode' in a buffer to become
598 effective."
599 :group 'org-startup
600 :type '(choice (const :tag "Default" nil)
601 (face :tag "Face" :value org-warning)
602 (string :tag "String" :value "...#")))
604 (defvar org-display-table nil
605 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
607 (defgroup org-keywords nil
608 "Keywords in Org-mode."
609 :tag "Org Keywords"
610 :group 'org)
612 (defcustom org-deadline-string "DEADLINE:"
613 "String to mark deadline entries.
614 A deadline is this string, followed by a time stamp. Should be a word,
615 terminated by a colon. You can insert a schedule keyword and
616 a timestamp with \\[org-deadline].
617 Changes become only effective after restarting Emacs."
618 :group 'org-keywords
619 :type 'string)
621 (defcustom org-scheduled-string "SCHEDULED:"
622 "String to mark scheduled TODO entries.
623 A schedule is this string, followed by a time stamp. Should be a word,
624 terminated by a colon. You can insert a schedule keyword and
625 a timestamp with \\[org-schedule].
626 Changes become only effective after restarting Emacs."
627 :group 'org-keywords
628 :type 'string)
630 (defcustom org-closed-string "CLOSED:"
631 "String used as the prefix for timestamps logging closing a TODO entry."
632 :group 'org-keywords
633 :type 'string)
635 (defcustom org-clock-string "CLOCK:"
636 "String used as prefix for timestamps clocking work hours on an item."
637 :group 'org-keywords
638 :type 'string)
640 (defcustom org-comment-string "COMMENT"
641 "Entries starting with this keyword will never be exported.
642 An entry can be toggled between COMMENT and normal with
643 \\[org-toggle-comment].
644 Changes become only effective after restarting Emacs."
645 :group 'org-keywords
646 :type 'string)
648 (defcustom org-quote-string "QUOTE"
649 "Entries starting with this keyword will be exported in fixed-width font.
650 Quoting applies only to the text in the entry following the headline, and does
651 not extend beyond the next headline, even if that is lower level.
652 An entry can be toggled between QUOTE and normal with
653 \\[org-toggle-fixed-width-section]."
654 :group 'org-keywords
655 :type 'string)
657 (defconst org-repeat-re
658 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)"
659 "Regular expression for specifying repeated events.
660 After a match, group 1 contains the repeat expression.")
662 (defgroup org-structure nil
663 "Options concerning the general structure of Org-mode files."
664 :tag "Org Structure"
665 :group 'org)
667 (defgroup org-reveal-location nil
668 "Options about how to make context of a location visible."
669 :tag "Org Reveal Location"
670 :group 'org-structure)
672 (defconst org-context-choice
673 '(choice
674 (const :tag "Always" t)
675 (const :tag "Never" nil)
676 (repeat :greedy t :tag "Individual contexts"
677 (cons
678 (choice :tag "Context"
679 (const agenda)
680 (const org-goto)
681 (const occur-tree)
682 (const tags-tree)
683 (const link-search)
684 (const mark-goto)
685 (const bookmark-jump)
686 (const isearch)
687 (const default))
688 (boolean))))
689 "Contexts for the reveal options.")
691 (defcustom org-show-hierarchy-above '((default . t))
692 "Non-nil means show full hierarchy when revealing a location.
693 Org-mode often shows locations in an org-mode file which might have
694 been invisible before. When this is set, the hierarchy of headings
695 above the exposed location is shown.
696 Turning this off for example for sparse trees makes them very compact.
697 Instead of t, this can also be an alist specifying this option for different
698 contexts. Valid contexts are
699 agenda when exposing an entry from the agenda
700 org-goto when using the command `org-goto' on key C-c C-j
701 occur-tree when using the command `org-occur' on key C-c /
702 tags-tree when constructing a sparse tree based on tags matches
703 link-search when exposing search matches associated with a link
704 mark-goto when exposing the jump goal of a mark
705 bookmark-jump when exposing a bookmark location
706 isearch when exiting from an incremental search
707 default default for all contexts not set explicitly"
708 :group 'org-reveal-location
709 :type org-context-choice)
711 (defcustom org-show-following-heading '((default . nil))
712 "Non-nil means show following heading when revealing a location.
713 Org-mode often shows locations in an org-mode file which might have
714 been invisible before. When this is set, the heading following the
715 match is shown.
716 Turning this off for example for sparse trees makes them very compact,
717 but makes it harder to edit the location of the match. In such a case,
718 use the command \\[org-reveal] to show more context.
719 Instead of t, this can also be an alist specifying this option for different
720 contexts. See `org-show-hierarchy-above' for valid contexts."
721 :group 'org-reveal-location
722 :type org-context-choice)
724 (defcustom org-show-siblings '((default . nil) (isearch t))
725 "Non-nil means show all sibling heading when revealing a location.
726 Org-mode often shows locations in an org-mode file which might have
727 been invisible before. When this is set, the sibling of the current entry
728 heading are all made visible. If `org-show-hierarchy-above' is t,
729 the same happens on each level of the hierarchy above the current entry.
731 By default this is on for the isearch context, off for all other contexts.
732 Turning this off for example for sparse trees makes them very compact,
733 but makes it harder to edit the location of the match. In such a case,
734 use the command \\[org-reveal] to show more context.
735 Instead of t, this can also be an alist specifying this option for different
736 contexts. See `org-show-hierarchy-above' for valid contexts."
737 :group 'org-reveal-location
738 :type org-context-choice)
740 (defcustom org-show-entry-below '((default . nil))
741 "Non-nil means show the entry below a headline when revealing a location.
742 Org-mode often shows locations in an org-mode file which might have
743 been invisible before. When this is set, the text below the headline that is
744 exposed is also shown.
746 By default this is off for all contexts.
747 Instead of t, this can also be an alist specifying this option for different
748 contexts. See `org-show-hierarchy-above' for valid contexts."
749 :group 'org-reveal-location
750 :type org-context-choice)
752 (defcustom org-indirect-buffer-display 'other-window
753 "How should indirect tree buffers be displayed?
754 This applies to indirect buffers created with the commands
755 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
756 Valid values are:
757 current-window Display in the current window
758 other-window Just display in another window.
759 dedicated-frame Create one new frame, and re-use it each time.
760 new-frame Make a new frame each time. Note that in this case
761 previously-made indirect buffers are kept, and you need to
762 kill these buffers yourself."
763 :group 'org-structure
764 :group 'org-agenda-windows
765 :type '(choice
766 (const :tag "In current window" current-window)
767 (const :tag "In current frame, other window" other-window)
768 (const :tag "Each time a new frame" new-frame)
769 (const :tag "One dedicated frame" dedicated-frame)))
771 (defcustom org-use-speed-commands nil
772 "Non-nil means activate single letter commands at beginning of a headline.
773 This may also be a function to test for appropriate locations where speed
774 commands should be active."
775 :group 'org-structure
776 :type '(choice
777 (const :tag "Never" nil)
778 (const :tag "At beginning of headline stars" t)
779 (function)))
781 (defcustom org-speed-commands-user nil
782 "Alist of additional speed commands.
783 This list will be checked before `org-speed-commands-default'
784 when the variable `org-use-speed-commands' is non-nil
785 and when the cursor is at the beginning of a headline.
786 The car if each entry is a string with a single letter, which must
787 be assigned to `self-insert-command' in the global map.
788 The cdr is either a command to be called interactively, a function
789 to be called, or a form to be evaluated.
790 An entry that is just a list with a single string will be interpreted
791 as a descriptive headline that will be added when listing the speed
792 commands in the Help buffer using the `?' speed command."
793 :group 'org-structure
794 :type '(repeat :value ("k" . ignore)
795 (choice :value ("k" . ignore)
796 (list :tag "Descriptive Headline" (string :tag "Headline"))
797 (cons :tag "Letter and Command"
798 (string :tag "Command letter")
799 (choice
800 (function)
801 (sexp))))))
803 (defgroup org-cycle nil
804 "Options concerning visibility cycling in Org-mode."
805 :tag "Org Cycle"
806 :group 'org-structure)
808 (defcustom org-cycle-skip-children-state-if-no-children t
809 "Non-nil means skip CHILDREN state in entries that don't have any."
810 :group 'org-cycle
811 :type 'boolean)
813 (defcustom org-cycle-max-level nil
814 "Maximum level which should still be subject to visibility cycling.
815 Levels higher than this will, for cycling, be treated as text, not a headline.
816 When `org-odd-levels-only' is set, a value of N in this variable actually
817 means 2N-1 stars as the limiting headline.
818 When nil, cycle all levels.
819 Note that the limiting level of cycling is also influenced by
820 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
821 `org-inlinetask-min-level' is, cycling will be limited to levels one less
822 than its value."
823 :group 'org-cycle
824 :type '(choice
825 (const :tag "No limit" nil)
826 (integer :tag "Maximum level")))
828 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK")
829 "Names of drawers. Drawers are not opened by cycling on the headline above.
830 Drawers only open with a TAB on the drawer line itself. A drawer looks like
831 this:
832 :DRAWERNAME:
833 .....
834 :END:
835 The drawer \"PROPERTIES\" is special for capturing properties through
836 the property API.
838 Drawers can be defined on the per-file basis with a line like:
840 #+DRAWERS: HIDDEN STATE PROPERTIES"
841 :group 'org-structure
842 :group 'org-cycle
843 :type '(repeat (string :tag "Drawer Name")))
845 (defcustom org-hide-block-startup nil
846 "Non-nil means entering Org-mode will fold all blocks.
847 This can also be set in on a per-file basis with
849 #+STARTUP: hideblocks
850 #+STARTUP: showblocks"
851 :group 'org-startup
852 :group 'org-cycle
853 :type 'boolean)
855 (defcustom org-cycle-global-at-bob nil
856 "Cycle globally if cursor is at beginning of buffer and not at a headline.
857 This makes it possible to do global cycling without having to use S-TAB or
858 \\[universal-argument] TAB. For this special case to work, the first line \
859 of the buffer
860 must not be a headline - it may be empty or some other text. When used in
861 this way, `org-cycle-hook' is disables temporarily, to make sure the
862 cursor stays at the beginning of the buffer.
863 When this option is nil, don't do anything special at the beginning
864 of the buffer."
865 :group 'org-cycle
866 :type 'boolean)
868 (defcustom org-cycle-level-after-item/entry-creation t
869 "Non-nil means cycle entry level or item indentation in new empty entries.
871 When the cursor is at the end of an empty headline, i.e with only stars
872 and maybe a TODO keyword, TAB will then switch the entry to become a child,
873 and then all possible ancestor states, before returning to the original state.
874 This makes data entry extremely fast: M-RET to create a new headline,
875 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
877 When the cursor is at the end of an empty plain list item, one TAB will
878 make it a subitem, two or more tabs will back up to make this an item
879 higher up in the item hierarchy."
880 :group 'org-cycle
881 :type 'boolean)
883 (defcustom org-cycle-emulate-tab t
884 "Where should `org-cycle' emulate TAB.
885 nil Never
886 white Only in completely white lines
887 whitestart Only at the beginning of lines, before the first non-white char
888 t Everywhere except in headlines
889 exc-hl-bol Everywhere except at the start of a headline
890 If TAB is used in a place where it does not emulate TAB, the current subtree
891 visibility is cycled."
892 :group 'org-cycle
893 :type '(choice (const :tag "Never" nil)
894 (const :tag "Only in completely white lines" white)
895 (const :tag "Before first char in a line" whitestart)
896 (const :tag "Everywhere except in headlines" t)
897 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
900 (defcustom org-cycle-separator-lines 2
901 "Number of empty lines needed to keep an empty line between collapsed trees.
902 If you leave an empty line between the end of a subtree and the following
903 headline, this empty line is hidden when the subtree is folded.
904 Org-mode will leave (exactly) one empty line visible if the number of
905 empty lines is equal or larger to the number given in this variable.
906 So the default 2 means at least 2 empty lines after the end of a subtree
907 are needed to produce free space between a collapsed subtree and the
908 following headline.
910 If the number is negative, and the number of empty lines is at least -N,
911 all empty lines are shown.
913 Special case: when 0, never leave empty lines in collapsed view."
914 :group 'org-cycle
915 :type 'integer)
916 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
918 (defcustom org-pre-cycle-hook nil
919 "Hook that is run before visibility cycling is happening.
920 The function(s) in this hook must accept a single argument which indicates
921 the new state that will be set right after running this hook. The
922 argument is a symbol. Before a global state change, it can have the values
923 `overview', `content', or `all'. Before a local state change, it can have
924 the values `folded', `children', or `subtree'."
925 :group 'org-cycle
926 :type 'hook)
928 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
929 org-cycle-hide-drawers
930 org-cycle-show-empty-lines
931 org-optimize-window-after-visibility-change)
932 "Hook that is run after `org-cycle' has changed the buffer visibility.
933 The function(s) in this hook must accept a single argument which indicates
934 the new state that was set by the most recent `org-cycle' command. The
935 argument is a symbol. After a global state change, it can have the values
936 `overview', `content', or `all'. After a local state change, it can have
937 the values `folded', `children', or `subtree'."
938 :group 'org-cycle
939 :type 'hook)
941 (defgroup org-edit-structure nil
942 "Options concerning structure editing in Org-mode."
943 :tag "Org Edit Structure"
944 :group 'org-structure)
946 (defcustom org-odd-levels-only nil
947 "Non-nil means skip even levels and only use odd levels for the outline.
948 This has the effect that two stars are being added/taken away in
949 promotion/demotion commands. It also influences how levels are
950 handled by the exporters.
951 Changing it requires restart of `font-lock-mode' to become effective
952 for fontification also in regions already fontified.
953 You may also set this on a per-file basis by adding one of the following
954 lines to the buffer:
956 #+STARTUP: odd
957 #+STARTUP: oddeven"
958 :group 'org-edit-structure
959 :group 'org-appearance
960 :type 'boolean)
962 (defcustom org-adapt-indentation t
963 "Non-nil means adapt indentation to outline node level.
965 When this variable is set, Org assumes that you write outlines by
966 indenting text in each node to align with the headline (after the stars).
967 The following issues are influenced by this variable:
969 - When this is set and the *entire* text in an entry is indented, the
970 indentation is increased by one space in a demotion command, and
971 decreased by one in a promotion command. If any line in the entry
972 body starts with text at column 0, indentation is not changed at all.
974 - Property drawers and planning information is inserted indented when
975 this variable s set. When nil, they will not be indented.
977 - TAB indents a line relative to context. The lines below a headline
978 will be indented when this variable is set.
980 Note that this is all about true indentation, by adding and removing
981 space characters. See also `org-indent.el' which does level-dependent
982 indentation in a virtual way, i.e. at display time in Emacs."
983 :group 'org-edit-structure
984 :type 'boolean)
986 (defcustom org-special-ctrl-a/e nil
987 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
989 When t, `C-a' will bring back the cursor to the beginning of the
990 headline text, i.e. after the stars and after a possible TODO keyword.
991 In an item, this will be the position after the bullet.
992 When the cursor is already at that position, another `C-a' will bring
993 it to the beginning of the line.
995 `C-e' will jump to the end of the headline, ignoring the presence of tags
996 in the headline. A second `C-e' will then jump to the true end of the
997 line, after any tags. This also means that, when this variable is
998 non-nil, `C-e' also will never jump beyond the end of the heading of a
999 folded section, i.e. not after the ellipses.
1001 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
1002 going to the true line boundary first. Only a directly following, identical
1003 keypress will bring the cursor to the special positions.
1005 This may also be a cons cell where the behavior for `C-a' and `C-e' is
1006 set separately."
1007 :group 'org-edit-structure
1008 :type '(choice
1009 (const :tag "off" nil)
1010 (const :tag "on: after stars/bullet and before tags first" t)
1011 (const :tag "reversed: true line boundary first" reversed)
1012 (cons :tag "Set C-a and C-e separately"
1013 (choice :tag "Special C-a"
1014 (const :tag "off" nil)
1015 (const :tag "on: after stars/bullet first" t)
1016 (const :tag "reversed: before stars/bullet first" reversed))
1017 (choice :tag "Special C-e"
1018 (const :tag "off" nil)
1019 (const :tag "on: before tags first" t)
1020 (const :tag "reversed: after tags first" reversed)))))
1021 (if (fboundp 'defvaralias)
1022 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
1024 (defcustom org-special-ctrl-k nil
1025 "Non-nil means `C-k' will behave specially in headlines.
1026 When nil, `C-k' will call the default `kill-line' command.
1027 When t, the following will happen while the cursor is in the headline:
1029 - When the cursor is at the beginning of a headline, kill the entire
1030 line and possible the folded subtree below the line.
1031 - When in the middle of the headline text, kill the headline up to the tags.
1032 - When after the headline text, kill the tags."
1033 :group 'org-edit-structure
1034 :type 'boolean)
1036 (defcustom org-ctrl-k-protect-subtree nil
1037 "Non-nil means, do not delete a hidden subtree with C-k.
1038 When set to the symbol `error', simply throw an error when C-k is
1039 used to kill (part-of) a headline that has hidden text behind it.
1040 Any other non-nil value will result in a query to the user, if it is
1041 OK to kill that hidden subtree. When nil, kill without remorse."
1042 :group 'org-edit-structure
1043 :type '(choice
1044 (const :tag "Do not protect hidden subtrees" nil)
1045 (const :tag "Protect hidden subtrees with a security query" t)
1046 (const :tag "Never kill a hidden subtree with C-k" error)))
1048 (defcustom org-yank-folded-subtrees t
1049 "Non-nil means when yanking subtrees, fold them.
1050 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1051 it starts with a heading and all other headings in it are either children
1052 or siblings, then fold all the subtrees. However, do this only if no
1053 text after the yank would be swallowed into a folded tree by this action."
1054 :group 'org-edit-structure
1055 :type 'boolean)
1057 (defcustom org-yank-adjusted-subtrees nil
1058 "Non-nil means when yanking subtrees, adjust the level.
1059 With this setting, `org-paste-subtree' is used to insert the subtree, see
1060 this function for details."
1061 :group 'org-edit-structure
1062 :type 'boolean)
1064 (defcustom org-M-RET-may-split-line '((default . t))
1065 "Non-nil means M-RET will split the line at the cursor position.
1066 When nil, it will go to the end of the line before making a
1067 new line.
1068 You may also set this option in a different way for different
1069 contexts. Valid contexts are:
1071 headline when creating a new headline
1072 item when creating a new item
1073 table in a table field
1074 default the value to be used for all contexts not explicitly
1075 customized"
1076 :group 'org-structure
1077 :group 'org-table
1078 :type '(choice
1079 (const :tag "Always" t)
1080 (const :tag "Never" nil)
1081 (repeat :greedy t :tag "Individual contexts"
1082 (cons
1083 (choice :tag "Context"
1084 (const headline)
1085 (const item)
1086 (const table)
1087 (const default))
1088 (boolean)))))
1091 (defcustom org-insert-heading-respect-content nil
1092 "Non-nil means insert new headings after the current subtree.
1093 When nil, the new heading is created directly after the current line.
1094 The commands \\[org-insert-heading-respect-content] and
1095 \\[org-insert-todo-heading-respect-content] turn this variable on
1096 for the duration of the command."
1097 :group 'org-structure
1098 :type 'boolean)
1100 (defcustom org-blank-before-new-entry '((heading . auto)
1101 (plain-list-item . auto))
1102 "Should `org-insert-heading' leave a blank line before new heading/item?
1103 The value is an alist, with `heading' and `plain-list-item' as CAR,
1104 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1105 which case Org will look at the surrounding headings/items and try to
1106 make an intelligent decision whether to insert a blank line or not.
1108 For plain lists, if the variable `org-empty-line-terminates-plain-lists' is
1109 set, the setting here is ignored and no empty line is inserted, to avoid
1110 breaking the list structure."
1111 :group 'org-edit-structure
1112 :type '(list
1113 (cons (const heading)
1114 (choice (const :tag "Never" nil)
1115 (const :tag "Always" t)
1116 (const :tag "Auto" auto)))
1117 (cons (const plain-list-item)
1118 (choice (const :tag "Never" nil)
1119 (const :tag "Always" t)
1120 (const :tag "Auto" auto)))))
1122 (defcustom org-insert-heading-hook nil
1123 "Hook being run after inserting a new heading."
1124 :group 'org-edit-structure
1125 :type 'hook)
1127 (defcustom org-enable-fixed-width-editor t
1128 "Non-nil means lines starting with \":\" are treated as fixed-width.
1129 This currently only means they are never auto-wrapped.
1130 When nil, such lines will be treated like ordinary lines.
1131 See also the QUOTE keyword."
1132 :group 'org-edit-structure
1133 :type 'boolean)
1135 (defcustom org-goto-auto-isearch t
1136 "Non-nil means typing characters in `org-goto' starts incremental search."
1137 :group 'org-edit-structure
1138 :type 'boolean)
1140 (defgroup org-sparse-trees nil
1141 "Options concerning sparse trees in Org-mode."
1142 :tag "Org Sparse Trees"
1143 :group 'org-structure)
1145 (defcustom org-highlight-sparse-tree-matches t
1146 "Non-nil means highlight all matches that define a sparse tree.
1147 The highlights will automatically disappear the next time the buffer is
1148 changed by an edit command."
1149 :group 'org-sparse-trees
1150 :type 'boolean)
1152 (defcustom org-remove-highlights-with-change t
1153 "Non-nil means any change to the buffer will remove temporary highlights.
1154 Such highlights are created by `org-occur' and `org-clock-display'.
1155 When nil, `C-c C-c needs to be used to get rid of the highlights.
1156 The highlights created by `org-preview-latex-fragment' always need
1157 `C-c C-c' to be removed."
1158 :group 'org-sparse-trees
1159 :group 'org-time
1160 :type 'boolean)
1163 (defcustom org-occur-hook '(org-first-headline-recenter)
1164 "Hook that is run after `org-occur' has constructed a sparse tree.
1165 This can be used to recenter the window to show as much of the structure
1166 as possible."
1167 :group 'org-sparse-trees
1168 :type 'hook)
1170 (defgroup org-imenu-and-speedbar nil
1171 "Options concerning imenu and speedbar in Org-mode."
1172 :tag "Org Imenu and Speedbar"
1173 :group 'org-structure)
1175 (defcustom org-imenu-depth 2
1176 "The maximum level for Imenu access to Org-mode headlines.
1177 This also applied for speedbar access."
1178 :group 'org-imenu-and-speedbar
1179 :type 'integer)
1181 (defgroup org-table nil
1182 "Options concerning tables in Org-mode."
1183 :tag "Org Table"
1184 :group 'org)
1186 (defcustom org-enable-table-editor 'optimized
1187 "Non-nil means lines starting with \"|\" are handled by the table editor.
1188 When nil, such lines will be treated like ordinary lines.
1190 When equal to the symbol `optimized', the table editor will be optimized to
1191 do the following:
1192 - Automatic overwrite mode in front of whitespace in table fields.
1193 This makes the structure of the table stay in tact as long as the edited
1194 field does not exceed the column width.
1195 - Minimize the number of realigns. Normally, the table is aligned each time
1196 TAB or RET are pressed to move to another field. With optimization this
1197 happens only if changes to a field might have changed the column width.
1198 Optimization requires replacing the functions `self-insert-command',
1199 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1200 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1201 very good at guessing when a re-align will be necessary, but you can always
1202 force one with \\[org-ctrl-c-ctrl-c].
1204 If you would like to use the optimized version in Org-mode, but the
1205 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1207 This variable can be used to turn on and off the table editor during a session,
1208 but in order to toggle optimization, a restart is required.
1210 See also the variable `org-table-auto-blank-field'."
1211 :group 'org-table
1212 :type '(choice
1213 (const :tag "off" nil)
1214 (const :tag "on" t)
1215 (const :tag "on, optimized" optimized)))
1217 (defcustom org-self-insert-cluster-for-undo t
1218 "Non-nil means cluster self-insert commands for undo when possible.
1219 If this is set, then, like in the Emacs command loop, 20 consecutive
1220 characters will be undone together.
1221 This is configurable, because there is some impact on typing performance."
1222 :group 'org-table
1223 :type 'boolean)
1225 (defcustom org-table-tab-recognizes-table.el t
1226 "Non-nil means TAB will automatically notice a table.el table.
1227 When it sees such a table, it moves point into it and - if necessary -
1228 calls `table-recognize-table'."
1229 :group 'org-table-editing
1230 :type 'boolean)
1232 (defgroup org-link nil
1233 "Options concerning links in Org-mode."
1234 :tag "Org Link"
1235 :group 'org)
1237 (defvar org-link-abbrev-alist-local nil
1238 "Buffer-local version of `org-link-abbrev-alist', which see.
1239 The value of this is taken from the #+LINK lines.")
1240 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1242 (defcustom org-link-abbrev-alist nil
1243 "Alist of link abbreviations.
1244 The car of each element is a string, to be replaced at the start of a link.
1245 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1246 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1248 [[linkkey:tag][description]]
1250 The 'linkkey' must be a word word, starting with a letter, followed
1251 by letters, numbers, '-' or '_'.
1253 If REPLACE is a string, the tag will simply be appended to create the link.
1254 If the string contains \"%s\", the tag will be inserted there. Alternatively,
1255 the placeholder \"%h\" will cause a url-encoded version of the tag to
1256 be inserted at that point (see the function `url-hexify-string').
1258 REPLACE may also be a function that will be called with the tag as the
1259 only argument to create the link, which should be returned as a string.
1261 See the manual for examples."
1262 :group 'org-link
1263 :type '(repeat
1264 (cons
1265 (string :tag "Protocol")
1266 (choice
1267 (string :tag "Format")
1268 (function)))))
1270 (defcustom org-descriptive-links t
1271 "Non-nil means hide link part and only show description of bracket links.
1272 Bracket links are like [[link][description]]. This variable sets the initial
1273 state in new org-mode buffers. The setting can then be toggled on a
1274 per-buffer basis from the Org->Hyperlinks menu."
1275 :group 'org-link
1276 :type 'boolean)
1278 (defcustom org-link-file-path-type 'adaptive
1279 "How the path name in file links should be stored.
1280 Valid values are:
1282 relative Relative to the current directory, i.e. the directory of the file
1283 into which the link is being inserted.
1284 absolute Absolute path, if possible with ~ for home directory.
1285 noabbrev Absolute path, no abbreviation of home directory.
1286 adaptive Use relative path for files in the current directory and sub-
1287 directories of it. For other files, use an absolute path."
1288 :group 'org-link
1289 :type '(choice
1290 (const relative)
1291 (const absolute)
1292 (const noabbrev)
1293 (const adaptive)))
1295 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1296 "Types of links that should be activated in Org-mode files.
1297 This is a list of symbols, each leading to the activation of a certain link
1298 type. In principle, it does not hurt to turn on most link types - there may
1299 be a small gain when turning off unused link types. The types are:
1301 bracket The recommended [[link][description]] or [[link]] links with hiding.
1302 angle Links in angular brackets that may contain whitespace like
1303 <bbdb:Carsten Dominik>.
1304 plain Plain links in normal text, no whitespace, like http://google.com.
1305 radio Text that is matched by a radio target, see manual for details.
1306 tag Tag settings in a headline (link to tag search).
1307 date Time stamps (link to calendar).
1308 footnote Footnote labels.
1310 Changing this variable requires a restart of Emacs to become effective."
1311 :group 'org-link
1312 :type '(set :greedy t
1313 (const :tag "Double bracket links" bracket)
1314 (const :tag "Angular bracket links" angle)
1315 (const :tag "Plain text links" plain)
1316 (const :tag "Radio target matches" radio)
1317 (const :tag "Tags" tag)
1318 (const :tag "Timestamps" date)
1319 (const :tag "Footnotes" footnote)))
1321 (defcustom org-make-link-description-function nil
1322 "Function to use to generate link descriptions from links.
1323 If nil the link location will be used. This function must take
1324 two parameters; the first is the link and the second the
1325 description `org-insert-link' has generated, and should return the
1326 description to use."
1327 :group 'org-link
1328 :type 'function)
1330 (defcustom org-link-display-descriptive t
1331 "Non-nil means Org will display descriptive links.
1332 E.g. [[http://orgmode.org][Org website]] will be displayed as
1333 \"Org Website\", hiding the link itself and just displaying its
1334 description. When set to `nil', Org will display the full links
1335 literally.
1337 You can interactively set the value of this variable using the
1338 `org-toggle-link-display'."
1339 :group 'org-link
1340 :type 'boolean)
1342 (defgroup org-link-store nil
1343 "Options concerning storing links in Org-mode."
1344 :tag "Org Store Link"
1345 :group 'org-link)
1347 (defcustom org-email-link-description-format "Email %c: %.30s"
1348 "Format of the description part of a link to an email or usenet message.
1349 The following %-escapes will be replaced by corresponding information:
1351 %F full \"From\" field
1352 %f name, taken from \"From\" field, address if no name
1353 %T full \"To\" field
1354 %t first name in \"To\" field, address if no name
1355 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1356 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1357 %s subject
1358 %d date
1359 %m message-id.
1361 You may use normal field width specification between the % and the letter.
1362 This is for example useful to limit the length of the subject.
1364 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1365 :group 'org-link-store
1366 :type 'string)
1368 (defcustom org-from-is-user-regexp
1369 (let (r1 r2)
1370 (when (and user-mail-address (not (string= user-mail-address "")))
1371 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1372 (when (and user-full-name (not (string= user-full-name "")))
1373 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1374 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1375 "Regexp matched against the \"From:\" header of an email or usenet message.
1376 It should match if the message is from the user him/herself."
1377 :group 'org-link-store
1378 :type 'regexp)
1380 (defcustom org-link-to-org-use-id 'create-if-interactive-and-no-custom-id
1381 "Non-nil means storing a link to an Org file will use entry IDs.
1383 Note that before this variable is even considered, org-id must be loaded,
1384 so please customize `org-modules' and turn it on.
1386 The variable can have the following values:
1388 t Create an ID if needed to make a link to the current entry.
1390 create-if-interactive
1391 If `org-store-link' is called directly (interactively, as a user
1392 command), do create an ID to support the link. But when doing the
1393 job for remember, only use the ID if it already exists. The
1394 purpose of this setting is to avoid proliferation of unwanted
1395 IDs, just because you happen to be in an Org file when you
1396 call `org-remember' that automatically and preemptively
1397 creates a link. If you do want to get an ID link in a remember
1398 template to an entry not having an ID, create it first by
1399 explicitly creating a link to it, using `C-c C-l' first.
1401 create-if-interactive-and-no-custom-id
1402 Like create-if-interactive, but do not create an ID if there is
1403 a CUSTOM_ID property defined in the entry. This is the default.
1405 use-existing
1406 Use existing ID, do not create one.
1408 nil Never use an ID to make a link, instead link using a text search for
1409 the headline text."
1410 :group 'org-link-store
1411 :type '(choice
1412 (const :tag "Create ID to make link" t)
1413 (const :tag "Create if storing link interactively"
1414 create-if-interactive)
1415 (const :tag "Create if storing link interactively and no CUSTOM_ID is present"
1416 create-if-interactive-and-no-custom-id)
1417 (const :tag "Only use existing" use-existing)
1418 (const :tag "Do not use ID to create link" nil)))
1420 (defcustom org-context-in-file-links t
1421 "Non-nil means file links from `org-store-link' contain context.
1422 A search string will be added to the file name with :: as separator and
1423 used to find the context when the link is activated by the command
1424 `org-open-at-point'. When this option is t, the entire active region
1425 will be placed in the search string of the file link. If set to a
1426 positive integer, only the first n lines of context will be stored.
1428 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1429 negates this setting for the duration of the command."
1430 :group 'org-link-store
1431 :type '(choice boolean integer))
1433 (defcustom org-keep-stored-link-after-insertion nil
1434 "Non-nil means keep link in list for entire session.
1436 The command `org-store-link' adds a link pointing to the current
1437 location to an internal list. These links accumulate during a session.
1438 The command `org-insert-link' can be used to insert links into any
1439 Org-mode file (offering completion for all stored links). When this
1440 option is nil, every link which has been inserted once using \\[org-insert-link]
1441 will be removed from the list, to make completing the unused links
1442 more efficient."
1443 :group 'org-link-store
1444 :type 'boolean)
1446 (defgroup org-link-follow nil
1447 "Options concerning following links in Org-mode."
1448 :tag "Org Follow Link"
1449 :group 'org-link)
1451 (defcustom org-link-translation-function nil
1452 "Function to translate links with different syntax to Org syntax.
1453 This can be used to translate links created for example by the Planner
1454 or emacs-wiki packages to Org syntax.
1455 The function must accept two parameters, a TYPE containing the link
1456 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1457 which is everything after the link protocol. It should return a cons
1458 with possibly modified values of type and path.
1459 Org contains a function for this, so if you set this variable to
1460 `org-translate-link-from-planner', you should be able follow many
1461 links created by planner."
1462 :group 'org-link-follow
1463 :type 'function)
1465 (defcustom org-follow-link-hook nil
1466 "Hook that is run after a link has been followed."
1467 :group 'org-link-follow
1468 :type 'hook)
1470 (defcustom org-tab-follows-link nil
1471 "Non-nil means on links TAB will follow the link.
1472 Needs to be set before org.el is loaded.
1473 This really should not be used, it does not make sense, and the
1474 implementation is bad."
1475 :group 'org-link-follow
1476 :type 'boolean)
1478 (defcustom org-return-follows-link nil
1479 "Non-nil means on links RET will follow the link."
1480 :group 'org-link-follow
1481 :type 'boolean)
1483 (defcustom org-mouse-1-follows-link
1484 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1485 "Non-nil means mouse-1 on a link will follow the link.
1486 A longer mouse click will still set point. Does not work on XEmacs.
1487 Needs to be set before org.el is loaded."
1488 :group 'org-link-follow
1489 :type 'boolean)
1491 (defcustom org-mark-ring-length 4
1492 "Number of different positions to be recorded in the ring.
1493 Changing this requires a restart of Emacs to work correctly."
1494 :group 'org-link-follow
1495 :type 'integer)
1497 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1498 "Non-nil means internal links in Org files must exactly match a headline.
1499 When nil, the link search tries to match a phrase with all words
1500 in the search text."
1501 :group 'org-link-follow
1502 :type '(choice
1503 (const :tag "Use fuzy text search" nil)
1504 (const :tag "Match only exact headline" t)
1505 (const :tag "Match extact headline or query to create it"
1506 query-to-create)))
1508 (defcustom org-link-frame-setup
1509 '((vm . vm-visit-folder-other-frame)
1510 (gnus . org-gnus-no-new-news)
1511 (file . find-file-other-window)
1512 (wl . wl-other-frame))
1513 "Setup the frame configuration for following links.
1514 When following a link with Emacs, it may often be useful to display
1515 this link in another window or frame. This variable can be used to
1516 set this up for the different types of links.
1517 For VM, use any of
1518 `vm-visit-folder'
1519 `vm-visit-folder-other-window'
1520 `vm-visit-folder-other-frame'
1521 For Gnus, use any of
1522 `gnus'
1523 `gnus-other-frame'
1524 `org-gnus-no-new-news'
1525 For FILE, use any of
1526 `find-file'
1527 `find-file-other-window'
1528 `find-file-other-frame'
1529 For Wanderlust use any of
1530 `wl'
1531 `wl-other-frame'
1532 For the calendar, use the variable `calendar-setup'.
1533 For BBDB, it is currently only possible to display the matches in
1534 another window."
1535 :group 'org-link-follow
1536 :type '(list
1537 (cons (const vm)
1538 (choice
1539 (const vm-visit-folder)
1540 (const vm-visit-folder-other-window)
1541 (const vm-visit-folder-other-frame)))
1542 (cons (const gnus)
1543 (choice
1544 (const gnus)
1545 (const gnus-other-frame)
1546 (const org-gnus-no-new-news)))
1547 (cons (const file)
1548 (choice
1549 (const find-file)
1550 (const find-file-other-window)
1551 (const find-file-other-frame)))
1552 (cons (const wl)
1553 (choice
1554 (const wl)
1555 (const wl-other-frame)))))
1557 (defcustom org-display-internal-link-with-indirect-buffer nil
1558 "Non-nil means use indirect buffer to display infile links.
1559 Activating internal links (from one location in a file to another location
1560 in the same file) normally just jumps to the location. When the link is
1561 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1562 is displayed in
1563 another window. When this option is set, the other window actually displays
1564 an indirect buffer clone of the current buffer, to avoid any visibility
1565 changes to the current buffer."
1566 :group 'org-link-follow
1567 :type 'boolean)
1569 (defcustom org-open-non-existing-files nil
1570 "Non-nil means `org-open-file' will open non-existing files.
1571 When nil, an error will be generated.
1572 This variable applies only to external applications because they
1573 might choke on non-existing files. If the link is to a file that
1574 will be opened in Emacs, the variable is ignored."
1575 :group 'org-link-follow
1576 :type 'boolean)
1578 (defcustom org-open-directory-means-index-dot-org nil
1579 "Non-nil means a link to a directory really means to index.org.
1580 When nil, following a directory link will run dired or open a finder/explorer
1581 window on that directory."
1582 :group 'org-link-follow
1583 :type 'boolean)
1585 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1586 "Function and arguments to call for following mailto links.
1587 This is a list with the first element being a Lisp function, and the
1588 remaining elements being arguments to the function. In string arguments,
1589 %a will be replaced by the address, and %s will be replaced by the subject
1590 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1591 :group 'org-link-follow
1592 :type '(choice
1593 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1594 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1595 (const :tag "message-mail" (message-mail "%a" "%s"))
1596 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1598 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1599 "Non-nil means ask for confirmation before executing shell links.
1600 Shell links can be dangerous: just think about a link
1602 [[shell:rm -rf ~/*][Google Search]]
1604 This link would show up in your Org-mode document as \"Google Search\",
1605 but really it would remove your entire home directory.
1606 Therefore we advise against setting this variable to nil.
1607 Just change it to `y-or-n-p' if you want to confirm with a
1608 single keystroke rather than having to type \"yes\"."
1609 :group 'org-link-follow
1610 :type '(choice
1611 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1612 (const :tag "with y-or-n (faster)" y-or-n-p)
1613 (const :tag "no confirmation (dangerous)" nil)))
1614 (put 'org-confirm-shell-link-function
1615 'safe-local-variable
1616 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1618 (defcustom org-confirm-shell-link-not-regexp ""
1619 "A regexp to skip confirmation for shell links."
1620 :group 'org-link-follow
1621 :type 'regexp)
1623 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1624 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1625 Elisp links can be dangerous: just think about a link
1627 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1629 This link would show up in your Org-mode document as \"Google Search\",
1630 but really it would remove your entire home directory.
1631 Therefore we advise against setting this variable to nil.
1632 Just change it to `y-or-n-p' if you want to confirm with a
1633 single keystroke rather than having to type \"yes\"."
1634 :group 'org-link-follow
1635 :type '(choice
1636 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1637 (const :tag "with y-or-n (faster)" y-or-n-p)
1638 (const :tag "no confirmation (dangerous)" nil)))
1639 (put 'org-confirm-shell-link-function
1640 'safe-local-variable
1641 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1643 (defcustom org-confirm-elisp-link-not-regexp ""
1644 "A regexp to skip confirmation for Elisp links."
1645 :group 'org-link-follow
1646 :type 'regexp)
1648 (defconst org-file-apps-defaults-gnu
1649 '((remote . emacs)
1650 (system . mailcap)
1651 (t . mailcap))
1652 "Default file applications on a UNIX or GNU/Linux system.
1653 See `org-file-apps'.")
1655 (defconst org-file-apps-defaults-macosx
1656 '((remote . emacs)
1657 (t . "open %s")
1658 (system . "open %s")
1659 ("ps.gz" . "gv %s")
1660 ("eps.gz" . "gv %s")
1661 ("dvi" . "xdvi %s")
1662 ("fig" . "xfig %s"))
1663 "Default file applications on a MacOS X system.
1664 The system \"open\" is known as a default, but we use X11 applications
1665 for some files for which the OS does not have a good default.
1666 See `org-file-apps'.")
1668 (defconst org-file-apps-defaults-windowsnt
1669 (list
1670 '(remote . emacs)
1671 (cons t
1672 (list (if (featurep 'xemacs)
1673 'mswindows-shell-execute
1674 'w32-shell-execute)
1675 "open" 'file))
1676 (cons 'system
1677 (list (if (featurep 'xemacs)
1678 'mswindows-shell-execute
1679 'w32-shell-execute)
1680 "open" 'file)))
1681 "Default file applications on a Windows NT system.
1682 The system \"open\" is used for most files.
1683 See `org-file-apps'.")
1685 (defcustom org-file-apps
1687 (auto-mode . emacs)
1688 ("\\.mm\\'" . default)
1689 ("\\.x?html?\\'" . default)
1690 ("\\.pdf\\'" . default)
1692 "External applications for opening `file:path' items in a document.
1693 Org-mode uses system defaults for different file types, but
1694 you can use this variable to set the application for a given file
1695 extension. The entries in this list are cons cells where the car identifies
1696 files and the cdr the corresponding command. Possible values for the
1697 file identifier are
1698 \"string\" A string as a file identifier can be interpreted in different
1699 ways, depending on its contents:
1701 - Alphanumeric characters only:
1702 Match links with this file extension.
1703 Example: (\"pdf\" . \"evince %s\")
1704 to open PDFs with evince.
1706 - Regular expression: Match links where the
1707 filename matches the regexp. If you want to
1708 use groups here, use shy groups.
1710 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1711 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1712 to open *.html and *.xhtml with firefox.
1714 - Regular expression which contains (non-shy) groups:
1715 Match links where the whole link, including \"::\", and
1716 anything after that, matches the regexp.
1717 In a custom command string, %1, %2, etc. are replaced with
1718 the parts of the link that were matched by the groups.
1719 For backwards compatibility, if a command string is given
1720 that does not use any of the group matches, this case is
1721 handled identically to the second one (i.e. match against
1722 file name only).
1723 In a custom lisp form, you can access the group matches with
1724 (match-string n link).
1726 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1727 to open [[file:document.pdf::5]] with evince at page 5.
1729 `directory' Matches a directory
1730 `remote' Matches a remote file, accessible through tramp or efs.
1731 Remote files most likely should be visited through Emacs
1732 because external applications cannot handle such paths.
1733 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1734 so all files Emacs knows how to handle. Using this with
1735 command `emacs' will open most files in Emacs. Beware that this
1736 will also open html files inside Emacs, unless you add
1737 (\"html\" . default) to the list as well.
1738 t Default for files not matched by any of the other options.
1739 `system' The system command to open files, like `open' on Windows
1740 and Mac OS X, and mailcap under GNU/Linux. This is the command
1741 that will be selected if you call `C-c C-o' with a double
1742 \\[universal-argument] \\[universal-argument] prefix.
1744 Possible values for the command are:
1745 `emacs' The file will be visited by the current Emacs process.
1746 `default' Use the default application for this file type, which is the
1747 association for t in the list, most likely in the system-specific
1748 part.
1749 This can be used to overrule an unwanted setting in the
1750 system-specific variable.
1751 `system' Use the system command for opening files, like \"open\".
1752 This command is specified by the entry whose car is `system'.
1753 Most likely, the system-specific version of this variable
1754 does define this command, but you can overrule/replace it
1755 here.
1756 string A command to be executed by a shell; %s will be replaced
1757 by the path to the file.
1758 sexp A Lisp form which will be evaluated. The file path will
1759 be available in the Lisp variable `file'.
1760 For more examples, see the system specific constants
1761 `org-file-apps-defaults-macosx'
1762 `org-file-apps-defaults-windowsnt'
1763 `org-file-apps-defaults-gnu'."
1764 :group 'org-link-follow
1765 :type '(repeat
1766 (cons (choice :value ""
1767 (string :tag "Extension")
1768 (const :tag "System command to open files" system)
1769 (const :tag "Default for unrecognized files" t)
1770 (const :tag "Remote file" remote)
1771 (const :tag "Links to a directory" directory)
1772 (const :tag "Any files that have Emacs modes"
1773 auto-mode))
1774 (choice :value ""
1775 (const :tag "Visit with Emacs" emacs)
1776 (const :tag "Use default" default)
1777 (const :tag "Use the system command" system)
1778 (string :tag "Command")
1779 (sexp :tag "Lisp form")))))
1783 (defgroup org-refile nil
1784 "Options concerning refiling entries in Org-mode."
1785 :tag "Org Refile"
1786 :group 'org)
1788 (defcustom org-directory "~/org"
1789 "Directory with org files.
1790 This is just a default location to look for Org files. There is no need
1791 at all to put your files into this directory. It is only used in the
1792 following situations:
1794 1. When a remember template specifies a target file that is not an
1795 absolute path. The path will then be interpreted relative to
1796 `org-directory'
1797 2. When a remember note is filed away in an interactive way (when exiting the
1798 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1799 with `org-directory' as the default path."
1800 :group 'org-refile
1801 :group 'org-remember
1802 :type 'directory)
1804 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1805 "Default target for storing notes.
1806 Used as a fall back file for org-remember.el and org-capture.el, for
1807 templates that do not specify a target file."
1808 :group 'org-refile
1809 :group 'org-remember
1810 :type '(choice
1811 (const :tag "Default from remember-data-file" nil)
1812 file))
1814 (defcustom org-goto-interface 'outline
1815 "The default interface to be used for `org-goto'.
1816 Allowed values are:
1817 outline The interface shows an outline of the relevant file
1818 and the correct heading is found by moving through
1819 the outline or by searching with incremental search.
1820 outline-path-completion Headlines in the current buffer are offered via
1821 completion. This is the interface also used by
1822 the refile command."
1823 :group 'org-refile
1824 :type '(choice
1825 (const :tag "Outline" outline)
1826 (const :tag "Outline-path-completion" outline-path-completion)))
1828 (defcustom org-goto-max-level 5
1829 "Maximum target level when running `org-goto' with refile interface."
1830 :group 'org-refile
1831 :type 'integer)
1833 (defcustom org-reverse-note-order nil
1834 "Non-nil means store new notes at the beginning of a file or entry.
1835 When nil, new notes will be filed to the end of a file or entry.
1836 This can also be a list with cons cells of regular expressions that
1837 are matched against file names, and values."
1838 :group 'org-remember
1839 :group 'org-refile
1840 :type '(choice
1841 (const :tag "Reverse always" t)
1842 (const :tag "Reverse never" nil)
1843 (repeat :tag "By file name regexp"
1844 (cons regexp boolean))))
1846 (defcustom org-log-refile nil
1847 "Information to record when a task is refiled.
1849 Possible values are:
1851 nil Don't add anything
1852 time Add a time stamp to the task
1853 note Prompt for a note and add it with template `org-log-note-headings'
1855 This option can also be set with on a per-file-basis with
1857 #+STARTUP: nologrefile
1858 #+STARTUP: logrefile
1859 #+STARTUP: lognoterefile
1861 You can have local logging settings for a subtree by setting the LOGGING
1862 property to one or more of these keywords.
1864 When bulk-refiling from the agenda, the value `note' is forbidden and
1865 will temporarily be changed to `time'."
1866 :group 'org-refile
1867 :group 'org-progress
1868 :type '(choice
1869 (const :tag "No logging" nil)
1870 (const :tag "Record timestamp" time)
1871 (const :tag "Record timestamp with note." note)))
1873 (defcustom org-refile-targets nil
1874 "Targets for refiling entries with \\[org-refile].
1875 This is list of cons cells. Each cell contains:
1876 - a specification of the files to be considered, either a list of files,
1877 or a symbol whose function or variable value will be used to retrieve
1878 a file name or a list of file names. If you use `org-agenda-files' for
1879 that, all agenda files will be scanned for targets. Nil means consider
1880 headings in the current buffer.
1881 - A specification of how to find candidate refile targets. This may be
1882 any of:
1883 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1884 This tag has to be present in all target headlines, inheritance will
1885 not be considered.
1886 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1887 todo keyword.
1888 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1889 headlines that are refiling targets.
1890 - a cons cell (:level . N). Any headline of level N is considered a target.
1891 Note that, when `org-odd-levels-only' is set, level corresponds to
1892 order in hierarchy, not to the number of stars.
1893 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1894 Note that, when `org-odd-levels-only' is set, level corresponds to
1895 order in hierarchy, not to the number of stars.
1897 You can set the variable `org-refile-target-verify-function' to a function
1898 to verify each headline found by the simple criteria above.
1900 When this variable is nil, all top-level headlines in the current buffer
1901 are used, equivalent to the value `((nil . (:level . 1))'."
1902 :group 'org-refile
1903 :type '(repeat
1904 (cons
1905 (choice :value org-agenda-files
1906 (const :tag "All agenda files" org-agenda-files)
1907 (const :tag "Current buffer" nil)
1908 (function) (variable) (file))
1909 (choice :tag "Identify target headline by"
1910 (cons :tag "Specific tag" (const :value :tag) (string))
1911 (cons :tag "TODO keyword" (const :value :todo) (string))
1912 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1913 (cons :tag "Level number" (const :value :level) (integer))
1914 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1916 (defcustom org-refile-target-verify-function nil
1917 "Function to verify if the headline at point should be a refile target.
1918 The function will be called without arguments, with point at the
1919 beginning of the headline. It should return t and leave point
1920 where it is if the headline is a valid target for refiling.
1922 If the target should not be selected, the function must return nil.
1923 In addition to this, it may move point to a place from where the search
1924 should be continued. For example, the function may decide that the entire
1925 subtree of the current entry should be excluded and move point to the end
1926 of the subtree."
1927 :group 'org-refile
1928 :type 'function)
1930 (defcustom org-refile-use-cache nil
1931 "Non-nil means cache refile targets to speed up the process.
1932 The cache for a particular file will be updated automatically when
1933 the buffer has been killed, or when any of the marker used for flagging
1934 refile targets no longer points at a live buffer.
1935 If you have added new entries to a buffer that might themselves be targets,
1936 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
1937 find that easier, `C-u C-u C-u C-c C-w'."
1938 :group 'org-refile
1939 :type 'boolean)
1941 (defcustom org-refile-use-outline-path nil
1942 "Non-nil means provide refile targets as paths.
1943 So a level 3 headline will be available as level1/level2/level3.
1945 When the value is `file', also include the file name (without directory)
1946 into the path. In this case, you can also stop the completion after
1947 the file name, to get entries inserted as top level in the file.
1949 When `full-file-path', include the full file path."
1950 :group 'org-refile
1951 :type '(choice
1952 (const :tag "Not" nil)
1953 (const :tag "Yes" t)
1954 (const :tag "Start with file name" file)
1955 (const :tag "Start with full file path" full-file-path)))
1957 (defcustom org-outline-path-complete-in-steps t
1958 "Non-nil means complete the outline path in hierarchical steps.
1959 When Org-mode uses the refile interface to select an outline path
1960 \(see variable `org-refile-use-outline-path'), the completion of
1961 the path can be done is a single go, or if can be done in steps down
1962 the headline hierarchy. Going in steps is probably the best if you
1963 do not use a special completion package like `ido' or `icicles'.
1964 However, when using these packages, going in one step can be very
1965 fast, while still showing the whole path to the entry."
1966 :group 'org-refile
1967 :type 'boolean)
1969 (defcustom org-refile-allow-creating-parent-nodes nil
1970 "Non-nil means allow to create new nodes as refile targets.
1971 New nodes are then created by adding \"/new node name\" to the completion
1972 of an existing node. When the value of this variable is `confirm',
1973 new node creation must be confirmed by the user (recommended)
1974 When nil, the completion must match an existing entry.
1976 Note that, if the new heading is not seen by the criteria
1977 listed in `org-refile-targets', multiple instances of the same
1978 heading would be created by trying again to file under the new
1979 heading."
1980 :group 'org-refile
1981 :type '(choice
1982 (const :tag "Never" nil)
1983 (const :tag "Always" t)
1984 (const :tag "Prompt for confirmation" confirm)))
1986 (defcustom org-refile-active-region-within-subtree nil
1987 "Non-nil means also refile active region within a subtree.
1989 By default `org-refile' doesn't allow refiling regions if they
1990 don't contain a set of subtrees, but it might be convenient to
1991 do so sometimes: in that case, the first line of the region is
1992 converted to a headline before refiling."
1993 :group 'org-refile
1994 :type 'boolean)
1996 (defgroup org-todo nil
1997 "Options concerning TODO items in Org-mode."
1998 :tag "Org TODO"
1999 :group 'org)
2001 (defgroup org-progress nil
2002 "Options concerning Progress logging in Org-mode."
2003 :tag "Org Progress"
2004 :group 'org-time)
2006 (defvar org-todo-interpretation-widgets
2007 '((:tag "Sequence (cycling hits every state)" sequence)
2008 (:tag "Type (cycling directly to DONE)" type))
2009 "The available interpretation symbols for customizing `org-todo-keywords'.
2010 Interested libraries should add to this list.")
2012 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2013 "List of TODO entry keyword sequences and their interpretation.
2014 \\<org-mode-map>This is a list of sequences.
2016 Each sequence starts with a symbol, either `sequence' or `type',
2017 indicating if the keywords should be interpreted as a sequence of
2018 action steps, or as different types of TODO items. The first
2019 keywords are states requiring action - these states will select a headline
2020 for inclusion into the global TODO list Org-mode produces. If one of
2021 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2022 signify that no further action is necessary. If \"|\" is not found,
2023 the last keyword is treated as the only DONE state of the sequence.
2025 The command \\[org-todo] cycles an entry through these states, and one
2026 additional state where no keyword is present. For details about this
2027 cycling, see the manual.
2029 TODO keywords and interpretation can also be set on a per-file basis with
2030 the special #+SEQ_TODO and #+TYP_TODO lines.
2032 Each keyword can optionally specify a character for fast state selection
2033 \(in combination with the variable `org-use-fast-todo-selection')
2034 and specifiers for state change logging, using the same syntax
2035 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
2036 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2037 indicates to record a time stamp each time this state is selected.
2039 Each keyword may also specify if a timestamp or a note should be
2040 recorded when entering or leaving the state, by adding additional
2041 characters in the parenthesis after the keyword. This looks like this:
2042 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2043 record only the time of the state change. With X and Y being either
2044 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2045 Y when leaving the state if and only if the *target* state does not
2046 define X. You may omit any of the fast-selection key or X or /Y,
2047 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2049 For backward compatibility, this variable may also be just a list
2050 of keywords - in this case the interpretation (sequence or type) will be
2051 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2052 :group 'org-todo
2053 :group 'org-keywords
2054 :type '(choice
2055 (repeat :tag "Old syntax, just keywords"
2056 (string :tag "Keyword"))
2057 (repeat :tag "New syntax"
2058 (cons
2059 (choice
2060 :tag "Interpretation"
2061 ;;Quick and dirty way to see
2062 ;;`org-todo-interpretations'. This takes the
2063 ;;place of item arguments
2064 :convert-widget
2065 (lambda (widget)
2066 (widget-put widget
2067 :args (mapcar
2068 #'(lambda (x)
2069 (widget-convert
2070 (cons 'const x)))
2071 org-todo-interpretation-widgets))
2072 widget))
2073 (repeat
2074 (string :tag "Keyword"))))))
2076 (defvar org-todo-keywords-1 nil
2077 "All TODO and DONE keywords active in a buffer.")
2078 (make-variable-buffer-local 'org-todo-keywords-1)
2079 (defvar org-todo-keywords-for-agenda nil)
2080 (defvar org-done-keywords-for-agenda nil)
2081 (defvar org-drawers-for-agenda nil)
2082 (defvar org-todo-keyword-alist-for-agenda nil)
2083 (defvar org-tag-alist-for-agenda nil)
2084 (defvar org-agenda-contributing-files nil)
2085 (defvar org-not-done-keywords nil)
2086 (make-variable-buffer-local 'org-not-done-keywords)
2087 (defvar org-done-keywords nil)
2088 (make-variable-buffer-local 'org-done-keywords)
2089 (defvar org-todo-heads nil)
2090 (make-variable-buffer-local 'org-todo-heads)
2091 (defvar org-todo-sets nil)
2092 (make-variable-buffer-local 'org-todo-sets)
2093 (defvar org-todo-log-states nil)
2094 (make-variable-buffer-local 'org-todo-log-states)
2095 (defvar org-todo-kwd-alist nil)
2096 (make-variable-buffer-local 'org-todo-kwd-alist)
2097 (defvar org-todo-key-alist nil)
2098 (make-variable-buffer-local 'org-todo-key-alist)
2099 (defvar org-todo-key-trigger nil)
2100 (make-variable-buffer-local 'org-todo-key-trigger)
2102 (defcustom org-todo-interpretation 'sequence
2103 "Controls how TODO keywords are interpreted.
2104 This variable is in principle obsolete and is only used for
2105 backward compatibility, if the interpretation of todo keywords is
2106 not given already in `org-todo-keywords'. See that variable for
2107 more information."
2108 :group 'org-todo
2109 :group 'org-keywords
2110 :type '(choice (const sequence)
2111 (const type)))
2113 (defcustom org-use-fast-todo-selection t
2114 "Non-nil means use the fast todo selection scheme with C-c C-t.
2115 This variable describes if and under what circumstances the cycling
2116 mechanism for TODO keywords will be replaced by a single-key, direct
2117 selection scheme.
2119 When nil, fast selection is never used.
2121 When the symbol `prefix', it will be used when `org-todo' is called with
2122 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
2123 in an agenda buffer.
2125 When t, fast selection is used by default. In this case, the prefix
2126 argument forces cycling instead.
2128 In all cases, the special interface is only used if access keys have actually
2129 been assigned by the user, i.e. if keywords in the configuration are followed
2130 by a letter in parenthesis, like TODO(t)."
2131 :group 'org-todo
2132 :type '(choice
2133 (const :tag "Never" nil)
2134 (const :tag "By default" t)
2135 (const :tag "Only with C-u C-c C-t" prefix)))
2137 (defcustom org-provide-todo-statistics t
2138 "Non-nil means update todo statistics after insert and toggle.
2139 ALL-HEADLINES means update todo statistics by including headlines
2140 with no TODO keyword as well, counting them as not done.
2141 A list of TODO keywords means the same, but skip keywords that are
2142 not in this list.
2144 When this is set, todo statistics is updated in the parent of the
2145 current entry each time a todo state is changed."
2146 :group 'org-todo
2147 :type '(choice
2148 (const :tag "Yes, only for TODO entries" t)
2149 (const :tag "Yes, including all entries" 'all-headlines)
2150 (repeat :tag "Yes, for TODOs in this list"
2151 (string :tag "TODO keyword"))
2152 (other :tag "No TODO statistics" nil)))
2154 (defcustom org-hierarchical-todo-statistics t
2155 "Non-nil means TODO statistics covers just direct children.
2156 When nil, all entries in the subtree are considered.
2157 This has only an effect if `org-provide-todo-statistics' is set.
2158 To set this to nil for only a single subtree, use a COOKIE_DATA
2159 property and include the word \"recursive\" into the value."
2160 :group 'org-todo
2161 :type 'boolean)
2163 (defcustom org-after-todo-state-change-hook nil
2164 "Hook which is run after the state of a TODO item was changed.
2165 The new state (a string with a TODO keyword, or nil) is available in the
2166 Lisp variable `state'."
2167 :group 'org-todo
2168 :type 'hook)
2170 (defvar org-blocker-hook nil
2171 "Hook for functions that are allowed to block a state change.
2173 Each function gets as its single argument a property list, see
2174 `org-trigger-hook' for more information about this list.
2176 If any of the functions in this hook returns nil, the state change
2177 is blocked.")
2179 (defvar org-trigger-hook nil
2180 "Hook for functions that are triggered by a state change.
2182 Each function gets as its single argument a property list with at least
2183 the following elements:
2185 (:type type-of-change :position pos-at-entry-start
2186 :from old-state :to new-state)
2188 Depending on the type, more properties may be present.
2190 This mechanism is currently implemented for:
2192 TODO state changes
2193 ------------------
2194 :type todo-state-change
2195 :from previous state (keyword as a string), or nil, or a symbol
2196 'todo' or 'done', to indicate the general type of state.
2197 :to new state, like in :from")
2199 (defcustom org-enforce-todo-dependencies nil
2200 "Non-nil means undone TODO entries will block switching the parent to DONE.
2201 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2202 be blocked if any prior sibling is not yet done.
2203 Finally, if the parent is blocked because of ordered siblings of its own,
2204 the child will also be blocked.
2205 This variable needs to be set before org.el is loaded, and you need to
2206 restart Emacs after a change to make the change effective. The only way
2207 to change is while Emacs is running is through the customize interface."
2208 :set (lambda (var val)
2209 (set var val)
2210 (if val
2211 (add-hook 'org-blocker-hook
2212 'org-block-todo-from-children-or-siblings-or-parent)
2213 (remove-hook 'org-blocker-hook
2214 'org-block-todo-from-children-or-siblings-or-parent)))
2215 :group 'org-todo
2216 :type 'boolean)
2218 (defcustom org-enforce-todo-checkbox-dependencies nil
2219 "Non-nil means unchecked boxes will block switching the parent to DONE.
2220 When this is nil, checkboxes have no influence on switching TODO states.
2221 When non-nil, you first need to check off all check boxes before the TODO
2222 entry can be switched to DONE.
2223 This variable needs to be set before org.el is loaded, and you need to
2224 restart Emacs after a change to make the change effective. The only way
2225 to change is while Emacs is running is through the customize interface."
2226 :set (lambda (var val)
2227 (set var val)
2228 (if val
2229 (add-hook 'org-blocker-hook
2230 'org-block-todo-from-checkboxes)
2231 (remove-hook 'org-blocker-hook
2232 'org-block-todo-from-checkboxes)))
2233 :group 'org-todo
2234 :type 'boolean)
2236 (defcustom org-treat-insert-todo-heading-as-state-change nil
2237 "Non-nil means inserting a TODO heading is treated as state change.
2238 So when the command \\[org-insert-todo-heading] is used, state change
2239 logging will apply if appropriate. When nil, the new TODO item will
2240 be inserted directly, and no logging will take place."
2241 :group 'org-todo
2242 :type 'boolean)
2244 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2245 "Non-nil means switching TODO states with S-cursor counts as state change.
2246 This is the default behavior. However, setting this to nil allows a
2247 convenient way to select a TODO state and bypass any logging associated
2248 with that."
2249 :group 'org-todo
2250 :type 'boolean)
2252 (defcustom org-todo-state-tags-triggers nil
2253 "Tag changes that should be triggered by TODO state changes.
2254 This is a list. Each entry is
2256 (state-change (tag . flag) .......)
2258 State-change can be a string with a state, and empty string to indicate the
2259 state that has no TODO keyword, or it can be one of the symbols `todo'
2260 or `done', meaning any not-done or done state, respectively."
2261 :group 'org-todo
2262 :group 'org-tags
2263 :type '(repeat
2264 (cons (choice :tag "When changing to"
2265 (const :tag "Not-done state" todo)
2266 (const :tag "Done state" done)
2267 (string :tag "State"))
2268 (repeat
2269 (cons :tag "Tag action"
2270 (string :tag "Tag")
2271 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2273 (defcustom org-log-done nil
2274 "Information to record when a task moves to the DONE state.
2276 Possible values are:
2278 nil Don't add anything, just change the keyword
2279 time Add a time stamp to the task
2280 note Prompt for a note and add it with template `org-log-note-headings'
2282 This option can also be set with on a per-file-basis with
2284 #+STARTUP: nologdone
2285 #+STARTUP: logdone
2286 #+STARTUP: lognotedone
2288 You can have local logging settings for a subtree by setting the LOGGING
2289 property to one or more of these keywords."
2290 :group 'org-todo
2291 :group 'org-progress
2292 :type '(choice
2293 (const :tag "No logging" nil)
2294 (const :tag "Record CLOSED timestamp" time)
2295 (const :tag "Record CLOSED timestamp with note." note)))
2297 ;; Normalize old uses of org-log-done.
2298 (cond
2299 ((eq org-log-done t) (setq org-log-done 'time))
2300 ((and (listp org-log-done) (memq 'done org-log-done))
2301 (setq org-log-done 'note)))
2303 (defcustom org-log-reschedule nil
2304 "Information to record when the scheduling date of a tasks is modified.
2306 Possible values are:
2308 nil Don't add anything, just change the date
2309 time Add a time stamp to the task
2310 note Prompt for a note and add it with template `org-log-note-headings'
2312 This option can also be set with on a per-file-basis with
2314 #+STARTUP: nologreschedule
2315 #+STARTUP: logreschedule
2316 #+STARTUP: lognotereschedule"
2317 :group 'org-todo
2318 :group 'org-progress
2319 :type '(choice
2320 (const :tag "No logging" nil)
2321 (const :tag "Record timestamp" time)
2322 (const :tag "Record timestamp with note." note)))
2324 (defcustom org-log-redeadline nil
2325 "Information to record when the deadline date of a tasks is modified.
2327 Possible values are:
2329 nil Don't add anything, just change the date
2330 time Add a time stamp to the task
2331 note Prompt for a note and add it with template `org-log-note-headings'
2333 This option can also be set with on a per-file-basis with
2335 #+STARTUP: nologredeadline
2336 #+STARTUP: logredeadline
2337 #+STARTUP: lognoteredeadline
2339 You can have local logging settings for a subtree by setting the LOGGING
2340 property to one or more of these keywords."
2341 :group 'org-todo
2342 :group 'org-progress
2343 :type '(choice
2344 (const :tag "No logging" nil)
2345 (const :tag "Record timestamp" time)
2346 (const :tag "Record timestamp with note." note)))
2348 (defcustom org-log-note-clock-out nil
2349 "Non-nil means record a note when clocking out of an item.
2350 This can also be configured on a per-file basis by adding one of
2351 the following lines anywhere in the buffer:
2353 #+STARTUP: lognoteclock-out
2354 #+STARTUP: nolognoteclock-out"
2355 :group 'org-todo
2356 :group 'org-progress
2357 :type 'boolean)
2359 (defcustom org-log-done-with-time t
2360 "Non-nil means the CLOSED time stamp will contain date and time.
2361 When nil, only the date will be recorded."
2362 :group 'org-progress
2363 :type 'boolean)
2365 (defcustom org-log-note-headings
2366 '((done . "CLOSING NOTE %t")
2367 (state . "State %-12s from %-12S %t")
2368 (note . "Note taken on %t")
2369 (reschedule . "Rescheduled from %S on %t")
2370 (delschedule . "Not scheduled, was %S on %t")
2371 (redeadline . "New deadline from %S on %t")
2372 (deldeadline . "Removed deadline, was %S on %t")
2373 (refile . "Refiled on %t")
2374 (clock-out . ""))
2375 "Headings for notes added to entries.
2376 The value is an alist, with the car being a symbol indicating the note
2377 context, and the cdr is the heading to be used. The heading may also be the
2378 empty string.
2379 %t in the heading will be replaced by a time stamp.
2380 %T will be an active time stamp instead the default inactive one
2381 %s will be replaced by the new TODO state, in double quotes.
2382 %S will be replaced by the old TODO state, in double quotes.
2383 %u will be replaced by the user name.
2384 %U will be replaced by the full user name.
2386 In fact, it is not a good idea to change the `state' entry, because
2387 agenda log mode depends on the format of these entries."
2388 :group 'org-todo
2389 :group 'org-progress
2390 :type '(list :greedy t
2391 (cons (const :tag "Heading when closing an item" done) string)
2392 (cons (const :tag
2393 "Heading when changing todo state (todo sequence only)"
2394 state) string)
2395 (cons (const :tag "Heading when just taking a note" note) string)
2396 (cons (const :tag "Heading when clocking out" clock-out) string)
2397 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2398 (cons (const :tag "Heading when rescheduling" reschedule) string)
2399 (cons (const :tag "Heading when changing deadline" redeadline) string)
2400 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2401 (cons (const :tag "Heading when refiling" refile) string)))
2403 (unless (assq 'note org-log-note-headings)
2404 (push '(note . "%t") org-log-note-headings))
2406 (defcustom org-log-into-drawer nil
2407 "Non-nil means insert state change notes and time stamps into a drawer.
2408 When nil, state changes notes will be inserted after the headline and
2409 any scheduling and clock lines, but not inside a drawer.
2411 The value of this variable should be the name of the drawer to use.
2412 LOGBOOK is proposed as the default drawer for this purpose, you can
2413 also set this to a string to define the drawer of your choice.
2415 A value of t is also allowed, representing \"LOGBOOK\".
2417 If this variable is set, `org-log-state-notes-insert-after-drawers'
2418 will be ignored.
2420 You can set the property LOG_INTO_DRAWER to overrule this setting for
2421 a subtree."
2422 :group 'org-todo
2423 :group 'org-progress
2424 :type '(choice
2425 (const :tag "Not into a drawer" nil)
2426 (const :tag "LOGBOOK" t)
2427 (string :tag "Other")))
2429 (if (fboundp 'defvaralias)
2430 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2432 (defun org-log-into-drawer ()
2433 "Return the value of `org-log-into-drawer', but let properties overrule.
2434 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2435 used instead of the default value."
2436 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit)))
2437 (cond
2438 ((or (not p) (equal p "nil")) org-log-into-drawer)
2439 ((equal p "t") "LOGBOOK")
2440 (t p))))
2442 (defcustom org-log-state-notes-insert-after-drawers nil
2443 "Non-nil means insert state change notes after any drawers in entry.
2444 Only the drawers that *immediately* follow the headline and the
2445 deadline/scheduled line are skipped.
2446 When nil, insert notes right after the heading and perhaps the line
2447 with deadline/scheduling if present.
2449 This variable will have no effect if `org-log-into-drawer' is
2450 set."
2451 :group 'org-todo
2452 :group 'org-progress
2453 :type 'boolean)
2455 (defcustom org-log-states-order-reversed t
2456 "Non-nil means the latest state note will be directly after heading.
2457 When nil, the state change notes will be ordered according to time."
2458 :group 'org-todo
2459 :group 'org-progress
2460 :type 'boolean)
2462 (defcustom org-todo-repeat-to-state nil
2463 "The TODO state to which a repeater should return the repeating task.
2464 By default this is the first task in a TODO sequence, or the previous state
2465 in a TODO_TYP set. But you can specify another task here.
2466 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2467 :group 'org-todo
2468 :type '(choice (const :tag "Head of sequence" nil)
2469 (string :tag "Specific state")))
2471 (defcustom org-log-repeat 'time
2472 "Non-nil means record moving through the DONE state when triggering repeat.
2473 An auto-repeating task is immediately switched back to TODO when
2474 marked DONE. If you are not logging state changes (by adding \"@\"
2475 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2476 record a closing note, there will be no record of the task moving
2477 through DONE. This variable forces taking a note anyway.
2479 nil Don't force a record
2480 time Record a time stamp
2481 note Record a note
2483 This option can also be set with on a per-file-basis with
2485 #+STARTUP: logrepeat
2486 #+STARTUP: lognoterepeat
2487 #+STARTUP: nologrepeat
2489 You can have local logging settings for a subtree by setting the LOGGING
2490 property to one or more of these keywords."
2491 :group 'org-todo
2492 :group 'org-progress
2493 :type '(choice
2494 (const :tag "Don't force a record" nil)
2495 (const :tag "Force recording the DONE state" time)
2496 (const :tag "Force recording a note with the DONE state" note)))
2499 (defgroup org-priorities nil
2500 "Priorities in Org-mode."
2501 :tag "Org Priorities"
2502 :group 'org-todo)
2504 (defcustom org-enable-priority-commands t
2505 "Non-nil means priority commands are active.
2506 When nil, these commands will be disabled, so that you never accidentally
2507 set a priority."
2508 :group 'org-priorities
2509 :type 'boolean)
2511 (defcustom org-highest-priority ?A
2512 "The highest priority of TODO items. A character like ?A, ?B etc.
2513 Must have a smaller ASCII number than `org-lowest-priority'."
2514 :group 'org-priorities
2515 :type 'character)
2517 (defcustom org-lowest-priority ?C
2518 "The lowest priority of TODO items. A character like ?A, ?B etc.
2519 Must have a larger ASCII number than `org-highest-priority'."
2520 :group 'org-priorities
2521 :type 'character)
2523 (defcustom org-default-priority ?B
2524 "The default priority of TODO items.
2525 This is the priority an item gets if no explicit priority is given.
2526 When starting to cycle on an empty priority the first step in the cycle
2527 depends on `org-priority-start-cycle-with-default'. The resulting first
2528 step priority must not exceed the range from `org-highest-priority' to
2529 `org-lowest-priority' which means that `org-default-priority' has to be
2530 in this range exclusive or inclusive the range boundaries. Else the
2531 first step refuses to set the default and the second will fall back
2532 to (depending on the command used) the highest or lowest priority."
2533 :group 'org-priorities
2534 :type 'character)
2536 (defcustom org-priority-start-cycle-with-default t
2537 "Non-nil means start with default priority when starting to cycle.
2538 When this is nil, the first step in the cycle will be (depending on the
2539 command used) one higher or lower than the default priority.
2540 See also `org-default-priority'."
2541 :group 'org-priorities
2542 :type 'boolean)
2544 (defcustom org-get-priority-function nil
2545 "Function to extract the priority from a string.
2546 The string is normally the headline. If this is nil Org computes the
2547 priority from the priority cookie like [#A] in the headline. It returns
2548 an integer, increasing by 1000 for each priority level.
2549 The user can set a different function here, which should take a string
2550 as an argument and return the numeric priority."
2551 :group 'org-priorities
2552 :type 'function)
2554 (defgroup org-time nil
2555 "Options concerning time stamps and deadlines in Org-mode."
2556 :tag "Org Time"
2557 :group 'org)
2559 (defcustom org-insert-labeled-timestamps-at-point nil
2560 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2561 When nil, these labeled time stamps are forces into the second line of an
2562 entry, just after the headline. When scheduling from the global TODO list,
2563 the time stamp will always be forced into the second line."
2564 :group 'org-time
2565 :type 'boolean)
2567 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2568 "Formats for `format-time-string' which are used for time stamps.
2569 It is not recommended to change this constant.")
2571 (defcustom org-time-stamp-rounding-minutes '(0 5)
2572 "Number of minutes to round time stamps to.
2573 These are two values, the first applies when first creating a time stamp.
2574 The second applies when changing it with the commands `S-up' and `S-down'.
2575 When changing the time stamp, this means that it will change in steps
2576 of N minutes, as given by the second value.
2578 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2579 numbers should be factors of 60, so for example 5, 10, 15.
2581 When this is larger than 1, you can still force an exact time stamp by using
2582 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2583 and by using a prefix arg to `S-up/down' to specify the exact number
2584 of minutes to shift."
2585 :group 'org-time
2586 :get #'(lambda (var) ; Make sure both elements are there
2587 (if (integerp (default-value var))
2588 (list (default-value var) 5)
2589 (default-value var)))
2590 :type '(list
2591 (integer :tag "when inserting times")
2592 (integer :tag "when modifying times")))
2594 ;; Normalize old customizations of this variable.
2595 (when (integerp org-time-stamp-rounding-minutes)
2596 (setq org-time-stamp-rounding-minutes
2597 (list org-time-stamp-rounding-minutes
2598 org-time-stamp-rounding-minutes)))
2600 (defcustom org-display-custom-times nil
2601 "Non-nil means overlay custom formats over all time stamps.
2602 The formats are defined through the variable `org-time-stamp-custom-formats'.
2603 To turn this on on a per-file basis, insert anywhere in the file:
2604 #+STARTUP: customtime"
2605 :group 'org-time
2606 :set 'set-default
2607 :type 'sexp)
2608 (make-variable-buffer-local 'org-display-custom-times)
2610 (defcustom org-time-stamp-custom-formats
2611 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2612 "Custom formats for time stamps. See `format-time-string' for the syntax.
2613 These are overlayed over the default ISO format if the variable
2614 `org-display-custom-times' is set. Time like %H:%M should be at the
2615 end of the second format. The custom formats are also honored by export
2616 commands, if custom time display is turned on at the time of export."
2617 :group 'org-time
2618 :type 'sexp)
2620 (defun org-time-stamp-format (&optional long inactive)
2621 "Get the right format for a time string."
2622 (let ((f (if long (cdr org-time-stamp-formats)
2623 (car org-time-stamp-formats))))
2624 (if inactive
2625 (concat "[" (substring f 1 -1) "]")
2626 f)))
2628 (defcustom org-time-clocksum-format "%d:%02d"
2629 "The format string used when creating CLOCKSUM lines.
2630 This is also used when org-mode generates a time duration."
2631 :group 'org-time
2632 :type 'string)
2634 (defcustom org-time-clocksum-use-fractional nil
2635 "If non-nil, \\[org-clock-display] uses fractional times.
2636 org-mode generates a time duration."
2637 :group 'org-time
2638 :type 'boolean)
2640 (defcustom org-time-clocksum-fractional-format "%.2f"
2641 "The format string used when creating CLOCKSUM lines, or when
2642 org-mode generates a time duration."
2643 :group 'org-time
2644 :type 'string)
2646 (defcustom org-deadline-warning-days 14
2647 "No. of days before expiration during which a deadline becomes active.
2648 This variable governs the display in sparse trees and in the agenda.
2649 When 0 or negative, it means use this number (the absolute value of it)
2650 even if a deadline has a different individual lead time specified.
2652 Custom commands can set this variable in the options section."
2653 :group 'org-time
2654 :group 'org-agenda-daily/weekly
2655 :type 'integer)
2657 (defcustom org-read-date-prefer-future t
2658 "Non-nil means assume future for incomplete date input from user.
2659 This affects the following situations:
2660 1. The user gives a month but not a year.
2661 For example, if it is April and you enter \"feb 2\", this will be read
2662 as Feb 2, *next* year. \"May 5\", however, will be this year.
2663 2. The user gives a day, but no month.
2664 For example, if today is the 15th, and you enter \"3\", Org-mode will
2665 read this as the third of *next* month. However, if you enter \"17\",
2666 it will be considered as *this* month.
2668 If you set this variable to the symbol `time', then also the following
2669 will work:
2671 3. If the user gives a time, but no day. If the time is before now,
2672 to will be interpreted as tomorrow.
2674 Currently none of this works for ISO week specifications.
2676 When this option is nil, the current day, month and year will always be
2677 used as defaults.
2679 See also `org-agenda-jump-prefer-future'."
2680 :group 'org-time
2681 :type '(choice
2682 (const :tag "Never" nil)
2683 (const :tag "Check month and day" t)
2684 (const :tag "Check month, day, and time" time)))
2686 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
2687 "Should the agenda jump command prefer the future for incomplete dates?
2688 The default is to do the same as configured in `org-read-date-prefer-future'.
2689 But you can also set a deviating value here.
2690 This may t or nil, or the symbol `org-read-date-prefer-future'."
2691 :group 'org-agenda
2692 :group 'org-time
2693 :type '(choice
2694 (const :tag "Use org-read-date-prefer-future"
2695 org-read-date-prefer-future)
2696 (const :tag "Never" nil)
2697 (const :tag "Always" t)))
2699 (defcustom org-read-date-force-compatible-dates t
2700 "Should date/time prompt force dates that are guaranteed to work in Emacs?
2702 Depending on the system Emacs is running on, certain dates cannot
2703 be represented with the type used internally to represent time.
2704 Dates between 1970-1-1 and 2038-1-1 can always be represented
2705 correctly. Some systems allow for earlier dates, some for later,
2706 some for both. One way to find out it to insert any date into an
2707 Org buffer, putting the cursor on the year and hitting S-up and
2708 S-down to test the range.
2710 When this variable is set to t, the date/time prompt will not let
2711 you specify dates outside the 1970-2037 range, so it is certain that
2712 these dates will work in whatever version of Emacs you are
2713 running, and also that you can move a file from one Emacs implementation
2714 to another. WHenever Org is forcing the year for you, it will display
2715 a message and beep.
2717 When this variable is nil, Org will check if the date is
2718 representable in the specific Emacs implementation you are using.
2719 If not, it will force a year, usually the current year, and beep
2720 to remind you. Currently this setting is not recommended because
2721 the likelihood that you will open your Org files in an Emacs that
2722 has limited date range is not negligible.
2724 A workaround for this problem is to use diary sexp dates for time
2725 stamps outside of this range."
2726 :group 'org-time
2727 :type 'boolean)
2729 (defcustom org-read-date-display-live t
2730 "Non-nil means display current interpretation of date prompt live.
2731 This display will be in an overlay, in the minibuffer."
2732 :group 'org-time
2733 :type 'boolean)
2735 (defcustom org-read-date-popup-calendar t
2736 "Non-nil means pop up a calendar when prompting for a date.
2737 In the calendar, the date can be selected with mouse-1. However, the
2738 minibuffer will also be active, and you can simply enter the date as well.
2739 When nil, only the minibuffer will be available."
2740 :group 'org-time
2741 :type 'boolean)
2742 (if (fboundp 'defvaralias)
2743 (defvaralias 'org-popup-calendar-for-date-prompt
2744 'org-read-date-popup-calendar))
2746 (defcustom org-read-date-minibuffer-setup-hook nil
2747 "Hook to be used to set up keys for the date/time interface.
2748 Add key definitions to `minibuffer-local-map', which will be a temporary
2749 copy."
2750 :group 'org-time
2751 :type 'hook)
2753 (defcustom org-extend-today-until 0
2754 "The hour when your day really ends. Must be an integer.
2755 This has influence for the following applications:
2756 - When switching the agenda to \"today\". It it is still earlier than
2757 the time given here, the day recognized as TODAY is actually yesterday.
2758 - When a date is read from the user and it is still before the time given
2759 here, the current date and time will be assumed to be yesterday, 23:59.
2760 Also, timestamps inserted in remember templates follow this rule.
2762 IMPORTANT: This is a feature whose implementation is and likely will
2763 remain incomplete. Really, it is only here because past midnight seems to
2764 be the favorite working time of John Wiegley :-)"
2765 :group 'org-time
2766 :type 'integer)
2768 (defcustom org-use-effective-time nil
2769 "If non-nil, consider `org-extend-today-until' when creating timestamps.
2770 For example, if `org-extend-today-until' is 8, and it's 4am, then the
2771 \"effective time\" of any timestamps between midnight and 8am will be
2772 23:59 of the previous day."
2773 :group 'boolean
2774 :type 'integer)
2776 (defcustom org-edit-timestamp-down-means-later nil
2777 "Non-nil means S-down will increase the time in a time stamp.
2778 When nil, S-up will increase."
2779 :group 'org-time
2780 :type 'boolean)
2782 (defcustom org-calendar-follow-timestamp-change t
2783 "Non-nil means make the calendar window follow timestamp changes.
2784 When a timestamp is modified and the calendar window is visible, it will be
2785 moved to the new date."
2786 :group 'org-time
2787 :type 'boolean)
2789 (defgroup org-tags nil
2790 "Options concerning tags in Org-mode."
2791 :tag "Org Tags"
2792 :group 'org)
2794 (defcustom org-tag-alist nil
2795 "List of tags allowed in Org-mode files.
2796 When this list is nil, Org-mode will base TAG input on what is already in the
2797 buffer.
2798 The value of this variable is an alist, the car of each entry must be a
2799 keyword as a string, the cdr may be a character that is used to select
2800 that tag through the fast-tag-selection interface.
2801 See the manual for details."
2802 :group 'org-tags
2803 :type '(repeat
2804 (choice
2805 (cons (string :tag "Tag name")
2806 (character :tag "Access char"))
2807 (list :tag "Start radio group"
2808 (const :startgroup)
2809 (option (string :tag "Group description")))
2810 (list :tag "End radio group"
2811 (const :endgroup)
2812 (option (string :tag "Group description")))
2813 (const :tag "New line" (:newline)))))
2815 (defcustom org-tag-persistent-alist nil
2816 "List of tags that will always appear in all Org-mode files.
2817 This is in addition to any in buffer settings or customizations
2818 of `org-tag-alist'.
2819 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2820 The value of this variable is an alist, the car of each entry must be a
2821 keyword as a string, the cdr may be a character that is used to select
2822 that tag through the fast-tag-selection interface.
2823 See the manual for details.
2824 To disable these tags on a per-file basis, insert anywhere in the file:
2825 #+STARTUP: noptag"
2826 :group 'org-tags
2827 :type '(repeat
2828 (choice
2829 (cons (string :tag "Tag name")
2830 (character :tag "Access char"))
2831 (const :tag "Start radio group" (:startgroup))
2832 (const :tag "End radio group" (:endgroup))
2833 (const :tag "New line" (:newline)))))
2835 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
2836 "If non-nil, always offer completion for all tags of all agenda files.
2837 Instead of customizing this variable directly, you might want to
2838 set it locally for capture buffers, because there no list of
2839 tags in that file can be created dynamically (there are none).
2841 (add-hook 'org-capture-mode-hook
2842 (lambda ()
2843 (set (make-local-variable
2844 'org-complete-tags-always-offer-all-agenda-tags)
2845 t)))"
2846 :group 'org-tags
2847 :type 'boolean)
2849 (defvar org-file-tags nil
2850 "List of tags that can be inherited by all entries in the file.
2851 The tags will be inherited if the variable `org-use-tag-inheritance'
2852 says they should be.
2853 This variable is populated from #+FILETAGS lines.")
2855 (defcustom org-use-fast-tag-selection 'auto
2856 "Non-nil means use fast tag selection scheme.
2857 This is a special interface to select and deselect tags with single keys.
2858 When nil, fast selection is never used.
2859 When the symbol `auto', fast selection is used if and only if selection
2860 characters for tags have been configured, either through the variable
2861 `org-tag-alist' or through a #+TAGS line in the buffer.
2862 When t, fast selection is always used and selection keys are assigned
2863 automatically if necessary."
2864 :group 'org-tags
2865 :type '(choice
2866 (const :tag "Always" t)
2867 (const :tag "Never" nil)
2868 (const :tag "When selection characters are configured" 'auto)))
2870 (defcustom org-fast-tag-selection-single-key nil
2871 "Non-nil means fast tag selection exits after first change.
2872 When nil, you have to press RET to exit it.
2873 During fast tag selection, you can toggle this flag with `C-c'.
2874 This variable can also have the value `expert'. In this case, the window
2875 displaying the tags menu is not even shown, until you press C-c again."
2876 :group 'org-tags
2877 :type '(choice
2878 (const :tag "No" nil)
2879 (const :tag "Yes" t)
2880 (const :tag "Expert" expert)))
2882 (defvar org-fast-tag-selection-include-todo nil
2883 "Non-nil means fast tags selection interface will also offer TODO states.
2884 This is an undocumented feature, you should not rely on it.")
2886 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2887 "The column to which tags should be indented in a headline.
2888 If this number is positive, it specifies the column. If it is negative,
2889 it means that the tags should be flushright to that column. For example,
2890 -80 works well for a normal 80 character screen."
2891 :group 'org-tags
2892 :type 'integer)
2894 (defcustom org-auto-align-tags t
2895 "Non-nil keeps tags aligned when modifying headlines.
2896 Some operations (i.e. demoting) change the length of a headline and
2897 therefore shift the tags around. With this option turned on, after
2898 each such operation the tags are again aligned to `org-tags-column'."
2899 :group 'org-tags
2900 :type 'boolean)
2902 (defcustom org-use-tag-inheritance t
2903 "Non-nil means tags in levels apply also for sublevels.
2904 When nil, only the tags directly given in a specific line apply there.
2905 This may also be a list of tags that should be inherited, or a regexp that
2906 matches tags that should be inherited. Additional control is possible
2907 with the variable `org-tags-exclude-from-inheritance' which gives an
2908 explicit list of tags to be excluded from inheritance., even if the value of
2909 `org-use-tag-inheritance' would select it for inheritance.
2911 If this option is t, a match early-on in a tree can lead to a large
2912 number of matches in the subtree when constructing the agenda or creating
2913 a sparse tree. If you only want to see the first match in a tree during
2914 a search, check out the variable `org-tags-match-list-sublevels'."
2915 :group 'org-tags
2916 :type '(choice
2917 (const :tag "Not" nil)
2918 (const :tag "Always" t)
2919 (repeat :tag "Specific tags" (string :tag "Tag"))
2920 (regexp :tag "Tags matched by regexp")))
2922 (defcustom org-tags-exclude-from-inheritance nil
2923 "List of tags that should never be inherited.
2924 This is a way to exclude a few tags from inheritance. For way to do
2925 the opposite, to actively allow inheritance for selected tags,
2926 see the variable `org-use-tag-inheritance'."
2927 :group 'org-tags
2928 :type '(repeat (string :tag "Tag")))
2930 (defun org-tag-inherit-p (tag)
2931 "Check if TAG is one that should be inherited."
2932 (cond
2933 ((member tag org-tags-exclude-from-inheritance) nil)
2934 ((eq org-use-tag-inheritance t) t)
2935 ((not org-use-tag-inheritance) nil)
2936 ((stringp org-use-tag-inheritance)
2937 (string-match org-use-tag-inheritance tag))
2938 ((listp org-use-tag-inheritance)
2939 (member tag org-use-tag-inheritance))
2940 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
2942 (defcustom org-tags-match-list-sublevels t
2943 "Non-nil means list also sublevels of headlines matching a search.
2944 This variable applies to tags/property searches, and also to stuck
2945 projects because this search is based on a tags match as well.
2947 When set to the symbol `indented', sublevels are indented with
2948 leading dots.
2950 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2951 the sublevels of a headline matching a tag search often also match
2952 the same search. Listing all of them can create very long lists.
2953 Setting this variable to nil causes subtrees of a match to be skipped.
2955 This variable is semi-obsolete and probably should always be true. It
2956 is better to limit inheritance to certain tags using the variables
2957 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
2958 :group 'org-tags
2959 :type '(choice
2960 (const :tag "No, don't list them" nil)
2961 (const :tag "Yes, do list them" t)
2962 (const :tag "List them, indented with leading dots" indented)))
2964 (defcustom org-tags-sort-function nil
2965 "When set, tags are sorted using this function as a comparator."
2966 :group 'org-tags
2967 :type '(choice
2968 (const :tag "No sorting" nil)
2969 (const :tag "Alphabetical" string<)
2970 (const :tag "Reverse alphabetical" string>)
2971 (function :tag "Custom function" nil)))
2973 (defvar org-tags-history nil
2974 "History of minibuffer reads for tags.")
2975 (defvar org-last-tags-completion-table nil
2976 "The last used completion table for tags.")
2977 (defvar org-after-tags-change-hook nil
2978 "Hook that is run after the tags in a line have changed.")
2980 (defgroup org-properties nil
2981 "Options concerning properties in Org-mode."
2982 :tag "Org Properties"
2983 :group 'org)
2985 (defcustom org-property-format "%-10s %s"
2986 "How property key/value pairs should be formatted by `indent-line'.
2987 When `indent-line' hits a property definition, it will format the line
2988 according to this format, mainly to make sure that the values are
2989 lined-up with respect to each other."
2990 :group 'org-properties
2991 :type 'string)
2993 (defcustom org-properties-postprocess-alist nil
2994 "Alist of properties and functions to adjust inserted values.
2995 Elements of this alist must be of the form
2997 ([string] [function])
2999 where [string] must be a property name and [function] must be a
3000 lambda expression: this lambda expression must take one argument,
3001 the value to adjust, and return the new value as a string.
3003 For example, this element will allow the property \"Remaining\"
3004 to be updated wrt the relation between the \"Effort\" property
3005 and the clock summary:
3007 ((\"Remaining\" (lambda(value)
3008 (let ((clocksum (org-clock-sum-current-item))
3009 (effort (org-duration-string-to-minutes
3010 (org-entry-get (point) \"Effort\"))))
3011 (org-minutes-to-hh:mm-string (- effort clocksum))))))"
3012 :group 'org-properties
3013 :type 'alist)
3015 (defcustom org-use-property-inheritance nil
3016 "Non-nil means properties apply also for sublevels.
3018 This setting is chiefly used during property searches. Turning it on can
3019 cause significant overhead when doing a search, which is why it is not
3020 on by default.
3022 When nil, only the properties directly given in the current entry count.
3023 When t, every property is inherited. The value may also be a list of
3024 properties that should have inheritance, or a regular expression matching
3025 properties that should be inherited.
3027 However, note that some special properties use inheritance under special
3028 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3029 and the properties ending in \"_ALL\" when they are used as descriptor
3030 for valid values of a property.
3032 Note for programmers:
3033 When querying an entry with `org-entry-get', you can control if inheritance
3034 should be used. By default, `org-entry-get' looks only at the local
3035 properties. You can request inheritance by setting the inherit argument
3036 to t (to force inheritance) or to `selective' (to respect the setting
3037 in this variable)."
3038 :group 'org-properties
3039 :type '(choice
3040 (const :tag "Not" nil)
3041 (const :tag "Always" t)
3042 (repeat :tag "Specific properties" (string :tag "Property"))
3043 (regexp :tag "Properties matched by regexp")))
3045 (defun org-property-inherit-p (property)
3046 "Check if PROPERTY is one that should be inherited."
3047 (cond
3048 ((eq org-use-property-inheritance t) t)
3049 ((not org-use-property-inheritance) nil)
3050 ((stringp org-use-property-inheritance)
3051 (string-match org-use-property-inheritance property))
3052 ((listp org-use-property-inheritance)
3053 (member property org-use-property-inheritance))
3054 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3056 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3057 "The default column format, if no other format has been defined.
3058 This variable can be set on the per-file basis by inserting a line
3060 #+COLUMNS: %25ITEM ....."
3061 :group 'org-properties
3062 :type 'string)
3064 (defcustom org-columns-ellipses ".."
3065 "The ellipses to be used when a field in column view is truncated.
3066 When this is the empty string, as many characters as possible are shown,
3067 but then there will be no visual indication that the field has been truncated.
3068 When this is a string of length N, the last N characters of a truncated
3069 field are replaced by this string. If the column is narrower than the
3070 ellipses string, only part of the ellipses string will be shown."
3071 :group 'org-properties
3072 :type 'string)
3074 (defcustom org-columns-modify-value-for-display-function nil
3075 "Function that modifies values for display in column view.
3076 For example, it can be used to cut out a certain part from a time stamp.
3077 The function must take 2 arguments:
3079 column-title The title of the column (*not* the property name)
3080 value The value that should be modified.
3082 The function should return the value that should be displayed,
3083 or nil if the normal value should be used."
3084 :group 'org-properties
3085 :type 'function)
3087 (defcustom org-effort-property "Effort"
3088 "The property that is being used to keep track of effort estimates.
3089 Effort estimates given in this property need to have the format H:MM."
3090 :group 'org-properties
3091 :group 'org-progress
3092 :type '(string :tag "Property"))
3094 (defconst org-global-properties-fixed
3095 '(("VISIBILITY_ALL" . "folded children content all")
3096 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3097 "List of property/value pairs that can be inherited by any entry.
3099 These are fixed values, for the preset properties. The user variable
3100 that can be used to add to this list is `org-global-properties'.
3102 The entries in this list are cons cells where the car is a property
3103 name and cdr is a string with the value. If the value represents
3104 multiple items like an \"_ALL\" property, separate the items by
3105 spaces.")
3107 (defcustom org-global-properties nil
3108 "List of property/value pairs that can be inherited by any entry.
3110 This list will be combined with the constant `org-global-properties-fixed'.
3112 The entries in this list are cons cells where the car is a property
3113 name and cdr is a string with the value.
3115 You can set buffer-local values for the same purpose in the variable
3116 `org-file-properties' this by adding lines like
3118 #+PROPERTY: NAME VALUE"
3119 :group 'org-properties
3120 :type '(repeat
3121 (cons (string :tag "Property")
3122 (string :tag "Value"))))
3124 (defvar org-file-properties nil
3125 "List of property/value pairs that can be inherited by any entry.
3126 Valid for the current buffer.
3127 This variable is populated from #+PROPERTY lines.")
3128 (make-variable-buffer-local 'org-file-properties)
3130 (defgroup org-agenda nil
3131 "Options concerning agenda views in Org-mode."
3132 :tag "Org Agenda"
3133 :group 'org)
3135 (defvar org-category nil
3136 "Variable used by org files to set a category for agenda display.
3137 Such files should use a file variable to set it, for example
3139 # -*- mode: org; org-category: \"ELisp\"
3141 or contain a special line
3143 #+CATEGORY: ELisp
3145 If the file does not specify a category, then file's base name
3146 is used instead.")
3147 (make-variable-buffer-local 'org-category)
3148 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3150 (defcustom org-agenda-files nil
3151 "The files to be used for agenda display.
3152 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3153 \\[org-remove-file]. You can also use customize to edit the list.
3155 If an entry is a directory, all files in that directory that are matched by
3156 `org-agenda-file-regexp' will be part of the file list.
3158 If the value of the variable is not a list but a single file name, then
3159 the list of agenda files is actually stored and maintained in that file, one
3160 agenda file per line. In this file paths can be given relative to
3161 `org-directory'. Tilde expansion and environment variable substitution
3162 are also made."
3163 :group 'org-agenda
3164 :type '(choice
3165 (repeat :tag "List of files and directories" file)
3166 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3168 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3169 "Regular expression to match files for `org-agenda-files'.
3170 If any element in the list in that variable contains a directory instead
3171 of a normal file, all files in that directory that are matched by this
3172 regular expression will be included."
3173 :group 'org-agenda
3174 :type 'regexp)
3176 (defcustom org-agenda-text-search-extra-files nil
3177 "List of extra files to be searched by text search commands.
3178 These files will be search in addition to the agenda files by the
3179 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3180 Note that these files will only be searched for text search commands,
3181 not for the other agenda views like todo lists, tag searches or the weekly
3182 agenda. This variable is intended to list notes and possibly archive files
3183 that should also be searched by these two commands.
3184 In fact, if the first element in the list is the symbol `agenda-archives',
3185 than all archive files of all agenda files will be added to the search
3186 scope."
3187 :group 'org-agenda
3188 :type '(set :greedy t
3189 (const :tag "Agenda Archives" agenda-archives)
3190 (repeat :inline t (file))))
3192 (if (fboundp 'defvaralias)
3193 (defvaralias 'org-agenda-multi-occur-extra-files
3194 'org-agenda-text-search-extra-files))
3196 (defcustom org-agenda-skip-unavailable-files nil
3197 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3198 A nil value means to remove them, after a query, from the list."
3199 :group 'org-agenda
3200 :type 'boolean)
3202 (defcustom org-calendar-to-agenda-key [?c]
3203 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3204 The command `org-calendar-goto-agenda' will be bound to this key. The
3205 default is the character `c' because then `c' can be used to switch back and
3206 forth between agenda and calendar."
3207 :group 'org-agenda
3208 :type 'sexp)
3210 (defcustom org-calendar-agenda-action-key [?k]
3211 "The key to be installed in `calendar-mode-map' for agenda-action.
3212 The command `org-agenda-action' will be bound to this key. The
3213 default is the character `k' because we use the same key in the agenda."
3214 :group 'org-agenda
3215 :type 'sexp)
3217 (defcustom org-calendar-insert-diary-entry-key [?i]
3218 "The key to be installed in `calendar-mode-map' for adding diary entries.
3219 This option is irrelevant until `org-agenda-diary-file' has been configured
3220 to point to an Org-mode file. When that is the case, the command
3221 `org-agenda-diary-entry' will be bound to the key given here, by default
3222 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3223 if you want to continue doing this, you need to change this to a different
3224 key."
3225 :group 'org-agenda
3226 :type 'sexp)
3228 (defcustom org-agenda-diary-file 'diary-file
3229 "File to which to add new entries with the `i' key in agenda and calendar.
3230 When this is the symbol `diary-file', the functionality in the Emacs
3231 calendar will be used to add entries to the `diary-file'. But when this
3232 points to a file, `org-agenda-diary-entry' will be used instead."
3233 :group 'org-agenda
3234 :type '(choice
3235 (const :tag "The standard Emacs diary file" diary-file)
3236 (file :tag "Special Org file diary entries")))
3238 (eval-after-load "calendar"
3239 '(progn
3240 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3241 'org-calendar-goto-agenda)
3242 (org-defkey calendar-mode-map org-calendar-agenda-action-key
3243 'org-agenda-action)
3244 (add-hook 'calendar-mode-hook
3245 (lambda ()
3246 (unless (eq org-agenda-diary-file 'diary-file)
3247 (define-key calendar-mode-map
3248 org-calendar-insert-diary-entry-key
3249 'org-agenda-diary-entry))))))
3251 (defgroup org-latex nil
3252 "Options for embedding LaTeX code into Org-mode."
3253 :tag "Org LaTeX"
3254 :group 'org)
3256 (defcustom org-format-latex-options
3257 '(:foreground default :background default :scale 1.0
3258 :html-foreground "Black" :html-background "Transparent"
3259 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3260 "Options for creating images from LaTeX fragments.
3261 This is a property list with the following properties:
3262 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3263 `default' means use the foreground of the default face.
3264 :background the background color, or \"Transparent\".
3265 `default' means use the background of the default face.
3266 :scale a scaling factor for the size of the images, to get more pixels
3267 :html-foreground, :html-background, :html-scale
3268 the same numbers for HTML export.
3269 :matchers a list indicating which matchers should be used to
3270 find LaTeX fragments. Valid members of this list are:
3271 \"begin\" find environments
3272 \"$1\" find single characters surrounded by $.$
3273 \"$\" find math expressions surrounded by $...$
3274 \"$$\" find math expressions surrounded by $$....$$
3275 \"\\(\" find math expressions surrounded by \\(...\\)
3276 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3277 :group 'org-latex
3278 :type 'plist)
3280 (defcustom org-format-latex-signal-error t
3281 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3282 When nil, just push out a message."
3283 :group 'org-latex
3284 :type 'boolean)
3286 (defcustom org-format-latex-header "\\documentclass{article}
3287 \\usepackage[usenames]{color}
3288 \\usepackage{amsmath}
3289 \\usepackage[mathscr]{eucal}
3290 \\pagestyle{empty} % do not remove
3291 \[PACKAGES]
3292 \[DEFAULT-PACKAGES]
3293 % The settings below are copied from fullpage.sty
3294 \\setlength{\\textwidth}{\\paperwidth}
3295 \\addtolength{\\textwidth}{-3cm}
3296 \\setlength{\\oddsidemargin}{1.5cm}
3297 \\addtolength{\\oddsidemargin}{-2.54cm}
3298 \\setlength{\\evensidemargin}{\\oddsidemargin}
3299 \\setlength{\\textheight}{\\paperheight}
3300 \\addtolength{\\textheight}{-\\headheight}
3301 \\addtolength{\\textheight}{-\\headsep}
3302 \\addtolength{\\textheight}{-\\footskip}
3303 \\addtolength{\\textheight}{-3cm}
3304 \\setlength{\\topmargin}{1.5cm}
3305 \\addtolength{\\topmargin}{-2.54cm}"
3306 "The document header used for processing LaTeX fragments.
3307 It is imperative that this header make sure that no page number
3308 appears on the page. The package defined in the variables
3309 `org-export-latex-default-packages-alist' and `org-export-latex-packages-alist'
3310 will either replace the placeholder \"[PACKAGES]\" in this header, or they
3311 will be appended."
3312 :group 'org-latex
3313 :type 'string)
3315 (defvar org-format-latex-header-extra nil)
3317 (defun org-set-packages-alist (var val)
3318 "Set the packages alist and make sure it has 3 elements per entry."
3319 (set var (mapcar (lambda (x)
3320 (if (and (consp x) (= (length x) 2))
3321 (list (car x) (nth 1 x) t)
3323 val)))
3325 (defun org-get-packages-alist (var)
3327 "Get the packages alist and make sure it has 3 elements per entry."
3328 (mapcar (lambda (x)
3329 (if (and (consp x) (= (length x) 2))
3330 (list (car x) (nth 1 x) t)
3332 (default-value var)))
3334 ;; The following variables are defined here because is it also used
3335 ;; when formatting latex fragments. Originally it was part of the
3336 ;; LaTeX exporter, which is why the name includes "export".
3337 (defcustom org-export-latex-default-packages-alist
3338 '(("AUTO" "inputenc" t)
3339 ("T1" "fontenc" t)
3340 ("" "fixltx2e" nil)
3341 ("" "graphicx" t)
3342 ("" "longtable" nil)
3343 ("" "float" nil)
3344 ("" "wrapfig" nil)
3345 ("" "soul" t)
3346 ("" "textcomp" t)
3347 ("" "marvosym" t)
3348 ("" "wasysym" t)
3349 ("" "latexsym" t)
3350 ("" "amssymb" t)
3351 ("" "hyperref" nil)
3352 "\\tolerance=1000"
3354 "Alist of default packages to be inserted in the header.
3355 Change this only if one of the packages here causes an incompatibility
3356 with another package you are using.
3357 The packages in this list are needed by one part or another of Org-mode
3358 to function properly.
3360 - inputenc, fontenc: for basic font and character selection
3361 - textcomp, marvosymb, wasysym, latexsym, amssym: for various symbols used
3362 for interpreting the entities in `org-entities'. You can skip some of these
3363 packages if you don't use any of the symbols in it.
3364 - graphicx: for including images
3365 - float, wrapfig: for figure placement
3366 - longtable: for long tables
3367 - hyperref: for cross references
3369 Therefore you should not modify this variable unless you know what you
3370 are doing. The one reason to change it anyway is that you might be loading
3371 some other package that conflicts with one of the default packages.
3372 Each cell is of the format \( \"options\" \"package\" snippet-flag\).
3373 If SNIPPET-FLAG is t, the package also needs to be included when
3374 compiling LaTeX snippets into images for inclusion into HTML."
3375 :group 'org-export-latex
3376 :set 'org-set-packages-alist
3377 :get 'org-get-packages-alist
3378 :type '(repeat
3379 (choice
3380 (list :tag "options/package pair"
3381 (string :tag "options")
3382 (string :tag "package")
3383 (boolean :tag "Snippet"))
3384 (string :tag "A line of LaTeX"))))
3386 (defcustom org-export-latex-packages-alist nil
3387 "Alist of packages to be inserted in every LaTeX header.
3388 These will be inserted after `org-export-latex-default-packages-alist'.
3389 Each cell is of the format \( \"options\" \"package\" snippet-flag \).
3390 SNIPPET-FLAG, when t, indicates that this package is also needed when
3391 turning LaTeX snippets into images for inclusion into HTML.
3392 Make sure that you only list packages here which:
3393 - you want in every file
3394 - do not conflict with the default packages in
3395 `org-export-latex-default-packages-alist'
3396 - do not conflict with the setup in `org-format-latex-header'."
3397 :group 'org-export-latex
3398 :set 'org-set-packages-alist
3399 :get 'org-get-packages-alist
3400 :type '(repeat
3401 (choice
3402 (list :tag "options/package pair"
3403 (string :tag "options")
3404 (string :tag "package")
3405 (boolean :tag "Snippet"))
3406 (string :tag "A line of LaTeX"))))
3409 (defgroup org-appearance nil
3410 "Settings for Org-mode appearance."
3411 :tag "Org Appearance"
3412 :group 'org)
3414 (defcustom org-level-color-stars-only nil
3415 "Non-nil means fontify only the stars in each headline.
3416 When nil, the entire headline is fontified.
3417 Changing it requires restart of `font-lock-mode' to become effective
3418 also in regions already fontified."
3419 :group 'org-appearance
3420 :type 'boolean)
3422 (defcustom org-hide-leading-stars nil
3423 "Non-nil means hide the first N-1 stars in a headline.
3424 This works by using the face `org-hide' for these stars. This
3425 face is white for a light background, and black for a dark
3426 background. You may have to customize the face `org-hide' to
3427 make this work.
3428 Changing it requires restart of `font-lock-mode' to become effective
3429 also in regions already fontified.
3430 You may also set this on a per-file basis by adding one of the following
3431 lines to the buffer:
3433 #+STARTUP: hidestars
3434 #+STARTUP: showstars"
3435 :group 'org-appearance
3436 :type 'boolean)
3438 (defcustom org-hidden-keywords nil
3439 "List of symbols corresponding to keywords to be hidden the org buffer.
3440 For example, a value '(title) for this list will make the document's title
3441 appear in the buffer without the initial #+TITLE: keyword."
3442 :group 'org-appearance
3443 :type '(set (const :tag "#+AUTHOR" author)
3444 (const :tag "#+DATE" date)
3445 (const :tag "#+EMAIL" email)
3446 (const :tag "#+TITLE" title)))
3448 (defcustom org-fontify-done-headline nil
3449 "Non-nil means change the face of a headline if it is marked DONE.
3450 Normally, only the TODO/DONE keyword indicates the state of a headline.
3451 When this is non-nil, the headline after the keyword is set to the
3452 `org-headline-done' as an additional indication."
3453 :group 'org-appearance
3454 :type 'boolean)
3456 (defcustom org-fontify-emphasized-text t
3457 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3458 Changing this variable requires a restart of Emacs to take effect."
3459 :group 'org-appearance
3460 :type 'boolean)
3462 (defcustom org-fontify-whole-heading-line nil
3463 "Non-nil means fontify the whole line for headings.
3464 This is useful when setting a background color for the
3465 org-level-* faces."
3466 :group 'org-appearance
3467 :type 'boolean)
3469 (defcustom org-highlight-latex-fragments-and-specials nil
3470 "Non-nil means fontify what is treated specially by the exporters."
3471 :group 'org-appearance
3472 :type 'boolean)
3474 (defcustom org-hide-emphasis-markers nil
3475 "Non-nil mean font-lock should hide the emphasis marker characters."
3476 :group 'org-appearance
3477 :type 'boolean)
3479 (defcustom org-pretty-entities nil
3480 "Non-nil means show entities as UTF8 characters.
3481 When nil, the \\name form remains in the buffer."
3482 :group 'org-appearance
3483 :type 'boolean)
3485 (defcustom org-pretty-entities-include-sub-superscripts t
3486 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3487 :group 'org-appearance
3488 :type 'boolean)
3490 (defvar org-emph-re nil
3491 "Regular expression for matching emphasis.
3492 After a match, the match groups contain these elements:
3493 0 The match of the full regular expression, including the characters
3494 before and after the proper match
3495 1 The character before the proper match, or empty at beginning of line
3496 2 The proper match, including the leading and trailing markers
3497 3 The leading marker like * or /, indicating the type of highlighting
3498 4 The text between the emphasis markers, not including the markers
3499 5 The character after the match, empty at the end of a line")
3500 (defvar org-verbatim-re nil
3501 "Regular expression for matching verbatim text.")
3502 (defvar org-emphasis-regexp-components) ; defined just below
3503 (defvar org-emphasis-alist) ; defined just below
3504 (defun org-set-emph-re (var val)
3505 "Set variable and compute the emphasis regular expression."
3506 (set var val)
3507 (when (and (boundp 'org-emphasis-alist)
3508 (boundp 'org-emphasis-regexp-components)
3509 org-emphasis-alist org-emphasis-regexp-components)
3510 (let* ((e org-emphasis-regexp-components)
3511 (pre (car e))
3512 (post (nth 1 e))
3513 (border (nth 2 e))
3514 (body (nth 3 e))
3515 (nl (nth 4 e))
3516 (body1 (concat body "*?"))
3517 (markers (mapconcat 'car org-emphasis-alist ""))
3518 (vmarkers (mapconcat
3519 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3520 org-emphasis-alist "")))
3521 ;; make sure special characters appear at the right position in the class
3522 (if (string-match "\\^" markers)
3523 (setq markers (concat (replace-match "" t t markers) "^")))
3524 (if (string-match "-" markers)
3525 (setq markers (concat (replace-match "" t t markers) "-")))
3526 (if (string-match "\\^" vmarkers)
3527 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3528 (if (string-match "-" vmarkers)
3529 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3530 (if (> nl 0)
3531 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3532 (int-to-string nl) "\\}")))
3533 ;; Make the regexp
3534 (setq org-emph-re
3535 (concat "\\([" pre "]\\|^\\)"
3536 "\\("
3537 "\\([" markers "]\\)"
3538 "\\("
3539 "[^" border "]\\|"
3540 "[^" border "]"
3541 body1
3542 "[^" border "]"
3543 "\\)"
3544 "\\3\\)"
3545 "\\([" post "]\\|$\\)"))
3546 (setq org-verbatim-re
3547 (concat "\\([" pre "]\\|^\\)"
3548 "\\("
3549 "\\([" vmarkers "]\\)"
3550 "\\("
3551 "[^" border "]\\|"
3552 "[^" border "]"
3553 body1
3554 "[^" border "]"
3555 "\\)"
3556 "\\3\\)"
3557 "\\([" post "]\\|$\\)")))))
3559 (defcustom org-emphasis-regexp-components
3560 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
3561 "Components used to build the regular expression for emphasis.
3562 This is a list with five entries. Terminology: In an emphasis string
3563 like \" *strong word* \", we call the initial space PREMATCH, the final
3564 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3565 and \"trong wor\" is the body. The different components in this variable
3566 specify what is allowed/forbidden in each part:
3568 pre Chars allowed as prematch. Beginning of line will be allowed too.
3569 post Chars allowed as postmatch. End of line will be allowed too.
3570 border The chars *forbidden* as border characters.
3571 body-regexp A regexp like \".\" to match a body character. Don't use
3572 non-shy groups here, and don't allow newline here.
3573 newline The maximum number of newlines allowed in an emphasis exp.
3575 Use customize to modify this, or restart Emacs after changing it."
3576 :group 'org-appearance
3577 :set 'org-set-emph-re
3578 :type '(list
3579 (sexp :tag "Allowed chars in pre ")
3580 (sexp :tag "Allowed chars in post ")
3581 (sexp :tag "Forbidden chars in border ")
3582 (sexp :tag "Regexp for body ")
3583 (integer :tag "number of newlines allowed")
3584 (option (boolean :tag "Please ignore this button"))))
3586 (defcustom org-emphasis-alist
3587 `(("*" bold "<b>" "</b>")
3588 ("/" italic "<i>" "</i>")
3589 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
3590 ("=" org-code "<code>" "</code>" verbatim)
3591 ("~" org-verbatim "<code>" "</code>" verbatim)
3592 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
3593 "<del>" "</del>")
3595 "Special syntax for emphasized text.
3596 Text starting and ending with a special character will be emphasized, for
3597 example *bold*, _underlined_ and /italic/. This variable sets the marker
3598 characters, the face to be used by font-lock for highlighting in Org-mode
3599 Emacs buffers, and the HTML tags to be used for this.
3600 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
3601 For DocBook export, see the variable `org-export-docbook-emphasis-alist'.
3602 Use customize to modify this, or restart Emacs after changing it."
3603 :group 'org-appearance
3604 :set 'org-set-emph-re
3605 :type '(repeat
3606 (list
3607 (string :tag "Marker character")
3608 (choice
3609 (face :tag "Font-lock-face")
3610 (plist :tag "Face property list"))
3611 (string :tag "HTML start tag")
3612 (string :tag "HTML end tag")
3613 (option (const verbatim)))))
3615 (defvar org-protecting-blocks
3616 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
3617 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
3618 This is needed for font-lock setup.")
3620 ;;; Miscellaneous options
3622 (defgroup org-completion nil
3623 "Completion in Org-mode."
3624 :tag "Org Completion"
3625 :group 'org)
3627 (defcustom org-completion-use-ido nil
3628 "Non-nil means use ido completion wherever possible.
3629 Note that `ido-mode' must be active for this variable to be relevant.
3630 If you decide to turn this variable on, you might well want to turn off
3631 `org-outline-path-complete-in-steps'.
3632 See also `org-completion-use-iswitchb'."
3633 :group 'org-completion
3634 :type 'boolean)
3636 (defcustom org-completion-use-iswitchb nil
3637 "Non-nil means use iswitchb completion wherever possible.
3638 Note that `iswitchb-mode' must be active for this variable to be relevant.
3639 If you decide to turn this variable on, you might well want to turn off
3640 `org-outline-path-complete-in-steps'.
3641 Note that this variable has only an effect if `org-completion-use-ido' is nil."
3642 :group 'org-completion
3643 :type 'boolean)
3645 (defcustom org-completion-fallback-command 'hippie-expand
3646 "The expansion command called by \\[pcomplete] in normal context.
3647 Normal means, no org-mode-specific context."
3648 :group 'org-completion
3649 :type 'function)
3651 ;;; Functions and variables from their packages
3652 ;; Declared here to avoid compiler warnings
3654 ;; XEmacs only
3655 (defvar outline-mode-menu-heading)
3656 (defvar outline-mode-menu-show)
3657 (defvar outline-mode-menu-hide)
3658 (defvar zmacs-regions) ; XEmacs regions
3660 ;; Emacs only
3661 (defvar mark-active)
3663 ;; Various packages
3664 (declare-function calendar-absolute-from-iso "cal-iso" (date))
3665 (declare-function calendar-forward-day "cal-move" (arg))
3666 (declare-function calendar-goto-date "cal-move" (date))
3667 (declare-function calendar-goto-today "cal-move" ())
3668 (declare-function calendar-iso-from-absolute "cal-iso" (date))
3669 (defvar calc-embedded-close-formula)
3670 (defvar calc-embedded-open-formula)
3671 (declare-function cdlatex-tab "ext:cdlatex" ())
3672 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3673 (defvar font-lock-unfontify-region-function)
3674 (declare-function iswitchb-read-buffer "iswitchb"
3675 (prompt &optional default require-match start matches-set))
3676 (defvar iswitchb-temp-buflist)
3677 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
3678 (defvar org-agenda-tags-todo-honor-ignore-options)
3679 (declare-function org-agenda-skip "org-agenda" ())
3680 (declare-function
3681 org-format-agenda-item "org-agenda"
3682 (extra txt &optional category tags dotime noprefix remove-re habitp))
3683 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
3684 (declare-function org-agenda-change-all-lines "org-agenda"
3685 (newhead hdmarker &optional fixface just-this))
3686 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
3687 (declare-function org-agenda-maybe-redo "org-agenda" ())
3688 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
3689 (beg end))
3690 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
3691 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
3692 "org-agenda" (&optional end))
3693 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
3694 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
3695 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
3696 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
3697 (declare-function org-indent-mode "org-indent" (&optional arg))
3698 (declare-function parse-time-string "parse-time" (string))
3699 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
3700 (declare-function org-export-latex-fix-inputenc "org-latex" ())
3701 (declare-function orgtbl-send-table "org-table" (&optional maybe))
3702 (defvar remember-data-file)
3703 (defvar texmathp-why)
3704 (declare-function speedbar-line-directory "speedbar" (&optional depth))
3705 (declare-function table--at-cell-p "table" (position &optional object at-column))
3707 (defvar w3m-current-url)
3708 (defvar w3m-current-title)
3710 (defvar org-latex-regexps)
3712 ;;; Autoload and prepare some org modules
3714 ;; Some table stuff that needs to be defined here, because it is used
3715 ;; by the functions setting up org-mode or checking for table context.
3717 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
3718 "Detect an org-type or table-type table.")
3719 (defconst org-table-line-regexp "^[ \t]*|"
3720 "Detect an org-type table line.")
3721 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
3722 "Detect an org-type table line.")
3723 (defconst org-table-hline-regexp "^[ \t]*|-"
3724 "Detect an org-type table hline.")
3725 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
3726 "Detect a table-type table hline.")
3727 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
3728 "Detect the first line outside a table when searching from within it.
3729 This works for both table types.")
3731 ;; Autoload the functions in org-table.el that are needed by functions here.
3733 (eval-and-compile
3734 (org-autoload "org-table"
3735 '(org-table-align org-table-begin org-table-blank-field
3736 org-table-convert org-table-convert-region org-table-copy-down
3737 org-table-copy-region org-table-create
3738 org-table-create-or-convert-from-region
3739 org-table-create-with-table.el org-table-current-dline
3740 org-table-cut-region org-table-delete-column org-table-edit-field
3741 org-table-edit-formulas org-table-end org-table-eval-formula
3742 org-table-export org-table-field-info
3743 org-table-get-stored-formulas org-table-goto-column
3744 org-table-hline-and-move org-table-import org-table-insert-column
3745 org-table-insert-hline org-table-insert-row org-table-iterate
3746 org-table-justify-field-maybe org-table-kill-row
3747 org-table-maybe-eval-formula org-table-maybe-recalculate-line
3748 org-table-move-column org-table-move-column-left
3749 org-table-move-column-right org-table-move-row
3750 org-table-move-row-down org-table-move-row-up
3751 org-table-next-field org-table-next-row org-table-paste-rectangle
3752 org-table-previous-field org-table-recalculate
3753 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
3754 org-table-toggle-coordinate-overlays
3755 org-table-toggle-formula-debugger org-table-wrap-region
3756 orgtbl-mode turn-on-orgtbl org-table-to-lisp
3757 orgtbl-to-generic orgtbl-to-tsv orgtbl-to-csv orgtbl-to-latex
3758 orgtbl-to-orgtbl orgtbl-to-html orgtbl-to-texinfo)))
3760 (defun org-at-table-p (&optional table-type)
3761 "Return t if the cursor is inside an org-type table.
3762 If TABLE-TYPE is non-nil, also check for table.el-type tables."
3763 (if org-enable-table-editor
3764 (save-excursion
3765 (beginning-of-line 1)
3766 (looking-at (if table-type org-table-any-line-regexp
3767 org-table-line-regexp)))
3768 nil))
3769 (defsubst org-table-p () (org-at-table-p))
3771 (defun org-at-table.el-p ()
3772 "Return t if and only if we are at a table.el table."
3773 (and (org-at-table-p 'any)
3774 (save-excursion
3775 (goto-char (org-table-begin 'any))
3776 (looking-at org-table1-hline-regexp))))
3777 (defun org-table-recognize-table.el ()
3778 "If there is a table.el table nearby, recognize it and move into it."
3779 (if org-table-tab-recognizes-table.el
3780 (if (org-at-table.el-p)
3781 (progn
3782 (beginning-of-line 1)
3783 (if (looking-at org-table-dataline-regexp)
3785 (if (looking-at org-table1-hline-regexp)
3786 (progn
3787 (beginning-of-line 2)
3788 (if (looking-at org-table-any-border-regexp)
3789 (beginning-of-line -1)))))
3790 (if (re-search-forward "|" (org-table-end t) t)
3791 (progn
3792 (require 'table)
3793 (if (table--at-cell-p (point))
3795 (message "recognizing table.el table...")
3796 (table-recognize-table)
3797 (message "recognizing table.el table...done")))
3798 (error "This should not happen"))
3800 nil)
3801 nil))
3803 (defun org-at-table-hline-p ()
3804 "Return t if the cursor is inside a hline in a table."
3805 (if org-enable-table-editor
3806 (save-excursion
3807 (beginning-of-line 1)
3808 (looking-at org-table-hline-regexp))
3809 nil))
3811 (defvar org-table-clean-did-remove-column nil)
3813 (defun org-table-map-tables (function &optional quietly)
3814 "Apply FUNCTION to the start of all tables in the buffer."
3815 (save-excursion
3816 (save-restriction
3817 (widen)
3818 (goto-char (point-min))
3819 (while (re-search-forward org-table-any-line-regexp nil t)
3820 (unless quietly
3821 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
3822 (beginning-of-line 1)
3823 (when (looking-at org-table-line-regexp)
3824 (save-excursion (funcall function))
3825 (or (looking-at org-table-line-regexp)
3826 (forward-char 1)))
3827 (re-search-forward org-table-any-border-regexp nil 1))))
3828 (unless quietly (message "Mapping tables: done")))
3830 ;; Declare and autoload functions from org-exp.el & Co
3832 (declare-function org-default-export-plist "org-exp")
3833 (declare-function org-infile-export-plist "org-exp")
3834 (declare-function org-get-current-options "org-exp")
3835 (eval-and-compile
3836 (org-autoload "org-exp"
3837 '(org-export org-export-visible
3838 org-insert-export-options-template
3839 org-table-clean-before-export))
3840 (org-autoload "org-ascii"
3841 '(org-export-as-ascii org-export-ascii-preprocess
3842 org-export-as-ascii-to-buffer org-replace-region-by-ascii
3843 org-export-region-as-ascii))
3844 (org-autoload "org-latex"
3845 '(org-export-as-latex-batch org-export-as-latex-to-buffer
3846 org-replace-region-by-latex org-export-region-as-latex
3847 org-export-as-latex org-export-as-pdf
3848 org-export-as-pdf-and-open))
3849 (org-autoload "org-html"
3850 '(org-export-as-html-and-open
3851 org-export-as-html-batch org-export-as-html-to-buffer
3852 org-replace-region-by-html org-export-region-as-html
3853 org-export-as-html))
3854 (org-autoload "org-docbook"
3855 '(org-export-as-docbook-batch org-export-as-docbook-to-buffer
3856 org-replace-region-by-docbook org-export-region-as-docbook
3857 org-export-as-docbook-pdf org-export-as-docbook-pdf-and-open
3858 org-export-as-docbook))
3859 (org-autoload "org-icalendar"
3860 '(org-export-icalendar-this-file
3861 org-export-icalendar-all-agenda-files
3862 org-export-icalendar-combine-agenda-files))
3863 (org-autoload "org-xoxo" '(org-export-as-xoxo))
3864 (org-autoload "org-beamer" '(org-beamer-mode org-beamer-sectioning)))
3866 ;; Declare and autoload functions from org-agenda.el
3868 (eval-and-compile
3869 (org-autoload "org-agenda"
3870 '(org-agenda org-agenda-list org-search-view
3871 org-todo-list org-tags-view org-agenda-list-stuck-projects
3872 org-diary org-agenda-to-appt
3873 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
3875 ;; Autoload org-remember
3877 (eval-and-compile
3878 (org-autoload "org-remember"
3879 '(org-remember-insinuate org-remember-annotation
3880 org-remember-apply-template org-remember org-remember-handler)))
3882 (eval-and-compile
3883 (org-autoload "org-capture"
3884 '(org-capture org-capture-insert-template-here
3885 org-capture-import-remember-templates)))
3887 ;; Autoload org-clock.el
3889 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
3890 (beg end))
3891 (declare-function org-clock-update-mode-line "org-clock" ())
3892 (declare-function org-resolve-clocks "org-clock"
3893 (&optional also-non-dangling-p prompt last-valid))
3894 (defvar org-clock-start-time)
3895 (defvar org-clock-marker (make-marker)
3896 "Marker recording the last clock-in.")
3897 (defvar org-clock-hd-marker (make-marker)
3898 "Marker recording the last clock-in, but the headline position.")
3899 (defvar org-clock-heading ""
3900 "The heading of the current clock entry.")
3901 (defun org-clock-is-active ()
3902 "Return non-nil if clock is currently running.
3903 The return value is actually the clock marker."
3904 (marker-buffer org-clock-marker))
3906 (eval-and-compile
3907 (org-autoload
3908 "org-clock"
3909 '(org-clock-in org-clock-out org-clock-cancel
3910 org-clock-goto org-clock-sum org-clock-display
3911 org-clock-remove-overlays org-clock-report
3912 org-clocktable-shift org-dblock-write:clocktable
3913 org-get-clocktable org-resolve-clocks)))
3915 (defun org-clock-update-time-maybe ()
3916 "If this is a CLOCK line, update it and return t.
3917 Otherwise, return nil."
3918 (interactive)
3919 (save-excursion
3920 (beginning-of-line 1)
3921 (skip-chars-forward " \t")
3922 (when (looking-at org-clock-string)
3923 (let ((re (concat "[ \t]*" org-clock-string
3924 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
3925 "\\([ \t]*=>.*\\)?\\)?"))
3926 ts te h m s neg)
3927 (cond
3928 ((not (looking-at re))
3929 nil)
3930 ((not (match-end 2))
3931 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3932 (> org-clock-marker (point))
3933 (<= org-clock-marker (point-at-eol)))
3934 ;; The clock is running here
3935 (setq org-clock-start-time
3936 (apply 'encode-time
3937 (org-parse-time-string (match-string 1))))
3938 (org-clock-update-mode-line)))
3940 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
3941 (end-of-line 1)
3942 (setq ts (match-string 1)
3943 te (match-string 3))
3944 (setq s (- (org-float-time
3945 (apply 'encode-time (org-parse-time-string te)))
3946 (org-float-time
3947 (apply 'encode-time (org-parse-time-string ts))))
3948 neg (< s 0)
3949 s (abs s)
3950 h (floor (/ s 3600))
3951 s (- s (* 3600 h))
3952 m (floor (/ s 60))
3953 s (- s (* 60 s)))
3954 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
3955 t))))))
3957 (defun org-check-running-clock ()
3958 "Check if the current buffer contains the running clock.
3959 If yes, offer to stop it and to save the buffer with the changes."
3960 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3961 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
3962 (buffer-name))))
3963 (org-clock-out)
3964 (when (y-or-n-p "Save changed buffer?")
3965 (save-buffer))))
3967 (defun org-clocktable-try-shift (dir n)
3968 "Check if this line starts a clock table, if yes, shift the time block."
3969 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
3970 (org-clocktable-shift dir n)))
3972 ;; Autoload org-timer.el
3974 (eval-and-compile
3975 (org-autoload
3976 "org-timer"
3977 '(org-timer-start org-timer org-timer-item
3978 org-timer-change-times-in-region
3979 org-timer-set-timer
3980 org-timer-reset-timers
3981 org-timer-show-remaining-time)))
3983 ;; Autoload org-feed.el
3985 (eval-and-compile
3986 (org-autoload
3987 "org-feed"
3988 '(org-feed-update org-feed-update-all org-feed-goto-inbox)))
3991 ;; Autoload org-indent.el
3993 ;; Define the variable already here, to make sure we have it.
3994 (defvar org-indent-mode nil
3995 "Non-nil if Org-Indent mode is enabled.
3996 Use the command `org-indent-mode' to change this variable.")
3998 (eval-and-compile
3999 (org-autoload
4000 "org-indent"
4001 '(org-indent-mode)))
4003 ;; Autoload org-mobile.el
4005 (eval-and-compile
4006 (org-autoload
4007 "org-mobile"
4008 '(org-mobile-push org-mobile-pull org-mobile-create-sumo-agenda)))
4010 ;; Autoload archiving code
4011 ;; The stuff that is needed for cycling and tags has to be defined here.
4013 (defgroup org-archive nil
4014 "Options concerning archiving in Org-mode."
4015 :tag "Org Archive"
4016 :group 'org-structure)
4018 (defcustom org-archive-location "%s_archive::"
4019 "The location where subtrees should be archived.
4021 The value of this variable is a string, consisting of two parts,
4022 separated by a double-colon. The first part is a filename and
4023 the second part is a headline.
4025 When the filename is omitted, archiving happens in the same file.
4026 %s in the filename will be replaced by the current file
4027 name (without the directory part). Archiving to a different file
4028 is useful to keep archived entries from contributing to the
4029 Org-mode Agenda.
4031 The archived entries will be filed as subtrees of the specified
4032 headline. When the headline is omitted, the subtrees are simply
4033 filed away at the end of the file, as top-level entries. Also in
4034 the heading you can use %s to represent the file name, this can be
4035 useful when using the same archive for a number of different files.
4037 Here are a few examples:
4038 \"%s_archive::\"
4039 If the current file is Projects.org, archive in file
4040 Projects.org_archive, as top-level trees. This is the default.
4042 \"::* Archived Tasks\"
4043 Archive in the current file, under the top-level headline
4044 \"* Archived Tasks\".
4046 \"~/org/archive.org::\"
4047 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4049 \"~/org/archive.org::From %s\"
4050 Archive in file ~/org/archive.org (absolute path), under headlines
4051 \"From FILENAME\" where file name is the current file name.
4053 \"basement::** Finished Tasks\"
4054 Archive in file ./basement (relative path), as level 3 trees
4055 below the level 2 heading \"** Finished Tasks\".
4057 You may set this option on a per-file basis by adding to the buffer a
4058 line like
4060 #+ARCHIVE: basement::** Finished Tasks
4062 You may also define it locally for a subtree by setting an ARCHIVE property
4063 in the entry. If such a property is found in an entry, or anywhere up
4064 the hierarchy, it will be used."
4065 :group 'org-archive
4066 :type 'string)
4068 (defcustom org-archive-tag "ARCHIVE"
4069 "The tag that marks a subtree as archived.
4070 An archived subtree does not open during visibility cycling, and does
4071 not contribute to the agenda listings.
4072 After changing this, font-lock must be restarted in the relevant buffers to
4073 get the proper fontification."
4074 :group 'org-archive
4075 :group 'org-keywords
4076 :type 'string)
4078 (defcustom org-agenda-skip-archived-trees t
4079 "Non-nil means the agenda will skip any items located in archived trees.
4080 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4081 variable is no longer recommended, you should leave it at the value t.
4082 Instead, use the key `v' to cycle the archives-mode in the agenda."
4083 :group 'org-archive
4084 :group 'org-agenda-skip
4085 :type 'boolean)
4087 (defcustom org-columns-skip-archived-trees t
4088 "Non-nil means ignore archived trees when creating column view."
4089 :group 'org-archive
4090 :group 'org-properties
4091 :type 'boolean)
4093 (defcustom org-cycle-open-archived-trees nil
4094 "Non-nil means `org-cycle' will open archived trees.
4095 An archived tree is a tree marked with the tag ARCHIVE.
4096 When nil, archived trees will stay folded. You can still open them with
4097 normal outline commands like `show-all', but not with the cycling commands."
4098 :group 'org-archive
4099 :group 'org-cycle
4100 :type 'boolean)
4102 (defcustom org-sparse-tree-open-archived-trees nil
4103 "Non-nil means sparse tree construction shows matches in archived trees.
4104 When nil, matches in these trees are highlighted, but the trees are kept in
4105 collapsed state."
4106 :group 'org-archive
4107 :group 'org-sparse-trees
4108 :type 'boolean)
4110 (defun org-cycle-hide-archived-subtrees (state)
4111 "Re-hide all archived subtrees after a visibility state change."
4112 (when (and (not org-cycle-open-archived-trees)
4113 (not (memq state '(overview folded))))
4114 (save-excursion
4115 (let* ((globalp (memq state '(contents all)))
4116 (beg (if globalp (point-min) (point)))
4117 (end (if globalp (point-max) (org-end-of-subtree t))))
4118 (org-hide-archived-subtrees beg end)
4119 (goto-char beg)
4120 (if (looking-at (concat ".*:" org-archive-tag ":"))
4121 (message "%s" (substitute-command-keys
4122 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4124 (defun org-force-cycle-archived ()
4125 "Cycle subtree even if it is archived."
4126 (interactive)
4127 (setq this-command 'org-cycle)
4128 (let ((org-cycle-open-archived-trees t))
4129 (call-interactively 'org-cycle)))
4131 (defun org-hide-archived-subtrees (beg end)
4132 "Re-hide all archived subtrees after a visibility state change."
4133 (save-excursion
4134 (let* ((re (concat ":" org-archive-tag ":")))
4135 (goto-char beg)
4136 (while (re-search-forward re end t)
4137 (when (org-on-heading-p)
4138 (org-flag-subtree t)
4139 (org-end-of-subtree t))))))
4141 (defun org-flag-subtree (flag)
4142 (save-excursion
4143 (org-back-to-heading t)
4144 (outline-end-of-heading)
4145 (outline-flag-region (point)
4146 (progn (org-end-of-subtree t) (point))
4147 flag)))
4149 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4151 (eval-and-compile
4152 (org-autoload "org-archive"
4153 '(org-add-archive-files org-archive-subtree
4154 org-archive-to-archive-sibling org-toggle-archive-tag
4155 org-archive-subtree-default
4156 org-archive-subtree-default-with-confirmation)))
4158 ;; Autoload Column View Code
4160 (declare-function org-columns-number-to-string "org-colview")
4161 (declare-function org-columns-get-format-and-top-level "org-colview")
4162 (declare-function org-columns-compute "org-colview")
4164 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4165 '(org-columns-number-to-string org-columns-get-format-and-top-level
4166 org-columns-compute org-agenda-columns org-columns-remove-overlays
4167 org-columns org-insert-columns-dblock org-dblock-write:columnview))
4169 ;; Autoload ID code
4171 (declare-function org-id-store-link "org-id")
4172 (declare-function org-id-locations-load "org-id")
4173 (declare-function org-id-locations-save "org-id")
4174 (defvar org-id-track-globally)
4175 (org-autoload "org-id"
4176 '(org-id-get-create org-id-new org-id-copy org-id-get
4177 org-id-get-with-outline-path-completion
4178 org-id-get-with-outline-drilling org-id-store-link
4179 org-id-goto org-id-find org-id-store-link))
4181 ;; Autoload Plotting Code
4183 (org-autoload "org-plot"
4184 '(org-plot/gnuplot))
4186 ;;; Variables for pre-computed regular expressions, all buffer local
4188 (defvar org-drawer-regexp nil
4189 "Matches first line of a hidden block.")
4190 (make-variable-buffer-local 'org-drawer-regexp)
4191 (defvar org-todo-regexp nil
4192 "Matches any of the TODO state keywords.")
4193 (make-variable-buffer-local 'org-todo-regexp)
4194 (defvar org-not-done-regexp nil
4195 "Matches any of the TODO state keywords except the last one.")
4196 (make-variable-buffer-local 'org-not-done-regexp)
4197 (defvar org-not-done-heading-regexp nil
4198 "Matches a TODO headline that is not done.")
4199 (make-variable-buffer-local 'org-not-done-regexp)
4200 (defvar org-todo-line-regexp nil
4201 "Matches a headline and puts TODO state into group 2 if present.")
4202 (make-variable-buffer-local 'org-todo-line-regexp)
4203 (defvar org-complex-heading-regexp nil
4204 "Matches a headline and puts everything into groups:
4205 group 1: the stars
4206 group 2: The todo keyword, maybe
4207 group 3: Priority cookie
4208 group 4: True headline
4209 group 5: Tags")
4210 (make-variable-buffer-local 'org-complex-heading-regexp)
4211 (defvar org-complex-heading-regexp-format nil
4212 "Printf format to make regexp to match an exact headline.
4213 This regexp will match the headline of any node which hase the exact
4214 headline text that is put into the format, but may have any TODO state,
4215 priority and tags.")
4216 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4217 (defvar org-todo-line-tags-regexp nil
4218 "Matches a headline and puts TODO state into group 2 if present.
4219 Also put tags into group 4 if tags are present.")
4220 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4221 (defvar org-nl-done-regexp nil
4222 "Matches newline followed by a headline with the DONE keyword.")
4223 (make-variable-buffer-local 'org-nl-done-regexp)
4224 (defvar org-looking-at-done-regexp nil
4225 "Matches the DONE keyword a point.")
4226 (make-variable-buffer-local 'org-looking-at-done-regexp)
4227 (defvar org-ds-keyword-length 12
4228 "Maximum length of the Deadline and SCHEDULED keywords.")
4229 (make-variable-buffer-local 'org-ds-keyword-length)
4230 (defvar org-deadline-regexp nil
4231 "Matches the DEADLINE keyword.")
4232 (make-variable-buffer-local 'org-deadline-regexp)
4233 (defvar org-deadline-time-regexp nil
4234 "Matches the DEADLINE keyword together with a time stamp.")
4235 (make-variable-buffer-local 'org-deadline-time-regexp)
4236 (defvar org-deadline-line-regexp nil
4237 "Matches the DEADLINE keyword and the rest of the line.")
4238 (make-variable-buffer-local 'org-deadline-line-regexp)
4239 (defvar org-scheduled-regexp nil
4240 "Matches the SCHEDULED keyword.")
4241 (make-variable-buffer-local 'org-scheduled-regexp)
4242 (defvar org-scheduled-time-regexp nil
4243 "Matches the SCHEDULED keyword together with a time stamp.")
4244 (make-variable-buffer-local 'org-scheduled-time-regexp)
4245 (defvar org-closed-time-regexp nil
4246 "Matches the CLOSED keyword together with a time stamp.")
4247 (make-variable-buffer-local 'org-closed-time-regexp)
4249 (defvar org-keyword-time-regexp nil
4250 "Matches any of the 4 keywords, together with the time stamp.")
4251 (make-variable-buffer-local 'org-keyword-time-regexp)
4252 (defvar org-keyword-time-not-clock-regexp nil
4253 "Matches any of the 3 keywords, together with the time stamp.")
4254 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4255 (defvar org-maybe-keyword-time-regexp nil
4256 "Matches a timestamp, possibly preceded by a keyword.")
4257 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4258 (defvar org-planning-or-clock-line-re nil
4259 "Matches a line with planning or clock info.")
4260 (make-variable-buffer-local 'org-planning-or-clock-line-re)
4261 (defvar org-all-time-keywords nil
4262 "List of time keywords.")
4263 (make-variable-buffer-local 'org-all-time-keywords)
4265 (defconst org-plain-time-of-day-regexp
4266 (concat
4267 "\\(\\<[012]?[0-9]"
4268 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4269 "\\(--?"
4270 "\\(\\<[012]?[0-9]"
4271 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4272 "\\)?")
4273 "Regular expression to match a plain time or time range.
4274 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4275 groups carry important information:
4276 0 the full match
4277 1 the first time, range or not
4278 8 the second time, if it is a range.")
4280 (defconst org-plain-time-extension-regexp
4281 (concat
4282 "\\(\\<[012]?[0-9]"
4283 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4284 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4285 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4286 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4287 groups carry important information:
4288 0 the full match
4289 7 hours of duration
4290 9 minutes of duration")
4292 (defconst org-stamp-time-of-day-regexp
4293 (concat
4294 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4295 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4296 "\\(--?"
4297 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4298 "Regular expression to match a timestamp time or time range.
4299 After a match, the following groups carry important information:
4300 0 the full match
4301 1 date plus weekday, for back referencing to make sure both times are on the same day
4302 2 the first time, range or not
4303 4 the second time, if it is a range.")
4305 (defconst org-startup-options
4306 '(("fold" org-startup-folded t)
4307 ("overview" org-startup-folded t)
4308 ("nofold" org-startup-folded nil)
4309 ("showall" org-startup-folded nil)
4310 ("showeverything" org-startup-folded showeverything)
4311 ("content" org-startup-folded content)
4312 ("indent" org-startup-indented t)
4313 ("noindent" org-startup-indented nil)
4314 ("hidestars" org-hide-leading-stars t)
4315 ("showstars" org-hide-leading-stars nil)
4316 ("odd" org-odd-levels-only t)
4317 ("oddeven" org-odd-levels-only nil)
4318 ("align" org-startup-align-all-tables t)
4319 ("noalign" org-startup-align-all-tables nil)
4320 ("inlineimages" org-startup-with-inline-images t)
4321 ("noinlineimages" org-startup-with-inline-images nil)
4322 ("customtime" org-display-custom-times t)
4323 ("logdone" org-log-done time)
4324 ("lognotedone" org-log-done note)
4325 ("nologdone" org-log-done nil)
4326 ("lognoteclock-out" org-log-note-clock-out t)
4327 ("nolognoteclock-out" org-log-note-clock-out nil)
4328 ("logrepeat" org-log-repeat state)
4329 ("lognoterepeat" org-log-repeat note)
4330 ("nologrepeat" org-log-repeat nil)
4331 ("logreschedule" org-log-reschedule time)
4332 ("lognotereschedule" org-log-reschedule note)
4333 ("nologreschedule" org-log-reschedule nil)
4334 ("logredeadline" org-log-redeadline time)
4335 ("lognoteredeadline" org-log-redeadline note)
4336 ("nologredeadline" org-log-redeadline nil)
4337 ("logrefile" org-log-refile time)
4338 ("lognoterefile" org-log-refile note)
4339 ("nologrefile" org-log-refile nil)
4340 ("fninline" org-footnote-define-inline t)
4341 ("nofninline" org-footnote-define-inline nil)
4342 ("fnlocal" org-footnote-section nil)
4343 ("fnauto" org-footnote-auto-label t)
4344 ("fnprompt" org-footnote-auto-label nil)
4345 ("fnconfirm" org-footnote-auto-label confirm)
4346 ("fnplain" org-footnote-auto-label plain)
4347 ("fnadjust" org-footnote-auto-adjust t)
4348 ("nofnadjust" org-footnote-auto-adjust nil)
4349 ("constcgs" constants-unit-system cgs)
4350 ("constSI" constants-unit-system SI)
4351 ("noptag" org-tag-persistent-alist nil)
4352 ("hideblocks" org-hide-block-startup t)
4353 ("nohideblocks" org-hide-block-startup nil)
4354 ("beamer" org-startup-with-beamer-mode t)
4355 ("entitiespretty" org-pretty-entities t)
4356 ("entitiesplain" org-pretty-entities nil))
4357 "Variable associated with STARTUP options for org-mode.
4358 Each element is a list of three items: The startup options as written
4359 in the #+STARTUP line, the corresponding variable, and the value to
4360 set this variable to if the option is found. An optional forth element PUSH
4361 means to push this value onto the list in the variable.")
4363 (defun org-set-regexps-and-options ()
4364 "Precompute regular expressions for current buffer."
4365 (when (org-mode-p)
4366 (org-set-local 'org-todo-kwd-alist nil)
4367 (org-set-local 'org-todo-key-alist nil)
4368 (org-set-local 'org-todo-key-trigger nil)
4369 (org-set-local 'org-todo-keywords-1 nil)
4370 (org-set-local 'org-done-keywords nil)
4371 (org-set-local 'org-todo-heads nil)
4372 (org-set-local 'org-todo-sets nil)
4373 (org-set-local 'org-todo-log-states nil)
4374 (org-set-local 'org-file-properties nil)
4375 (org-set-local 'org-file-tags nil)
4376 (let ((re (org-make-options-regexp
4377 '("CATEGORY" "TODO" "COLUMNS"
4378 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
4379 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE" "LATEX_CLASS"
4380 "OPTIONS")
4381 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4382 (splitre "[ \t]+")
4383 (scripts org-use-sub-superscripts)
4384 kwds kws0 kwsa key log value cat arch tags const links hw dws
4385 tail sep kws1 prio props ftags drawers beamer-p
4386 ext-setup-or-nil setup-contents (start 0))
4387 (save-excursion
4388 (save-restriction
4389 (widen)
4390 (goto-char (point-min))
4391 (while (or (and ext-setup-or-nil
4392 (string-match re ext-setup-or-nil start)
4393 (setq start (match-end 0)))
4394 (and (setq ext-setup-or-nil nil start 0)
4395 (re-search-forward re nil t)))
4396 (setq key (upcase (match-string 1 ext-setup-or-nil))
4397 value (org-match-string-no-properties 2 ext-setup-or-nil))
4398 (if (stringp value) (setq value (org-trim value)))
4399 (cond
4400 ((equal key "CATEGORY")
4401 (setq cat value))
4402 ((member key '("SEQ_TODO" "TODO"))
4403 (push (cons 'sequence (org-split-string value splitre)) kwds))
4404 ((equal key "TYP_TODO")
4405 (push (cons 'type (org-split-string value splitre)) kwds))
4406 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4407 ;; general TODO-like setup
4408 (push (cons (intern (downcase (match-string 1 key)))
4409 (org-split-string value splitre)) kwds))
4410 ((equal key "TAGS")
4411 (setq tags (append tags (if tags '("\\n") nil)
4412 (org-split-string value splitre))))
4413 ((equal key "COLUMNS")
4414 (org-set-local 'org-columns-default-format value))
4415 ((equal key "LINK")
4416 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4417 (push (cons (match-string 1 value)
4418 (org-trim (match-string 2 value)))
4419 links)))
4420 ((equal key "PRIORITIES")
4421 (setq prio (org-split-string value " +")))
4422 ((equal key "PROPERTY")
4423 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4424 (push (cons (match-string 1 value) (match-string 2 value))
4425 props)))
4426 ((equal key "FILETAGS")
4427 (when (string-match "\\S-" value)
4428 (setq ftags
4429 (append
4430 ftags
4431 (apply 'append
4432 (mapcar (lambda (x) (org-split-string x ":"))
4433 (org-split-string value)))))))
4434 ((equal key "DRAWERS")
4435 (setq drawers (org-split-string value splitre)))
4436 ((equal key "CONSTANTS")
4437 (setq const (append const (org-split-string value splitre))))
4438 ((equal key "STARTUP")
4439 (let ((opts (org-split-string value splitre))
4440 l var val)
4441 (while (setq l (pop opts))
4442 (when (setq l (assoc l org-startup-options))
4443 (setq var (nth 1 l) val (nth 2 l))
4444 (if (not (nth 3 l))
4445 (set (make-local-variable var) val)
4446 (if (not (listp (symbol-value var)))
4447 (set (make-local-variable var) nil))
4448 (set (make-local-variable var) (symbol-value var))
4449 (add-to-list var val))))))
4450 ((equal key "ARCHIVE")
4451 (setq arch value)
4452 (remove-text-properties 0 (length arch)
4453 '(face t fontified t) arch))
4454 ((equal key "LATEX_CLASS")
4455 (setq beamer-p (equal value "beamer")))
4456 ((equal key "OPTIONS")
4457 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4458 (setq scripts (read (match-string 2 value)))))
4459 ((equal key "SETUPFILE")
4460 (setq setup-contents (org-file-contents
4461 (expand-file-name
4462 (org-remove-double-quotes value))
4463 'noerror))
4464 (if (not ext-setup-or-nil)
4465 (setq ext-setup-or-nil setup-contents start 0)
4466 (setq ext-setup-or-nil
4467 (concat (substring ext-setup-or-nil 0 start)
4468 "\n" setup-contents "\n"
4469 (substring ext-setup-or-nil start)))))
4470 ))))
4471 (org-set-local 'org-use-sub-superscripts scripts)
4472 (when cat
4473 (org-set-local 'org-category (intern cat))
4474 (push (cons "CATEGORY" cat) props))
4475 (when prio
4476 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4477 (setq prio (mapcar 'string-to-char prio))
4478 (org-set-local 'org-highest-priority (nth 0 prio))
4479 (org-set-local 'org-lowest-priority (nth 1 prio))
4480 (org-set-local 'org-default-priority (nth 2 prio)))
4481 (and props (org-set-local 'org-file-properties (nreverse props)))
4482 (and ftags (org-set-local 'org-file-tags
4483 (mapcar 'org-add-prop-inherited ftags)))
4484 (and drawers (org-set-local 'org-drawers drawers))
4485 (and arch (org-set-local 'org-archive-location arch))
4486 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4487 ;; Process the TODO keywords
4488 (unless kwds
4489 ;; Use the global values as if they had been given locally.
4490 (setq kwds (default-value 'org-todo-keywords))
4491 (if (stringp (car kwds))
4492 (setq kwds (list (cons org-todo-interpretation
4493 (default-value 'org-todo-keywords)))))
4494 (setq kwds (reverse kwds)))
4495 (setq kwds (nreverse kwds))
4496 (let (inter kws kw)
4497 (while (setq kws (pop kwds))
4498 (let ((kws (or
4499 (run-hook-with-args-until-success
4500 'org-todo-setup-filter-hook kws)
4501 kws)))
4502 (setq inter (pop kws) sep (member "|" kws)
4503 kws0 (delete "|" (copy-sequence kws))
4504 kwsa nil
4505 kws1 (mapcar
4506 (lambda (x)
4507 ;; 1 2
4508 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4509 (progn
4510 (setq kw (match-string 1 x)
4511 key (and (match-end 2) (match-string 2 x))
4512 log (org-extract-log-state-settings x))
4513 (push (cons kw (and key (string-to-char key))) kwsa)
4514 (and log (push log org-todo-log-states))
4516 (error "Invalid TODO keyword %s" x)))
4517 kws0)
4518 kwsa (if kwsa (append '((:startgroup))
4519 (nreverse kwsa)
4520 '((:endgroup))))
4521 hw (car kws1)
4522 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4523 tail (list inter hw (car dws) (org-last dws))))
4524 (add-to-list 'org-todo-heads hw 'append)
4525 (push kws1 org-todo-sets)
4526 (setq org-done-keywords (append org-done-keywords dws nil))
4527 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4528 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4529 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4530 (setq org-todo-sets (nreverse org-todo-sets)
4531 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4532 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4533 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4534 ;; Process the constants
4535 (when const
4536 (let (e cst)
4537 (while (setq e (pop const))
4538 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4539 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4540 (setq org-table-formula-constants-local cst)))
4542 ;; Process the tags.
4543 (when tags
4544 (let (e tgs)
4545 (while (setq e (pop tags))
4546 (cond
4547 ((equal e "{") (push '(:startgroup) tgs))
4548 ((equal e "}") (push '(:endgroup) tgs))
4549 ((equal e "\\n") (push '(:newline) tgs))
4550 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4551 (push (cons (match-string 1 e)
4552 (string-to-char (match-string 2 e)))
4553 tgs))
4554 (t (push (list e) tgs))))
4555 (org-set-local 'org-tag-alist nil)
4556 (while (setq e (pop tgs))
4557 (or (and (stringp (car e))
4558 (assoc (car e) org-tag-alist))
4559 (push e org-tag-alist)))))
4561 ;; Compute the regular expressions and other local variables
4562 (if (not org-done-keywords)
4563 (setq org-done-keywords (and org-todo-keywords-1
4564 (list (org-last org-todo-keywords-1)))))
4565 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4566 (length org-scheduled-string)
4567 (length org-clock-string)
4568 (length org-closed-string)))
4569 org-drawer-regexp
4570 (concat "^[ \t]*:\\("
4571 (mapconcat 'regexp-quote org-drawers "\\|")
4572 "\\):[ \t]*$")
4573 org-not-done-keywords
4574 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4575 org-todo-regexp
4576 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
4577 "\\|") "\\)\\>")
4578 org-not-done-regexp
4579 (concat "\\<\\("
4580 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4581 "\\)\\>")
4582 org-not-done-heading-regexp
4583 (concat "^\\(\\*+\\)[ \t]+\\("
4584 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4585 "\\)[ \t]+")
4586 org-todo-line-regexp
4587 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4588 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4589 "\\)[ \t]+\\)?\\(.*\\)")
4590 org-complex-heading-regexp
4591 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4592 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4593 "\\)[ \t]+\\)?"
4594 "\\(?:\\(\\[#.\\]\\)[ \t]+\\)?"
4595 "\\(.*?\\)"
4596 "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
4597 org-complex-heading-regexp-format
4598 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4599 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4600 "\\)[ \t]+\\)?"
4601 "\\(?:\\(\\[#.\\]\\)[ \t]+\\)?"
4602 "\\(?:\\(?:\\[[0-9%%/]+\\]\\)[ \t]+\\)?" ; stats cookie
4603 "\\(%s\\)[ \t]*"
4604 "\\(?:\\[[0-9%%/]+\\]\\)?" ; stats cookie
4605 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?[ \t]*$"))
4606 org-nl-done-regexp
4607 (concat "\n\\*+[ \t]+"
4608 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
4609 "\\)" "[ \t]+")
4610 org-todo-line-tags-regexp
4611 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4612 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4613 "\\)[ \t]+\\)"
4614 (org-re "\\(.*?\\([ \t]:[[:alnum:]:_@#%]+:[ \t]*\\)?$\\)"))
4615 org-looking-at-done-regexp
4616 (concat "^" "\\(?:"
4617 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
4618 "[ \t]+")
4619 org-deadline-regexp (concat "\\<" org-deadline-string)
4620 org-deadline-time-regexp
4621 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4622 org-deadline-line-regexp
4623 (concat "\\<\\(" org-deadline-string "\\).*")
4624 org-scheduled-regexp
4625 (concat "\\<" org-scheduled-string)
4626 org-scheduled-time-regexp
4627 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4628 org-closed-time-regexp
4629 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4630 org-keyword-time-regexp
4631 (concat "\\<\\(" org-scheduled-string
4632 "\\|" org-deadline-string
4633 "\\|" org-closed-string
4634 "\\|" org-clock-string "\\)"
4635 " *[[<]\\([^]>]+\\)[]>]")
4636 org-keyword-time-not-clock-regexp
4637 (concat "\\<\\(" org-scheduled-string
4638 "\\|" org-deadline-string
4639 "\\|" org-closed-string
4640 "\\)"
4641 " *[[<]\\([^]>]+\\)[]>]")
4642 org-maybe-keyword-time-regexp
4643 (concat "\\(\\<\\(" org-scheduled-string
4644 "\\|" org-deadline-string
4645 "\\|" org-closed-string
4646 "\\|" org-clock-string "\\)\\)?"
4647 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4648 org-planning-or-clock-line-re
4649 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
4650 "\\|" org-deadline-string
4651 "\\|" org-closed-string "\\|" org-clock-string
4652 "\\)\\>\\)")
4653 org-all-time-keywords
4654 (mapcar (lambda (w) (substring w 0 -1))
4655 (list org-scheduled-string org-deadline-string
4656 org-clock-string org-closed-string))
4658 (org-compute-latex-and-specials-regexp)
4659 (org-set-font-lock-defaults))))
4661 (defun org-file-contents (file &optional noerror)
4662 "Return the contents of FILE, as a string."
4663 (if (or (not file)
4664 (not (file-readable-p file)))
4665 (if noerror
4666 (progn
4667 (message "Cannot read file \"%s\"" file)
4668 (ding) (sit-for 2)
4670 (error "Cannot read file \"%s\"" file))
4671 (with-temp-buffer
4672 (insert-file-contents file)
4673 (buffer-string))))
4675 (defun org-extract-log-state-settings (x)
4676 "Extract the log state setting from a TODO keyword string.
4677 This will extract info from a string like \"WAIT(w@/!)\"."
4678 (let (kw key log1 log2)
4679 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4680 (setq kw (match-string 1 x)
4681 key (and (match-end 2) (match-string 2 x))
4682 log1 (and (match-end 3) (match-string 3 x))
4683 log2 (and (match-end 4) (match-string 4 x)))
4684 (and (or log1 log2)
4685 (list kw
4686 (and log1 (if (equal log1 "!") 'time 'note))
4687 (and log2 (if (equal log2 "!") 'time 'note)))))))
4689 (defun org-remove-keyword-keys (list)
4690 "Remove a pair of parenthesis at the end of each string in LIST."
4691 (mapcar (lambda (x)
4692 (if (string-match "(.*)$" x)
4693 (substring x 0 (match-beginning 0))
4695 list))
4697 (defun org-assign-fast-keys (alist)
4698 "Assign fast keys to a keyword-key alist.
4699 Respect keys that are already there."
4700 (let (new e (alt ?0))
4701 (while (setq e (pop alist))
4702 (if (or (memq (car e) '(:newline :endgroup :startgroup))
4703 (cdr e)) ;; Key already assigned.
4704 (push e new)
4705 (let ((clist (string-to-list (downcase (car e))))
4706 (used (append new alist)))
4707 (when (= (car clist) ?@)
4708 (pop clist))
4709 (while (and clist (rassoc (car clist) used))
4710 (pop clist))
4711 (unless clist
4712 (while (rassoc alt used)
4713 (incf alt)))
4714 (push (cons (car e) (or (car clist) alt)) new))))
4715 (nreverse new)))
4717 ;;; Some variables used in various places
4719 (defvar org-window-configuration nil
4720 "Used in various places to store a window configuration.")
4721 (defvar org-selected-window nil
4722 "Used in various places to store a window configuration.")
4723 (defvar org-finish-function nil
4724 "Function to be called when `C-c C-c' is used.
4725 This is for getting out of special buffers like remember.")
4728 ;; FIXME: Occasionally check by commenting these, to make sure
4729 ;; no other functions uses these, forgetting to let-bind them.
4730 (defvar entry)
4731 (defvar last-state)
4732 (defvar date)
4734 ;; Defined somewhere in this file, but used before definition.
4735 (defvar org-entities) ;; defined in org-entities.el
4736 (defvar org-struct-menu)
4737 (defvar org-org-menu)
4738 (defvar org-tbl-menu)
4740 ;;;; Define the Org-mode
4742 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4743 (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"))
4746 ;; We use a before-change function to check if a table might need
4747 ;; an update.
4748 (defvar org-table-may-need-update t
4749 "Indicates that a table might need an update.
4750 This variable is set by `org-before-change-function'.
4751 `org-table-align' sets it back to nil.")
4752 (defun org-before-change-function (beg end)
4753 "Every change indicates that a table might need an update."
4754 (setq org-table-may-need-update t))
4755 (defvar org-mode-map)
4756 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4757 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
4758 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4759 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
4760 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
4761 (defvar org-table-buffer-is-an nil)
4763 ;; `org-outline-regexp' ought to be a defconst but is let-binding in
4764 ;; some places -- e.g. see the macro org-with-limited-levels.
4766 ;; In Org buffers, the value of `outline-regexp' is that of
4767 ;; `org-outline-regexp'. The only function still directly relying on
4768 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
4769 ;; job when `orgstruct-mode' is active.
4770 (defvar org-outline-regexp "\\*+ "
4771 "Regexp to match Org headlines.")
4772 (defconst org-outline-regexp-bol "^\\*+ "
4773 "Regexp to match Org headlines.
4774 This is similar to `org-outline-regexp' but additionally makes
4775 sure that we are at the beginning of the line.")
4777 ;;;###autoload
4778 (define-derived-mode org-mode outline-mode "Org"
4779 "Outline-based notes management and organizer, alias
4780 \"Carsten's outline-mode for keeping track of everything.\"
4782 Org-mode develops organizational tasks around a NOTES file which
4783 contains information about projects as plain text. Org-mode is
4784 implemented on top of outline-mode, which is ideal to keep the content
4785 of large files well structured. It supports ToDo items, deadlines and
4786 time stamps, which magically appear in the diary listing of the Emacs
4787 calendar. Tables are easily created with a built-in table editor.
4788 Plain text URL-like links connect to websites, emails (VM), Usenet
4789 messages (Gnus), BBDB entries, and any files related to the project.
4790 For printing and sharing of notes, an Org-mode file (or a part of it)
4791 can be exported as a structured ASCII or HTML file.
4793 The following commands are available:
4795 \\{org-mode-map}"
4797 ;; Get rid of Outline menus, they are not needed
4798 ;; Need to do this here because define-derived-mode sets up
4799 ;; the keymap so late. Still, it is a waste to call this each time
4800 ;; we switch another buffer into org-mode.
4801 (if (featurep 'xemacs)
4802 (when (boundp 'outline-mode-menu-heading)
4803 ;; Assume this is Greg's port, it uses easymenu
4804 (easy-menu-remove outline-mode-menu-heading)
4805 (easy-menu-remove outline-mode-menu-show)
4806 (easy-menu-remove outline-mode-menu-hide))
4807 (define-key org-mode-map [menu-bar headings] 'undefined)
4808 (define-key org-mode-map [menu-bar hide] 'undefined)
4809 (define-key org-mode-map [menu-bar show] 'undefined))
4811 (org-load-modules-maybe)
4812 (easy-menu-add org-org-menu)
4813 (easy-menu-add org-tbl-menu)
4814 (org-install-agenda-files-menu)
4815 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
4816 (add-to-invisibility-spec '(org-cwidth))
4817 (add-to-invisibility-spec '(org-hide-block . t))
4818 (when (featurep 'xemacs)
4819 (org-set-local 'line-move-ignore-invisible t))
4820 (org-set-local 'outline-regexp org-outline-regexp)
4821 (org-set-local 'outline-level 'org-outline-level)
4822 (when (and org-ellipsis
4823 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
4824 (fboundp 'make-glyph-code))
4825 (unless org-display-table
4826 (setq org-display-table (make-display-table)))
4827 (set-display-table-slot
4828 org-display-table 4
4829 (vconcat (mapcar
4830 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
4831 org-ellipsis)))
4832 (if (stringp org-ellipsis) org-ellipsis "..."))))
4833 (setq buffer-display-table org-display-table))
4834 (org-set-regexps-and-options)
4835 (when (and org-tag-faces (not org-tags-special-faces-re))
4836 ;; tag faces set outside customize.... force initialization.
4837 (org-set-tag-faces 'org-tag-faces org-tag-faces))
4838 ;; Calc embedded
4839 (org-set-local 'calc-embedded-open-mode "# ")
4840 (modify-syntax-entry ?@ "w")
4841 (if org-startup-truncated (setq truncate-lines t))
4842 (org-set-local 'font-lock-unfontify-region-function
4843 'org-unfontify-region)
4844 ;; Activate before-change-function
4845 (org-set-local 'org-table-may-need-update t)
4846 (org-add-hook 'before-change-functions 'org-before-change-function nil
4847 'local)
4848 ;; Check for running clock before killing a buffer
4849 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
4850 ;; Paragraphs and auto-filling
4851 (org-set-autofill-regexps)
4852 (setq indent-line-function 'org-indent-line-function)
4853 (org-update-radio-target-regexp)
4854 ;; Beginning/end of defun
4855 (org-set-local 'beginning-of-defun-function 'org-beginning-of-defun)
4856 (org-set-local 'end-of-defun-function 'org-end-of-defun)
4857 ;; Next error for sparse trees
4858 (org-set-local 'next-error-function 'org-occur-next-match)
4859 ;; Make sure dependence stuff works reliably, even for users who set it
4860 ;; too late :-(
4861 (if org-enforce-todo-dependencies
4862 (add-hook 'org-blocker-hook
4863 'org-block-todo-from-children-or-siblings-or-parent)
4864 (remove-hook 'org-blocker-hook
4865 'org-block-todo-from-children-or-siblings-or-parent))
4866 (if org-enforce-todo-checkbox-dependencies
4867 (add-hook 'org-blocker-hook
4868 'org-block-todo-from-checkboxes)
4869 (remove-hook 'org-blocker-hook
4870 'org-block-todo-from-checkboxes))
4872 ;; Comment characters
4873 (org-set-local 'comment-start "#")
4874 (org-set-local 'comment-padding " ")
4876 ;; Align options lines
4877 (org-set-local
4878 'align-mode-rules-list
4879 '((org-in-buffer-settings
4880 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
4881 (modes . '(org-mode)))))
4883 ;; Imenu
4884 (org-set-local 'imenu-create-index-function
4885 'org-imenu-get-tree)
4887 ;; Make isearch reveal context
4888 (if (or (featurep 'xemacs)
4889 (not (boundp 'outline-isearch-open-invisible-function)))
4890 ;; Emacs 21 and XEmacs make use of the hook
4891 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
4892 ;; Emacs 22 deals with this through a special variable
4893 (org-set-local 'outline-isearch-open-invisible-function
4894 (lambda (&rest ignore) (org-show-context 'isearch))))
4896 ;; Turn on org-beamer-mode?
4897 (and org-startup-with-beamer-mode (org-beamer-mode 1))
4899 ;; Setup the pcomplete hooks
4900 (set (make-local-variable 'pcomplete-command-completion-function)
4901 'org-pcomplete-initial)
4902 (set (make-local-variable 'pcomplete-command-name-function)
4903 'org-command-at-point)
4904 (set (make-local-variable 'pcomplete-default-completion-function)
4905 'ignore)
4906 (set (make-local-variable 'pcomplete-parse-arguments-function)
4907 'org-parse-arguments)
4908 (set (make-local-variable 'pcomplete-termination-string) "")
4909 (set (make-local-variable 'face-remapping-alist)
4910 '((default org-default)))
4912 ;; If empty file that did not turn on org-mode automatically, make it to.
4913 (if (and org-insert-mode-line-in-empty-file
4914 (org-called-interactively-p 'any)
4915 (= (point-min) (point-max)))
4916 (insert "# -*- mode: org -*-\n\n"))
4917 (unless org-inhibit-startup
4918 (when org-startup-align-all-tables
4919 (let ((bmp (buffer-modified-p)))
4920 (org-table-map-tables 'org-table-align 'quietly)
4921 (set-buffer-modified-p bmp)))
4922 (when org-startup-with-inline-images
4923 (org-display-inline-images))
4924 (when org-startup-indented
4925 (require 'org-indent)
4926 (org-indent-mode 1))
4927 (unless org-inhibit-startup-visibility-stuff
4928 (org-set-startup-visibility))))
4930 (when (fboundp 'abbrev-table-put)
4931 (abbrev-table-put org-mode-abbrev-table
4932 :parents (list text-mode-abbrev-table)))
4934 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
4936 (defun org-current-time ()
4937 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
4938 (if (> (car org-time-stamp-rounding-minutes) 1)
4939 (let ((r (car org-time-stamp-rounding-minutes))
4940 (time (decode-time)))
4941 (apply 'encode-time
4942 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
4943 (nthcdr 2 time))))
4944 (current-time)))
4946 (defun org-today ()
4947 "Return today date, considering `org-extend-today-until'."
4948 (time-to-days
4949 (time-subtract (current-time)
4950 (list 0 (* 3600 org-extend-today-until) 0))))
4952 ;;;; Font-Lock stuff, including the activators
4954 (defvar org-mouse-map (make-sparse-keymap))
4955 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
4956 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
4957 (when org-mouse-1-follows-link
4958 (org-defkey org-mouse-map [follow-link] 'mouse-face))
4959 (when org-tab-follows-link
4960 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
4961 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
4963 (require 'font-lock)
4965 (defconst org-non-link-chars "]\t\n\r<>")
4966 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
4967 "shell" "elisp" "doi" "message"))
4968 (defvar org-link-types-re nil
4969 "Matches a link that has a url-like prefix like \"http:\"")
4970 (defvar org-link-re-with-space nil
4971 "Matches a link with spaces, optional angular brackets around it.")
4972 (defvar org-link-re-with-space2 nil
4973 "Matches a link with spaces, optional angular brackets around it.")
4974 (defvar org-link-re-with-space3 nil
4975 "Matches a link with spaces, only for internal part in bracket links.")
4976 (defvar org-angle-link-re nil
4977 "Matches link with angular brackets, spaces are allowed.")
4978 (defvar org-plain-link-re nil
4979 "Matches plain link, without spaces.")
4980 (defvar org-bracket-link-regexp nil
4981 "Matches a link in double brackets.")
4982 (defvar org-bracket-link-analytic-regexp nil
4983 "Regular expression used to analyze links.
4984 Here is what the match groups contain after a match:
4985 1: http:
4986 2: http
4987 3: path
4988 4: [desc]
4989 5: desc")
4990 (defvar org-bracket-link-analytic-regexp++ nil
4991 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
4992 (defvar org-any-link-re nil
4993 "Regular expression matching any link.")
4995 (defcustom org-match-sexp-depth 3
4996 "Number of stacked braces for sub/superscript matching.
4997 This has to be set before loading org.el to be effective."
4998 :group 'org-export-translation ; ??????????????????????????/
4999 :type 'integer)
5001 (defun org-create-multibrace-regexp (left right n)
5002 "Create a regular expression which will match a balanced sexp.
5003 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5004 as single character strings.
5005 The regexp returned will match the entire expression including the
5006 delimiters. It will also define a single group which contains the
5007 match except for the outermost delimiters. The maximum depth of
5008 stacked delimiters is N. Escaping delimiters is not possible."
5009 (let* ((nothing (concat "[^" left right "]*?"))
5010 (or "\\|")
5011 (re nothing)
5012 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5013 (while (> n 1)
5014 (setq n (1- n)
5015 re (concat re or next)
5016 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5017 (concat left "\\(" re "\\)" right)))
5019 (defvar org-match-substring-regexp
5020 (concat
5021 "\\([^\\]\\)\\([_^]\\)\\("
5022 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5023 "\\|"
5024 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5025 "\\|"
5026 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5027 "The regular expression matching a sub- or superscript.")
5029 (defvar org-match-substring-with-braces-regexp
5030 (concat
5031 "\\([^\\]\\)\\([_^]\\)\\("
5032 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5033 "\\)")
5034 "The regular expression matching a sub- or superscript, forcing braces.")
5036 (defun org-make-link-regexps ()
5037 "Update the link regular expressions.
5038 This should be called after the variable `org-link-types' has changed."
5039 (setq org-link-types-re
5040 (concat
5041 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5042 org-link-re-with-space
5043 (concat
5044 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5045 "\\([^" org-non-link-chars " ]"
5046 "[^" org-non-link-chars "]*"
5047 "[^" org-non-link-chars " ]\\)>?")
5048 org-link-re-with-space2
5049 (concat
5050 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5051 "\\([^" org-non-link-chars " ]"
5052 "[^\t\n\r]*"
5053 "[^" org-non-link-chars " ]\\)>?")
5054 org-link-re-with-space3
5055 (concat
5056 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5057 "\\([^" org-non-link-chars " ]"
5058 "[^\t\n\r]*\\)")
5059 org-angle-link-re
5060 (concat
5061 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5062 "\\([^" org-non-link-chars " ]"
5063 "[^" org-non-link-chars "]*"
5064 "\\)>")
5065 org-plain-link-re
5066 (concat
5067 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5068 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5069 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5070 org-bracket-link-regexp
5071 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5072 org-bracket-link-analytic-regexp
5073 (concat
5074 "\\[\\["
5075 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5076 "\\([^]]+\\)"
5077 "\\]"
5078 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5079 "\\]")
5080 org-bracket-link-analytic-regexp++
5081 (concat
5082 "\\[\\["
5083 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5084 "\\([^]]+\\)"
5085 "\\]"
5086 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5087 "\\]")
5088 org-any-link-re
5089 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5090 org-angle-link-re "\\)\\|\\("
5091 org-plain-link-re "\\)")))
5093 (org-make-link-regexps)
5095 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
5096 "Regular expression for fast time stamp matching.")
5097 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?\\)[]>]"
5098 "Regular expression for fast time stamp matching.")
5099 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5100 "Regular expression matching time strings for analysis.
5101 This one does not require the space after the date, so it can be used
5102 on a string that terminates immediately after the date.")
5103 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5104 "Regular expression matching time strings for analysis.")
5105 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5106 "Regular expression matching time stamps, with groups.")
5107 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5108 "Regular expression matching time stamps (also [..]), with groups.")
5109 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5110 "Regular expression matching a time stamp range.")
5111 (defconst org-tr-regexp-both
5112 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5113 "Regular expression matching a time stamp range.")
5114 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5115 org-ts-regexp "\\)?")
5116 "Regular expression matching a time stamp or time stamp range.")
5117 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5118 org-ts-regexp-both "\\)?")
5119 "Regular expression matching a time stamp or time stamp range.
5120 The time stamps may be either active or inactive.")
5122 (defvar org-emph-face nil)
5124 (defun org-do-emphasis-faces (limit)
5125 "Run through the buffer and add overlays to emphasised strings."
5126 (let (rtn a)
5127 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5128 (if (not (= (char-after (match-beginning 3))
5129 (char-after (match-beginning 4))))
5130 (progn
5131 (setq rtn t)
5132 (setq a (assoc (match-string 3) org-emphasis-alist))
5133 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5134 'face
5135 (nth 1 a))
5136 (and (nth 4 a)
5137 (org-remove-flyspell-overlays-in
5138 (match-beginning 0) (match-end 0)))
5139 (add-text-properties (match-beginning 2) (match-end 2)
5140 '(font-lock-multiline t org-emphasis t))
5141 (when org-hide-emphasis-markers
5142 (add-text-properties (match-end 4) (match-beginning 5)
5143 '(invisible org-link))
5144 (add-text-properties (match-beginning 3) (match-end 3)
5145 '(invisible org-link)))))
5146 (backward-char 1))
5147 rtn))
5149 (defun org-emphasize (&optional char)
5150 "Insert or change an emphasis, i.e. a font like bold or italic.
5151 If there is an active region, change that region to a new emphasis.
5152 If there is no region, just insert the marker characters and position
5153 the cursor between them.
5154 CHAR should be either the marker character, or the first character of the
5155 HTML tag associated with that emphasis. If CHAR is a space, the means
5156 to remove the emphasis of the selected region.
5157 If char is not given (for example in an interactive call) it
5158 will be prompted for."
5159 (interactive)
5160 (let ((eal org-emphasis-alist) e det
5161 (erc org-emphasis-regexp-components)
5162 (prompt "")
5163 (string "") beg end move tag c s)
5164 (if (org-region-active-p)
5165 (setq beg (region-beginning) end (region-end)
5166 string (buffer-substring beg end))
5167 (setq move t))
5169 (while (setq e (pop eal))
5170 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5171 c (aref tag 0))
5172 (push (cons c (string-to-char (car e))) det)
5173 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5174 (substring tag 1)))))
5175 (setq det (nreverse det))
5176 (unless char
5177 (message "%s" (concat "Emphasis marker or tag:" prompt))
5178 (setq char (read-char-exclusive)))
5179 (setq char (or (cdr (assoc char det)) char))
5180 (if (equal char ?\ )
5181 (setq s "" move nil)
5182 (unless (assoc (char-to-string char) org-emphasis-alist)
5183 (error "No such emphasis marker: \"%c\"" char))
5184 (setq s (char-to-string char)))
5185 (while (and (> (length string) 1)
5186 (equal (substring string 0 1) (substring string -1))
5187 (assoc (substring string 0 1) org-emphasis-alist))
5188 (setq string (substring string 1 -1)))
5189 (setq string (concat s string s))
5190 (if beg (delete-region beg end))
5191 (unless (or (bolp)
5192 (string-match (concat "[" (nth 0 erc) "\n]")
5193 (char-to-string (char-before (point)))))
5194 (insert " "))
5195 (unless (or (eobp)
5196 (string-match (concat "[" (nth 1 erc) "\n]")
5197 (char-to-string (char-after (point)))))
5198 (insert " ") (backward-char 1))
5199 (insert string)
5200 (and move (backward-char 1))))
5202 (defconst org-nonsticky-props
5203 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
5205 (defsubst org-rear-nonsticky-at (pos)
5206 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5208 (defun org-activate-plain-links (limit)
5209 "Run through the buffer and add overlays to links."
5210 (catch 'exit
5211 (let (f)
5212 (if (re-search-forward org-plain-link-re limit t)
5213 (progn
5214 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5215 (setq f (get-text-property (match-beginning 0) 'face))
5216 (if (or (eq f 'org-tag)
5217 (and (listp f) (memq 'org-tag f)))
5219 (add-text-properties (match-beginning 0) (match-end 0)
5220 (list 'mouse-face 'highlight
5221 'face 'org-link
5222 'keymap org-mouse-map))
5223 (org-rear-nonsticky-at (match-end 0)))
5224 t)))))
5226 (defun org-activate-code (limit)
5227 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5228 (progn
5229 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5230 (remove-text-properties (match-beginning 0) (match-end 0)
5231 '(display t invisible t intangible t))
5232 t)))
5234 (defcustom org-src-fontify-natively nil
5235 "When non-nil, fontify code in code blocks."
5236 :type 'boolean
5237 :group 'org-appearance
5238 :group 'org-babel)
5240 (defun org-fontify-meta-lines-and-blocks (limit)
5241 (condition-case nil
5242 (org-fontify-meta-lines-and-blocks-1 limit)
5243 (error (message "org-mode fontification error"))))
5245 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5246 "Fontify #+ lines and blocks, in the correct ways."
5247 (let ((case-fold-search t))
5248 (if (re-search-forward
5249 "^\\([ \t]*#\\+\\(\\([a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5250 limit t)
5251 (let ((beg (match-beginning 0))
5252 (block-start (match-end 0))
5253 (block-end nil)
5254 (lang (match-string 7))
5255 (beg1 (line-beginning-position 2))
5256 (dc1 (downcase (match-string 2)))
5257 (dc3 (downcase (match-string 3)))
5258 end end1 quoting block-type ovl)
5259 (cond
5260 ((member dc1 '("html:" "ascii:" "latex:" "docbook:"))
5261 ;; a single line of backend-specific content
5262 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5263 (remove-text-properties (match-beginning 0) (match-end 0)
5264 '(display t invisible t intangible t))
5265 (add-text-properties (match-beginning 1) (match-end 3)
5266 '(font-lock-fontified t face org-meta-line))
5267 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5268 '(font-lock-fontified t face org-block))
5269 ; for backend-specific code
5271 ((and (match-end 4) (equal dc3 "begin"))
5272 ;; Truly a block
5273 (setq block-type (downcase (match-string 5))
5274 quoting (member block-type org-protecting-blocks))
5275 (when (re-search-forward
5276 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5277 nil t) ;; on purpose, we look further than LIMIT
5278 (setq end (match-end 0) end1 (1- (match-beginning 0)))
5279 (setq block-end (match-beginning 0))
5280 (when quoting
5281 (remove-text-properties beg end
5282 '(display t invisible t intangible t)))
5283 (add-text-properties
5284 beg end
5285 '(font-lock-fontified t font-lock-multiline t))
5286 (add-text-properties beg beg1 '(face org-meta-line))
5287 (add-text-properties end1 (min (point-max) (1+ end))
5288 '(face org-meta-line)) ; for end_src
5289 (cond
5290 ((and lang (not (string= lang "")) org-src-fontify-natively)
5291 (org-src-font-lock-fontify-block lang block-start block-end)
5292 ;; remove old background overlays
5293 (mapc (lambda (ov)
5294 (if (eq (overlay-get ov 'face) 'org-block-background)
5295 (delete-overlay ov)))
5296 (overlays-at (/ (+ beg1 block-end) 2)))
5297 ;; add a background overlay
5298 (setq ovl (make-overlay beg1 block-end))
5299 (overlay-put ovl 'face 'org-block-background)
5300 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5301 (quoting
5302 (add-text-properties beg1 (min (point-max) (1+ end1))
5303 '(face org-block))) ; end of source block
5304 ((not org-fontify-quote-and-verse-blocks))
5305 ((string= block-type "quote")
5306 (add-text-properties beg1 (1+ end1) '(face org-quote)))
5307 ((string= block-type "verse")
5308 (add-text-properties beg1 (1+ end1) '(face org-verse))))
5309 (add-text-properties beg beg1 '(face org-block-begin-line))
5310 (add-text-properties (1+ end) (1+ end1) '(face org-block-end-line))
5312 ((member dc1 '("title:" "author:" "email:" "date:"))
5313 (add-text-properties
5314 beg (match-end 3)
5315 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5316 '(font-lock-fontified t invisible t)
5317 '(font-lock-fontified t face org-document-info-keyword)))
5318 (add-text-properties
5319 (match-beginning 6) (match-end 6)
5320 (if (string-equal dc1 "title:")
5321 '(font-lock-fontified t face org-document-title)
5322 '(font-lock-fontified t face org-document-info))))
5323 ((not (member (char-after beg) '(?\ ?\t)))
5324 ;; just any other in-buffer setting, but not indented
5325 (add-text-properties
5326 beg (1+ (match-end 0))
5327 '(font-lock-fontified t face org-meta-line))
5329 ((or (member dc1 '("begin:" "end:" "caption:" "label:"
5330 "orgtbl:" "tblfm:" "tblname:" "result:"
5331 "results:" "source:" "srcname:" "call:"
5332 "data:" "header:" "headers:"))
5333 (and (match-end 4) (equal dc3 "attr")))
5334 (add-text-properties
5335 beg (match-end 0)
5336 '(font-lock-fontified t face org-meta-line))
5338 ((member dc3 '(" " ""))
5339 (add-text-properties
5340 beg (match-end 0)
5341 '(font-lock-fontified t face font-lock-comment-face)))
5342 (t nil))))))
5344 (defun org-activate-angle-links (limit)
5345 "Run through the buffer and add overlays to links."
5346 (if (re-search-forward org-angle-link-re limit t)
5347 (progn
5348 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5349 (add-text-properties (match-beginning 0) (match-end 0)
5350 (list 'mouse-face 'highlight
5351 'keymap org-mouse-map))
5352 (org-rear-nonsticky-at (match-end 0))
5353 t)))
5355 (defun org-activate-footnote-links (limit)
5356 "Run through the buffer and add overlays to footnotes."
5357 (let ((fn (org-footnote-next-reference-or-definition limit)))
5358 (when fn
5359 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5360 (org-remove-flyspell-overlays-in beg end)
5361 (add-text-properties beg end
5362 (list 'mouse-face 'highlight
5363 'keymap org-mouse-map
5364 'help-echo
5365 (if (= (point-at-bol) beg)
5366 "Footnote definition"
5367 "Footnote reference")
5368 'font-lock-fontified t
5369 'font-lock-multiline t
5370 'face 'org-footnote))))))
5372 (defun org-activate-bracket-links (limit)
5373 "Run through the buffer and add overlays to bracketed links."
5374 (if (re-search-forward org-bracket-link-regexp limit t)
5375 (let* ((help (concat "LINK: "
5376 (org-match-string-no-properties 1)))
5377 ;; FIXME: above we should remove the escapes.
5378 ;; but that requires another match, protecting match data,
5379 ;; a lot of overhead for font-lock.
5380 (ip (org-maybe-intangible
5381 (list 'invisible 'org-link
5382 'keymap org-mouse-map 'mouse-face 'highlight
5383 'font-lock-multiline t 'help-echo help)))
5384 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5385 'font-lock-multiline t 'help-echo help)))
5386 ;; We need to remove the invisible property here. Table narrowing
5387 ;; may have made some of this invisible.
5388 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5389 (remove-text-properties (match-beginning 0) (match-end 0)
5390 '(invisible nil))
5391 (if (match-end 3)
5392 (progn
5393 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5394 (org-rear-nonsticky-at (match-beginning 3))
5395 (add-text-properties (match-beginning 3) (match-end 3) vp)
5396 (org-rear-nonsticky-at (match-end 3))
5397 (add-text-properties (match-end 3) (match-end 0) ip)
5398 (org-rear-nonsticky-at (match-end 0)))
5399 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5400 (org-rear-nonsticky-at (match-beginning 1))
5401 (add-text-properties (match-beginning 1) (match-end 1) vp)
5402 (org-rear-nonsticky-at (match-end 1))
5403 (add-text-properties (match-end 1) (match-end 0) ip)
5404 (org-rear-nonsticky-at (match-end 0)))
5405 t)))
5407 (defun org-activate-dates (limit)
5408 "Run through the buffer and add overlays to dates."
5409 (if (re-search-forward org-tsr-regexp-both limit t)
5410 (progn
5411 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5412 (add-text-properties (match-beginning 0) (match-end 0)
5413 (list 'mouse-face 'highlight
5414 'keymap org-mouse-map))
5415 (org-rear-nonsticky-at (match-end 0))
5416 (when org-display-custom-times
5417 (if (match-end 3)
5418 (org-display-custom-time (match-beginning 3) (match-end 3)))
5419 (org-display-custom-time (match-beginning 1) (match-end 1)))
5420 t)))
5422 (defvar org-target-link-regexp nil
5423 "Regular expression matching radio targets in plain text.")
5424 (make-variable-buffer-local 'org-target-link-regexp)
5425 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5426 "Regular expression matching a link target.")
5427 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5428 "Regular expression matching a radio target.")
5429 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5430 "Regular expression matching any target.")
5432 (defun org-activate-target-links (limit)
5433 "Run through the buffer and add overlays to target matches."
5434 (when org-target-link-regexp
5435 (let ((case-fold-search t))
5436 (if (re-search-forward org-target-link-regexp limit t)
5437 (progn
5438 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5439 (add-text-properties (match-beginning 0) (match-end 0)
5440 (list 'mouse-face 'highlight
5441 'keymap org-mouse-map
5442 'help-echo "Radio target link"
5443 'org-linked-text t))
5444 (org-rear-nonsticky-at (match-end 0))
5445 t)))))
5447 (defun org-update-radio-target-regexp ()
5448 "Find all radio targets in this file and update the regular expression."
5449 (interactive)
5450 (when (memq 'radio org-activate-links)
5451 (setq org-target-link-regexp
5452 (org-make-target-link-regexp (org-all-targets 'radio)))
5453 (org-restart-font-lock)))
5455 (defun org-hide-wide-columns (limit)
5456 (let (s e)
5457 (setq s (text-property-any (point) (or limit (point-max))
5458 'org-cwidth t))
5459 (when s
5460 (setq e (next-single-property-change s 'org-cwidth))
5461 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5462 (goto-char e)
5463 t)))
5465 (defvar org-latex-and-specials-regexp nil
5466 "Regular expression for highlighting export special stuff.")
5467 (defvar org-match-substring-regexp)
5468 (defvar org-match-substring-with-braces-regexp)
5470 ;; This should be with the exporter code, but we also use if for font-locking
5471 (defconst org-export-html-special-string-regexps
5472 '(("\\\\-" . "&shy;")
5473 ("---\\([^-]\\)" . "&mdash;\\1")
5474 ("--\\([^-]\\)" . "&ndash;\\1")
5475 ("\\.\\.\\." . "&hellip;"))
5476 "Regular expressions for special string conversion.")
5479 (defun org-compute-latex-and-specials-regexp ()
5480 "Compute regular expression for stuff treated specially by exporters."
5481 (if (not org-highlight-latex-fragments-and-specials)
5482 (org-set-local 'org-latex-and-specials-regexp nil)
5483 (require 'org-exp)
5484 (let*
5485 ((matchers (plist-get org-format-latex-options :matchers))
5486 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5487 org-latex-regexps)))
5488 (org-export-allow-BIND nil)
5489 (options (org-combine-plists (org-default-export-plist)
5490 (org-infile-export-plist)))
5491 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5492 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5493 (org-export-with-TeX-macros (plist-get options :TeX-macros))
5494 (org-export-html-expand (plist-get options :expand-quoted-html))
5495 (org-export-with-special-strings (plist-get options :special-strings))
5496 (re-sub
5497 (cond
5498 ((equal org-export-with-sub-superscripts '{})
5499 (list org-match-substring-with-braces-regexp))
5500 (org-export-with-sub-superscripts
5501 (list org-match-substring-regexp))
5502 (t nil)))
5503 (re-latex
5504 (if org-export-with-LaTeX-fragments
5505 (mapcar (lambda (x) (nth 1 x)) latexs)))
5506 (re-macros
5507 (if org-export-with-TeX-macros
5508 (list (concat "\\\\"
5509 (regexp-opt
5510 (append
5512 (delq nil
5513 (mapcar 'car-safe
5514 (append org-entities-user
5515 org-entities)))
5516 (if (boundp 'org-latex-entities)
5517 (mapcar (lambda (x)
5518 (or (car-safe x) x))
5519 org-latex-entities)
5520 nil))
5521 'words))) ; FIXME
5523 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5524 (re-special (if org-export-with-special-strings
5525 (mapcar (lambda (x) (car x))
5526 org-export-html-special-string-regexps)))
5527 (re-rest
5528 (delq nil
5529 (list
5530 (if org-export-html-expand "@<[^>\n]+>")
5531 ))))
5532 (org-set-local
5533 'org-latex-and-specials-regexp
5534 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5535 re-rest) "\\|")))))
5537 (defun org-do-latex-and-special-faces (limit)
5538 "Run through the buffer and add overlays to links."
5539 (when org-latex-and-specials-regexp
5540 (let (rtn d)
5541 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5542 limit t))
5543 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5544 'face))
5545 '(org-code org-verbatim underline)))
5546 (progn
5547 (setq rtn t
5548 d (cond ((member (char-after (1+ (match-beginning 0)))
5549 '(?_ ?^)) 1)
5550 (t 0)))
5551 (font-lock-prepend-text-property
5552 (+ d (match-beginning 0)) (match-end 0)
5553 'face 'org-latex-and-export-specials)
5554 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5555 '(font-lock-multiline t)))))
5556 rtn)))
5558 (defun org-restart-font-lock ()
5559 "Restart `font-lock-mode', to force refontification."
5560 (when (and (boundp 'font-lock-mode) font-lock-mode)
5561 (font-lock-mode -1)
5562 (font-lock-mode 1)))
5564 (defun org-all-targets (&optional radio)
5565 "Return a list of all targets in this file.
5566 With optional argument RADIO, only find radio targets."
5567 (let ((re (if radio org-radio-target-regexp org-target-regexp))
5568 rtn)
5569 (save-excursion
5570 (goto-char (point-min))
5571 (while (re-search-forward re nil t)
5572 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
5573 rtn)))
5575 (defun org-make-target-link-regexp (targets)
5576 "Make regular expression matching all strings in TARGETS.
5577 The regular expression finds the targets also if there is a line break
5578 between words."
5579 (and targets
5580 (concat
5581 "\\<\\("
5582 (mapconcat
5583 (lambda (x)
5584 (setq x (regexp-quote x))
5585 (while (string-match " +" x)
5586 (setq x (replace-match "\\s-+" t t x)))
5588 targets
5589 "\\|")
5590 "\\)\\>")))
5592 (defun org-activate-tags (limit)
5593 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
5594 (progn
5595 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5596 (add-text-properties (match-beginning 1) (match-end 1)
5597 (list 'mouse-face 'highlight
5598 'keymap org-mouse-map))
5599 (org-rear-nonsticky-at (match-end 1))
5600 t)))
5602 (defun org-outline-level ()
5603 "Compute the outline level of the heading at point.
5604 This function assumes that the cursor is at the beginning of a line matched
5605 by `outline-regexp'. Otherwise it returns garbage.
5606 If this is called at a normal headline, the level is the number of stars.
5607 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
5608 (save-excursion
5609 (looking-at org-outline-regexp)
5610 (1- (- (match-end 0) (match-beginning 0)))))
5612 (defvar org-font-lock-keywords nil)
5614 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
5615 "Regular expression matching a property line.")
5617 (defvar org-font-lock-hook nil
5618 "Functions to be called for special font lock stuff.")
5620 (defvar org-font-lock-set-keywords-hook nil
5621 "Functions that can manipulate `org-font-lock-extra-keywords'.
5622 This is calles after `org-font-lock-extra-keywords' is defined, but before
5623 it is installed to be used by font lock. This can be useful if something
5624 needs to be inserted at a specific position in the font-lock sequence.")
5626 (defun org-font-lock-hook (limit)
5627 (run-hook-with-args 'org-font-lock-hook limit))
5629 (defun org-set-font-lock-defaults ()
5630 (let* ((em org-fontify-emphasized-text)
5631 (lk org-activate-links)
5632 (org-font-lock-extra-keywords
5633 (list
5634 ;; Call the hook
5635 '(org-font-lock-hook)
5636 ;; Headlines
5637 `(,(if org-fontify-whole-heading-line
5638 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
5639 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
5640 (1 (org-get-level-face 1))
5641 (2 (org-get-level-face 2))
5642 (3 (org-get-level-face 3)))
5643 ;; Table lines
5644 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5645 (1 'org-table t))
5646 ;; Table internals
5647 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5648 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5649 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5650 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
5651 ;; Drawers
5652 (list org-drawer-regexp '(0 'org-special-keyword t))
5653 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5654 ;; Properties
5655 (list org-property-re
5656 '(1 'org-special-keyword t)
5657 '(3 'org-property-value t))
5658 ;; Links
5659 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5660 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5661 (if (memq 'plain lk) '(org-activate-plain-links))
5662 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5663 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5664 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5665 (if (memq 'footnote lk) '(org-activate-footnote-links))
5666 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5667 '(org-hide-wide-columns (0 nil append))
5668 ;; TODO lines
5669 (list (concat "^\\*+[ \t]+" org-todo-regexp "\\([ \t]\\|$\\)")
5670 '(1 (org-get-todo-face 1) t))
5671 ;; DONE
5672 (if org-fontify-done-headline
5673 (list (concat "^[*]+ +\\<\\("
5674 (mapconcat 'regexp-quote org-done-keywords "\\|")
5675 "\\)\\(.*\\)")
5676 '(2 'org-headline-done t))
5677 nil)
5678 ;; Priorities
5679 '(org-font-lock-add-priority-faces)
5680 ;; Tags
5681 '(org-font-lock-add-tag-faces)
5682 ;; Special keywords
5683 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5684 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5685 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5686 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5687 ;; Emphasis
5688 (if em
5689 (if (featurep 'xemacs)
5690 '(org-do-emphasis-faces (0 nil append))
5691 '(org-do-emphasis-faces)))
5692 ;; Checkboxes
5693 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
5694 1 'org-checkbox prepend)
5695 (if (cdr (assq 'checkbox org-list-automatic-rules))
5696 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5697 (0 (org-get-checkbox-statistics-face) t)))
5698 ;; Description list items
5699 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
5700 1 'bold prepend)
5701 ;; ARCHIVEd headings
5702 (list (concat
5703 org-outline-regexp-bol
5704 "\\(.*:" org-archive-tag ":.*\\)")
5705 '(1 'org-archived prepend))
5706 ;; Specials
5707 '(org-do-latex-and-special-faces)
5708 '(org-fontify-entities)
5709 '(org-raise-scripts)
5710 ;; Code
5711 '(org-activate-code (1 'org-code t))
5712 ;; COMMENT
5713 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
5714 "\\|" org-quote-string "\\)\\>")
5715 '(1 'org-special-keyword t))
5716 '("^#.*" (0 'font-lock-comment-face t))
5717 ;; Blocks and meta lines
5718 '(org-fontify-meta-lines-and-blocks)
5720 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5721 (run-hooks 'org-font-lock-set-keywords-hook)
5722 ;; Now set the full font-lock-keywords
5723 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5724 (org-set-local 'font-lock-defaults
5725 '(org-font-lock-keywords t nil nil backward-paragraph))
5726 (kill-local-variable 'font-lock-keywords) nil))
5728 (defun org-toggle-pretty-entities ()
5729 "Toggle the composition display of entities as UTF8 characters."
5730 (interactive)
5731 (org-set-local 'org-pretty-entities (not org-pretty-entities))
5732 (org-restart-font-lock)
5733 (if org-pretty-entities
5734 (message "Entities are displayed as UTF8 characers")
5735 (save-restriction
5736 (widen)
5737 (org-decompose-region (point-min) (point-max))
5738 (message "Entities are displayed plain"))))
5740 (defun org-fontify-entities (limit)
5741 "Find an entity to fontify."
5742 (let (ee)
5743 (when org-pretty-entities
5744 (catch 'match
5745 (while (re-search-forward
5746 "\\\\\\([a-zA-Z][a-zA-Z0-9]*\\)\\($\\|[^[:alnum:]\n]\\)"
5747 limit t)
5748 (if (and (not (org-in-indented-comment-line))
5749 (setq ee (org-entity-get (match-string 1)))
5750 (= (length (nth 6 ee)) 1))
5751 (progn
5752 (add-text-properties
5753 (match-beginning 0) (match-end 1)
5754 (list 'font-lock-fontified t))
5755 (compose-region (match-beginning 0) (match-end 1)
5756 (nth 6 ee) nil)
5757 (backward-char 1)
5758 (throw 'match t))))
5759 nil))))
5761 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
5762 "Fontify string S like in Org-mode."
5763 (with-temp-buffer
5764 (insert s)
5765 (let ((org-odd-levels-only odd-levels))
5766 (org-mode)
5767 (font-lock-fontify-buffer)
5768 (buffer-string))))
5770 (defvar org-m nil)
5771 (defvar org-l nil)
5772 (defvar org-f nil)
5773 (defun org-get-level-face (n)
5774 "Get the right face for match N in font-lock matching of headlines."
5775 (setq org-l (- (match-end 2) (match-beginning 1) 1))
5776 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
5777 (if org-cycle-level-faces
5778 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
5779 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
5780 (cond
5781 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
5782 ((eq n 2) org-f)
5783 (t (if org-level-color-stars-only nil org-f))))
5786 (defun org-get-todo-face (kwd)
5787 "Get the right face for a TODO keyword KWD.
5788 If KWD is a number, get the corresponding match group."
5789 (if (numberp kwd) (setq kwd (match-string kwd)))
5790 (or (org-face-from-face-or-color
5791 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
5792 (and (member kwd org-done-keywords) 'org-done)
5793 'org-todo))
5795 (defun org-face-from-face-or-color (context inherit face-or-color)
5796 "Create a face list that inherits INHERIT, but sets the foreground color.
5797 When FACE-OR-COLOR is not a string, just return it."
5798 (if (stringp face-or-color)
5799 (list :inherit inherit
5800 (cdr (assoc context org-faces-easy-properties))
5801 face-or-color)
5802 face-or-color))
5804 (defun org-font-lock-add-tag-faces (limit)
5805 "Add the special tag faces."
5806 (when (and org-tag-faces org-tags-special-faces-re)
5807 (while (re-search-forward org-tags-special-faces-re limit t)
5808 (add-text-properties (match-beginning 1) (match-end 1)
5809 (list 'face (org-get-tag-face 1)
5810 'font-lock-fontified t))
5811 (backward-char 1))))
5813 (defun org-font-lock-add-priority-faces (limit)
5814 "Add the special priority faces."
5815 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
5816 (add-text-properties
5817 (match-beginning 0) (match-end 0)
5818 (list 'face (or (org-face-from-face-or-color
5819 'priority 'org-special-keyword
5820 (cdr (assoc (char-after (match-beginning 1))
5821 org-priority-faces)))
5822 'org-special-keyword)
5823 'font-lock-fontified t))))
5825 (defun org-get-tag-face (kwd)
5826 "Get the right face for a TODO keyword KWD.
5827 If KWD is a number, get the corresponding match group."
5828 (if (numberp kwd) (setq kwd (match-string kwd)))
5829 (or (org-face-from-face-or-color
5830 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
5831 'org-tag))
5833 (defun org-unfontify-region (beg end &optional maybe_loudly)
5834 "Remove fontification and activation overlays from links."
5835 (font-lock-default-unfontify-region beg end)
5836 (let* ((buffer-undo-list t)
5837 (inhibit-read-only t) (inhibit-point-motion-hooks t)
5838 (inhibit-modification-hooks t)
5839 deactivate-mark buffer-file-name buffer-file-truename)
5840 (org-decompose-region beg end)
5841 (remove-text-properties beg end
5842 '(mouse-face t keymap t org-linked-text t
5843 invisible t intangible t
5844 org-no-flyspell t org-emphasis t))
5845 (org-remove-font-lock-display-properties beg end)))
5847 (defconst org-script-display '(((raise -0.3) (height 0.7))
5848 ((raise 0.3) (height 0.7))
5849 ((raise -0.5))
5850 ((raise 0.5)))
5851 "Display properties for showing superscripts and subscripts.")
5853 (defun org-remove-font-lock-display-properties (beg end)
5854 "Remove specific display properties that have been added by font lock.
5855 The will remove the raise properties that are used to show superscripts
5856 and subscripts."
5857 (let (next prop)
5858 (while (< beg end)
5859 (setq next (next-single-property-change beg 'display nil end)
5860 prop (get-text-property beg 'display))
5861 (if (member prop org-script-display)
5862 (put-text-property beg next 'display nil))
5863 (setq beg next))))
5865 (defun org-raise-scripts (limit)
5866 "Add raise properties to sub/superscripts."
5867 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
5868 (if (re-search-forward
5869 (if (eq org-use-sub-superscripts t)
5870 org-match-substring-regexp
5871 org-match-substring-with-braces-regexp)
5872 limit t)
5873 (let* ((pos (point)) table-p comment-p
5874 (mpos (match-beginning 3))
5875 (emph-p (get-text-property mpos 'org-emphasis))
5876 (link-p (get-text-property mpos 'mouse-face))
5877 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
5878 (goto-char (point-at-bol))
5879 (setq table-p (org-looking-at-p org-table-dataline-regexp)
5880 comment-p (org-looking-at-p "[ \t]*#"))
5881 (goto-char pos)
5882 ;; FIXME: Should we go back one character here, for a_b^c
5883 ;; (goto-char (1- pos)) ;????????????????????
5884 (if (or comment-p emph-p link-p keyw-p)
5886 (put-text-property (match-beginning 3) (match-end 0)
5887 'display
5888 (if (equal (char-after (match-beginning 2)) ?^)
5889 (nth (if table-p 3 1) org-script-display)
5890 (nth (if table-p 2 0) org-script-display)))
5891 (add-text-properties (match-beginning 2) (match-end 2)
5892 (list 'invisible t
5893 'org-dwidth t 'org-dwidth-n 1))
5894 (if (and (eq (char-after (match-beginning 3)) ?{)
5895 (eq (char-before (match-end 3)) ?}))
5896 (progn
5897 (add-text-properties
5898 (match-beginning 3) (1+ (match-beginning 3))
5899 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
5900 (add-text-properties
5901 (1- (match-end 3)) (match-end 3)
5902 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
5903 t)))))
5905 ;;;; Visibility cycling, including org-goto and indirect buffer
5907 ;;; Cycling
5909 (defvar org-cycle-global-status nil)
5910 (make-variable-buffer-local 'org-cycle-global-status)
5911 (defvar org-cycle-subtree-status nil)
5912 (make-variable-buffer-local 'org-cycle-subtree-status)
5914 ;;;###autoload
5916 (defvar org-inlinetask-min-level)
5918 (defun org-cycle (&optional arg)
5919 "TAB-action and visibility cycling for Org-mode.
5921 This is the command invoked in Org-mode by the TAB key. Its main purpose
5922 is outline visibility cycling, but it also invokes other actions
5923 in special contexts.
5925 - When this function is called with a prefix argument, rotate the entire
5926 buffer through 3 states (global cycling)
5927 1. OVERVIEW: Show only top-level headlines.
5928 2. CONTENTS: Show all headlines of all levels, but no body text.
5929 3. SHOW ALL: Show everything.
5930 When called with two `C-u C-u' prefixes, switch to the startup visibility,
5931 determined by the variable `org-startup-folded', and by any VISIBILITY
5932 properties in the buffer.
5933 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
5934 including any drawers.
5936 - When inside a table, re-align the table and move to the next field.
5938 - When point is at the beginning of a headline, rotate the subtree started
5939 by this line through 3 different states (local cycling)
5940 1. FOLDED: Only the main headline is shown.
5941 2. CHILDREN: The main headline and the direct children are shown.
5942 From this state, you can move to one of the children
5943 and zoom in further.
5944 3. SUBTREE: Show the entire subtree, including body text.
5945 If there is no subtree, switch directly from CHILDREN to FOLDED.
5947 - When point is at the beginning of an empty headline and the variable
5948 `org-cycle-level-after-item/entry-creation' is set, cycle the level
5949 of the headline by demoting and promoting it to likely levels. This
5950 speeds up creation document structure by pressing TAB once or several
5951 times right after creating a new headline.
5953 - When there is a numeric prefix, go up to a heading with level ARG, do
5954 a `show-subtree' and return to the previous cursor position. If ARG
5955 is negative, go up that many levels.
5957 - When point is not at the beginning of a headline, execute the global
5958 binding for TAB, which is re-indenting the line. See the option
5959 `org-cycle-emulate-tab' for details.
5961 - Special case: if point is at the beginning of the buffer and there is
5962 no headline in line 1, this function will act as if called with prefix arg
5963 (C-u TAB, same as S-TAB) also when called without prefix arg.
5964 But only if also the variable `org-cycle-global-at-bob' is t."
5965 (interactive "P")
5966 (org-load-modules-maybe)
5967 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
5968 (and org-cycle-level-after-item/entry-creation
5969 (or (org-cycle-level)
5970 (org-cycle-item-indentation))))
5971 (let* ((limit-level
5972 (or org-cycle-max-level
5973 (and (boundp 'org-inlinetask-min-level)
5974 org-inlinetask-min-level
5975 (1- org-inlinetask-min-level))))
5976 (nstars (and limit-level
5977 (if org-odd-levels-only
5978 (and limit-level (1- (* limit-level 2)))
5979 limit-level)))
5980 (org-outline-regexp
5981 (if (not (org-mode-p))
5982 outline-regexp
5983 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
5984 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
5985 (not (looking-at org-outline-regexp))))
5986 (org-cycle-hook
5987 (if bob-special
5988 (delq 'org-optimize-window-after-visibility-change
5989 (copy-sequence org-cycle-hook))
5990 org-cycle-hook))
5991 (pos (point)))
5993 (if (or bob-special (equal arg '(4)))
5994 ;; special case: use global cycling
5995 (setq arg t))
5997 (cond
5999 ((equal arg '(16))
6000 (setq last-command 'dummy)
6001 (org-set-startup-visibility)
6002 (message "Startup visibility, plus VISIBILITY properties"))
6004 ((equal arg '(64))
6005 (show-all)
6006 (message "Entire buffer visible, including drawers"))
6008 ;; Table: enter it or move to the next field.
6009 ((org-at-table-p 'any)
6010 (if (org-at-table.el-p)
6011 (message "Use C-c ' to edit table.el tables")
6012 (if arg (org-table-edit-field t)
6013 (org-table-justify-field-maybe)
6014 (call-interactively 'org-table-next-field))))
6016 ((run-hook-with-args-until-success
6017 'org-tab-after-check-for-table-hook))
6019 ;; Global cycling: delegate to `org-cycle-internal-global'.
6020 ((eq arg t) (org-cycle-internal-global))
6022 ;; Drawers: delegate to `org-flag-drawer'.
6023 ((and org-drawers org-drawer-regexp
6024 (save-excursion
6025 (beginning-of-line 1)
6026 (looking-at org-drawer-regexp)))
6027 (org-flag-drawer ; toggle block visibility
6028 (not (get-char-property (match-end 0) 'invisible))))
6030 ;; Show-subtree, ARG levels up from here.
6031 ((integerp arg)
6032 (save-excursion
6033 (org-back-to-heading)
6034 (outline-up-heading (if (< arg 0) (- arg)
6035 (- (funcall outline-level) arg)))
6036 (org-show-subtree)))
6038 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6039 ((and (featurep 'org-inlinetask)
6040 (org-inlinetask-at-task-p)
6041 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6042 (org-inlinetask-toggle-visibility))
6044 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6045 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6046 (save-excursion (beginning-of-line 1)
6047 (looking-at org-outline-regexp)))
6048 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6049 (org-cycle-internal-local))
6051 ;; From there: TAB emulation and template completion.
6052 (buffer-read-only (org-back-to-heading))
6054 ((run-hook-with-args-until-success
6055 'org-tab-after-check-for-cycling-hook))
6057 ((org-try-structure-completion))
6059 ((org-try-cdlatex-tab))
6061 ((run-hook-with-args-until-success
6062 'org-tab-before-tab-emulation-hook))
6064 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6065 (or (not (bolp))
6066 (not (looking-at org-outline-regexp))))
6067 (call-interactively (global-key-binding "\t")))
6069 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6070 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6071 (or (and (eq org-cycle-emulate-tab 'white)
6072 (= (match-end 0) (point-at-eol)))
6073 (and (eq org-cycle-emulate-tab 'whitestart)
6074 (>= (match-end 0) pos))))
6076 (eq org-cycle-emulate-tab t))
6077 (call-interactively (global-key-binding "\t")))
6079 (t (save-excursion
6080 (org-back-to-heading)
6081 (org-cycle)))))))
6083 (defun org-cycle-internal-global ()
6084 "Do the global cycling action."
6085 (cond
6086 ((and (eq last-command this-command)
6087 (eq org-cycle-global-status 'overview))
6088 ;; We just created the overview - now do table of contents
6089 ;; This can be slow in very large buffers, so indicate action
6090 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6091 (message "CONTENTS...")
6092 (org-content)
6093 (message "CONTENTS...done")
6094 (setq org-cycle-global-status 'contents)
6095 (run-hook-with-args 'org-cycle-hook 'contents))
6097 ((and (eq last-command this-command)
6098 (eq org-cycle-global-status 'contents))
6099 ;; We just showed the table of contents - now show everything
6100 (run-hook-with-args 'org-pre-cycle-hook 'all)
6101 (show-all)
6102 (message "SHOW ALL")
6103 (setq org-cycle-global-status 'all)
6104 (run-hook-with-args 'org-cycle-hook 'all))
6107 ;; Default action: go to overview
6108 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6109 (org-overview)
6110 (message "OVERVIEW")
6111 (setq org-cycle-global-status 'overview)
6112 (run-hook-with-args 'org-cycle-hook 'overview))))
6114 (defun org-cycle-internal-local ()
6115 "Do the local cycling action."
6116 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6117 ;; First, determine end of headline (EOH), end of subtree or item
6118 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6119 (save-excursion
6120 (if (org-at-item-p)
6121 (progn
6122 (beginning-of-line)
6123 (setq struct (org-list-struct))
6124 (setq eoh (point-at-eol))
6125 (setq eos (org-list-get-item-end-before-blank (point) struct))
6126 (setq has-children (org-list-has-child-p (point) struct)))
6127 (org-back-to-heading)
6128 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6129 (setq eos (save-excursion
6130 (org-end-of-subtree t)
6131 (unless (eobp)
6132 (skip-chars-forward " \t\n"))
6133 (if (eobp) (point) (1- (point)))))
6134 (setq has-children
6135 (or (save-excursion
6136 (let ((level (funcall outline-level)))
6137 (outline-next-heading)
6138 (and (org-at-heading-p t)
6139 (> (funcall outline-level) level))))
6140 (save-excursion
6141 (org-list-search-forward (org-item-beginning-re) eos t)))))
6142 ;; Determine end invisible part of buffer (EOL)
6143 (beginning-of-line 2)
6144 ;; XEmacs doesn't have `next-single-char-property-change'
6145 (if (featurep 'xemacs)
6146 (while (and (not (eobp)) ;; this is like `next-line'
6147 (get-char-property (1- (point)) 'invisible))
6148 (beginning-of-line 2))
6149 (while (and (not (eobp)) ;; this is like `next-line'
6150 (get-char-property (1- (point)) 'invisible))
6151 (goto-char (next-single-char-property-change (point) 'invisible))
6152 (and (eolp) (beginning-of-line 2))))
6153 (setq eol (point)))
6154 ;; Find out what to do next and set `this-command'
6155 (cond
6156 ((= eos eoh)
6157 ;; Nothing is hidden behind this heading
6158 (run-hook-with-args 'org-pre-cycle-hook 'empty)
6159 (message "EMPTY ENTRY")
6160 (setq org-cycle-subtree-status nil)
6161 (save-excursion
6162 (goto-char eos)
6163 (outline-next-heading)
6164 (if (outline-invisible-p) (org-flag-heading nil))))
6165 ((and (or (>= eol eos)
6166 (not (string-match "\\S-" (buffer-substring eol eos))))
6167 (or has-children
6168 (not (setq children-skipped
6169 org-cycle-skip-children-state-if-no-children))))
6170 ;; Entire subtree is hidden in one line: children view
6171 (run-hook-with-args 'org-pre-cycle-hook 'children)
6172 (if (org-at-item-p)
6173 (org-list-set-item-visibility (point-at-bol) struct 'children)
6174 (org-show-entry)
6175 (show-children)
6176 ;; Fold every list in subtree to top-level items.
6177 (when (eq org-cycle-include-plain-lists 'integrate)
6178 (save-excursion
6179 (org-back-to-heading)
6180 (while (org-list-search-forward (org-item-beginning-re) eos t)
6181 (beginning-of-line 1)
6182 (let* ((struct (org-list-struct))
6183 (prevs (org-list-prevs-alist struct))
6184 (end (org-list-get-bottom-point struct)))
6185 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6186 (org-list-get-all-items (point) struct prevs))
6187 (goto-char end))))))
6188 (message "CHILDREN")
6189 (save-excursion
6190 (goto-char eos)
6191 (outline-next-heading)
6192 (if (outline-invisible-p) (org-flag-heading nil)))
6193 (setq org-cycle-subtree-status 'children)
6194 (run-hook-with-args 'org-cycle-hook 'children))
6195 ((or children-skipped
6196 (and (eq last-command this-command)
6197 (eq org-cycle-subtree-status 'children)))
6198 ;; We just showed the children, or no children are there,
6199 ;; now show everything.
6200 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
6201 (outline-flag-region eoh eos nil)
6202 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6203 (setq org-cycle-subtree-status 'subtree)
6204 (run-hook-with-args 'org-cycle-hook 'subtree))
6206 ;; Default action: hide the subtree.
6207 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6208 (outline-flag-region eoh eos t)
6209 (message "FOLDED")
6210 (setq org-cycle-subtree-status 'folded)
6211 (run-hook-with-args 'org-cycle-hook 'folded)))))
6213 ;;;###autoload
6214 (defun org-global-cycle (&optional arg)
6215 "Cycle the global visibility. For details see `org-cycle'.
6216 With \\[universal-argument] prefix arg, switch to startup visibility.
6217 With a numeric prefix, show all headlines up to that level."
6218 (interactive "P")
6219 (let ((org-cycle-include-plain-lists
6220 (if (org-mode-p) org-cycle-include-plain-lists nil)))
6221 (cond
6222 ((integerp arg)
6223 (show-all)
6224 (hide-sublevels arg)
6225 (setq org-cycle-global-status 'contents))
6226 ((equal arg '(4))
6227 (org-set-startup-visibility)
6228 (message "Startup visibility, plus VISIBILITY properties."))
6230 (org-cycle '(4))))))
6232 (defun org-set-startup-visibility ()
6233 "Set the visibility required by startup options and properties."
6234 (cond
6235 ((eq org-startup-folded t)
6236 (org-cycle '(4)))
6237 ((eq org-startup-folded 'content)
6238 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6239 (org-cycle '(4)) (org-cycle '(4)))))
6240 (unless (eq org-startup-folded 'showeverything)
6241 (if org-hide-block-startup (org-hide-block-all))
6242 (org-set-visibility-according-to-property 'no-cleanup)
6243 (org-cycle-hide-archived-subtrees 'all)
6244 (org-cycle-hide-drawers 'all)
6245 (org-cycle-show-empty-lines t)))
6247 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6248 "Switch subtree visibilities according to :VISIBILITY: property."
6249 (interactive)
6250 (let (org-show-entry-below state)
6251 (save-excursion
6252 (goto-char (point-min))
6253 (while (re-search-forward
6254 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6255 nil t)
6256 (setq state (match-string 1))
6257 (save-excursion
6258 (org-back-to-heading t)
6259 (hide-subtree)
6260 (org-reveal)
6261 (cond
6262 ((equal state '("fold" "folded"))
6263 (hide-subtree))
6264 ((equal state "children")
6265 (org-show-hidden-entry)
6266 (show-children))
6267 ((equal state "content")
6268 (save-excursion
6269 (save-restriction
6270 (org-narrow-to-subtree)
6271 (org-content))))
6272 ((member state '("all" "showall"))
6273 (show-subtree)))))
6274 (unless no-cleanup
6275 (org-cycle-hide-archived-subtrees 'all)
6276 (org-cycle-hide-drawers 'all)
6277 (org-cycle-show-empty-lines 'all)))))
6279 ;; This function uses outline-regexp instead of the more fundamental
6280 ;; org-outline-regexp so that org-cycle-global works outside of Org
6281 ;; buffers, where outline-regexp is needed.
6282 (defun org-overview ()
6283 "Switch to overview mode, showing only top-level headlines.
6284 Really, this shows all headlines with level equal or greater than the level
6285 of the first headline in the buffer. This is important, because if the
6286 first headline is not level one, then (hide-sublevels 1) gives confusing
6287 results."
6288 (interactive)
6289 (let ((level (save-excursion
6290 (goto-char (point-min))
6291 (if (re-search-forward (concat "^" outline-regexp) nil t)
6292 (progn
6293 (goto-char (match-beginning 0))
6294 (funcall outline-level))))))
6295 (and level (hide-sublevels level))))
6297 (defun org-content (&optional arg)
6298 "Show all headlines in the buffer, like a table of contents.
6299 With numerical argument N, show content up to level N."
6300 (interactive "P")
6301 (save-excursion
6302 ;; Visit all headings and show their offspring
6303 (and (integerp arg) (org-overview))
6304 (goto-char (point-max))
6305 (catch 'exit
6306 (while (and (progn (condition-case nil
6307 (outline-previous-visible-heading 1)
6308 (error (goto-char (point-min))))
6310 (looking-at org-outline-regexp))
6311 (if (integerp arg)
6312 (show-children (1- arg))
6313 (show-branches))
6314 (if (bobp) (throw 'exit nil))))))
6317 (defun org-optimize-window-after-visibility-change (state)
6318 "Adjust the window after a change in outline visibility.
6319 This function is the default value of the hook `org-cycle-hook'."
6320 (when (get-buffer-window (current-buffer))
6321 (cond
6322 ((eq state 'content) nil)
6323 ((eq state 'all) nil)
6324 ((eq state 'folded) nil)
6325 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6326 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6328 (defun org-remove-empty-overlays-at (pos)
6329 "Remove outline overlays that do not contain non-white stuff."
6330 (mapc
6331 (lambda (o)
6332 (and (eq 'outline (overlay-get o 'invisible))
6333 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6334 (overlay-end o))))
6335 (delete-overlay o)))
6336 (overlays-at pos)))
6338 (defun org-clean-visibility-after-subtree-move ()
6339 "Fix visibility issues after moving a subtree."
6340 ;; First, find a reasonable region to look at:
6341 ;; Start two siblings above, end three below
6342 (let* ((beg (save-excursion
6343 (and (org-get-last-sibling)
6344 (org-get-last-sibling))
6345 (point)))
6346 (end (save-excursion
6347 (and (org-get-next-sibling)
6348 (org-get-next-sibling)
6349 (org-get-next-sibling))
6350 (if (org-at-heading-p)
6351 (point-at-eol)
6352 (point))))
6353 (level (looking-at "\\*+"))
6354 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6355 (save-excursion
6356 (save-restriction
6357 (narrow-to-region beg end)
6358 (when re
6359 ;; Properly fold already folded siblings
6360 (goto-char (point-min))
6361 (while (re-search-forward re nil t)
6362 (if (and (not (outline-invisible-p))
6363 (save-excursion
6364 (goto-char (point-at-eol)) (outline-invisible-p)))
6365 (hide-entry))))
6366 (org-cycle-show-empty-lines 'overview)
6367 (org-cycle-hide-drawers 'overview)))))
6369 (defun org-cycle-show-empty-lines (state)
6370 "Show empty lines above all visible headlines.
6371 The region to be covered depends on STATE when called through
6372 `org-cycle-hook'. Lisp program can use t for STATE to get the
6373 entire buffer covered. Note that an empty line is only shown if there
6374 are at least `org-cycle-separator-lines' empty lines before the headline."
6375 (when (not (= org-cycle-separator-lines 0))
6376 (save-excursion
6377 (let* ((n (abs org-cycle-separator-lines))
6378 (re (cond
6379 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6380 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6381 (t (let ((ns (number-to-string (- n 2))))
6382 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6383 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6384 beg end b e)
6385 (cond
6386 ((memq state '(overview contents t))
6387 (setq beg (point-min) end (point-max)))
6388 ((memq state '(children folded))
6389 (setq beg (point) end (progn (org-end-of-subtree t t)
6390 (beginning-of-line 2)
6391 (point)))))
6392 (when beg
6393 (goto-char beg)
6394 (while (re-search-forward re end t)
6395 (unless (get-char-property (match-end 1) 'invisible)
6396 (setq e (match-end 1))
6397 (if (< org-cycle-separator-lines 0)
6398 (setq b (save-excursion
6399 (goto-char (match-beginning 0))
6400 (org-back-over-empty-lines)
6401 (if (save-excursion
6402 (goto-char (max (point-min) (1- (point))))
6403 (org-on-heading-p))
6404 (1- (point))
6405 (point))))
6406 (setq b (match-beginning 1)))
6407 (outline-flag-region b e nil)))))))
6408 ;; Never hide empty lines at the end of the file.
6409 (save-excursion
6410 (goto-char (point-max))
6411 (outline-previous-heading)
6412 (outline-end-of-heading)
6413 (if (and (looking-at "[ \t\n]+")
6414 (= (match-end 0) (point-max)))
6415 (outline-flag-region (point) (match-end 0) nil))))
6417 (defun org-show-empty-lines-in-parent ()
6418 "Move to the parent and re-show empty lines before visible headlines."
6419 (save-excursion
6420 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6421 (org-cycle-show-empty-lines context))))
6423 (defun org-files-list ()
6424 "Return `org-agenda-files' list, plus all open org-mode files.
6425 This is useful for operations that need to scan all of a user's
6426 open and agenda-wise Org files."
6427 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6428 (dolist (buf (buffer-list))
6429 (with-current-buffer buf
6430 (if (and (org-mode-p) (buffer-file-name))
6431 (let ((file (expand-file-name (buffer-file-name))))
6432 (unless (member file files)
6433 (push file files))))))
6434 files))
6436 (defsubst org-entry-beginning-position ()
6437 "Return the beginning position of the current entry."
6438 (save-excursion (outline-back-to-heading t) (point)))
6440 (defsubst org-entry-end-position ()
6441 "Return the end position of the current entry."
6442 (save-excursion (outline-next-heading) (point)))
6444 (defun org-cycle-hide-drawers (state)
6445 "Re-hide all drawers after a visibility state change."
6446 (when (and (org-mode-p)
6447 (not (memq state '(overview folded contents))))
6448 (save-excursion
6449 (let* ((globalp (memq state '(contents all)))
6450 (beg (if globalp (point-min) (point)))
6451 (end (if globalp (point-max)
6452 (if (eq state 'children)
6453 (save-excursion (outline-next-heading) (point))
6454 (org-end-of-subtree t)))))
6455 (goto-char beg)
6456 (while (re-search-forward org-drawer-regexp end t)
6457 (org-flag-drawer t))))))
6459 (defun org-flag-drawer (flag)
6460 (save-excursion
6461 (beginning-of-line 1)
6462 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6463 (let ((b (match-end 0)))
6464 (if (re-search-forward
6465 "^[ \t]*:END:"
6466 (save-excursion (outline-next-heading) (point)) t)
6467 (outline-flag-region b (point-at-eol) flag)
6468 (error ":END: line missing at position %s" b))))))
6470 (defun org-subtree-end-visible-p ()
6471 "Is the end of the current subtree visible?"
6472 (pos-visible-in-window-p
6473 (save-excursion (org-end-of-subtree t) (point))))
6475 (defun org-first-headline-recenter (&optional N)
6476 "Move cursor to the first headline and recenter the headline.
6477 Optional argument N means put the headline into the Nth line of the window."
6478 (goto-char (point-min))
6479 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
6480 (beginning-of-line)
6481 (recenter (prefix-numeric-value N))))
6483 ;;; Saving and restoring visibility
6485 (defun org-outline-overlay-data (&optional use-markers)
6486 "Return a list of the locations of all outline overlays.
6487 These are overlays with the `invisible' property value `outline'.
6488 The return value is a list of cons cells, with start and stop
6489 positions for each overlay.
6490 If USE-MARKERS is set, return the positions as markers."
6491 (let (beg end)
6492 (save-excursion
6493 (save-restriction
6494 (widen)
6495 (delq nil
6496 (mapcar (lambda (o)
6497 (when (eq (overlay-get o 'invisible) 'outline)
6498 (setq beg (overlay-start o)
6499 end (overlay-end o))
6500 (and beg end (> end beg)
6501 (if use-markers
6502 (cons (move-marker (make-marker) beg)
6503 (move-marker (make-marker) end))
6504 (cons beg end)))))
6505 (overlays-in (point-min) (point-max))))))))
6507 (defun org-set-outline-overlay-data (data)
6508 "Create visibility overlays for all positions in DATA.
6509 DATA should have been made by `org-outline-overlay-data'."
6510 (let (o)
6511 (save-excursion
6512 (save-restriction
6513 (widen)
6514 (show-all)
6515 (mapc (lambda (c)
6516 (setq o (make-overlay (car c) (cdr c)))
6517 (overlay-put o 'invisible 'outline))
6518 data)))))
6520 ;;; Folding of blocks
6522 (defconst org-block-regexp
6523 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
6524 "Regular expression for hiding blocks.")
6526 (defvar org-hide-block-overlays nil
6527 "Overlays hiding blocks.")
6528 (make-variable-buffer-local 'org-hide-block-overlays)
6530 (defun org-block-map (function &optional start end)
6531 "Call FUNCTION at the head of all source blocks in the current buffer.
6532 Optional arguments START and END can be used to limit the range."
6533 (let ((start (or start (point-min)))
6534 (end (or end (point-max))))
6535 (save-excursion
6536 (goto-char start)
6537 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
6538 (save-excursion
6539 (save-match-data
6540 (goto-char (match-beginning 0))
6541 (funcall function)))))))
6543 (defun org-hide-block-toggle-all ()
6544 "Toggle the visibility of all blocks in the current buffer."
6545 (org-block-map #'org-hide-block-toggle))
6547 (defun org-hide-block-all ()
6548 "Fold all blocks in the current buffer."
6549 (interactive)
6550 (org-show-block-all)
6551 (org-block-map #'org-hide-block-toggle-maybe))
6553 (defun org-show-block-all ()
6554 "Unfold all blocks in the current buffer."
6555 (interactive)
6556 (mapc 'delete-overlay org-hide-block-overlays)
6557 (setq org-hide-block-overlays nil))
6559 (defun org-hide-block-toggle-maybe ()
6560 "Toggle visibility of block at point."
6561 (interactive)
6562 (let ((case-fold-search t))
6563 (if (save-excursion
6564 (beginning-of-line 1)
6565 (looking-at org-block-regexp))
6566 (progn (org-hide-block-toggle)
6567 t) ;; to signal that we took action
6568 nil))) ;; to signal that we did not
6570 (defun org-hide-block-toggle (&optional force)
6571 "Toggle the visibility of the current block."
6572 (interactive)
6573 (save-excursion
6574 (beginning-of-line)
6575 (if (re-search-forward org-block-regexp nil t)
6576 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
6577 (end (match-end 0)) ;; end of entire body
6579 (if (memq t (mapcar (lambda (overlay)
6580 (eq (overlay-get overlay 'invisible)
6581 'org-hide-block))
6582 (overlays-at start)))
6583 (if (or (not force) (eq force 'off))
6584 (mapc (lambda (ov)
6585 (when (member ov org-hide-block-overlays)
6586 (setq org-hide-block-overlays
6587 (delq ov org-hide-block-overlays)))
6588 (when (eq (overlay-get ov 'invisible)
6589 'org-hide-block)
6590 (delete-overlay ov)))
6591 (overlays-at start)))
6592 (setq ov (make-overlay start end))
6593 (overlay-put ov 'invisible 'org-hide-block)
6594 ;; make the block accessible to isearch
6595 (overlay-put
6596 ov 'isearch-open-invisible
6597 (lambda (ov)
6598 (when (member ov org-hide-block-overlays)
6599 (setq org-hide-block-overlays
6600 (delq ov org-hide-block-overlays)))
6601 (when (eq (overlay-get ov 'invisible)
6602 'org-hide-block)
6603 (delete-overlay ov))))
6604 (push ov org-hide-block-overlays)))
6605 (error "Not looking at a source block"))))
6607 ;; org-tab-after-check-for-cycling-hook
6608 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
6609 ;; Remove overlays when changing major mode
6610 (add-hook 'org-mode-hook
6611 (lambda () (org-add-hook 'change-major-mode-hook
6612 'org-show-block-all 'append 'local)))
6614 ;;; Org-goto
6616 (defvar org-goto-window-configuration nil)
6617 (defvar org-goto-marker nil)
6618 (defvar org-goto-map
6619 (let ((map (make-sparse-keymap)))
6620 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
6621 (while (setq cmd (pop cmds))
6622 (substitute-key-definition cmd cmd map global-map)))
6623 (suppress-keymap map)
6624 (org-defkey map "\C-m" 'org-goto-ret)
6625 (org-defkey map [(return)] 'org-goto-ret)
6626 (org-defkey map [(left)] 'org-goto-left)
6627 (org-defkey map [(right)] 'org-goto-right)
6628 (org-defkey map [(control ?g)] 'org-goto-quit)
6629 (org-defkey map "\C-i" 'org-cycle)
6630 (org-defkey map [(tab)] 'org-cycle)
6631 (org-defkey map [(down)] 'outline-next-visible-heading)
6632 (org-defkey map [(up)] 'outline-previous-visible-heading)
6633 (if org-goto-auto-isearch
6634 (if (fboundp 'define-key-after)
6635 (define-key-after map [t] 'org-goto-local-auto-isearch)
6636 nil)
6637 (org-defkey map "q" 'org-goto-quit)
6638 (org-defkey map "n" 'outline-next-visible-heading)
6639 (org-defkey map "p" 'outline-previous-visible-heading)
6640 (org-defkey map "f" 'outline-forward-same-level)
6641 (org-defkey map "b" 'outline-backward-same-level)
6642 (org-defkey map "u" 'outline-up-heading))
6643 (org-defkey map "/" 'org-occur)
6644 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
6645 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
6646 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
6647 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
6648 (org-defkey map "\C-c\C-u" 'outline-up-heading)
6649 map))
6651 (defconst org-goto-help
6652 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
6653 RET=jump to location [Q]uit and return to previous location
6654 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
6656 (defvar org-goto-start-pos) ; dynamically scoped parameter
6658 ;; FIXME: Docstring does not mention both interfaces
6659 (defun org-goto (&optional alternative-interface)
6660 "Look up a different location in the current file, keeping current visibility.
6662 When you want look-up or go to a different location in a document, the
6663 fastest way is often to fold the entire buffer and then dive into the tree.
6664 This method has the disadvantage, that the previous location will be folded,
6665 which may not be what you want.
6667 This command works around this by showing a copy of the current buffer
6668 in an indirect buffer, in overview mode. You can dive into the tree in
6669 that copy, use org-occur and incremental search to find a location.
6670 When pressing RET or `Q', the command returns to the original buffer in
6671 which the visibility is still unchanged. After RET is will also jump to
6672 the location selected in the indirect buffer and expose the headline
6673 hierarchy above."
6674 (interactive "P")
6675 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
6676 (org-refile-use-outline-path t)
6677 (org-refile-target-verify-function nil)
6678 (interface
6679 (if (not alternative-interface)
6680 org-goto-interface
6681 (if (eq org-goto-interface 'outline)
6682 'outline-path-completion
6683 'outline)))
6684 (org-goto-start-pos (point))
6685 (selected-point
6686 (if (eq interface 'outline)
6687 (car (org-get-location (current-buffer) org-goto-help))
6688 (let ((pa (org-refile-get-location "Goto")))
6689 (org-refile-check-position pa)
6690 (nth 3 pa)))))
6691 (if selected-point
6692 (progn
6693 (org-mark-ring-push org-goto-start-pos)
6694 (goto-char selected-point)
6695 (if (or (outline-invisible-p) (org-invisible-p2))
6696 (org-show-context 'org-goto)))
6697 (message "Quit"))))
6699 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
6700 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
6701 (defvar org-goto-local-auto-isearch-map) ; defined below
6703 (defun org-get-location (buf help)
6704 "Let the user select a location in the Org-mode buffer BUF.
6705 This function uses a recursive edit. It returns the selected position
6706 or nil."
6707 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
6708 (isearch-hide-immediately nil)
6709 (isearch-search-fun-function
6710 (lambda () 'org-goto-local-search-headings))
6711 (org-goto-selected-point org-goto-exit-command)
6712 (pop-up-frames nil)
6713 (special-display-buffer-names nil)
6714 (special-display-regexps nil)
6715 (special-display-function nil))
6716 (save-excursion
6717 (save-window-excursion
6718 (delete-other-windows)
6719 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
6720 (org-pop-to-buffer-same-window
6721 (condition-case nil
6722 (make-indirect-buffer (current-buffer) "*org-goto*")
6723 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
6724 (with-output-to-temp-buffer "*Help*"
6725 (princ help))
6726 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
6727 (setq buffer-read-only nil)
6728 (let ((org-startup-truncated t)
6729 (org-startup-folded nil)
6730 (org-startup-align-all-tables nil))
6731 (org-mode)
6732 (org-overview))
6733 (setq buffer-read-only t)
6734 (if (and (boundp 'org-goto-start-pos)
6735 (integer-or-marker-p org-goto-start-pos))
6736 (let ((org-show-hierarchy-above t)
6737 (org-show-siblings t)
6738 (org-show-following-heading t))
6739 (goto-char org-goto-start-pos)
6740 (and (outline-invisible-p) (org-show-context)))
6741 (goto-char (point-min)))
6742 (let (org-special-ctrl-a/e) (org-beginning-of-line))
6743 (message "Select location and press RET")
6744 (use-local-map org-goto-map)
6745 (recursive-edit)
6747 (kill-buffer "*org-goto*")
6748 (cons org-goto-selected-point org-goto-exit-command)))
6750 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
6751 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
6752 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
6753 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
6755 (defun org-goto-local-search-headings (string bound noerror)
6756 "Search and make sure that any matches are in headlines."
6757 (catch 'return
6758 (while (if isearch-forward
6759 (search-forward string bound noerror)
6760 (search-backward string bound noerror))
6761 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
6762 (and (member :headline context)
6763 (not (member :tags context))))
6764 (throw 'return (point))))))
6766 (defun org-goto-local-auto-isearch ()
6767 "Start isearch."
6768 (interactive)
6769 (goto-char (point-min))
6770 (let ((keys (this-command-keys)))
6771 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
6772 (isearch-mode t)
6773 (isearch-process-search-char (string-to-char keys)))))
6775 (defun org-goto-ret (&optional arg)
6776 "Finish `org-goto' by going to the new location."
6777 (interactive "P")
6778 (setq org-goto-selected-point (point)
6779 org-goto-exit-command 'return)
6780 (throw 'exit nil))
6782 (defun org-goto-left ()
6783 "Finish `org-goto' by going to the new location."
6784 (interactive)
6785 (if (org-on-heading-p)
6786 (progn
6787 (beginning-of-line 1)
6788 (setq org-goto-selected-point (point)
6789 org-goto-exit-command 'left)
6790 (throw 'exit nil))
6791 (error "Not on a heading")))
6793 (defun org-goto-right ()
6794 "Finish `org-goto' by going to the new location."
6795 (interactive)
6796 (if (org-on-heading-p)
6797 (progn
6798 (setq org-goto-selected-point (point)
6799 org-goto-exit-command 'right)
6800 (throw 'exit nil))
6801 (error "Not on a heading")))
6803 (defun org-goto-quit ()
6804 "Finish `org-goto' without cursor motion."
6805 (interactive)
6806 (setq org-goto-selected-point nil)
6807 (setq org-goto-exit-command 'quit)
6808 (throw 'exit nil))
6810 ;;; Indirect buffer display of subtrees
6812 (defvar org-indirect-dedicated-frame nil
6813 "This is the frame being used for indirect tree display.")
6814 (defvar org-last-indirect-buffer nil)
6816 (defun org-tree-to-indirect-buffer (&optional arg)
6817 "Create indirect buffer and narrow it to current subtree.
6818 With numerical prefix ARG, go up to this level and then take that tree.
6819 If ARG is negative, go up that many levels.
6820 If `org-indirect-buffer-display' is not `new-frame', the command removes the
6821 indirect buffer previously made with this command, to avoid proliferation of
6822 indirect buffers. However, when you call the command with a \
6823 \\[universal-argument] prefix, or
6824 when `org-indirect-buffer-display' is `new-frame', the last buffer
6825 is kept so that you can work with several indirect buffers at the same time.
6826 If `org-indirect-buffer-display' is `dedicated-frame', the \
6827 \\[universal-argument] prefix also
6828 requests that a new frame be made for the new buffer, so that the dedicated
6829 frame is not changed."
6830 (interactive "P")
6831 (let ((cbuf (current-buffer))
6832 (cwin (selected-window))
6833 (pos (point))
6834 beg end level heading ibuf)
6835 (save-excursion
6836 (org-back-to-heading t)
6837 (when (numberp arg)
6838 (setq level (org-outline-level))
6839 (if (< arg 0) (setq arg (+ level arg)))
6840 (while (> (setq level (org-outline-level)) arg)
6841 (outline-up-heading 1 t)))
6842 (setq beg (point)
6843 heading (org-get-heading))
6844 (org-end-of-subtree t t)
6845 (if (org-on-heading-p) (backward-char 1))
6846 (setq end (point)))
6847 (if (and (buffer-live-p org-last-indirect-buffer)
6848 (not (eq org-indirect-buffer-display 'new-frame))
6849 (not arg))
6850 (kill-buffer org-last-indirect-buffer))
6851 (setq ibuf (org-get-indirect-buffer cbuf)
6852 org-last-indirect-buffer ibuf)
6853 (cond
6854 ((or (eq org-indirect-buffer-display 'new-frame)
6855 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
6856 (select-frame (make-frame))
6857 (delete-other-windows)
6858 (org-pop-to-buffer-same-window ibuf)
6859 (org-set-frame-title heading))
6860 ((eq org-indirect-buffer-display 'dedicated-frame)
6861 (raise-frame
6862 (select-frame (or (and org-indirect-dedicated-frame
6863 (frame-live-p org-indirect-dedicated-frame)
6864 org-indirect-dedicated-frame)
6865 (setq org-indirect-dedicated-frame (make-frame)))))
6866 (delete-other-windows)
6867 (org-pop-to-buffer-same-window ibuf)
6868 (org-set-frame-title (concat "Indirect: " heading)))
6869 ((eq org-indirect-buffer-display 'current-window)
6870 (org-pop-to-buffer-same-window ibuf))
6871 ((eq org-indirect-buffer-display 'other-window)
6872 (pop-to-buffer ibuf))
6873 (t (error "Invalid value")))
6874 (if (featurep 'xemacs)
6875 (save-excursion (org-mode) (turn-on-font-lock)))
6876 (narrow-to-region beg end)
6877 (show-all)
6878 (goto-char pos)
6879 (and (window-live-p cwin) (select-window cwin))))
6881 (defun org-get-indirect-buffer (&optional buffer)
6882 (setq buffer (or buffer (current-buffer)))
6883 (let ((n 1) (base (buffer-name buffer)) bname)
6884 (while (buffer-live-p
6885 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
6886 (setq n (1+ n)))
6887 (condition-case nil
6888 (make-indirect-buffer buffer bname 'clone)
6889 (error (make-indirect-buffer buffer bname)))))
6891 (defun org-set-frame-title (title)
6892 "Set the title of the current frame to the string TITLE."
6893 ;; FIXME: how to name a single frame in XEmacs???
6894 (unless (featurep 'xemacs)
6895 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
6897 ;;;; Structure editing
6899 ;;; Inserting headlines
6901 (defun org-previous-line-empty-p ()
6902 (save-excursion
6903 (and (not (bobp))
6904 (or (beginning-of-line 0) t)
6905 (save-match-data
6906 (looking-at "[ \t]*$")))))
6908 (defun org-insert-heading (&optional force-heading invisible-ok)
6909 "Insert a new heading or item with same depth at point.
6910 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
6911 If point is at the beginning of a headline, insert a sibling before the
6912 current headline. If point is not at the beginning, split the line,
6913 create the new headline with the text in the current line after point
6914 \(but see also the variable `org-M-RET-may-split-line').
6916 When INVISIBLE-OK is set, stop at invisible headlines when going back.
6917 This is important for non-interactive uses of the command."
6918 (interactive "P")
6919 (if (or (= (buffer-size) 0)
6920 (and (not (save-excursion
6921 (and (ignore-errors (org-back-to-heading invisible-ok))
6922 (org-on-heading-p))))
6923 (or force-heading (not (org-in-item-p)))))
6924 (progn
6925 (insert "\n* ")
6926 (run-hooks 'org-insert-heading-hook))
6927 (when (or force-heading (not (org-insert-item)))
6928 (let* ((empty-line-p nil)
6929 (level nil)
6930 (on-heading (org-on-heading-p))
6931 (head (save-excursion
6932 (condition-case nil
6933 (progn
6934 (org-back-to-heading invisible-ok)
6935 (when (and (not on-heading)
6936 (featurep 'org-inlinetask)
6937 (integerp org-inlinetask-min-level)
6938 (>= (length (match-string 0))
6939 org-inlinetask-min-level))
6940 ;; Find a heading level before the inline task
6941 (while (and (setq level (org-up-heading-safe))
6942 (>= level org-inlinetask-min-level)))
6943 (if (org-on-heading-p)
6944 (org-back-to-heading invisible-ok)
6945 (error "This should not happen")))
6946 (setq empty-line-p (org-previous-line-empty-p))
6947 (match-string 0))
6948 (error "*"))))
6949 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
6950 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
6951 pos hide-previous previous-pos)
6952 (cond
6953 ((and (org-on-heading-p) (bolp)
6954 (or (bobp)
6955 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
6956 ;; insert before the current line
6957 (open-line (if blank 2 1)))
6958 ((and (bolp)
6959 (not org-insert-heading-respect-content)
6960 (or (bobp)
6961 (save-excursion
6962 (backward-char 1) (not (outline-invisible-p)))))
6963 ;; insert right here
6964 nil)
6966 ;; somewhere in the line
6967 (save-excursion
6968 (setq previous-pos (point-at-bol))
6969 (end-of-line)
6970 (setq hide-previous (outline-invisible-p)))
6971 (and org-insert-heading-respect-content (org-show-subtree))
6972 (let ((split
6973 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
6974 (save-excursion
6975 (let ((p (point)))
6976 (goto-char (point-at-bol))
6977 (and (looking-at org-complex-heading-regexp)
6978 (> p (match-beginning 4)))))))
6979 tags pos)
6980 (cond
6981 (org-insert-heading-respect-content
6982 (org-end-of-subtree nil t)
6983 (when (featurep 'org-inlinetask)
6984 (while (and (not (eobp))
6985 (looking-at "\\(\\*+\\)[ \t]+")
6986 (>= (length (match-string 1))
6987 org-inlinetask-min-level))
6988 (org-end-of-subtree nil t)))
6989 (or (bolp) (newline))
6990 (or (org-previous-line-empty-p)
6991 (and blank (newline)))
6992 (open-line 1))
6993 ((org-on-heading-p)
6994 (when hide-previous
6995 (show-children)
6996 (org-show-entry))
6997 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
6998 (setq tags (and (match-end 2) (match-string 2)))
6999 (and (match-end 1)
7000 (delete-region (match-beginning 1) (match-end 1)))
7001 (setq pos (point-at-bol))
7002 (or split (end-of-line 1))
7003 (delete-horizontal-space)
7004 (if (string-match "\\`\\*+\\'"
7005 (buffer-substring (point-at-bol) (point)))
7006 (insert " "))
7007 (newline (if blank 2 1))
7008 (when tags
7009 (save-excursion
7010 (goto-char pos)
7011 (end-of-line 1)
7012 (insert " " tags)
7013 (org-set-tags nil 'align))))
7015 (or split (end-of-line 1))
7016 (newline (if blank 2 1)))))))
7017 (insert head) (just-one-space)
7018 (setq pos (point))
7019 (end-of-line 1)
7020 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7021 (when (and org-insert-heading-respect-content hide-previous)
7022 (save-excursion
7023 (goto-char previous-pos)
7024 (hide-subtree)))
7025 (run-hooks 'org-insert-heading-hook)))))
7027 (defun org-get-heading (&optional no-tags no-todo)
7028 "Return the heading of the current entry, without the stars.
7029 When NO-TAGS is non-nil, don't include tags.
7030 When NO-TODO is non-nil, don't include TODO keywords."
7031 (save-excursion
7032 (org-back-to-heading t)
7033 (cond
7034 ((and no-tags no-todo)
7035 (looking-at org-complex-heading-regexp)
7036 (match-string 4))
7037 (no-tags
7038 (looking-at "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@#%]+:[ \t]*\\)?$")
7039 (match-string 1))
7040 (no-todo
7041 (looking-at (concat "\\*+[ \t]+" org-todo-regexp " +"
7042 "\\([^\n\r]*?[ \t]+:[[:alnum:]:_@#%]+:[ \t]*\\)?$"))
7043 (match-string 2))
7044 (t (looking-at "\\*+[ \t]+\\([^\r\n]*\\)")
7045 (match-string 1)))))
7047 (defun org-heading-components ()
7048 "Return the components of the current heading.
7049 This is a list with the following elements:
7050 - the level as an integer
7051 - the reduced level, different if `org-odd-levels-only' is set.
7052 - the TODO keyword, or nil
7053 - the priority character, like ?A, or nil if no priority is given
7054 - the headline text itself, or the tags string if no headline text
7055 - the tags string, or nil."
7056 (save-excursion
7057 (org-back-to-heading t)
7058 (if (let (case-fold-search) (looking-at org-complex-heading-regexp))
7059 (list (length (match-string 1))
7060 (org-reduced-level (length (match-string 1)))
7061 (org-match-string-no-properties 2)
7062 (and (match-end 3) (aref (match-string 3) 2))
7063 (org-match-string-no-properties 4)
7064 (org-match-string-no-properties 5)))))
7066 (defun org-get-entry ()
7067 "Get the entry text, after heading, entire subtree."
7068 (save-excursion
7069 (org-back-to-heading t)
7070 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7072 (defun org-insert-heading-after-current ()
7073 "Insert a new heading with same level as current, after current subtree."
7074 (interactive)
7075 (org-back-to-heading)
7076 (org-insert-heading)
7077 (org-move-subtree-down)
7078 (end-of-line 1))
7080 (defun org-insert-heading-respect-content ()
7081 (interactive)
7082 (let ((org-insert-heading-respect-content t))
7083 (org-insert-heading t)))
7085 (defun org-insert-todo-heading-respect-content (&optional force-state)
7086 (interactive "P")
7087 (let ((org-insert-heading-respect-content t))
7088 (org-insert-todo-heading force-state t)))
7090 (defun org-insert-todo-heading (arg &optional force-heading)
7091 "Insert a new heading with the same level and TODO state as current heading.
7092 If the heading has no TODO state, or if the state is DONE, use the first
7093 state (TODO by default). Also with prefix arg, force first state."
7094 (interactive "P")
7095 (when (or force-heading (not (org-insert-item 'checkbox)))
7096 (org-insert-heading force-heading)
7097 (save-excursion
7098 (org-back-to-heading)
7099 (outline-previous-heading)
7100 (looking-at org-todo-line-regexp))
7101 (let*
7102 ((new-mark-x
7103 (if (or arg
7104 (not (match-beginning 2))
7105 (member (match-string 2) org-done-keywords))
7106 (car org-todo-keywords-1)
7107 (match-string 2)))
7108 (new-mark
7110 (run-hook-with-args-until-success
7111 'org-todo-get-default-hook new-mark-x nil)
7112 new-mark-x)))
7113 (beginning-of-line 1)
7114 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7115 (if org-treat-insert-todo-heading-as-state-change
7116 (org-todo new-mark)
7117 (insert new-mark " "))))
7118 (when org-provide-todo-statistics
7119 (org-update-parent-todo-statistics))))
7121 (defun org-insert-subheading (arg)
7122 "Insert a new subheading and demote it.
7123 Works for outline headings and for plain lists alike."
7124 (interactive "P")
7125 (org-insert-heading arg)
7126 (cond
7127 ((org-on-heading-p) (org-do-demote))
7128 ((org-at-item-p) (org-indent-item))))
7130 (defun org-insert-todo-subheading (arg)
7131 "Insert a new subheading with TODO keyword or checkbox and demote it.
7132 Works for outline headings and for plain lists alike."
7133 (interactive "P")
7134 (org-insert-todo-heading arg)
7135 (cond
7136 ((org-on-heading-p) (org-do-demote))
7137 ((org-at-item-p) (org-indent-item))))
7139 ;;; Promotion and Demotion
7141 (defvar org-after-demote-entry-hook nil
7142 "Hook run after an entry has been demoted.
7143 The cursor will be at the beginning of the entry.
7144 When a subtree is being demoted, the hook will be called for each node.")
7146 (defvar org-after-promote-entry-hook nil
7147 "Hook run after an entry has been promoted.
7148 The cursor will be at the beginning of the entry.
7149 When a subtree is being promoted, the hook will be called for each node.")
7151 (defun org-promote-subtree ()
7152 "Promote the entire subtree.
7153 See also `org-promote'."
7154 (interactive)
7155 (save-excursion
7156 (org-with-limited-levels (org-map-tree 'org-promote)))
7157 (org-fix-position-after-promote))
7159 (defun org-demote-subtree ()
7160 "Demote the entire subtree. See `org-demote'.
7161 See also `org-promote'."
7162 (interactive)
7163 (save-excursion
7164 (org-with-limited-levels (org-map-tree 'org-demote)))
7165 (org-fix-position-after-promote))
7168 (defun org-do-promote ()
7169 "Promote the current heading higher up the tree.
7170 If the region is active in `transient-mark-mode', promote all headings
7171 in the region."
7172 (interactive)
7173 (save-excursion
7174 (if (org-region-active-p)
7175 (org-map-region 'org-promote (region-beginning) (region-end))
7176 (org-promote)))
7177 (org-fix-position-after-promote))
7179 (defun org-do-demote ()
7180 "Demote the current heading lower down the tree.
7181 If the region is active in `transient-mark-mode', demote all headings
7182 in the region."
7183 (interactive)
7184 (save-excursion
7185 (if (org-region-active-p)
7186 (org-map-region 'org-demote (region-beginning) (region-end))
7187 (org-demote)))
7188 (org-fix-position-after-promote))
7190 (defun org-fix-position-after-promote ()
7191 "Make sure that after pro/demotion cursor position is right."
7192 (let ((pos (point)))
7193 (when (save-excursion
7194 (beginning-of-line 1)
7195 (looking-at org-todo-line-regexp)
7196 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7197 (cond ((eobp) (insert " "))
7198 ((eolp) (insert " "))
7199 ((equal (char-after) ?\ ) (forward-char 1))))))
7201 (defun org-current-level ()
7202 "Return the level of the current entry, or nil if before the first headline.
7203 The level is the number of stars at the beginning of the headline."
7204 (save-excursion
7205 (org-with-limited-levels
7206 (ignore-errors
7207 (org-back-to-heading t)
7208 (funcall outline-level)))))
7210 (defun org-get-previous-line-level ()
7211 "Return the outline depth of the last headline before the current line.
7212 Returns 0 for the first headline in the buffer, and nil if before the
7213 first headline."
7214 (let ((current-level (org-current-level))
7215 (prev-level (when (> (line-number-at-pos) 1)
7216 (save-excursion
7217 (beginning-of-line 0)
7218 (org-current-level)))))
7219 (cond ((null current-level) nil) ; Before first headline
7220 ((null prev-level) 0) ; At first headline
7221 (prev-level))))
7223 (defun org-reduced-level (l)
7224 "Compute the effective level of a heading.
7225 This takes into account the setting of `org-odd-levels-only'."
7226 (cond
7227 ((zerop l) 0)
7228 (org-odd-levels-only (1+ (floor (/ l 2))))
7229 (t l)))
7231 (defun org-level-increment ()
7232 "Return the number of stars that will be added or removed at a
7233 time to headlines when structure editing, based on the value of
7234 `org-odd-levels-only'."
7235 (if org-odd-levels-only 2 1))
7237 (defun org-get-valid-level (level &optional change)
7238 "Rectify a level change under the influence of `org-odd-levels-only'
7239 LEVEL is a current level, CHANGE is by how much the level should be
7240 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7241 even level numbers will become the next higher odd number."
7242 (if org-odd-levels-only
7243 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7244 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7245 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7246 (max 1 (+ level (or change 0)))))
7248 (if (boundp 'define-obsolete-function-alias)
7249 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7250 (define-obsolete-function-alias 'org-get-legal-level
7251 'org-get-valid-level)
7252 (define-obsolete-function-alias 'org-get-legal-level
7253 'org-get-valid-level "23.1")))
7255 (defun org-promote ()
7256 "Promote the current heading higher up the tree.
7257 If the region is active in `transient-mark-mode', promote all headings
7258 in the region."
7259 (org-back-to-heading t)
7260 (let* ((level (save-match-data (funcall outline-level)))
7261 (after-change-functions (remove 'flyspell-after-change-function
7262 after-change-functions))
7263 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7264 (diff (abs (- level (length up-head) -1))))
7265 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
7266 (replace-match up-head nil t)
7267 ;; Fixup tag positioning
7268 (and org-auto-align-tags (org-set-tags nil t))
7269 (if org-adapt-indentation (org-fixup-indentation (- diff)))
7270 (run-hooks 'org-after-promote-entry-hook)))
7272 (defun org-demote ()
7273 "Demote the current heading lower down the tree.
7274 If the region is active in `transient-mark-mode', demote all headings
7275 in the region."
7276 (org-back-to-heading t)
7277 (let* ((level (save-match-data (funcall outline-level)))
7278 (after-change-functions (remove 'flyspell-after-change-function
7279 after-change-functions))
7280 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7281 (diff (abs (- level (length down-head) -1))))
7282 (replace-match down-head nil t)
7283 ;; Fixup tag positioning
7284 (and org-auto-align-tags (org-set-tags nil t))
7285 (if org-adapt-indentation (org-fixup-indentation diff))
7286 (run-hooks 'org-after-demote-entry-hook)))
7288 (defun org-cycle-level ()
7289 "Cycle the level of an empty headline through possible states.
7290 This goes first to child, then to parent, level, then up the hierarchy.
7291 After top level, it switches back to sibling level."
7292 (interactive)
7293 (let ((org-adapt-indentation nil))
7294 (when (org-point-at-end-of-empty-headline)
7295 (setq this-command 'org-cycle-level) ; Only needed for caching
7296 (let ((cur-level (org-current-level))
7297 (prev-level (org-get-previous-line-level)))
7298 (cond
7299 ;; If first headline in file, promote to top-level.
7300 ((= prev-level 0)
7301 (loop repeat (/ (- cur-level 1) (org-level-increment))
7302 do (org-do-promote)))
7303 ;; If same level as prev, demote one.
7304 ((= prev-level cur-level)
7305 (org-do-demote))
7306 ;; If parent is top-level, promote to top level if not already.
7307 ((= prev-level 1)
7308 (loop repeat (/ (- cur-level 1) (org-level-increment))
7309 do (org-do-promote)))
7310 ;; If top-level, return to prev-level.
7311 ((= cur-level 1)
7312 (loop repeat (/ (- prev-level 1) (org-level-increment))
7313 do (org-do-demote)))
7314 ;; If less than prev-level, promote one.
7315 ((< cur-level prev-level)
7316 (org-do-promote))
7317 ;; If deeper than prev-level, promote until higher than
7318 ;; prev-level.
7319 ((> cur-level prev-level)
7320 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7321 do (org-do-promote))))
7322 t))))
7324 (defun org-map-tree (fun)
7325 "Call FUN for every heading underneath the current one."
7326 (org-back-to-heading)
7327 (let ((level (funcall outline-level)))
7328 (save-excursion
7329 (funcall fun)
7330 (while (and (progn
7331 (outline-next-heading)
7332 (> (funcall outline-level) level))
7333 (not (eobp)))
7334 (funcall fun)))))
7336 (defun org-map-region (fun beg end)
7337 "Call FUN for every heading between BEG and END."
7338 (let ((org-ignore-region t))
7339 (save-excursion
7340 (setq end (copy-marker end))
7341 (goto-char beg)
7342 (if (and (re-search-forward org-outline-regexp-bol nil t)
7343 (< (point) end))
7344 (funcall fun))
7345 (while (and (progn
7346 (outline-next-heading)
7347 (< (point) end))
7348 (not (eobp)))
7349 (funcall fun)))))
7351 (defun org-fixup-indentation (diff)
7352 "Change the indentation in the current entry by DIFF.
7353 However, if any line in the current entry has no indentation, or if it
7354 would end up with no indentation after the change, nothing at all is done."
7355 (save-excursion
7356 (let* ((end (save-excursion (outline-next-heading)
7357 (point-marker)))
7358 ;; FIXME we should use `org-end-of-meta-data-and-drawers'
7359 ;; here but it matches misplaced :END:...
7360 (drawer-end (save-excursion
7361 (and (re-search-forward
7362 org-property-end-re end t)
7363 (match-end 0))))
7364 (prohibit (if (> diff 0)
7365 "^\\S-"
7366 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7367 col)
7368 (while (re-search-forward
7369 (concat "\\(" (regexp-opt org-all-time-keywords)
7370 "\\|" "^[ \t]*" org-tsr-regexp-both "*$"
7371 "\\|" "^[ \t]*:[a-zA-Z][a-zA-Z0-9_]*:.*$"
7372 "\\)") (or drawer-end end) t)
7373 (beginning-of-line)
7374 (when (looking-at "^[ \t]+")
7375 (goto-char (match-end 0))
7376 (setq col (current-column))
7377 (if (< diff 0) (replace-match ""))
7378 (org-indent-to-column (+ diff col))
7379 (if drawer-end (setq drawer-end (+ diff drawer-end))))
7380 (end-of-line))
7381 (unless (save-excursion (end-of-line 1)
7382 (re-search-forward prohibit end t))
7383 (while (and (< (point) end)
7384 (re-search-forward "^[ \t]+" end t))
7385 (goto-char (match-end 0))
7386 (setq col (current-column))
7387 (if (< diff 0) (replace-match ""))
7388 (org-indent-to-column (+ diff col))))
7389 (move-marker end nil))))
7391 (defun org-convert-to-odd-levels ()
7392 "Convert an org-mode file with all levels allowed to one with odd levels.
7393 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7394 level 5 etc."
7395 (interactive)
7396 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7397 (let ((outline-level 'org-outline-level)
7398 (org-odd-levels-only nil) n)
7399 (save-excursion
7400 (goto-char (point-min))
7401 (while (re-search-forward "^\\*\\*+ " nil t)
7402 (setq n (- (length (match-string 0)) 2))
7403 (while (>= (setq n (1- n)) 0)
7404 (org-demote))
7405 (end-of-line 1))))))
7407 (defun org-convert-to-oddeven-levels ()
7408 "Convert an org-mode file with only odd levels to one with odd/even levels.
7409 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7410 file contains a section with an even level, conversion would
7411 destroy the structure of the file. An error is signaled in this
7412 case."
7413 (interactive)
7414 (goto-char (point-min))
7415 ;; First check if there are no even levels
7416 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7417 (org-show-context t)
7418 (error "Not all levels are odd in this file. Conversion not possible"))
7419 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
7420 (let ((outline-regexp org-outline-regexp)
7421 (outline-level 'org-outline-level)
7422 (org-odd-levels-only nil) n)
7423 (save-excursion
7424 (goto-char (point-min))
7425 (while (re-search-forward "^\\*\\*+ " nil t)
7426 (setq n (/ (1- (length (match-string 0))) 2))
7427 (while (>= (setq n (1- n)) 0)
7428 (org-promote))
7429 (end-of-line 1))))))
7431 (defun org-tr-level (n)
7432 "Make N odd if required."
7433 (if org-odd-levels-only (1+ (/ n 2)) n))
7435 ;;; Vertical tree motion, cutting and pasting of subtrees
7437 (defun org-move-subtree-up (&optional arg)
7438 "Move the current subtree up past ARG headlines of the same level."
7439 (interactive "p")
7440 (org-move-subtree-down (- (prefix-numeric-value arg))))
7442 (defun org-move-subtree-down (&optional arg)
7443 "Move the current subtree down past ARG headlines of the same level."
7444 (interactive "p")
7445 (setq arg (prefix-numeric-value arg))
7446 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
7447 'org-get-last-sibling))
7448 (ins-point (make-marker))
7449 (cnt (abs arg))
7450 (col (current-column))
7451 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
7452 ;; Select the tree
7453 (org-back-to-heading)
7454 (setq beg0 (point))
7455 (save-excursion
7456 (setq ne-beg (org-back-over-empty-lines))
7457 (setq beg (point)))
7458 (save-match-data
7459 (save-excursion (outline-end-of-heading)
7460 (setq folded (outline-invisible-p)))
7461 (outline-end-of-subtree))
7462 (outline-next-heading)
7463 (setq ne-end (org-back-over-empty-lines))
7464 (setq end (point))
7465 (goto-char beg0)
7466 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
7467 ;; include less whitespace
7468 (save-excursion
7469 (goto-char beg)
7470 (forward-line (- ne-beg ne-end))
7471 (setq beg (point))))
7472 ;; Find insertion point, with error handling
7473 (while (> cnt 0)
7474 (or (and (funcall movfunc) (looking-at org-outline-regexp))
7475 (progn (goto-char beg0)
7476 (error "Cannot move past superior level or buffer limit")))
7477 (setq cnt (1- cnt)))
7478 (if (> arg 0)
7479 ;; Moving forward - still need to move over subtree
7480 (progn (org-end-of-subtree t t)
7481 (save-excursion
7482 (org-back-over-empty-lines)
7483 (or (bolp) (newline)))))
7484 (setq ne-ins (org-back-over-empty-lines))
7485 (move-marker ins-point (point))
7486 (setq txt (buffer-substring beg end))
7487 (org-save-markers-in-region beg end)
7488 (delete-region beg end)
7489 (org-remove-empty-overlays-at beg)
7490 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
7491 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
7492 (and (not (bolp)) (looking-at "\n") (forward-char 1))
7493 (let ((bbb (point)))
7494 (insert-before-markers txt)
7495 (org-reinstall-markers-in-region bbb)
7496 (move-marker ins-point bbb))
7497 (or (bolp) (insert "\n"))
7498 (setq ins-end (point))
7499 (goto-char ins-point)
7500 (org-skip-whitespace)
7501 (when (and (< arg 0)
7502 (org-first-sibling-p)
7503 (> ne-ins ne-beg))
7504 ;; Move whitespace back to beginning
7505 (save-excursion
7506 (goto-char ins-end)
7507 (let ((kill-whole-line t))
7508 (kill-line (- ne-ins ne-beg)) (point)))
7509 (insert (make-string (- ne-ins ne-beg) ?\n)))
7510 (move-marker ins-point nil)
7511 (if folded
7512 (hide-subtree)
7513 (org-show-entry)
7514 (show-children)
7515 (org-cycle-hide-drawers 'children))
7516 (org-clean-visibility-after-subtree-move)
7517 ;; move back to the initial column we were at
7518 (move-to-column col)))
7520 (defvar org-subtree-clip ""
7521 "Clipboard for cut and paste of subtrees.
7522 This is actually only a copy of the kill, because we use the normal kill
7523 ring. We need it to check if the kill was created by `org-copy-subtree'.")
7525 (defvar org-subtree-clip-folded nil
7526 "Was the last copied subtree folded?
7527 This is used to fold the tree back after pasting.")
7529 (defun org-cut-subtree (&optional n)
7530 "Cut the current subtree into the clipboard.
7531 With prefix arg N, cut this many sequential subtrees.
7532 This is a short-hand for marking the subtree and then cutting it."
7533 (interactive "p")
7534 (org-copy-subtree n 'cut))
7536 (defun org-copy-subtree (&optional n cut force-store-markers)
7537 "Cut the current subtree into the clipboard.
7538 With prefix arg N, cut this many sequential subtrees.
7539 This is a short-hand for marking the subtree and then copying it.
7540 If CUT is non-nil, actually cut the subtree.
7541 If FORCE-STORE-MARKERS is non-nil, store the relative locations
7542 of some markers in the region, even if CUT is non-nil. This is
7543 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
7544 (interactive "p")
7545 (let (beg end folded (beg0 (point)))
7546 (if (org-called-interactively-p 'any)
7547 (org-back-to-heading nil) ; take what looks like a subtree
7548 (org-back-to-heading t)) ; take what is really there
7549 (org-back-over-empty-lines)
7550 (setq beg (point))
7551 (skip-chars-forward " \t\r\n")
7552 (save-match-data
7553 (save-excursion (outline-end-of-heading)
7554 (setq folded (outline-invisible-p)))
7555 (condition-case nil
7556 (org-forward-same-level (1- n) t)
7557 (error nil))
7558 (org-end-of-subtree t t))
7559 (org-back-over-empty-lines)
7560 (setq end (point))
7561 (goto-char beg0)
7562 (when (> end beg)
7563 (setq org-subtree-clip-folded folded)
7564 (when (or cut force-store-markers)
7565 (org-save-markers-in-region beg end))
7566 (if cut (kill-region beg end) (copy-region-as-kill beg end))
7567 (setq org-subtree-clip (current-kill 0))
7568 (message "%s: Subtree(s) with %d characters"
7569 (if cut "Cut" "Copied")
7570 (length org-subtree-clip)))))
7572 (defun org-paste-subtree (&optional level tree for-yank)
7573 "Paste the clipboard as a subtree, with modification of headline level.
7574 The entire subtree is promoted or demoted in order to match a new headline
7575 level.
7577 If the cursor is at the beginning of a headline, the same level as
7578 that headline is used to paste the tree
7580 If not, the new level is derived from the *visible* headings
7581 before and after the insertion point, and taken to be the inferior headline
7582 level of the two. So if the previous visible heading is level 3 and the
7583 next is level 4 (or vice versa), level 4 will be used for insertion.
7584 This makes sure that the subtree remains an independent subtree and does
7585 not swallow low level entries.
7587 You can also force a different level, either by using a numeric prefix
7588 argument, or by inserting the heading marker by hand. For example, if the
7589 cursor is after \"*****\", then the tree will be shifted to level 5.
7591 If optional TREE is given, use this text instead of the kill ring.
7593 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
7594 move back over whitespace before inserting, and move point to the end of
7595 the inserted text when done."
7596 (interactive "P")
7597 (setq tree (or tree (and kill-ring (current-kill 0))))
7598 (unless (org-kill-is-subtree-p tree)
7599 (error "%s"
7600 (substitute-command-keys
7601 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
7602 (org-with-limited-levels
7603 (let* ((visp (not (outline-invisible-p)))
7604 (txt tree)
7605 (^re_ (concat "\\(\\*+\\)[ \t]*"))
7606 (old-level (if (string-match org-outline-regexp-bol txt)
7607 (- (match-end 0) (match-beginning 0) 1)
7608 -1))
7609 (force-level (cond (level (prefix-numeric-value level))
7610 ((and (looking-at "[ \t]*$")
7611 (string-match
7612 "^\\*+$" (buffer-substring
7613 (point-at-bol) (point))))
7614 (- (match-end 1) (match-beginning 1)))
7615 ((and (bolp)
7616 (looking-at org-outline-regexp))
7617 (- (match-end 0) (point) 1))
7618 (t nil)))
7619 (previous-level (save-excursion
7620 (condition-case nil
7621 (progn
7622 (outline-previous-visible-heading 1)
7623 (if (looking-at ^re_)
7624 (- (match-end 0) (match-beginning 0) 1)
7626 (error 1))))
7627 (next-level (save-excursion
7628 (condition-case nil
7629 (progn
7630 (or (looking-at org-outline-regexp)
7631 (outline-next-visible-heading 1))
7632 (if (looking-at ^re_)
7633 (- (match-end 0) (match-beginning 0) 1)
7635 (error 1))))
7636 (new-level (or force-level (max previous-level next-level)))
7637 (shift (if (or (= old-level -1)
7638 (= new-level -1)
7639 (= old-level new-level))
7641 (- new-level old-level)))
7642 (delta (if (> shift 0) -1 1))
7643 (func (if (> shift 0) 'org-demote 'org-promote))
7644 (org-odd-levels-only nil)
7645 beg end newend)
7646 ;; Remove the forced level indicator
7647 (if force-level
7648 (delete-region (point-at-bol) (point)))
7649 ;; Paste
7650 (beginning-of-line (if (bolp) 1 2))
7651 (unless for-yank (org-back-over-empty-lines))
7652 (setq beg (point))
7653 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
7654 (insert-before-markers txt)
7655 (unless (string-match "\n\\'" txt) (insert "\n"))
7656 (setq newend (point))
7657 (org-reinstall-markers-in-region beg)
7658 (setq end (point))
7659 (goto-char beg)
7660 (skip-chars-forward " \t\n\r")
7661 (setq beg (point))
7662 (if (and (outline-invisible-p) visp)
7663 (save-excursion (outline-show-heading)))
7664 ;; Shift if necessary
7665 (unless (= shift 0)
7666 (save-restriction
7667 (narrow-to-region beg end)
7668 (while (not (= shift 0))
7669 (org-map-region func (point-min) (point-max))
7670 (setq shift (+ delta shift)))
7671 (goto-char (point-min))
7672 (setq newend (point-max))))
7673 (when (or (org-called-interactively-p 'interactive) for-yank)
7674 (message "Clipboard pasted as level %d subtree" new-level))
7675 (if (and (not for-yank) ; in this case, org-yank will decide about folding
7676 kill-ring
7677 (eq org-subtree-clip (current-kill 0))
7678 org-subtree-clip-folded)
7679 ;; The tree was folded before it was killed/copied
7680 (hide-subtree))
7681 (and for-yank (goto-char newend)))))
7683 (defun org-kill-is-subtree-p (&optional txt)
7684 "Check if the current kill is an outline subtree, or a set of trees.
7685 Returns nil if kill does not start with a headline, or if the first
7686 headline level is not the largest headline level in the tree.
7687 So this will actually accept several entries of equal levels as well,
7688 which is OK for `org-paste-subtree'.
7689 If optional TXT is given, check this string instead of the current kill."
7690 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
7691 (re (org-get-limited-outline-regexp))
7692 (^re (concat "^" re))
7693 (start-level (and kill
7694 (string-match
7695 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
7696 kill)
7697 (- (match-end 2) (match-beginning 2) 1)))
7698 (start (1+ (or (match-beginning 2) -1))))
7699 (if (not start-level)
7700 (progn
7701 nil) ;; does not even start with a heading
7702 (catch 'exit
7703 (while (setq start (string-match ^re kill (1+ start)))
7704 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
7705 (throw 'exit nil)))
7706 t))))
7708 (defvar org-markers-to-move nil
7709 "Markers that should be moved with a cut-and-paste operation.
7710 Those markers are stored together with their positions relative to
7711 the start of the region.")
7713 (defun org-save-markers-in-region (beg end)
7714 "Check markers in region.
7715 If these markers are between BEG and END, record their position relative
7716 to BEG, so that after moving the block of text, we can put the markers back
7717 into place.
7718 This function gets called just before an entry or tree gets cut from the
7719 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
7720 called immediately, to move the markers with the entries."
7721 (setq org-markers-to-move nil)
7722 (when (featurep 'org-clock)
7723 (org-clock-save-markers-for-cut-and-paste beg end))
7724 (when (featurep 'org-agenda)
7725 (org-agenda-save-markers-for-cut-and-paste beg end)))
7727 (defun org-check-and-save-marker (marker beg end)
7728 "Check if MARKER is between BEG and END.
7729 If yes, remember the marker and the distance to BEG."
7730 (when (and (marker-buffer marker)
7731 (equal (marker-buffer marker) (current-buffer)))
7732 (if (and (>= marker beg) (< marker end))
7733 (push (cons marker (- marker beg)) org-markers-to-move))))
7735 (defun org-reinstall-markers-in-region (beg)
7736 "Move all remembered markers to their position relative to BEG."
7737 (mapc (lambda (x)
7738 (move-marker (car x) (+ beg (cdr x))))
7739 org-markers-to-move)
7740 (setq org-markers-to-move nil))
7742 (defun org-narrow-to-subtree ()
7743 "Narrow buffer to the current subtree."
7744 (interactive)
7745 (save-excursion
7746 (save-match-data
7747 (org-with-limited-levels
7748 (narrow-to-region
7749 (progn (org-back-to-heading t) (point))
7750 (progn (org-end-of-subtree t t)
7751 (if (and (org-on-heading-p) (not (eobp))) (backward-char 1))
7752 (point)))))))
7754 (defun org-narrow-to-block ()
7755 "Narrow buffer to the current block."
7756 (interactive)
7757 (let* ((case-fold-search t)
7758 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
7759 "^[ \t]*#\\+end_.*")))
7760 (if blockp
7761 (narrow-to-region (car blockp) (cdr blockp))
7762 (error "Not in a block"))))
7764 (eval-when-compile
7765 (defvar org-property-drawer-re))
7767 (defvar org-property-start-re) ;; defined below
7768 (defun org-clone-subtree-with-time-shift (n &optional shift)
7769 "Clone the task (subtree) at point N times.
7770 The clones will be inserted as siblings.
7772 In interactive use, the user will be prompted for the number of
7773 clones to be produced, and for a time SHIFT, which may be a
7774 repeater as used in time stamps, for example `+3d'.
7776 When a valid repeater is given and the entry contains any time
7777 stamps, the clones will become a sequence in time, with time
7778 stamps in the subtree shifted for each clone produced. If SHIFT
7779 is nil or the empty string, time stamps will be left alone. The
7780 ID property of the original subtree is removed.
7782 If the original subtree did contain time stamps with a repeater,
7783 the following will happen:
7784 - the repeater will be removed in each clone
7785 - an additional clone will be produced, with the current, unshifted
7786 date(s) in the entry.
7787 - the original entry will be placed *after* all the clones, with
7788 repeater intact.
7789 - the start days in the repeater in the original entry will be shifted
7790 to past the last clone.
7791 I this way you can spell out a number of instances of a repeating task,
7792 and still retain the repeater to cover future instances of the task."
7793 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
7794 (let (beg end template task idprop
7795 shift-n shift-what doshift nmin nmax (n-no-remove -1))
7796 (if (not (and (integerp n) (> n 0)))
7797 (error "Invalid number of replications %s" n))
7798 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
7799 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
7800 shift)))
7801 (error "Invalid shift specification %s" shift))
7802 (when doshift
7803 (setq shift-n (string-to-number (match-string 1 shift))
7804 shift-what (cdr (assoc (match-string 2 shift)
7805 '(("d" . day) ("w" . week)
7806 ("m" . month) ("y" . year))))))
7807 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
7808 (setq nmin 1 nmax n)
7809 (org-back-to-heading t)
7810 (setq beg (point))
7811 (setq idprop (org-entry-get nil "ID"))
7812 (org-end-of-subtree t t)
7813 (or (bolp) (insert "\n"))
7814 (setq end (point))
7815 (setq template (buffer-substring beg end))
7816 ;; Remove clocks and empty drawers
7817 (with-temp-buffer
7818 (insert template)
7819 (goto-char (point-min))
7820 (while (re-search-forward
7821 "^[ \t]*CLOCK:.*$" (save-excursion (org-end-of-subtree t t)) t)
7822 (replace-match "")
7823 (kill-whole-line))
7824 (goto-char (point-min))
7825 (while (re-search-forward
7826 (concat "^[ \t]*:" (regexp-opt org-drawers) ":[ \t]*$") nil t)
7827 (mapc (lambda(d) (org-remove-empty-drawer-at d (point))) org-drawers))
7828 (setq template (buffer-substring (point-min) (point-max))))
7829 (when (and doshift
7830 (string-match "<[^<>\n]+ \\+[0-9]+[dwmy][^<>\n]*>" template))
7831 (delete-region beg end)
7832 (setq end beg)
7833 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
7834 (goto-char end)
7835 (loop for n from nmin to nmax do
7836 ;; prepare clone
7837 (with-temp-buffer
7838 (insert template)
7839 (org-mode)
7840 (goto-char (point-min))
7841 (and idprop (if org-clone-delete-id
7842 (org-entry-delete nil "ID")
7843 (org-id-get-create t)))
7844 (while (re-search-forward org-property-start-re nil t)
7845 (org-remove-empty-drawer-at "PROPERTIES" (point)))
7846 (goto-char (point-min))
7847 (when doshift
7848 (while (re-search-forward org-ts-regexp-both nil t)
7849 (org-timestamp-change (* n shift-n) shift-what))
7850 (unless (= n n-no-remove)
7851 (goto-char (point-min))
7852 (while (re-search-forward org-ts-regexp nil t)
7853 (save-excursion
7854 (goto-char (match-beginning 0))
7855 (if (looking-at "<[^<>\n]+\\( +\\+[0-9]+[dwmy]\\)")
7856 (delete-region (match-beginning 1) (match-end 1)))))))
7857 (setq task (buffer-string)))
7858 (insert task))
7859 (goto-char beg)))
7861 ;;; Outline Sorting
7863 (defun org-sort (with-case)
7864 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
7865 Optional argument WITH-CASE means sort case-sensitively.
7866 With a double prefix argument, also remove duplicate entries."
7867 (interactive "P")
7868 (cond
7869 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
7870 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
7872 (org-call-with-arg 'org-sort-entries with-case))))
7874 (defun org-sort-remove-invisible (s)
7875 (remove-text-properties 0 (length s) org-rm-props s)
7876 (while (string-match org-bracket-link-regexp s)
7877 (setq s (replace-match (if (match-end 2)
7878 (match-string 3 s)
7879 (match-string 1 s)) t t s)))
7882 (defvar org-priority-regexp) ; defined later in the file
7884 (defvar org-after-sorting-entries-or-items-hook nil
7885 "Hook that is run after a bunch of entries or items have been sorted.
7886 When children are sorted, the cursor is in the parent line when this
7887 hook gets called. When a region or a plain list is sorted, the cursor
7888 will be in the first entry of the sorted region/list.")
7890 (defun org-sort-entries
7891 (&optional with-case sorting-type getkey-func compare-func property)
7892 "Sort entries on a certain level of an outline tree.
7893 If there is an active region, the entries in the region are sorted.
7894 Else, if the cursor is before the first entry, sort the top-level items.
7895 Else, the children of the entry at point are sorted.
7897 Sorting can be alphabetically, numerically, by date/time as given by
7898 a time stamp, by a property or by priority.
7900 The command prompts for the sorting type unless it has been given to the
7901 function through the SORTING-TYPE argument, which needs to be a character,
7902 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F). Here is the
7903 precise meaning of each character:
7905 n Numerically, by converting the beginning of the entry/item to a number.
7906 a Alphabetically, ignoring the TODO keyword and the priority, if any.
7907 t By date/time, either the first active time stamp in the entry, or, if
7908 none exist, by the first inactive one.
7909 s By the scheduled date/time.
7910 d By deadline date/time.
7911 c By creation time, which is assumed to be the first inactive time stamp
7912 at the beginning of a line.
7913 p By priority according to the cookie.
7914 r By the value of a property.
7916 Capital letters will reverse the sort order.
7918 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
7919 called with point at the beginning of the record. It must return either
7920 a string or a number that should serve as the sorting key for that record.
7922 Comparing entries ignores case by default. However, with an optional argument
7923 WITH-CASE, the sorting considers case as well."
7924 (interactive "P")
7925 (let ((case-func (if with-case 'identity 'downcase))
7926 start beg end stars re re2
7927 txt what tmp)
7928 ;; Find beginning and end of region to sort
7929 (cond
7930 ((org-region-active-p)
7931 ;; we will sort the region
7932 (setq end (region-end)
7933 what "region")
7934 (goto-char (region-beginning))
7935 (if (not (org-on-heading-p)) (outline-next-heading))
7936 (setq start (point)))
7937 ((or (org-on-heading-p)
7938 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
7939 ;; we will sort the children of the current headline
7940 (org-back-to-heading)
7941 (setq start (point)
7942 end (progn (org-end-of-subtree t t)
7943 (or (bolp) (insert "\n"))
7944 (org-back-over-empty-lines)
7945 (point))
7946 what "children")
7947 (goto-char start)
7948 (show-subtree)
7949 (outline-next-heading))
7951 ;; we will sort the top-level entries in this file
7952 (goto-char (point-min))
7953 (or (org-on-heading-p) (outline-next-heading))
7954 (setq start (point))
7955 (goto-char (point-max))
7956 (beginning-of-line 1)
7957 (when (looking-at ".*?\\S-")
7958 ;; File ends in a non-white line
7959 (end-of-line 1)
7960 (insert "\n"))
7961 (setq end (point-max))
7962 (setq what "top-level")
7963 (goto-char start)
7964 (show-all)))
7966 (setq beg (point))
7967 (if (>= beg end) (error "Nothing to sort"))
7969 (looking-at "\\(\\*+\\)")
7970 (setq stars (match-string 1)
7971 re (concat "^" (regexp-quote stars) " +")
7972 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
7973 txt (buffer-substring beg end))
7974 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
7975 (if (and (not (equal stars "*")) (string-match re2 txt))
7976 (error "Region to sort contains a level above the first entry"))
7978 (unless sorting-type
7979 (message
7980 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
7981 [t]ime [s]cheduled [d]eadline [c]reated
7982 A/N/T/S/D/C/P/O/F means reversed:"
7983 what)
7984 (setq sorting-type (read-char-exclusive))
7986 (and (= (downcase sorting-type) ?f)
7987 (setq getkey-func
7988 (org-icompleting-read "Sort using function: "
7989 obarray 'fboundp t nil nil))
7990 (setq getkey-func (intern getkey-func)))
7992 (and (= (downcase sorting-type) ?r)
7993 (setq property
7994 (org-icompleting-read "Property: "
7995 (mapcar 'list (org-buffer-property-keys t))
7996 nil t))))
7998 (message "Sorting entries...")
8000 (save-restriction
8001 (narrow-to-region start end)
8002 (let ((dcst (downcase sorting-type))
8003 (case-fold-search nil)
8004 (now (current-time)))
8005 (sort-subr
8006 (/= dcst sorting-type)
8007 ;; This function moves to the beginning character of the "record" to
8008 ;; be sorted.
8009 (lambda nil
8010 (if (re-search-forward re nil t)
8011 (goto-char (match-beginning 0))
8012 (goto-char (point-max))))
8013 ;; This function moves to the last character of the "record" being
8014 ;; sorted.
8015 (lambda nil
8016 (save-match-data
8017 (condition-case nil
8018 (outline-forward-same-level 1)
8019 (error
8020 (goto-char (point-max))))))
8021 ;; This function returns the value that gets sorted against.
8022 (lambda nil
8023 (cond
8024 ((= dcst ?n)
8025 (if (looking-at org-complex-heading-regexp)
8026 (string-to-number (match-string 4))
8027 nil))
8028 ((= dcst ?a)
8029 (if (looking-at org-complex-heading-regexp)
8030 (funcall case-func (match-string 4))
8031 nil))
8032 ((= dcst ?t)
8033 (let ((end (save-excursion (outline-next-heading) (point))))
8034 (if (or (re-search-forward org-ts-regexp end t)
8035 (re-search-forward org-ts-regexp-both end t))
8036 (org-time-string-to-seconds (match-string 0))
8037 (org-float-time now))))
8038 ((= dcst ?c)
8039 (let ((end (save-excursion (outline-next-heading) (point))))
8040 (if (re-search-forward
8041 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8042 end t)
8043 (org-time-string-to-seconds (match-string 0))
8044 (org-float-time now))))
8045 ((= dcst ?s)
8046 (let ((end (save-excursion (outline-next-heading) (point))))
8047 (if (re-search-forward org-scheduled-time-regexp end t)
8048 (org-time-string-to-seconds (match-string 1))
8049 (org-float-time now))))
8050 ((= dcst ?d)
8051 (let ((end (save-excursion (outline-next-heading) (point))))
8052 (if (re-search-forward org-deadline-time-regexp end t)
8053 (org-time-string-to-seconds (match-string 1))
8054 (org-float-time now))))
8055 ((= dcst ?p)
8056 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8057 (string-to-char (match-string 2))
8058 org-default-priority))
8059 ((= dcst ?r)
8060 (or (org-entry-get nil property) ""))
8061 ((= dcst ?o)
8062 (if (looking-at org-complex-heading-regexp)
8063 (- 9999 (length (member (match-string 2)
8064 org-todo-keywords-1)))))
8065 ((= dcst ?f)
8066 (if getkey-func
8067 (progn
8068 (setq tmp (funcall getkey-func))
8069 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8070 tmp)
8071 (error "Invalid key function `%s'" getkey-func)))
8072 (t (error "Invalid sorting type `%c'" sorting-type))))
8074 (cond
8075 ((= dcst ?a) 'string<)
8076 ((= dcst ?f) compare-func)
8077 ((member dcst '(?p ?t ?s ?d ?c)) '<)
8078 (t nil)))))
8079 (run-hooks 'org-after-sorting-entries-or-items-hook)
8080 (message "Sorting entries...done")))
8082 (defun org-do-sort (table what &optional with-case sorting-type)
8083 "Sort TABLE of WHAT according to SORTING-TYPE.
8084 The user will be prompted for the SORTING-TYPE if the call to this
8085 function does not specify it. WHAT is only for the prompt, to indicate
8086 what is being sorted. The sorting key will be extracted from
8087 the car of the elements of the table.
8088 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8089 (unless sorting-type
8090 (message
8091 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
8092 what)
8093 (setq sorting-type (read-char-exclusive)))
8094 (let ((dcst (downcase sorting-type))
8095 extractfun comparefun)
8096 ;; Define the appropriate functions
8097 (cond
8098 ((= dcst ?n)
8099 (setq extractfun 'string-to-number
8100 comparefun (if (= dcst sorting-type) '< '>)))
8101 ((= dcst ?a)
8102 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8103 (lambda(x) (downcase (org-sort-remove-invisible x))))
8104 comparefun (if (= dcst sorting-type)
8105 'string<
8106 (lambda (a b) (and (not (string< a b))
8107 (not (string= a b)))))))
8108 ((= dcst ?t)
8109 (setq extractfun
8110 (lambda (x)
8111 (if (or (string-match org-ts-regexp x)
8112 (string-match org-ts-regexp-both x))
8113 (org-float-time
8114 (org-time-string-to-time (match-string 0 x)))
8116 comparefun (if (= dcst sorting-type) '< '>)))
8117 (t (error "Invalid sorting type `%c'" sorting-type)))
8119 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8120 table)
8121 (lambda (a b) (funcall comparefun (car a) (car b))))))
8124 ;;; The orgstruct minor mode
8126 ;; Define a minor mode which can be used in other modes in order to
8127 ;; integrate the org-mode structure editing commands.
8129 ;; This is really a hack, because the org-mode structure commands use
8130 ;; keys which normally belong to the major mode. Here is how it
8131 ;; works: The minor mode defines all the keys necessary to operate the
8132 ;; structure commands, but wraps the commands into a function which
8133 ;; tests if the cursor is currently at a headline or a plain list
8134 ;; item. If that is the case, the structure command is used,
8135 ;; temporarily setting many Org-mode variables like regular
8136 ;; expressions for filling etc. However, when any of those keys is
8137 ;; used at a different location, function uses `key-binding' to look
8138 ;; up if the key has an associated command in another currently active
8139 ;; keymap (minor modes, major mode, global), and executes that
8140 ;; command. There might be problems if any of the keys is otherwise
8141 ;; used as a prefix key.
8143 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
8144 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
8145 ;; addresses this by checking explicitly for both bindings.
8147 (defvar orgstruct-mode-map (make-sparse-keymap)
8148 "Keymap for the minor `orgstruct-mode'.")
8150 (defvar org-local-vars nil
8151 "List of local variables, for use by `orgstruct-mode'.")
8153 ;;;###autoload
8154 (define-minor-mode orgstruct-mode
8155 "Toggle the minor mode `orgstruct-mode'.
8156 This mode is for using Org-mode structure commands in other
8157 modes. The following keys behave as if Org-mode were active, if
8158 the cursor is on a headline, or on a plain list item (both as
8159 defined by Org-mode).
8161 M-up Move entry/item up
8162 M-down Move entry/item down
8163 M-left Promote
8164 M-right Demote
8165 M-S-up Move entry/item up
8166 M-S-down Move entry/item down
8167 M-S-left Promote subtree
8168 M-S-right Demote subtree
8169 M-q Fill paragraph and items like in Org-mode
8170 C-c ^ Sort entries
8171 C-c - Cycle list bullet
8172 TAB Cycle item visibility
8173 M-RET Insert new heading/item
8174 S-M-RET Insert new TODO heading / Checkbox item
8175 C-c C-c Set tags / toggle checkbox"
8176 nil " OrgStruct" nil
8177 (org-load-modules-maybe)
8178 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
8180 ;;;###autoload
8181 (defun turn-on-orgstruct ()
8182 "Unconditionally turn on `orgstruct-mode'."
8183 (orgstruct-mode 1))
8185 (defun orgstruct++-mode (&optional arg)
8186 "Toggle `orgstruct-mode', the enhanced version of it.
8187 In addition to setting orgstruct-mode, this also exports all indentation
8188 and autofilling variables from org-mode into the buffer. It will also
8189 recognize item context in multiline items.
8190 Note that turning off orgstruct-mode will *not* remove the
8191 indentation/paragraph settings. This can only be done by refreshing the
8192 major mode, for example with \\[normal-mode]."
8193 (interactive "P")
8194 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8195 (if (< arg 1)
8196 (orgstruct-mode -1)
8197 (orgstruct-mode 1)
8198 (let (var val)
8199 (mapc
8200 (lambda (x)
8201 (when (string-match
8202 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
8203 (symbol-name (car x)))
8204 (setq var (car x) val (nth 1 x))
8205 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8206 org-local-vars)
8207 (org-set-local 'orgstruct-is-++ t))))
8209 (defvar orgstruct-is-++ nil
8210 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8211 (make-variable-buffer-local 'orgstruct-is-++)
8213 ;;;###autoload
8214 (defun turn-on-orgstruct++ ()
8215 "Unconditionally turn on `orgstruct++-mode'."
8216 (orgstruct++-mode 1))
8218 (defun orgstruct-error ()
8219 "Error when there is no default binding for a structure key."
8220 (interactive)
8221 (error "This key has no function outside structure elements"))
8223 (defun orgstruct-setup ()
8224 "Setup orgstruct keymaps."
8225 (let ((nfunc 0)
8226 (bindings
8227 (list
8228 '([(meta up)] org-metaup)
8229 '([(meta down)] org-metadown)
8230 '([(meta left)] org-metaleft)
8231 '([(meta right)] org-metaright)
8232 '([(meta shift up)] org-shiftmetaup)
8233 '([(meta shift down)] org-shiftmetadown)
8234 '([(meta shift left)] org-shiftmetaleft)
8235 '([(meta shift right)] org-shiftmetaright)
8236 '([?\e (up)] org-metaup)
8237 '([?\e (down)] org-metadown)
8238 '([?\e (left)] org-metaleft)
8239 '([?\e (right)] org-metaright)
8240 '([?\e (shift up)] org-shiftmetaup)
8241 '([?\e (shift down)] org-shiftmetadown)
8242 '([?\e (shift left)] org-shiftmetaleft)
8243 '([?\e (shift right)] org-shiftmetaright)
8244 '([(shift up)] org-shiftup)
8245 '([(shift down)] org-shiftdown)
8246 '([(shift left)] org-shiftleft)
8247 '([(shift right)] org-shiftright)
8248 '("\C-c\C-c" org-ctrl-c-ctrl-c)
8249 '("\M-q" fill-paragraph)
8250 '("\C-c^" org-sort)
8251 '("\C-c-" org-cycle-list-bullet)))
8252 elt key fun cmd)
8253 (while (setq elt (pop bindings))
8254 (setq nfunc (1+ nfunc))
8255 (setq key (org-key (car elt))
8256 fun (nth 1 elt)
8257 cmd (orgstruct-make-binding fun nfunc key))
8258 (org-defkey orgstruct-mode-map key cmd))
8260 ;; Special treatment needed for TAB and RET
8261 (org-defkey orgstruct-mode-map [(tab)]
8262 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
8263 (org-defkey orgstruct-mode-map "\C-i"
8264 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
8266 (org-defkey orgstruct-mode-map "\M-\C-m"
8267 (orgstruct-make-binding 'org-insert-heading 105
8268 "\M-\C-m" [(meta return)]))
8269 (org-defkey orgstruct-mode-map [(meta return)]
8270 (orgstruct-make-binding 'org-insert-heading 106
8271 [(meta return)] "\M-\C-m"))
8273 (org-defkey orgstruct-mode-map [(shift meta return)]
8274 (orgstruct-make-binding 'org-insert-todo-heading 107
8275 [(meta return)] "\M-\C-m"))
8277 (org-defkey orgstruct-mode-map "\e\C-m"
8278 (orgstruct-make-binding 'org-insert-heading 108
8279 "\e\C-m" [?\e (return)]))
8280 (org-defkey orgstruct-mode-map [?\e (return)]
8281 (orgstruct-make-binding 'org-insert-heading 109
8282 [?\e (return)] "\e\C-m"))
8283 (org-defkey orgstruct-mode-map [?\e (shift return)]
8284 (orgstruct-make-binding 'org-insert-todo-heading 110
8285 [?\e (return)] "\e\C-m"))
8287 (unless org-local-vars
8288 (setq org-local-vars (org-get-local-variables)))
8292 (defun orgstruct-make-binding (fun n &rest keys)
8293 "Create a function for binding in the structure minor mode.
8294 FUN is the command to call inside a table. N is used to create a unique
8295 command name. KEYS are keys that should be checked in for a command
8296 to execute outside of tables."
8297 (eval
8298 (list 'defun
8299 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
8300 '(arg)
8301 (concat "In Structure, run `" (symbol-name fun) "'.\n"
8302 "Outside of structure, run the binding of `"
8303 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
8304 "'.")
8305 '(interactive "p")
8306 (list 'if
8307 `(org-context-p 'headline 'item
8308 (and orgstruct-is-++
8309 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
8310 'item-body))
8311 (list 'org-run-like-in-org-mode (list 'quote fun))
8312 (list 'let '(orgstruct-mode)
8313 (list 'call-interactively
8314 (append '(or)
8315 (mapcar (lambda (k)
8316 (list 'key-binding k))
8317 keys)
8318 '('orgstruct-error))))))))
8320 (defun org-context-p (&rest contexts)
8321 "Check if local context is any of CONTEXTS.
8322 Possible values in the list of contexts are `table', `headline', and `item'."
8323 (let ((pos (point)))
8324 (goto-char (point-at-bol))
8325 (prog1 (or (and (memq 'table contexts)
8326 (looking-at "[ \t]*|"))
8327 (and (memq 'headline contexts)
8328 (looking-at org-outline-regexp))
8329 (and (memq 'item contexts)
8330 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
8331 (and (memq 'item-body contexts)
8332 (org-in-item-p)))
8333 (goto-char pos))))
8335 (defun org-get-local-variables ()
8336 "Return a list of all local variables in an org-mode buffer."
8337 (let (varlist)
8338 (with-current-buffer (get-buffer-create "*Org tmp*")
8339 (erase-buffer)
8340 (org-mode)
8341 (setq varlist (buffer-local-variables)))
8342 (kill-buffer "*Org tmp*")
8343 (delq nil
8344 (mapcar
8345 (lambda (x)
8346 (setq x
8347 (if (symbolp x)
8348 (list x)
8349 (list (car x) (list 'quote (cdr x)))))
8350 (if (string-match
8351 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
8352 (symbol-name (car x)))
8353 x nil))
8354 varlist))))
8356 (defun org-clone-local-variables (from-buffer &optional regexp)
8357 "Clone local variables from FROM-BUFFER.
8358 Optional argument REGEXP selects variables to clone."
8359 (mapc
8360 (lambda (pair)
8361 (and (symbolp (car pair))
8362 (or (null regexp)
8363 (string-match regexp (symbol-name (car pair))))
8364 (set (make-local-variable (car pair))
8365 (cdr pair))))
8366 (buffer-local-variables from-buffer)))
8368 ;;;###autoload
8369 (defun org-run-like-in-org-mode (cmd)
8370 "Run a command, pretending that the current buffer is in Org-mode.
8371 This will temporarily bind local variables that are typically bound in
8372 Org-mode to the values they have in Org-mode, and then interactively
8373 call CMD."
8374 (org-load-modules-maybe)
8375 (unless org-local-vars
8376 (setq org-local-vars (org-get-local-variables)))
8377 (eval (list 'let org-local-vars
8378 (list 'call-interactively (list 'quote cmd)))))
8380 ;;;; Archiving
8382 (defun org-get-category (&optional pos force-refresh)
8383 "Get the category applying to position POS."
8384 (if force-refresh (org-refresh-category-properties))
8385 (let ((pos (or pos (point))))
8386 (or (get-text-property pos 'org-category)
8387 (progn (org-refresh-category-properties)
8388 (get-text-property pos 'org-category)))))
8390 (defun org-refresh-category-properties ()
8391 "Refresh category text properties in the buffer."
8392 (let ((def-cat (cond
8393 ((null org-category)
8394 (if buffer-file-name
8395 (file-name-sans-extension
8396 (file-name-nondirectory buffer-file-name))
8397 "???"))
8398 ((symbolp org-category) (symbol-name org-category))
8399 (t org-category)))
8400 beg end cat pos optionp)
8401 (org-unmodified
8402 (save-excursion
8403 (save-restriction
8404 (widen)
8405 (goto-char (point-min))
8406 (put-text-property (point) (point-max) 'org-category def-cat)
8407 (while (re-search-forward
8408 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8409 (setq pos (match-end 0)
8410 optionp (equal (char-after (match-beginning 0)) ?#)
8411 cat (org-trim (match-string 2)))
8412 (if optionp
8413 (setq beg (point-at-bol) end (point-max))
8414 (org-back-to-heading t)
8415 (setq beg (point) end (org-end-of-subtree t t)))
8416 (put-text-property beg end 'org-category cat)
8417 (goto-char pos)))))))
8420 ;;;; Link Stuff
8422 ;;; Link abbreviations
8424 (defun org-link-expand-abbrev (link)
8425 "Apply replacements as defined in `org-link-abbrev-alist."
8426 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
8427 (let* ((key (match-string 1 link))
8428 (as (or (assoc key org-link-abbrev-alist-local)
8429 (assoc key org-link-abbrev-alist)))
8430 (tag (and (match-end 2) (match-string 3 link)))
8431 rpl)
8432 (if (not as)
8433 link
8434 (setq rpl (cdr as))
8435 (cond
8436 ((symbolp rpl) (funcall rpl tag))
8437 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
8438 ((string-match "%h" rpl)
8439 (replace-match (url-hexify-string (or tag "")) t t rpl))
8440 (t (concat rpl tag)))))
8441 link))
8443 ;;; Storing and inserting links
8445 (defvar org-insert-link-history nil
8446 "Minibuffer history for links inserted with `org-insert-link'.")
8448 (defvar org-stored-links nil
8449 "Contains the links stored with `org-store-link'.")
8451 (defvar org-store-link-plist nil
8452 "Plist with info about the most recently link created with `org-store-link'.")
8454 (defvar org-link-protocols nil
8455 "Link protocols added to Org-mode using `org-add-link-type'.")
8457 (defvar org-store-link-functions nil
8458 "List of functions that are called to create and store a link.
8459 Each function will be called in turn until one returns a non-nil
8460 value. Each function should check if it is responsible for creating
8461 this link (for example by looking at the major mode).
8462 If not, it must exit and return nil.
8463 If yes, it should return a non-nil value after a calling
8464 `org-store-link-props' with a list of properties and values.
8465 Special properties are:
8467 :type The link prefix, like \"http\". This must be given.
8468 :link The link, like \"http://www.astro.uva.nl/~dominik\".
8469 This is obligatory as well.
8470 :description Optional default description for the second pair
8471 of brackets in an Org-mode link. The user can still change
8472 this when inserting this link into an Org-mode buffer.
8474 In addition to these, any additional properties can be specified
8475 and then used in remember templates.")
8477 (defun org-add-link-type (type &optional follow export)
8478 "Add TYPE to the list of `org-link-types'.
8479 Re-compute all regular expressions depending on `org-link-types'
8481 FOLLOW and EXPORT are two functions.
8483 FOLLOW should take the link path as the single argument and do whatever
8484 is necessary to follow the link, for example find a file or display
8485 a mail message.
8487 EXPORT should format the link path for export to one of the export formats.
8488 It should be a function accepting three arguments:
8490 path the path of the link, the text after the prefix (like \"http:\")
8491 desc the description of the link, if any, or a description added by
8492 org-export-normalize-links if there is none
8493 format the export format, a symbol like `html' or `latex' or `ascii'..
8495 The function may use the FORMAT information to return different values
8496 depending on the format. The return value will be put literally into
8497 the exported file. If the return value is nil, this means Org should
8498 do what it normally does with links which do not have EXPORT defined.
8500 Org-mode has a built-in default for exporting links. If you are happy with
8501 this default, there is no need to define an export function for the link
8502 type. For a simple example of an export function, see `org-bbdb.el'."
8503 (add-to-list 'org-link-types type t)
8504 (org-make-link-regexps)
8505 (if (assoc type org-link-protocols)
8506 (setcdr (assoc type org-link-protocols) (list follow export))
8507 (push (list type follow export) org-link-protocols)))
8509 (defvar org-agenda-buffer-name)
8511 ;;;###autoload
8512 (defun org-store-link (arg)
8513 "\\<org-mode-map>Store an org-link to the current location.
8514 This link is added to `org-stored-links' and can later be inserted
8515 into an org-buffer with \\[org-insert-link].
8517 For some link types, a prefix arg is interpreted:
8518 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
8519 For file links, arg negates `org-context-in-file-links'."
8520 (interactive "P")
8521 (org-load-modules-maybe)
8522 (setq org-store-link-plist nil) ; reset
8523 (org-with-limited-levels
8524 (let (link cpltxt desc description search txt custom-id agenda-link)
8525 (cond
8527 ((run-hook-with-args-until-success 'org-store-link-functions)
8528 (setq link (plist-get org-store-link-plist :link)
8529 desc (or (plist-get org-store-link-plist :description) link)))
8531 ((equal (buffer-name) "*Org Edit Src Example*")
8532 (let (label gc)
8533 (while (or (not label)
8534 (save-excursion
8535 (save-restriction
8536 (widen)
8537 (goto-char (point-min))
8538 (re-search-forward
8539 (regexp-quote (format org-coderef-label-format label))
8540 nil t))))
8541 (when label (message "Label exists already") (sit-for 2))
8542 (setq label (read-string "Code line label: " label)))
8543 (end-of-line 1)
8544 (setq link (format org-coderef-label-format label))
8545 (setq gc (- 79 (length link)))
8546 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
8547 (insert link)
8548 (setq link (concat "(" label ")") desc nil)))
8550 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
8551 ;; We are in the agenda, link to referenced location
8552 (let ((m (or (get-text-property (point) 'org-hd-marker)
8553 (get-text-property (point) 'org-marker))))
8554 (when m
8555 (org-with-point-at m
8556 (setq agenda-link
8557 (if (org-called-interactively-p 'any)
8558 (call-interactively 'org-store-link)
8559 (org-store-link nil)))))))
8561 ((eq major-mode 'calendar-mode)
8562 (let ((cd (calendar-cursor-to-date)))
8563 (setq link
8564 (format-time-string
8565 (car org-time-stamp-formats)
8566 (apply 'encode-time
8567 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
8568 nil nil nil))))
8569 (org-store-link-props :type "calendar" :date cd)))
8571 ((eq major-mode 'w3-mode)
8572 (setq cpltxt (if (and (buffer-name)
8573 (not (string-match "Untitled" (buffer-name))))
8574 (buffer-name)
8575 (url-view-url t))
8576 link (org-make-link (url-view-url t)))
8577 (org-store-link-props :type "w3" :url (url-view-url t)))
8579 ((eq major-mode 'w3m-mode)
8580 (setq cpltxt (or w3m-current-title w3m-current-url)
8581 link (org-make-link w3m-current-url))
8582 (org-store-link-props :type "w3m" :url (url-view-url t)))
8584 ((setq search (run-hook-with-args-until-success
8585 'org-create-file-search-functions))
8586 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
8587 "::" search))
8588 (setq cpltxt (or description link)))
8590 ((eq major-mode 'image-mode)
8591 (setq cpltxt (concat "file:"
8592 (abbreviate-file-name buffer-file-name))
8593 link (org-make-link cpltxt))
8594 (org-store-link-props :type "image" :file buffer-file-name))
8596 ((eq major-mode 'dired-mode)
8597 ;; link to the file in the current line
8598 (let ((file (dired-get-filename nil t)))
8599 (setq file (if file
8600 (abbreviate-file-name
8601 (expand-file-name (dired-get-filename nil t)))
8602 ;; otherwise, no file so use current directory.
8603 default-directory))
8604 (setq cpltxt (concat "file:" file)
8605 link (org-make-link cpltxt))))
8607 ((and (buffer-file-name (buffer-base-buffer)) (org-mode-p))
8608 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
8609 (cond
8610 ((org-in-regexp "<<\\(.*?\\)>>")
8611 (setq cpltxt
8612 (concat "file:"
8613 (abbreviate-file-name
8614 (buffer-file-name (buffer-base-buffer)))
8615 "::" (match-string 1))
8616 link (org-make-link cpltxt)))
8617 ((and (featurep 'org-id)
8618 (or (eq org-link-to-org-use-id t)
8619 (and (eq org-link-to-org-use-id 'create-if-interactive)
8620 (org-called-interactively-p 'any))
8621 (and (eq org-link-to-org-use-id
8622 'create-if-interactive-and-no-custom-id)
8623 (org-called-interactively-p 'any)
8624 (not custom-id))
8625 (and org-link-to-org-use-id
8626 (org-entry-get nil "ID"))))
8627 ;; We can make a link using the ID.
8628 (setq link (condition-case nil
8629 (prog1 (org-id-store-link)
8630 (setq desc (plist-get org-store-link-plist
8631 :description)))
8632 (error
8633 ;; probably before first headline, link to file only
8634 (concat "file:"
8635 (abbreviate-file-name
8636 (buffer-file-name (buffer-base-buffer))))))))
8638 ;; Just link to current headline
8639 (setq cpltxt (concat "file:"
8640 (abbreviate-file-name
8641 (buffer-file-name (buffer-base-buffer)))))
8642 ;; Add a context search string
8643 (when (org-xor org-context-in-file-links arg)
8644 (setq txt (cond
8645 ((org-on-heading-p) nil)
8646 ((org-region-active-p)
8647 (buffer-substring (region-beginning) (region-end)))
8648 (t nil)))
8649 (when (or (null txt) (string-match "\\S-" txt))
8650 (setq cpltxt
8651 (concat cpltxt "::"
8652 (condition-case nil
8653 (org-make-org-heading-search-string txt)
8654 (error "")))
8655 desc (or (nth 4 (ignore-errors
8656 (org-heading-components))) "NONE"))))
8657 (if (string-match "::\\'" cpltxt)
8658 (setq cpltxt (substring cpltxt 0 -2)))
8659 (setq link (org-make-link cpltxt)))))
8661 ((buffer-file-name (buffer-base-buffer))
8662 ;; Just link to this file here.
8663 (setq cpltxt (concat "file:"
8664 (abbreviate-file-name
8665 (buffer-file-name (buffer-base-buffer)))))
8666 ;; Add a context string
8667 (when (org-xor org-context-in-file-links arg)
8668 (setq txt (if (org-region-active-p)
8669 (buffer-substring (region-beginning) (region-end))
8670 (buffer-substring (point-at-bol) (point-at-eol))))
8671 ;; Only use search option if there is some text.
8672 (when (string-match "\\S-" txt)
8673 (setq cpltxt
8674 (concat cpltxt "::" (org-make-org-heading-search-string txt))
8675 desc "NONE")))
8676 (setq link (org-make-link cpltxt)))
8678 ((org-called-interactively-p 'interactive)
8679 (error "Cannot link to a buffer which is not visiting a file"))
8681 (t (setq link nil)))
8683 (if (consp link) (setq cpltxt (car link) link (cdr link)))
8684 (setq link (or link cpltxt)
8685 desc (or desc cpltxt))
8686 (if (equal desc "NONE") (setq desc nil))
8688 (if (and (or (org-called-interactively-p 'any) executing-kbd-macro) link)
8689 (progn
8690 (setq org-stored-links
8691 (cons (list link desc) org-stored-links))
8692 (message "Stored: %s" (or desc link))
8693 (when custom-id
8694 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
8695 "::#" custom-id))
8696 (setq org-stored-links
8697 (cons (list link desc) org-stored-links))))
8698 (or agenda-link (and link (org-make-link-string link desc)))))))
8700 (defun org-store-link-props (&rest plist)
8701 "Store link properties, extract names and addresses."
8702 (let (x adr)
8703 (when (setq x (plist-get plist :from))
8704 (setq adr (mail-extract-address-components x))
8705 (setq plist (plist-put plist :fromname (car adr)))
8706 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
8707 (when (setq x (plist-get plist :to))
8708 (setq adr (mail-extract-address-components x))
8709 (setq plist (plist-put plist :toname (car adr)))
8710 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
8711 (let ((from (plist-get plist :from))
8712 (to (plist-get plist :to)))
8713 (when (and from to org-from-is-user-regexp)
8714 (setq plist
8715 (plist-put plist :fromto
8716 (if (string-match org-from-is-user-regexp from)
8717 (concat "to %t")
8718 (concat "from %f"))))))
8719 (setq org-store-link-plist plist))
8721 (defun org-add-link-props (&rest plist)
8722 "Add these properties to the link property list."
8723 (let (key value)
8724 (while plist
8725 (setq key (pop plist) value (pop plist))
8726 (setq org-store-link-plist
8727 (plist-put org-store-link-plist key value)))))
8729 (defun org-email-link-description (&optional fmt)
8730 "Return the description part of an email link.
8731 This takes information from `org-store-link-plist' and formats it
8732 according to FMT (default from `org-email-link-description-format')."
8733 (setq fmt (or fmt org-email-link-description-format))
8734 (let* ((p org-store-link-plist)
8735 (to (plist-get p :toaddress))
8736 (from (plist-get p :fromaddress))
8737 (table
8738 (list
8739 (cons "%c" (plist-get p :fromto))
8740 (cons "%F" (plist-get p :from))
8741 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
8742 (cons "%T" (plist-get p :to))
8743 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
8744 (cons "%s" (plist-get p :subject))
8745 (cons "%d" (plist-get p :date))
8746 (cons "%m" (plist-get p :message-id)))))
8747 (when (string-match "%c" fmt)
8748 ;; Check if the user wrote this message
8749 (if (and org-from-is-user-regexp from to
8750 (save-match-data (string-match org-from-is-user-regexp from)))
8751 (setq fmt (replace-match "to %t" t t fmt))
8752 (setq fmt (replace-match "from %f" t t fmt))))
8753 (org-replace-escapes fmt table)))
8755 (defun org-make-org-heading-search-string (&optional string heading)
8756 "Make search string for STRING or current headline."
8757 (interactive)
8758 (let ((s (or string (org-get-heading)))
8759 (lines org-context-in-file-links))
8760 (unless (and string (not heading))
8761 ;; We are using a headline, clean up garbage in there.
8762 (if (string-match org-todo-regexp s)
8763 (setq s (replace-match "" t t s)))
8764 (if (string-match (org-re ":[[:alnum:]_@#%:]+:[ \t]*$") s)
8765 (setq s (replace-match "" t t s)))
8766 (setq s (org-trim s))
8767 (if (string-match (concat "^\\(" org-quote-string "\\|"
8768 org-comment-string "\\)") s)
8769 (setq s (replace-match "" t t s)))
8770 (while (string-match org-ts-regexp s)
8771 (setq s (replace-match "" t t s))))
8772 (or string (setq s (concat "*" s))) ; Add * for headlines
8773 (when (and string (integerp lines) (> lines 0))
8774 (let ((slines (org-split-string s "\n")))
8775 (when (< lines (length slines))
8776 (setq s (mapconcat
8777 'identity
8778 (reverse (nthcdr (- (length slines) lines)
8779 (reverse slines))) "\n")))))
8780 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
8782 (defun org-make-link (&rest strings)
8783 "Concatenate STRINGS."
8784 (apply 'concat strings))
8786 (defun org-make-link-string (link &optional description)
8787 "Make a link with brackets, consisting of LINK and DESCRIPTION."
8788 (unless (string-match "\\S-" link)
8789 (error "Empty link"))
8790 (when (and description
8791 (stringp description)
8792 (not (string-match "\\S-" description)))
8793 (setq description nil))
8794 (when (stringp description)
8795 ;; Remove brackets from the description, they are fatal.
8796 (while (string-match "\\[" description)
8797 (setq description (replace-match "{" t t description)))
8798 (while (string-match "\\]" description)
8799 (setq description (replace-match "}" t t description))))
8800 (when (equal link description)
8801 ;; No description needed, it is identical
8802 (setq description nil))
8803 (when (and (not description)
8804 (not (string-match (org-image-file-name-regexp) link))
8805 (not (equal link (org-link-escape link))))
8806 (setq description (org-extract-attributes link)))
8807 (setq link
8808 (cond ((string-match (org-image-file-name-regexp) link) link)
8809 ((string-match org-link-types-re link)
8810 (concat (match-string 1 link)
8811 (org-link-escape (substring link (match-end 1)))))
8812 (t (org-link-escape link))))
8813 (concat "[[" link "]"
8814 (if description (concat "[" description "]") "")
8815 "]"))
8817 (defconst org-link-escape-chars
8818 '(?\ ?\[ ?\] ?\; ?\= ?\+)
8819 "List of characters that should be escaped in link.
8820 This is the list that is used for internal purposes.")
8822 (defvar org-url-encoding-use-url-hexify nil)
8824 (defconst org-link-escape-chars-browser
8825 '(?\ )
8826 "List of escapes for characters that are problematic in links.
8827 This is the list that is used before handing over to the browser.")
8829 (defun org-link-escape (text &optional table merge)
8830 "Return percent escaped representation of TEXT.
8831 TEXT is a string with the text to escape.
8832 Optional argument TABLE is a list with characters that should be
8833 escaped. When nil, `org-link-escape-chars' is used.
8834 If optional argument MERGE is set, merge TABLE into
8835 `org-link-escape-chars'."
8836 (if (and org-url-encoding-use-url-hexify (not table))
8837 (url-hexify-string text)
8838 (cond
8839 ((and table merge)
8840 (mapc (lambda (defchr)
8841 (unless (member defchr table)
8842 (setq table (cons defchr table)))) org-link-escape-chars))
8843 ((null table)
8844 (setq table org-link-escape-chars)))
8845 (mapconcat
8846 (lambda (char)
8847 (if (or (member char table)
8848 (< char 32) (= char 37) (> char 126))
8849 (mapconcat (lambda (sequence-element)
8850 (format "%%%.2X" sequence-element))
8851 (or (encode-coding-char char 'utf-8)
8852 (error "Unable to percent escape character: %s"
8853 (char-to-string char))) "")
8854 (char-to-string char))) text "")))
8856 (defun org-link-unescape (str)
8857 "Unhex hexified unicode strings as returned from the JavaScript function
8858 encodeURIComponent. E.g. `%C3%B6' is the german Umlaut `ö'."
8859 (unless (and (null str) (string= "" str))
8860 (let ((pos 0) (case-fold-search t) unhexed)
8861 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
8862 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
8863 (setq str (replace-match unhexed t t str))
8864 (setq pos (+ pos (length unhexed))))))
8865 str)
8867 (defun org-link-unescape-compound (hex)
8868 "Unhexify unicode hex-chars. E.g. `%C3%B6' is the German Umlaut `ö'.
8869 Note: this function also decodes single byte encodings like
8870 `%E1' (\"á\") if not followed by another `%[A-F0-9]{2}' group."
8871 (save-match-data
8872 (let* ((bytes (cdr (split-string hex "%")))
8873 (ret "")
8874 (eat 0)
8875 (sum 0))
8876 (while bytes
8877 (let* ((val (string-to-number (pop bytes) 16))
8878 (shift-xor
8879 (if (= 0 eat)
8880 (cond
8881 ((>= val 252) (cons 6 252))
8882 ((>= val 248) (cons 5 248))
8883 ((>= val 240) (cons 4 240))
8884 ((>= val 224) (cons 3 224))
8885 ((>= val 192) (cons 2 192))
8886 (t (cons 0 0)))
8887 (cons 6 128))))
8888 (if (>= val 192) (setq eat (car shift-xor)))
8889 (setq val (logxor val (cdr shift-xor)))
8890 (setq sum (+ (lsh sum (car shift-xor)) val))
8891 (if (> eat 0) (setq eat (- eat 1)))
8892 (cond
8893 ((= 0 eat) ;multi byte
8894 (setq ret (concat ret (org-char-to-string sum)))
8895 (setq sum 0))
8896 ((not bytes) ; single byte(s)
8897 (setq ret (org-link-unescape-single-byte-sequence hex))))
8898 )) ;; end (while bytes
8899 ret )))
8901 (defun org-link-unescape-single-byte-sequence (hex)
8902 "Unhexify hex-encoded single byte character sequences."
8903 (mapconcat (lambda (byte)
8904 (char-to-string (string-to-number byte 16)))
8905 (cdr (split-string hex "%")) ""))
8907 (defun org-xor (a b)
8908 "Exclusive or."
8909 (if a (not b) b))
8911 (defun org-fixup-message-id-for-http (s)
8912 "Replace special characters in a message id, so it can be used in an http query."
8913 (when (string-match "%" s)
8914 (setq s (mapconcat (lambda (c)
8915 (if (eq c ?%)
8916 "%25"
8917 (char-to-string c)))
8918 s "")))
8919 (while (string-match "<" s)
8920 (setq s (replace-match "%3C" t t s)))
8921 (while (string-match ">" s)
8922 (setq s (replace-match "%3E" t t s)))
8923 (while (string-match "@" s)
8924 (setq s (replace-match "%40" t t s)))
8927 ;;;###autoload
8928 (defun org-insert-link-global ()
8929 "Insert a link like Org-mode does.
8930 This command can be called in any mode to insert a link in Org-mode syntax."
8931 (interactive)
8932 (org-load-modules-maybe)
8933 (org-run-like-in-org-mode 'org-insert-link))
8935 (defun org-insert-link (&optional complete-file link-location)
8936 "Insert a link. At the prompt, enter the link.
8938 Completion can be used to insert any of the link protocol prefixes like
8939 http or ftp in use.
8941 The history can be used to select a link previously stored with
8942 `org-store-link'. When the empty string is entered (i.e. if you just
8943 press RET at the prompt), the link defaults to the most recently
8944 stored link. As SPC triggers completion in the minibuffer, you need to
8945 use M-SPC or C-q SPC to force the insertion of a space character.
8947 You will also be prompted for a description, and if one is given, it will
8948 be displayed in the buffer instead of the link.
8950 If there is already a link at point, this command will allow you to edit link
8951 and description parts.
8953 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
8954 be selected using completion. The path to the file will be relative to the
8955 current directory if the file is in the current directory or a subdirectory.
8956 Otherwise, the link will be the absolute path as completed in the minibuffer
8957 \(i.e. normally ~/path/to/file). You can configure this behavior using the
8958 option `org-link-file-path-type'.
8960 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
8961 the current directory or below.
8963 With three \\[universal-argument] prefixes, negate the meaning of
8964 `org-keep-stored-link-after-insertion'.
8966 If `org-make-link-description-function' is non-nil, this function will be
8967 called with the link target, and the result will be the default
8968 link description.
8970 If the LINK-LOCATION parameter is non-nil, this value will be
8971 used as the link location instead of reading one interactively."
8972 (interactive "P")
8973 (let* ((wcf (current-window-configuration))
8974 (region (if (org-region-active-p)
8975 (buffer-substring (region-beginning) (region-end))))
8976 (remove (and region (list (region-beginning) (region-end))))
8977 (desc region)
8978 tmphist ; byte-compile incorrectly complains about this
8979 (link link-location)
8980 entry file all-prefixes)
8981 (cond
8982 (link-location) ; specified by arg, just use it.
8983 ((org-in-regexp org-bracket-link-regexp 1)
8984 ;; We do have a link at point, and we are going to edit it.
8985 (setq remove (list (match-beginning 0) (match-end 0)))
8986 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
8987 (setq link (read-string "Link: "
8988 (org-link-unescape
8989 (org-match-string-no-properties 1)))))
8990 ((or (org-in-regexp org-angle-link-re)
8991 (org-in-regexp org-plain-link-re))
8992 ;; Convert to bracket link
8993 (setq remove (list (match-beginning 0) (match-end 0))
8994 link (read-string "Link: "
8995 (org-remove-angle-brackets (match-string 0)))))
8996 ((member complete-file '((4) (16)))
8997 ;; Completing read for file names.
8998 (setq link (org-file-complete-link complete-file)))
9000 ;; Read link, with completion for stored links.
9001 (with-output-to-temp-buffer "*Org Links*"
9002 (princ "Insert a link.
9003 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9004 (when org-stored-links
9005 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9006 (princ (mapconcat
9007 (lambda (x)
9008 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
9009 (reverse org-stored-links) "\n"))))
9010 (let ((cw (selected-window)))
9011 (select-window (get-buffer-window "*Org Links*" 'visible))
9012 (with-current-buffer "*Org Links*" (setq truncate-lines) t)
9013 (unless (pos-visible-in-window-p (point-max))
9014 (org-fit-window-to-buffer))
9015 (and (window-live-p cw) (select-window cw)))
9016 ;; Fake a link history, containing the stored links.
9017 (setq tmphist (append (mapcar 'car org-stored-links)
9018 org-insert-link-history))
9019 (setq all-prefixes (append (mapcar 'car org-link-abbrev-alist-local)
9020 (mapcar 'car org-link-abbrev-alist)
9021 org-link-types))
9022 (unwind-protect
9023 (progn
9024 (setq link
9025 (let ((org-completion-use-ido nil)
9026 (org-completion-use-iswitchb nil))
9027 (org-completing-read
9028 "Link: "
9029 (append
9030 (mapcar (lambda (x) (list (concat x ":")))
9031 all-prefixes)
9032 (mapcar 'car org-stored-links))
9033 nil nil nil
9034 'tmphist
9035 (car (car org-stored-links)))))
9036 (if (not (string-match "\\S-" link))
9037 (error "No link selected"))
9038 (if (or (member link all-prefixes)
9039 (and (equal ":" (substring link -1))
9040 (member (substring link 0 -1) all-prefixes)
9041 (setq link (substring link 0 -1))))
9042 (setq link (org-link-try-special-completion link))))
9043 (set-window-configuration wcf)
9044 (kill-buffer "*Org Links*"))
9045 (setq entry (assoc link org-stored-links))
9046 (or entry (push link org-insert-link-history))
9047 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9048 (not org-keep-stored-link-after-insertion))
9049 (setq org-stored-links (delq (assoc link org-stored-links)
9050 org-stored-links)))
9051 (setq desc (or desc (nth 1 entry)))))
9053 (if (string-match org-plain-link-re link)
9054 ;; URL-like link, normalize the use of angular brackets.
9055 (setq link (org-make-link (org-remove-angle-brackets link))))
9057 ;; Check if we are linking to the current file with a search option
9058 ;; If yes, simplify the link by using only the search option.
9059 (when (and buffer-file-name
9060 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
9061 (let* ((path (match-string 1 link))
9062 (case-fold-search nil)
9063 (search (match-string 2 link)))
9064 (save-match-data
9065 (if (equal (file-truename buffer-file-name) (file-truename path))
9066 ;; We are linking to this same file, with a search option
9067 (setq link search)))))
9069 ;; Check if we can/should use a relative path. If yes, simplify the link
9070 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
9071 (let* ((type (match-string 1 link))
9072 (path (match-string 2 link))
9073 (origpath path)
9074 (case-fold-search nil))
9075 (cond
9076 ((or (eq org-link-file-path-type 'absolute)
9077 (equal complete-file '(16)))
9078 (setq path (abbreviate-file-name (expand-file-name path))))
9079 ((eq org-link-file-path-type 'noabbrev)
9080 (setq path (expand-file-name path)))
9081 ((eq org-link-file-path-type 'relative)
9082 (setq path (file-relative-name path)))
9084 (save-match-data
9085 (if (string-match (concat "^" (regexp-quote
9086 (expand-file-name
9087 (file-name-as-directory
9088 default-directory))))
9089 (expand-file-name path))
9090 ;; We are linking a file with relative path name.
9091 (setq path (substring (expand-file-name path)
9092 (match-end 0)))
9093 (setq path (abbreviate-file-name (expand-file-name path)))))))
9094 (setq link (concat type path))
9095 (if (equal desc origpath)
9096 (setq desc path))))
9098 (if org-make-link-description-function
9099 (setq desc (funcall org-make-link-description-function link desc)))
9101 (setq desc (read-string "Description: " desc))
9102 (unless (string-match "\\S-" desc) (setq desc nil))
9103 (if remove (apply 'delete-region remove))
9104 (insert (org-make-link-string link desc))))
9106 (defun org-link-try-special-completion (type)
9107 "If there is completion support for link type TYPE, offer it."
9108 (let ((fun (intern (concat "org-" type "-complete-link"))))
9109 (if (functionp fun)
9110 (funcall fun)
9111 (read-string "Link (no completion support): " (concat type ":")))))
9113 (defun org-file-complete-link (&optional arg)
9114 "Create a file link using completion."
9115 (let (file link)
9116 (setq file (read-file-name "File: "))
9117 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9118 (pwd1 (file-name-as-directory (abbreviate-file-name
9119 (expand-file-name ".")))))
9120 (cond
9121 ((equal arg '(16))
9122 (setq link (org-make-link
9123 "file:"
9124 (abbreviate-file-name (expand-file-name file)))))
9125 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9126 (setq link (org-make-link "file:" (match-string 1 file))))
9127 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9128 (expand-file-name file))
9129 (setq link (org-make-link
9130 "file:" (match-string 1 (expand-file-name file)))))
9131 (t (setq link (org-make-link "file:" file)))))
9132 link))
9134 (defun org-completing-read (&rest args)
9135 "Completing-read with SPACE being a normal character."
9136 (let ((minibuffer-local-completion-map
9137 (copy-keymap minibuffer-local-completion-map)))
9138 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
9139 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
9140 (apply 'org-icompleting-read args)))
9142 (defun org-completing-read-no-i (&rest args)
9143 (let (org-completion-use-ido org-completion-use-iswitchb)
9144 (apply 'org-completing-read args)))
9146 (defun org-iswitchb-completing-read (prompt choices &rest args)
9147 "Use iswitch as a completing-read replacement to choose from choices.
9148 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
9149 from."
9150 (let* ((iswitchb-use-virtual-buffers nil)
9151 (iswitchb-make-buflist-hook
9152 (lambda ()
9153 (setq iswitchb-temp-buflist choices))))
9154 (iswitchb-read-buffer prompt)))
9156 (defun org-icompleting-read (&rest args)
9157 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
9158 (org-without-partial-completion
9159 (if (and org-completion-use-ido
9160 (fboundp 'ido-completing-read)
9161 (boundp 'ido-mode) ido-mode
9162 (listp (second args)))
9163 (let ((ido-enter-matching-directory nil))
9164 (apply 'ido-completing-read (concat (car args))
9165 (if (consp (car (nth 1 args)))
9166 (mapcar 'car (nth 1 args))
9167 (nth 1 args))
9168 (cddr args)))
9169 (if (and org-completion-use-iswitchb
9170 (boundp 'iswitchb-mode) iswitchb-mode
9171 (listp (second args)))
9172 (apply 'org-iswitchb-completing-read (concat (car args))
9173 (if (consp (car (nth 1 args)))
9174 (mapcar 'car (nth 1 args))
9175 (nth 1 args))
9176 (cddr args))
9177 (apply 'completing-read args)))))
9179 (defun org-extract-attributes (s)
9180 "Extract the attributes cookie from a string and set as text property."
9181 (let (a attr (start 0) key value)
9182 (save-match-data
9183 (when (string-match "{{\\([^}]+\\)}}$" s)
9184 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
9185 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
9186 (setq key (match-string 1 a) value (match-string 2 a)
9187 start (match-end 0)
9188 attr (plist-put attr (intern key) value))))
9189 (org-add-props s nil 'org-attr attr))
9192 (defun org-extract-attributes-from-string (tag)
9193 (let (key value attr)
9194 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
9195 (setq key (match-string 1 tag) value (match-string 2 tag)
9196 tag (replace-match "" t t tag)
9197 attr (plist-put attr (intern key) value)))
9198 (cons tag attr)))
9200 (defun org-attributes-to-string (plist)
9201 "Format a property list into an HTML attribute list."
9202 (let ((s "") key value)
9203 (while plist
9204 (setq key (pop plist) value (pop plist))
9205 (and value
9206 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
9209 ;;; Opening/following a link
9211 (defvar org-link-search-failed nil)
9213 (defvar org-open-link-functions nil
9214 "Hook for functions finding a plain text link.
9215 These functions must take a single argument, the link content.
9216 They will be called for links that look like [[link text][description]]
9217 when LINK TEXT does not have a protocol like \"http:\" and does not look
9218 like a filename (e.g. \"./blue.png\").
9220 These functions will be called *before* Org attempts to resolve the
9221 link by doing text searches in the current buffer - so if you want a
9222 link \"[[target]]\" to still find \"<<target>>\", your function should
9223 handle this as a special case.
9225 When the function does handle the link, it must return a non-nil value.
9226 If it decides that it is not responsible for this link, it must return
9227 nil to indicate that that Org-mode can continue with other options
9228 like exact and fuzzy text search.")
9230 (defun org-next-link ()
9231 "Move forward to the next link.
9232 If the link is in hidden text, expose it."
9233 (interactive)
9234 (when (and org-link-search-failed (eq this-command last-command))
9235 (goto-char (point-min))
9236 (message "Link search wrapped back to beginning of buffer"))
9237 (setq org-link-search-failed nil)
9238 (let* ((pos (point))
9239 (ct (org-context))
9240 (a (assoc :link ct)))
9241 (if a (goto-char (nth 2 a)))
9242 (if (re-search-forward org-any-link-re nil t)
9243 (progn
9244 (goto-char (match-beginning 0))
9245 (if (outline-invisible-p) (org-show-context)))
9246 (goto-char pos)
9247 (setq org-link-search-failed t)
9248 (error "No further link found"))))
9250 (defun org-previous-link ()
9251 "Move backward to the previous link.
9252 If the link is in hidden text, expose it."
9253 (interactive)
9254 (when (and org-link-search-failed (eq this-command last-command))
9255 (goto-char (point-max))
9256 (message "Link search wrapped back to end of buffer"))
9257 (setq org-link-search-failed nil)
9258 (let* ((pos (point))
9259 (ct (org-context))
9260 (a (assoc :link ct)))
9261 (if a (goto-char (nth 1 a)))
9262 (if (re-search-backward org-any-link-re nil t)
9263 (progn
9264 (goto-char (match-beginning 0))
9265 (if (outline-invisible-p) (org-show-context)))
9266 (goto-char pos)
9267 (setq org-link-search-failed t)
9268 (error "No further link found"))))
9270 (defun org-translate-link (s)
9271 "Translate a link string if a translation function has been defined."
9272 (if (and org-link-translation-function
9273 (fboundp org-link-translation-function)
9274 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
9275 (progn
9276 (setq s (funcall org-link-translation-function
9277 (match-string 1) (match-string 2)))
9278 (concat (car s) ":" (cdr s)))
9281 (defun org-translate-link-from-planner (type path)
9282 "Translate a link from Emacs Planner syntax so that Org can follow it.
9283 This is still an experimental function, your mileage may vary."
9284 (cond
9285 ((member type '("http" "https" "news" "ftp"))
9286 ;; standard Internet links are the same.
9287 nil)
9288 ((and (equal type "irc") (string-match "^//" path))
9289 ;; Planner has two / at the beginning of an irc link, we have 1.
9290 ;; We should have zero, actually....
9291 (setq path (substring path 1)))
9292 ((and (equal type "lisp") (string-match "^/" path))
9293 ;; Planner has a slash, we do not.
9294 (setq type "elisp" path (substring path 1)))
9295 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9296 ;; A typical message link. Planner has the id after the final slash,
9297 ;; we separate it with a hash mark
9298 (setq path (concat (match-string 1 path) "#"
9299 (org-remove-angle-brackets (match-string 2 path)))))
9301 (cons type path))
9303 (defun org-find-file-at-mouse (ev)
9304 "Open file link or URL at mouse."
9305 (interactive "e")
9306 (mouse-set-point ev)
9307 (org-open-at-point 'in-emacs))
9309 (defun org-open-at-mouse (ev)
9310 "Open file link or URL at mouse.
9311 See the docstring of `org-open-file' for details."
9312 (interactive "e")
9313 (mouse-set-point ev)
9314 (if (eq major-mode 'org-agenda-mode)
9315 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
9316 (org-open-at-point))
9318 (defvar org-window-config-before-follow-link nil
9319 "The window configuration before following a link.
9320 This is saved in case the need arises to restore it.")
9322 (defvar org-open-link-marker (make-marker)
9323 "Marker pointing to the location where `org-open-at-point; was called.")
9325 ;;;###autoload
9326 (defun org-open-at-point-global ()
9327 "Follow a link like Org-mode does.
9328 This command can be called in any mode to follow a link that has
9329 Org-mode syntax."
9330 (interactive)
9331 (org-run-like-in-org-mode 'org-open-at-point))
9333 ;;;###autoload
9334 (defun org-open-link-from-string (s &optional arg reference-buffer)
9335 "Open a link in the string S, as if it was in Org-mode."
9336 (interactive "sLink: \nP")
9337 (let ((reference-buffer (or reference-buffer (current-buffer))))
9338 (with-temp-buffer
9339 (let ((org-inhibit-startup t))
9340 (org-mode)
9341 (insert s)
9342 (goto-char (point-min))
9343 (when reference-buffer
9344 (setq org-link-abbrev-alist-local
9345 (with-current-buffer reference-buffer
9346 org-link-abbrev-alist-local)))
9347 (org-open-at-point arg reference-buffer)))))
9349 (defvar org-open-at-point-functions nil
9350 "Hook that is run when following a link at point.
9352 Functions in this hook must return t if they identify and follow
9353 a link at point. If they don't find anything interesting at point,
9354 they must return nil.")
9356 (defun org-open-at-point (&optional arg reference-buffer)
9357 "Open link at or after point.
9358 If there is no link at point, this function will search forward up to
9359 the end of the current line.
9360 Normally, files will be opened by an appropriate application. If the
9361 optional prefix argument ARG is non-nil, Emacs will visit the file.
9362 With a double prefix argument, try to open outside of Emacs, in the
9363 application the system uses for this file type."
9364 (interactive "P")
9365 ;; if in a code block, then open the block's results
9366 (unless (call-interactively #'org-babel-open-src-block-result)
9367 (org-load-modules-maybe)
9368 (move-marker org-open-link-marker (point))
9369 (setq org-window-config-before-follow-link (current-window-configuration))
9370 (org-remove-occur-highlights nil nil t)
9371 (cond
9372 ((and (org-on-heading-p)
9373 (not (org-in-regexp
9374 (concat org-plain-link-re "\\|"
9375 org-bracket-link-regexp "\\|"
9376 org-angle-link-re "\\|"
9377 "[ \t]:[^ \t\n]+:[ \t]*$")))
9378 (not (get-text-property (point) 'org-linked-text)))
9379 (or (org-offer-links-in-entry arg)
9380 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
9381 ((run-hook-with-args-until-success 'org-open-at-point-functions))
9382 ((org-at-timestamp-p t) (org-follow-timestamp-link))
9383 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
9384 (not (org-in-regexp org-bracket-link-regexp)))
9385 (org-footnote-action))
9387 (let (type path link line search (pos (point)))
9388 (catch 'match
9389 (save-excursion
9390 (skip-chars-forward "^]\n\r")
9391 (when (org-in-regexp org-bracket-link-regexp 1)
9392 (setq link (org-extract-attributes
9393 (org-link-unescape (org-match-string-no-properties 1))))
9394 (while (string-match " *\n *" link)
9395 (setq link (replace-match " " t t link)))
9396 (setq link (org-link-expand-abbrev link))
9397 (cond
9398 ((or (file-name-absolute-p link)
9399 (string-match "^\\.\\.?/" link))
9400 (setq type "file" path link))
9401 ((string-match org-link-re-with-space3 link)
9402 (setq type (match-string 1 link) path (match-string 2 link)))
9403 (t (setq type "thisfile" path link)))
9404 (throw 'match t)))
9406 (when (get-text-property (point) 'org-linked-text)
9407 (setq type "thisfile"
9408 pos (if (get-text-property (1+ (point)) 'org-linked-text)
9409 (1+ (point)) (point))
9410 path (buffer-substring
9411 (or (previous-single-property-change pos 'org-linked-text)
9412 (point-min))
9413 (or (next-single-property-change pos 'org-linked-text)
9414 (point-max))))
9415 (throw 'match t))
9417 (save-excursion
9418 (when (or (org-in-regexp org-angle-link-re)
9419 (org-in-regexp org-plain-link-re))
9420 (setq type (match-string 1) path (match-string 2))
9421 (throw 'match t)))
9422 (save-excursion
9423 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
9424 (setq type "tags"
9425 path (match-string 1))
9426 (while (string-match ":" path)
9427 (setq path (replace-match "+" t t path)))
9428 (throw 'match t)))
9429 (when (org-in-regexp "<\\([^><\n]+\\)>")
9430 (setq type "tree-match"
9431 path (match-string 1))
9432 (throw 'match t)))
9433 (unless path
9434 (error "No link found"))
9436 ;; switch back to reference buffer
9437 ;; needed when if called in a temporary buffer through
9438 ;; org-open-link-from-string
9439 (with-current-buffer (or reference-buffer (current-buffer))
9441 ;; Remove any trailing spaces in path
9442 (if (string-match " +\\'" path)
9443 (setq path (replace-match "" t t path)))
9444 (if (and org-link-translation-function
9445 (fboundp org-link-translation-function))
9446 ;; Check if we need to translate the link
9447 (let ((tmp (funcall org-link-translation-function type path)))
9448 (setq type (car tmp) path (cdr tmp))))
9450 (cond
9452 ((assoc type org-link-protocols)
9453 (funcall (nth 1 (assoc type org-link-protocols)) path))
9455 ((equal type "mailto")
9456 (let ((cmd (car org-link-mailto-program))
9457 (args (cdr org-link-mailto-program)) args1
9458 (address path) (subject "") a)
9459 (if (string-match "\\(.*\\)::\\(.*\\)" path)
9460 (setq address (match-string 1 path)
9461 subject (org-link-escape (match-string 2 path))))
9462 (while args
9463 (cond
9464 ((not (stringp (car args))) (push (pop args) args1))
9465 (t (setq a (pop args))
9466 (if (string-match "%a" a)
9467 (setq a (replace-match address t t a)))
9468 (if (string-match "%s" a)
9469 (setq a (replace-match subject t t a)))
9470 (push a args1))))
9471 (apply cmd (nreverse args1))))
9473 ((member type '("http" "https" "ftp" "news"))
9474 (browse-url (concat type ":" (org-link-escape
9475 path org-link-escape-chars-browser))))
9477 ((string= type "doi")
9478 (browse-url (concat "http://dx.doi.org/"
9479 (org-link-escape
9480 path org-link-escape-chars-browser))))
9482 ((member type '("message"))
9483 (browse-url (concat type ":" path)))
9485 ((string= type "tags")
9486 (org-tags-view arg path))
9488 ((string= type "tree-match")
9489 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
9491 ((string= type "file")
9492 (if (string-match "::\\([0-9]+\\)\\'" path)
9493 (setq line (string-to-number (match-string 1 path))
9494 path (substring path 0 (match-beginning 0)))
9495 (if (string-match "::\\(.+\\)\\'" path)
9496 (setq search (match-string 1 path)
9497 path (substring path 0 (match-beginning 0)))))
9498 (if (string-match "[*?{]" (file-name-nondirectory path))
9499 (dired path)
9500 (org-open-file path arg line search)))
9502 ((string= type "shell")
9503 (let ((cmd path))
9504 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
9505 (string-match org-confirm-shell-link-not-regexp cmd))
9506 (not org-confirm-shell-link-function)
9507 (funcall org-confirm-shell-link-function
9508 (format "Execute \"%s\" in shell? "
9509 (org-add-props cmd nil
9510 'face 'org-warning))))
9511 (progn
9512 (message "Executing %s" cmd)
9513 (shell-command cmd))
9514 (error "Abort"))))
9516 ((string= type "elisp")
9517 (let ((cmd path))
9518 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
9519 (string-match org-confirm-elisp-link-not-regexp cmd))
9520 (not org-confirm-elisp-link-function)
9521 (funcall org-confirm-elisp-link-function
9522 (format "Execute \"%s\" as elisp? "
9523 (org-add-props cmd nil
9524 'face 'org-warning))))
9525 (message "%s => %s" cmd
9526 (if (equal (string-to-char cmd) ?\()
9527 (eval (read cmd))
9528 (call-interactively (read cmd))))
9529 (error "Abort"))))
9531 ((and (string= type "thisfile")
9532 (run-hook-with-args-until-success
9533 'org-open-link-functions path)))
9535 ((string= type "thisfile")
9536 (if arg
9537 (switch-to-buffer-other-window
9538 (org-get-buffer-for-internal-link (current-buffer)))
9539 (org-mark-ring-push))
9540 (let ((cmd `(org-link-search
9541 ,path
9542 ,(cond ((equal arg '(4)) ''occur)
9543 ((equal arg '(16)) ''org-occur)
9544 (t nil))
9545 ,pos)))
9546 (condition-case nil (eval cmd)
9547 (error (progn (widen) (eval cmd))))))
9550 (browse-url-at-point)))))))
9551 (move-marker org-open-link-marker nil)
9552 (run-hook-with-args 'org-follow-link-hook)))
9554 (defun org-offer-links-in-entry (&optional nth zero)
9555 "Offer links in the current entry and follow the selected link.
9556 If there is only one link, follow it immediately as well.
9557 If NTH is an integer, immediately pick the NTH link found.
9558 If ZERO is a string, check also this string for a link, and if
9559 there is one, offer it as link number zero."
9560 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
9561 "\\(" org-angle-link-re "\\)\\|"
9562 "\\(" org-plain-link-re "\\)"))
9563 (cnt ?0)
9564 (in-emacs (if (integerp nth) nil nth))
9565 have-zero end links link c)
9566 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
9567 (push (match-string 0 zero) links)
9568 (setq cnt (1- cnt) have-zero t))
9569 (save-excursion
9570 (org-back-to-heading t)
9571 (setq end (save-excursion (outline-next-heading) (point)))
9572 (while (re-search-forward re end t)
9573 (push (match-string 0) links))
9574 (setq links (org-uniquify (reverse links))))
9576 (cond
9577 ((null links)
9578 (message "No links"))
9579 ((equal (length links) 1)
9580 (setq link (list (car links))))
9581 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
9582 (setq link (nth (if have-zero nth (1- nth)) links)))
9583 (t ; we have to select a link
9584 (save-excursion
9585 (save-window-excursion
9586 (delete-other-windows)
9587 (with-output-to-temp-buffer "*Select Link*"
9588 (mapc (lambda (l)
9589 (if (not (string-match org-bracket-link-regexp l))
9590 (princ (format "[%c] %s\n" (incf cnt)
9591 (org-remove-angle-brackets l)))
9592 (if (match-end 3)
9593 (princ (format "[%c] %s (%s)\n" (incf cnt)
9594 (match-string 3 l) (match-string 1 l)))
9595 (princ (format "[%c] %s\n" (incf cnt)
9596 (match-string 1 l))))))
9597 links))
9598 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
9599 (message "Select link to open, RET to open all:")
9600 (setq c (read-char-exclusive))
9601 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
9602 (when (equal c ?q) (error "Abort"))
9603 (if (equal c ?\C-m)
9604 (setq link links)
9605 (setq nth (- c ?0))
9606 (if have-zero (setq nth (1+ nth)))
9607 (unless (and (integerp nth) (>= (length links) nth))
9608 (error "Invalid link selection"))
9609 (setq link (list (nth (1- nth) links))))))
9610 (if link
9611 (let ((buf (current-buffer)))
9612 (dolist (l link)
9613 (org-open-link-from-string l in-emacs buf))
9615 nil)))
9617 ;; Add special file links that specify the way of opening
9619 (org-add-link-type "file+sys" 'org-open-file-with-system)
9620 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
9621 (defun org-open-file-with-system (path)
9622 "Open file at PATH using the system way of opening it."
9623 (org-open-file path 'system))
9624 (defun org-open-file-with-emacs (path)
9625 "Open file at PATH in Emacs."
9626 (org-open-file path 'emacs))
9627 (defun org-remove-file-link-modifiers ()
9628 "Remove the file link modifiers in `file+sys:' and `file+emacs:' links."
9629 (goto-char (point-min))
9630 (while (re-search-forward "\\<file\\+\\(sys\\|emacs\\):" nil t)
9631 (org-if-unprotected
9632 (replace-match "file:" t t))))
9633 (eval-after-load "org-exp"
9634 '(add-hook 'org-export-preprocess-before-normalizing-links-hook
9635 'org-remove-file-link-modifiers))
9637 ;;;; Time estimates
9639 (defun org-get-effort (&optional pom)
9640 "Get the effort estimate for the current entry."
9641 (org-entry-get pom org-effort-property))
9643 ;;; File search
9645 (defvar org-create-file-search-functions nil
9646 "List of functions to construct the right search string for a file link.
9647 These functions are called in turn with point at the location to
9648 which the link should point.
9650 A function in the hook should first test if it would like to
9651 handle this file type, for example by checking the `major-mode'
9652 or the file extension. If it decides not to handle this file, it
9653 should just return nil to give other functions a chance. If it
9654 does handle the file, it must return the search string to be used
9655 when following the link. The search string will be part of the
9656 file link, given after a double colon, and `org-open-at-point'
9657 will automatically search for it. If special measures must be
9658 taken to make the search successful, another function should be
9659 added to the companion hook `org-execute-file-search-functions',
9660 which see.
9662 A function in this hook may also use `setq' to set the variable
9663 `description' to provide a suggestion for the descriptive text to
9664 be used for this link when it gets inserted into an Org-mode
9665 buffer with \\[org-insert-link].")
9667 (defvar org-execute-file-search-functions nil
9668 "List of functions to execute a file search triggered by a link.
9670 Functions added to this hook must accept a single argument, the
9671 search string that was part of the file link, the part after the
9672 double colon. The function must first check if it would like to
9673 handle this search, for example by checking the `major-mode' or
9674 the file extension. If it decides not to handle this search, it
9675 should just return nil to give other functions a chance. If it
9676 does handle the search, it must return a non-nil value to keep
9677 other functions from trying.
9679 Each function can access the current prefix argument through the
9680 variable `current-prefix-argument'. Note that a single prefix is
9681 used to force opening a link in Emacs, so it may be good to only
9682 use a numeric or double prefix to guide the search function.
9684 In case this is needed, a function in this hook can also restore
9685 the window configuration before `org-open-at-point' was called using:
9687 (set-window-configuration org-window-config-before-follow-link)")
9689 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
9690 (defun org-link-search (s &optional type avoid-pos)
9691 "Search for a link search option.
9692 If S is surrounded by forward slashes, it is interpreted as a
9693 regular expression. In org-mode files, this will create an `org-occur'
9694 sparse tree. In ordinary files, `occur' will be used to list matches.
9695 If the current buffer is in `dired-mode', grep will be used to search
9696 in all files. If AVOID-POS is given, ignore matches near that position."
9697 (let ((case-fold-search t)
9698 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
9699 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
9700 (append '(("") (" ") ("\t") ("\n"))
9701 org-emphasis-alist)
9702 "\\|") "\\)"))
9703 (pos (point))
9704 (pre nil) (post nil)
9705 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
9706 (cond
9707 ;; First check if there are any special search functions
9708 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
9709 ;; Now try the builtin stuff
9710 ((and (equal (string-to-char s0) ?#)
9711 (> (length s0) 1)
9712 (save-excursion
9713 (goto-char (point-min))
9714 (and
9715 (re-search-forward
9716 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
9717 (setq type 'dedicated
9718 pos (match-beginning 0))))
9719 ;; There is an exact target for this
9720 (goto-char pos)
9721 (org-back-to-heading t)))
9722 ((save-excursion
9723 (goto-char (point-min))
9724 (and
9725 (re-search-forward
9726 (concat "<<" (regexp-quote s0) ">>") nil t)
9727 (setq type 'dedicated
9728 pos (match-beginning 0))))
9729 ;; There is an exact target for this
9730 (goto-char pos))
9731 ((and (string-match "^(\\(.*\\))$" s0)
9732 (save-excursion
9733 (goto-char (point-min))
9734 (and
9735 (re-search-forward
9736 (concat "[^[]" (regexp-quote
9737 (format org-coderef-label-format
9738 (match-string 1 s0))))
9739 nil t)
9740 (setq type 'dedicated
9741 pos (1+ (match-beginning 0))))))
9742 ;; There is a coderef target for this
9743 (goto-char pos))
9744 ((string-match "^/\\(.*\\)/$" s)
9745 ;; A regular expression
9746 (cond
9747 ((org-mode-p)
9748 (org-occur (match-string 1 s)))
9749 ;;((eq major-mode 'dired-mode)
9750 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
9751 (t (org-do-occur (match-string 1 s)))))
9752 ((and (org-mode-p) org-link-search-must-match-exact-headline)
9753 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
9754 (goto-char (point-min))
9755 (cond
9756 ((let (case-fold-search)
9757 (re-search-forward (format org-complex-heading-regexp-format
9758 (regexp-quote s))
9759 nil t))
9760 ;; OK, found a match
9761 (setq type 'dedicated)
9762 (goto-char (match-beginning 0)))
9763 ((and (not org-link-search-inhibit-query)
9764 (eq org-link-search-must-match-exact-headline 'query-to-create)
9765 (y-or-n-p "No match - create this as a new heading? "))
9766 (goto-char (point-max))
9767 (or (bolp) (newline))
9768 (insert "* " s "\n")
9769 (beginning-of-line 0))
9771 (goto-char pos)
9772 (error "No match"))))
9774 ;; A normal search string
9775 (when (equal (string-to-char s) ?*)
9776 ;; Anchor on headlines, post may include tags.
9777 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
9778 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
9779 s (substring s 1)))
9780 (remove-text-properties
9781 0 (length s)
9782 '(face nil mouse-face nil keymap nil fontified nil) s)
9783 ;; Make a series of regular expressions to find a match
9784 (setq words (org-split-string s "[ \n\r\t]+")
9786 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
9787 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
9788 "\\)" markers)
9789 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
9790 re2a (concat "[ \t\r\n]" re2a_)
9791 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
9792 re4 (concat "[^a-zA-Z_]" re4_)
9794 re1 (concat pre re2 post)
9795 re3 (concat pre (if pre re4_ re4) post)
9796 re5 (concat pre ".*" re4)
9797 re2 (concat pre re2)
9798 re2a (concat pre (if pre re2a_ re2a))
9799 re4 (concat pre (if pre re4_ re4))
9800 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
9801 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
9802 re5 "\\)"
9804 (cond
9805 ((eq type 'org-occur) (org-occur reall))
9806 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
9807 (t (goto-char (point-min))
9808 (setq type 'fuzzy)
9809 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
9810 (org-search-not-self 1 re1 nil t)
9811 (org-search-not-self 1 re2 nil t)
9812 (org-search-not-self 1 re2a nil t)
9813 (org-search-not-self 1 re3 nil t)
9814 (org-search-not-self 1 re4 nil t)
9815 (org-search-not-self 1 re5 nil t)
9817 (goto-char (match-beginning 1))
9818 (goto-char pos)
9819 (error "No match"))))))
9820 (and (org-mode-p) (org-show-context 'link-search))
9821 type))
9823 (defun org-search-not-self (group &rest args)
9824 "Execute `re-search-forward', but only accept matches that do not
9825 enclose the position of `org-open-link-marker'."
9826 (let ((m org-open-link-marker))
9827 (catch 'exit
9828 (while (apply 're-search-forward args)
9829 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
9830 (goto-char (match-end group))
9831 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
9832 (> (match-beginning 0) (marker-position m))
9833 (< (match-end 0) (marker-position m)))
9834 (save-match-data
9835 (or (not (org-in-regexp
9836 org-bracket-link-analytic-regexp 1))
9837 (not (match-end 4)) ; no description
9838 (and (<= (match-beginning 4) (point))
9839 (>= (match-end 4) (point))))))
9840 (throw 'exit (point))))))))
9842 (defun org-get-buffer-for-internal-link (buffer)
9843 "Return a buffer to be used for displaying the link target of internal links."
9844 (cond
9845 ((not org-display-internal-link-with-indirect-buffer)
9846 buffer)
9847 ((string-match "(Clone)$" (buffer-name buffer))
9848 (message "Buffer is already a clone, not making another one")
9849 ;; we also do not modify visibility in this case
9850 buffer)
9851 (t ; make a new indirect buffer for displaying the link
9852 (let* ((bn (buffer-name buffer))
9853 (ibn (concat bn "(Clone)"))
9854 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
9855 (with-current-buffer ib (org-overview))
9856 ib))))
9858 (defun org-do-occur (regexp &optional cleanup)
9859 "Call the Emacs command `occur'.
9860 If CLEANUP is non-nil, remove the printout of the regular expression
9861 in the *Occur* buffer. This is useful if the regex is long and not useful
9862 to read."
9863 (occur regexp)
9864 (when cleanup
9865 (let ((cwin (selected-window)) win beg end)
9866 (when (setq win (get-buffer-window "*Occur*"))
9867 (select-window win))
9868 (goto-char (point-min))
9869 (when (re-search-forward "match[a-z]+" nil t)
9870 (setq beg (match-end 0))
9871 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
9872 (setq end (1- (match-beginning 0)))))
9873 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
9874 (goto-char (point-min))
9875 (select-window cwin))))
9877 ;;; The mark ring for links jumps
9879 (defvar org-mark-ring nil
9880 "Mark ring for positions before jumps in Org-mode.")
9881 (defvar org-mark-ring-last-goto nil
9882 "Last position in the mark ring used to go back.")
9883 ;; Fill and close the ring
9884 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
9885 (loop for i from 1 to org-mark-ring-length do
9886 (push (make-marker) org-mark-ring))
9887 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
9888 org-mark-ring)
9890 (defun org-mark-ring-push (&optional pos buffer)
9891 "Put the current position or POS into the mark ring and rotate it."
9892 (interactive)
9893 (setq pos (or pos (point)))
9894 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
9895 (move-marker (car org-mark-ring)
9896 (or pos (point))
9897 (or buffer (current-buffer)))
9898 (message "%s"
9899 (substitute-command-keys
9900 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
9902 (defun org-mark-ring-goto (&optional n)
9903 "Jump to the previous position in the mark ring.
9904 With prefix arg N, jump back that many stored positions. When
9905 called several times in succession, walk through the entire ring.
9906 Org-mode commands jumping to a different position in the current file,
9907 or to another Org-mode file, automatically push the old position
9908 onto the ring."
9909 (interactive "p")
9910 (let (p m)
9911 (if (eq last-command this-command)
9912 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
9913 (setq p org-mark-ring))
9914 (setq org-mark-ring-last-goto p)
9915 (setq m (car p))
9916 (org-pop-to-buffer-same-window (marker-buffer m))
9917 (goto-char m)
9918 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
9920 (defun org-remove-angle-brackets (s)
9921 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
9922 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
9924 (defun org-add-angle-brackets (s)
9925 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
9926 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
9928 (defun org-remove-double-quotes (s)
9929 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
9930 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
9933 ;;; Following specific links
9935 (defun org-follow-timestamp-link ()
9936 (cond
9937 ((org-at-date-range-p t)
9938 (let ((org-agenda-start-on-weekday)
9939 (t1 (match-string 1))
9940 (t2 (match-string 2)))
9941 (setq t1 (time-to-days (org-time-string-to-time t1))
9942 t2 (time-to-days (org-time-string-to-time t2)))
9943 (org-agenda-list nil t1 (1+ (- t2 t1)))))
9944 ((org-at-timestamp-p t)
9945 (org-agenda-list nil (time-to-days (org-time-string-to-time
9946 (substring (match-string 1) 0 10)))
9948 (t (error "This should not happen"))))
9951 ;;; Following file links
9952 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
9953 (declare-function mailcap-extension-to-mime "mailcap" (extn))
9954 (declare-function mailcap-mime-info
9955 "mailcap" (string &optional request no-decode))
9956 (defvar org-wait nil)
9957 (defun org-open-file (path &optional in-emacs line search)
9958 "Open the file at PATH.
9959 First, this expands any special file name abbreviations. Then the
9960 configuration variable `org-file-apps' is checked if it contains an
9961 entry for this file type, and if yes, the corresponding command is launched.
9963 If no application is found, Emacs simply visits the file.
9965 With optional prefix argument IN-EMACS, Emacs will visit the file.
9966 With a double \\[universal-argument] \\[universal-argument] \
9967 prefix arg, Org tries to avoid opening in Emacs
9968 and to use an external application to visit the file.
9970 Optional LINE specifies a line to go to, optional SEARCH a string
9971 to search for. If LINE or SEARCH is given, the file will be
9972 opened in Emacs, unless an entry from org-file-apps that makes
9973 use of groups in a regexp matches.
9975 If you want to change the way frames are used when following a
9976 link, please customize `org-link-frame-setup'.
9978 If the file does not exist, an error is thrown."
9979 (let* ((file (if (equal path "")
9980 buffer-file-name
9981 (substitute-in-file-name (expand-file-name path))))
9982 (file-apps (append org-file-apps (org-default-apps)))
9983 (apps (org-remove-if
9984 'org-file-apps-entry-match-against-dlink-p file-apps))
9985 (apps-dlink (org-remove-if-not
9986 'org-file-apps-entry-match-against-dlink-p file-apps))
9987 (remp (and (assq 'remote apps) (org-file-remote-p file)))
9988 (dirp (if remp nil (file-directory-p file)))
9989 (file (if (and dirp org-open-directory-means-index-dot-org)
9990 (concat (file-name-as-directory file) "index.org")
9991 file))
9992 (a-m-a-p (assq 'auto-mode apps))
9993 (dfile (downcase file))
9994 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
9995 (link (cond ((and (eq line nil)
9996 (eq search nil))
9997 file)
9998 (line
9999 (concat file "::" (number-to-string line)))
10000 (search
10001 (concat file "::" search))))
10002 (dlink (downcase link))
10003 (old-buffer (current-buffer))
10004 (old-pos (point))
10005 (old-mode major-mode)
10006 ext cmd link-match-data)
10007 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10008 (setq ext (match-string 1 dfile))
10009 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10010 (setq ext (match-string 1 dfile))))
10011 (cond
10012 ((member in-emacs '((16) system))
10013 (setq cmd (cdr (assoc 'system apps))))
10014 (in-emacs (setq cmd 'emacs))
10016 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10017 (and dirp (cdr (assoc 'directory apps)))
10018 ; first, try matching against apps-dlink
10019 ; if we get a match here, store the match data for later
10020 (let ((match (assoc-default dlink apps-dlink
10021 'string-match)))
10022 (if match
10023 (progn (setq link-match-data (match-data))
10024 match)
10025 (progn (setq in-emacs (or in-emacs line search))
10026 nil))) ; if we have no match in apps-dlink,
10027 ; always open the file in emacs if line or search
10028 ; is given (for backwards compatibility)
10029 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10030 'string-match)
10031 (cdr (assoc ext apps))
10032 (cdr (assoc t apps))))))
10033 (when (eq cmd 'system)
10034 (setq cmd (cdr (assoc 'system apps))))
10035 (when (eq cmd 'default)
10036 (setq cmd (cdr (assoc t apps))))
10037 (when (eq cmd 'mailcap)
10038 (require 'mailcap)
10039 (mailcap-parse-mailcaps)
10040 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10041 (command (mailcap-mime-info mime-type)))
10042 (if (stringp command)
10043 (setq cmd command)
10044 (setq cmd 'emacs))))
10045 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10046 (not (file-exists-p file))
10047 (not org-open-non-existing-files))
10048 (error "No such file: %s" file))
10049 (cond
10050 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10051 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10052 (while (string-match "['\"]%s['\"]" cmd)
10053 (setq cmd (replace-match "%s" t t cmd)))
10054 (while (string-match "%s" cmd)
10055 (setq cmd (replace-match
10056 (save-match-data
10057 (shell-quote-argument
10058 (convert-standard-filename file)))
10059 t t cmd)))
10061 ;; Replace "%1", "%2" etc. in command with group matches from regex
10062 (save-match-data
10063 (let ((match-index 1)
10064 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10065 (set-match-data link-match-data)
10066 (while (<= match-index number-of-groups)
10067 (let ((regex (concat "%" (number-to-string match-index)))
10068 (replace-with (match-string match-index dlink)))
10069 (while (string-match regex cmd)
10070 (setq cmd (replace-match replace-with t t cmd))))
10071 (setq match-index (+ match-index 1)))))
10073 (save-window-excursion
10074 (start-process-shell-command cmd nil cmd)
10075 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
10077 ((or (stringp cmd)
10078 (eq cmd 'emacs))
10079 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10080 (widen)
10081 (if line (org-goto-line line)
10082 (if search (org-link-search search))))
10083 ((consp cmd)
10084 (let ((file (convert-standard-filename file)))
10085 (save-match-data
10086 (set-match-data link-match-data)
10087 (eval cmd))))
10088 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10089 (and (org-mode-p) (eq old-mode 'org-mode)
10090 (or (not (equal old-buffer (current-buffer)))
10091 (not (equal old-pos (point))))
10092 (org-mark-ring-push old-pos old-buffer))))
10094 (defun org-file-apps-entry-match-against-dlink-p (entry)
10095 "This function returns non-nil if `entry' uses a regular
10096 expression which should be matched against the whole link by
10097 org-open-file.
10099 It assumes that is the case when the entry uses a regular
10100 expression which has at least one grouping construct and the
10101 action is either a lisp form or a command string containing
10102 '%1', i.e. using at least one subexpression match as a
10103 parameter."
10104 (let ((selector (car entry))
10105 (action (cdr entry)))
10106 (if (stringp selector)
10107 (and (> (regexp-opt-depth selector) 0)
10108 (or (and (stringp action)
10109 (string-match "%[0-9]" action))
10110 (consp action)))
10111 nil)))
10113 (defun org-default-apps ()
10114 "Return the default applications for this operating system."
10115 (cond
10116 ((eq system-type 'darwin)
10117 org-file-apps-defaults-macosx)
10118 ((eq system-type 'windows-nt)
10119 org-file-apps-defaults-windowsnt)
10120 (t org-file-apps-defaults-gnu)))
10122 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10123 "Convert extensions to regular expressions in the cars of LIST.
10124 Also, weed out any non-string entries, because the return value is used
10125 only for regexp matching.
10126 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10127 point to the symbol `emacs', indicating that the file should
10128 be opened in Emacs."
10129 (append
10130 (delq nil
10131 (mapcar (lambda (x)
10132 (if (not (stringp (car x)))
10134 (if (string-match "\\W" (car x))
10136 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10137 list))
10138 (if add-auto-mode
10139 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10141 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10142 (defun org-file-remote-p (file)
10143 "Test whether FILE specifies a location on a remote system.
10144 Return non-nil if the location is indeed remote.
10146 For example, the filename \"/user@host:/foo\" specifies a location
10147 on the system \"/user@host:\"."
10148 (cond ((fboundp 'file-remote-p)
10149 (file-remote-p file))
10150 ((fboundp 'tramp-handle-file-remote-p)
10151 (tramp-handle-file-remote-p file))
10152 ((and (boundp 'ange-ftp-name-format)
10153 (string-match (car ange-ftp-name-format) file))
10155 (t nil)))
10158 ;;;; Refiling
10160 (defun org-get-org-file ()
10161 "Read a filename, with default directory `org-directory'."
10162 (let ((default (or org-default-notes-file remember-data-file)))
10163 (read-file-name (format "File name [%s]: " default)
10164 (file-name-as-directory org-directory)
10165 default)))
10167 (defun org-notes-order-reversed-p ()
10168 "Check if the current file should receive notes in reversed order."
10169 (cond
10170 ((not org-reverse-note-order) nil)
10171 ((eq t org-reverse-note-order) t)
10172 ((not (listp org-reverse-note-order)) nil)
10173 (t (catch 'exit
10174 (let ((all org-reverse-note-order)
10175 entry)
10176 (while (setq entry (pop all))
10177 (if (string-match (car entry) buffer-file-name)
10178 (throw 'exit (cdr entry))))
10179 nil)))))
10181 (defvar org-refile-target-table nil
10182 "The list of refile targets, created by `org-refile'.")
10184 (defvar org-agenda-new-buffers nil
10185 "Buffers created to visit agenda files.")
10187 (defvar org-refile-cache nil
10188 "Cache for refile targets.")
10190 (defvar org-refile-markers nil
10191 "All the markers used for caching refile locations.")
10193 (defun org-refile-marker (pos)
10194 "Get a new refile marker, but only if caching is in use."
10195 (if (not org-refile-use-cache)
10197 (let ((m (make-marker)))
10198 (move-marker m pos)
10199 (push m org-refile-markers)
10200 m)))
10202 (defun org-refile-cache-clear ()
10203 "Clear the refile cache and disable all the markers."
10204 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
10205 (setq org-refile-markers nil)
10206 (setq org-refile-cache nil)
10207 (message "Refile cache has been cleared"))
10209 (defun org-refile-cache-check-set (set)
10210 "Check if all the markers in the cache still have live buffers."
10211 (let (marker)
10212 (catch 'exit
10213 (while (and set (setq marker (nth 3 (pop set))))
10214 ;; if org-refile-use-outline-path is 'file, marker may be nil
10215 (when (and marker (null (marker-buffer marker)))
10216 (message "not found") (sit-for 3)
10217 (throw 'exit nil)))
10218 t)))
10220 (defun org-refile-cache-put (set &rest identifiers)
10221 "Push the refile targets SET into the cache, under IDENTIFIERS."
10222 (let* ((key (sha1 (prin1-to-string identifiers)))
10223 (entry (assoc key org-refile-cache)))
10224 (if entry
10225 (setcdr entry set)
10226 (push (cons key set) org-refile-cache))))
10228 (defun org-refile-cache-get (&rest identifiers)
10229 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10230 (cond
10231 ((not org-refile-cache) nil)
10232 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10234 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10235 org-refile-cache))))
10236 (and set (org-refile-cache-check-set set) set)))))
10238 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
10239 "Produce a table with refile targets."
10240 (let ((case-fold-search nil)
10241 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10242 (entries (or org-refile-targets '((nil . (:level . 1)))))
10243 targets tgs txt re files f desc descre fast-path-p level pos0)
10244 (message "Getting targets...")
10245 (with-current-buffer (or default-buffer (current-buffer))
10246 (while (setq entry (pop entries))
10247 (setq files (car entry) desc (cdr entry))
10248 (setq fast-path-p nil)
10249 (cond
10250 ((null files) (setq files (list (current-buffer))))
10251 ((eq files 'org-agenda-files)
10252 (setq files (org-agenda-files 'unrestricted)))
10253 ((and (symbolp files) (fboundp files))
10254 (setq files (funcall files)))
10255 ((and (symbolp files) (boundp files))
10256 (setq files (symbol-value files))))
10257 (if (stringp files) (setq files (list files)))
10258 (cond
10259 ((eq (car desc) :tag)
10260 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
10261 ((eq (car desc) :todo)
10262 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
10263 ((eq (car desc) :regexp)
10264 (setq descre (cdr desc)))
10265 ((eq (car desc) :level)
10266 (setq descre (concat "^\\*\\{" (number-to-string
10267 (if org-odd-levels-only
10268 (1- (* 2 (cdr desc)))
10269 (cdr desc)))
10270 "\\}[ \t]")))
10271 ((eq (car desc) :maxlevel)
10272 (setq fast-path-p t)
10273 (setq descre (concat "^\\*\\{1," (number-to-string
10274 (if org-odd-levels-only
10275 (1- (* 2 (cdr desc)))
10276 (cdr desc)))
10277 "\\}[ \t]")))
10278 (t (error "Bad refiling target description %s" desc)))
10279 (while (setq f (pop files))
10280 (with-current-buffer
10281 (if (bufferp f) f (org-get-agenda-file-buffer f))
10283 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
10284 (progn
10285 (if (bufferp f) (setq f (buffer-file-name
10286 (buffer-base-buffer f))))
10287 (setq f (and f (expand-file-name f)))
10288 (if (eq org-refile-use-outline-path 'file)
10289 (push (list (file-name-nondirectory f) f nil nil) tgs))
10290 (save-excursion
10291 (save-restriction
10292 (widen)
10293 (goto-char (point-min))
10294 (while (re-search-forward descre nil t)
10295 (goto-char (setq pos0 (point-at-bol)))
10296 (catch 'next
10297 (when org-refile-target-verify-function
10298 (save-match-data
10299 (or (funcall org-refile-target-verify-function)
10300 (throw 'next t))))
10301 (when (and (looking-at org-complex-heading-regexp)
10302 (not (member (match-string 4) excluded-entries)))
10303 (setq level (org-reduced-level
10304 (- (match-end 1) (match-beginning 1)))
10305 txt (org-link-display-format (match-string 4))
10306 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
10307 re (format org-complex-heading-regexp-format
10308 (regexp-quote (match-string 4))))
10309 (when org-refile-use-outline-path
10310 (setq txt (mapconcat
10311 'org-protect-slash
10312 (append
10313 (if (eq org-refile-use-outline-path
10314 'file)
10315 (list (file-name-nondirectory
10316 (buffer-file-name
10317 (buffer-base-buffer))))
10318 (if (eq org-refile-use-outline-path
10319 'full-file-path)
10320 (list (buffer-file-name
10321 (buffer-base-buffer)))))
10322 (org-get-outline-path fast-path-p
10323 level txt)
10324 (list txt))
10325 "/")))
10326 (push (list txt f re (org-refile-marker (point)))
10327 tgs)))
10328 (when (= (point) pos0)
10329 ;; verification function has not moved point
10330 (goto-char (point-at-eol))))))))
10331 (when org-refile-use-cache
10332 (org-refile-cache-put tgs (buffer-file-name) descre))
10333 (setq targets (append tgs targets))
10334 ))))
10335 (message "Getting targets...done")
10336 (nreverse targets)))
10338 (defun org-protect-slash (s)
10339 (while (string-match "/" s)
10340 (setq s (replace-match "\\" t t s)))
10343 (defvar org-olpa (make-vector 20 nil))
10345 (defun org-get-outline-path (&optional fastp level heading)
10346 "Return the outline path to the current entry, as a list.
10348 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
10349 routine which makes outline path derivations for an entire file,
10350 avoiding backtracing. Refile target collection makes use of that."
10351 (if fastp
10352 (progn
10353 (if (> level 19)
10354 (error "Outline path failure, more than 19 levels"))
10355 (loop for i from level upto 19 do
10356 (aset org-olpa i nil))
10357 (prog1
10358 (delq nil (append org-olpa nil))
10359 (aset org-olpa level heading)))
10360 (let (rtn case-fold-search)
10361 (save-excursion
10362 (save-restriction
10363 (widen)
10364 (while (org-up-heading-safe)
10365 (when (looking-at org-complex-heading-regexp)
10366 (push (org-match-string-no-properties 4) rtn)))
10367 rtn)))))
10369 (defun org-format-outline-path (path &optional width prefix)
10370 "Format the outline path PATH for display.
10371 Width is the maximum number of characters that is available.
10372 Prefix is a prefix to be included in the returned string,
10373 such as the file name."
10374 (setq width (or width 79))
10375 (if prefix (setq width (- width (length prefix))))
10376 (if (not path)
10377 (or prefix "")
10378 (let* ((nsteps (length path))
10379 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
10380 (maxwidth (if (<= total-width width)
10381 10000 ;; everything fits
10382 ;; we need to shorten the level headings
10383 (/ (- width nsteps) nsteps)))
10384 (org-odd-levels-only nil)
10385 (n 0)
10386 (total (1+ (length prefix))))
10387 (setq maxwidth (max maxwidth 10))
10388 (concat prefix
10389 (mapconcat
10390 (lambda (h)
10391 (setq n (1+ n))
10392 (if (and (= n nsteps) (< maxwidth 10000))
10393 (setq maxwidth (- total-width total)))
10394 (if (< (length h) maxwidth)
10395 (progn (setq total (+ total (length h) 1)) h)
10396 (setq h (substring h 0 (- maxwidth 2))
10397 total (+ total maxwidth 1))
10398 (if (string-match "[ \t]+\\'" h)
10399 (setq h (substring h 0 (match-beginning 0))))
10400 (setq h (concat h "..")))
10401 (org-add-props h nil 'face
10402 (nth (% (1- n) org-n-level-faces)
10403 org-level-faces))
10405 path "/")))))
10407 (defun org-display-outline-path (&optional file current)
10408 "Display the current outline path in the echo area."
10409 (interactive "P")
10410 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
10411 (case-fold-search nil)
10412 (path (and (org-mode-p) (org-get-outline-path))))
10413 (if current (setq path (append path
10414 (save-excursion
10415 (org-back-to-heading t)
10416 (if (looking-at org-complex-heading-regexp)
10417 (list (match-string 4)))))))
10418 (message "%s"
10419 (org-format-outline-path
10420 path
10421 (1- (frame-width))
10422 (and file bfn (concat (file-name-nondirectory bfn) "/"))))))
10424 (defvar org-refile-history nil
10425 "History for refiling operations.")
10427 (defvar org-after-refile-insert-hook nil
10428 "Hook run after `org-refile' has inserted its stuff at the new location.
10429 Note that this is still *before* the stuff will be removed from
10430 the *old* location.")
10432 (defvar org-capture-last-stored-marker)
10433 (defun org-refile (&optional goto default-buffer rfloc)
10434 "Move the entry or entries at point to another heading.
10435 The list of target headings is compiled using the information in
10436 `org-refile-targets', which see.
10438 At the target location, the entry is filed as a subitem of the target
10439 heading. Depending on `org-reverse-note-order', the new subitem will
10440 either be the first or the last subitem.
10442 If there is an active region, all entries in that region will be moved.
10443 However, the region must fulfill the requirement that the first heading
10444 is the first one sets the top-level of the moved text - at most siblings
10445 below it are allowed.
10447 With prefix arg GOTO, the command will only visit the target location
10448 and not actually move anything.
10450 With a double prefix arg \\[universal-argument] \\[universal-argument], \
10451 go to the location where the last refiling operation has put the subtree.
10452 With a prefix argument of `2', refile to the running clock.
10454 RFLOC can be a refile location obtained in a different way.
10456 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
10458 If you are using target caching (see `org-refile-use-cache'),
10459 You have to clear the target cache in order to find new targets.
10460 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
10461 prefix argument (`C-u C-u C-u C-c C-w')."
10463 (interactive "P")
10464 (if (member goto '(0 (64)))
10465 (org-refile-cache-clear)
10466 (let* ((cbuf (current-buffer))
10467 (regionp (org-region-active-p))
10468 (region-start (and regionp (region-beginning)))
10469 (region-end (and regionp (region-end)))
10470 (region-length (and regionp (- region-end region-start)))
10471 (filename (buffer-file-name (buffer-base-buffer cbuf)))
10472 pos it nbuf file re level reversed)
10473 (setq last-command nil)
10474 (when regionp
10475 (goto-char region-start)
10476 (or (bolp) (goto-char (point-at-bol)))
10477 (setq region-start (point))
10478 (unless (or (org-kill-is-subtree-p
10479 (buffer-substring region-start region-end))
10480 (prog1 org-refile-active-region-within-subtree
10481 (org-toggle-heading)))
10482 (error "The region is not a (sequence of) subtree(s)")))
10483 (if (equal goto '(16))
10484 (org-refile-goto-last-stored)
10485 (when (or
10486 (and (equal goto 2)
10487 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
10488 (prog1
10489 (setq it (list (or org-clock-heading "running clock")
10490 (buffer-file-name
10491 (marker-buffer org-clock-hd-marker))
10493 (marker-position org-clock-hd-marker)))
10494 (setq goto nil)))
10495 (setq it (or rfloc
10496 (save-excursion
10497 (org-back-to-heading t)
10498 (org-refile-get-location
10499 (cond (goto "Goto")
10500 (regionp "Refile region to")
10501 (t "Refile subtree to")) default-buffer
10502 org-refile-allow-creating-parent-nodes)))))
10503 (setq file (nth 1 it)
10504 re (nth 2 it)
10505 pos (nth 3 it))
10506 (if (and (not goto)
10508 (equal (buffer-file-name) file)
10509 (if regionp
10510 (and (>= pos region-start)
10511 (<= pos region-end))
10512 (and (>= pos (point))
10513 (< pos (save-excursion
10514 (org-end-of-subtree t t))))))
10515 (error "Cannot refile to position inside the tree or region"))
10517 (setq nbuf (or (find-buffer-visiting file)
10518 (find-file-noselect file)))
10519 (if goto
10520 (progn
10521 (org-pop-to-buffer-same-window nbuf)
10522 (goto-char pos)
10523 (org-show-context 'org-goto))
10524 (if regionp
10525 (progn
10526 (org-kill-new (buffer-substring region-start region-end))
10527 (org-save-markers-in-region region-start region-end))
10528 (org-copy-subtree 1 nil t))
10529 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
10530 (find-file-noselect file)))
10531 (setq reversed (org-notes-order-reversed-p))
10532 (save-excursion
10533 (save-restriction
10534 (widen)
10535 (if pos
10536 (progn
10537 (goto-char pos)
10538 (looking-at org-outline-regexp)
10539 (setq level (org-get-valid-level (funcall outline-level) 1))
10540 (goto-char
10541 (if reversed
10542 (or (outline-next-heading) (point-max))
10543 (or (save-excursion (org-get-next-sibling))
10544 (org-end-of-subtree t t)
10545 (point-max)))))
10546 (setq level 1)
10547 (if (not reversed)
10548 (goto-char (point-max))
10549 (goto-char (point-min))
10550 (or (outline-next-heading) (goto-char (point-max)))))
10551 (if (not (bolp)) (newline))
10552 (org-paste-subtree level)
10553 (when org-log-refile
10554 (org-add-log-setup 'refile nil nil 'findpos
10555 org-log-refile)
10556 (unless (eq org-log-refile 'note)
10557 (save-excursion (org-add-log-note))))
10558 (and org-auto-align-tags (org-set-tags nil t))
10559 (bookmark-set "org-refile-last-stored")
10560 ;; If we are refiling for capture, make sure that the
10561 ;; last-capture pointers point here
10562 (when (org-bound-and-true-p org-refile-for-capture)
10563 (bookmark-set "org-capture-last-stored-marker")
10564 (move-marker org-capture-last-stored-marker (point)))
10565 (if (fboundp 'deactivate-mark) (deactivate-mark))
10566 (run-hooks 'org-after-refile-insert-hook))))
10567 (if regionp
10568 (delete-region (point) (+ (point) region-length))
10569 (org-cut-subtree))
10570 (when (featurep 'org-inlinetask)
10571 (org-inlinetask-remove-END-maybe))
10572 (setq org-markers-to-move nil)
10573 (message "Refiled to \"%s\" in file %s" (car it) file)))))))
10575 (defun org-refile-goto-last-stored ()
10576 "Go to the location where the last refile was stored."
10577 (interactive)
10578 (bookmark-jump "org-refile-last-stored")
10579 (message "This is the location of the last refile"))
10581 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
10582 "Prompt the user for a refile location, using PROMPT.
10583 PROMPT should not be suffixed with a colon and a space, because
10584 this function appends the default value from
10585 `org-refile-history' automatically, if that is not empty."
10586 (let ((org-refile-targets org-refile-targets)
10587 (org-refile-use-outline-path org-refile-use-outline-path)
10588 excluded-entries)
10589 (when (and (eq major-mode 'org-mode)
10590 (not org-refile-use-cache))
10591 (org-map-tree
10592 (lambda()
10593 (setq excluded-entries
10594 (append excluded-entries (list (org-get-heading t t)))))))
10595 (setq org-refile-target-table
10596 (org-refile-get-targets default-buffer excluded-entries)))
10597 (unless org-refile-target-table
10598 (error "No refile targets"))
10599 (let* ((prompt (concat prompt
10600 (and (car org-refile-history)
10601 (concat " (default " (car org-refile-history) ")"))
10602 ": "))
10603 (cbuf (current-buffer))
10604 (partial-completion-mode nil)
10605 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
10606 (cfunc (if (and org-refile-use-outline-path
10607 org-outline-path-complete-in-steps)
10608 'org-olpath-completing-read
10609 'org-icompleting-read))
10610 (extra (if org-refile-use-outline-path "/" ""))
10611 (filename (and cfn (expand-file-name cfn)))
10612 (tbl (mapcar
10613 (lambda (x)
10614 (if (and (not (member org-refile-use-outline-path
10615 '(file full-file-path)))
10616 (not (equal filename (nth 1 x))))
10617 (cons (concat (car x) extra " ("
10618 (file-name-nondirectory (nth 1 x)) ")")
10619 (cdr x))
10620 (cons (concat (car x) extra) (cdr x))))
10621 org-refile-target-table))
10622 (completion-ignore-case t)
10623 pa answ parent-target child parent old-hist)
10624 (setq old-hist org-refile-history)
10625 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
10626 nil 'org-refile-history (car org-refile-history)))
10627 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
10628 (org-refile-check-position pa)
10629 (if pa
10630 (progn
10631 (when (or (not org-refile-history)
10632 (not (eq old-hist org-refile-history))
10633 (not (equal (car pa) (car org-refile-history))))
10634 (setq org-refile-history
10635 (cons (car pa) (if (assoc (car org-refile-history) tbl)
10636 org-refile-history
10637 (cdr org-refile-history))))
10638 (if (equal (car org-refile-history) (nth 1 org-refile-history))
10639 (pop org-refile-history)))
10641 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
10642 (progn
10643 (setq parent (match-string 1 answ)
10644 child (match-string 2 answ))
10645 (setq parent-target (or (assoc parent tbl)
10646 (assoc (concat parent "/") tbl)))
10647 (when (and parent-target
10648 (or (eq new-nodes t)
10649 (and (eq new-nodes 'confirm)
10650 (y-or-n-p (format "Create new node \"%s\"? "
10651 child)))))
10652 (org-refile-new-child parent-target child)))
10653 (error "Invalid target location")))))
10655 (defun org-refile-check-position (refile-pointer)
10656 "Check if the refile pointer matches the readline to which it points."
10657 (let* ((file (nth 1 refile-pointer))
10658 (re (nth 2 refile-pointer))
10659 (pos (nth 3 refile-pointer))
10660 buffer)
10661 (when (org-string-nw-p re)
10662 (setq buffer (if (markerp pos)
10663 (marker-buffer pos)
10664 (or (find-buffer-visiting file)
10665 (find-file-noselect file))))
10666 (with-current-buffer buffer
10667 (save-excursion
10668 (save-restriction
10669 (widen)
10670 (goto-char pos)
10671 (beginning-of-line 1)
10672 (unless (org-looking-at-p re)
10673 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
10675 (defun org-refile-new-child (parent-target child)
10676 "Use refile target PARENT-TARGET to add new CHILD below it."
10677 (unless parent-target
10678 (error "Cannot find parent for new node"))
10679 (let ((file (nth 1 parent-target))
10680 (pos (nth 3 parent-target))
10681 level)
10682 (with-current-buffer (or (find-buffer-visiting file)
10683 (find-file-noselect file))
10684 (save-excursion
10685 (save-restriction
10686 (widen)
10687 (if pos
10688 (goto-char pos)
10689 (goto-char (point-max))
10690 (if (not (bolp)) (newline)))
10691 (when (looking-at org-outline-regexp)
10692 (setq level (funcall outline-level))
10693 (org-end-of-subtree t t))
10694 (org-back-over-empty-lines)
10695 (insert "\n" (make-string
10696 (if pos (org-get-valid-level level 1) 1) ?*)
10697 " " child "\n")
10698 (beginning-of-line 0)
10699 (list (concat (car parent-target) "/" child) file "" (point)))))))
10701 (defun org-olpath-completing-read (prompt collection &rest args)
10702 "Read an outline path like a file name."
10703 (let ((thetable collection)
10704 (org-completion-use-ido nil) ; does not work with ido.
10705 (org-completion-use-iswitchb nil)) ; or iswitchb
10706 (apply
10707 'org-icompleting-read prompt
10708 (lambda (string predicate &optional flag)
10709 (let (rtn r f (l (length string)))
10710 (cond
10711 ((eq flag nil)
10712 ;; try completion
10713 (try-completion string thetable))
10714 ((eq flag t)
10715 ;; all-completions
10716 (setq rtn (all-completions string thetable predicate))
10717 (mapcar
10718 (lambda (x)
10719 (setq r (substring x l))
10720 (if (string-match " ([^)]*)$" x)
10721 (setq f (match-string 0 x))
10722 (setq f ""))
10723 (if (string-match "/" r)
10724 (concat string (substring r 0 (match-end 0)) f)
10726 rtn))
10727 ((eq flag 'lambda)
10728 ;; exact match?
10729 (assoc string thetable)))
10731 args)))
10733 ;;;; Dynamic blocks
10735 (defun org-find-dblock (name)
10736 "Find the first dynamic block with name NAME in the buffer.
10737 If not found, stay at current position and return nil."
10738 (let (pos)
10739 (save-excursion
10740 (goto-char (point-min))
10741 (setq pos (and (re-search-forward (concat "^[ \t]*#\\+BEGIN:[ \t]+" name "\\>")
10742 nil t)
10743 (match-beginning 0))))
10744 (if pos (goto-char pos))
10745 pos))
10747 (defconst org-dblock-start-re
10748 "^[ \t]*#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
10749 "Matches the start line of a dynamic block, with parameters.")
10751 (defconst org-dblock-end-re "^[ \t]*#\\+END\\([: \t\r\n]\\|$\\)"
10752 "Matches the end of a dynamic block.")
10754 (defun org-create-dblock (plist)
10755 "Create a dynamic block section, with parameters taken from PLIST.
10756 PLIST must contain a :name entry which is used as name of the block."
10757 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
10758 (end-of-line 1)
10759 (newline))
10760 (let ((col (current-column))
10761 (name (plist-get plist :name)))
10762 (insert "#+BEGIN: " name)
10763 (while plist
10764 (if (eq (car plist) :name)
10765 (setq plist (cddr plist))
10766 (insert " " (prin1-to-string (pop plist)))))
10767 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
10768 (beginning-of-line -2)))
10770 (defun org-prepare-dblock ()
10771 "Prepare dynamic block for refresh.
10772 This empties the block, puts the cursor at the insert position and returns
10773 the property list including an extra property :name with the block name."
10774 (unless (looking-at org-dblock-start-re)
10775 (error "Not at a dynamic block"))
10776 (let* ((begdel (1+ (match-end 0)))
10777 (name (org-no-properties (match-string 1)))
10778 (params (append (list :name name)
10779 (read (concat "(" (match-string 3) ")")))))
10780 (save-excursion
10781 (beginning-of-line 1)
10782 (skip-chars-forward " \t")
10783 (setq params (plist-put params :indentation-column (current-column))))
10784 (unless (re-search-forward org-dblock-end-re nil t)
10785 (error "Dynamic block not terminated"))
10786 (setq params
10787 (append params
10788 (list :content (buffer-substring
10789 begdel (match-beginning 0)))))
10790 (delete-region begdel (match-beginning 0))
10791 (goto-char begdel)
10792 (open-line 1)
10793 params))
10795 (defun org-map-dblocks (&optional command)
10796 "Apply COMMAND to all dynamic blocks in the current buffer.
10797 If COMMAND is not given, use `org-update-dblock'."
10798 (let ((cmd (or command 'org-update-dblock)))
10799 (save-excursion
10800 (goto-char (point-min))
10801 (while (re-search-forward org-dblock-start-re nil t)
10802 (goto-char (match-beginning 0))
10803 (save-excursion
10804 (condition-case nil
10805 (funcall cmd)
10806 (error (message "Error during update of dynamic block"))))
10807 (unless (re-search-forward org-dblock-end-re nil t)
10808 (error "Dynamic block not terminated"))))))
10810 (defun org-dblock-update (&optional arg)
10811 "User command for updating dynamic blocks.
10812 Update the dynamic block at point. With prefix ARG, update all dynamic
10813 blocks in the buffer."
10814 (interactive "P")
10815 (if arg
10816 (org-update-all-dblocks)
10817 (or (looking-at org-dblock-start-re)
10818 (org-beginning-of-dblock))
10819 (org-update-dblock)))
10821 (defun org-update-dblock ()
10822 "Update the dynamic block at point.
10823 This means to empty the block, parse for parameters and then call
10824 the correct writing function."
10825 (interactive)
10826 (save-window-excursion
10827 (let* ((pos (point))
10828 (line (org-current-line))
10829 (params (org-prepare-dblock))
10830 (name (plist-get params :name))
10831 (indent (plist-get params :indentation-column))
10832 (cmd (intern (concat "org-dblock-write:" name))))
10833 (message "Updating dynamic block `%s' at line %d..." name line)
10834 (funcall cmd params)
10835 (message "Updating dynamic block `%s' at line %d...done" name line)
10836 (goto-char pos)
10837 (when (and indent (> indent 0))
10838 (setq indent (make-string indent ?\ ))
10839 (save-excursion
10840 (org-beginning-of-dblock)
10841 (forward-line 1)
10842 (while (not (looking-at org-dblock-end-re))
10843 (insert indent)
10844 (beginning-of-line 2))
10845 (when (looking-at org-dblock-end-re)
10846 (and (looking-at "[ \t]+")
10847 (replace-match ""))
10848 (insert indent)))))))
10850 (defun org-beginning-of-dblock ()
10851 "Find the beginning of the dynamic block at point.
10852 Error if there is no such block at point."
10853 (let ((pos (point))
10854 beg)
10855 (end-of-line 1)
10856 (if (and (re-search-backward org-dblock-start-re nil t)
10857 (setq beg (match-beginning 0))
10858 (re-search-forward org-dblock-end-re nil t)
10859 (> (match-end 0) pos))
10860 (goto-char beg)
10861 (goto-char pos)
10862 (error "Not in a dynamic block"))))
10864 (defun org-update-all-dblocks ()
10865 "Update all dynamic blocks in the buffer.
10866 This function can be used in a hook."
10867 (interactive)
10868 (when (org-mode-p)
10869 (org-map-dblocks 'org-update-dblock)))
10872 ;;;; Completion
10874 (defconst org-additional-option-like-keywords
10875 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML:"
10876 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook:"
10877 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"
10878 "LATEX_CLASS:" "LATEX_CLASS_OPTIONS:" "ATTR_LaTeX:"
10879 "BEGIN:" "END:"
10880 "ORGTBL" "TBLFM:" "TBLNAME:"
10881 "BEGIN_EXAMPLE" "END_EXAMPLE"
10882 "BEGIN_QUOTE" "END_QUOTE"
10883 "BEGIN_VERSE" "END_VERSE"
10884 "BEGIN_CENTER" "END_CENTER"
10885 "BEGIN_SRC" "END_SRC"
10886 "BEGIN_RESULT" "END_RESULT"
10887 "SOURCE:" "SRCNAME:" "FUNCTION:"
10888 "RESULTS:" "DATA:"
10889 "HEADER:" "HEADERS:"
10890 "BABEL:"
10891 "CATEGORY:" "COLUMNS:" "PROPERTY:"
10892 "CAPTION:" "LABEL:"
10893 "SETUPFILE:"
10894 "INCLUDE:"
10895 "BIND:"
10896 "MACRO:"))
10898 (defcustom org-structure-template-alist
10900 ("s" "#+begin_src ?\n\n#+end_src"
10901 "<src lang=\"?\">\n\n</src>")
10902 ("e" "#+begin_example\n?\n#+end_example"
10903 "<example>\n?\n</example>")
10904 ("q" "#+begin_quote\n?\n#+end_quote"
10905 "<quote>\n?\n</quote>")
10906 ("v" "#+begin_verse\n?\n#+end_verse"
10907 "<verse>\n?\n/verse>")
10908 ("c" "#+begin_center\n?\n#+end_center"
10909 "<center>\n?\n/center>")
10910 ("l" "#+begin_latex\n?\n#+end_latex"
10911 "<literal style=\"latex\">\n?\n</literal>")
10912 ("L" "#+latex: "
10913 "<literal style=\"latex\">?</literal>")
10914 ("h" "#+begin_html\n?\n#+end_html"
10915 "<literal style=\"html\">\n?\n</literal>")
10916 ("H" "#+html: "
10917 "<literal style=\"html\">?</literal>")
10918 ("a" "#+begin_ascii\n?\n#+end_ascii")
10919 ("A" "#+ascii: ")
10920 ("i" "#+index: ?"
10921 "#+index: ?")
10922 ("I" "#+include %file ?"
10923 "<include file=%file markup=\"?\">")
10925 "Structure completion elements.
10926 This is a list of abbreviation keys and values. The value gets inserted
10927 if you type `<' followed by the key and then press the completion key,
10928 usually `M-TAB'. %file will be replaced by a file name after prompting
10929 for the file using completion. The cursor will be placed at the position
10930 of the `?` in the template.
10931 There are two templates for each key, the first uses the original Org syntax,
10932 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
10933 the default when the /org-mtags.el/ module has been loaded. See also the
10934 variable `org-mtags-prefer-muse-templates'.
10935 This is an experimental feature, it is undecided if it is going to stay in."
10936 :group 'org-completion
10937 :type '(repeat
10938 (string :tag "Key")
10939 (string :tag "Template")
10940 (string :tag "Muse Template")))
10942 (defun org-try-structure-completion ()
10943 "Try to complete a structure template before point.
10944 This looks for strings like \"<e\" on an otherwise empty line and
10945 expands them."
10946 (let ((l (buffer-substring (point-at-bol) (point)))
10948 (when (and (looking-at "[ \t]*$")
10949 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
10950 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
10951 (org-complete-expand-structure-template (+ -1 (point-at-bol)
10952 (match-beginning 1)) a)
10953 t)))
10955 (defun org-complete-expand-structure-template (start cell)
10956 "Expand a structure template."
10957 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
10958 (rpl (nth (if musep 2 1) cell))
10959 (ind ""))
10960 (delete-region start (point))
10961 (when (string-match "\\`#\\+" rpl)
10962 (cond
10963 ((bolp))
10964 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
10965 (setq ind (buffer-substring (point-at-bol) (point))))
10966 (t (newline))))
10967 (setq start (point))
10968 (if (string-match "%file" rpl)
10969 (setq rpl (replace-match
10970 (concat
10971 "\""
10972 (save-match-data
10973 (abbreviate-file-name (read-file-name "Include file: ")))
10974 "\"")
10975 t t rpl)))
10976 (setq rpl (mapconcat 'identity (split-string rpl "\n")
10977 (concat "\n" ind)))
10978 (insert rpl)
10979 (if (re-search-backward "\\?" start t) (delete-char 1))))
10981 ;;;; TODO, DEADLINE, Comments
10983 (defun org-toggle-comment ()
10984 "Change the COMMENT state of an entry."
10985 (interactive)
10986 (save-excursion
10987 (org-back-to-heading)
10988 (let (case-fold-search)
10989 (if (looking-at (concat org-outline-regexp
10990 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
10991 (replace-match "" t t nil 1)
10992 (if (looking-at org-outline-regexp)
10993 (progn
10994 (goto-char (match-end 0))
10995 (insert org-comment-string " ")))))))
10997 (defvar org-last-todo-state-is-todo nil
10998 "This is non-nil when the last TODO state change led to a TODO state.
10999 If the last change removed the TODO tag or switched to DONE, then
11000 this is nil.")
11002 (defvar org-setting-tags nil) ; dynamically skipped
11004 (defvar org-todo-setup-filter-hook nil
11005 "Hook for functions that pre-filter todo specs.
11006 Each function takes a todo spec and returns either nil or the spec
11007 transformed into canonical form." )
11009 (defvar org-todo-get-default-hook nil
11010 "Hook for functions that get a default item for todo.
11011 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11012 nil or a string to be used for the todo mark." )
11014 (defvar org-agenda-headline-snapshot-before-repeat)
11016 (defun org-current-effective-time ()
11017 "Return current time adjusted for `org-extend-today-until' variable"
11018 (let* ((ct (org-current-time))
11019 (dct (decode-time ct))
11020 (ct1
11021 (if (and org-use-effective-time
11022 (< (nth 2 dct) org-extend-today-until))
11023 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct))
11024 ct)))
11025 ct1))
11027 (defun org-todo-yesterday (&optional arg)
11028 "Like `org-todo' but the time of change will be 23:59 of yesterday"
11029 (interactive "P")
11030 (let* ((hour (third (decode-time
11031 (org-current-time))))
11032 (org-extend-today-until (1+ hour)))
11033 (org-todo arg)))
11035 (defun org-todo (&optional arg)
11036 "Change the TODO state of an item.
11037 The state of an item is given by a keyword at the start of the heading,
11038 like
11039 *** TODO Write paper
11040 *** DONE Call mom
11042 The different keywords are specified in the variable `org-todo-keywords'.
11043 By default the available states are \"TODO\" and \"DONE\".
11044 So for this example: when the item starts with TODO, it is changed to DONE.
11045 When it starts with DONE, the DONE is removed. And when neither TODO nor
11046 DONE are present, add TODO at the beginning of the heading.
11048 With \\[universal-argument] prefix arg, use completion to determine the new \
11049 state.
11050 With numeric prefix arg, switch to that state.
11051 With a double \\[universal-argument] prefix, switch to the next set of TODO \
11052 keywords (nextset).
11053 With a triple \\[universal-argument] prefix, circumvent any state blocking.
11055 For calling through lisp, arg is also interpreted in the following way:
11056 'none -> empty state
11057 \"\"(empty string) -> switch to empty state
11058 'done -> switch to DONE
11059 'nextset -> switch to the next set of keywords
11060 'previousset -> switch to the previous set of keywords
11061 \"WAITING\" -> switch to the specified keyword, but only if it
11062 really is a member of `org-todo-keywords'."
11063 (interactive "P")
11064 (if (equal arg '(16)) (setq arg 'nextset))
11065 (let ((org-blocker-hook org-blocker-hook)
11066 (case-fold-search nil))
11067 (when (equal arg '(64))
11068 (setq arg nil org-blocker-hook nil))
11069 (when (and org-blocker-hook
11070 (or org-inhibit-blocking
11071 (org-entry-get nil "NOBLOCKING")))
11072 (setq org-blocker-hook nil))
11073 (save-excursion
11074 (catch 'exit
11075 (org-back-to-heading t)
11076 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
11077 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|$\\)"))
11078 (looking-at " *"))
11079 (let* ((match-data (match-data))
11080 (startpos (point-at-bol))
11081 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
11082 (org-log-done org-log-done)
11083 (org-log-repeat org-log-repeat)
11084 (org-todo-log-states org-todo-log-states)
11085 (this (match-string 1))
11086 (hl-pos (match-beginning 0))
11087 (head (org-get-todo-sequence-head this))
11088 (ass (assoc head org-todo-kwd-alist))
11089 (interpret (nth 1 ass))
11090 (done-word (nth 3 ass))
11091 (final-done-word (nth 4 ass))
11092 (last-state (or this ""))
11093 (completion-ignore-case t)
11094 (member (member this org-todo-keywords-1))
11095 (tail (cdr member))
11096 (state (cond
11097 ((and org-todo-key-trigger
11098 (or (and (equal arg '(4))
11099 (eq org-use-fast-todo-selection 'prefix))
11100 (and (not arg) org-use-fast-todo-selection
11101 (not (eq org-use-fast-todo-selection
11102 'prefix)))))
11103 ;; Use fast selection
11104 (org-fast-todo-selection))
11105 ((and (equal arg '(4))
11106 (or (not org-use-fast-todo-selection)
11107 (not org-todo-key-trigger)))
11108 ;; Read a state with completion
11109 (org-icompleting-read
11110 "State: " (mapcar (lambda(x) (list x))
11111 org-todo-keywords-1)
11112 nil t))
11113 ((eq arg 'right)
11114 (if this
11115 (if tail (car tail) nil)
11116 (car org-todo-keywords-1)))
11117 ((eq arg 'left)
11118 (if (equal member org-todo-keywords-1)
11120 (if this
11121 (nth (- (length org-todo-keywords-1)
11122 (length tail) 2)
11123 org-todo-keywords-1)
11124 (org-last org-todo-keywords-1))))
11125 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
11126 (setq arg nil))) ; hack to fall back to cycling
11127 (arg
11128 ;; user or caller requests a specific state
11129 (cond
11130 ((equal arg "") nil)
11131 ((eq arg 'none) nil)
11132 ((eq arg 'done) (or done-word (car org-done-keywords)))
11133 ((eq arg 'nextset)
11134 (or (car (cdr (member head org-todo-heads)))
11135 (car org-todo-heads)))
11136 ((eq arg 'previousset)
11137 (let ((org-todo-heads (reverse org-todo-heads)))
11138 (or (car (cdr (member head org-todo-heads)))
11139 (car org-todo-heads))))
11140 ((car (member arg org-todo-keywords-1)))
11141 ((stringp arg)
11142 (error "State `%s' not valid in this file" arg))
11143 ((nth (1- (prefix-numeric-value arg))
11144 org-todo-keywords-1))))
11145 ((null member) (or head (car org-todo-keywords-1)))
11146 ((equal this final-done-word) nil) ;; -> make empty
11147 ((null tail) nil) ;; -> first entry
11148 ((memq interpret '(type priority))
11149 (if (eq this-command last-command)
11150 (car tail)
11151 (if (> (length tail) 0)
11152 (or done-word (car org-done-keywords))
11153 nil)))
11155 (car tail))))
11156 (state (or
11157 (run-hook-with-args-until-success
11158 'org-todo-get-default-hook state last-state)
11159 state))
11160 (next (if state (concat " " state " ") " "))
11161 (change-plist (list :type 'todo-state-change :from this :to state
11162 :position startpos))
11163 dolog now-done-p)
11164 (when org-blocker-hook
11165 (setq org-last-todo-state-is-todo
11166 (not (member this org-done-keywords)))
11167 (unless (save-excursion
11168 (save-match-data
11169 (org-with-wide-buffer
11170 (run-hook-with-args-until-failure
11171 'org-blocker-hook change-plist))))
11172 (if (org-called-interactively-p 'interactive)
11173 (error "TODO state change from %s to %s blocked" this state)
11174 ;; fail silently
11175 (message "TODO state change from %s to %s blocked" this state)
11176 (throw 'exit nil))))
11177 (store-match-data match-data)
11178 (replace-match next t t)
11179 (unless (pos-visible-in-window-p hl-pos)
11180 (message "TODO state changed to %s" (org-trim next)))
11181 (unless head
11182 (setq head (org-get-todo-sequence-head state)
11183 ass (assoc head org-todo-kwd-alist)
11184 interpret (nth 1 ass)
11185 done-word (nth 3 ass)
11186 final-done-word (nth 4 ass)))
11187 (when (memq arg '(nextset previousset))
11188 (message "Keyword-Set %d/%d: %s"
11189 (- (length org-todo-sets) -1
11190 (length (memq (assoc state org-todo-sets) org-todo-sets)))
11191 (length org-todo-sets)
11192 (mapconcat 'identity (assoc state org-todo-sets) " ")))
11193 (setq org-last-todo-state-is-todo
11194 (not (member state org-done-keywords)))
11195 (setq now-done-p (and (member state org-done-keywords)
11196 (not (member this org-done-keywords))))
11197 (and logging (org-local-logging logging))
11198 (when (and (or org-todo-log-states org-log-done)
11199 (not (eq org-inhibit-logging t))
11200 (not (memq arg '(nextset previousset))))
11201 ;; we need to look at recording a time and note
11202 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
11203 (nth 2 (assoc this org-todo-log-states))))
11204 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
11205 (setq dolog 'time))
11206 (when (and state
11207 (member state org-not-done-keywords)
11208 (not (member this org-not-done-keywords)))
11209 ;; This is now a todo state and was not one before
11210 ;; If there was a CLOSED time stamp, get rid of it.
11211 (org-add-planning-info nil nil 'closed))
11212 (when (and now-done-p org-log-done)
11213 ;; It is now done, and it was not done before
11214 (org-add-planning-info 'closed (org-current-effective-time))
11215 (if (and (not dolog) (eq 'note org-log-done))
11216 (org-add-log-setup 'done state this 'findpos 'note)))
11217 (when (and state dolog)
11218 ;; This is a non-nil state, and we need to log it
11219 (org-add-log-setup 'state state this 'findpos dolog)))
11220 ;; Fixup tag positioning
11221 (org-todo-trigger-tag-changes state)
11222 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
11223 (when org-provide-todo-statistics
11224 (org-update-parent-todo-statistics))
11225 (run-hooks 'org-after-todo-state-change-hook)
11226 (if (and arg (not (member state org-done-keywords)))
11227 (setq head (org-get-todo-sequence-head state)))
11228 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
11229 ;; Do we need to trigger a repeat?
11230 (when now-done-p
11231 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
11232 ;; This is for the agenda, take a snapshot of the headline.
11233 (save-match-data
11234 (setq org-agenda-headline-snapshot-before-repeat
11235 (org-get-heading))))
11236 (org-auto-repeat-maybe state))
11237 ;; Fixup cursor location if close to the keyword
11238 (if (and (outline-on-heading-p)
11239 (not (bolp))
11240 (save-excursion (beginning-of-line 1)
11241 (looking-at org-todo-line-regexp))
11242 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
11243 (progn
11244 (goto-char (or (match-end 2) (match-end 1)))
11245 (and (looking-at " ") (just-one-space))))
11246 (when org-trigger-hook
11247 (save-excursion
11248 (run-hook-with-args 'org-trigger-hook change-plist))))))))
11250 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
11251 "Block turning an entry into a TODO, using the hierarchy.
11252 This checks whether the current task should be blocked from state
11253 changes. Such blocking occurs when:
11255 1. The task has children which are not all in a completed state.
11257 2. A task has a parent with the property :ORDERED:, and there
11258 are siblings prior to the current task with incomplete
11259 status.
11261 3. The parent of the task is blocked because it has siblings that should
11262 be done first, or is child of a block grandparent TODO entry."
11264 (if (not org-enforce-todo-dependencies)
11265 t ; if locally turned off don't block
11266 (catch 'dont-block
11267 ;; If this is not a todo state change, or if this entry is already DONE,
11268 ;; do not block
11269 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11270 (member (plist-get change-plist :from)
11271 (cons 'done org-done-keywords))
11272 (member (plist-get change-plist :to)
11273 (cons 'todo org-not-done-keywords))
11274 (not (plist-get change-plist :to)))
11275 (throw 'dont-block t))
11276 ;; If this task has children, and any are undone, it's blocked
11277 (save-excursion
11278 (org-back-to-heading t)
11279 (let ((this-level (funcall outline-level)))
11280 (outline-next-heading)
11281 (let ((child-level (funcall outline-level)))
11282 (while (and (not (eobp))
11283 (> child-level this-level))
11284 ;; this todo has children, check whether they are all
11285 ;; completed
11286 (if (and (not (org-entry-is-done-p))
11287 (org-entry-is-todo-p))
11288 (throw 'dont-block nil))
11289 (outline-next-heading)
11290 (setq child-level (funcall outline-level))))))
11291 ;; Otherwise, if the task's parent has the :ORDERED: property, and
11292 ;; any previous siblings are undone, it's blocked
11293 (save-excursion
11294 (org-back-to-heading t)
11295 (let* ((pos (point))
11296 (parent-pos (and (org-up-heading-safe) (point))))
11297 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11298 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11299 (forward-line 1)
11300 (re-search-forward org-not-done-heading-regexp pos t))
11301 (throw 'dont-block nil)) ; block, there is an older sibling not done.
11302 ;; Search further up the hierarchy, to see if an anchestor is blocked
11303 (while t
11304 (goto-char parent-pos)
11305 (if (not (looking-at org-not-done-heading-regexp))
11306 (throw 'dont-block t)) ; do not block, parent is not a TODO
11307 (setq pos (point))
11308 (setq parent-pos (and (org-up-heading-safe) (point)))
11309 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11310 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11311 (forward-line 1)
11312 (re-search-forward org-not-done-heading-regexp pos t))
11313 (throw 'dont-block nil)))))))) ; block, older sibling not done.
11315 (defcustom org-track-ordered-property-with-tag nil
11316 "Should the ORDERED property also be shown as a tag?
11317 The ORDERED property decides if an entry should require subtasks to be
11318 completed in sequence. Since a property is not very visible, setting
11319 this option means that toggling the ORDERED property with the command
11320 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
11321 not relevant for the behavior, but it makes things more visible.
11323 Note that toggling the tag with tags commands will not change the property
11324 and therefore not influence behavior!
11326 This can be t, meaning the tag ORDERED should be used, It can also be a
11327 string to select a different tag for this task."
11328 :group 'org-todo
11329 :type '(choice
11330 (const :tag "No tracking" nil)
11331 (const :tag "Track with ORDERED tag" t)
11332 (string :tag "Use other tag")))
11334 (defun org-toggle-ordered-property ()
11335 "Toggle the ORDERED property of the current entry.
11336 For better visibility, you can track the value of this property with a tag.
11337 See variable `org-track-ordered-property-with-tag'."
11338 (interactive)
11339 (let* ((t1 org-track-ordered-property-with-tag)
11340 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
11341 (save-excursion
11342 (org-back-to-heading)
11343 (if (org-entry-get nil "ORDERED")
11344 (progn
11345 (org-delete-property "ORDERED")
11346 (and tag (org-toggle-tag tag 'off))
11347 (message "Subtasks can be completed in arbitrary order"))
11348 (org-entry-put nil "ORDERED" "t")
11349 (and tag (org-toggle-tag tag 'on))
11350 (message "Subtasks must be completed in sequence")))))
11352 (defvar org-blocked-by-checkboxes) ; dynamically scoped
11353 (defun org-block-todo-from-checkboxes (change-plist)
11354 "Block turning an entry into a TODO, using checkboxes.
11355 This checks whether the current task should be blocked from state
11356 changes because there are unchecked boxes in this entry."
11357 (if (not org-enforce-todo-checkbox-dependencies)
11358 t ; if locally turned off don't block
11359 (catch 'dont-block
11360 ;; If this is not a todo state change, or if this entry is already DONE,
11361 ;; do not block
11362 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11363 (member (plist-get change-plist :from)
11364 (cons 'done org-done-keywords))
11365 (member (plist-get change-plist :to)
11366 (cons 'todo org-not-done-keywords))
11367 (not (plist-get change-plist :to)))
11368 (throw 'dont-block t))
11369 ;; If this task has checkboxes that are not checked, it's blocked
11370 (save-excursion
11371 (org-back-to-heading t)
11372 (let ((beg (point)) end)
11373 (outline-next-heading)
11374 (setq end (point))
11375 (goto-char beg)
11376 (if (re-search-forward "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\)[ \t]+\\[[- ]\\]"
11377 end t)
11378 (progn
11379 (if (boundp 'org-blocked-by-checkboxes)
11380 (setq org-blocked-by-checkboxes t))
11381 (throw 'dont-block nil)))))
11382 t))) ; do not block
11384 (defun org-entry-blocked-p ()
11385 "Is the current entry blocked?"
11386 (if (org-entry-get nil "NOBLOCKING")
11387 nil ;; Never block this entry
11388 (not
11389 (run-hook-with-args-until-failure
11390 'org-blocker-hook
11391 (list :type 'todo-state-change
11392 :position (point)
11393 :from 'todo
11394 :to 'done)))))
11396 (defun org-update-statistics-cookies (all)
11397 "Update the statistics cookie, either from TODO or from checkboxes.
11398 This should be called with the cursor in a line with a statistics cookie."
11399 (interactive "P")
11400 (if all
11401 (progn
11402 (org-update-checkbox-count 'all)
11403 (org-map-entries 'org-update-parent-todo-statistics))
11404 (if (not (org-on-heading-p))
11405 (org-update-checkbox-count)
11406 (let ((pos (move-marker (make-marker) (point)))
11407 end l1 l2)
11408 (ignore-errors (org-back-to-heading t))
11409 (if (not (org-on-heading-p))
11410 (org-update-checkbox-count)
11411 (setq l1 (org-outline-level))
11412 (setq end (save-excursion
11413 (outline-next-heading)
11414 (if (org-on-heading-p) (setq l2 (org-outline-level)))
11415 (point)))
11416 (if (and (save-excursion
11417 (re-search-forward
11418 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
11419 (not (save-excursion (re-search-forward
11420 ":COOKIE_DATA:.*\\<todo\\>" end t))))
11421 (org-update-checkbox-count)
11422 (if (and l2 (> l2 l1))
11423 (progn
11424 (goto-char end)
11425 (org-update-parent-todo-statistics))
11426 (goto-char pos)
11427 (beginning-of-line 1)
11428 (while (re-search-forward
11429 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
11430 (point-at-eol) t)
11431 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
11432 (goto-char pos)
11433 (move-marker pos nil)))))
11435 (defvar org-entry-property-inherited-from) ;; defined below
11436 (defun org-update-parent-todo-statistics ()
11437 "Update any statistics cookie in the parent of the current headline.
11438 When `org-hierarchical-todo-statistics' is nil, statistics will cover
11439 the entire subtree and this will travel up the hierarchy and update
11440 statistics everywhere."
11441 (let* ((prop (save-excursion (org-up-heading-safe)
11442 (org-entry-get nil "COOKIE_DATA" 'inherit)))
11443 (recursive (or (not org-hierarchical-todo-statistics)
11444 (and prop (string-match "\\<recursive\\>" prop))))
11445 (lim (or (and prop (marker-position org-entry-property-inherited-from))
11447 (first t)
11448 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
11449 level ltoggle l1 new ndel
11450 (cnt-all 0) (cnt-done 0) is-percent kwd
11451 checkbox-beg ov ovs ove cookie-present)
11452 (catch 'exit
11453 (save-excursion
11454 (beginning-of-line 1)
11455 (setq ltoggle (funcall outline-level))
11456 ;; Three situations are to consider:
11458 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
11459 ;; to the top-level ancestor on the headline;
11461 ;; 2. If parent has "recursive" property, repeat up to the
11462 ;; headline setting that property, taking inheritance into
11463 ;; account;
11465 ;; 3. Else, move up to direct parent and proceed only once.
11466 (while (and (setq level (org-up-heading-safe))
11467 (or recursive first)
11468 (>= (point) lim))
11469 (setq first nil cookie-present nil)
11470 (unless (and level
11471 (not (string-match
11472 "\\<checkbox\\>"
11473 (downcase (or (org-entry-get nil "COOKIE_DATA")
11474 "")))))
11475 (throw 'exit nil))
11476 (while (re-search-forward box-re (point-at-eol) t)
11477 (setq cnt-all 0 cnt-done 0 cookie-present t)
11478 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
11479 (save-match-data
11480 (unless (outline-next-heading) (throw 'exit nil))
11481 (while (and (looking-at org-complex-heading-regexp)
11482 (> (setq l1 (length (match-string 1))) level))
11483 (setq kwd (and (or recursive (= l1 ltoggle))
11484 (match-string 2)))
11485 (if (or (eq org-provide-todo-statistics 'all-headlines)
11486 (and (listp org-provide-todo-statistics)
11487 (or (member kwd org-provide-todo-statistics)
11488 (member kwd org-done-keywords))))
11489 (setq cnt-all (1+ cnt-all))
11490 (if (eq org-provide-todo-statistics t)
11491 (and kwd (setq cnt-all (1+ cnt-all)))))
11492 (and (member kwd org-done-keywords)
11493 (setq cnt-done (1+ cnt-done)))
11494 (outline-next-heading)))
11495 (setq new
11496 (if is-percent
11497 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
11498 (format "[%d/%d]" cnt-done cnt-all))
11499 ndel (- (match-end 0) checkbox-beg))
11500 ;; handle overlays when updating cookie from column view
11501 (when (setq ov (car (overlays-at checkbox-beg)))
11502 (setq ovs (overlay-start ov) ove (overlay-end ov))
11503 (delete-overlay ov))
11504 (goto-char checkbox-beg)
11505 (insert new)
11506 (delete-region (point) (+ (point) ndel))
11507 (when org-auto-align-tags (org-fix-tags-on-the-fly))
11508 (when ov (move-overlay ov ovs ove)))
11509 (when cookie-present
11510 (run-hook-with-args 'org-after-todo-statistics-hook
11511 cnt-done (- cnt-all cnt-done))))))
11512 (run-hooks 'org-todo-statistics-hook)))
11514 (defvar org-after-todo-statistics-hook nil
11515 "Hook that is called after a TODO statistics cookie has been updated.
11516 Each function is called with two arguments: the number of not-done entries
11517 and the number of done entries.
11519 For example, the following function, when added to this hook, will switch
11520 an entry to DONE when all children are done, and back to TODO when new
11521 entries are set to a TODO status. Note that this hook is only called
11522 when there is a statistics cookie in the headline!
11524 (defun org-summary-todo (n-done n-not-done)
11525 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
11526 (let (org-log-done org-log-states) ; turn off logging
11527 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
11530 (defvar org-todo-statistics-hook nil
11531 "Hook that is run whenever Org thinks TODO statistics should be updated.
11532 This hook runs even if there is no statistics cookie present, in which case
11533 `org-after-todo-statistics-hook' would not run.")
11535 (defun org-todo-trigger-tag-changes (state)
11536 "Apply the changes defined in `org-todo-state-tags-triggers'."
11537 (let ((l org-todo-state-tags-triggers)
11538 changes)
11539 (when (or (not state) (equal state ""))
11540 (setq changes (append changes (cdr (assoc "" l)))))
11541 (when (and (stringp state) (> (length state) 0))
11542 (setq changes (append changes (cdr (assoc state l)))))
11543 (when (member state org-not-done-keywords)
11544 (setq changes (append changes (cdr (assoc 'todo l)))))
11545 (when (member state org-done-keywords)
11546 (setq changes (append changes (cdr (assoc 'done l)))))
11547 (dolist (c changes)
11548 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
11550 (defun org-local-logging (value)
11551 "Get logging settings from a property VALUE."
11552 (let* (words w a)
11553 ;; directly set the variables, they are already local.
11554 (setq org-log-done nil
11555 org-log-repeat nil
11556 org-todo-log-states nil)
11557 (setq words (org-split-string value))
11558 (while (setq w (pop words))
11559 (cond
11560 ((setq a (assoc w org-startup-options))
11561 (and (member (nth 1 a) '(org-log-done org-log-repeat))
11562 (set (nth 1 a) (nth 2 a))))
11563 ((setq a (org-extract-log-state-settings w))
11564 (and (member (car a) org-todo-keywords-1)
11565 (push a org-todo-log-states)))))))
11567 (defun org-get-todo-sequence-head (kwd)
11568 "Return the head of the TODO sequence to which KWD belongs.
11569 If KWD is not set, check if there is a text property remembering the
11570 right sequence."
11571 (let (p)
11572 (cond
11573 ((not kwd)
11574 (or (get-text-property (point-at-bol) 'org-todo-head)
11575 (progn
11576 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
11577 nil (point-at-eol)))
11578 (get-text-property p 'org-todo-head))))
11579 ((not (member kwd org-todo-keywords-1))
11580 (car org-todo-keywords-1))
11581 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
11583 (defun org-fast-todo-selection ()
11584 "Fast TODO keyword selection with single keys.
11585 Returns the new TODO keyword, or nil if no state change should occur."
11586 (let* ((fulltable org-todo-key-alist)
11587 (done-keywords org-done-keywords) ;; needed for the faces.
11588 (maxlen (apply 'max (mapcar
11589 (lambda (x)
11590 (if (stringp (car x)) (string-width (car x)) 0))
11591 fulltable)))
11592 (expert nil)
11593 (fwidth (+ maxlen 3 1 3))
11594 (ncol (/ (- (window-width) 4) fwidth))
11595 tg cnt e c tbl
11596 groups ingroup)
11597 (save-excursion
11598 (save-window-excursion
11599 (if expert
11600 (set-buffer (get-buffer-create " *Org todo*"))
11601 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
11602 (erase-buffer)
11603 (org-set-local 'org-done-keywords done-keywords)
11604 (setq tbl fulltable cnt 0)
11605 (while (setq e (pop tbl))
11606 (cond
11607 ((equal e '(:startgroup))
11608 (push '() groups) (setq ingroup t)
11609 (when (not (= cnt 0))
11610 (setq cnt 0)
11611 (insert "\n"))
11612 (insert "{ "))
11613 ((equal e '(:endgroup))
11614 (setq ingroup nil cnt 0)
11615 (insert "}\n"))
11616 ((equal e '(:newline))
11617 (when (not (= cnt 0))
11618 (setq cnt 0)
11619 (insert "\n")
11620 (setq e (car tbl))
11621 (while (equal (car tbl) '(:newline))
11622 (insert "\n")
11623 (setq tbl (cdr tbl)))))
11625 (setq tg (car e) c (cdr e))
11626 (if ingroup (push tg (car groups)))
11627 (setq tg (org-add-props tg nil 'face
11628 (org-get-todo-face tg)))
11629 (if (and (= cnt 0) (not ingroup)) (insert " "))
11630 (insert "[" c "] " tg (make-string
11631 (- fwidth 4 (length tg)) ?\ ))
11632 (when (= (setq cnt (1+ cnt)) ncol)
11633 (insert "\n")
11634 (if ingroup (insert " "))
11635 (setq cnt 0)))))
11636 (insert "\n")
11637 (goto-char (point-min))
11638 (if (not expert) (org-fit-window-to-buffer))
11639 (message "[a-z..]:Set [SPC]:clear")
11640 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
11641 (cond
11642 ((or (= c ?\C-g)
11643 (and (= c ?q) (not (rassoc c fulltable))))
11644 (setq quit-flag t))
11645 ((= c ?\ ) nil)
11646 ((setq e (rassoc c fulltable) tg (car e))
11648 (t (setq quit-flag t)))))))
11650 (defun org-entry-is-todo-p ()
11651 (member (org-get-todo-state) org-not-done-keywords))
11653 (defun org-entry-is-done-p ()
11654 (member (org-get-todo-state) org-done-keywords))
11656 (defun org-get-todo-state ()
11657 (save-excursion
11658 (org-back-to-heading t)
11659 (and (looking-at org-todo-line-regexp)
11660 (match-end 2)
11661 (match-string 2))))
11663 (defun org-at-date-range-p (&optional inactive-ok)
11664 "Is the cursor inside a date range?"
11665 (interactive)
11666 (save-excursion
11667 (catch 'exit
11668 (let ((pos (point)))
11669 (skip-chars-backward "^[<\r\n")
11670 (skip-chars-backward "<[")
11671 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
11672 (>= (match-end 0) pos)
11673 (throw 'exit t))
11674 (skip-chars-backward "^<[\r\n")
11675 (skip-chars-backward "<[")
11676 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
11677 (>= (match-end 0) pos)
11678 (throw 'exit t)))
11679 nil)))
11681 (defun org-get-repeat (&optional tagline)
11682 "Check if there is a deadline/schedule with repeater in this entry."
11683 (save-match-data
11684 (save-excursion
11685 (org-back-to-heading t)
11686 (and (re-search-forward (if tagline
11687 (concat tagline "\\s-*" org-repeat-re)
11688 org-repeat-re)
11689 (org-entry-end-position) t)
11690 (match-string-no-properties 1)))))
11692 (defvar org-last-changed-timestamp)
11693 (defvar org-last-inserted-timestamp)
11694 (defvar org-log-post-message)
11695 (defvar org-log-note-purpose)
11696 (defvar org-log-note-how)
11697 (defvar org-log-note-extra)
11698 (defun org-auto-repeat-maybe (done-word)
11699 "Check if the current headline contains a repeated deadline/schedule.
11700 If yes, set TODO state back to what it was and change the base date
11701 of repeating deadline/scheduled time stamps to new date.
11702 This function is run automatically after each state change to a DONE state."
11703 ;; last-state is dynamically scoped into this function
11704 (let* ((repeat (org-get-repeat))
11705 (aa (assoc last-state org-todo-kwd-alist))
11706 (interpret (nth 1 aa))
11707 (head (nth 2 aa))
11708 (whata '(("d" . day) ("m" . month) ("y" . year)))
11709 (msg "Entry repeats: ")
11710 (org-log-done nil)
11711 (org-todo-log-states nil)
11712 re type n what ts time to-state)
11713 (when repeat
11714 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
11715 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
11716 org-todo-repeat-to-state))
11717 (unless (and to-state (member to-state org-todo-keywords-1))
11718 (setq to-state (if (eq interpret 'type) last-state head)))
11719 (org-todo to-state)
11720 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
11721 (org-entry-put nil "LAST_REPEAT" (format-time-string
11722 (org-time-stamp-format t t))))
11723 (when org-log-repeat
11724 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
11725 (memq 'org-add-log-note post-command-hook))
11726 ;; OK, we are already setup for some record
11727 (if (eq org-log-repeat 'note)
11728 ;; make sure we take a note, not only a time stamp
11729 (setq org-log-note-how 'note))
11730 ;; Set up for taking a record
11731 (org-add-log-setup 'state (or done-word (car org-done-keywords))
11732 last-state
11733 'findpos org-log-repeat)))
11734 (org-back-to-heading t)
11735 (org-add-planning-info nil nil 'closed)
11736 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
11737 org-deadline-time-regexp "\\)\\|\\("
11738 org-ts-regexp "\\)"))
11739 (while (re-search-forward
11740 re (save-excursion (outline-next-heading) (point)) t)
11741 (setq type (if (match-end 1) org-scheduled-string
11742 (if (match-end 3) org-deadline-string "Plain:"))
11743 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
11744 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
11745 (setq n (string-to-number (match-string 2 ts))
11746 what (match-string 3 ts))
11747 (if (equal what "w") (setq n (* n 7) what "d"))
11748 ;; Preparation, see if we need to modify the start date for the change
11749 (when (match-end 1)
11750 (setq time (save-match-data (org-time-string-to-time ts)))
11751 (cond
11752 ((equal (match-string 1 ts) ".")
11753 ;; Shift starting date to today
11754 (org-timestamp-change
11755 (- (org-today) (time-to-days time))
11756 'day))
11757 ((equal (match-string 1 ts) "+")
11758 (let ((nshiftmax 10) (nshift 0))
11759 (while (or (= nshift 0)
11760 (<= (time-to-days time)
11761 (time-to-days (current-time))))
11762 (when (= (incf nshift) nshiftmax)
11763 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
11764 (error "Abort")))
11765 (org-timestamp-change n (cdr (assoc what whata)))
11766 (org-at-timestamp-p t)
11767 (setq ts (match-string 1))
11768 (setq time (save-match-data (org-time-string-to-time ts)))))
11769 (org-timestamp-change (- n) (cdr (assoc what whata)))
11770 ;; rematch, so that we have everything in place for the real shift
11771 (org-at-timestamp-p t)
11772 (setq ts (match-string 1))
11773 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
11774 (org-timestamp-change n (cdr (assoc what whata)))
11775 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
11776 (setq org-log-post-message msg)
11777 (message "%s" msg))))
11779 (defun org-show-todo-tree (arg)
11780 "Make a compact tree which shows all headlines marked with TODO.
11781 The tree will show the lines where the regexp matches, and all higher
11782 headlines above the match.
11783 With a \\[universal-argument] prefix, prompt for a regexp to match.
11784 With a numeric prefix N, construct a sparse tree for the Nth element
11785 of `org-todo-keywords-1'."
11786 (interactive "P")
11787 (let ((case-fold-search nil)
11788 (kwd-re
11789 (cond ((null arg) org-not-done-regexp)
11790 ((equal arg '(4))
11791 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
11792 (mapcar 'list org-todo-keywords-1))))
11793 (concat "\\("
11794 (mapconcat 'identity (org-split-string kwd "|") "\\|")
11795 "\\)\\>")))
11796 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
11797 (regexp-quote (nth (1- (prefix-numeric-value arg))
11798 org-todo-keywords-1)))
11799 (t (error "Invalid prefix argument: %s" arg)))))
11800 (message "%d TODO entries found"
11801 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
11803 (defun org-deadline (&optional remove time)
11804 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
11805 With argument REMOVE, remove any deadline from the item.
11806 With argument TIME, set the deadline at the corresponding date. TIME
11807 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
11808 (interactive "P")
11809 (let* ((old-date (org-entry-get nil "DEADLINE"))
11810 (repeater (and old-date
11811 (string-match
11812 "\\([.+-]+[0-9]+[dwmy]\\(?:[/ ][-+]?[0-9]+[dwmy]\\)?\\) ?"
11813 old-date)
11814 (match-string 1 old-date))))
11815 (if remove
11816 (progn
11817 (when (and old-date org-log-redeadline)
11818 (org-add-log-setup 'deldeadline nil old-date 'findpos
11819 org-log-redeadline))
11820 (org-remove-timestamp-with-keyword org-deadline-string)
11821 (message "Item no longer has a deadline."))
11822 (org-add-planning-info 'deadline time 'closed)
11823 (when (and old-date org-log-redeadline
11824 (not (equal old-date
11825 (substring org-last-inserted-timestamp 1 -1))))
11826 (org-add-log-setup 'redeadline nil old-date 'findpos
11827 org-log-redeadline))
11828 (when repeater
11829 (save-excursion
11830 (org-back-to-heading t)
11831 (when (re-search-forward (concat org-deadline-string " "
11832 org-last-inserted-timestamp)
11833 (save-excursion
11834 (outline-next-heading) (point)) t)
11835 (goto-char (1- (match-end 0)))
11836 (insert " " repeater)
11837 (setq org-last-inserted-timestamp
11838 (concat (substring org-last-inserted-timestamp 0 -1)
11839 " " repeater
11840 (substring org-last-inserted-timestamp -1))))))
11841 (message "Deadline on %s" org-last-inserted-timestamp))))
11843 (defun org-schedule (&optional remove time)
11844 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
11845 With argument REMOVE, remove any scheduling date from the item.
11846 With argument TIME, scheduled at the corresponding date. TIME can
11847 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
11848 (interactive "P")
11849 (let* ((old-date (org-entry-get nil "SCHEDULED"))
11850 (repeater (and old-date
11851 (string-match
11852 "\\([.+-]+[0-9]+[dwmy]\\(?:[/ ][-+]?[0-9]+[dwmy]\\)?\\) ?"
11853 old-date)
11854 (match-string 1 old-date))))
11855 (if remove
11856 (progn
11857 (when (and old-date org-log-reschedule)
11858 (org-add-log-setup 'delschedule nil old-date 'findpos
11859 org-log-reschedule))
11860 (org-remove-timestamp-with-keyword org-scheduled-string)
11861 (message "Item is no longer scheduled."))
11862 (org-add-planning-info 'scheduled time 'closed)
11863 (when (and old-date org-log-reschedule
11864 (not (equal old-date
11865 (substring org-last-inserted-timestamp 1 -1))))
11866 (org-add-log-setup 'reschedule nil old-date 'findpos
11867 org-log-reschedule))
11868 (when repeater
11869 (save-excursion
11870 (org-back-to-heading t)
11871 (when (re-search-forward (concat org-scheduled-string " "
11872 org-last-inserted-timestamp)
11873 (save-excursion
11874 (outline-next-heading) (point)) t)
11875 (goto-char (1- (match-end 0)))
11876 (insert " " repeater)
11877 (setq org-last-inserted-timestamp
11878 (concat (substring org-last-inserted-timestamp 0 -1)
11879 " " repeater
11880 (substring org-last-inserted-timestamp -1))))))
11881 (message "Scheduled to %s" org-last-inserted-timestamp))))
11883 (defun org-get-scheduled-time (pom &optional inherit)
11884 "Get the scheduled time as a time tuple, of a format suitable
11885 for calling org-schedule with, or if there is no scheduling,
11886 returns nil."
11887 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
11888 (when time
11889 (apply 'encode-time (org-parse-time-string time)))))
11891 (defun org-get-deadline-time (pom &optional inherit)
11892 "Get the deadline as a time tuple, of a format suitable for
11893 calling org-deadline with, or if there is no scheduling, returns
11894 nil."
11895 (let ((time (org-entry-get pom "DEADLINE" inherit)))
11896 (when time
11897 (apply 'encode-time (org-parse-time-string time)))))
11899 (defun org-remove-timestamp-with-keyword (keyword)
11900 "Remove all time stamps with KEYWORD in the current entry."
11901 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
11902 beg)
11903 (save-excursion
11904 (org-back-to-heading t)
11905 (setq beg (point))
11906 (outline-next-heading)
11907 (while (re-search-backward re beg t)
11908 (replace-match "")
11909 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
11910 (equal (char-before) ?\ ))
11911 (backward-delete-char 1)
11912 (if (string-match "^[ \t]*$" (buffer-substring
11913 (point-at-bol) (point-at-eol)))
11914 (delete-region (point-at-bol)
11915 (min (point-max) (1+ (point-at-eol))))))))))
11917 (defun org-add-planning-info (what &optional time &rest remove)
11918 "Insert new timestamp with keyword in the line directly after the headline.
11919 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
11920 If non is given, the user is prompted for a date.
11921 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
11922 be removed."
11923 (interactive)
11924 (let (org-time-was-given org-end-time-was-given ts
11925 end default-time default-input)
11927 (catch 'exit
11928 (when (and (memq what '(scheduled deadline))
11929 (or (not time)
11930 (and (stringp time)
11931 (string-match "^[-+]+[0-9]" time))))
11932 ;; Try to get a default date/time from existing timestamp
11933 (save-excursion
11934 (org-back-to-heading t)
11935 (setq end (save-excursion (outline-next-heading) (point)))
11936 (when (re-search-forward (if (eq what 'scheduled)
11937 org-scheduled-time-regexp
11938 org-deadline-time-regexp)
11939 end t)
11940 (setq ts (match-string 1)
11941 default-time
11942 (apply 'encode-time (org-parse-time-string ts))
11943 default-input (and ts (org-get-compact-tod ts))))))
11944 (when what
11945 (setq time
11946 (if (and (stringp time)
11947 (string-match "^[-+]+[0-9]" time))
11948 ;; This is a relative time, set the proper date
11949 (apply 'encode-time
11950 (org-read-date-analyze
11951 time default-time (decode-time default-time)))
11952 ;; If necessary, get the time from the user
11953 (or time (org-read-date nil 'to-time nil nil
11954 default-time default-input)))))
11956 (when (and org-insert-labeled-timestamps-at-point
11957 (member what '(scheduled deadline)))
11958 (insert
11959 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
11960 (org-insert-time-stamp time org-time-was-given
11961 nil nil nil (list org-end-time-was-given))
11962 (setq what nil))
11963 (save-excursion
11964 (save-restriction
11965 (let (col list elt ts buffer-invisibility-spec)
11966 (org-back-to-heading t)
11967 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
11968 (goto-char (match-end 1))
11969 (setq col (current-column))
11970 (goto-char (match-end 0))
11971 (if (eobp) (insert "\n") (forward-char 1))
11972 (when (and (not what)
11973 (not (looking-at
11974 (concat "[ \t]*"
11975 org-keyword-time-not-clock-regexp))))
11976 ;; Nothing to add, nothing to remove...... :-)
11977 (throw 'exit nil))
11978 (if (and (not (looking-at org-outline-regexp))
11979 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
11980 "[^\r\n]*"))
11981 (not (equal (match-string 1) org-clock-string)))
11982 (narrow-to-region (match-beginning 0) (match-end 0))
11983 (insert-before-markers "\n")
11984 (backward-char 1)
11985 (narrow-to-region (point) (point))
11986 (and org-adapt-indentation (org-indent-to-column col)))
11987 ;; Check if we have to remove something.
11988 (setq list (cons what remove))
11989 (while list
11990 (setq elt (pop list))
11991 (when (or (and (eq elt 'scheduled)
11992 (re-search-forward org-scheduled-time-regexp nil t))
11993 (and (eq elt 'deadline)
11994 (re-search-forward org-deadline-time-regexp nil t))
11995 (and (eq elt 'closed)
11996 (re-search-forward org-closed-time-regexp nil t)))
11997 (replace-match "")
11998 (if (looking-at "--+<[^>]+>") (replace-match ""))))
11999 (and (looking-at "[ \t]+") (replace-match ""))
12000 (and org-adapt-indentation (bolp) (org-indent-to-column col))
12001 (when what
12002 (insert
12003 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
12004 (cond ((eq what 'scheduled) org-scheduled-string)
12005 ((eq what 'deadline) org-deadline-string)
12006 ((eq what 'closed) org-closed-string))
12007 " ")
12008 (setq ts (org-insert-time-stamp
12009 time
12010 (or org-time-was-given
12011 (and (eq what 'closed) org-log-done-with-time))
12012 (eq what 'closed)
12013 nil nil (list org-end-time-was-given)))
12014 (insert
12015 (if (not (or (bolp) (eq (char-before) ?\ )
12016 (memq (char-after) '(32 10))
12017 (eobp))) " " ""))
12018 (end-of-line 1))
12019 (goto-char (point-min))
12020 (widen)
12021 (if (and (looking-at "[ \t]*\n")
12022 (equal (char-before) ?\n))
12023 (delete-region (1- (point)) (point-at-eol)))
12024 ts))))))
12026 (defvar org-log-note-marker (make-marker))
12027 (defvar org-log-note-purpose nil)
12028 (defvar org-log-note-state nil)
12029 (defvar org-log-note-previous-state nil)
12030 (defvar org-log-note-how nil)
12031 (defvar org-log-note-extra nil)
12032 (defvar org-log-note-window-configuration nil)
12033 (defvar org-log-note-return-to (make-marker))
12034 (defvar org-log-note-effective-time nil
12035 "Remembered current time so that dynamically scoped
12036 `org-extend-today-until' affects tha timestamps in state change
12037 log")
12039 (defvar org-log-post-message nil
12040 "Message to be displayed after a log note has been stored.
12041 The auto-repeater uses this.")
12043 (defun org-add-note ()
12044 "Add a note to the current entry.
12045 This is done in the same way as adding a state change note."
12046 (interactive)
12047 (org-add-log-setup 'note nil nil 'findpos nil))
12049 (defvar org-property-end-re)
12050 (defun org-add-log-setup (&optional purpose state prev-state
12051 findpos how extra)
12052 "Set up the post command hook to take a note.
12053 If this is about to TODO state change, the new state is expected in STATE.
12054 When FINDPOS is non-nil, find the correct position for the note in
12055 the current entry. If not, assume that it can be inserted at point.
12056 HOW is an indicator what kind of note should be created.
12057 EXTRA is additional text that will be inserted into the notes buffer."
12058 (let* ((org-log-into-drawer (org-log-into-drawer))
12059 (drawer (cond ((stringp org-log-into-drawer)
12060 org-log-into-drawer)
12061 (org-log-into-drawer "LOGBOOK")
12062 (t nil))))
12063 (save-restriction
12064 (save-excursion
12065 (when findpos
12066 (org-back-to-heading t)
12067 (narrow-to-region (point) (save-excursion
12068 (outline-next-heading) (point)))
12069 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
12070 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
12071 "[^\r\n]*\\)?"))
12072 (goto-char (match-end 0))
12073 (cond
12074 (drawer
12075 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
12076 nil t)
12077 (progn
12078 (goto-char (match-end 0))
12079 (or org-log-states-order-reversed
12080 (and (re-search-forward org-property-end-re nil t)
12081 (goto-char (1- (match-beginning 0))))))
12082 (insert "\n:" drawer ":\n:END:")
12083 (beginning-of-line 0)
12084 (org-indent-line-function)
12085 (beginning-of-line 2)
12086 (org-indent-line-function)
12087 (end-of-line 0)))
12088 ((and org-log-state-notes-insert-after-drawers
12089 (save-excursion
12090 (forward-line) (looking-at org-drawer-regexp)))
12091 (forward-line)
12092 (while (looking-at org-drawer-regexp)
12093 (goto-char (match-end 0))
12094 (re-search-forward org-property-end-re (point-max) t)
12095 (forward-line))
12096 (forward-line -1)))
12097 (unless org-log-states-order-reversed
12098 (and (= (char-after) ?\n) (forward-char 1))
12099 (org-skip-over-state-notes)
12100 (skip-chars-backward " \t\n\r")))
12101 (move-marker org-log-note-marker (point))
12102 (setq org-log-note-purpose purpose
12103 org-log-note-state state
12104 org-log-note-previous-state prev-state
12105 org-log-note-how how
12106 org-log-note-extra extra
12107 org-log-note-effective-time (org-current-effective-time))
12108 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
12110 (defun org-skip-over-state-notes ()
12111 "Skip past the list of State notes in an entry."
12112 (if (looking-at "\n[ \t]*- State") (forward-char 1))
12113 (when (ignore-errors (goto-char (org-in-item-p)))
12114 (let* ((struct (org-list-struct))
12115 (prevs (org-list-prevs-alist struct)))
12116 (while (looking-at "[ \t]*- State")
12117 (goto-char (or (org-list-get-next-item (point) struct prevs)
12118 (org-list-get-item-end (point) struct)))))))
12120 (defun org-add-log-note (&optional purpose)
12121 "Pop up a window for taking a note, and add this note later at point."
12122 (remove-hook 'post-command-hook 'org-add-log-note)
12123 (setq org-log-note-window-configuration (current-window-configuration))
12124 (delete-other-windows)
12125 (move-marker org-log-note-return-to (point))
12126 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
12127 (goto-char org-log-note-marker)
12128 (org-switch-to-buffer-other-window "*Org Note*")
12129 (erase-buffer)
12130 (if (memq org-log-note-how '(time state))
12131 (let (current-prefix-arg) (org-store-log-note))
12132 (let ((org-inhibit-startup t)) (org-mode))
12133 (insert (format "# Insert note for %s.
12134 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
12135 (cond
12136 ((eq org-log-note-purpose 'clock-out) "stopped clock")
12137 ((eq org-log-note-purpose 'done) "closed todo item")
12138 ((eq org-log-note-purpose 'state)
12139 (format "state change from \"%s\" to \"%s\""
12140 (or org-log-note-previous-state "")
12141 (or org-log-note-state "")))
12142 ((eq org-log-note-purpose 'reschedule)
12143 "rescheduling")
12144 ((eq org-log-note-purpose 'delschedule)
12145 "no longer scheduled")
12146 ((eq org-log-note-purpose 'redeadline)
12147 "changing deadline")
12148 ((eq org-log-note-purpose 'deldeadline)
12149 "removing deadline")
12150 ((eq org-log-note-purpose 'refile)
12151 "refiling")
12152 ((eq org-log-note-purpose 'note)
12153 "this entry")
12154 (t (error "This should not happen")))))
12155 (if org-log-note-extra (insert org-log-note-extra))
12156 (org-set-local 'org-finish-function 'org-store-log-note)
12157 (run-hooks 'org-log-buffer-setup-hook)))
12159 (defvar org-note-abort nil) ; dynamically scoped
12160 (defun org-store-log-note ()
12161 "Finish taking a log note, and insert it to where it belongs."
12162 (let ((txt (buffer-string))
12163 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
12164 lines ind bul)
12165 (kill-buffer (current-buffer))
12166 (while (string-match "\\`#.*\n[ \t\n]*" txt)
12167 (setq txt (replace-match "" t t txt)))
12168 (if (string-match "\\s-+\\'" txt)
12169 (setq txt (replace-match "" t t txt)))
12170 (setq lines (org-split-string txt "\n"))
12171 (when (and note (string-match "\\S-" note))
12172 (setq note
12173 (org-replace-escapes
12174 note
12175 (list (cons "%u" (user-login-name))
12176 (cons "%U" user-full-name)
12177 (cons "%t" (format-time-string
12178 (org-time-stamp-format 'long 'inactive)
12179 org-log-note-effective-time))
12180 (cons "%T" (format-time-string
12181 (org-time-stamp-format 'long nil)
12182 org-log-note-effective-time))
12183 (cons "%s" (if org-log-note-state
12184 (concat "\"" org-log-note-state "\"")
12185 ""))
12186 (cons "%S" (if org-log-note-previous-state
12187 (concat "\"" org-log-note-previous-state "\"")
12188 "\"\"")))))
12189 (if lines (setq note (concat note " \\\\")))
12190 (push note lines))
12191 (when (or current-prefix-arg org-note-abort)
12192 (when org-log-into-drawer
12193 (org-remove-empty-drawer-at
12194 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
12195 org-log-note-marker))
12196 (setq lines nil))
12197 (when lines
12198 (with-current-buffer (marker-buffer org-log-note-marker)
12199 (save-excursion
12200 (goto-char org-log-note-marker)
12201 (move-marker org-log-note-marker nil)
12202 (end-of-line 1)
12203 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
12204 (setq ind (save-excursion
12205 (if (ignore-errors (goto-char (org-in-item-p)))
12206 (let ((struct (org-list-struct)))
12207 (org-list-get-ind
12208 (org-list-get-top-point struct) struct))
12209 (skip-chars-backward " \r\t\n")
12210 (cond
12211 ((and (org-at-heading-p)
12212 org-adapt-indentation)
12213 (1+ (org-current-level)))
12214 ((org-at-heading-p) 0)
12215 (t (org-get-indentation))))))
12216 (setq bul (org-list-bullet-string "-"))
12217 (org-indent-line-to ind)
12218 (insert bul (pop lines))
12219 (let ((ind-body (+ (length bul) ind)))
12220 (while lines
12221 (insert "\n")
12222 (org-indent-line-to ind-body)
12223 (insert (pop lines))))
12224 (message "Note stored")
12225 (org-back-to-heading t)
12226 (org-cycle-hide-drawers 'children)))))
12227 (set-window-configuration org-log-note-window-configuration)
12228 (with-current-buffer (marker-buffer org-log-note-return-to)
12229 (goto-char org-log-note-return-to))
12230 (move-marker org-log-note-return-to nil)
12231 (and org-log-post-message (message "%s" org-log-post-message)))
12233 (defun org-remove-empty-drawer-at (drawer pos)
12234 "Remove an empty drawer DRAWER at position POS.
12235 POS may also be a marker."
12236 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
12237 (save-excursion
12238 (save-restriction
12239 (widen)
12240 (goto-char pos)
12241 (if (org-in-regexp
12242 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
12243 (replace-match ""))))))
12245 (defun org-sparse-tree (&optional arg)
12246 "Create a sparse tree, prompt for the details.
12247 This command can create sparse trees. You first need to select the type
12248 of match used to create the tree:
12250 t Show all TODO entries.
12251 T Show entries with a specific TODO keyword.
12252 m Show entries selected by a tags/property match.
12253 p Enter a property name and its value (both with completion on existing
12254 names/values) and show entries with that property.
12255 r Show entries matching a regular expression (`/' can be used as well)
12256 d Show deadlines due within `org-deadline-warning-days'.
12257 b Show deadlines and scheduled items before a date.
12258 a Show deadlines and scheduled items after a date."
12259 (interactive "P")
12260 (let (ans kwd value)
12261 (message "Sparse tree: [r]egexp [/]regexp [t]odo [T]odo-kwd [m]atch [p]roperty\n [d]eadlines [b]efore-date [a]fter-date")
12262 (setq ans (read-char-exclusive))
12263 (cond
12264 ((equal ans ?d)
12265 (call-interactively 'org-check-deadlines))
12266 ((equal ans ?b)
12267 (call-interactively 'org-check-before-date))
12268 ((equal ans ?a)
12269 (call-interactively 'org-check-after-date))
12270 ((equal ans ?t)
12271 (org-show-todo-tree nil))
12272 ((equal ans ?T)
12273 (org-show-todo-tree '(4)))
12274 ((member ans '(?T ?m))
12275 (call-interactively 'org-match-sparse-tree))
12276 ((member ans '(?p ?P))
12277 (setq kwd (org-icompleting-read "Property: "
12278 (mapcar 'list (org-buffer-property-keys))))
12279 (setq value (org-icompleting-read "Value: "
12280 (mapcar 'list (org-property-values kwd))))
12281 (unless (string-match "\\`{.*}\\'" value)
12282 (setq value (concat "\"" value "\"")))
12283 (org-match-sparse-tree arg (concat kwd "=" value)))
12284 ((member ans '(?r ?R ?/))
12285 (call-interactively 'org-occur))
12286 (t (error "No such sparse tree command \"%c\"" ans)))))
12288 (defvar org-occur-highlights nil
12289 "List of overlays used for occur matches.")
12290 (make-variable-buffer-local 'org-occur-highlights)
12291 (defvar org-occur-parameters nil
12292 "Parameters of the active org-occur calls.
12293 This is a list, each call to org-occur pushes as cons cell,
12294 containing the regular expression and the callback, onto the list.
12295 The list can contain several entries if `org-occur' has been called
12296 several time with the KEEP-PREVIOUS argument. Otherwise, this list
12297 will only contain one set of parameters. When the highlights are
12298 removed (for example with `C-c C-c', or with the next edit (depending
12299 on `org-remove-highlights-with-change'), this variable is emptied
12300 as well.")
12301 (make-variable-buffer-local 'org-occur-parameters)
12303 (defun org-occur (regexp &optional keep-previous callback)
12304 "Make a compact tree which shows all matches of REGEXP.
12305 The tree will show the lines where the regexp matches, and all higher
12306 headlines above the match. It will also show the heading after the match,
12307 to make sure editing the matching entry is easy.
12308 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
12309 call to `org-occur' will be kept, to allow stacking of calls to this
12310 command.
12311 If CALLBACK is non-nil, it is a function which is called to confirm
12312 that the match should indeed be shown."
12313 (interactive "sRegexp: \nP")
12314 (when (equal regexp "")
12315 (error "Regexp cannot be empty"))
12316 (unless keep-previous
12317 (org-remove-occur-highlights nil nil t))
12318 (push (cons regexp callback) org-occur-parameters)
12319 (let ((cnt 0))
12320 (save-excursion
12321 (goto-char (point-min))
12322 (if (or (not keep-previous) ; do not want to keep
12323 (not org-occur-highlights)) ; no previous matches
12324 ;; hide everything
12325 (org-overview))
12326 (while (re-search-forward regexp nil t)
12327 (when (or (not callback)
12328 (save-match-data (funcall callback)))
12329 (setq cnt (1+ cnt))
12330 (when org-highlight-sparse-tree-matches
12331 (org-highlight-new-match (match-beginning 0) (match-end 0)))
12332 (org-show-context 'occur-tree))))
12333 (when org-remove-highlights-with-change
12334 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
12335 nil 'local))
12336 (unless org-sparse-tree-open-archived-trees
12337 (org-hide-archived-subtrees (point-min) (point-max)))
12338 (run-hooks 'org-occur-hook)
12339 (if (org-called-interactively-p 'interactive)
12340 (message "%d match(es) for regexp %s" cnt regexp))
12341 cnt))
12343 (defun org-occur-next-match (&optional n reset)
12344 "Function for `next-error-function' to find sparse tree matches.
12345 N is the number of matches to move, when negative move backwards.
12346 RESET is entirely ignored - this function always goes back to the
12347 starting point when no match is found."
12348 (let* ((limit (if (< n 0) (point-min) (point-max)))
12349 (search-func (if (< n 0)
12350 'previous-single-char-property-change
12351 'next-single-char-property-change))
12352 (n (abs n))
12353 (pos (point))
12355 (catch 'exit
12356 (while (setq p1 (funcall search-func (point) 'org-type))
12357 (when (equal p1 limit)
12358 (goto-char pos)
12359 (error "No more matches"))
12360 (when (equal (get-char-property p1 'org-type) 'org-occur)
12361 (setq n (1- n))
12362 (when (= n 0)
12363 (goto-char p1)
12364 (throw 'exit (point))))
12365 (goto-char p1))
12366 (goto-char p1)
12367 (error "No more matches"))))
12369 (defun org-show-context (&optional key)
12370 "Make sure point and context are visible.
12371 How much context is shown depends upon the variables
12372 `org-show-hierarchy-above', `org-show-following-heading'. and
12373 `org-show-siblings'."
12374 (let ((heading-p (org-on-heading-p t))
12375 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
12376 (following-p (org-get-alist-option org-show-following-heading key))
12377 (entry-p (org-get-alist-option org-show-entry-below key))
12378 (siblings-p (org-get-alist-option org-show-siblings key)))
12379 (catch 'exit
12380 ;; Show heading or entry text
12381 (if (and heading-p (not entry-p))
12382 (org-flag-heading nil) ; only show the heading
12383 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
12384 (org-show-hidden-entry))) ; show entire entry
12385 (when following-p
12386 ;; Show next sibling, or heading below text
12387 (save-excursion
12388 (and (if heading-p (org-goto-sibling) (outline-next-heading))
12389 (org-flag-heading nil))))
12390 (when siblings-p (org-show-siblings))
12391 (when hierarchy-p
12392 ;; show all higher headings, possibly with siblings
12393 (save-excursion
12394 (while (and (condition-case nil
12395 (progn (org-up-heading-all 1) t)
12396 (error nil))
12397 (not (bobp)))
12398 (org-flag-heading nil)
12399 (when siblings-p (org-show-siblings))))))))
12401 (defvar org-reveal-start-hook nil
12402 "Hook run before revealing a location.")
12404 (defun org-reveal (&optional siblings)
12405 "Show current entry, hierarchy above it, and the following headline.
12406 This can be used to show a consistent set of context around locations
12407 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
12408 not t for the search context.
12410 With optional argument SIBLINGS, on each level of the hierarchy all
12411 siblings are shown. This repairs the tree structure to what it would
12412 look like when opened with hierarchical calls to `org-cycle'.
12413 With double optional argument \\[universal-argument] \\[universal-argument], \
12414 go to the parent and show the
12415 entire tree."
12416 (interactive "P")
12417 (run-hooks 'org-reveal-start-hook)
12418 (let ((org-show-hierarchy-above t)
12419 (org-show-following-heading t)
12420 (org-show-siblings (if siblings t org-show-siblings)))
12421 (org-show-context nil))
12422 (when (equal siblings '(16))
12423 (save-excursion
12424 (when (org-up-heading-safe)
12425 (org-show-subtree)
12426 (run-hook-with-args 'org-cycle-hook 'subtree)))))
12428 (defun org-highlight-new-match (beg end)
12429 "Highlight from BEG to END and mark the highlight is an occur headline."
12430 (let ((ov (make-overlay beg end)))
12431 (overlay-put ov 'face 'secondary-selection)
12432 (overlay-put ov 'org-type 'org-occur)
12433 (push ov org-occur-highlights)))
12435 (defun org-remove-occur-highlights (&optional beg end noremove)
12436 "Remove the occur highlights from the buffer.
12437 BEG and END are ignored. If NOREMOVE is nil, remove this function
12438 from the `before-change-functions' in the current buffer."
12439 (interactive)
12440 (unless org-inhibit-highlight-removal
12441 (mapc 'delete-overlay org-occur-highlights)
12442 (setq org-occur-highlights nil)
12443 (setq org-occur-parameters nil)
12444 (unless noremove
12445 (remove-hook 'before-change-functions
12446 'org-remove-occur-highlights 'local))))
12448 ;;;; Priorities
12450 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
12451 "Regular expression matching the priority indicator.")
12453 (defvar org-remove-priority-next-time nil)
12455 (defun org-priority-up ()
12456 "Increase the priority of the current item."
12457 (interactive)
12458 (org-priority 'up))
12460 (defun org-priority-down ()
12461 "Decrease the priority of the current item."
12462 (interactive)
12463 (org-priority 'down))
12465 (defun org-priority (&optional action)
12466 "Change the priority of an item by ARG.
12467 ACTION can be `set', `up', `down', or a character."
12468 (interactive)
12469 (unless org-enable-priority-commands
12470 (error "Priority commands are disabled"))
12471 (setq action (or action 'set))
12472 (let (current new news have remove)
12473 (save-excursion
12474 (org-back-to-heading t)
12475 (if (looking-at org-priority-regexp)
12476 (setq current (string-to-char (match-string 2))
12477 have t))
12478 (cond
12479 ((eq action 'remove)
12480 (setq remove t new ?\ ))
12481 ((or (eq action 'set)
12482 (if (featurep 'xemacs) (characterp action) (integerp action)))
12483 (if (not (eq action 'set))
12484 (setq new action)
12485 (message "Priority %c-%c, SPC to remove: "
12486 org-highest-priority org-lowest-priority)
12487 (save-match-data
12488 (setq new (read-char-exclusive))))
12489 (if (and (= (upcase org-highest-priority) org-highest-priority)
12490 (= (upcase org-lowest-priority) org-lowest-priority))
12491 (setq new (upcase new)))
12492 (cond ((equal new ?\ ) (setq remove t))
12493 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
12494 (error "Priority must be between `%c' and `%c'"
12495 org-highest-priority org-lowest-priority))))
12496 ((eq action 'up)
12497 (setq new (if have
12498 (1- current) ; normal cycling
12499 ;; last priority was empty
12500 (if (eq last-command this-command)
12501 org-lowest-priority ; wrap around empty to lowest
12502 ;; default
12503 (if org-priority-start-cycle-with-default
12504 org-default-priority
12505 (1- org-default-priority))))))
12506 ((eq action 'down)
12507 (setq new (if have
12508 (1+ current) ; normal cycling
12509 ;; last priority was empty
12510 (if (eq last-command this-command)
12511 org-highest-priority ; wrap around empty to highest
12512 ;; default
12513 (if org-priority-start-cycle-with-default
12514 org-default-priority
12515 (1+ org-default-priority))))))
12516 (t (error "Invalid action")))
12517 (if (or (< (upcase new) org-highest-priority)
12518 (> (upcase new) org-lowest-priority))
12519 (if (and (memq action '(up down))
12520 (not have) (not (eq last-command this-command)))
12521 ;; `new' is from default priority
12522 (error
12523 "The default can not be set, see `org-default-priority' why")
12524 ;; normal cycling: `new' is beyond highest/lowest priority
12525 ;; and is wrapped around to the empty priority
12526 (setq remove t)))
12527 (setq news (format "%c" new))
12528 (if have
12529 (if remove
12530 (replace-match "" t t nil 1)
12531 (replace-match news t t nil 2))
12532 (if remove
12533 (error "No priority cookie found in line")
12534 (let ((case-fold-search nil))
12535 (looking-at org-todo-line-regexp))
12536 (if (match-end 2)
12537 (progn
12538 (goto-char (match-end 2))
12539 (insert " [#" news "]"))
12540 (goto-char (match-beginning 3))
12541 (insert "[#" news "] "))))
12542 (org-preserve-lc (org-set-tags nil 'align)))
12543 (if remove
12544 (message "Priority removed")
12545 (message "Priority of current item set to %s" news))))
12547 (defun org-get-priority (s)
12548 "Find priority cookie and return priority."
12549 (if (functionp org-get-priority-function)
12550 (funcall org-get-priority-function)
12551 (save-match-data
12552 (if (not (string-match org-priority-regexp s))
12553 (* 1000 (- org-lowest-priority org-default-priority))
12554 (* 1000 (- org-lowest-priority
12555 (string-to-char (match-string 2 s))))))))
12557 ;;;; Tags
12559 (defvar org-agenda-archives-mode)
12560 (defvar org-map-continue-from nil
12561 "Position from where mapping should continue.
12562 Can be set by the action argument to `org-scan-tag's and `org-map-entries'.")
12564 (defvar org-scanner-tags nil
12565 "The current tag list while the tags scanner is running.")
12566 (defvar org-trust-scanner-tags nil
12567 "Should `org-get-tags-at' use the tags for the scanner.
12568 This is for internal dynamical scoping only.
12569 When this is non-nil, the function `org-get-tags-at' will return the value
12570 of `org-scanner-tags' instead of building the list by itself. This
12571 can lead to large speed-ups when the tags scanner is used in a file with
12572 many entries, and when the list of tags is retrieved, for example to
12573 obtain a list of properties. Building the tags list for each entry in such
12574 a file becomes an N^2 operation - but with this variable set, it scales
12575 as N.")
12577 (defun org-scan-tags (action matcher &optional todo-only)
12578 "Scan headline tags with inheritance and produce output ACTION.
12580 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
12581 or `agenda' to produce an entry list for an agenda view. It can also be
12582 a Lisp form or a function that should be called at each matched headline, in
12583 this case the return value is a list of all return values from these calls.
12585 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
12586 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
12587 only lines with a TODO keyword are included in the output."
12588 (require 'org-agenda)
12589 (let* ((re (concat "^" org-outline-regexp " *\\(\\<\\("
12590 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
12591 (org-re
12592 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
12593 (props (list 'face 'default
12594 'done-face 'org-agenda-done
12595 'undone-face 'default
12596 'mouse-face 'highlight
12597 'org-not-done-regexp org-not-done-regexp
12598 'org-todo-regexp org-todo-regexp
12599 'help-echo
12600 (format "mouse-2 or RET jump to org file %s"
12601 (abbreviate-file-name
12602 (or (buffer-file-name (buffer-base-buffer))
12603 (buffer-name (buffer-base-buffer)))))))
12604 (case-fold-search nil)
12605 (org-map-continue-from nil)
12606 lspos tags tags-list
12607 (tags-alist (list (cons 0 org-file-tags)))
12608 (llast 0) rtn rtn1 level category i txt
12609 todo marker entry priority)
12610 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
12611 (setq action (list 'lambda nil action)))
12612 (save-excursion
12613 (goto-char (point-min))
12614 (when (eq action 'sparse-tree)
12615 (org-overview)
12616 (org-remove-occur-highlights))
12617 (while (re-search-forward re nil t)
12618 (catch :skip
12619 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
12620 tags (if (match-end 4) (org-match-string-no-properties 4)))
12621 (goto-char (setq lspos (match-beginning 0)))
12622 (setq level (org-reduced-level (funcall outline-level))
12623 category (org-get-category))
12624 (setq i llast llast level)
12625 ;; remove tag lists from same and sublevels
12626 (while (>= i level)
12627 (when (setq entry (assoc i tags-alist))
12628 (setq tags-alist (delete entry tags-alist)))
12629 (setq i (1- i)))
12630 ;; add the next tags
12631 (when tags
12632 (setq tags (org-split-string tags ":")
12633 tags-alist
12634 (cons (cons level tags) tags-alist)))
12635 ;; compile tags for current headline
12636 (setq tags-list
12637 (if org-use-tag-inheritance
12638 (apply 'append (mapcar 'cdr (reverse tags-alist)))
12639 tags)
12640 org-scanner-tags tags-list)
12641 (when org-use-tag-inheritance
12642 (setcdr (car tags-alist)
12643 (mapcar (lambda (x)
12644 (setq x (copy-sequence x))
12645 (org-add-prop-inherited x))
12646 (cdar tags-alist))))
12647 (when (and tags org-use-tag-inheritance
12648 (or (not (eq t org-use-tag-inheritance))
12649 org-tags-exclude-from-inheritance))
12650 ;; selective inheritance, remove uninherited ones
12651 (setcdr (car tags-alist)
12652 (org-remove-uninherited-tags (cdar tags-alist))))
12653 (when (and
12655 ;; eval matcher only when the todo condition is OK
12656 (and (or (not todo-only) (member todo org-not-done-keywords))
12657 (let ((case-fold-search t)) (eval matcher)))
12659 ;; Call the skipper, but return t if it does not skip,
12660 ;; so that the `and' form continues evaluating
12661 (progn
12662 (unless (eq action 'sparse-tree) (org-agenda-skip))
12665 ;; Check if timestamps are deselecting this entry
12666 (or (not todo-only)
12667 (and (member todo org-not-done-keywords)
12668 (or (not org-agenda-tags-todo-honor-ignore-options)
12669 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
12671 ;; Extra check for the archive tag
12672 ;; FIXME: Does the skipper already do this????
12674 (not (member org-archive-tag tags-list))
12675 ;; we have an archive tag, should we use this anyway?
12676 (or (not org-agenda-skip-archived-trees)
12677 (and (eq action 'agenda) org-agenda-archives-mode))))
12679 ;; select this headline
12681 (cond
12682 ((eq action 'sparse-tree)
12683 (and org-highlight-sparse-tree-matches
12684 (org-get-heading) (match-end 0)
12685 (org-highlight-new-match
12686 (match-beginning 0) (match-beginning 1)))
12687 (org-show-context 'tags-tree))
12688 ((eq action 'agenda)
12689 (setq txt (org-format-agenda-item
12691 (concat
12692 (if (eq org-tags-match-list-sublevels 'indented)
12693 (make-string (1- level) ?.) "")
12694 (org-get-heading))
12695 category
12696 tags-list
12698 priority (org-get-priority txt))
12699 (goto-char lspos)
12700 (setq marker (org-agenda-new-marker))
12701 (org-add-props txt props
12702 'org-marker marker 'org-hd-marker marker 'org-category category
12703 'todo-state todo
12704 'priority priority 'type "tagsmatch")
12705 (push txt rtn))
12706 ((functionp action)
12707 (setq org-map-continue-from nil)
12708 (save-excursion
12709 (setq rtn1 (funcall action))
12710 (push rtn1 rtn)))
12711 (t (error "Invalid action")))
12713 ;; if we are to skip sublevels, jump to end of subtree
12714 (unless org-tags-match-list-sublevels
12715 (org-end-of-subtree t)
12716 (backward-char 1))))
12717 ;; Get the correct position from where to continue
12718 (if org-map-continue-from
12719 (goto-char org-map-continue-from)
12720 (and (= (point) lspos) (end-of-line 1)))))
12721 (when (and (eq action 'sparse-tree)
12722 (not org-sparse-tree-open-archived-trees))
12723 (org-hide-archived-subtrees (point-min) (point-max)))
12724 (nreverse rtn)))
12726 (defun org-remove-uninherited-tags (tags)
12727 "Remove all tags that are not inherited from the list TAGS."
12728 (cond
12729 ((eq org-use-tag-inheritance t)
12730 (if org-tags-exclude-from-inheritance
12731 (org-delete-all org-tags-exclude-from-inheritance tags)
12732 tags))
12733 ((not org-use-tag-inheritance) nil)
12734 ((stringp org-use-tag-inheritance)
12735 (delq nil (mapcar
12736 (lambda (x)
12737 (if (and (string-match org-use-tag-inheritance x)
12738 (not (member x org-tags-exclude-from-inheritance)))
12739 x nil))
12740 tags)))
12741 ((listp org-use-tag-inheritance)
12742 (delq nil (mapcar
12743 (lambda (x)
12744 (if (member x org-use-tag-inheritance) x nil))
12745 tags)))))
12747 (defvar todo-only) ;; dynamically scoped
12749 (defun org-match-sparse-tree (&optional todo-only match)
12750 "Create a sparse tree according to tags string MATCH.
12751 MATCH can contain positive and negative selection of tags, like
12752 \"+WORK+URGENT-WITHBOSS\".
12753 If optional argument TODO-ONLY is non-nil, only select lines that are
12754 also TODO lines."
12755 (interactive "P")
12756 (org-prepare-agenda-buffers (list (current-buffer)))
12757 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
12759 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
12761 (defvar org-cached-props nil)
12762 (defun org-cached-entry-get (pom property)
12763 (if (or (eq t org-use-property-inheritance)
12764 (and (stringp org-use-property-inheritance)
12765 (string-match org-use-property-inheritance property))
12766 (and (listp org-use-property-inheritance)
12767 (member property org-use-property-inheritance)))
12768 ;; Caching is not possible, check it directly
12769 (org-entry-get pom property 'inherit)
12770 ;; Get all properties, so that we can do complicated checks easily
12771 (cdr (assoc property (or org-cached-props
12772 (setq org-cached-props
12773 (org-entry-properties pom)))))))
12775 (defun org-global-tags-completion-table (&optional files)
12776 "Return the list of all tags in all agenda buffer/files.
12777 Optional FILES argument is a list of files to which can be used
12778 instead of the agenda files."
12779 (save-excursion
12780 (org-uniquify
12781 (delq nil
12782 (apply 'append
12783 (mapcar
12784 (lambda (file)
12785 (set-buffer (find-file-noselect file))
12786 (append (org-get-buffer-tags)
12787 (mapcar (lambda (x) (if (stringp (car-safe x))
12788 (list (car-safe x)) nil))
12789 org-tag-alist)))
12790 (if (and files (car files))
12791 files
12792 (org-agenda-files))))))))
12794 (defun org-make-tags-matcher (match)
12795 "Create the TAGS/TODO matcher form for the selection string MATCH."
12796 ;; todo-only is scoped dynamically into this function, and the function
12797 ;; may change it if the matcher asks for it.
12798 (unless match
12799 ;; Get a new match request, with completion
12800 (let ((org-last-tags-completion-table
12801 (org-global-tags-completion-table)))
12802 (setq match (org-completing-read-no-i
12803 "Match: " 'org-tags-completion-function nil nil nil
12804 'org-tags-history))))
12806 ;; Parse the string and create a lisp form
12807 (let ((match0 match)
12808 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
12809 minus tag mm
12810 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
12811 orterms term orlist re-p str-p level-p level-op time-p
12812 prop-p pn pv po gv rest)
12813 (if (string-match "/+" match)
12814 ;; match contains also a todo-matching request
12815 (progn
12816 (setq tagsmatch (substring match 0 (match-beginning 0))
12817 todomatch (substring match (match-end 0)))
12818 (if (string-match "^!" todomatch)
12819 (setq todo-only t todomatch (substring todomatch 1)))
12820 (if (string-match "^\\s-*$" todomatch)
12821 (setq todomatch nil)))
12822 ;; only matching tags
12823 (setq tagsmatch match todomatch nil))
12825 ;; Make the tags matcher
12826 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
12827 (setq tagsmatcher t)
12828 (setq orterms (org-split-string tagsmatch "|") orlist nil)
12829 (while (setq term (pop orterms))
12830 (while (and (equal (substring term -1) "\\") orterms)
12831 (setq term (concat term "|" (pop orterms)))) ; repair bad split
12832 (while (string-match re term)
12833 (setq rest (substring term (match-end 0))
12834 minus (and (match-end 1)
12835 (equal (match-string 1 term) "-"))
12836 tag (save-match-data (replace-regexp-in-string
12837 "\\\\-" "-"
12838 (match-string 2 term)))
12839 re-p (equal (string-to-char tag) ?{)
12840 level-p (match-end 4)
12841 prop-p (match-end 5)
12842 mm (cond
12843 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
12844 (level-p
12845 (setq level-op (org-op-to-function (match-string 3 term)))
12846 `(,level-op level ,(string-to-number
12847 (match-string 4 term))))
12848 (prop-p
12849 (setq pn (match-string 5 term)
12850 po (match-string 6 term)
12851 pv (match-string 7 term)
12852 re-p (equal (string-to-char pv) ?{)
12853 str-p (equal (string-to-char pv) ?\")
12854 time-p (save-match-data
12855 (string-match "^\"[[<].*[]>]\"$" pv))
12856 pv (if (or re-p str-p) (substring pv 1 -1) pv))
12857 (if time-p (setq pv (org-matcher-time pv)))
12858 (setq po (org-op-to-function po (if time-p 'time str-p)))
12859 (cond
12860 ((equal pn "CATEGORY")
12861 (setq gv '(get-text-property (point) 'org-category)))
12862 ((equal pn "TODO")
12863 (setq gv 'todo))
12865 (setq gv `(org-cached-entry-get nil ,pn))))
12866 (if re-p
12867 (if (eq po 'org<>)
12868 `(not (string-match ,pv (or ,gv "")))
12869 `(string-match ,pv (or ,gv "")))
12870 (if str-p
12871 `(,po (or ,gv "") ,pv)
12872 `(,po (string-to-number (or ,gv ""))
12873 ,(string-to-number pv) ))))
12874 (t `(member ,tag tags-list)))
12875 mm (if minus (list 'not mm) mm)
12876 term rest)
12877 (push mm tagsmatcher))
12878 (push (if (> (length tagsmatcher) 1)
12879 (cons 'and tagsmatcher)
12880 (car tagsmatcher))
12881 orlist)
12882 (setq tagsmatcher nil))
12883 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
12884 (setq tagsmatcher
12885 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
12886 ;; Make the todo matcher
12887 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
12888 (setq todomatcher t)
12889 (setq orterms (org-split-string todomatch "|") orlist nil)
12890 (while (setq term (pop orterms))
12891 (while (string-match re term)
12892 (setq minus (and (match-end 1)
12893 (equal (match-string 1 term) "-"))
12894 kwd (match-string 2 term)
12895 re-p (equal (string-to-char kwd) ?{)
12896 term (substring term (match-end 0))
12897 mm (if re-p
12898 `(string-match ,(substring kwd 1 -1) todo)
12899 (list 'equal 'todo kwd))
12900 mm (if minus (list 'not mm) mm))
12901 (push mm todomatcher))
12902 (push (if (> (length todomatcher) 1)
12903 (cons 'and todomatcher)
12904 (car todomatcher))
12905 orlist)
12906 (setq todomatcher nil))
12907 (setq todomatcher (if (> (length orlist) 1)
12908 (cons 'or orlist) (car orlist))))
12910 ;; Return the string and lisp forms of the matcher
12911 (setq matcher (if todomatcher
12912 (list 'and tagsmatcher todomatcher)
12913 tagsmatcher))
12914 (cons match0 matcher)))
12916 (defun org-op-to-function (op &optional stringp)
12917 "Turn an operator into the appropriate function."
12918 (setq op
12919 (cond
12920 ((equal op "<" ) '(< string< org-time<))
12921 ((equal op ">" ) '(> org-string> org-time>))
12922 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
12923 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
12924 ((member op '("=" "==")) '(= string= org-time=))
12925 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
12926 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
12928 (defun org<> (a b) (not (= a b)))
12929 (defun org-string<= (a b) (or (string= a b) (string< a b)))
12930 (defun org-string>= (a b) (not (string< a b)))
12931 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
12932 (defun org-string<> (a b) (not (string= a b)))
12933 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
12934 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
12935 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
12936 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
12937 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
12938 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
12939 (defun org-2ft (s)
12940 "Convert S to a floating point time.
12941 If S is already a number, just return it. If it is a string, parse
12942 it as a time string and apply `float-time' to it. If S is nil, just return 0."
12943 (cond
12944 ((numberp s) s)
12945 ((stringp s)
12946 (condition-case nil
12947 (float-time (apply 'encode-time (org-parse-time-string s)))
12948 (error 0.)))
12949 (t 0.)))
12951 (defun org-time-today ()
12952 "Time in seconds today at 0:00.
12953 Returns the float number of seconds since the beginning of the
12954 epoch to the beginning of today (00:00)."
12955 (float-time (apply 'encode-time
12956 (append '(0 0 0) (nthcdr 3 (decode-time))))))
12958 (defun org-matcher-time (s)
12959 "Interpret a time comparison value."
12960 (save-match-data
12961 (cond
12962 ((string= s "<now>") (float-time))
12963 ((string= s "<today>") (org-time-today))
12964 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
12965 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
12966 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
12967 (+ (org-time-today)
12968 (* (string-to-number (match-string 1 s))
12969 (cdr (assoc (match-string 2 s)
12970 '(("d" . 86400.0) ("w" . 604800.0)
12971 ("m" . 2678400.0) ("y" . 31557600.0)))))))
12972 (t (org-2ft s)))))
12974 (defun org-match-any-p (re list)
12975 "Does re match any element of list?"
12976 (setq list (mapcar (lambda (x) (string-match re x)) list))
12977 (delq nil list))
12979 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
12980 (defvar org-tags-overlay (make-overlay 1 1))
12981 (org-detach-overlay org-tags-overlay)
12983 (defun org-get-local-tags-at (&optional pos)
12984 "Get a list of tags defined in the current headline."
12985 (org-get-tags-at pos 'local))
12987 (defun org-get-local-tags ()
12988 "Get a list of tags defined in the current headline."
12989 (org-get-tags-at nil 'local))
12991 (defun org-get-tags-at (&optional pos local)
12992 "Get a list of all headline tags applicable at POS.
12993 POS defaults to point. If tags are inherited, the list contains
12994 the targets in the same sequence as the headlines appear, i.e.
12995 the tags of the current headline come last.
12996 When LOCAL is non-nil, only return tags from the current headline,
12997 ignore inherited ones."
12998 (interactive)
12999 (if (and org-trust-scanner-tags
13000 (or (not pos) (equal pos (point)))
13001 (not local))
13002 org-scanner-tags
13003 (let (tags ltags lastpos parent)
13004 (save-excursion
13005 (save-restriction
13006 (widen)
13007 (goto-char (or pos (point)))
13008 (save-match-data
13009 (catch 'done
13010 (condition-case nil
13011 (progn
13012 (org-back-to-heading t)
13013 (while (not (equal lastpos (point)))
13014 (setq lastpos (point))
13015 (when (looking-at
13016 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
13017 (setq ltags (org-split-string
13018 (org-match-string-no-properties 1) ":"))
13019 (when parent
13020 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
13021 (setq tags (append
13022 (if parent
13023 (org-remove-uninherited-tags ltags)
13024 ltags)
13025 tags)))
13026 (or org-use-tag-inheritance (throw 'done t))
13027 (if local (throw 'done t))
13028 (or (org-up-heading-safe) (error nil))
13029 (setq parent t)))
13030 (error nil)))))
13031 (if local
13032 tags
13033 (append (org-remove-uninherited-tags org-file-tags) tags))))))
13035 (defun org-add-prop-inherited (s)
13036 (add-text-properties 0 (length s) '(inherited t) s)
13039 (defun org-toggle-tag (tag &optional onoff)
13040 "Toggle the tag TAG for the current line.
13041 If ONOFF is `on' or `off', don't toggle but set to this state."
13042 (let (res current)
13043 (save-excursion
13044 (org-back-to-heading t)
13045 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
13046 (point-at-eol) t)
13047 (progn
13048 (setq current (match-string 1))
13049 (replace-match ""))
13050 (setq current ""))
13051 (setq current (nreverse (org-split-string current ":")))
13052 (cond
13053 ((eq onoff 'on)
13054 (setq res t)
13055 (or (member tag current) (push tag current)))
13056 ((eq onoff 'off)
13057 (or (not (member tag current)) (setq current (delete tag current))))
13058 (t (if (member tag current)
13059 (setq current (delete tag current))
13060 (setq res t)
13061 (push tag current))))
13062 (end-of-line 1)
13063 (if current
13064 (progn
13065 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
13066 (org-set-tags nil t))
13067 (delete-horizontal-space))
13068 (run-hooks 'org-after-tags-change-hook))
13069 res))
13071 (defun org-align-tags-here (to-col)
13072 ;; Assumes that this is a headline
13073 (let ((pos (point)) (col (current-column)) ncol tags-l p)
13074 (beginning-of-line 1)
13075 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13076 (< pos (match-beginning 2)))
13077 (progn
13078 (setq tags-l (- (match-end 2) (match-beginning 2)))
13079 (goto-char (match-beginning 1))
13080 (insert " ")
13081 (delete-region (point) (1+ (match-beginning 2)))
13082 (setq ncol (max (1+ (current-column))
13083 (1+ col)
13084 (if (> to-col 0)
13085 to-col
13086 (- (abs to-col) tags-l))))
13087 (setq p (point))
13088 (insert (make-string (- ncol (current-column)) ?\ ))
13089 (setq ncol (current-column))
13090 (when indent-tabs-mode (tabify p (point-at-eol)))
13091 (org-move-to-column (min ncol col) t))
13092 (goto-char pos))))
13094 (defun org-set-tags-command (&optional arg just-align)
13095 "Call the set-tags command for the current entry."
13096 (interactive "P")
13097 (if (org-on-heading-p)
13098 (org-set-tags arg just-align)
13099 (save-excursion
13100 (org-back-to-heading t)
13101 (org-set-tags arg just-align))))
13103 (defun org-set-tags-to (data)
13104 "Set the tags of the current entry to DATA, replacing the current tags.
13105 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
13106 If DATA is nil or the empty string, any tags will be removed."
13107 (interactive "sTags: ")
13108 (setq data
13109 (cond
13110 ((eq data nil) "")
13111 ((equal data "") "")
13112 ((stringp data)
13113 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
13114 ":"))
13115 ((listp data)
13116 (concat ":" (mapconcat 'identity data ":") ":"))
13117 (t nil)))
13118 (when data
13119 (save-excursion
13120 (org-back-to-heading t)
13121 (when (looking-at org-complex-heading-regexp)
13122 (if (match-end 5)
13123 (progn
13124 (goto-char (match-beginning 5))
13125 (insert data)
13126 (delete-region (point) (point-at-eol))
13127 (org-set-tags nil 'align))
13128 (goto-char (point-at-eol))
13129 (insert " " data)
13130 (org-set-tags nil 'align)))
13131 (beginning-of-line 1)
13132 (if (looking-at ".*?\\([ \t]+\\)$")
13133 (delete-region (match-beginning 1) (match-end 1))))))
13135 (defun org-align-all-tags ()
13136 "Align the tags i all headings."
13137 (interactive)
13138 (save-excursion
13139 (or (ignore-errors (org-back-to-heading t))
13140 (outline-next-heading))
13141 (if (org-on-heading-p)
13142 (org-set-tags t)
13143 (message "No headings"))))
13145 (defvar org-indent-indentation-per-level)
13146 (defun org-set-tags (&optional arg just-align)
13147 "Set the tags for the current headline.
13148 With prefix ARG, realign all tags in headings in the current buffer."
13149 (interactive "P")
13150 (let* ((re org-outline-regexp-bol)
13151 (current (org-get-tags-string))
13152 (col (current-column))
13153 (org-setting-tags t)
13154 table current-tags inherited-tags ; computed below when needed
13155 tags p0 c0 c1 rpl di tc level)
13156 (if arg
13157 (save-excursion
13158 (goto-char (point-min))
13159 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
13160 (while (re-search-forward re nil t)
13161 (org-set-tags nil t)
13162 (end-of-line 1)))
13163 (message "All tags realigned to column %d" org-tags-column))
13164 (if just-align
13165 (setq tags current)
13166 ;; Get a new set of tags from the user
13167 (save-excursion
13168 (setq table (append org-tag-persistent-alist
13169 (or org-tag-alist (org-get-buffer-tags))
13170 (and
13171 org-complete-tags-always-offer-all-agenda-tags
13172 (org-global-tags-completion-table
13173 (org-agenda-files))))
13174 org-last-tags-completion-table table
13175 current-tags (org-split-string current ":")
13176 inherited-tags (nreverse
13177 (nthcdr (length current-tags)
13178 (nreverse (org-get-tags-at))))
13179 tags
13180 (if (or (eq t org-use-fast-tag-selection)
13181 (and org-use-fast-tag-selection
13182 (delq nil (mapcar 'cdr table))))
13183 (org-fast-tag-selection
13184 current-tags inherited-tags table
13185 (if org-fast-tag-selection-include-todo
13186 org-todo-key-alist))
13187 (let ((org-add-colon-after-tag-completion t))
13188 (org-trim
13189 (org-icompleting-read "Tags: "
13190 'org-tags-completion-function
13191 nil nil current 'org-tags-history))))))
13192 (while (string-match "[-+&]+" tags)
13193 ;; No boolean logic, just a list
13194 (setq tags (replace-match ":" t t tags))))
13196 (setq tags (replace-regexp-in-string "[,]" ":" tags))
13198 (if org-tags-sort-function
13199 (setq tags (mapconcat 'identity
13200 (sort (org-split-string
13201 tags (org-re "[^[:alnum:]_@#%]+"))
13202 org-tags-sort-function) ":")))
13204 (if (string-match "\\`[\t ]*\\'" tags)
13205 (setq tags "")
13206 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
13207 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
13209 ;; Insert new tags at the correct column
13210 (beginning-of-line 1)
13211 (setq level (or (and (looking-at org-outline-regexp)
13212 (- (match-end 0) (point) 1))
13214 (cond
13215 ((and (equal current "") (equal tags "")))
13216 ((re-search-forward
13217 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
13218 (point-at-eol) t)
13219 (if (equal tags "")
13220 (setq rpl "")
13221 (goto-char (match-beginning 0))
13222 (setq c0 (current-column)
13223 ;; compute offset for the case of org-indent-mode active
13224 di (if org-indent-mode
13225 (* (1- org-indent-indentation-per-level) (1- level))
13227 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
13228 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
13229 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
13230 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
13231 (replace-match rpl t t)
13232 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
13233 tags)
13234 (t (error "Tags alignment failed")))
13235 (org-move-to-column col)
13236 (unless just-align
13237 (run-hooks 'org-after-tags-change-hook)))))
13239 (defun org-change-tag-in-region (beg end tag off)
13240 "Add or remove TAG for each entry in the region.
13241 This works in the agenda, and also in an org-mode buffer."
13242 (interactive
13243 (list (region-beginning) (region-end)
13244 (let ((org-last-tags-completion-table
13245 (if (org-mode-p)
13246 (org-get-buffer-tags)
13247 (org-global-tags-completion-table))))
13248 (org-icompleting-read
13249 "Tag: " 'org-tags-completion-function nil nil nil
13250 'org-tags-history))
13251 (progn
13252 (message "[s]et or [r]emove? ")
13253 (equal (read-char-exclusive) ?r))))
13254 (if (fboundp 'deactivate-mark) (deactivate-mark))
13255 (let ((agendap (equal major-mode 'org-agenda-mode))
13256 l1 l2 m buf pos newhead (cnt 0))
13257 (goto-char end)
13258 (setq l2 (1- (org-current-line)))
13259 (goto-char beg)
13260 (setq l1 (org-current-line))
13261 (loop for l from l1 to l2 do
13262 (org-goto-line l)
13263 (setq m (get-text-property (point) 'org-hd-marker))
13264 (when (or (and (org-mode-p) (org-on-heading-p))
13265 (and agendap m))
13266 (setq buf (if agendap (marker-buffer m) (current-buffer))
13267 pos (if agendap m (point)))
13268 (with-current-buffer buf
13269 (save-excursion
13270 (save-restriction
13271 (goto-char pos)
13272 (setq cnt (1+ cnt))
13273 (org-toggle-tag tag (if off 'off 'on))
13274 (setq newhead (org-get-heading)))))
13275 (and agendap (org-agenda-change-all-lines newhead m))))
13276 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
13278 (defun org-tags-completion-function (string predicate &optional flag)
13279 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
13280 (confirm (lambda (x) (stringp (car x)))))
13281 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
13282 (setq s1 (match-string 1 string)
13283 s2 (match-string 2 string))
13284 (setq s1 "" s2 string))
13285 (cond
13286 ((eq flag nil)
13287 ;; try completion
13288 (setq rtn (try-completion s2 ctable confirm))
13289 (if (stringp rtn)
13290 (setq rtn
13291 (concat s1 s2 (substring rtn (length s2))
13292 (if (and org-add-colon-after-tag-completion
13293 (assoc rtn ctable))
13294 ":" ""))))
13295 rtn)
13296 ((eq flag t)
13297 ;; all-completions
13298 (all-completions s2 ctable confirm)
13300 ((eq flag 'lambda)
13301 ;; exact match?
13302 (assoc s2 ctable)))
13305 (defun org-fast-tag-insert (kwd tags face &optional end)
13306 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
13307 (insert (format "%-12s" (concat kwd ":"))
13308 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
13309 (or end "")))
13311 (defun org-fast-tag-show-exit (flag)
13312 (save-excursion
13313 (org-goto-line 3)
13314 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
13315 (replace-match ""))
13316 (when flag
13317 (end-of-line 1)
13318 (org-move-to-column (- (window-width) 19) t)
13319 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
13321 (defun org-set-current-tags-overlay (current prefix)
13322 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
13323 (if (featurep 'xemacs)
13324 (org-overlay-display org-tags-overlay (concat prefix s)
13325 'secondary-selection)
13326 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
13327 (org-overlay-display org-tags-overlay (concat prefix s)))))
13329 (defvar org-last-tag-selection-key nil)
13330 (defun org-fast-tag-selection (current inherited table &optional todo-table)
13331 "Fast tag selection with single keys.
13332 CURRENT is the current list of tags in the headline, INHERITED is the
13333 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
13334 possibly with grouping information. TODO-TABLE is a similar table with
13335 TODO keywords, should these have keys assigned to them.
13336 If the keys are nil, a-z are automatically assigned.
13337 Returns the new tags string, or nil to not change the current settings."
13338 (let* ((fulltable (append table todo-table))
13339 (maxlen (apply 'max (mapcar
13340 (lambda (x)
13341 (if (stringp (car x)) (string-width (car x)) 0))
13342 fulltable)))
13343 (buf (current-buffer))
13344 (expert (eq org-fast-tag-selection-single-key 'expert))
13345 (buffer-tags nil)
13346 (fwidth (+ maxlen 3 1 3))
13347 (ncol (/ (- (window-width) 4) fwidth))
13348 (i-face 'org-done)
13349 (c-face 'org-todo)
13350 tg cnt e c char c1 c2 ntable tbl rtn
13351 ov-start ov-end ov-prefix
13352 (exit-after-next org-fast-tag-selection-single-key)
13353 (done-keywords org-done-keywords)
13354 groups ingroup)
13355 (save-excursion
13356 (beginning-of-line 1)
13357 (if (looking-at
13358 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13359 (setq ov-start (match-beginning 1)
13360 ov-end (match-end 1)
13361 ov-prefix "")
13362 (setq ov-start (1- (point-at-eol))
13363 ov-end (1+ ov-start))
13364 (skip-chars-forward "^\n\r")
13365 (setq ov-prefix
13366 (concat
13367 (buffer-substring (1- (point)) (point))
13368 (if (> (current-column) org-tags-column)
13370 (make-string (- org-tags-column (current-column)) ?\ ))))))
13371 (move-overlay org-tags-overlay ov-start ov-end)
13372 (save-window-excursion
13373 (if expert
13374 (set-buffer (get-buffer-create " *Org tags*"))
13375 (delete-other-windows)
13376 (split-window-vertically)
13377 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
13378 (erase-buffer)
13379 (org-set-local 'org-done-keywords done-keywords)
13380 (org-fast-tag-insert "Inherited" inherited i-face "\n")
13381 (org-fast-tag-insert "Current" current c-face "\n\n")
13382 (org-fast-tag-show-exit exit-after-next)
13383 (org-set-current-tags-overlay current ov-prefix)
13384 (setq tbl fulltable char ?a cnt 0)
13385 (while (setq e (pop tbl))
13386 (cond
13387 ((equal (car e) :startgroup)
13388 (push '() groups) (setq ingroup t)
13389 (when (not (= cnt 0))
13390 (setq cnt 0)
13391 (insert "\n"))
13392 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
13393 ((equal (car e) :endgroup)
13394 (setq ingroup nil cnt 0)
13395 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
13396 ((equal e '(:newline))
13397 (when (not (= cnt 0))
13398 (setq cnt 0)
13399 (insert "\n")
13400 (setq e (car tbl))
13401 (while (equal (car tbl) '(:newline))
13402 (insert "\n")
13403 (setq tbl (cdr tbl)))))
13405 (setq tg (copy-sequence (car e)) c2 nil)
13406 (if (cdr e)
13407 (setq c (cdr e))
13408 ;; automatically assign a character.
13409 (setq c1 (string-to-char
13410 (downcase (substring
13411 tg (if (= (string-to-char tg) ?@) 1 0)))))
13412 (if (or (rassoc c1 ntable) (rassoc c1 table))
13413 (while (or (rassoc char ntable) (rassoc char table))
13414 (setq char (1+ char)))
13415 (setq c2 c1))
13416 (setq c (or c2 char)))
13417 (if ingroup (push tg (car groups)))
13418 (setq tg (org-add-props tg nil 'face
13419 (cond
13420 ((not (assoc tg table))
13421 (org-get-todo-face tg))
13422 ((member tg current) c-face)
13423 ((member tg inherited) i-face)
13424 (t nil))))
13425 (if (and (= cnt 0) (not ingroup)) (insert " "))
13426 (insert "[" c "] " tg (make-string
13427 (- fwidth 4 (length tg)) ?\ ))
13428 (push (cons tg c) ntable)
13429 (when (= (setq cnt (1+ cnt)) ncol)
13430 (insert "\n")
13431 (if ingroup (insert " "))
13432 (setq cnt 0)))))
13433 (setq ntable (nreverse ntable))
13434 (insert "\n")
13435 (goto-char (point-min))
13436 (if (not expert) (org-fit-window-to-buffer))
13437 (setq rtn
13438 (catch 'exit
13439 (while t
13440 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
13441 (if (not groups) "no " "")
13442 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
13443 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13444 (setq org-last-tag-selection-key c)
13445 (cond
13446 ((= c ?\r) (throw 'exit t))
13447 ((= c ?!)
13448 (setq groups (not groups))
13449 (goto-char (point-min))
13450 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
13451 ((= c ?\C-c)
13452 (if (not expert)
13453 (org-fast-tag-show-exit
13454 (setq exit-after-next (not exit-after-next)))
13455 (setq expert nil)
13456 (delete-other-windows)
13457 (set-window-buffer (split-window-vertically) " *Org tags*")
13458 (org-switch-to-buffer-other-window " *Org tags*")
13459 (org-fit-window-to-buffer)))
13460 ((or (= c ?\C-g)
13461 (and (= c ?q) (not (rassoc c ntable))))
13462 (org-detach-overlay org-tags-overlay)
13463 (setq quit-flag t))
13464 ((= c ?\ )
13465 (setq current nil)
13466 (if exit-after-next (setq exit-after-next 'now)))
13467 ((= c ?\t)
13468 (condition-case nil
13469 (setq tg (org-icompleting-read
13470 "Tag: "
13471 (or buffer-tags
13472 (with-current-buffer buf
13473 (org-get-buffer-tags)))))
13474 (quit (setq tg "")))
13475 (when (string-match "\\S-" tg)
13476 (add-to-list 'buffer-tags (list tg))
13477 (if (member tg current)
13478 (setq current (delete tg current))
13479 (push tg current)))
13480 (if exit-after-next (setq exit-after-next 'now)))
13481 ((setq e (rassoc c todo-table) tg (car e))
13482 (with-current-buffer buf
13483 (save-excursion (org-todo tg)))
13484 (if exit-after-next (setq exit-after-next 'now)))
13485 ((setq e (rassoc c ntable) tg (car e))
13486 (if (member tg current)
13487 (setq current (delete tg current))
13488 (loop for g in groups do
13489 (if (member tg g)
13490 (mapc (lambda (x)
13491 (setq current (delete x current)))
13492 g)))
13493 (push tg current))
13494 (if exit-after-next (setq exit-after-next 'now))))
13496 ;; Create a sorted list
13497 (setq current
13498 (sort current
13499 (lambda (a b)
13500 (assoc b (cdr (memq (assoc a ntable) ntable))))))
13501 (if (eq exit-after-next 'now) (throw 'exit t))
13502 (goto-char (point-min))
13503 (beginning-of-line 2)
13504 (delete-region (point) (point-at-eol))
13505 (org-fast-tag-insert "Current" current c-face)
13506 (org-set-current-tags-overlay current ov-prefix)
13507 (while (re-search-forward
13508 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
13509 (setq tg (match-string 1))
13510 (add-text-properties
13511 (match-beginning 1) (match-end 1)
13512 (list 'face
13513 (cond
13514 ((member tg current) c-face)
13515 ((member tg inherited) i-face)
13516 (t (get-text-property (match-beginning 1) 'face))))))
13517 (goto-char (point-min)))))
13518 (org-detach-overlay org-tags-overlay)
13519 (if rtn
13520 (mapconcat 'identity current ":")
13521 nil))))
13523 (defun org-get-tags-string ()
13524 "Get the TAGS string in the current headline."
13525 (unless (org-on-heading-p t)
13526 (error "Not on a heading"))
13527 (save-excursion
13528 (beginning-of-line 1)
13529 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13530 (org-match-string-no-properties 1)
13531 "")))
13533 (defun org-get-tags ()
13534 "Get the list of tags specified in the current headline."
13535 (org-split-string (org-get-tags-string) ":"))
13537 (defun org-get-buffer-tags ()
13538 "Get a table of all tags used in the buffer, for completion."
13539 (let (tags)
13540 (save-excursion
13541 (goto-char (point-min))
13542 (while (re-search-forward
13543 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
13544 (when (equal (char-after (point-at-bol 0)) ?*)
13545 (mapc (lambda (x) (add-to-list 'tags x))
13546 (org-split-string (org-match-string-no-properties 1) ":")))))
13547 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
13548 (mapcar 'list tags)))
13550 ;;;; The mapping API
13552 ;;;###autoload
13553 (defun org-map-entries (func &optional match scope &rest skip)
13554 "Call FUNC at each headline selected by MATCH in SCOPE.
13556 FUNC is a function or a lisp form. The function will be called without
13557 arguments, with the cursor positioned at the beginning of the headline.
13558 The return values of all calls to the function will be collected and
13559 returned as a list.
13561 The call to FUNC will be wrapped into a save-excursion form, so FUNC
13562 does not need to preserve point. After evaluation, the cursor will be
13563 moved to the end of the line (presumably of the headline of the
13564 processed entry) and search continues from there. Under some
13565 circumstances, this may not produce the wanted results. For example,
13566 if you have removed (e.g. archived) the current (sub)tree it could
13567 mean that the next entry will be skipped entirely. In such cases, you
13568 can specify the position from where search should continue by making
13569 FUNC set the variable `org-map-continue-from' to the desired buffer
13570 position.
13572 MATCH is a tags/property/todo match as it is used in the agenda tags view.
13573 Only headlines that are matched by this query will be considered during
13574 the iteration. When MATCH is nil or t, all headlines will be
13575 visited by the iteration.
13577 SCOPE determines the scope of this command. It can be any of:
13579 nil The current buffer, respecting the restriction if any
13580 tree The subtree started with the entry at point
13581 region The entries within the active region, if any
13582 file The current buffer, without restriction
13583 file-with-archives
13584 The current buffer, and any archives associated with it
13585 agenda All agenda files
13586 agenda-with-archives
13587 All agenda files with any archive files associated with them
13588 \(file1 file2 ...)
13589 If this is a list, all files in the list will be scanned
13591 The remaining args are treated as settings for the skipping facilities of
13592 the scanner. The following items can be given here:
13594 archive skip trees with the archive tag.
13595 comment skip trees with the COMMENT keyword
13596 function or Emacs Lisp form:
13597 will be used as value for `org-agenda-skip-function', so whenever
13598 the function returns t, FUNC will not be called for that
13599 entry and search will continue from the point where the
13600 function leaves it.
13602 If your function needs to retrieve the tags including inherited tags
13603 at the *current* entry, you can use the value of the variable
13604 `org-scanner-tags' which will be much faster than getting the value
13605 with `org-get-tags-at'. If your function gets properties with
13606 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
13607 to t around the call to `org-entry-properties' to get the same speedup.
13608 Note that if your function moves around to retrieve tags and properties at
13609 a *different* entry, you cannot use these techniques."
13610 (let* ((org-agenda-archives-mode nil) ; just to make sure
13611 (org-agenda-skip-archived-trees (memq 'archive skip))
13612 (org-agenda-skip-comment-trees (memq 'comment skip))
13613 (org-agenda-skip-function
13614 (car (org-delete-all '(comment archive) skip)))
13615 (org-tags-match-list-sublevels t)
13616 matcher file res
13617 org-todo-keywords-for-agenda
13618 org-done-keywords-for-agenda
13619 org-todo-keyword-alist-for-agenda
13620 org-drawers-for-agenda
13621 org-tag-alist-for-agenda)
13623 (cond
13624 ((eq match t) (setq matcher t))
13625 ((eq match nil) (setq matcher t))
13626 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
13628 (save-excursion
13629 (save-restriction
13630 (cond ((eq scope 'tree)
13631 (org-back-to-heading t)
13632 (org-narrow-to-subtree)
13633 (setq scope nil))
13634 ((and (eq scope 'region) (org-region-active-p))
13635 (narrow-to-region (region-beginning) (region-end))
13636 (setq scope nil)))
13638 (if (not scope)
13639 (progn
13640 (org-prepare-agenda-buffers
13641 (list (buffer-file-name (current-buffer))))
13642 (setq res (org-scan-tags func matcher)))
13643 ;; Get the right scope
13644 (cond
13645 ((and scope (listp scope) (symbolp (car scope)))
13646 (setq scope (eval scope)))
13647 ((eq scope 'agenda)
13648 (setq scope (org-agenda-files t)))
13649 ((eq scope 'agenda-with-archives)
13650 (setq scope (org-agenda-files t))
13651 (setq scope (org-add-archive-files scope)))
13652 ((eq scope 'file)
13653 (setq scope (list (buffer-file-name))))
13654 ((eq scope 'file-with-archives)
13655 (setq scope (org-add-archive-files (list (buffer-file-name))))))
13656 (org-prepare-agenda-buffers scope)
13657 (while (setq file (pop scope))
13658 (with-current-buffer (org-find-base-buffer-visiting file)
13659 (save-excursion
13660 (save-restriction
13661 (widen)
13662 (goto-char (point-min))
13663 (setq res (append res (org-scan-tags func matcher))))))))))
13664 res))
13666 ;;;; Properties
13668 ;;; Setting and retrieving properties
13670 (defconst org-special-properties
13671 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
13672 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM")
13673 "The special properties valid in Org-mode.
13675 These are properties that are not defined in the property drawer,
13676 but in some other way.")
13678 (defconst org-default-properties
13679 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
13680 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
13681 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
13682 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
13683 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
13684 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
13685 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
13686 "Some properties that are used by Org-mode for various purposes.
13687 Being in this list makes sure that they are offered for completion.")
13689 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
13690 "Regular expression matching the first line of a property drawer.")
13692 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
13693 "Regular expression matching the last line of a property drawer.")
13695 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
13696 "Regular expression matching the first line of a property drawer.")
13698 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
13699 "Regular expression matching the first line of a property drawer.")
13701 (defconst org-property-drawer-re
13702 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
13703 org-property-end-re "\\)\n?")
13704 "Matches an entire property drawer.")
13706 (defconst org-clock-drawer-re
13707 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
13708 org-property-end-re "\\)\n?")
13709 "Matches an entire clock drawer.")
13711 (defsubst org-re-property (property)
13712 "Return a regexp matching PROPERTY.
13713 Match group 1 will be set to the value of the property."
13714 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
13716 (defun org-property-action ()
13717 "Do an action on properties."
13718 (interactive)
13719 (let (c)
13720 (org-at-property-p)
13721 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
13722 (setq c (read-char-exclusive))
13723 (cond
13724 ((equal c ?s)
13725 (call-interactively 'org-set-property))
13726 ((equal c ?d)
13727 (call-interactively 'org-delete-property))
13728 ((equal c ?D)
13729 (call-interactively 'org-delete-property-globally))
13730 ((equal c ?c)
13731 (call-interactively 'org-compute-property-at-point))
13732 (t (error "No such property action %c" c)))))
13734 (defun org-set-effort (&optional value)
13735 "Set the effort property of the current entry.
13736 With numerical prefix arg, use the nth allowed value, 0 stands for the 10th
13737 allowed value."
13738 (interactive "P")
13739 (if (equal value 0) (setq value 10))
13740 (let* ((completion-ignore-case t)
13741 (prop org-effort-property)
13742 (cur (org-entry-get nil prop))
13743 (allowed (org-property-get-allowed-values nil prop 'table))
13744 (existing (mapcar 'list (org-property-values prop)))
13746 (val (cond
13747 ((stringp value) value)
13748 ((and allowed (integerp value))
13749 (or (car (nth (1- value) allowed))
13750 (car (org-last allowed))))
13751 (allowed
13752 (message "Select 1-9,0, [RET%s]: %s"
13753 (if cur (concat "=" cur) "")
13754 (mapconcat 'car allowed " "))
13755 (setq rpl (read-char-exclusive))
13756 (if (equal rpl ?\r)
13758 (setq rpl (- rpl ?0))
13759 (if (equal rpl 0) (setq rpl 10))
13760 (if (and (> rpl 0) (<= rpl (length allowed)))
13761 (car (nth (1- rpl) allowed))
13762 (org-completing-read "Effort: " allowed nil))))
13764 (let (org-completion-use-ido org-completion-use-iswitchb)
13765 (org-completing-read
13766 (concat "Effort " (if (and cur (string-match "\\S-" cur))
13767 (concat "[" cur "]") "")
13768 ": ")
13769 existing nil nil "" nil cur))))))
13770 (unless (equal (org-entry-get nil prop) val)
13771 (org-entry-put nil prop val))
13772 (message "%s is now %s" prop val)))
13774 (defun org-at-property-p ()
13775 "Is cursor inside a property drawer?"
13776 (save-excursion
13777 (beginning-of-line 1)
13778 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
13779 (save-match-data ;; Used by calling procedures
13780 (let ((p (point))
13781 (range (unless (org-before-first-heading-p)
13782 (org-get-property-block))))
13783 (and range (<= (car range) p) (< p (cdr range))))))))
13785 (defun org-get-property-block (&optional beg end force)
13786 "Return the (beg . end) range of the body of the property drawer.
13787 BEG and END can be beginning and end of subtree, if not given
13788 they will be found.
13789 If the drawer does not exist and FORCE is non-nil, create the drawer."
13790 (catch 'exit
13791 (save-excursion
13792 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
13793 (end (or end (progn (outline-next-heading) (point)))))
13794 (goto-char beg)
13795 (if (re-search-forward org-property-start-re end t)
13796 (setq beg (1+ (match-end 0)))
13797 (if force
13798 (save-excursion
13799 (org-insert-property-drawer)
13800 (setq end (progn (outline-next-heading) (point))))
13801 (throw 'exit nil))
13802 (goto-char beg)
13803 (if (re-search-forward org-property-start-re end t)
13804 (setq beg (1+ (match-end 0)))))
13805 (if (re-search-forward org-property-end-re end t)
13806 (setq end (match-beginning 0))
13807 (or force (throw 'exit nil))
13808 (goto-char beg)
13809 (setq end beg)
13810 (org-indent-line-function)
13811 (insert ":END:\n"))
13812 (cons beg end)))))
13814 (defun org-entry-properties (&optional pom which specific)
13815 "Get all properties of the entry at point-or-marker POM.
13816 This includes the TODO keyword, the tags, time strings for deadline,
13817 scheduled, and clocking, and any additional properties defined in the
13818 entry. The return value is an alist, keys may occur multiple times
13819 if the property key was used several times.
13820 POM may also be nil, in which case the current entry is used.
13821 If WHICH is nil or `all', get all properties. If WHICH is
13822 `special' or `standard', only get that subclass. If WHICH
13823 is a string only get exactly this property. SPECIFIC can be a string, the
13824 specific property we are interested in. Specifying it can speed
13825 things up because then unnecessary parsing is avoided."
13826 (setq which (or which 'all))
13827 (org-with-point-at pom
13828 (let ((clockstr (substring org-clock-string 0 -1))
13829 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
13830 (case-fold-search nil)
13831 beg end range props sum-props key key1 value string clocksum)
13832 (save-excursion
13833 (when (condition-case nil
13834 (and (org-mode-p) (org-back-to-heading t))
13835 (error nil))
13836 (setq beg (point))
13837 (setq sum-props (get-text-property (point) 'org-summaries))
13838 (setq clocksum (get-text-property (point) :org-clock-minutes))
13839 (outline-next-heading)
13840 (setq end (point))
13841 (when (memq which '(all special))
13842 ;; Get the special properties, like TODO and tags
13843 (goto-char beg)
13844 (when (and (or (not specific) (string= specific "TODO"))
13845 (looking-at org-todo-line-regexp) (match-end 2))
13846 (push (cons "TODO" (org-match-string-no-properties 2)) props))
13847 (when (and (or (not specific) (string= specific "PRIORITY"))
13848 (looking-at org-priority-regexp))
13849 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
13850 (when (or (not specific) (string= specific "FILE"))
13851 (push (cons "FILE" buffer-file-name) props))
13852 (when (and (or (not specific) (string= specific "TAGS"))
13853 (setq value (org-get-tags-string))
13854 (string-match "\\S-" value))
13855 (push (cons "TAGS" value) props))
13856 (when (and (or (not specific) (string= specific "ALLTAGS"))
13857 (setq value (org-get-tags-at)))
13858 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
13859 ":"))
13860 props))
13861 (when (or (not specific) (string= specific "BLOCKED"))
13862 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
13863 (when (or (not specific)
13864 (member specific
13865 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
13866 "TIMESTAMP" "TIMESTAMP_IA")))
13867 (catch 'match
13868 (while (re-search-forward org-maybe-keyword-time-regexp end t)
13869 (setq key (if (match-end 1)
13870 (substring (org-match-string-no-properties 1)
13871 0 -1))
13872 string (if (equal key clockstr)
13873 (org-no-properties
13874 (org-trim
13875 (buffer-substring
13876 (match-beginning 3) (goto-char
13877 (point-at-eol)))))
13878 (substring (org-match-string-no-properties 3)
13879 1 -1)))
13880 ;; Get the correct property name from the key. This is
13881 ;; necessary if the user has configured time keywords.
13882 (setq key1 (concat key ":"))
13883 (cond
13884 ((not key)
13885 (setq key
13886 (if (= (char-after (match-beginning 3)) ?\[)
13887 "TIMESTAMP_IA" "TIMESTAMP")))
13888 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
13889 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
13890 ((equal key1 org-closed-string) (setq key "CLOSED"))
13891 ((equal key1 org-clock-string) (setq key "CLOCK")))
13892 (if (and specific (equal key specific) (not (equal key "CLOCK")))
13893 (progn
13894 (push (cons key string) props)
13895 ;; no need to search further if match is found
13896 (throw 'match t))
13897 (when (or (equal key "CLOCK") (not (assoc key props)))
13898 (push (cons key string) props))))))
13901 (when (memq which '(all standard))
13902 ;; Get the standard properties, like :PROP: ...
13903 (setq range (org-get-property-block beg end))
13904 (when range
13905 (goto-char (car range))
13906 (while (re-search-forward
13907 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
13908 (cdr range) t)
13909 (setq key (org-match-string-no-properties 1)
13910 value (org-trim (or (org-match-string-no-properties 2) "")))
13911 (unless (member key excluded)
13912 (push (cons key (or value "")) props)))))
13913 (if clocksum
13914 (push (cons "CLOCKSUM"
13915 (org-columns-number-to-string (/ (float clocksum) 60.)
13916 'add_times))
13917 props))
13918 (unless (assoc "CATEGORY" props)
13919 (push (cons "CATEGORY" (org-get-category)) props))
13920 (append sum-props (nreverse props)))))))
13922 (defun org-entry-get (pom property &optional inherit literal-nil)
13923 "Get value of PROPERTY for entry at point-or-marker POM.
13924 If INHERIT is non-nil and the entry does not have the property,
13925 then also check higher levels of the hierarchy.
13926 If INHERIT is the symbol `selective', use inheritance only if the setting
13927 in `org-use-property-inheritance' selects PROPERTY for inheritance.
13928 If the property is present but empty, the return value is the empty string.
13929 If the property is not present at all, nil is returned.
13931 If LITERAL-NIL is set, return the string value \"nil\" as a string,
13932 do not interpret it as the list atom nil. This is used for inheritance
13933 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
13934 (org-with-point-at pom
13935 (if (and inherit (if (eq inherit 'selective)
13936 (org-property-inherit-p property)
13938 (org-entry-get-with-inheritance property literal-nil)
13939 (if (member property org-special-properties)
13940 ;; We need a special property. Use `org-entry-properties' to
13941 ;; retrieve it, but specify the wanted property
13942 (cdr (assoc property (org-entry-properties nil 'special property)))
13943 (let ((range (unless (org-before-first-heading-p)
13944 (org-get-property-block))))
13945 (if (and range
13946 (goto-char (car range))
13947 (re-search-forward
13948 (org-re-property property)
13949 (cdr range) t))
13950 ;; Found the property, return it.
13951 (if (match-end 1)
13952 (if literal-nil
13953 (org-match-string-no-properties 1)
13954 (org-not-nil (org-match-string-no-properties 1)))
13955 "")))))))
13957 (defun org-property-or-variable-value (var &optional inherit)
13958 "Check if there is a property fixing the value of VAR.
13959 If yes, return this value. If not, return the current value of the variable."
13960 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
13961 (if (and prop (stringp prop) (string-match "\\S-" prop))
13962 (read prop)
13963 (symbol-value var))))
13965 (defun org-entry-delete (pom property)
13966 "Delete the property PROPERTY from entry at point-or-marker POM."
13967 (org-with-point-at pom
13968 (if (member property org-special-properties)
13969 nil ; cannot delete these properties.
13970 (let ((range (org-get-property-block)))
13971 (if (and range
13972 (goto-char (car range))
13973 (re-search-forward
13974 (org-re-property property)
13975 (cdr range) t))
13976 (progn
13977 (delete-region (match-beginning 0) (1+ (point-at-eol)))
13979 nil)))))
13981 ;; Multi-values properties are properties that contain multiple values
13982 ;; These values are assumed to be single words, separated by whitespace.
13983 (defun org-entry-add-to-multivalued-property (pom property value)
13984 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
13985 (let* ((old (org-entry-get pom property))
13986 (values (and old (org-split-string old "[ \t]"))))
13987 (setq value (org-entry-protect-space value))
13988 (unless (member value values)
13989 (setq values (cons value values))
13990 (org-entry-put pom property
13991 (mapconcat 'identity values " ")))))
13993 (defun org-entry-remove-from-multivalued-property (pom property value)
13994 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
13995 (let* ((old (org-entry-get pom property))
13996 (values (and old (org-split-string old "[ \t]"))))
13997 (setq value (org-entry-protect-space value))
13998 (when (member value values)
13999 (setq values (delete value values))
14000 (org-entry-put pom property
14001 (mapconcat 'identity values " ")))))
14003 (defun org-entry-member-in-multivalued-property (pom property value)
14004 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
14005 (let* ((old (org-entry-get pom property))
14006 (values (and old (org-split-string old "[ \t]"))))
14007 (setq value (org-entry-protect-space value))
14008 (member value values)))
14010 (defun org-entry-get-multivalued-property (pom property)
14011 "Return a list of values in a multivalued property."
14012 (let* ((value (org-entry-get pom property))
14013 (values (and value (org-split-string value "[ \t]"))))
14014 (mapcar 'org-entry-restore-space values)))
14016 (defun org-entry-put-multivalued-property (pom property &rest values)
14017 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
14018 VALUES should be a list of strings. Spaces will be protected."
14019 (org-entry-put pom property
14020 (mapconcat 'org-entry-protect-space values " "))
14021 (let* ((value (org-entry-get pom property))
14022 (values (and value (org-split-string value "[ \t]"))))
14023 (mapcar 'org-entry-restore-space values)))
14025 (defun org-entry-protect-space (s)
14026 "Protect spaces and newline in string S."
14027 (while (string-match " " s)
14028 (setq s (replace-match "%20" t t s)))
14029 (while (string-match "\n" s)
14030 (setq s (replace-match "%0A" t t s)))
14033 (defun org-entry-restore-space (s)
14034 "Restore spaces and newline in string S."
14035 (while (string-match "%20" s)
14036 (setq s (replace-match " " t t s)))
14037 (while (string-match "%0A" s)
14038 (setq s (replace-match "\n" t t s)))
14041 (defvar org-entry-property-inherited-from (make-marker)
14042 "Marker pointing to the entry from where a property was inherited.
14043 Each call to `org-entry-get-with-inheritance' will set this marker to the
14044 location of the entry where the inheritance search matched. If there was
14045 no match, the marker will point nowhere.
14046 Note that also `org-entry-get' calls this function, if the INHERIT flag
14047 is set.")
14049 (defun org-entry-get-with-inheritance (property &optional literal-nil)
14050 "Get entry property, and search higher levels if not present.
14051 The search will stop at the first ancestor which has the property defined.
14052 If the value found is \"nil\", return nil to show that the property
14053 should be considered as undefined (this is the meaning of nil here).
14054 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
14055 (move-marker org-entry-property-inherited-from nil)
14056 (let (tmp)
14057 (unless (org-before-first-heading-p)
14058 (save-excursion
14059 (save-restriction
14060 (widen)
14061 (catch 'ex
14062 (while t
14063 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
14064 (org-back-to-heading t)
14065 (move-marker org-entry-property-inherited-from (point))
14066 (throw 'ex tmp))
14067 (or (org-up-heading-safe) (throw 'ex nil)))))))
14068 (setq tmp (or tmp
14069 (cdr (assoc property org-file-properties))
14070 (cdr (assoc property org-global-properties))
14071 (cdr (assoc property org-global-properties-fixed))))
14072 (if literal-nil tmp (org-not-nil tmp))))
14074 (defvar org-property-changed-functions nil
14075 "Hook called when the value of a property has changed.
14076 Each hook function should accept two arguments, the name of the property
14077 and the new value.")
14079 (defun org-entry-put (pom property value)
14080 "Set PROPERTY to VALUE for entry at point-or-marker POM."
14081 (org-with-point-at pom
14082 (org-back-to-heading t)
14083 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
14084 range)
14085 (cond
14086 ((equal property "TODO")
14087 (when (and (stringp value) (string-match "\\S-" value)
14088 (not (member value org-todo-keywords-1)))
14089 (error "\"%s\" is not a valid TODO state" value))
14090 (if (or (not value)
14091 (not (string-match "\\S-" value)))
14092 (setq value 'none))
14093 (org-todo value)
14094 (org-set-tags nil 'align))
14095 ((equal property "PRIORITY")
14096 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
14097 (string-to-char value) ?\ ))
14098 (org-set-tags nil 'align))
14099 ((equal property "SCHEDULED")
14100 (if (re-search-forward org-scheduled-time-regexp end t)
14101 (cond
14102 ((eq value 'earlier) (org-timestamp-change -1 'day))
14103 ((eq value 'later) (org-timestamp-change 1 'day))
14104 (t (call-interactively 'org-schedule)))
14105 (call-interactively 'org-schedule)))
14106 ((equal property "DEADLINE")
14107 (if (re-search-forward org-deadline-time-regexp end t)
14108 (cond
14109 ((eq value 'earlier) (org-timestamp-change -1 'day))
14110 ((eq value 'later) (org-timestamp-change 1 'day))
14111 (t (call-interactively 'org-deadline)))
14112 (call-interactively 'org-deadline)))
14113 ((member property org-special-properties)
14114 (error "The %s property can not yet be set with `org-entry-put'"
14115 property))
14116 (t ; a non-special property
14117 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
14118 (setq range (org-get-property-block beg end 'force))
14119 (goto-char (car range))
14120 (if (re-search-forward
14121 (org-re-property property) (cdr range) t)
14122 (progn
14123 (delete-region (match-beginning 0) (match-end 0))
14124 (goto-char (match-beginning 0)))
14125 (goto-char (cdr range))
14126 (insert "\n")
14127 (backward-char 1)
14128 (org-indent-line-function))
14129 (insert ":" property ":")
14130 (and value (insert " " value))
14131 (org-indent-line-function)))))
14132 (run-hook-with-args 'org-property-changed-functions property value)))
14134 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
14135 "Get all property keys in the current buffer.
14136 With INCLUDE-SPECIALS, also list the special properties that reflect things
14137 like tags and TODO state.
14138 With INCLUDE-DEFAULTS, also include properties that has special meaning
14139 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
14140 and others.
14141 With INCLUDE-COLUMNS, also include property names given in COLUMN
14142 formats in the current buffer."
14143 (let (rtn range cfmt s p)
14144 (save-excursion
14145 (save-restriction
14146 (widen)
14147 (goto-char (point-min))
14148 (while (re-search-forward org-property-start-re nil t)
14149 (setq range (org-get-property-block))
14150 (goto-char (car range))
14151 (while (re-search-forward
14152 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
14153 (cdr range) t)
14154 (add-to-list 'rtn (org-match-string-no-properties 1)))
14155 (outline-next-heading))))
14157 (when include-specials
14158 (setq rtn (append org-special-properties rtn)))
14160 (when include-defaults
14161 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
14162 (add-to-list 'rtn org-effort-property))
14164 (when include-columns
14165 (save-excursion
14166 (save-restriction
14167 (widen)
14168 (goto-char (point-min))
14169 (while (re-search-forward
14170 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
14171 nil t)
14172 (setq cfmt (match-string 2) s 0)
14173 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
14174 cfmt s)
14175 (setq s (match-end 0)
14176 p (match-string 1 cfmt))
14177 (unless (or (equal p "ITEM")
14178 (member p org-special-properties))
14179 (add-to-list 'rtn (match-string 1 cfmt))))))))
14181 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
14183 (defun org-property-values (key)
14184 "Return a list of all values of property KEY in the current buffer."
14185 (save-excursion
14186 (save-restriction
14187 (widen)
14188 (goto-char (point-min))
14189 (let ((re (org-re-property key))
14190 values)
14191 (while (re-search-forward re nil t)
14192 (add-to-list 'values (org-trim (match-string 1))))
14193 (delete "" values)))))
14195 (defun org-insert-property-drawer ()
14196 "Insert a property drawer into the current entry."
14197 (interactive)
14198 (org-back-to-heading t)
14199 (looking-at org-outline-regexp)
14200 (let ((indent (if org-adapt-indentation
14201 (- (match-end 0)(match-beginning 0))
14203 (beg (point))
14204 (re (concat "^[ \t]*" org-keyword-time-regexp))
14205 end hiddenp)
14206 (outline-next-heading)
14207 (setq end (point))
14208 (goto-char beg)
14209 (while (re-search-forward re end t))
14210 (setq hiddenp (outline-invisible-p))
14211 (end-of-line 1)
14212 (and (equal (char-after) ?\n) (forward-char 1))
14213 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
14214 (if (member (match-string 1) '("CLOCK:" ":END:"))
14215 ;; just skip this line
14216 (beginning-of-line 2)
14217 ;; Drawer start, find the end
14218 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
14219 (beginning-of-line 1)))
14220 (org-skip-over-state-notes)
14221 (skip-chars-backward " \t\n\r")
14222 (if (eq (char-before) ?*) (forward-char 1))
14223 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
14224 (beginning-of-line 0)
14225 (org-indent-to-column indent)
14226 (beginning-of-line 2)
14227 (org-indent-to-column indent)
14228 (beginning-of-line 0)
14229 (if hiddenp
14230 (save-excursion
14231 (org-back-to-heading t)
14232 (hide-entry))
14233 (org-flag-drawer t))))
14235 (defvar org-property-set-functions-alist nil
14236 "Property set function alist.
14237 Each entry should have the following format:
14239 (PROPERTY . READ-FUNCTION)
14241 The read function will be called with the same argument as
14242 `org-completing-read'.")
14244 (defun org-set-property-function (property)
14245 "Get the function that should be used to set PROPERTY.
14246 This is computed according to `org-property-set-functions-alist'."
14247 (or (cdr (assoc property org-property-set-functions-alist))
14248 'org-completing-read))
14250 (defun org-read-property-value (property)
14251 "Read PROPERTY value from user."
14252 (let* ((completion-ignore-case t)
14253 (allowed (org-property-get-allowed-values nil property 'table))
14254 (cur (org-entry-get nil property))
14255 (prompt (concat property " value"
14256 (if (and cur (string-match "\\S-" cur))
14257 (concat " [" cur "]") "") ": "))
14258 (set-function (org-set-property-function property))
14259 (val (if allowed
14260 (funcall set-function prompt allowed nil
14261 (not (get-text-property 0 'org-unrestricted
14262 (caar allowed))))
14263 (let (org-completion-use-ido org-completion-use-iswitchb)
14264 (funcall set-function prompt
14265 (mapcar 'list (org-property-values property))
14266 nil nil "" nil cur)))))
14267 (if (equal val "")
14269 val)))
14271 (defvar org-last-set-property nil)
14272 (defun org-read-property-name ()
14273 "Read a property name."
14274 (let* ((completion-ignore-case t)
14275 (keys (org-buffer-property-keys nil t t))
14276 (default-prop (or (save-excursion
14277 (save-match-data
14278 (beginning-of-line)
14279 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
14280 (null (string= (match-string 1) "END"))
14281 (match-string 1))))
14282 org-last-set-property))
14283 (property (org-icompleting-read
14284 (concat "Property"
14285 (if default-prop (concat " [" default-prop "]") "")
14286 ": ")
14287 (mapcar 'list keys)
14288 nil nil nil nil
14289 default-prop
14291 (if (member property keys)
14292 property
14293 (or (cdr (assoc (downcase property)
14294 (mapcar (lambda (x) (cons (downcase x) x))
14295 keys)))
14296 property))))
14298 (defun org-set-property (property value)
14299 "In the current entry, set PROPERTY to VALUE.
14300 When called interactively, this will prompt for a property name, offering
14301 completion on existing and default properties. And then it will prompt
14302 for a value, offering completion either on allowed values (via an inherited
14303 xxx_ALL property) or on existing values in other instances of this property
14304 in the current file."
14305 (interactive (list nil nil))
14306 (let* ((property (or property (org-read-property-name)))
14307 (value (or value (org-read-property-value property))))
14308 (setq org-last-set-property property)
14309 ;; Possibly postprocess the inserted value:
14310 (when (assoc property org-properties-postprocess-alist)
14311 (setq value (funcall (cadr fn) value)))
14312 (unless (equal (org-entry-get nil property) value)
14313 (org-entry-put nil property value))))
14315 (defun org-delete-property (property)
14316 "In the current entry, delete PROPERTY."
14317 (interactive
14318 (let* ((completion-ignore-case t)
14319 (prop (org-icompleting-read "Property: "
14320 (org-entry-properties nil 'standard))))
14321 (list prop)))
14322 (message "Property %s %s" property
14323 (if (org-entry-delete nil property)
14324 "deleted"
14325 "was not present in the entry")))
14327 (defun org-delete-property-globally (property)
14328 "Remove PROPERTY globally, from all entries."
14329 (interactive
14330 (let* ((completion-ignore-case t)
14331 (prop (org-icompleting-read
14332 "Globally remove property: "
14333 (mapcar 'list (org-buffer-property-keys)))))
14334 (list prop)))
14335 (save-excursion
14336 (save-restriction
14337 (widen)
14338 (goto-char (point-min))
14339 (let ((cnt 0))
14340 (while (re-search-forward
14341 (org-re-property property)
14342 nil t)
14343 (setq cnt (1+ cnt))
14344 (replace-match ""))
14345 (message "Property \"%s\" removed from %d entries" property cnt)))))
14347 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
14349 (defun org-compute-property-at-point ()
14350 "Compute the property at point.
14351 This looks for an enclosing column format, extracts the operator and
14352 then applies it to the property in the column format's scope."
14353 (interactive)
14354 (unless (org-at-property-p)
14355 (error "Not at a property"))
14356 (let ((prop (org-match-string-no-properties 2)))
14357 (org-columns-get-format-and-top-level)
14358 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
14359 (error "No operator defined for property %s" prop))
14360 (org-columns-compute prop)))
14362 (defvar org-property-allowed-value-functions nil
14363 "Hook for functions supplying allowed values for a specific property.
14364 The functions must take a single argument, the name of the property, and
14365 return a flat list of allowed values. If \":ETC\" is one of
14366 the values, this means that these values are intended as defaults for
14367 completion, but that other values should be allowed too.
14368 The functions must return nil if they are not responsible for this
14369 property.")
14371 (defun org-property-get-allowed-values (pom property &optional table)
14372 "Get allowed values for the property PROPERTY.
14373 When TABLE is non-nil, return an alist that can directly be used for
14374 completion."
14375 (let (vals)
14376 (cond
14377 ((equal property "TODO")
14378 (setq vals (org-with-point-at pom
14379 (append org-todo-keywords-1 '("")))))
14380 ((equal property "PRIORITY")
14381 (let ((n org-lowest-priority))
14382 (while (>= n org-highest-priority)
14383 (push (char-to-string n) vals)
14384 (setq n (1- n)))))
14385 ((member property org-special-properties))
14386 ((setq vals (run-hook-with-args-until-success
14387 'org-property-allowed-value-functions property)))
14389 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
14390 (when (and vals (string-match "\\S-" vals))
14391 (setq vals (car (read-from-string (concat "(" vals ")"))))
14392 (setq vals (mapcar (lambda (x)
14393 (cond ((stringp x) x)
14394 ((numberp x) (number-to-string x))
14395 ((symbolp x) (symbol-name x))
14396 (t "???")))
14397 vals)))))
14398 (when (member ":ETC" vals)
14399 (setq vals (remove ":ETC" vals))
14400 (org-add-props (car vals) '(org-unrestricted t)))
14401 (if table (mapcar 'list vals) vals)))
14403 (defun org-property-previous-allowed-value (&optional previous)
14404 "Switch to the next allowed value for this property."
14405 (interactive)
14406 (org-property-next-allowed-value t))
14408 (defun org-property-next-allowed-value (&optional previous)
14409 "Switch to the next allowed value for this property."
14410 (interactive)
14411 (unless (org-at-property-p)
14412 (error "Not at a property"))
14413 (let* ((key (match-string 2))
14414 (value (match-string 3))
14415 (allowed (or (org-property-get-allowed-values (point) key)
14416 (and (member value '("[ ]" "[-]" "[X]"))
14417 '("[ ]" "[X]"))))
14418 nval)
14419 (unless allowed
14420 (error "Allowed values for this property have not been defined"))
14421 (if previous (setq allowed (reverse allowed)))
14422 (if (member value allowed)
14423 (setq nval (car (cdr (member value allowed)))))
14424 (setq nval (or nval (car allowed)))
14425 (if (equal nval value)
14426 (error "Only one allowed value for this property"))
14427 (org-at-property-p)
14428 (replace-match (concat " :" key ": " nval) t t)
14429 (org-indent-line-function)
14430 (beginning-of-line 1)
14431 (skip-chars-forward " \t")
14432 (run-hook-with-args 'org-property-changed-functions key nval)))
14434 (defun org-find-olp (path &optional this-buffer)
14435 "Return a marker pointing to the entry at outline path OLP.
14436 If anything goes wrong, throw an error.
14437 You can wrap this call to catch the error like this:
14439 (condition-case msg
14440 (org-mobile-locate-entry (match-string 4))
14441 (error (nth 1 msg)))
14443 The return value will then be either a string with the error message,
14444 or a marker if everything is OK.
14446 If THIS-BUFFER is set, the outline path does not contain a file,
14447 only headings."
14448 (let* ((file (if this-buffer buffer-file-name (pop path)))
14449 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
14450 (level 1)
14451 (lmin 1)
14452 (lmax 1)
14453 limit re end found pos heading cnt flevel)
14454 (unless buffer (error "File not found :%s" file))
14455 (with-current-buffer buffer
14456 (save-excursion
14457 (save-restriction
14458 (widen)
14459 (setq limit (point-max))
14460 (goto-char (point-min))
14461 (while (setq heading (pop path))
14462 (setq re (format org-complex-heading-regexp-format
14463 (regexp-quote heading)))
14464 (setq cnt 0 pos (point))
14465 (while (re-search-forward re end t)
14466 (setq level (- (match-end 1) (match-beginning 1)))
14467 (if (and (>= level lmin) (<= level lmax))
14468 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
14469 (when (= cnt 0) (error "Heading not found on level %d: %s"
14470 lmax heading))
14471 (when (> cnt 1) (error "Heading not unique on level %d: %s"
14472 lmax heading))
14473 (goto-char found)
14474 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
14475 (setq end (save-excursion (org-end-of-subtree t t))))
14476 (when (org-on-heading-p)
14477 (move-marker (make-marker) (point))))))))
14479 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
14480 "Find node HEADING in BUFFER.
14481 Return a marker to the heading if it was found, or nil if not.
14482 If POS-ONLY is set, return just the position instead of a marker.
14484 The heading text must match exact, but it may have a TODO keyword,
14485 a priority cookie and tags in the standard locations."
14486 (with-current-buffer (or buffer (current-buffer))
14487 (save-excursion
14488 (save-restriction
14489 (widen)
14490 (goto-char (point-min))
14491 (let (case-fold-search)
14492 (if (re-search-forward
14493 (format org-complex-heading-regexp-format
14494 (regexp-quote heading)) nil t)
14495 (if pos-only
14496 (match-beginning 0)
14497 (move-marker (make-marker) (match-beginning 0)))))))))
14499 (defun org-find-exact-heading-in-directory (heading &optional dir)
14500 "Find Org node headline HEADING in all .org files in directory DIR.
14501 When the target headline is found, return a marker to this location."
14502 (let ((files (directory-files (or dir default-directory)
14503 nil "\\`[^.#].*\\.org\\'"))
14504 file visiting m buffer)
14505 (catch 'found
14506 (while (setq file (pop files))
14507 (message "trying %s" file)
14508 (setq visiting (org-find-base-buffer-visiting file))
14509 (setq buffer (or visiting (find-file-noselect file)))
14510 (setq m (org-find-exact-headline-in-buffer
14511 heading buffer))
14512 (when (and (not m) (not visiting)) (kill-buffer buffer))
14513 (and m (throw 'found m))))))
14515 (defun org-find-entry-with-id (ident)
14516 "Locate the entry that contains the ID property with exact value IDENT.
14517 IDENT can be a string, a symbol or a number, this function will search for
14518 the string representation of it.
14519 Return the position where this entry starts, or nil if there is no such entry."
14520 (interactive "sID: ")
14521 (let ((id (cond
14522 ((stringp ident) ident)
14523 ((symbol-name ident) (symbol-name ident))
14524 ((numberp ident) (number-to-string ident))
14525 (t (error "IDENT %s must be a string, symbol or number" ident))))
14526 (case-fold-search nil))
14527 (save-excursion
14528 (save-restriction
14529 (widen)
14530 (goto-char (point-min))
14531 (when (re-search-forward
14532 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
14533 nil t)
14534 (org-back-to-heading t)
14535 (point))))))
14537 ;;;; Timestamps
14539 (defvar org-last-changed-timestamp nil)
14540 (defvar org-last-inserted-timestamp nil
14541 "The last time stamp inserted with `org-insert-time-stamp'.")
14542 (defvar org-time-was-given) ; dynamically scoped parameter
14543 (defvar org-end-time-was-given) ; dynamically scoped parameter
14544 (defvar org-ts-what) ; dynamically scoped parameter
14546 (defun org-time-stamp (arg &optional inactive)
14547 "Prompt for a date/time and insert a time stamp.
14548 If the user specifies a time like HH:MM, or if this command is called
14549 with a prefix argument, the time stamp will contain date and time.
14550 Otherwise, only the date will be included. All parts of a date not
14551 specified by the user will be filled in from the current date/time.
14552 So if you press just return without typing anything, the time stamp
14553 will represent the current date/time. If there is already a timestamp
14554 at the cursor, it will be modified."
14555 (interactive "P")
14556 (let* ((ts nil)
14557 (default-time
14558 ;; Default time is either today, or, when entering a range,
14559 ;; the range start.
14560 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
14561 (save-excursion
14562 (re-search-backward
14563 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
14564 (- (point) 20) t)))
14565 (apply 'encode-time (org-parse-time-string (match-string 1)))
14566 (current-time)))
14567 (default-input (and ts (org-get-compact-tod ts)))
14568 (repeater (save-excursion
14569 (save-match-data
14570 (beginning-of-line)
14571 (when (re-search-forward
14572 "\\([.+-]+[0-9]+[dwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[dwmy]\\)?\\) ?"
14573 (save-excursion (progn (end-of-line) (point))) t)
14574 (match-string 0)))))
14575 org-time-was-given org-end-time-was-given time)
14576 (cond
14577 ((and (org-at-timestamp-p t)
14578 (memq last-command '(org-time-stamp org-time-stamp-inactive))
14579 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
14580 (insert "--")
14581 (setq time (let ((this-command this-command))
14582 (org-read-date arg 'totime nil nil
14583 default-time default-input)))
14584 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
14585 ((org-at-timestamp-p t)
14586 (setq time (let ((this-command this-command))
14587 (org-read-date arg 'totime nil nil default-time default-input)))
14588 (when (org-at-timestamp-p t) ; just to get the match data
14589 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
14590 (replace-match "")
14591 (setq org-last-changed-timestamp
14592 (org-insert-time-stamp
14593 time (or org-time-was-given arg)
14594 inactive nil nil (list org-end-time-was-given)))
14595 (when repeater (goto-char (1- (point))) (insert " " repeater)
14596 (setq org-last-changed-timestamp
14597 (concat (substring org-last-inserted-timestamp 0 -1)
14598 " " repeater ">"))))
14599 (message "Timestamp updated"))
14601 (setq time (let ((this-command this-command))
14602 (org-read-date arg 'totime nil nil default-time default-input)))
14603 (org-insert-time-stamp time (or org-time-was-given arg) inactive
14604 nil nil (list org-end-time-was-given))))))
14606 ;; FIXME: can we use this for something else, like computing time differences?
14607 (defun org-get-compact-tod (s)
14608 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
14609 (let* ((t1 (match-string 1 s))
14610 (h1 (string-to-number (match-string 2 s)))
14611 (m1 (string-to-number (match-string 3 s)))
14612 (t2 (and (match-end 4) (match-string 5 s)))
14613 (h2 (and t2 (string-to-number (match-string 6 s))))
14614 (m2 (and t2 (string-to-number (match-string 7 s))))
14615 dh dm)
14616 (if (not t2)
14618 (setq dh (- h2 h1) dm (- m2 m1))
14619 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
14620 (concat t1 "+" (number-to-string dh)
14621 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
14623 (defun org-time-stamp-inactive (&optional arg)
14624 "Insert an inactive time stamp.
14625 An inactive time stamp is enclosed in square brackets instead of angle
14626 brackets. It is inactive in the sense that it does not trigger agenda entries,
14627 does not link to the calendar and cannot be changed with the S-cursor keys.
14628 So these are more for recording a certain time/date."
14629 (interactive "P")
14630 (org-time-stamp arg 'inactive))
14632 (defvar org-date-ovl (make-overlay 1 1))
14633 (overlay-put org-date-ovl 'face 'org-warning)
14634 (org-detach-overlay org-date-ovl)
14636 (defvar org-ans1) ; dynamically scoped parameter
14637 (defvar org-ans2) ; dynamically scoped parameter
14639 (defvar org-plain-time-of-day-regexp) ; defined below
14641 (defvar org-overriding-default-time nil) ; dynamically scoped
14642 (defvar org-read-date-overlay nil)
14643 (defvar org-dcst nil) ; dynamically scoped
14644 (defvar org-read-date-history nil)
14645 (defvar org-read-date-final-answer nil)
14646 (defvar org-read-date-analyze-futurep nil)
14647 (defvar org-read-date-analyze-forced-year nil)
14649 (defun org-read-date (&optional with-time to-time from-string prompt
14650 default-time default-input)
14651 "Read a date, possibly a time, and make things smooth for the user.
14652 The prompt will suggest to enter an ISO date, but you can also enter anything
14653 which will at least partially be understood by `parse-time-string'.
14654 Unrecognized parts of the date will default to the current day, month, year,
14655 hour and minute. If this command is called to replace a timestamp at point,
14656 of to enter the second timestamp of a range, the default time is taken
14657 from the existing stamp. Furthermore, the command prefers the future,
14658 so if you are giving a date where the year is not given, and the day-month
14659 combination is already past in the current year, it will assume you
14660 mean next year. For details, see the manual. A few examples:
14662 3-2-5 --> 2003-02-05
14663 feb 15 --> currentyear-02-15
14664 2/15 --> currentyear-02-15
14665 sep 12 9 --> 2009-09-12
14666 12:45 --> today 12:45
14667 22 sept 0:34 --> currentyear-09-22 0:34
14668 12 --> currentyear-currentmonth-12
14669 Fri --> nearest Friday (today or later)
14670 etc.
14672 Furthermore you can specify a relative date by giving, as the *first* thing
14673 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
14674 change in days weeks, months, years.
14675 With a single plus or minus, the date is relative to today. With a double
14676 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
14677 +4d --> four days from today
14678 +4 --> same as above
14679 +2w --> two weeks from today
14680 ++5 --> five days from default date
14682 The function understands only English month and weekday abbreviations,
14683 but this can be configured with the variables `parse-time-months' and
14684 `parse-time-weekdays'.
14686 While prompting, a calendar is popped up - you can also select the
14687 date with the mouse (button 1). The calendar shows a period of three
14688 months. To scroll it to other months, use the keys `>' and `<'.
14689 If you don't like the calendar, turn it off with
14690 \(setq org-read-date-popup-calendar nil)
14692 With optional argument TO-TIME, the date will immediately be converted
14693 to an internal time.
14694 With an optional argument WITH-TIME, the prompt will suggest to also
14695 insert a time. Note that when WITH-TIME is not set, you can still
14696 enter a time, and this function will inform the calling routine about
14697 this change. The calling routine may then choose to change the format
14698 used to insert the time stamp into the buffer to include the time.
14699 With optional argument FROM-STRING, read from this string instead from
14700 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
14701 the time/date that is used for everything that is not specified by the
14702 user."
14703 (require 'parse-time)
14704 (let* ((org-time-stamp-rounding-minutes
14705 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
14706 (org-dcst org-display-custom-times)
14707 (ct (org-current-time))
14708 (def (or org-overriding-default-time default-time ct))
14709 (defdecode (decode-time def))
14710 (dummy (progn
14711 (when (< (nth 2 defdecode) org-extend-today-until)
14712 (setcar (nthcdr 2 defdecode) -1)
14713 (setcar (nthcdr 1 defdecode) 59)
14714 (setq def (apply 'encode-time defdecode)
14715 defdecode (decode-time def)))))
14716 (calendar-frame-setup nil)
14717 (calendar-setup nil)
14718 (calendar-move-hook nil)
14719 (calendar-view-diary-initially-flag nil)
14720 (calendar-view-holidays-initially-flag nil)
14721 (timestr (format-time-string
14722 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
14723 (prompt (concat (if prompt (concat prompt " ") "")
14724 (format "Date+time [%s]: " timestr)))
14725 ans (org-ans0 "") org-ans1 org-ans2 final)
14727 (cond
14728 (from-string (setq ans from-string))
14729 (org-read-date-popup-calendar
14730 (save-excursion
14731 (save-window-excursion
14732 (calendar)
14733 (unwind-protect
14734 (progn
14735 (calendar-forward-day (- (time-to-days def)
14736 (calendar-absolute-from-gregorian
14737 (calendar-current-date))))
14738 (org-eval-in-calendar nil t)
14739 (let* ((old-map (current-local-map))
14740 (map (copy-keymap calendar-mode-map))
14741 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
14742 (org-defkey map (kbd "RET") 'org-calendar-select)
14743 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
14744 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
14745 (org-defkey minibuffer-local-map [(meta shift left)]
14746 (lambda () (interactive)
14747 (org-eval-in-calendar '(calendar-backward-month 1))))
14748 (org-defkey minibuffer-local-map [(meta shift right)]
14749 (lambda () (interactive)
14750 (org-eval-in-calendar '(calendar-forward-month 1))))
14751 (org-defkey minibuffer-local-map [(meta shift up)]
14752 (lambda () (interactive)
14753 (org-eval-in-calendar '(calendar-backward-year 1))))
14754 (org-defkey minibuffer-local-map [(meta shift down)]
14755 (lambda () (interactive)
14756 (org-eval-in-calendar '(calendar-forward-year 1))))
14757 (org-defkey minibuffer-local-map [?\e (shift left)]
14758 (lambda () (interactive)
14759 (org-eval-in-calendar '(calendar-backward-month 1))))
14760 (org-defkey minibuffer-local-map [?\e (shift right)]
14761 (lambda () (interactive)
14762 (org-eval-in-calendar '(calendar-forward-month 1))))
14763 (org-defkey minibuffer-local-map [?\e (shift up)]
14764 (lambda () (interactive)
14765 (org-eval-in-calendar '(calendar-backward-year 1))))
14766 (org-defkey minibuffer-local-map [?\e (shift down)]
14767 (lambda () (interactive)
14768 (org-eval-in-calendar '(calendar-forward-year 1))))
14769 (org-defkey minibuffer-local-map [(shift up)]
14770 (lambda () (interactive)
14771 (org-eval-in-calendar '(calendar-backward-week 1))))
14772 (org-defkey minibuffer-local-map [(shift down)]
14773 (lambda () (interactive)
14774 (org-eval-in-calendar '(calendar-forward-week 1))))
14775 (org-defkey minibuffer-local-map [(shift left)]
14776 (lambda () (interactive)
14777 (org-eval-in-calendar '(calendar-backward-day 1))))
14778 (org-defkey minibuffer-local-map [(shift right)]
14779 (lambda () (interactive)
14780 (org-eval-in-calendar '(calendar-forward-day 1))))
14781 (org-defkey minibuffer-local-map ">"
14782 (lambda () (interactive)
14783 (org-eval-in-calendar '(scroll-calendar-left 1))))
14784 (org-defkey minibuffer-local-map "<"
14785 (lambda () (interactive)
14786 (org-eval-in-calendar '(scroll-calendar-right 1))))
14787 (org-defkey minibuffer-local-map "\C-v"
14788 (lambda () (interactive)
14789 (org-eval-in-calendar
14790 '(calendar-scroll-left-three-months 1))))
14791 (org-defkey minibuffer-local-map "\M-v"
14792 (lambda () (interactive)
14793 (org-eval-in-calendar
14794 '(calendar-scroll-right-three-months 1))))
14795 (run-hooks 'org-read-date-minibuffer-setup-hook)
14796 (unwind-protect
14797 (progn
14798 (use-local-map map)
14799 (add-hook 'post-command-hook 'org-read-date-display)
14800 (setq org-ans0 (read-string prompt default-input
14801 'org-read-date-history nil))
14802 ;; org-ans0: from prompt
14803 ;; org-ans1: from mouse click
14804 ;; org-ans2: from calendar motion
14805 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
14806 (remove-hook 'post-command-hook 'org-read-date-display)
14807 (use-local-map old-map)
14808 (when org-read-date-overlay
14809 (delete-overlay org-read-date-overlay)
14810 (setq org-read-date-overlay nil)))))
14811 (bury-buffer "*Calendar*")))))
14813 (t ; Naked prompt only
14814 (unwind-protect
14815 (setq ans (read-string prompt default-input
14816 'org-read-date-history timestr))
14817 (when org-read-date-overlay
14818 (delete-overlay org-read-date-overlay)
14819 (setq org-read-date-overlay nil)))))
14821 (setq final (org-read-date-analyze ans def defdecode))
14823 (when org-read-date-analyze-forced-year
14824 (message "Year was forced into %s"
14825 (if org-read-date-force-compatible-dates
14826 "compatible range (1970-2037)"
14827 "range representable on this machine"))
14828 (ding))
14830 ;; One round trip to get rid of 34th of August and stuff like that....
14831 (setq final (decode-time (apply 'encode-time final)))
14833 (setq org-read-date-final-answer ans)
14835 (if to-time
14836 (apply 'encode-time final)
14837 (if (and (boundp 'org-time-was-given) org-time-was-given)
14838 (format "%04d-%02d-%02d %02d:%02d"
14839 (nth 5 final) (nth 4 final) (nth 3 final)
14840 (nth 2 final) (nth 1 final))
14841 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
14843 (defvar def)
14844 (defvar defdecode)
14845 (defvar with-time)
14846 (defun org-read-date-display ()
14847 "Display the current date prompt interpretation in the minibuffer."
14848 (when org-read-date-display-live
14849 (when org-read-date-overlay
14850 (delete-overlay org-read-date-overlay))
14851 (let ((p (point)))
14852 (end-of-line 1)
14853 (while (not (equal (buffer-substring
14854 (max (point-min) (- (point) 4)) (point))
14855 " "))
14856 (insert " "))
14857 (goto-char p))
14858 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
14859 " " (or org-ans1 org-ans2)))
14860 (org-end-time-was-given nil)
14861 (f (org-read-date-analyze ans def defdecode))
14862 (fmts (if org-dcst
14863 org-time-stamp-custom-formats
14864 org-time-stamp-formats))
14865 (fmt (if (or with-time
14866 (and (boundp 'org-time-was-given) org-time-was-given))
14867 (cdr fmts)
14868 (car fmts)))
14869 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
14870 (when (and org-end-time-was-given
14871 (string-match org-plain-time-of-day-regexp txt))
14872 (setq txt (concat (substring txt 0 (match-end 0)) "-"
14873 org-end-time-was-given
14874 (substring txt (match-end 0)))))
14875 (when org-read-date-analyze-futurep
14876 (setq txt (concat txt " (=>F)")))
14877 (setq org-read-date-overlay
14878 (make-overlay (1- (point-at-eol)) (point-at-eol)))
14879 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
14881 (defun org-read-date-analyze (ans def defdecode)
14882 "Analyze the combined answer of the date prompt."
14883 ;; FIXME: cleanup and comment
14884 (let ((nowdecode (decode-time (current-time)))
14885 delta deltan deltaw deltadef year month day
14886 hour minute second wday pm h2 m2 tl wday1
14887 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
14888 (setq org-read-date-analyze-futurep nil
14889 org-read-date-analyze-forced-year nil)
14890 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
14891 (setq ans "+0"))
14893 (when (setq delta (org-read-date-get-relative ans (current-time) def))
14894 (setq ans (replace-match "" t t ans)
14895 deltan (car delta)
14896 deltaw (nth 1 delta)
14897 deltadef (nth 2 delta)))
14899 ;; Check if there is an iso week date in there
14900 ;; If yes, store the info and postpone interpreting it until the rest
14901 ;; of the parsing is done
14902 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
14903 (setq iso-year (if (match-end 1)
14904 (org-small-year-to-year
14905 (string-to-number (match-string 1 ans))))
14906 iso-weekday (if (match-end 3)
14907 (string-to-number (match-string 3 ans)))
14908 iso-week (string-to-number (match-string 2 ans)))
14909 (setq ans (replace-match "" t t ans)))
14911 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
14912 (when (string-match
14913 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
14914 (setq year (if (match-end 2)
14915 (string-to-number (match-string 2 ans))
14916 (progn (setq kill-year t)
14917 (string-to-number (format-time-string "%Y"))))
14918 month (string-to-number (match-string 3 ans))
14919 day (string-to-number (match-string 4 ans)))
14920 (if (< year 100) (setq year (+ 2000 year)))
14921 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
14922 t nil ans)))
14924 ;; Help matching dottet european dates
14925 (when (string-match
14926 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\. ?\\([1-9][0-9][0-9][0-9]\\)?" ans)
14927 (setq year (if (match-end 3)
14928 (string-to-number (match-string 3 ans))
14929 (progn (setq kill-year t)
14930 (string-to-number (format-time-string "%Y"))))
14931 day (string-to-number (match-string 1 ans))
14932 month (string-to-number (match-string 2 ans))
14933 ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
14934 t nil ans)))
14936 ;; Help matching american dates, like 5/30 or 5/30/7
14937 (when (string-match
14938 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
14939 (setq year (if (match-end 4)
14940 (string-to-number (match-string 4 ans))
14941 (progn (setq kill-year t)
14942 (string-to-number (format-time-string "%Y"))))
14943 month (string-to-number (match-string 1 ans))
14944 day (string-to-number (match-string 2 ans)))
14945 (if (< year 100) (setq year (+ 2000 year)))
14946 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
14947 t nil ans)))
14948 ;; Help matching am/pm times, because `parse-time-string' does not do that.
14949 ;; If there is a time with am/pm, and *no* time without it, we convert
14950 ;; so that matching will be successful.
14951 (loop for i from 1 to 2 do ; twice, for end time as well
14952 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
14953 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
14954 (setq hour (string-to-number (match-string 1 ans))
14955 minute (if (match-end 3)
14956 (string-to-number (match-string 3 ans))
14958 pm (equal ?p
14959 (string-to-char (downcase (match-string 4 ans)))))
14960 (if (and (= hour 12) (not pm))
14961 (setq hour 0)
14962 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
14963 (setq ans (replace-match (format "%02d:%02d" hour minute)
14964 t t ans))))
14966 ;; Check if a time range is given as a duration
14967 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
14968 (setq hour (string-to-number (match-string 1 ans))
14969 h2 (+ hour (string-to-number (match-string 3 ans)))
14970 minute (string-to-number (match-string 2 ans))
14971 m2 (+ minute (if (match-end 5) (string-to-number
14972 (match-string 5 ans))0)))
14973 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
14974 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
14975 t t ans)))
14977 ;; Check if there is a time range
14978 (when (boundp 'org-end-time-was-given)
14979 (setq org-time-was-given nil)
14980 (when (and (string-match org-plain-time-of-day-regexp ans)
14981 (match-end 8))
14982 (setq org-end-time-was-given (match-string 8 ans))
14983 (setq ans (concat (substring ans 0 (match-beginning 7))
14984 (substring ans (match-end 7))))))
14986 (setq tl (parse-time-string ans)
14987 day (or (nth 3 tl) (nth 3 defdecode))
14988 month (or (nth 4 tl)
14989 (if (and org-read-date-prefer-future
14990 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
14991 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
14992 (nth 4 defdecode)))
14993 year (or (and (not kill-year) (nth 5 tl))
14994 (if (and org-read-date-prefer-future
14995 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
14996 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
14997 (nth 5 defdecode)))
14998 hour (or (nth 2 tl) (nth 2 defdecode))
14999 minute (or (nth 1 tl) (nth 1 defdecode))
15000 second (or (nth 0 tl) 0)
15001 wday (nth 6 tl))
15003 (when (and (eq org-read-date-prefer-future 'time)
15004 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
15005 (equal day (nth 3 nowdecode))
15006 (equal month (nth 4 nowdecode))
15007 (equal year (nth 5 nowdecode))
15008 (nth 2 tl)
15009 (or (< (nth 2 tl) (nth 2 nowdecode))
15010 (and (= (nth 2 tl) (nth 2 nowdecode))
15011 (nth 1 tl)
15012 (< (nth 1 tl) (nth 1 nowdecode)))))
15013 (setq day (1+ day)
15014 futurep t))
15016 ;; Special date definitions below
15017 (cond
15018 (iso-week
15019 ;; There was an iso week
15020 (require 'cal-iso)
15021 (setq futurep nil)
15022 (setq year (or iso-year year)
15023 day (or iso-weekday wday 1)
15024 wday nil ; to make sure that the trigger below does not match
15025 iso-date (calendar-gregorian-from-absolute
15026 (calendar-absolute-from-iso
15027 (list iso-week day year))))
15028 ; FIXME: Should we also push ISO weeks into the future?
15029 ; (when (and org-read-date-prefer-future
15030 ; (not iso-year)
15031 ; (< (calendar-absolute-from-gregorian iso-date)
15032 ; (time-to-days (current-time))))
15033 ; (setq year (1+ year)
15034 ; iso-date (calendar-gregorian-from-absolute
15035 ; (calendar-absolute-from-iso
15036 ; (list iso-week day year)))))
15037 (setq month (car iso-date)
15038 year (nth 2 iso-date)
15039 day (nth 1 iso-date)))
15040 (deltan
15041 (setq futurep nil)
15042 (unless deltadef
15043 (let ((now (decode-time (current-time))))
15044 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
15045 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
15046 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
15047 ((equal deltaw "m") (setq month (+ month deltan)))
15048 ((equal deltaw "y") (setq year (+ year deltan)))))
15049 ((and wday (not (nth 3 tl)))
15050 (setq futurep nil)
15051 ;; Weekday was given, but no day, so pick that day in the week
15052 ;; on or after the derived date.
15053 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
15054 (unless (equal wday wday1)
15055 (setq day (+ day (% (- wday wday1 -7) 7))))))
15056 (if (and (boundp 'org-time-was-given)
15057 (nth 2 tl))
15058 (setq org-time-was-given t))
15059 (if (< year 100) (setq year (+ 2000 year)))
15060 ;; Check of the date is representable
15061 (if org-read-date-force-compatible-dates
15062 (progn
15063 (if (< year 1970)
15064 (setq year 1970 org-read-date-analyze-forced-year t))
15065 (if (> year 2037)
15066 (setq year 2037 org-read-date-analyze-forced-year t)))
15067 (condition-case nil
15068 (ignore (encode-time second minute hour day month year))
15069 (error
15070 (setq year (nth 5 defdecode))
15071 (setq org-read-date-analyze-forced-year t))))
15072 (setq org-read-date-analyze-futurep futurep)
15073 (list second minute hour day month year)))
15075 (defvar parse-time-weekdays)
15077 (defun org-read-date-get-relative (s today default)
15078 "Check string S for special relative date string.
15079 TODAY and DEFAULT are internal times, for today and for a default.
15080 Return shift list (N what def-flag)
15081 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
15082 N is the number of WHATs to shift.
15083 DEF-FLAG is t when a double ++ or -- indicates shift relative to
15084 the DEFAULT date rather than TODAY."
15085 (when (and
15086 (string-match
15087 (concat
15088 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
15089 "\\([0-9]+\\)?"
15090 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
15091 "\\([ \t]\\|$\\)") s)
15092 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
15093 (let* ((dir (if (> (match-end 1) (match-beginning 1))
15094 (string-to-char (substring (match-string 1 s) -1))
15095 ?+))
15096 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
15097 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
15098 (what (if (match-end 3) (match-string 3 s) "d"))
15099 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
15100 (date (if rel default today))
15101 (wday (nth 6 (decode-time date)))
15102 delta)
15103 (if wday1
15104 (progn
15105 (setq delta (mod (+ 7 (- wday1 wday)) 7))
15106 (if (= dir ?-) (setq delta (- delta 7)))
15107 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
15108 (list delta "d" rel))
15109 (list (* n (if (= dir ?-) -1 1)) what rel)))))
15111 (defun org-order-calendar-date-args (arg1 arg2 arg3)
15112 "Turn a user-specified date into the internal representation.
15113 The internal representation needed by the calendar is (month day year).
15114 This is a wrapper to handle the brain-dead convention in calendar that
15115 user function argument order change dependent on argument order."
15116 (if (boundp 'calendar-date-style)
15117 (cond
15118 ((eq calendar-date-style 'american)
15119 (list arg1 arg2 arg3))
15120 ((eq calendar-date-style 'european)
15121 (list arg2 arg1 arg3))
15122 ((eq calendar-date-style 'iso)
15123 (list arg2 arg3 arg1)))
15124 (with-no-warnings ;; european-calendar-style is obsolete as of version 23.1
15125 (if (org-bound-and-true-p european-calendar-style)
15126 (list arg2 arg1 arg3)
15127 (list arg1 arg2 arg3)))))
15129 (defun org-eval-in-calendar (form &optional keepdate)
15130 "Eval FORM in the calendar window and return to current window.
15131 Also, store the cursor date in variable org-ans2."
15132 (let ((sf (selected-frame))
15133 (sw (selected-window)))
15134 (select-window (get-buffer-window "*Calendar*" t))
15135 (eval form)
15136 (when (and (not keepdate) (calendar-cursor-to-date))
15137 (let* ((date (calendar-cursor-to-date))
15138 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15139 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
15140 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
15141 (select-window sw)
15142 (org-select-frame-set-input-focus sf)))
15144 (defun org-calendar-select ()
15145 "Return to `org-read-date' with the date currently selected.
15146 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15147 (interactive)
15148 (when (calendar-cursor-to-date)
15149 (let* ((date (calendar-cursor-to-date))
15150 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15151 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15152 (if (active-minibuffer-window) (exit-minibuffer))))
15154 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
15155 "Insert a date stamp for the date given by the internal TIME.
15156 WITH-HM means use the stamp format that includes the time of the day.
15157 INACTIVE means use square brackets instead of angular ones, so that the
15158 stamp will not contribute to the agenda.
15159 PRE and POST are optional strings to be inserted before and after the
15160 stamp.
15161 The command returns the inserted time stamp."
15162 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
15163 stamp)
15164 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
15165 (insert-before-markers (or pre ""))
15166 (when (listp extra)
15167 (setq extra (car extra))
15168 (if (and (stringp extra)
15169 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
15170 (setq extra (format "-%02d:%02d"
15171 (string-to-number (match-string 1 extra))
15172 (string-to-number (match-string 2 extra))))
15173 (setq extra nil)))
15174 (when extra
15175 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
15176 (insert-before-markers (setq stamp (format-time-string fmt time)))
15177 (insert-before-markers (or post ""))
15178 (setq org-last-inserted-timestamp stamp)))
15180 (defun org-toggle-time-stamp-overlays ()
15181 "Toggle the use of custom time stamp formats."
15182 (interactive)
15183 (setq org-display-custom-times (not org-display-custom-times))
15184 (unless org-display-custom-times
15185 (let ((p (point-min)) (bmp (buffer-modified-p)))
15186 (while (setq p (next-single-property-change p 'display))
15187 (if (and (get-text-property p 'display)
15188 (eq (get-text-property p 'face) 'org-date))
15189 (remove-text-properties
15190 p (setq p (next-single-property-change p 'display))
15191 '(display t))))
15192 (set-buffer-modified-p bmp)))
15193 (if (featurep 'xemacs)
15194 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
15195 (org-restart-font-lock)
15196 (setq org-table-may-need-update t)
15197 (if org-display-custom-times
15198 (message "Time stamps are overlayed with custom format")
15199 (message "Time stamp overlays removed")))
15201 (defun org-display-custom-time (beg end)
15202 "Overlay modified time stamp format over timestamp between BEG and END."
15203 (let* ((ts (buffer-substring beg end))
15204 t1 w1 with-hm tf time str w2 (off 0))
15205 (save-match-data
15206 (setq t1 (org-parse-time-string ts t))
15207 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)?\\'" ts)
15208 (setq off (- (match-end 0) (match-beginning 0)))))
15209 (setq end (- end off))
15210 (setq w1 (- end beg)
15211 with-hm (and (nth 1 t1) (nth 2 t1))
15212 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
15213 time (org-fix-decoded-time t1)
15214 str (org-add-props
15215 (format-time-string
15216 (substring tf 1 -1) (apply 'encode-time time))
15217 nil 'mouse-face 'highlight)
15218 w2 (length str))
15219 (if (not (= w2 w1))
15220 (add-text-properties (1+ beg) (+ 2 beg)
15221 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
15222 (if (featurep 'xemacs)
15223 (progn
15224 (put-text-property beg end 'invisible t)
15225 (put-text-property beg end 'end-glyph (make-glyph str)))
15226 (put-text-property beg end 'display str))))
15228 (defun org-translate-time (string)
15229 "Translate all timestamps in STRING to custom format.
15230 But do this only if the variable `org-display-custom-times' is set."
15231 (when org-display-custom-times
15232 (save-match-data
15233 (let* ((start 0)
15234 (re org-ts-regexp-both)
15235 t1 with-hm inactive tf time str beg end)
15236 (while (setq start (string-match re string start))
15237 (setq beg (match-beginning 0)
15238 end (match-end 0)
15239 t1 (save-match-data
15240 (org-parse-time-string (substring string beg end) t))
15241 with-hm (and (nth 1 t1) (nth 2 t1))
15242 inactive (equal (substring string beg (1+ beg)) "[")
15243 tf (funcall (if with-hm 'cdr 'car)
15244 org-time-stamp-custom-formats)
15245 time (org-fix-decoded-time t1)
15246 str (format-time-string
15247 (concat
15248 (if inactive "[" "<") (substring tf 1 -1)
15249 (if inactive "]" ">"))
15250 (apply 'encode-time time))
15251 string (replace-match str t t string)
15252 start (+ start (length str)))))))
15253 string)
15255 (defun org-fix-decoded-time (time)
15256 "Set 0 instead of nil for the first 6 elements of time.
15257 Don't touch the rest."
15258 (let ((n 0))
15259 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
15261 (defun org-days-to-time (timestamp-string)
15262 "Difference between TIMESTAMP-STRING and now in days."
15263 (- (time-to-days (org-time-string-to-time timestamp-string))
15264 (time-to-days (current-time))))
15266 (defun org-deadline-close (timestamp-string &optional ndays)
15267 "Is the time in TIMESTAMP-STRING close to the current date?"
15268 (setq ndays (or ndays (org-get-wdays timestamp-string)))
15269 (and (< (org-days-to-time timestamp-string) ndays)
15270 (not (org-entry-is-done-p))))
15272 (defun org-get-wdays (ts)
15273 "Get the deadline lead time appropriate for timestring TS."
15274 (cond
15275 ((<= org-deadline-warning-days 0)
15276 ;; 0 or negative, enforce this value no matter what
15277 (- org-deadline-warning-days))
15278 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\| \\)" ts)
15279 ;; lead time is specified.
15280 (floor (* (string-to-number (match-string 1 ts))
15281 (cdr (assoc (match-string 2 ts)
15282 '(("d" . 1) ("w" . 7)
15283 ("m" . 30.4) ("y" . 365.25)))))))
15284 ;; go for the default.
15285 (t org-deadline-warning-days)))
15287 (defun org-calendar-select-mouse (ev)
15288 "Return to `org-read-date' with the date currently selected.
15289 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15290 (interactive "e")
15291 (mouse-set-point ev)
15292 (when (calendar-cursor-to-date)
15293 (let* ((date (calendar-cursor-to-date))
15294 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15295 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15296 (if (active-minibuffer-window) (exit-minibuffer))))
15298 (defun org-check-deadlines (ndays)
15299 "Check if there are any deadlines due or past due.
15300 A deadline is considered due if it happens within `org-deadline-warning-days'
15301 days from today's date. If the deadline appears in an entry marked DONE,
15302 it is not shown. The prefix arg NDAYS can be used to test that many
15303 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
15304 (interactive "P")
15305 (let* ((org-warn-days
15306 (cond
15307 ((equal ndays '(4)) 100000)
15308 (ndays (prefix-numeric-value ndays))
15309 (t (abs org-deadline-warning-days))))
15310 (case-fold-search nil)
15311 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
15312 (callback
15313 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
15315 (message "%d deadlines past-due or due within %d days"
15316 (org-occur regexp nil callback)
15317 org-warn-days)))
15319 (defun org-check-before-date (date)
15320 "Check if there are deadlines or scheduled entries before DATE."
15321 (interactive (list (org-read-date)))
15322 (let ((case-fold-search nil)
15323 (regexp (concat "\\<\\(" org-deadline-string
15324 "\\|" org-scheduled-string
15325 "\\) *<\\([^>]+\\)>"))
15326 (callback
15327 (lambda () (time-less-p
15328 (org-time-string-to-time (match-string 2))
15329 (org-time-string-to-time date)))))
15330 (message "%d entries before %s"
15331 (org-occur regexp nil callback) date)))
15333 (defun org-check-after-date (date)
15334 "Check if there are deadlines or scheduled entries after DATE."
15335 (interactive (list (org-read-date)))
15336 (let ((case-fold-search nil)
15337 (regexp (concat "\\<\\(" org-deadline-string
15338 "\\|" org-scheduled-string
15339 "\\) *<\\([^>]+\\)>"))
15340 (callback
15341 (lambda () (not
15342 (time-less-p
15343 (org-time-string-to-time (match-string 2))
15344 (org-time-string-to-time date))))))
15345 (message "%d entries after %s"
15346 (org-occur regexp nil callback) date)))
15348 (defun org-evaluate-time-range (&optional to-buffer)
15349 "Evaluate a time range by computing the difference between start and end.
15350 Normally the result is just printed in the echo area, but with prefix arg
15351 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
15352 If the time range is actually in a table, the result is inserted into the
15353 next column.
15354 For time difference computation, a year is assumed to be exactly 365
15355 days in order to avoid rounding problems."
15356 (interactive "P")
15358 (org-clock-update-time-maybe)
15359 (save-excursion
15360 (unless (org-at-date-range-p t)
15361 (goto-char (point-at-bol))
15362 (re-search-forward org-tr-regexp-both (point-at-eol) t))
15363 (if (not (org-at-date-range-p t))
15364 (error "Not at a time-stamp range, and none found in current line")))
15365 (let* ((ts1 (match-string 1))
15366 (ts2 (match-string 2))
15367 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
15368 (match-end (match-end 0))
15369 (time1 (org-time-string-to-time ts1))
15370 (time2 (org-time-string-to-time ts2))
15371 (t1 (org-float-time time1))
15372 (t2 (org-float-time time2))
15373 (diff (abs (- t2 t1)))
15374 (negative (< (- t2 t1) 0))
15375 ;; (ys (floor (* 365 24 60 60)))
15376 (ds (* 24 60 60))
15377 (hs (* 60 60))
15378 (fy "%dy %dd %02d:%02d")
15379 (fy1 "%dy %dd")
15380 (fd "%dd %02d:%02d")
15381 (fd1 "%dd")
15382 (fh "%02d:%02d")
15383 y d h m align)
15384 (if havetime
15385 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
15387 d (floor (/ diff ds)) diff (mod diff ds)
15388 h (floor (/ diff hs)) diff (mod diff hs)
15389 m (floor (/ diff 60)))
15390 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
15392 d (floor (+ (/ diff ds) 0.5))
15393 h 0 m 0))
15394 (if (not to-buffer)
15395 (message "%s" (org-make-tdiff-string y d h m))
15396 (if (org-at-table-p)
15397 (progn
15398 (goto-char match-end)
15399 (setq align t)
15400 (and (looking-at " *|") (goto-char (match-end 0))))
15401 (goto-char match-end))
15402 (if (looking-at
15403 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
15404 (replace-match ""))
15405 (if negative (insert " -"))
15406 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
15407 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
15408 (insert " " (format fh h m))))
15409 (if align (org-table-align))
15410 (message "Time difference inserted")))))
15412 (defun org-make-tdiff-string (y d h m)
15413 (let ((fmt "")
15414 (l nil))
15415 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
15416 l (push y l)))
15417 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
15418 l (push d l)))
15419 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
15420 l (push h l)))
15421 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
15422 l (push m l)))
15423 (apply 'format fmt (nreverse l))))
15425 (defun org-time-string-to-time (s)
15426 (apply 'encode-time (org-parse-time-string s)))
15427 (defun org-time-string-to-seconds (s)
15428 (org-float-time (org-time-string-to-time s)))
15430 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
15431 "Convert a time stamp to an absolute day number.
15432 If there is a specifier for a cyclic time stamp, get the closest date to
15433 DAYNR.
15434 PREFER and SHOW-ALL are passed through to `org-closest-date'.
15435 The variable date is bound by the calendar when this is called."
15436 (cond
15437 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
15438 (if (org-diary-sexp-entry (match-string 1 s) "" date)
15439 daynr
15440 (+ daynr 1000)))
15441 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
15442 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
15443 (time-to-days (current-time))) (match-string 0 s)
15444 prefer show-all))
15445 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
15447 (defun org-days-to-iso-week (days)
15448 "Return the iso week number."
15449 (require 'cal-iso)
15450 (car (calendar-iso-from-absolute days)))
15452 (defun org-small-year-to-year (year)
15453 "Convert 2-digit years into 4-digit years.
15454 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
15455 The year 2000 cannot be abbreviated. Any year larger than 99
15456 is returned unchanged."
15457 (if (< year 38)
15458 (setq year (+ 2000 year))
15459 (if (< year 100)
15460 (setq year (+ 1900 year))))
15461 year)
15463 (defun org-time-from-absolute (d)
15464 "Return the time corresponding to date D.
15465 D may be an absolute day number, or a calendar-type list (month day year)."
15466 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
15467 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
15469 (defun org-calendar-holiday ()
15470 "List of holidays, for Diary display in Org-mode."
15471 (require 'holidays)
15472 (let ((hl (funcall
15473 (if (fboundp 'calendar-check-holidays)
15474 'calendar-check-holidays 'check-calendar-holidays) date)))
15475 (if hl (mapconcat 'identity hl "; "))))
15477 (defun org-diary-sexp-entry (sexp entry date)
15478 "Process a SEXP diary ENTRY for DATE."
15479 (require 'diary-lib)
15480 (let ((result (if calendar-debug-sexp
15481 (let ((stack-trace-on-error t))
15482 (eval (car (read-from-string sexp))))
15483 (condition-case nil
15484 (eval (car (read-from-string sexp)))
15485 (error
15486 (beep)
15487 (message "Bad sexp at line %d in %s: %s"
15488 (org-current-line)
15489 (buffer-file-name) sexp)
15490 (sleep-for 2))))))
15491 (cond ((stringp result) (split-string result "; "))
15492 ((and (consp result)
15493 (not (consp (cdr result)))
15494 (stringp (cdr result))) (cdr result))
15495 ((and (consp result)
15496 (stringp (car result))) result)
15497 (result entry)
15498 (t nil))))
15500 (defun org-diary-to-ical-string (frombuf)
15501 "Get iCalendar entries from diary entries in buffer FROMBUF.
15502 This uses the icalendar.el library."
15503 (let* ((tmpdir (if (featurep 'xemacs)
15504 (temp-directory)
15505 temporary-file-directory))
15506 (tmpfile (make-temp-name
15507 (expand-file-name "orgics" tmpdir)))
15508 buf rtn b e)
15509 (with-current-buffer frombuf
15510 (icalendar-export-region (point-min) (point-max) tmpfile)
15511 (setq buf (find-buffer-visiting tmpfile))
15512 (set-buffer buf)
15513 (goto-char (point-min))
15514 (if (re-search-forward "^BEGIN:VEVENT" nil t)
15515 (setq b (match-beginning 0)))
15516 (goto-char (point-max))
15517 (if (re-search-backward "^END:VEVENT" nil t)
15518 (setq e (match-end 0)))
15519 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
15520 (kill-buffer buf)
15521 (delete-file tmpfile)
15522 rtn))
15524 (defun org-closest-date (start current change prefer show-all)
15525 "Find the date closest to CURRENT that is consistent with START and CHANGE.
15526 When PREFER is `past', return a date that is either CURRENT or past.
15527 When PREFER is `future', return a date that is either CURRENT or future.
15528 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
15529 ;; Make the proper lists from the dates
15530 (catch 'exit
15531 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
15532 dn dw sday cday n1 n2 n0
15533 d m y y1 y2 date1 date2 nmonths nm ny m2)
15535 (setq start (org-date-to-gregorian start)
15536 current (org-date-to-gregorian
15537 (if show-all
15538 current
15539 (time-to-days (current-time))))
15540 sday (calendar-absolute-from-gregorian start)
15541 cday (calendar-absolute-from-gregorian current))
15543 (if (<= cday sday) (throw 'exit sday))
15545 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
15546 (setq dn (string-to-number (match-string 1 change))
15547 dw (cdr (assoc (match-string 2 change) a1)))
15548 (error "Invalid change specifier: %s" change))
15549 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
15550 (cond
15551 ((eq dw 'day)
15552 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
15553 n2 (+ n1 dn)))
15554 ((eq dw 'year)
15555 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
15556 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
15557 (setq date1 (list m d y1)
15558 n1 (calendar-absolute-from-gregorian date1)
15559 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
15560 n2 (calendar-absolute-from-gregorian date2)))
15561 ((eq dw 'month)
15562 ;; approx number of month between the two dates
15563 (setq nmonths (floor (/ (- cday sday) 30.436875)))
15564 ;; How often does dn fit in there?
15565 (setq d (nth 1 start) m (car start) y (nth 2 start)
15566 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
15567 m (+ m nm)
15568 ny (floor (/ m 12))
15569 y (+ y ny)
15570 m (- m (* ny 12)))
15571 (while (> m 12) (setq m (- m 12) y (1+ y)))
15572 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
15573 (setq m2 (+ m dn) y2 y)
15574 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
15575 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
15576 (while (<= n2 cday)
15577 (setq n1 n2 m m2 y y2)
15578 (setq m2 (+ m dn) y2 y)
15579 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
15580 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
15581 ;; Make sure n1 is the earlier date
15582 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
15583 (if show-all
15584 (cond
15585 ((eq prefer 'past) (if (= cday n2) n2 n1))
15586 ((eq prefer 'future) (if (= cday n1) n1 n2))
15587 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
15588 (cond
15589 ((eq prefer 'past) (if (= cday n2) n2 n1))
15590 ((eq prefer 'future) (if (= cday n1) n1 n2))
15591 (t (if (= cday n1) n1 n2)))))))
15593 (defun org-date-to-gregorian (date)
15594 "Turn any specification of DATE into a Gregorian date for the calendar."
15595 (cond ((integerp date) (calendar-gregorian-from-absolute date))
15596 ((and (listp date) (= (length date) 3)) date)
15597 ((stringp date)
15598 (setq date (org-parse-time-string date))
15599 (list (nth 4 date) (nth 3 date) (nth 5 date)))
15600 ((listp date)
15601 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
15603 (defun org-parse-time-string (s &optional nodefault)
15604 "Parse the standard Org-mode time string.
15605 This should be a lot faster than the normal `parse-time-string'.
15606 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
15607 hour and minute fields will be nil if not given."
15608 (if (string-match org-ts-regexp0 s)
15609 (list 0
15610 (if (or (match-beginning 8) (not nodefault))
15611 (string-to-number (or (match-string 8 s) "0")))
15612 (if (or (match-beginning 7) (not nodefault))
15613 (string-to-number (or (match-string 7 s) "0")))
15614 (string-to-number (match-string 4 s))
15615 (string-to-number (match-string 3 s))
15616 (string-to-number (match-string 2 s))
15617 nil nil nil)
15618 (error "Not a standard Org-mode time string: %s" s)))
15620 (defun org-timestamp-up (&optional arg)
15621 "Increase the date item at the cursor by one.
15622 If the cursor is on the year, change the year. If it is on the month,
15623 the day or the time, change that.
15624 With prefix ARG, change by that many units."
15625 (interactive "p")
15626 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
15628 (defun org-timestamp-down (&optional arg)
15629 "Decrease the date item at the cursor by one.
15630 If the cursor is on the year, change the year. If it is on the month,
15631 the day or the time, change that.
15632 With prefix ARG, change by that many units."
15633 (interactive "p")
15634 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
15636 (defun org-timestamp-up-day (&optional arg)
15637 "Increase the date in the time stamp by one day.
15638 With prefix ARG, change that many days."
15639 (interactive "p")
15640 (if (and (not (org-at-timestamp-p t))
15641 (org-on-heading-p))
15642 (org-todo 'up)
15643 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
15645 (defun org-timestamp-down-day (&optional arg)
15646 "Decrease the date in the time stamp by one day.
15647 With prefix ARG, change that many days."
15648 (interactive "p")
15649 (if (and (not (org-at-timestamp-p t))
15650 (org-on-heading-p))
15651 (org-todo 'down)
15652 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
15654 (defun org-at-timestamp-p (&optional inactive-ok)
15655 "Determine if the cursor is in or at a timestamp."
15656 (interactive)
15657 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
15658 (pos (point))
15659 (ans (or (looking-at tsr)
15660 (save-excursion
15661 (skip-chars-backward "^[<\n\r\t")
15662 (if (> (point) (point-min)) (backward-char 1))
15663 (and (looking-at tsr)
15664 (> (- (match-end 0) pos) -1))))))
15665 (and ans
15666 (boundp 'org-ts-what)
15667 (setq org-ts-what
15668 (cond
15669 ((= pos (match-beginning 0)) 'bracket)
15670 ;; Point is considered to be "on the bracket" whether
15671 ;; it's really on it or right after it.
15672 ((or (= pos (1- (match-end 0)))
15673 (= pos (match-end 0))) 'bracket)
15674 ((org-pos-in-match-range pos 2) 'year)
15675 ((org-pos-in-match-range pos 3) 'month)
15676 ((org-pos-in-match-range pos 7) 'hour)
15677 ((org-pos-in-match-range pos 8) 'minute)
15678 ((or (org-pos-in-match-range pos 4)
15679 (org-pos-in-match-range pos 5)) 'day)
15680 ((and (> pos (or (match-end 8) (match-end 5)))
15681 (< pos (match-end 0)))
15682 (- pos (or (match-end 8) (match-end 5))))
15683 (t 'day))))
15684 ans))
15686 (defun org-toggle-timestamp-type ()
15687 "Toggle the type (<active> or [inactive]) of a time stamp."
15688 (interactive)
15689 (when (org-at-timestamp-p t)
15690 (let ((beg (match-beginning 0)) (end (match-end 0))
15691 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
15692 (save-excursion
15693 (goto-char beg)
15694 (while (re-search-forward "[][<>]" end t)
15695 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
15696 t t)))
15697 (message "Timestamp is now %sactive"
15698 (if (equal (char-after beg) ?<) "" "in")))))
15700 (defun org-timestamp-change (n &optional what updown)
15701 "Change the date in the time stamp at point.
15702 The date will be changed by N times WHAT. WHAT can be `day', `month',
15703 `year', `minute', `second'. If WHAT is not given, the cursor position
15704 in the timestamp determines what will be changed."
15705 (let ((origin (point)) origin-cat
15706 with-hm inactive
15707 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
15708 org-ts-what
15709 extra rem
15710 ts time time0)
15711 (if (not (org-at-timestamp-p t))
15712 (error "Not at a timestamp"))
15713 (if (and (not what) (eq org-ts-what 'bracket))
15714 (org-toggle-timestamp-type)
15715 ;; Point isn't on brackets. Remember the part of the time-stamp
15716 ;; the point was in. Indeed, size of time-stamps may change,
15717 ;; but point must be kept in the same category nonetheless.
15718 (setq origin-cat org-ts-what)
15719 (if (and (not what) (not (eq org-ts-what 'day))
15720 org-display-custom-times
15721 (get-text-property (point) 'display)
15722 (not (get-text-property (1- (point)) 'display)))
15723 (setq org-ts-what 'day))
15724 (setq org-ts-what (or what org-ts-what)
15725 inactive (= (char-after (match-beginning 0)) ?\[)
15726 ts (match-string 0))
15727 (replace-match "")
15728 (if (string-match
15729 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)*\\)[]>]"
15731 (setq extra (match-string 1 ts)))
15732 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
15733 (setq with-hm t))
15734 (setq time0 (org-parse-time-string ts))
15735 (when (and updown
15736 (eq org-ts-what 'minute)
15737 (not current-prefix-arg))
15738 ;; This looks like s-up and s-down. Change by one rounding step.
15739 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
15740 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
15741 (setcar (cdr time0) (+ (nth 1 time0)
15742 (if (> n 0) (- rem) (- dm rem))))))
15743 (setq time
15744 (encode-time (or (car time0) 0)
15745 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
15746 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
15747 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
15748 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
15749 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
15750 (nthcdr 6 time0)))
15751 (when (and (member org-ts-what '(hour minute))
15752 extra
15753 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
15754 (setq extra (org-modify-ts-extra
15755 extra
15756 (if (eq org-ts-what 'hour) 2 5)
15757 n dm)))
15758 (when (integerp org-ts-what)
15759 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
15760 (if (eq what 'calendar)
15761 (let ((cal-date (org-get-date-from-calendar)))
15762 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
15763 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
15764 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
15765 (setcar time0 (or (car time0) 0))
15766 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
15767 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
15768 (setq time (apply 'encode-time time0))))
15769 ;; Insert the new time-stamp, and ensure point stays in the same
15770 ;; category as before (i.e. not after the last position in that
15771 ;; category).
15772 (let ((pos (point)))
15773 ;; Stay before inserted string. `save-excursion' is of no use.
15774 (setq org-last-changed-timestamp
15775 (org-insert-time-stamp time with-hm inactive nil nil extra))
15776 (goto-char pos))
15777 (save-match-data
15778 (looking-at org-ts-regexp3)
15779 (goto-char (cond
15780 ;; `day' category ends before `hour' if any, or at
15781 ;; the end of the day name.
15782 ((eq origin-cat 'day)
15783 (min (or (match-beginning 7) (1- (match-end 5))) origin))
15784 ((eq origin-cat 'hour) (min (match-end 7) origin))
15785 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
15786 ((integerp origin-cat) (min (1- (match-end 0)) origin))
15787 ;; `year' and `month' have both fixed size: point
15788 ;; couldn't have moved into another part.
15789 (t origin))))
15790 ;; Update clock if on a CLOCK line.
15791 (org-clock-update-time-maybe)
15792 ;; Try to recenter the calendar window, if any.
15793 (if (and org-calendar-follow-timestamp-change
15794 (get-buffer-window "*Calendar*" t)
15795 (memq org-ts-what '(day month year)))
15796 (org-recenter-calendar (time-to-days time))))))
15798 (defun org-modify-ts-extra (s pos n dm)
15799 "Change the different parts of the lead-time and repeat fields in timestamp."
15800 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
15801 ng h m new rem)
15802 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
15803 (cond
15804 ((or (org-pos-in-match-range pos 2)
15805 (org-pos-in-match-range pos 3))
15806 (setq m (string-to-number (match-string 3 s))
15807 h (string-to-number (match-string 2 s)))
15808 (if (org-pos-in-match-range pos 2)
15809 (setq h (+ h n))
15810 (setq n (* dm (org-no-warnings (signum n))))
15811 (when (not (= 0 (setq rem (% m dm))))
15812 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
15813 (setq m (+ m n)))
15814 (if (< m 0) (setq m (+ m 60) h (1- h)))
15815 (if (> m 59) (setq m (- m 60) h (1+ h)))
15816 (setq h (min 24 (max 0 h)))
15817 (setq ng 1 new (format "-%02d:%02d" h m)))
15818 ((org-pos-in-match-range pos 6)
15819 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
15820 ((org-pos-in-match-range pos 5)
15821 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
15823 ((org-pos-in-match-range pos 9)
15824 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
15825 ((org-pos-in-match-range pos 8)
15826 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
15828 (when ng
15829 (setq s (concat
15830 (substring s 0 (match-beginning ng))
15832 (substring s (match-end ng))))))
15835 (defun org-recenter-calendar (date)
15836 "If the calendar is visible, recenter it to DATE."
15837 (let* ((win (selected-window))
15838 (cwin (get-buffer-window "*Calendar*" t))
15839 (calendar-move-hook nil))
15840 (when cwin
15841 (select-window cwin)
15842 (calendar-goto-date (if (listp date) date
15843 (calendar-gregorian-from-absolute date)))
15844 (select-window win))))
15846 (defun org-goto-calendar (&optional arg)
15847 "Go to the Emacs calendar at the current date.
15848 If there is a time stamp in the current line, go to that date.
15849 A prefix ARG can be used to force the current date."
15850 (interactive "P")
15851 (let ((tsr org-ts-regexp) diff
15852 (calendar-move-hook nil)
15853 (calendar-view-holidays-initially-flag nil)
15854 (calendar-view-diary-initially-flag nil))
15855 (if (or (org-at-timestamp-p)
15856 (save-excursion
15857 (beginning-of-line 1)
15858 (looking-at (concat ".*" tsr))))
15859 (let ((d1 (time-to-days (current-time)))
15860 (d2 (time-to-days
15861 (org-time-string-to-time (match-string 1)))))
15862 (setq diff (- d2 d1))))
15863 (calendar)
15864 (calendar-goto-today)
15865 (if (and diff (not arg)) (calendar-forward-day diff))))
15867 (defun org-get-date-from-calendar ()
15868 "Return a list (month day year) of date at point in calendar."
15869 (with-current-buffer "*Calendar*"
15870 (save-match-data
15871 (calendar-cursor-to-date))))
15873 (defun org-date-from-calendar ()
15874 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
15875 If there is already a time stamp at the cursor position, update it."
15876 (interactive)
15877 (if (org-at-timestamp-p t)
15878 (org-timestamp-change 0 'calendar)
15879 (let ((cal-date (org-get-date-from-calendar)))
15880 (org-insert-time-stamp
15881 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
15883 (defcustom org-effort-durations
15884 `(("h" . 60)
15885 ("d" . ,(* 60 8))
15886 ("w" . ,(* 60 8 5))
15887 ("m" . ,(* 60 8 5 4))
15888 ("y" . ,(* 60 8 5 40)))
15889 "Conversion factor to minutes for an effort modifier.
15891 Each entry has the form (MODIFIER . MINUTES).
15893 In an effort string, a number followed by MODIFIER is multiplied
15894 by the specified number of MINUTES to obtain an effort in
15895 minutes.
15897 For example, if the value of this variable is ((\"hours\" . 60)), then an
15898 effort string \"2hours\" is equivalent to 120 minutes."
15899 :group 'org-agenda
15900 :type '(alist :key-type (string :tag "Modifier")
15901 :value-type (number :tag "Minutes")))
15903 ;;;; Files
15905 (defun org-save-all-org-buffers ()
15906 "Save all Org-mode buffers without user confirmation."
15907 (interactive)
15908 (message "Saving all Org-mode buffers...")
15909 (save-some-buffers t 'org-mode-p)
15910 (when (featurep 'org-id) (org-id-locations-save))
15911 (message "Saving all Org-mode buffers... done"))
15913 (defun org-revert-all-org-buffers ()
15914 "Revert all Org-mode buffers.
15915 Prompt for confirmation when there are unsaved changes.
15916 Be sure you know what you are doing before letting this function
15917 overwrite your changes.
15919 This function is useful in a setup where one tracks org files
15920 with a version control system, to revert on one machine after pulling
15921 changes from another. I believe the procedure must be like this:
15923 1. M-x org-save-all-org-buffers
15924 2. Pull changes from the other machine, resolve conflicts
15925 3. M-x org-revert-all-org-buffers"
15926 (interactive)
15927 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
15928 (error "Abort"))
15929 (save-excursion
15930 (save-window-excursion
15931 (mapc
15932 (lambda (b)
15933 (when (and (with-current-buffer b (org-mode-p))
15934 (with-current-buffer b buffer-file-name))
15935 (org-pop-to-buffer-same-window b)
15936 (revert-buffer t 'no-confirm)))
15937 (buffer-list))
15938 (when (and (featurep 'org-id) org-id-track-globally)
15939 (org-id-locations-load)))))
15941 ;;;; Agenda files
15943 ;;;###autoload
15944 (defun org-switchb (&optional arg)
15945 "Switch between Org buffers.
15946 With a prefix argument, restrict available to files.
15947 With two prefix arguments, restrict available buffers to agenda files.
15949 Defaults to `iswitchb' for buffer name completion.
15950 Set `org-completion-use-ido' to make it use ido instead."
15951 (interactive "P")
15952 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
15953 ((equal arg '(16)) (org-buffer-list 'agenda))
15954 (t (org-buffer-list))))
15955 (org-completion-use-iswitchb org-completion-use-iswitchb)
15956 (org-completion-use-ido org-completion-use-ido))
15957 (unless (or org-completion-use-ido org-completion-use-iswitchb)
15958 (setq org-completion-use-iswitchb t))
15959 (org-pop-to-buffer-same-window
15960 (org-icompleting-read "Org buffer: "
15961 (mapcar 'list (mapcar 'buffer-name blist))
15962 nil t))))
15964 ;;; Define some older names previously used for this functionality
15965 ;;;###autoload
15966 (defalias 'org-ido-switchb 'org-switchb)
15967 ;;;###autoload
15968 (defalias 'org-iswitchb 'org-switchb)
15970 (defun org-buffer-list (&optional predicate exclude-tmp)
15971 "Return a list of Org buffers.
15972 PREDICATE can be `export', `files' or `agenda'.
15974 export restrict the list to Export buffers.
15975 files restrict the list to buffers visiting Org files.
15976 agenda restrict the list to buffers visiting agenda files.
15978 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
15979 (let* ((bfn nil)
15980 (agenda-files (and (eq predicate 'agenda)
15981 (mapcar 'file-truename (org-agenda-files t))))
15982 (filter
15983 (cond
15984 ((eq predicate 'files)
15985 (lambda (b) (with-current-buffer b (org-mode-p))))
15986 ((eq predicate 'export)
15987 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
15988 ((eq predicate 'agenda)
15989 (lambda (b)
15990 (with-current-buffer b
15991 (and (org-mode-p)
15992 (setq bfn (buffer-file-name b))
15993 (member (file-truename bfn) agenda-files)))))
15994 (t (lambda (b) (with-current-buffer b
15995 (or (org-mode-p)
15996 (string-match "\*Org .*Export"
15997 (buffer-name b)))))))))
15998 (delq nil
15999 (mapcar
16000 (lambda(b)
16001 (if (and (funcall filter b)
16002 (or (not exclude-tmp)
16003 (not (string-match "tmp" (buffer-name b)))))
16005 nil))
16006 (buffer-list)))))
16008 (defun org-agenda-files (&optional unrestricted archives)
16009 "Get the list of agenda files.
16010 Optional UNRESTRICTED means return the full list even if a restriction
16011 is currently in place.
16012 When ARCHIVES is t, include all archive files that are really being
16013 used by the agenda files. If ARCHIVE is `ifmode', do this only if
16014 `org-agenda-archives-mode' is t."
16015 (let ((files
16016 (cond
16017 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
16018 ((stringp org-agenda-files) (org-read-agenda-file-list))
16019 ((listp org-agenda-files) org-agenda-files)
16020 (t (error "Invalid value of `org-agenda-files'")))))
16021 (setq files (apply 'append
16022 (mapcar (lambda (f)
16023 (if (file-directory-p f)
16024 (directory-files
16025 f t org-agenda-file-regexp)
16026 (list f)))
16027 files)))
16028 (when org-agenda-skip-unavailable-files
16029 (setq files (delq nil
16030 (mapcar (function
16031 (lambda (file)
16032 (and (file-readable-p file) file)))
16033 files))))
16034 (when (or (eq archives t)
16035 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
16036 (setq files (org-add-archive-files files)))
16037 files))
16039 (defun org-agenda-file-p (&optional file)
16040 "Return non-nil, if FILE is an agenda file.
16041 If FILE is omitted, use the file associated with the current
16042 buffer."
16043 (member (or file (buffer-file-name))
16044 (org-agenda-files t)))
16046 (defun org-edit-agenda-file-list ()
16047 "Edit the list of agenda files.
16048 Depending on setup, this either uses customize to edit the variable
16049 `org-agenda-files', or it visits the file that is holding the list. In the
16050 latter case, the buffer is set up in a way that saving it automatically kills
16051 the buffer and restores the previous window configuration."
16052 (interactive)
16053 (if (stringp org-agenda-files)
16054 (let ((cw (current-window-configuration)))
16055 (find-file org-agenda-files)
16056 (org-set-local 'org-window-configuration cw)
16057 (org-add-hook 'after-save-hook
16058 (lambda ()
16059 (set-window-configuration
16060 (prog1 org-window-configuration
16061 (kill-buffer (current-buffer))))
16062 (org-install-agenda-files-menu)
16063 (message "New agenda file list installed"))
16064 nil 'local)
16065 (message "%s" (substitute-command-keys
16066 "Edit list and finish with \\[save-buffer]")))
16067 (customize-variable 'org-agenda-files)))
16069 (defun org-store-new-agenda-file-list (list)
16070 "Set new value for the agenda file list and save it correctly."
16071 (if (stringp org-agenda-files)
16072 (let ((fe (org-read-agenda-file-list t)) b u)
16073 (while (setq b (find-buffer-visiting org-agenda-files))
16074 (kill-buffer b))
16075 (with-temp-file org-agenda-files
16076 (insert
16077 (mapconcat
16078 (lambda (f) ;; Keep un-expanded entries.
16079 (if (setq u (assoc f fe))
16080 (cdr u)
16082 list "\n")
16083 "\n")))
16084 (let ((org-mode-hook nil) (org-inhibit-startup t)
16085 (org-insert-mode-line-in-empty-file nil))
16086 (setq org-agenda-files list)
16087 (customize-save-variable 'org-agenda-files org-agenda-files))))
16089 (defun org-read-agenda-file-list (&optional pair-with-expansion)
16090 "Read the list of agenda files from a file.
16091 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
16092 filenames, used by `org-store-new-agenda-file-list' to write back
16093 un-expanded file names."
16094 (when (file-directory-p org-agenda-files)
16095 (error "`org-agenda-files' cannot be a single directory"))
16096 (when (stringp org-agenda-files)
16097 (with-temp-buffer
16098 (insert-file-contents org-agenda-files)
16099 (mapcar
16100 (lambda (f)
16101 (let ((e (expand-file-name (substitute-in-file-name f)
16102 org-directory)))
16103 (if pair-with-expansion
16104 (cons e f)
16105 e)))
16106 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
16108 ;;;###autoload
16109 (defun org-cycle-agenda-files ()
16110 "Cycle through the files in `org-agenda-files'.
16111 If the current buffer visits an agenda file, find the next one in the list.
16112 If the current buffer does not, find the first agenda file."
16113 (interactive)
16114 (let* ((fs (org-agenda-files t))
16115 (files (append fs (list (car fs))))
16116 (tcf (if buffer-file-name (file-truename buffer-file-name)))
16117 file)
16118 (unless files (error "No agenda files"))
16119 (catch 'exit
16120 (while (setq file (pop files))
16121 (if (equal (file-truename file) tcf)
16122 (when (car files)
16123 (find-file (car files))
16124 (throw 'exit t))))
16125 (find-file (car fs)))
16126 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
16128 (defun org-agenda-file-to-front (&optional to-end)
16129 "Move/add the current file to the top of the agenda file list.
16130 If the file is not present in the list, it is added to the front. If it is
16131 present, it is moved there. With optional argument TO-END, add/move to the
16132 end of the list."
16133 (interactive "P")
16134 (let ((org-agenda-skip-unavailable-files nil)
16135 (file-alist (mapcar (lambda (x)
16136 (cons (file-truename x) x))
16137 (org-agenda-files t)))
16138 (ctf (file-truename buffer-file-name))
16139 x had)
16140 (setq x (assoc ctf file-alist) had x)
16142 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
16143 (if to-end
16144 (setq file-alist (append (delq x file-alist) (list x)))
16145 (setq file-alist (cons x (delq x file-alist))))
16146 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
16147 (org-install-agenda-files-menu)
16148 (message "File %s to %s of agenda file list"
16149 (if had "moved" "added") (if to-end "end" "front"))))
16151 (defun org-remove-file (&optional file)
16152 "Remove current file from the list of files in variable `org-agenda-files'.
16153 These are the files which are being checked for agenda entries.
16154 Optional argument FILE means use this file instead of the current."
16155 (interactive)
16156 (let* ((org-agenda-skip-unavailable-files nil)
16157 (file (or file buffer-file-name))
16158 (true-file (file-truename file))
16159 (afile (abbreviate-file-name file))
16160 (files (delq nil (mapcar
16161 (lambda (x)
16162 (if (equal true-file
16163 (file-truename x))
16164 nil x))
16165 (org-agenda-files t)))))
16166 (if (not (= (length files) (length (org-agenda-files t))))
16167 (progn
16168 (org-store-new-agenda-file-list files)
16169 (org-install-agenda-files-menu)
16170 (message "Removed file: %s" afile))
16171 (message "File was not in list: %s (not removed)" afile))))
16173 (defun org-file-menu-entry (file)
16174 (vector file (list 'find-file file) t))
16176 (defun org-check-agenda-file (file)
16177 "Make sure FILE exists. If not, ask user what to do."
16178 (when (not (file-exists-p file))
16179 (message "non-existent agenda file %s. [R]emove from list or [A]bort?"
16180 (abbreviate-file-name file))
16181 (let ((r (downcase (read-char-exclusive))))
16182 (cond
16183 ((equal r ?r)
16184 (org-remove-file file)
16185 (throw 'nextfile t))
16186 (t (error "Abort"))))))
16188 (defun org-get-agenda-file-buffer (file)
16189 "Get a buffer visiting FILE. If the buffer needs to be created, add
16190 it to the list of buffers which might be released later."
16191 (let ((buf (org-find-base-buffer-visiting file)))
16192 (if buf
16193 buf ; just return it
16194 ;; Make a new buffer and remember it
16195 (setq buf (find-file-noselect file))
16196 (if buf (push buf org-agenda-new-buffers))
16197 buf)))
16199 (defun org-release-buffers (blist)
16200 "Release all buffers in list, asking the user for confirmation when needed.
16201 When a buffer is unmodified, it is just killed. When modified, it is saved
16202 \(if the user agrees) and then killed."
16203 (let (buf file)
16204 (while (setq buf (pop blist))
16205 (setq file (buffer-file-name buf))
16206 (when (and (buffer-modified-p buf)
16207 file
16208 (y-or-n-p (format "Save file %s? " file)))
16209 (with-current-buffer buf (save-buffer)))
16210 (kill-buffer buf))))
16212 (defun org-prepare-agenda-buffers (files)
16213 "Create buffers for all agenda files, protect archived trees and comments."
16214 (interactive)
16215 (let ((pa '(:org-archived t))
16216 (pc '(:org-comment t))
16217 (pall '(:org-archived t :org-comment t))
16218 (inhibit-read-only t)
16219 (rea (concat ":" org-archive-tag ":"))
16220 bmp file re)
16221 (save-excursion
16222 (save-restriction
16223 (while (setq file (pop files))
16224 (catch 'nextfile
16225 (if (bufferp file)
16226 (set-buffer file)
16227 (org-check-agenda-file file)
16228 (set-buffer (org-get-agenda-file-buffer file)))
16229 (widen)
16230 (setq bmp (buffer-modified-p))
16231 (org-refresh-category-properties)
16232 (setq org-todo-keywords-for-agenda
16233 (append org-todo-keywords-for-agenda org-todo-keywords-1))
16234 (setq org-done-keywords-for-agenda
16235 (append org-done-keywords-for-agenda org-done-keywords))
16236 (setq org-todo-keyword-alist-for-agenda
16237 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
16238 (setq org-drawers-for-agenda
16239 (append org-drawers-for-agenda org-drawers))
16240 (setq org-tag-alist-for-agenda
16241 (append org-tag-alist-for-agenda org-tag-alist))
16243 (save-excursion
16244 (remove-text-properties (point-min) (point-max) pall)
16245 (when org-agenda-skip-archived-trees
16246 (goto-char (point-min))
16247 (while (re-search-forward rea nil t)
16248 (if (org-on-heading-p t)
16249 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
16250 (goto-char (point-min))
16251 (setq re (concat org-outline-regexp-bol "+" org-comment-string "\\>"))
16252 (while (re-search-forward re nil t)
16253 (add-text-properties
16254 (match-beginning 0) (org-end-of-subtree t) pc)))
16255 (set-buffer-modified-p bmp)))))
16256 (setq org-todo-keywords-for-agenda
16257 (org-uniquify org-todo-keywords-for-agenda))
16258 (setq org-todo-keyword-alist-for-agenda
16259 (org-uniquify org-todo-keyword-alist-for-agenda)
16260 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
16262 ;;;; Embedded LaTeX
16264 (defvar org-cdlatex-mode-map (make-sparse-keymap)
16265 "Keymap for the minor `org-cdlatex-mode'.")
16267 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
16268 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
16269 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
16270 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
16271 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
16273 (defvar org-cdlatex-texmathp-advice-is-done nil
16274 "Flag remembering if we have applied the advice to texmathp already.")
16276 (define-minor-mode org-cdlatex-mode
16277 "Toggle the minor `org-cdlatex-mode'.
16278 This mode supports entering LaTeX environment and math in LaTeX fragments
16279 in Org-mode.
16280 \\{org-cdlatex-mode-map}"
16281 nil " OCDL" nil
16282 (when org-cdlatex-mode (require 'cdlatex))
16283 (unless org-cdlatex-texmathp-advice-is-done
16284 (setq org-cdlatex-texmathp-advice-is-done t)
16285 (defadvice texmathp (around org-math-always-on activate)
16286 "Always return t in org-mode buffers.
16287 This is because we want to insert math symbols without dollars even outside
16288 the LaTeX math segments. If Orgmode thinks that point is actually inside
16289 an embedded LaTeX fragment, let texmathp do its job.
16290 \\[org-cdlatex-mode-map]"
16291 (interactive)
16292 (let (p)
16293 (cond
16294 ((not (org-mode-p)) ad-do-it)
16295 ((eq this-command 'cdlatex-math-symbol)
16296 (setq ad-return-value t
16297 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
16299 (let ((p (org-inside-LaTeX-fragment-p)))
16300 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
16301 (setq ad-return-value t
16302 texmathp-why '("Org-mode embedded math" . 0))
16303 (if p ad-do-it)))))))))
16305 (defun turn-on-org-cdlatex ()
16306 "Unconditionally turn on `org-cdlatex-mode'."
16307 (org-cdlatex-mode 1))
16309 (defun org-inside-LaTeX-fragment-p ()
16310 "Test if point is inside a LaTeX fragment.
16311 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
16312 sequence appearing also before point.
16313 Even though the matchers for math are configurable, this function assumes
16314 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
16315 delimiters are skipped when they have been removed by customization.
16316 The return value is nil, or a cons cell with the delimiter and the
16317 position of this delimiter.
16319 This function does a reasonably good job, but can locally be fooled by
16320 for example currency specifications. For example it will assume being in
16321 inline math after \"$22.34\". The LaTeX fragment formatter will only format
16322 fragments that are properly closed, but during editing, we have to live
16323 with the uncertainty caused by missing closing delimiters. This function
16324 looks only before point, not after."
16325 (catch 'exit
16326 (let ((pos (point))
16327 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
16328 (lim (progn
16329 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
16330 (point)))
16331 dd-on str (start 0) m re)
16332 (goto-char pos)
16333 (when dodollar
16334 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
16335 re (nth 1 (assoc "$" org-latex-regexps)))
16336 (while (string-match re str start)
16337 (cond
16338 ((= (match-end 0) (length str))
16339 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
16340 ((= (match-end 0) (- (length str) 5))
16341 (throw 'exit nil))
16342 (t (setq start (match-end 0))))))
16343 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
16344 (goto-char pos)
16345 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
16346 (and (match-beginning 2) (throw 'exit nil))
16347 ;; count $$
16348 (while (re-search-backward "\\$\\$" lim t)
16349 (setq dd-on (not dd-on)))
16350 (goto-char pos)
16351 (if dd-on (cons "$$" m))))))
16353 (defun org-inside-latex-macro-p ()
16354 "Is point inside a LaTeX macro or its arguments?"
16355 (save-match-data
16356 (org-in-regexp
16357 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
16359 (defun org-try-cdlatex-tab ()
16360 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
16361 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
16362 - inside a LaTeX fragment, or
16363 - after the first word in a line, where an abbreviation expansion could
16364 insert a LaTeX environment."
16365 (when org-cdlatex-mode
16366 (cond
16367 ((save-excursion
16368 (skip-chars-backward "a-zA-Z0-9*")
16369 (skip-chars-backward " \t")
16370 (bolp))
16371 (cdlatex-tab) t)
16372 ((org-inside-LaTeX-fragment-p)
16373 (cdlatex-tab) t)
16374 (t nil))))
16376 (defun org-cdlatex-underscore-caret (&optional arg)
16377 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
16378 Revert to the normal definition outside of these fragments."
16379 (interactive "P")
16380 (if (org-inside-LaTeX-fragment-p)
16381 (call-interactively 'cdlatex-sub-superscript)
16382 (let (org-cdlatex-mode)
16383 (call-interactively (key-binding (vector last-input-event))))))
16385 (defun org-cdlatex-math-modify (&optional arg)
16386 "Execute `cdlatex-math-modify' in LaTeX fragments.
16387 Revert to the normal definition outside of these fragments."
16388 (interactive "P")
16389 (if (org-inside-LaTeX-fragment-p)
16390 (call-interactively 'cdlatex-math-modify)
16391 (let (org-cdlatex-mode)
16392 (call-interactively (key-binding (vector last-input-event))))))
16394 (defvar org-latex-fragment-image-overlays nil
16395 "List of overlays carrying the images of latex fragments.")
16396 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
16398 (defun org-remove-latex-fragment-image-overlays ()
16399 "Remove all overlays with LaTeX fragment images in current buffer."
16400 (mapc 'delete-overlay org-latex-fragment-image-overlays)
16401 (setq org-latex-fragment-image-overlays nil))
16403 (defun org-preview-latex-fragment (&optional subtree)
16404 "Preview the LaTeX fragment at point, or all locally or globally.
16405 If the cursor is in a LaTeX fragment, create the image and overlay
16406 it over the source code. If there is no fragment at point, display
16407 all fragments in the current text, from one headline to the next. With
16408 prefix SUBTREE, display all fragments in the current subtree. With a
16409 double prefix arg \\[universal-argument] \\[universal-argument], or when \
16410 the cursor is before the first headline,
16411 display all fragments in the buffer.
16412 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
16413 (interactive "P")
16414 (org-remove-latex-fragment-image-overlays)
16415 (save-excursion
16416 (save-restriction
16417 (let (beg end at msg)
16418 (cond
16419 ((or (equal subtree '(16))
16420 (not (save-excursion
16421 (re-search-backward org-outline-regexp-bol nil t))))
16422 (setq beg (point-min) end (point-max)
16423 msg "Creating images for buffer...%s"))
16424 ((equal subtree '(4))
16425 (org-back-to-heading)
16426 (setq beg (point) end (org-end-of-subtree t)
16427 msg "Creating images for subtree...%s"))
16429 (if (setq at (org-inside-LaTeX-fragment-p))
16430 (goto-char (max (point-min) (- (cdr at) 2)))
16431 (org-back-to-heading))
16432 (setq beg (point) end (progn (outline-next-heading) (point))
16433 msg (if at "Creating image...%s"
16434 "Creating images for entry...%s"))))
16435 (message msg "")
16436 (narrow-to-region beg end)
16437 (goto-char beg)
16438 (org-format-latex
16439 (concat "ltxpng/" (file-name-sans-extension
16440 (file-name-nondirectory
16441 buffer-file-name)))
16442 default-directory 'overlays msg at 'forbuffer 'dvipng)
16443 (message msg "done. Use `C-c C-c' to remove images.")))))
16445 (defvar org-latex-regexps
16446 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
16447 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
16448 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
16449 ("$1" "\\([^$]\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
16450 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
16451 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
16452 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
16453 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
16454 "Regular expressions for matching embedded LaTeX.")
16456 (defvar org-export-have-math nil) ;; dynamic scoping
16457 (defun org-format-latex (prefix &optional dir overlays msg at
16458 forbuffer processing-type)
16459 "Replace LaTeX fragments with links to an image, and produce images.
16460 Some of the options can be changed using the variable
16461 `org-format-latex-options'."
16462 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
16463 (let* ((prefixnodir (file-name-nondirectory prefix))
16464 (absprefix (expand-file-name prefix dir))
16465 (todir (file-name-directory absprefix))
16466 (opt org-format-latex-options)
16467 (matchers (plist-get opt :matchers))
16468 (re-list org-latex-regexps)
16469 (org-format-latex-header-extra
16470 (plist-get (org-infile-export-plist) :latex-header-extra))
16471 (cnt 0) txt hash link beg end re e checkdir
16472 executables-checked string
16473 m n block linkfile movefile ov)
16474 ;; Check the different regular expressions
16475 (while (setq e (pop re-list))
16476 (setq m (car e) re (nth 1 e) n (nth 2 e)
16477 block (if (nth 3 e) "\n\n" ""))
16478 (when (member m matchers)
16479 (goto-char (point-min))
16480 (while (re-search-forward re nil t)
16481 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
16482 (not (get-text-property (match-beginning n)
16483 'org-protected))
16484 (or (not overlays)
16485 (not (eq (get-char-property (match-beginning n)
16486 'org-overlay-type)
16487 'org-latex-overlay))))
16488 (setq org-export-have-math t)
16489 (cond
16490 ((eq processing-type 'verbatim)
16491 ;; Leave the text verbatim, just protect it
16492 (add-text-properties (match-beginning n) (match-end n)
16493 '(org-protected t)))
16494 ((eq processing-type 'mathjax)
16495 ;; Prepare for MathJax processing
16496 (setq string (match-string n))
16497 (if (member m '("$" "$1"))
16498 (save-excursion
16499 (delete-region (match-beginning n) (match-end n))
16500 (goto-char (match-beginning n))
16501 (insert (org-add-props (concat "\\(" (substring string 1 -1)
16502 "\\)")
16503 '(org-protected t))))
16504 (add-text-properties (match-beginning n) (match-end n)
16505 '(org-protected t))))
16506 ((or (eq processing-type 'dvipng) t)
16507 ;; Process to an image
16508 (setq txt (match-string n)
16509 beg (match-beginning n) end (match-end n)
16510 cnt (1+ cnt))
16511 (let (print-length print-level) ; make sure full list is printed
16512 (setq hash (sha1 (prin1-to-string
16513 (list org-format-latex-header
16514 org-format-latex-header-extra
16515 org-export-latex-default-packages-alist
16516 org-export-latex-packages-alist
16517 org-format-latex-options
16518 forbuffer txt)))
16519 linkfile (format "%s_%s.png" prefix hash)
16520 movefile (format "%s_%s.png" absprefix hash)))
16521 (setq link (concat block "[[file:" linkfile "]]" block))
16522 (if msg (message msg cnt))
16523 (goto-char beg)
16524 (unless checkdir ; make sure the directory exists
16525 (setq checkdir t)
16526 (or (file-directory-p todir) (make-directory todir t)))
16528 (unless executables-checked
16529 (org-check-external-command
16530 "latex" "needed to convert LaTeX fragments to images")
16531 (org-check-external-command
16532 "dvipng" "needed to convert LaTeX fragments to images")
16533 (setq executables-checked t))
16535 (unless (file-exists-p movefile)
16536 (org-create-formula-image
16537 txt movefile opt forbuffer))
16538 (if overlays
16539 (progn
16540 (mapc (lambda (o)
16541 (if (eq (overlay-get o 'org-overlay-type)
16542 'org-latex-overlay)
16543 (delete-overlay o)))
16544 (overlays-in beg end))
16545 (setq ov (make-overlay beg end))
16546 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
16547 (if (featurep 'xemacs)
16548 (progn
16549 (overlay-put ov 'invisible t)
16550 (overlay-put
16551 ov 'end-glyph
16552 (make-glyph (vector 'png :file movefile))))
16553 (overlay-put
16554 ov 'display
16555 (list 'image :type 'png :file movefile :ascent 'center)))
16556 (push ov org-latex-fragment-image-overlays)
16557 (goto-char end))
16558 (delete-region beg end)
16559 (insert (org-add-props link
16560 (list 'org-latex-src
16561 (replace-regexp-in-string
16562 "\"" "" txt)))))))))))))
16564 ;; This function borrows from Ganesh Swami's latex2png.el
16565 (defun org-create-formula-image (string tofile options buffer)
16566 "This calls dvipng."
16567 (require 'org-latex)
16568 (let* ((tmpdir (if (featurep 'xemacs)
16569 (temp-directory)
16570 temporary-file-directory))
16571 (texfilebase (make-temp-name
16572 (expand-file-name "orgtex" tmpdir)))
16573 (texfile (concat texfilebase ".tex"))
16574 (dvifile (concat texfilebase ".dvi"))
16575 (pngfile (concat texfilebase ".png"))
16576 (fnh (if (featurep 'xemacs)
16577 (font-height (get-face-font 'default))
16578 (face-attribute 'default :height nil)))
16579 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
16580 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
16581 (fg (or (plist-get options (if buffer :foreground :html-foreground))
16582 "Black"))
16583 (bg (or (plist-get options (if buffer :background :html-background))
16584 "Transparent")))
16585 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
16586 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
16587 (with-temp-file texfile
16588 (insert (org-splice-latex-header
16589 org-format-latex-header
16590 org-export-latex-default-packages-alist
16591 org-export-latex-packages-alist t
16592 org-format-latex-header-extra))
16593 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")
16594 (require 'org-latex)
16595 (org-export-latex-fix-inputenc))
16596 (let ((dir default-directory))
16597 (condition-case nil
16598 (progn
16599 (cd tmpdir)
16600 (call-process "latex" nil nil nil texfile))
16601 (error nil))
16602 (cd dir))
16603 (if (not (file-exists-p dvifile))
16604 (progn (message "Failed to create dvi file from %s" texfile) nil)
16605 (condition-case nil
16606 (call-process "dvipng" nil nil nil
16607 "-fg" fg "-bg" bg
16608 "-D" dpi
16609 ;;"-x" scale "-y" scale
16610 "-T" "tight"
16611 "-o" pngfile
16612 dvifile)
16613 (error nil))
16614 (if (not (file-exists-p pngfile))
16615 (if org-format-latex-signal-error
16616 (error "Failed to create png file from %s" texfile)
16617 (message "Failed to create png file from %s" texfile)
16618 nil)
16619 ;; Use the requested file name and clean up
16620 (copy-file pngfile tofile 'replace)
16621 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
16622 (delete-file (concat texfilebase e)))
16623 pngfile))))
16625 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
16626 "Fill a LaTeX header template TPL.
16627 In the template, the following place holders will be recognized:
16629 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
16630 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
16631 [PACKAGES] \\usepackage statements for PKG
16632 [NO-PACKAGES] do not include PKG
16633 [EXTRA] the string EXTRA
16634 [NO-EXTRA] do not include EXTRA
16636 For backward compatibility, if both the positive and the negative place
16637 holder is missing, the positive one (without the \"NO-\") will be
16638 assumed to be present at the end of the template.
16639 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
16640 EXTRA is a string.
16641 SNIPPETS-P indicates if this is run to create snippet images for HTML."
16642 (let (rpl (end ""))
16643 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
16644 (setq rpl (if (or (match-end 1) (not def-pkg))
16645 "" (org-latex-packages-to-string def-pkg snippets-p t))
16646 tpl (replace-match rpl t t tpl))
16647 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
16649 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
16650 (setq rpl (if (or (match-end 1) (not pkg))
16651 "" (org-latex-packages-to-string pkg snippets-p t))
16652 tpl (replace-match rpl t t tpl))
16653 (if pkg (setq end
16654 (concat end "\n"
16655 (org-latex-packages-to-string pkg snippets-p)))))
16657 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
16658 (setq rpl (if (or (match-end 1) (not extra))
16659 "" (concat extra "\n"))
16660 tpl (replace-match rpl t t tpl))
16661 (if (and extra (string-match "\\S-" extra))
16662 (setq end (concat end "\n" extra))))
16664 (if (string-match "\\S-" end)
16665 (concat tpl "\n" end)
16666 tpl)))
16668 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
16669 "Turn an alist of packages into a string with the \\usepackage macros."
16670 (setq pkg (mapconcat (lambda(p)
16671 (cond
16672 ((stringp p) p)
16673 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
16674 (format "%% Package %s omitted" (cadr p)))
16675 ((equal "" (car p))
16676 (format "\\usepackage{%s}" (cadr p)))
16678 (format "\\usepackage[%s]{%s}"
16679 (car p) (cadr p)))))
16681 "\n"))
16682 (if newline (concat pkg "\n") pkg))
16684 (defun org-dvipng-color (attr)
16685 "Return an rgb color specification for dvipng."
16686 (apply 'format "rgb %s %s %s"
16687 (mapcar 'org-normalize-color
16688 (color-values (face-attribute 'default attr nil)))))
16690 (defun org-normalize-color (value)
16691 "Return string to be used as color value for an RGB component."
16692 (format "%g" (/ value 65535.0)))
16694 ;; Image display
16697 (defvar org-inline-image-overlays nil)
16698 (make-variable-buffer-local 'org-inline-image-overlays)
16700 (defun org-toggle-inline-images (&optional include-linked)
16701 "Toggle the display of inline images.
16702 INCLUDE-LINKED is passed to `org-display-inline-images'."
16703 (interactive "P")
16704 (if org-inline-image-overlays
16705 (progn
16706 (org-remove-inline-images)
16707 (message "Inline image display turned off"))
16708 (org-display-inline-images include-linked)
16709 (if org-inline-image-overlays
16710 (message "%d images displayed inline"
16711 (length org-inline-image-overlays))
16712 (message "No images to display inline"))))
16714 (defun org-display-inline-images (&optional include-linked refresh beg end)
16715 "Display inline images.
16716 Normally only links without a description part are inlined, because this
16717 is how it will work for export. When INCLUDE-LINKED is set, also links
16718 with a description part will be inlined. This can be nice for a quick
16719 look at those images, but it does not reflect what exported files will look
16720 like.
16721 When REFRESH is set, refresh existing images between BEG and END.
16722 This will create new image displays only if necessary.
16723 BEG and END default to the buffer boundaries."
16724 (interactive "P")
16725 (unless refresh
16726 (org-remove-inline-images)
16727 (if (fboundp 'clear-image-cache) (clear-image-cache)))
16728 (save-excursion
16729 (save-restriction
16730 (widen)
16731 (setq beg (or beg (point-min)) end (or end (point-max)))
16732 (goto-char (point-min))
16733 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
16734 (substring (org-image-file-name-regexp) 0 -2)
16735 "\\)\\]" (if include-linked "" "\\]")))
16736 old file ov img)
16737 (while (re-search-forward re end t)
16738 (setq old (get-char-property-and-overlay (match-beginning 1)
16739 'org-image-overlay))
16740 (setq file (expand-file-name
16741 (concat (or (match-string 3) "") (match-string 4))))
16742 (when (file-exists-p file)
16743 (if (and (car-safe old) refresh)
16744 (image-refresh (overlay-get (cdr old) 'display))
16745 (setq img (save-match-data (create-image file)))
16746 (when img
16747 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
16748 (overlay-put ov 'display img)
16749 (overlay-put ov 'face 'default)
16750 (overlay-put ov 'org-image-overlay t)
16751 (overlay-put ov 'modification-hooks
16752 (list 'org-display-inline-modification-hook))
16753 (push ov org-inline-image-overlays)))))))))
16755 (defun org-display-inline-modification-hook (ov after beg end &optional len)
16756 "Remove inline-display overlay if a corresponding region is modified."
16757 (let ((inhibit-modification-hooks t))
16758 (when (and ov after)
16759 (delete ov org-inline-image-overlays)
16760 (delete-overlay ov))))
16762 (defun org-remove-inline-images ()
16763 "Remove inline display of images."
16764 (interactive)
16765 (mapc 'delete-overlay org-inline-image-overlays)
16766 (setq org-inline-image-overlays nil))
16768 ;;;; Key bindings
16770 ;; Make `C-c C-x' a prefix key
16771 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
16773 ;; TAB key with modifiers
16774 (org-defkey org-mode-map "\C-i" 'org-cycle)
16775 (org-defkey org-mode-map [(tab)] 'org-cycle)
16776 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
16777 (org-defkey org-mode-map [(meta tab)] 'pcomplete)
16778 (org-defkey org-mode-map "\M-\t" 'pcomplete)
16779 (org-defkey org-mode-map "\M-\C-i" 'pcomplete)
16780 ;; The following line is necessary under Suse GNU/Linux
16781 (unless (featurep 'xemacs)
16782 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
16783 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
16784 (define-key org-mode-map [backtab] 'org-shifttab)
16786 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
16787 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
16788 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
16790 ;; Cursor keys with modifiers
16791 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
16792 (org-defkey org-mode-map [(meta right)] 'org-metaright)
16793 (org-defkey org-mode-map [(meta up)] 'org-metaup)
16794 (org-defkey org-mode-map [(meta down)] 'org-metadown)
16796 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
16797 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
16798 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
16799 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
16801 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
16802 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
16803 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
16804 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
16806 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
16807 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
16808 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
16809 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
16811 ;; Babel keys
16812 (define-key org-mode-map org-babel-key-prefix org-babel-map)
16813 (mapc (lambda (pair)
16814 (define-key org-babel-map (car pair) (cdr pair)))
16815 org-babel-key-bindings)
16817 ;;; Extra keys for tty access.
16818 ;; We only set them when really needed because otherwise the
16819 ;; menus don't show the simple keys
16821 (when (or org-use-extra-keys
16822 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
16823 (not window-system))
16824 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
16825 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
16826 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
16827 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
16828 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
16829 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
16830 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
16831 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
16832 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
16833 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
16834 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
16835 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
16836 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
16837 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
16838 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
16839 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
16840 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
16841 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
16842 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
16843 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
16844 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
16845 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
16846 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
16847 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
16848 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
16849 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
16850 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
16851 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
16853 ;; All the other keys
16855 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
16856 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
16857 (if (boundp 'narrow-map)
16858 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
16859 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
16860 (if (boundp 'narrow-map)
16861 (org-defkey narrow-map "b" 'org-narrow-to-block)
16862 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
16863 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-same-level)
16864 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-same-level)
16865 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
16866 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
16867 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
16868 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
16869 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
16870 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
16871 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
16872 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
16873 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
16874 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
16875 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
16876 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
16877 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
16878 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
16879 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
16880 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
16881 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
16882 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
16883 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
16884 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
16885 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
16886 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
16887 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
16888 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
16889 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
16890 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
16891 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
16892 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
16893 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
16894 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
16895 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
16896 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
16897 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
16898 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
16899 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
16900 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
16901 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
16902 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
16903 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
16904 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
16905 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
16906 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
16907 (org-defkey org-mode-map "\C-c^" 'org-sort)
16908 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
16909 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
16910 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
16911 (org-defkey org-mode-map "\C-m" 'org-return)
16912 (org-defkey org-mode-map "\C-j" 'org-return-indent)
16913 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
16914 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
16915 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
16916 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
16917 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
16918 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
16919 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
16920 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
16921 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
16922 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
16923 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
16924 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
16925 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
16926 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
16927 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
16928 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
16929 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
16930 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
16931 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
16932 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
16933 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
16935 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
16936 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
16937 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
16938 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
16940 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
16941 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
16942 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
16943 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
16944 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
16945 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
16946 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
16947 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
16948 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
16949 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
16950 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
16951 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
16952 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
16953 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
16954 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
16955 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
16956 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
16957 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
16959 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
16960 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
16961 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
16962 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
16963 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
16965 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
16967 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
16969 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
16970 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
16972 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
16975 (when (featurep 'xemacs)
16976 (org-defkey org-mode-map 'button3 'popup-mode-menu))
16979 (defconst org-speed-commands-default
16981 ("Outline Navigation")
16982 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
16983 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
16984 ("f" . (org-speed-move-safe 'org-forward-same-level))
16985 ("b" . (org-speed-move-safe 'org-backward-same-level))
16986 ("u" . (org-speed-move-safe 'outline-up-heading))
16987 ("j" . org-goto)
16988 ("g" . (org-refile t))
16989 ("Outline Visibility")
16990 ("c" . org-cycle)
16991 ("C" . org-shifttab)
16992 (" " . org-display-outline-path)
16993 ("Outline Structure Editing")
16994 ("U" . org-shiftmetaup)
16995 ("D" . org-shiftmetadown)
16996 ("r" . org-metaright)
16997 ("l" . org-metaleft)
16998 ("R" . org-shiftmetaright)
16999 ("L" . org-shiftmetaleft)
17000 ("i" . (progn (forward-char 1) (call-interactively
17001 'org-insert-heading-respect-content)))
17002 ("^" . org-sort)
17003 ("w" . org-refile)
17004 ("a" . org-archive-subtree-default-with-confirmation)
17005 ("." . org-mark-subtree)
17006 ("Clock Commands")
17007 ("I" . org-clock-in)
17008 ("O" . org-clock-out)
17009 ("Meta Data Editing")
17010 ("t" . org-todo)
17011 ("0" . (org-priority ?\ ))
17012 ("1" . (org-priority ?A))
17013 ("2" . (org-priority ?B))
17014 ("3" . (org-priority ?C))
17015 (";" . org-set-tags-command)
17016 ("e" . org-set-effort)
17017 ("Agenda Views etc")
17018 ("v" . org-agenda)
17019 ("/" . org-sparse-tree)
17020 ("Misc")
17021 ("o" . org-open-at-point)
17022 ("?" . org-speed-command-help)
17023 ("<" . (org-agenda-set-restriction-lock 'subtree))
17024 (">" . (org-agenda-remove-restriction-lock))
17026 "The default speed commands.")
17028 (defun org-print-speed-command (e)
17029 (if (> (length (car e)) 1)
17030 (progn
17031 (princ "\n")
17032 (princ (car e))
17033 (princ "\n")
17034 (princ (make-string (length (car e)) ?-))
17035 (princ "\n"))
17036 (princ (car e))
17037 (princ " ")
17038 (if (symbolp (cdr e))
17039 (princ (symbol-name (cdr e)))
17040 (prin1 (cdr e)))
17041 (princ "\n")))
17043 (defun org-speed-command-help ()
17044 "Show the available speed commands."
17045 (interactive)
17046 (if (not org-use-speed-commands)
17047 (error "Speed commands are not activated, customize `org-use-speed-commands'")
17048 (with-output-to-temp-buffer "*Help*"
17049 (princ "User-defined Speed commands\n===========================\n")
17050 (mapc 'org-print-speed-command org-speed-commands-user)
17051 (princ "\n")
17052 (princ "Built-in Speed commands\n=======================\n")
17053 (mapc 'org-print-speed-command org-speed-commands-default))
17054 (with-current-buffer "*Help*"
17055 (setq truncate-lines t))))
17057 (defun org-speed-move-safe (cmd)
17058 "Execute CMD, but make sure that the cursor always ends up in a headline.
17059 If not, return to the original position and throw an error."
17060 (interactive)
17061 (let ((pos (point)))
17062 (call-interactively cmd)
17063 (unless (and (bolp) (org-on-heading-p))
17064 (goto-char pos)
17065 (error "Boundary reached while executing %s" cmd))))
17067 (defvar org-self-insert-command-undo-counter 0)
17069 (defvar org-table-auto-blank-field) ; defined in org-table.el
17070 (defvar org-speed-command nil)
17072 (defun org-speed-command-default-hook (keys)
17073 "Hook for activating single-letter speed commands.
17074 `org-speed-commands-default' specifies a minimal command set.
17075 Use `org-speed-commands-user' for further customization."
17076 (when (or (and (bolp) (looking-at org-outline-regexp))
17077 (and (functionp org-use-speed-commands)
17078 (funcall org-use-speed-commands)))
17079 (cdr (assoc keys (append org-speed-commands-user
17080 org-speed-commands-default)))))
17082 (defun org-babel-speed-command-hook (keys)
17083 "Hook for activating single-letter code block commands."
17084 (when (and (bolp) (looking-at org-babel-src-block-regexp))
17085 (cdr (assoc keys org-babel-key-bindings))))
17087 (defcustom org-speed-command-hook
17088 '(org-speed-command-default-hook org-babel-speed-command-hook)
17089 "Hook for activating speed commands at strategic locations.
17090 Hook functions are called in sequence until a valid handler is
17091 found.
17093 Each hook takes a single argument, a user-pressed command key
17094 which is also a `self-insert-command' from the global map.
17096 Within the hook, examine the cursor position and the command key
17097 and return nil or a valid handler as appropriate. Handler could
17098 be one of an interactive command, a function, or a form.
17100 Set `org-use-speed-commands' to non-nil value to enable this
17101 hook. The default setting is `org-speed-command-default-hook'."
17102 :group 'org-structure
17103 :type 'hook)
17105 (defun org-self-insert-command (N)
17106 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
17107 If the cursor is in a table looking at whitespace, the whitespace is
17108 overwritten, and the table is not marked as requiring realignment."
17109 (interactive "p")
17110 (cond
17111 ((and org-use-speed-commands
17112 (setq org-speed-command
17113 (run-hook-with-args-until-success
17114 'org-speed-command-hook (this-command-keys))))
17115 (cond
17116 ((commandp org-speed-command)
17117 (setq this-command org-speed-command)
17118 (call-interactively org-speed-command))
17119 ((functionp org-speed-command)
17120 (funcall org-speed-command))
17121 ((and org-speed-command (listp org-speed-command))
17122 (eval org-speed-command))
17123 (t (let (org-use-speed-commands)
17124 (call-interactively 'org-self-insert-command)))))
17125 ((and
17126 (org-table-p)
17127 (progn
17128 ;; check if we blank the field, and if that triggers align
17129 (and (featurep 'org-table) org-table-auto-blank-field
17130 (member last-command
17131 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
17132 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
17133 ;; got extra space, this field does not determine column width
17134 (let (org-table-may-need-update) (org-table-blank-field))
17135 ;; no extra space, this field may determine column width
17136 (org-table-blank-field)))
17138 (eq N 1)
17139 (looking-at "[^|\n]* |"))
17140 (let (org-table-may-need-update)
17141 (goto-char (1- (match-end 0)))
17142 (delete-char -1)
17143 (goto-char (match-beginning 0))
17144 (self-insert-command N)))
17146 (setq org-table-may-need-update t)
17147 (self-insert-command N)
17148 (org-fix-tags-on-the-fly)
17149 (if org-self-insert-cluster-for-undo
17150 (if (not (eq last-command 'org-self-insert-command))
17151 (setq org-self-insert-command-undo-counter 1)
17152 (if (>= org-self-insert-command-undo-counter 20)
17153 (setq org-self-insert-command-undo-counter 1)
17154 (and (> org-self-insert-command-undo-counter 0)
17155 buffer-undo-list (listp buffer-undo-list)
17156 (not (cadr buffer-undo-list)) ; remove nil entry
17157 (setcdr buffer-undo-list (cddr buffer-undo-list)))
17158 (setq org-self-insert-command-undo-counter
17159 (1+ org-self-insert-command-undo-counter))))))))
17161 (defun org-fix-tags-on-the-fly ()
17162 (when (and (equal (char-after (point-at-bol)) ?*)
17163 (org-on-heading-p))
17164 (org-align-tags-here org-tags-column)))
17166 (defun org-delete-backward-char (N)
17167 "Like `delete-backward-char', insert whitespace at field end in tables.
17168 When deleting backwards, in tables this function will insert whitespace in
17169 front of the next \"|\" separator, to keep the table aligned. The table will
17170 still be marked for re-alignment if the field did fill the entire column,
17171 because, in this case the deletion might narrow the column."
17172 (interactive "p")
17173 (if (and (org-table-p)
17174 (eq N 1)
17175 (string-match "|" (buffer-substring (point-at-bol) (point)))
17176 (looking-at ".*?|"))
17177 (let ((pos (point))
17178 (noalign (looking-at "[^|\n\r]* |"))
17179 (c org-table-may-need-update))
17180 (backward-delete-char N)
17181 (if (not overwrite-mode)
17182 (progn
17183 (skip-chars-forward "^|")
17184 (insert " ")
17185 (goto-char (1- pos))))
17186 ;; noalign: if there were two spaces at the end, this field
17187 ;; does not determine the width of the column.
17188 (if noalign (setq org-table-may-need-update c)))
17189 (backward-delete-char N)
17190 (org-fix-tags-on-the-fly)))
17192 (defun org-delete-char (N)
17193 "Like `delete-char', but insert whitespace at field end in tables.
17194 When deleting characters, in tables this function will insert whitespace in
17195 front of the next \"|\" separator, to keep the table aligned. The table will
17196 still be marked for re-alignment if the field did fill the entire column,
17197 because, in this case the deletion might narrow the column."
17198 (interactive "p")
17199 (if (and (org-table-p)
17200 (not (bolp))
17201 (not (= (char-after) ?|))
17202 (eq N 1))
17203 (if (looking-at ".*?|")
17204 (let ((pos (point))
17205 (noalign (looking-at "[^|\n\r]* |"))
17206 (c org-table-may-need-update))
17207 (replace-match (concat
17208 (substring (match-string 0) 1 -1)
17209 " |"))
17210 (goto-char pos)
17211 ;; noalign: if there were two spaces at the end, this field
17212 ;; does not determine the width of the column.
17213 (if noalign (setq org-table-may-need-update c)))
17214 (delete-char N))
17215 (delete-char N)
17216 (org-fix-tags-on-the-fly)))
17218 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
17219 (put 'org-self-insert-command 'delete-selection t)
17220 (put 'orgtbl-self-insert-command 'delete-selection t)
17221 (put 'org-delete-char 'delete-selection 'supersede)
17222 (put 'org-delete-backward-char 'delete-selection 'supersede)
17223 (put 'org-yank 'delete-selection 'yank)
17225 ;; Make `flyspell-mode' delay after some commands
17226 (put 'org-self-insert-command 'flyspell-delayed t)
17227 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
17228 (put 'org-delete-char 'flyspell-delayed t)
17229 (put 'org-delete-backward-char 'flyspell-delayed t)
17231 ;; Make pabbrev-mode expand after org-mode commands
17232 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
17233 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
17235 ;; How to do this: Measure non-white length of current string
17236 ;; If equal to column width, we should realign.
17238 (defun org-remap (map &rest commands)
17239 "In MAP, remap the functions given in COMMANDS.
17240 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
17241 (let (new old)
17242 (while commands
17243 (setq old (pop commands) new (pop commands))
17244 (if (fboundp 'command-remapping)
17245 (org-defkey map (vector 'remap old) new)
17246 (substitute-key-definition old new map global-map)))))
17248 (when (eq org-enable-table-editor 'optimized)
17249 ;; If the user wants maximum table support, we need to hijack
17250 ;; some standard editing functions
17251 (org-remap org-mode-map
17252 'self-insert-command 'org-self-insert-command
17253 'delete-char 'org-delete-char
17254 'delete-backward-char 'org-delete-backward-char)
17255 (org-defkey org-mode-map "|" 'org-force-self-insert))
17257 (defvar org-ctrl-c-ctrl-c-hook nil
17258 "Hook for functions attaching themselves to `C-c C-c'.
17260 This can be used to add additional functionality to the C-c C-c
17261 key which executes context-dependent commands. This hook is run
17262 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
17263 run after the last test.
17265 Each function will be called with no arguments. The function
17266 must check if the context is appropriate for it to act. If yes,
17267 it should do its thing and then return a non-nil value. If the
17268 context is wrong, just do nothing and return nil.")
17270 (defvar org-ctrl-c-ctrl-c-final-hook nil
17271 "Hook for functions attaching themselves to `C-c C-c'.
17273 This can be used to add additional functionality to the C-c C-c
17274 key which executes context-dependent commands. This hook is run
17275 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
17276 before the first test.
17278 Each function will be called with no arguments. The function
17279 must check if the context is appropriate for it to act. If yes,
17280 it should do its thing and then return a non-nil value. If the
17281 context is wrong, just do nothing and return nil.")
17283 (defvar org-tab-first-hook nil
17284 "Hook for functions to attach themselves to TAB.
17285 See `org-ctrl-c-ctrl-c-hook' for more information.
17286 This hook runs as the first action when TAB is pressed, even before
17287 `org-cycle' messes around with the `outline-regexp' to cater for
17288 inline tasks and plain list item folding.
17289 If any function in this hook returns t, any other actions that
17290 would have been caused by TAB (such as table field motion or visibility
17291 cycling) will not occur.")
17293 (defvar org-tab-after-check-for-table-hook nil
17294 "Hook for functions to attach themselves to TAB.
17295 See `org-ctrl-c-ctrl-c-hook' for more information.
17296 This hook runs after it has been established that the cursor is not in a
17297 table, but before checking if the cursor is in a headline or if global cycling
17298 should be done.
17299 If any function in this hook returns t, not other actions like visibility
17300 cycling will be done.")
17302 (defvar org-tab-after-check-for-cycling-hook nil
17303 "Hook for functions to attach themselves to TAB.
17304 See `org-ctrl-c-ctrl-c-hook' for more information.
17305 This hook runs after it has been established that not table field motion and
17306 not visibility should be done because of current context. This is probably
17307 the place where a package like yasnippets can hook in.")
17309 (defvar org-tab-before-tab-emulation-hook nil
17310 "Hook for functions to attach themselves to TAB.
17311 See `org-ctrl-c-ctrl-c-hook' for more information.
17312 This hook runs after every other options for TAB have been exhausted, but
17313 before indentation and \t insertion takes place.")
17315 (defvar org-metaleft-hook nil
17316 "Hook for functions attaching themselves to `M-left'.
17317 See `org-ctrl-c-ctrl-c-hook' for more information.")
17318 (defvar org-metaright-hook nil
17319 "Hook for functions attaching themselves to `M-right'.
17320 See `org-ctrl-c-ctrl-c-hook' for more information.")
17321 (defvar org-metaup-hook nil
17322 "Hook for functions attaching themselves to `M-up'.
17323 See `org-ctrl-c-ctrl-c-hook' for more information.")
17324 (defvar org-metadown-hook nil
17325 "Hook for functions attaching themselves to `M-down'.
17326 See `org-ctrl-c-ctrl-c-hook' for more information.")
17327 (defvar org-shiftmetaleft-hook nil
17328 "Hook for functions attaching themselves to `M-S-left'.
17329 See `org-ctrl-c-ctrl-c-hook' for more information.")
17330 (defvar org-shiftmetaright-hook nil
17331 "Hook for functions attaching themselves to `M-S-right'.
17332 See `org-ctrl-c-ctrl-c-hook' for more information.")
17333 (defvar org-shiftmetaup-hook nil
17334 "Hook for functions attaching themselves to `M-S-up'.
17335 See `org-ctrl-c-ctrl-c-hook' for more information.")
17336 (defvar org-shiftmetadown-hook nil
17337 "Hook for functions attaching themselves to `M-S-down'.
17338 See `org-ctrl-c-ctrl-c-hook' for more information.")
17339 (defvar org-metareturn-hook nil
17340 "Hook for functions attaching themselves to `M-RET'.
17341 See `org-ctrl-c-ctrl-c-hook' for more information.")
17342 (defvar org-shiftup-hook nil
17343 "Hook for functions attaching themselves to `S-up'.
17344 See `org-ctrl-c-ctrl-c-hook' for more information.")
17345 (defvar org-shiftup-final-hook nil
17346 "Hook for functions attaching themselves to `S-up'.
17347 This one runs after all other options except shift-select have been excluded.
17348 See `org-ctrl-c-ctrl-c-hook' for more information.")
17349 (defvar org-shiftdown-hook nil
17350 "Hook for functions attaching themselves to `S-down'.
17351 See `org-ctrl-c-ctrl-c-hook' for more information.")
17352 (defvar org-shiftdown-final-hook nil
17353 "Hook for functions attaching themselves to `S-down'.
17354 This one runs after all other options except shift-select have been excluded.
17355 See `org-ctrl-c-ctrl-c-hook' for more information.")
17356 (defvar org-shiftleft-hook nil
17357 "Hook for functions attaching themselves to `S-left'.
17358 See `org-ctrl-c-ctrl-c-hook' for more information.")
17359 (defvar org-shiftleft-final-hook nil
17360 "Hook for functions attaching themselves to `S-left'.
17361 This one runs after all other options except shift-select have been excluded.
17362 See `org-ctrl-c-ctrl-c-hook' for more information.")
17363 (defvar org-shiftright-hook nil
17364 "Hook for functions attaching themselves to `S-right'.
17365 See `org-ctrl-c-ctrl-c-hook' for more information.")
17366 (defvar org-shiftright-final-hook nil
17367 "Hook for functions attaching themselves to `S-right'.
17368 This one runs after all other options except shift-select have been excluded.
17369 See `org-ctrl-c-ctrl-c-hook' for more information.")
17371 (defun org-modifier-cursor-error ()
17372 "Throw an error, a modified cursor command was applied in wrong context."
17373 (error "This command is active in special context like tables, headlines or items"))
17375 (defun org-shiftselect-error ()
17376 "Throw an error because Shift-Cursor command was applied in wrong context."
17377 (if (and (boundp 'shift-select-mode) shift-select-mode)
17378 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
17379 (error "This command works only in special context like headlines or timestamps")))
17381 (defun org-call-for-shift-select (cmd)
17382 (let ((this-command-keys-shift-translated t))
17383 (call-interactively cmd)))
17385 (defun org-shifttab (&optional arg)
17386 "Global visibility cycling or move to previous table field.
17387 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
17388 on context.
17389 See the individual commands for more information."
17390 (interactive "P")
17391 (cond
17392 ((org-at-table-p) (call-interactively 'org-table-previous-field))
17393 ((integerp arg)
17394 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
17395 (message "Content view to level: %d" arg)
17396 (org-content (prefix-numeric-value arg2))
17397 (setq org-cycle-global-status 'overview)))
17398 (t (call-interactively 'org-global-cycle))))
17400 (defun org-shiftmetaleft ()
17401 "Promote subtree or delete table column.
17402 Calls `org-promote-subtree', `org-outdent-item',
17403 or `org-table-delete-column', depending on context.
17404 See the individual commands for more information."
17405 (interactive)
17406 (cond
17407 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
17408 ((org-at-table-p) (call-interactively 'org-table-delete-column))
17409 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
17410 ((org-at-item-p) (call-interactively 'org-outdent-item-tree))
17411 (t (org-modifier-cursor-error))))
17413 (defun org-shiftmetaright ()
17414 "Demote subtree or insert table column.
17415 Calls `org-demote-subtree', `org-indent-item',
17416 or `org-table-insert-column', depending on context.
17417 See the individual commands for more information."
17418 (interactive)
17419 (cond
17420 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
17421 ((org-at-table-p) (call-interactively 'org-table-insert-column))
17422 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
17423 ((org-at-item-p) (call-interactively 'org-indent-item-tree))
17424 (t (org-modifier-cursor-error))))
17426 (defun org-shiftmetaup (&optional arg)
17427 "Move subtree up or kill table row.
17428 Calls `org-move-subtree-up' or `org-table-kill-row' or
17429 `org-move-item-up' depending on context. See the individual commands
17430 for more information."
17431 (interactive "P")
17432 (cond
17433 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
17434 ((org-at-table-p) (call-interactively 'org-table-kill-row))
17435 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
17436 ((org-at-item-p) (call-interactively 'org-move-item-up))
17437 (t (org-modifier-cursor-error))))
17439 (defun org-shiftmetadown (&optional arg)
17440 "Move subtree down or insert table row.
17441 Calls `org-move-subtree-down' or `org-table-insert-row' or
17442 `org-move-item-down', depending on context. See the individual
17443 commands for more information."
17444 (interactive "P")
17445 (cond
17446 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
17447 ((org-at-table-p) (call-interactively 'org-table-insert-row))
17448 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
17449 ((org-at-item-p) (call-interactively 'org-move-item-down))
17450 (t (org-modifier-cursor-error))))
17452 (defsubst org-hidden-tree-error ()
17453 (error
17454 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
17456 (defun org-metaleft (&optional arg)
17457 "Promote heading or move table column to left.
17458 Calls `org-do-promote' or `org-table-move-column', depending on context.
17459 With no specific context, calls the Emacs default `backward-word'.
17460 See the individual commands for more information."
17461 (interactive "P")
17462 (cond
17463 ((run-hook-with-args-until-success 'org-metaleft-hook))
17464 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
17465 ((org-with-limited-levels
17466 (or (org-on-heading-p)
17467 (and (org-region-active-p)
17468 (save-excursion
17469 (goto-char (region-beginning))
17470 (org-on-heading-p)))))
17471 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
17472 (call-interactively 'org-do-promote))
17473 ;; At an inline task.
17474 ((org-on-heading-p)
17475 (call-interactively 'org-inlinetask-promote))
17476 ((or (org-at-item-p)
17477 (and (org-region-active-p)
17478 (save-excursion
17479 (goto-char (region-beginning))
17480 (org-at-item-p))))
17481 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
17482 (call-interactively 'org-outdent-item))
17483 (t (call-interactively 'backward-word))))
17485 (defun org-metaright (&optional arg)
17486 "Demote subtree or move table column to right.
17487 Calls `org-do-demote' or `org-table-move-column', depending on context.
17488 With no specific context, calls the Emacs default `forward-word'.
17489 See the individual commands for more information."
17490 (interactive "P")
17491 (cond
17492 ((run-hook-with-args-until-success 'org-metaright-hook))
17493 ((org-at-table-p) (call-interactively 'org-table-move-column))
17494 ((org-with-limited-levels
17495 (or (org-on-heading-p)
17496 (and (org-region-active-p)
17497 (save-excursion
17498 (goto-char (region-beginning))
17499 (org-on-heading-p)))))
17500 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
17501 (call-interactively 'org-do-demote))
17502 ;; At an inline task.
17503 ((org-on-heading-p)
17504 (call-interactively 'org-inlinetask-demote))
17505 ((or (org-at-item-p)
17506 (and (org-region-active-p)
17507 (save-excursion
17508 (goto-char (region-beginning))
17509 (org-at-item-p))))
17510 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
17511 (call-interactively 'org-indent-item))
17512 (t (call-interactively 'forward-word))))
17514 (defun org-check-for-hidden (what)
17515 "Check if there are hidden headlines/items in the current visual line.
17516 WHAT can be either `headlines' or `items'. If the current line is
17517 an outline or item heading and it has a folded subtree below it,
17518 this function returns t, nil otherwise."
17519 (let ((re (cond
17520 ((eq what 'headlines) org-outline-regexp-bol)
17521 ((eq what 'items) (org-item-beginning-re))
17522 (t (error "This should not happen"))))
17523 beg end)
17524 (save-excursion
17525 (catch 'exit
17526 (unless (org-region-active-p)
17527 (setq beg (point-at-bol))
17528 (beginning-of-line 2)
17529 (while (and (not (eobp)) ;; this is like `next-line'
17530 (get-char-property (1- (point)) 'invisible))
17531 (beginning-of-line 2))
17532 (setq end (point))
17533 (goto-char beg)
17534 (goto-char (point-at-eol))
17535 (setq end (max end (point)))
17536 (while (re-search-forward re end t)
17537 (if (get-char-property (match-beginning 0) 'invisible)
17538 (throw 'exit t))))
17539 nil))))
17541 (defun org-metaup (&optional arg)
17542 "Move subtree up or move table row up.
17543 Calls `org-move-subtree-up' or `org-table-move-row' or
17544 `org-move-item-up', depending on context. See the individual commands
17545 for more information."
17546 (interactive "P")
17547 (cond
17548 ((run-hook-with-args-until-success 'org-metaup-hook))
17549 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
17550 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
17551 ((org-at-item-p) (call-interactively 'org-move-item-up))
17552 (t (transpose-lines 1) (beginning-of-line -1))))
17554 (defun org-metadown (&optional arg)
17555 "Move subtree down or move table row down.
17556 Calls `org-move-subtree-down' or `org-table-move-row' or
17557 `org-move-item-down', depending on context. See the individual
17558 commands for more information."
17559 (interactive "P")
17560 (cond
17561 ((run-hook-with-args-until-success 'org-metadown-hook))
17562 ((org-at-table-p) (call-interactively 'org-table-move-row))
17563 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
17564 ((org-at-item-p) (call-interactively 'org-move-item-down))
17565 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
17567 (defun org-shiftup (&optional arg)
17568 "Increase item in timestamp or increase priority of current headline.
17569 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
17570 depending on context. See the individual commands for more information."
17571 (interactive "P")
17572 (cond
17573 ((run-hook-with-args-until-success 'org-shiftup-hook))
17574 ((and org-support-shift-select (org-region-active-p))
17575 (org-call-for-shift-select 'previous-line))
17576 ((org-at-timestamp-p t)
17577 (call-interactively (if org-edit-timestamp-down-means-later
17578 'org-timestamp-down 'org-timestamp-up)))
17579 ((and (not (eq org-support-shift-select 'always))
17580 org-enable-priority-commands
17581 (org-on-heading-p))
17582 (call-interactively 'org-priority-up))
17583 ((and (not org-support-shift-select) (org-at-item-p))
17584 (call-interactively 'org-previous-item))
17585 ((org-clocktable-try-shift 'up arg))
17586 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
17587 (org-support-shift-select
17588 (org-call-for-shift-select 'previous-line))
17589 (t (org-shiftselect-error))))
17591 (defun org-shiftdown (&optional arg)
17592 "Decrease item in timestamp or decrease priority of current headline.
17593 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
17594 depending on context. See the individual commands for more information."
17595 (interactive "P")
17596 (cond
17597 ((run-hook-with-args-until-success 'org-shiftdown-hook))
17598 ((and org-support-shift-select (org-region-active-p))
17599 (org-call-for-shift-select 'next-line))
17600 ((org-at-timestamp-p t)
17601 (call-interactively (if org-edit-timestamp-down-means-later
17602 'org-timestamp-up 'org-timestamp-down)))
17603 ((and (not (eq org-support-shift-select 'always))
17604 org-enable-priority-commands
17605 (org-on-heading-p))
17606 (call-interactively 'org-priority-down))
17607 ((and (not org-support-shift-select) (org-at-item-p))
17608 (call-interactively 'org-next-item))
17609 ((org-clocktable-try-shift 'down arg))
17610 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
17611 (org-support-shift-select
17612 (org-call-for-shift-select 'next-line))
17613 (t (org-shiftselect-error))))
17615 (defun org-shiftright (&optional arg)
17616 "Cycle the thing at point or in the current line, depending on context.
17617 Depending on context, this does one of the following:
17619 - switch a timestamp at point one day into the future
17620 - on a headline, switch to the next TODO keyword.
17621 - on an item, switch entire list to the next bullet type
17622 - on a property line, switch to the next allowed value
17623 - on a clocktable definition line, move time block into the future"
17624 (interactive "P")
17625 (cond
17626 ((run-hook-with-args-until-success 'org-shiftright-hook))
17627 ((and org-support-shift-select (org-region-active-p))
17628 (org-call-for-shift-select 'forward-char))
17629 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
17630 ((and (not (eq org-support-shift-select 'always))
17631 (org-on-heading-p))
17632 (let ((org-inhibit-logging
17633 (not org-treat-S-cursor-todo-selection-as-state-change))
17634 (org-inhibit-blocking
17635 (not org-treat-S-cursor-todo-selection-as-state-change)))
17636 (org-call-with-arg 'org-todo 'right)))
17637 ((or (and org-support-shift-select
17638 (not (eq org-support-shift-select 'always))
17639 (org-at-item-bullet-p))
17640 (and (not org-support-shift-select) (org-at-item-p)))
17641 (org-call-with-arg 'org-cycle-list-bullet nil))
17642 ((and (not (eq org-support-shift-select 'always))
17643 (org-at-property-p))
17644 (call-interactively 'org-property-next-allowed-value))
17645 ((org-clocktable-try-shift 'right arg))
17646 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
17647 (org-support-shift-select
17648 (org-call-for-shift-select 'forward-char))
17649 (t (org-shiftselect-error))))
17651 (defun org-shiftleft (&optional arg)
17652 "Cycle the thing at point or in the current line, depending on context.
17653 Depending on context, this does one of the following:
17655 - switch a timestamp at point one day into the past
17656 - on a headline, switch to the previous TODO keyword.
17657 - on an item, switch entire list to the previous bullet type
17658 - on a property line, switch to the previous allowed value
17659 - on a clocktable definition line, move time block into the past"
17660 (interactive "P")
17661 (cond
17662 ((run-hook-with-args-until-success 'org-shiftleft-hook))
17663 ((and org-support-shift-select (org-region-active-p))
17664 (org-call-for-shift-select 'backward-char))
17665 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
17666 ((and (not (eq org-support-shift-select 'always))
17667 (org-on-heading-p))
17668 (let ((org-inhibit-logging
17669 (not org-treat-S-cursor-todo-selection-as-state-change))
17670 (org-inhibit-blocking
17671 (not org-treat-S-cursor-todo-selection-as-state-change)))
17672 (org-call-with-arg 'org-todo 'left)))
17673 ((or (and org-support-shift-select
17674 (not (eq org-support-shift-select 'always))
17675 (org-at-item-bullet-p))
17676 (and (not org-support-shift-select) (org-at-item-p)))
17677 (org-call-with-arg 'org-cycle-list-bullet 'previous))
17678 ((and (not (eq org-support-shift-select 'always))
17679 (org-at-property-p))
17680 (call-interactively 'org-property-previous-allowed-value))
17681 ((org-clocktable-try-shift 'left arg))
17682 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
17683 (org-support-shift-select
17684 (org-call-for-shift-select 'backward-char))
17685 (t (org-shiftselect-error))))
17687 (defun org-shiftcontrolright ()
17688 "Switch to next TODO set."
17689 (interactive)
17690 (cond
17691 ((and org-support-shift-select (org-region-active-p))
17692 (org-call-for-shift-select 'forward-word))
17693 ((and (not (eq org-support-shift-select 'always))
17694 (org-on-heading-p))
17695 (org-call-with-arg 'org-todo 'nextset))
17696 (org-support-shift-select
17697 (org-call-for-shift-select 'forward-word))
17698 (t (org-shiftselect-error))))
17700 (defun org-shiftcontrolleft ()
17701 "Switch to previous TODO set."
17702 (interactive)
17703 (cond
17704 ((and org-support-shift-select (org-region-active-p))
17705 (org-call-for-shift-select 'backward-word))
17706 ((and (not (eq org-support-shift-select 'always))
17707 (org-on-heading-p))
17708 (org-call-with-arg 'org-todo 'previousset))
17709 (org-support-shift-select
17710 (org-call-for-shift-select 'backward-word))
17711 (t (org-shiftselect-error))))
17713 (defun org-shiftcontrolup ()
17714 "Change timestamps synchronously up in CLOCK log lines."
17715 (interactive)
17716 (cond ((and (not org-support-shift-select)
17717 (org-at-clock-log-p)
17718 (org-at-timestamp-p t))
17719 (org-clock-timestamps-up))
17720 (t (org-shiftselect-error))))
17722 (defun org-shiftcontroldown ()
17723 "Change timestamps synchronously down in CLOCK log lines."
17724 (interactive)
17725 (cond ((and (not org-support-shift-select)
17726 (org-at-clock-log-p)
17727 (org-at-timestamp-p t))
17728 (org-clock-timestamps-down))
17729 (t (org-shiftselect-error))))
17731 (defun org-ctrl-c-ret ()
17732 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
17733 (interactive)
17734 (cond
17735 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
17736 (t (call-interactively 'org-insert-heading))))
17738 (defun org-find-visible ()
17739 (let ((s (point)))
17740 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
17741 (get-char-property s 'invisible)))
17743 (defun org-find-invisible ()
17744 (let ((s (point)))
17745 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
17746 (not (get-char-property s 'invisible))))
17749 (defun org-copy-visible (beg end)
17750 "Copy the visible parts of the region."
17751 (interactive "r")
17752 (let (snippets s)
17753 (save-excursion
17754 (save-restriction
17755 (narrow-to-region beg end)
17756 (setq s (goto-char (point-min)))
17757 (while (not (= (point) (point-max)))
17758 (goto-char (org-find-invisible))
17759 (push (buffer-substring s (point)) snippets)
17760 (setq s (goto-char (org-find-visible))))))
17761 (kill-new (apply 'concat (nreverse snippets)))))
17763 (defun org-copy-special ()
17764 "Copy region in table or copy current subtree.
17765 Calls `org-table-copy' or `org-copy-subtree', depending on context.
17766 See the individual commands for more information."
17767 (interactive)
17768 (call-interactively
17769 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
17771 (defun org-cut-special ()
17772 "Cut region in table or cut current subtree.
17773 Calls `org-table-copy' or `org-cut-subtree', depending on context.
17774 See the individual commands for more information."
17775 (interactive)
17776 (call-interactively
17777 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
17779 (defun org-paste-special (arg)
17780 "Paste rectangular region into table, or past subtree relative to level.
17781 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
17782 See the individual commands for more information."
17783 (interactive "P")
17784 (if (org-at-table-p)
17785 (org-table-paste-rectangle)
17786 (org-paste-subtree arg)))
17788 (defun org-edit-special (&optional arg)
17789 "Call a special editor for the stuff at point.
17790 When at a table, call the formula editor with `org-table-edit-formulas'.
17791 When at the first line of an src example, call `org-edit-src-code'.
17792 When in an #+include line, visit the include file. Otherwise call
17793 `ffap' to visit the file at point."
17794 (interactive)
17795 ;; possibly prep session before editing source
17796 (when arg
17797 (let* ((info (org-babel-get-src-block-info))
17798 (lang (nth 0 info))
17799 (params (nth 2 info))
17800 (session (cdr (assoc :session params))))
17801 (when (and info session) ;; we are in a source-code block with a session
17802 (funcall
17803 (intern (concat "org-babel-prep-session:" lang)) session params))))
17804 (cond ;; proceed with `org-edit-special'
17805 ((save-excursion
17806 (beginning-of-line 1)
17807 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
17808 (find-file (org-trim (match-string 1))))
17809 ((org-edit-src-code))
17810 ((org-edit-fixed-width-region))
17811 ((org-at-table.el-p)
17812 (org-edit-src-code))
17813 ((or (org-at-table-p)
17814 (save-excursion
17815 (beginning-of-line 1)
17816 (looking-at "[ \t]*#\\+TBLFM:")))
17817 (call-interactively 'org-table-edit-formulas))
17818 (t (call-interactively 'ffap))))
17820 (defun org-ctrl-c-ctrl-c (&optional arg)
17821 "Set tags in headline, or update according to changed information at point.
17823 This command does many different things, depending on context:
17825 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
17826 this is what we do.
17828 - If the cursor is on a statistics cookie, update it.
17830 - If the cursor is in a headline, prompt for tags and insert them
17831 into the current line, aligned to `org-tags-column'. When called
17832 with prefix arg, realign all tags in the current buffer.
17834 - If the cursor is in one of the special #+KEYWORD lines, this
17835 triggers scanning the buffer for these lines and updating the
17836 information.
17838 - If the cursor is inside a table, realign the table. This command
17839 works even if the automatic table editor has been turned off.
17841 - If the cursor is on a #+TBLFM line, re-apply the formulas to
17842 the entire table.
17844 - If the cursor is at a footnote reference or definition, jump to
17845 the corresponding definition or references, respectively.
17847 - If the cursor is a the beginning of a dynamic block, update it.
17849 - If the current buffer is a capture buffer, close note and file it.
17851 - If the cursor is on a <<<target>>>, update radio targets and
17852 corresponding links in this buffer.
17854 - If the cursor is on a numbered item in a plain list, renumber the
17855 ordered list.
17857 - If the cursor is on a checkbox, toggle it.
17859 - If the cursor is on a code block, evaluate it. The variable
17860 `org-confirm-babel-evaluate' can be used to control prompting
17861 before code block evaluation, by default every code block
17862 evaluation requires confirmation. Code block evaluation can be
17863 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
17864 (interactive "P")
17865 (let ((org-enable-table-editor t))
17866 (cond
17867 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
17868 org-occur-highlights
17869 org-latex-fragment-image-overlays)
17870 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
17871 (org-remove-occur-highlights)
17872 (org-remove-latex-fragment-image-overlays)
17873 (message "Temporary highlights/overlays removed from current buffer"))
17874 ((and (local-variable-p 'org-finish-function (current-buffer))
17875 (fboundp org-finish-function))
17876 (funcall org-finish-function))
17877 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
17878 ((or (looking-at org-property-start-re)
17879 (org-at-property-p))
17880 (call-interactively 'org-property-action))
17881 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
17882 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
17883 (or (org-on-heading-p) (org-at-item-p)))
17884 (call-interactively 'org-update-statistics-cookies))
17885 ((org-on-heading-p) (call-interactively 'org-set-tags))
17886 ((org-at-table.el-p)
17887 (message "Use C-c ' to edit table.el tables"))
17888 ((org-at-table-p)
17889 (org-table-maybe-eval-formula)
17890 (if arg
17891 (call-interactively 'org-table-recalculate)
17892 (org-table-maybe-recalculate-line))
17893 (call-interactively 'org-table-align)
17894 (orgtbl-send-table 'maybe))
17895 ((or (org-footnote-at-reference-p)
17896 (org-footnote-at-definition-p))
17897 (call-interactively 'org-footnote-action))
17898 ((org-at-item-checkbox-p)
17899 ;; Cursor at a checkbox: repair list and update checkboxes. Send
17900 ;; list only if at top item.
17901 (let* ((cbox (match-string 1))
17902 (struct (org-list-struct))
17903 (old-struct (copy-tree struct))
17904 (parents (org-list-parents-alist struct))
17905 (prevs (org-list-prevs-alist struct))
17906 (orderedp (org-entry-get nil "ORDERED"))
17907 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
17908 block-item)
17909 ;; Use a light version of `org-toggle-checkbox' to avoid
17910 ;; computing list structure twice.
17911 (org-list-set-checkbox (point-at-bol) struct
17912 (cond
17913 ((equal arg '(16)) "[-]")
17914 ((equal arg '(4)) nil)
17915 ((equal "[X]" cbox) "[ ]")
17916 (t "[X]")))
17917 (org-list-struct-fix-ind struct parents)
17918 (org-list-struct-fix-bul struct prevs)
17919 (setq block-item
17920 (org-list-struct-fix-box struct parents prevs orderedp))
17921 (when block-item
17922 (message
17923 "Checkboxes were removed due to unchecked box at line %d"
17924 (org-current-line block-item)))
17925 (org-list-struct-apply-struct struct old-struct)
17926 (org-update-checkbox-count-maybe)
17927 (when firstp (org-list-send-list 'maybe))))
17928 ((org-at-item-p)
17929 ;; Cursor at an item: repair list. Do checkbox related actions
17930 ;; only if function was called with an argument. Send list only
17931 ;; if at top item.
17932 (let* ((struct (org-list-struct))
17933 (old-struct (copy-tree struct))
17934 (parents (org-list-parents-alist struct))
17935 (prevs (org-list-prevs-alist struct))
17936 (firstp (= (org-list-get-top-point struct) (point-at-bol))))
17937 (org-list-struct-fix-ind struct parents)
17938 (org-list-struct-fix-bul struct prevs)
17939 (when arg
17940 (org-list-set-checkbox (point-at-bol) struct "[ ]")
17941 (org-list-struct-fix-box struct parents prevs))
17942 (org-list-struct-apply-struct struct old-struct)
17943 (when arg (org-update-checkbox-count-maybe))
17944 (when firstp (org-list-send-list 'maybe))))
17945 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
17946 ;; Dynamic block
17947 (beginning-of-line 1)
17948 (save-excursion (org-update-dblock)))
17949 ((save-excursion
17950 (beginning-of-line 1)
17951 (looking-at "[ \t]*#\\+\\([A-Z]+\\)"))
17952 (cond
17953 ((equal (match-string 1) "TBLFM")
17954 ;; Recalculate the table before this line
17955 (save-excursion
17956 (beginning-of-line 1)
17957 (skip-chars-backward " \r\n\t")
17958 (if (org-at-table-p)
17959 (org-call-with-arg 'org-table-recalculate (or arg t)))))
17961 (let ((org-inhibit-startup-visibility-stuff t)
17962 (org-startup-align-all-tables nil))
17963 (org-save-outline-visibility 'use-markers (org-mode-restart)))
17964 (message "Local setup has been refreshed"))))
17965 ((org-clock-update-time-maybe))
17967 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
17968 (error "C-c C-c can do nothing useful at this location"))))))
17970 (defun org-mode-restart ()
17971 "Restart Org-mode, to scan again for special lines.
17972 Also updates the keyword regular expressions."
17973 (interactive)
17974 (org-mode)
17975 (message "Org-mode restarted"))
17977 (defun org-kill-note-or-show-branches ()
17978 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
17979 (interactive)
17980 (if (not org-finish-function)
17981 (progn
17982 (hide-subtree)
17983 (call-interactively 'show-branches))
17984 (let ((org-note-abort t))
17985 (funcall org-finish-function))))
17987 (defun org-return (&optional indent)
17988 "Goto next table row or insert a newline.
17989 Calls `org-table-next-row' or `newline', depending on context.
17990 See the individual commands for more information."
17991 (interactive)
17992 (cond
17993 ((bobp) (if indent (newline-and-indent) (newline)))
17994 ((org-at-table-p)
17995 (org-table-justify-field-maybe)
17996 (call-interactively 'org-table-next-row))
17997 ;; when `newline-and-indent' is called within a list, make sure
17998 ;; text moved stays inside the item.
17999 ((and (org-in-item-p) indent)
18000 (if (and (org-at-item-p) (>= (point) (match-end 0)))
18001 (progn
18002 (save-match-data (newline))
18003 (org-indent-line-to (length (match-string 0))))
18004 (let ((ind (org-get-indentation)))
18005 (newline)
18006 (if (org-looking-back org-list-end-re)
18007 (org-indent-line-function)
18008 (org-indent-line-to ind)))))
18009 ((and org-return-follows-link
18010 (eq (get-text-property (point) 'face) 'org-link))
18011 (call-interactively 'org-open-at-point))
18012 ((and (org-at-heading-p)
18013 (looking-at
18014 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
18015 (org-show-entry)
18016 (end-of-line 1)
18017 (newline))
18018 (t (if indent (newline-and-indent) (newline)))))
18020 (defun org-return-indent ()
18021 "Goto next table row or insert a newline and indent.
18022 Calls `org-table-next-row' or `newline-and-indent', depending on
18023 context. See the individual commands for more information."
18024 (interactive)
18025 (org-return t))
18027 (defun org-ctrl-c-star ()
18028 "Compute table, or change heading status of lines.
18029 Calls `org-table-recalculate' or `org-toggle-heading',
18030 depending on context."
18031 (interactive)
18032 (cond
18033 ((org-at-table-p)
18034 (call-interactively 'org-table-recalculate))
18036 ;; Convert all lines in region to list items
18037 (call-interactively 'org-toggle-heading))))
18039 (defun org-ctrl-c-minus ()
18040 "Insert separator line in table or modify bullet status of line.
18041 Also turns a plain line or a region of lines into list items.
18042 Calls `org-table-insert-hline', `org-toggle-item', or
18043 `org-cycle-list-bullet', depending on context."
18044 (interactive)
18045 (cond
18046 ((org-at-table-p)
18047 (call-interactively 'org-table-insert-hline))
18048 ((org-region-active-p)
18049 (call-interactively 'org-toggle-item))
18050 ((org-in-item-p)
18051 (call-interactively 'org-cycle-list-bullet))
18053 (call-interactively 'org-toggle-item))))
18055 (defun org-toggle-item (arg)
18056 "Convert headings or normal lines to items, items to normal lines.
18057 If there is no active region, only the current line is considered.
18059 If the first non blank line in the region is an headline, convert
18060 all headlines to items, shifting text accordingly.
18062 If it is an item, convert all items to normal lines.
18064 If it is normal text, change region into an item. With a prefix
18065 argument ARG, change each line in region into an item."
18066 (interactive "P")
18067 (let ((shift-text
18068 (function
18069 ;; Shift text in current section to IND, from point to END.
18070 ;; The function leaves point to END line.
18071 (lambda (ind end)
18072 (let ((min-i 1000) (end (copy-marker end)))
18073 ;; First determine the minimum indentation (MIN-I) of
18074 ;; the text.
18075 (save-excursion
18076 (catch 'exit
18077 (while (< (point) end)
18078 (let ((i (org-get-indentation)))
18079 (cond
18080 ;; Skip blank lines and inline tasks.
18081 ((looking-at "^[ \t]*$"))
18082 ((looking-at org-outline-regexp-bol))
18083 ;; We can't find less than 0 indentation.
18084 ((zerop i) (throw 'exit (setq min-i 0)))
18085 ((< i min-i) (setq min-i i))))
18086 (forward-line))))
18087 ;; Then indent each line so that a line indented to
18088 ;; MIN-I becomes indented to IND. Ignore blank lines
18089 ;; and inline tasks in the process.
18090 (let ((delta (- ind min-i)))
18091 (while (< (point) end)
18092 (unless (or (looking-at "^[ \t]*$")
18093 (looking-at org-outline-regexp-bol))
18094 (org-indent-line-to (+ (org-get-indentation) delta)))
18095 (forward-line)))))))
18096 (skip-blanks
18097 (function
18098 ;; Return beginning of first non-blank line, starting from
18099 ;; line at POS.
18100 (lambda (pos)
18101 (save-excursion
18102 (goto-char pos)
18103 (skip-chars-forward " \r\t\n")
18104 (point-at-bol)))))
18105 beg end)
18106 ;; Determine boundaries of changes.
18107 (if (org-region-active-p)
18108 (setq beg (funcall skip-blanks (region-beginning))
18109 end (copy-marker (region-end)))
18110 (setq beg (funcall skip-blanks (point-at-bol))
18111 end (copy-marker (point-at-eol))))
18112 ;; Depending on the starting line, choose an action on the text
18113 ;; between BEG and END.
18114 (org-with-limited-levels
18115 (save-excursion
18116 (goto-char beg)
18117 (cond
18118 ;; Case 1. Start at an item: de-itemize. Note that it only
18119 ;; happens when a region is active: `org-ctrl-c-minus'
18120 ;; would call `org-cycle-list-bullet' otherwise.
18121 ((org-at-item-p)
18122 (while (< (point) end)
18123 (when (org-at-item-p)
18124 (skip-chars-forward " \t")
18125 (delete-region (point) (match-end 0)))
18126 (forward-line)))
18127 ;; Case 2. Start at an heading: convert to items.
18128 ((org-on-heading-p)
18129 (let* ((bul (org-list-bullet-string "-"))
18130 (bul-len (length bul))
18131 ;; Indentation of the first heading. It should be
18132 ;; relative to the indentation of its parent, if any.
18133 (start-ind (save-excursion
18134 (cond
18135 ((not org-adapt-indentation) 0)
18136 ((not (outline-previous-heading)) 0)
18137 (t (length (match-string 0))))))
18138 ;; Level of first heading. Further headings will be
18139 ;; compared to it to determine hierarchy in the list.
18140 (ref-level (org-reduced-level (org-outline-level))))
18141 (while (< (point) end)
18142 (let* ((level (org-reduced-level (org-outline-level)))
18143 (delta (max 0 (- level ref-level))))
18144 ;; If current headline is less indented than the first
18145 ;; one, set it as reference, in order to preserve
18146 ;; subtrees.
18147 (when (< level ref-level) (setq ref-level level))
18148 (replace-match bul t t)
18149 (org-indent-line-to (+ start-ind (* delta bul-len)))
18150 ;; Ensure all text down to END (or SECTION-END) belongs
18151 ;; to the newly created item.
18152 (let ((section-end (save-excursion
18153 (or (outline-next-heading) (point)))))
18154 (forward-line)
18155 (funcall shift-text
18156 (+ start-ind (* (1+ delta) bul-len))
18157 (min end section-end)))))))
18158 ;; Case 3. Normal line with ARG: turn each non-item line into
18159 ;; an item.
18160 (arg
18161 (while (< (point) end)
18162 (unless (or (org-on-heading-p) (org-at-item-p))
18163 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
18164 (replace-match
18165 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
18166 (forward-line)))
18167 ;; Case 4. Normal line without ARG: make the first line of
18168 ;; region an item, and shift indentation of others
18169 ;; lines to set them as item's body.
18170 (t (let* ((bul (org-list-bullet-string "-"))
18171 (bul-len (length bul))
18172 (ref-ind (org-get-indentation)))
18173 (skip-chars-forward " \t")
18174 (insert bul)
18175 (forward-line)
18176 (while (< (point) end)
18177 ;; Ensure that lines less indented than first one
18178 ;; still get included in item body.
18179 (funcall shift-text
18180 (+ ref-ind bul-len)
18181 (min end (save-excursion (or (outline-next-heading)
18182 (point)))))
18183 (forward-line)))))))))
18185 (defun org-toggle-heading (&optional nstars)
18186 "Convert headings to normal text, or items or text to headings.
18187 If there is no active region, only the current line is considered.
18189 If the first non blank line is an headline, remove the stars from
18190 all headlines in the region.
18192 If it is a plain list item, turn all plain list items into headings.
18194 If it is a normal line, turn each and every normal line (i.e. not
18195 an heading or an item) in the region into a heading.
18197 When converting a line into a heading, the number of stars is chosen
18198 such that the lines become children of the current entry. However,
18199 when a prefix argument is given, its value determines the number of
18200 stars to add."
18201 (interactive "P")
18202 (let ((skip-blanks
18203 (function
18204 ;; Return beginning of first non-blank line, starting from
18205 ;; line at POS.
18206 (lambda (pos)
18207 (save-excursion
18208 (goto-char pos)
18209 (skip-chars-forward " \r\t\n")
18210 (point-at-bol)))))
18211 beg end)
18212 ;; Determine boundaries of changes. If region ends at a bol, do
18213 ;; not consider the last line to be in the region.
18214 (if (org-region-active-p)
18215 (setq beg (funcall skip-blanks (region-beginning))
18216 end (copy-marker (save-excursion
18217 (goto-char (region-end))
18218 (if (bolp) (point) (point-at-eol)))))
18219 (setq beg (funcall skip-blanks (point-at-bol))
18220 end (copy-marker (point-at-eol))))
18221 ;; Ensure inline tasks don't count as headings.
18222 (org-with-limited-levels
18223 (save-excursion
18224 (goto-char beg)
18225 (cond
18226 ;; Case 1. Started at an heading: de-star headings.
18227 ((org-on-heading-p)
18228 (while (< (point) end)
18229 (when (org-on-heading-p t)
18230 (looking-at org-outline-regexp) (replace-match ""))
18231 (forward-line)))
18232 ;; Case 2. Started at an item: change items into headlines.
18233 ;; One star will be added by `org-list-to-subtree'.
18234 ((org-at-item-p)
18235 (let* ((stars (make-string
18236 (if nstars
18237 ;; subtract the star that will be added again by
18238 ;; `org-list-to-subtree'
18239 (1- (prefix-numeric-value current-prefix-arg))
18240 (or (org-current-level) 0))
18241 ?*))
18242 (add-stars
18243 (cond (nstars "") ; stars from prefix only
18244 ((equal stars "") "") ; before first heading
18245 (org-odd-levels-only "*") ; inside heading, odd
18246 (t "")))) ; inside heading, oddeven
18247 (while (< (point) end)
18248 (when (org-at-item-p)
18249 ;; Pay attention to cases when region ends before list.
18250 (let* ((struct (org-list-struct))
18251 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
18252 (save-restriction
18253 (narrow-to-region (point) list-end)
18254 (insert
18255 (org-list-to-subtree
18256 (org-list-parse-list t)
18257 '(:istart (concat stars add-stars (funcall get-stars depth))
18258 :icount (concat stars add-stars (funcall get-stars depth))))))))
18259 (forward-line))))
18260 ;; Case 3. Started at normal text: make every line an heading,
18261 ;; skipping headlines and items.
18262 (t (let* ((stars (make-string
18263 (if nstars
18264 (prefix-numeric-value current-prefix-arg)
18265 (or (org-current-level) 0))
18266 ?*))
18267 (add-stars
18268 (cond (nstars "") ; stars from prefix only
18269 ((equal stars "") "*") ; before first heading
18270 (org-odd-levels-only "**") ; inside heading, odd
18271 (t "*"))) ; inside heading, oddeven
18272 (rpl (concat stars add-stars " ")))
18273 (while (< (point) end)
18274 (when (and (not (org-on-heading-p)) (not (org-at-item-p))
18275 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
18276 (replace-match (concat rpl (match-string 2))))
18277 (forward-line)))))))))
18279 (defun org-meta-return (&optional arg)
18280 "Insert a new heading or wrap a region in a table.
18281 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
18282 See the individual commands for more information."
18283 (interactive "P")
18284 (cond
18285 ((run-hook-with-args-until-success 'org-metareturn-hook))
18286 ((org-at-table-p)
18287 (call-interactively 'org-table-wrap-region))
18288 (t (call-interactively 'org-insert-heading))))
18290 ;;; Menu entries
18292 ;; Define the Org-mode menus
18293 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
18294 '("Tbl"
18295 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
18296 ["Next Field" org-cycle (org-at-table-p)]
18297 ["Previous Field" org-shifttab (org-at-table-p)]
18298 ["Next Row" org-return (org-at-table-p)]
18299 "--"
18300 ["Blank Field" org-table-blank-field (org-at-table-p)]
18301 ["Edit Field" org-table-edit-field (org-at-table-p)]
18302 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
18303 "--"
18304 ("Column"
18305 ["Move Column Left" org-metaleft (org-at-table-p)]
18306 ["Move Column Right" org-metaright (org-at-table-p)]
18307 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
18308 ["Insert Column" org-shiftmetaright (org-at-table-p)])
18309 ("Row"
18310 ["Move Row Up" org-metaup (org-at-table-p)]
18311 ["Move Row Down" org-metadown (org-at-table-p)]
18312 ["Delete Row" org-shiftmetaup (org-at-table-p)]
18313 ["Insert Row" org-shiftmetadown (org-at-table-p)]
18314 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
18315 "--"
18316 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
18317 ("Rectangle"
18318 ["Copy Rectangle" org-copy-special (org-at-table-p)]
18319 ["Cut Rectangle" org-cut-special (org-at-table-p)]
18320 ["Paste Rectangle" org-paste-special (org-at-table-p)]
18321 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
18322 "--"
18323 ("Calculate"
18324 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
18325 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
18326 ["Edit Formulas" org-edit-special (org-at-table-p)]
18327 "--"
18328 ["Recalculate line" org-table-recalculate (org-at-table-p)]
18329 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
18330 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
18331 "--"
18332 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
18333 "--"
18334 ["Sum Column/Rectangle" org-table-sum
18335 (or (org-at-table-p) (org-region-active-p))]
18336 ["Which Column?" org-table-current-column (org-at-table-p)])
18337 ["Debug Formulas"
18338 org-table-toggle-formula-debugger
18339 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
18340 ["Show Col/Row Numbers"
18341 org-table-toggle-coordinate-overlays
18342 :style toggle
18343 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
18344 "--"
18345 ["Create" org-table-create (and (not (org-at-table-p))
18346 org-enable-table-editor)]
18347 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
18348 ["Import from File" org-table-import (not (org-at-table-p))]
18349 ["Export to File" org-table-export (org-at-table-p)]
18350 "--"
18351 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
18353 (easy-menu-define org-org-menu org-mode-map "Org menu"
18354 '("Org"
18355 ("Show/Hide"
18356 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
18357 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
18358 ["Sparse Tree..." org-sparse-tree t]
18359 ["Reveal Context" org-reveal t]
18360 ["Show All" show-all t]
18361 "--"
18362 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
18363 "--"
18364 ["New Heading" org-insert-heading t]
18365 ("Navigate Headings"
18366 ["Up" outline-up-heading t]
18367 ["Next" outline-next-visible-heading t]
18368 ["Previous" outline-previous-visible-heading t]
18369 ["Next Same Level" outline-forward-same-level t]
18370 ["Previous Same Level" outline-backward-same-level t]
18371 "--"
18372 ["Jump" org-goto t])
18373 ("Edit Structure"
18374 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
18375 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
18376 "--"
18377 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
18378 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
18379 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
18380 "--"
18381 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
18382 "--"
18383 ["Copy visible text" org-copy-visible t]
18384 "--"
18385 ["Promote Heading" org-metaleft (not (org-at-table-p))]
18386 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
18387 ["Demote Heading" org-metaright (not (org-at-table-p))]
18388 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
18389 "--"
18390 ["Sort Region/Children" org-sort (not (org-at-table-p))]
18391 "--"
18392 ["Convert to odd levels" org-convert-to-odd-levels t]
18393 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
18394 ("Editing"
18395 ["Emphasis..." org-emphasize t]
18396 ["Edit Source Example" org-edit-special t]
18397 "--"
18398 ["Footnote new/jump" org-footnote-action t]
18399 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
18400 ("Archive"
18401 ["Archive (default method)" org-archive-subtree-default t]
18402 "--"
18403 ["Move Subtree to Archive file" org-advertized-archive-subtree t]
18404 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
18405 ["Move subtree to Archive sibling" org-archive-to-archive-sibling t]
18407 "--"
18408 ("Hyperlinks"
18409 ["Store Link (Global)" org-store-link t]
18410 ["Find existing link to here" org-occur-link-in-agenda-files t]
18411 ["Insert Link" org-insert-link t]
18412 ["Follow Link" org-open-at-point t]
18413 "--"
18414 ["Next link" org-next-link t]
18415 ["Previous link" org-previous-link t]
18416 "--"
18417 ["Descriptive Links"
18418 org-toggle-link-display
18419 :style radio
18420 :selected org-link-display-descriptive
18422 ["Literal Links"
18423 org-toggle-link-display
18424 :style radio
18425 :selected (not org-link-display-descriptive)])
18426 "--"
18427 ("TODO Lists"
18428 ["TODO/DONE/-" org-todo t]
18429 ("Select keyword"
18430 ["Next keyword" org-shiftright (org-on-heading-p)]
18431 ["Previous keyword" org-shiftleft (org-on-heading-p)]
18432 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
18433 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
18434 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
18435 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
18436 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
18437 "--"
18438 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
18439 :selected org-enforce-todo-dependencies :style toggle :active t]
18440 "Settings for tree at point"
18441 ["Do Children sequentially" org-toggle-ordered-property :style radio
18442 :selected (org-entry-get nil "ORDERED")
18443 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
18444 ["Do Children parallel" org-toggle-ordered-property :style radio
18445 :selected (not (org-entry-get nil "ORDERED"))
18446 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
18447 "--"
18448 ["Set Priority" org-priority t]
18449 ["Priority Up" org-shiftup t]
18450 ["Priority Down" org-shiftdown t]
18451 "--"
18452 ["Get news from all feeds" org-feed-update-all t]
18453 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
18454 ["Customize feeds" (customize-variable 'org-feed-alist) t])
18455 ("TAGS and Properties"
18456 ["Set Tags" org-set-tags-command t]
18457 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
18458 "--"
18459 ["Set property" org-set-property t]
18460 ["Column view of properties" org-columns t]
18461 ["Insert Column View DBlock" org-insert-columns-dblock t])
18462 ("Dates and Scheduling"
18463 ["Timestamp" org-time-stamp t]
18464 ["Timestamp (inactive)" org-time-stamp-inactive t]
18465 ("Change Date"
18466 ["1 Day Later" org-shiftright t]
18467 ["1 Day Earlier" org-shiftleft t]
18468 ["1 ... Later" org-shiftup t]
18469 ["1 ... Earlier" org-shiftdown t])
18470 ["Compute Time Range" org-evaluate-time-range t]
18471 ["Schedule Item" org-schedule t]
18472 ["Deadline" org-deadline t]
18473 "--"
18474 ["Custom time format" org-toggle-time-stamp-overlays
18475 :style radio :selected org-display-custom-times]
18476 "--"
18477 ["Goto Calendar" org-goto-calendar t]
18478 ["Date from Calendar" org-date-from-calendar t]
18479 "--"
18480 ["Start/Restart Timer" org-timer-start t]
18481 ["Pause/Continue Timer" org-timer-pause-or-continue t]
18482 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
18483 ["Insert Timer String" org-timer t]
18484 ["Insert Timer Item" org-timer-item t])
18485 ("Logging work"
18486 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
18487 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
18488 ["Clock out" org-clock-out t]
18489 ["Clock cancel" org-clock-cancel t]
18490 "--"
18491 ["Mark as default task" org-clock-mark-default-task t]
18492 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
18493 ["Goto running clock" org-clock-goto t]
18494 "--"
18495 ["Display times" org-clock-display t]
18496 ["Create clock table" org-clock-report t]
18497 "--"
18498 ["Record DONE time"
18499 (progn (setq org-log-done (not org-log-done))
18500 (message "Switching to %s will %s record a timestamp"
18501 (car org-done-keywords)
18502 (if org-log-done "automatically" "not")))
18503 :style toggle :selected org-log-done])
18504 "--"
18505 ["Agenda Command..." org-agenda t]
18506 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
18507 ("File List for Agenda")
18508 ("Special views current file"
18509 ["TODO Tree" org-show-todo-tree t]
18510 ["Check Deadlines" org-check-deadlines t]
18511 ["Timeline" org-timeline t]
18512 ["Tags/Property tree" org-match-sparse-tree t])
18513 "--"
18514 ["Export/Publish..." org-export t]
18515 ("LaTeX"
18516 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
18517 :selected org-cdlatex-mode]
18518 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
18519 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
18520 ["Modify math symbol" org-cdlatex-math-modify
18521 (org-inside-LaTeX-fragment-p)]
18522 ["Insert citation" org-reftex-citation t]
18523 "--"
18524 ["Template for BEAMER" org-insert-beamer-options-template t])
18525 "--"
18526 ("MobileOrg"
18527 ["Push Files and Views" org-mobile-push t]
18528 ["Get Captured and Flagged" org-mobile-pull t]
18529 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
18530 "--"
18531 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
18532 "--"
18533 ("Documentation"
18534 ["Show Version" org-version t]
18535 ["Info Documentation" org-info t])
18536 ("Customize"
18537 ["Browse Org Group" org-customize t]
18538 "--"
18539 ["Expand This Menu" org-create-customize-menu
18540 (fboundp 'customize-menu-create)])
18541 ["Send bug report" org-submit-bug-report t]
18542 "--"
18543 ("Refresh/Reload"
18544 ["Refresh setup current buffer" org-mode-restart t]
18545 ["Reload Org (after update)" org-reload t]
18546 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
18549 (defun org-info (&optional node)
18550 "Read documentation for Org-mode in the info system.
18551 With optional NODE, go directly to that node."
18552 (interactive)
18553 (info (format "(org)%s" (or node ""))))
18555 ;;;###autoload
18556 (defun org-submit-bug-report ()
18557 "Submit a bug report on Org-mode via mail.
18559 Don't hesitate to report any problems or inaccurate documentation.
18561 If you don't have setup sending mail from (X)Emacs, please copy the
18562 output buffer into your mail program, as it gives us important
18563 information about your Org-mode version and configuration."
18564 (interactive)
18565 (require 'reporter)
18566 (org-load-modules-maybe)
18567 (org-require-autoloaded-modules)
18568 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
18569 (reporter-submit-bug-report
18570 "emacs-orgmode@gnu.org"
18571 (org-version)
18572 (let (list)
18573 (save-window-excursion
18574 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
18575 (delete-other-windows)
18576 (erase-buffer)
18577 (insert "You are about to submit a bug report to the Org-mode mailing list.
18579 We would like to add your full Org-mode and Outline configuration to the
18580 bug report. This greatly simplifies the work of the maintainer and
18581 other experts on the mailing list.
18583 HOWEVER, some variables you have customized may contain private
18584 information. The names of customers, colleagues, or friends, might
18585 appear in the form of file names, tags, todo states, or search strings.
18586 If you answer yes to the prompt, you might want to check and remove
18587 such private information before sending the email.")
18588 (add-text-properties (point-min) (point-max) '(face org-warning))
18589 (when (yes-or-no-p "Include your Org-mode configuration ")
18590 (mapatoms
18591 (lambda (v)
18592 (and (boundp v)
18593 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
18594 (or (and (symbol-value v)
18595 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
18596 (and
18597 (get v 'custom-type) (get v 'standard-value)
18598 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
18599 (push v list)))))
18600 (kill-buffer (get-buffer "*Warn about privacy*"))
18601 list))
18602 nil nil
18603 "Remember to cover the basics, that is, what you expected to happen and
18604 what in fact did happen. You don't know how to make a good report? See
18606 http://orgmode.org/manual/Feedback.html#Feedback
18608 Your bug report will be posted to the Org-mode mailing list.
18609 ------------------------------------------------------------------------")
18610 (save-excursion
18611 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
18612 (replace-match "\\1Bug: \\3 [\\2]")))))
18615 (defun org-install-agenda-files-menu ()
18616 (let ((bl (buffer-list)))
18617 (save-excursion
18618 (while bl
18619 (set-buffer (pop bl))
18620 (if (org-mode-p) (setq bl nil)))
18621 (when (org-mode-p)
18622 (easy-menu-change
18623 '("Org") "File List for Agenda"
18624 (append
18625 (list
18626 ["Edit File List" (org-edit-agenda-file-list) t]
18627 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
18628 ["Remove Current File from List" org-remove-file t]
18629 ["Cycle through agenda files" org-cycle-agenda-files t]
18630 ["Occur in all agenda files" org-occur-in-agenda-files t]
18631 "--")
18632 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
18634 ;;;; Documentation
18636 ;;;###autoload
18637 (defun org-require-autoloaded-modules ()
18638 (interactive)
18639 (mapc 'require
18640 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
18641 org-docbook org-exp org-html org-icalendar
18642 org-id org-latex
18643 org-publish org-remember org-table
18644 org-timer org-xoxo)))
18646 ;;;###autoload
18647 (defun org-reload (&optional uncompiled)
18648 "Reload all org lisp files.
18649 With prefix arg UNCOMPILED, load the uncompiled versions."
18650 (interactive "P")
18651 (require 'find-func)
18652 (let* ((file-re "^\\(org\\|orgtbl\\)\\(\\.el\\|-.*\\.el\\)")
18653 (dir-org (file-name-directory (org-find-library-name "org")))
18654 (dir-org-contrib (ignore-errors
18655 (file-name-directory
18656 (org-find-library-name "org-contribdir"))))
18657 (babel-files
18658 (mapcar (lambda (el) (concat "ob" (when el (format "-%s" el)) ".el"))
18659 (append (list nil "comint" "eval" "exp" "keys"
18660 "lob" "ref" "table" "tangle")
18661 (delq nil
18662 (mapcar
18663 (lambda (lang)
18664 (when (cdr lang) (symbol-name (car lang))))
18665 org-babel-load-languages)))))
18666 (files
18667 (append (directory-files dir-org t file-re)
18668 babel-files
18669 (and dir-org-contrib
18670 (directory-files dir-org-contrib t file-re))))
18671 (remove-re (concat (if (featurep 'xemacs)
18672 "org-colview" "org-colview-xemacs")
18673 "\\'")))
18674 (setq files (mapcar 'file-name-sans-extension files))
18675 (setq files (mapcar
18676 (lambda (x) (if (string-match remove-re x) nil x))
18677 files))
18678 (setq files (delq nil files))
18679 (mapc
18680 (lambda (f)
18681 (when (featurep (intern (file-name-nondirectory f)))
18682 (if (and (not uncompiled)
18683 (file-exists-p (concat f ".elc")))
18684 (load (concat f ".elc") nil nil t)
18685 (load (concat f ".el") nil nil t))))
18686 files))
18687 (org-version))
18689 ;;;###autoload
18690 (defun org-customize ()
18691 "Call the customize function with org as argument."
18692 (interactive)
18693 (org-load-modules-maybe)
18694 (org-require-autoloaded-modules)
18695 (customize-browse 'org))
18697 (defun org-create-customize-menu ()
18698 "Create a full customization menu for Org-mode, insert it into the menu."
18699 (interactive)
18700 (org-load-modules-maybe)
18701 (org-require-autoloaded-modules)
18702 (if (fboundp 'customize-menu-create)
18703 (progn
18704 (easy-menu-change
18705 '("Org") "Customize"
18706 `(["Browse Org group" org-customize t]
18707 "--"
18708 ,(customize-menu-create 'org)
18709 ["Set" Custom-set t]
18710 ["Save" Custom-save t]
18711 ["Reset to Current" Custom-reset-current t]
18712 ["Reset to Saved" Custom-reset-saved t]
18713 ["Reset to Standard Settings" Custom-reset-standard t]))
18714 (message "\"Org\"-menu now contains full customization menu"))
18715 (error "Cannot expand menu (outdated version of cus-edit.el)")))
18717 ;;;; Miscellaneous stuff
18719 ;;; Generally useful functions
18721 (defun org-get-at-bol (property)
18722 "Get text property PROPERTY at beginning of line."
18723 (get-text-property (point-at-bol) property))
18725 (defun org-find-text-property-in-string (prop s)
18726 "Return the first non-nil value of property PROP in string S."
18727 (or (get-text-property 0 prop s)
18728 (get-text-property (or (next-single-property-change 0 prop s) 0)
18729 prop s)))
18731 (defun org-display-warning (message) ;; Copied from Emacs-Muse
18732 "Display the given MESSAGE as a warning."
18733 (if (fboundp 'display-warning)
18734 (display-warning 'org message
18735 (if (featurep 'xemacs) 'warning :warning))
18736 (let ((buf (get-buffer-create "*Org warnings*")))
18737 (with-current-buffer buf
18738 (goto-char (point-max))
18739 (insert "Warning (Org): " message)
18740 (unless (bolp)
18741 (newline)))
18742 (display-buffer buf)
18743 (sit-for 0))))
18745 (defun org-eval (form)
18746 "Eval FORM and return result."
18747 (condition-case error
18748 (eval form)
18749 (error (format "%%![Error: %s]" error))))
18751 (defun org-in-commented-line ()
18752 "Is point in a line starting with `#'?"
18753 (equal (char-after (point-at-bol)) ?#))
18755 (defun org-in-indented-comment-line ()
18756 "Is point in a line starting with `#' after some white space?"
18757 (save-excursion
18758 (save-match-data
18759 (goto-char (point-at-bol))
18760 (looking-at "[ \t]*#"))))
18762 (defun org-in-verbatim-emphasis ()
18763 (save-match-data
18764 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
18766 (defun org-goto-marker-or-bmk (marker &optional bookmark)
18767 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
18768 (if (and marker (marker-buffer marker)
18769 (buffer-live-p (marker-buffer marker)))
18770 (progn
18771 (org-pop-to-buffer-same-window (marker-buffer marker))
18772 (if (or (> marker (point-max)) (< marker (point-min)))
18773 (widen))
18774 (goto-char marker)
18775 (org-show-context 'org-goto))
18776 (if bookmark
18777 (bookmark-jump bookmark)
18778 (error "Cannot find location"))))
18780 (defun org-quote-csv-field (s)
18781 "Quote field for inclusion in CSV material."
18782 (if (string-match "[\",]" s)
18783 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
18786 (defun org-force-self-insert (N)
18787 "Needed to enforce self-insert under remapping."
18788 (interactive "p")
18789 (self-insert-command N))
18791 (defun org-string-width (s)
18792 "Compute width of string, ignoring invisible characters.
18793 This ignores character with invisibility property `org-link', and also
18794 characters with property `org-cwidth', because these will become invisible
18795 upon the next fontification round."
18796 (let (b l)
18797 (when (or (eq t buffer-invisibility-spec)
18798 (assq 'org-link buffer-invisibility-spec))
18799 (while (setq b (text-property-any 0 (length s)
18800 'invisible 'org-link s))
18801 (setq s (concat (substring s 0 b)
18802 (substring s (or (next-single-property-change
18803 b 'invisible s) (length s)))))))
18804 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
18805 (setq s (concat (substring s 0 b)
18806 (substring s (or (next-single-property-change
18807 b 'org-cwidth s) (length s))))))
18808 (setq l (string-width s) b -1)
18809 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
18810 (setq l (- l (get-text-property b 'org-dwidth-n s))))
18813 (defun org-shorten-string (s maxlength)
18814 "Shorten string S so tht it is no longer than MAXLENGTH characters.
18815 If the string is shorter or has length MAXLENGTH, just return the
18816 original string. If it is longer, the functions finds a space in the
18817 string, breaks this string off at that locations and adds three dots
18818 as ellipsis. Including the ellipsis, the string will not be longer
18819 than MAXLENGTH. If finding a good breaking point in the string does
18820 not work, the string is just chopped off in the middle of a word
18821 if necessary."
18822 (if (<= (length s) maxlength)
18824 (let* ((n (max (- maxlength 4) 1))
18825 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
18826 (if (string-match re s)
18827 (concat (match-string 1 s) "...")
18828 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
18830 (defun org-get-indentation (&optional line)
18831 "Get the indentation of the current line, interpreting tabs.
18832 When LINE is given, assume it represents a line and compute its indentation."
18833 (if line
18834 (if (string-match "^ *" (org-remove-tabs line))
18835 (match-end 0))
18836 (save-excursion
18837 (beginning-of-line 1)
18838 (skip-chars-forward " \t")
18839 (current-column))))
18841 (defun org-get-string-indentation (s)
18842 "What indentation has S due to SPACE and TAB at the beginning of the string?"
18843 (let ((n -1) (i 0) (w tab-width) c)
18844 (catch 'exit
18845 (while (< (setq n (1+ n)) (length s))
18846 (setq c (aref s n))
18847 (cond ((= c ?\ ) (setq i (1+ i)))
18848 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
18849 (t (throw 'exit t)))))
18852 (defun org-remove-tabs (s &optional width)
18853 "Replace tabulators in S with spaces.
18854 Assumes that s is a single line, starting in column 0."
18855 (setq width (or width tab-width))
18856 (while (string-match "\t" s)
18857 (setq s (replace-match
18858 (make-string
18859 (- (* width (/ (+ (match-beginning 0) width) width))
18860 (match-beginning 0)) ?\ )
18861 t t s)))
18864 (defun org-fix-indentation (line ind)
18865 "Fix indentation in LINE.
18866 IND is a cons cell with target and minimum indentation.
18867 If the current indentation in LINE is smaller than the minimum,
18868 leave it alone. If it is larger than ind, set it to the target."
18869 (let* ((l (org-remove-tabs line))
18870 (i (org-get-indentation l))
18871 (i1 (car ind)) (i2 (cdr ind)))
18872 (if (>= i i2) (setq l (substring line i2)))
18873 (if (> i1 0)
18874 (concat (make-string i1 ?\ ) l)
18875 l)))
18877 (defun org-remove-indentation (code &optional n)
18878 "Remove the maximum common indentation from the lines in CODE.
18879 N may optionally be the number of spaces to remove."
18880 (with-temp-buffer
18881 (insert code)
18882 (org-do-remove-indentation n)
18883 (buffer-string)))
18885 (defun org-do-remove-indentation (&optional n)
18886 "Remove the maximum common indentation from the buffer."
18887 (untabify (point-min) (point-max))
18888 (let ((min 10000) re)
18889 (if n
18890 (setq min n)
18891 (goto-char (point-min))
18892 (while (re-search-forward "^ *[^ \n]" nil t)
18893 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
18894 (unless (or (= min 0) (= min 10000))
18895 (setq re (format "^ \\{%d\\}" min))
18896 (goto-char (point-min))
18897 (while (re-search-forward re nil t)
18898 (replace-match "")
18899 (end-of-line 1))
18900 min)))
18902 (defun org-fill-template (template alist)
18903 "Find each %key of ALIST in TEMPLATE and replace it."
18904 (let ((case-fold-search nil)
18905 entry key value)
18906 (setq alist (sort (copy-sequence alist)
18907 (lambda (a b) (< (length (car a)) (length (car b))))))
18908 (while (setq entry (pop alist))
18909 (setq template
18910 (replace-regexp-in-string
18911 (concat "%" (regexp-quote (car entry)))
18912 (cdr entry) template t t)))
18913 template))
18915 (defun org-base-buffer (buffer)
18916 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
18917 (if (not buffer)
18918 buffer
18919 (or (buffer-base-buffer buffer)
18920 buffer)))
18922 (defun org-trim (s)
18923 "Remove whitespace at beginning and end of string."
18924 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
18925 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
18928 (defun org-wrap (string &optional width lines)
18929 "Wrap string to either a number of lines, or a width in characters.
18930 If WIDTH is non-nil, the string is wrapped to that width, however many lines
18931 that costs. If there is a word longer than WIDTH, the text is actually
18932 wrapped to the length of that word.
18933 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
18934 many lines, whatever width that takes.
18935 The return value is a list of lines, without newlines at the end."
18936 (let* ((words (org-split-string string "[ \t\n]+"))
18937 (maxword (apply 'max (mapcar 'org-string-width words)))
18938 w ll)
18939 (cond (width
18940 (org-do-wrap words (max maxword width)))
18941 (lines
18942 (setq w maxword)
18943 (setq ll (org-do-wrap words maxword))
18944 (if (<= (length ll) lines)
18946 (setq ll words)
18947 (while (> (length ll) lines)
18948 (setq w (1+ w))
18949 (setq ll (org-do-wrap words w)))
18950 ll))
18951 (t (error "Cannot wrap this")))))
18953 (defun org-do-wrap (words width)
18954 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
18955 (let (lines line)
18956 (while words
18957 (setq line (pop words))
18958 (while (and words (< (+ (length line) (length (car words))) width))
18959 (setq line (concat line " " (pop words))))
18960 (setq lines (push line lines)))
18961 (nreverse lines)))
18963 (defun org-split-string (string &optional separators)
18964 "Splits STRING into substrings at SEPARATORS.
18965 No empty strings are returned if there are matches at the beginning
18966 and end of string."
18967 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
18968 (start 0)
18969 notfirst
18970 (list nil))
18971 (while (and (string-match rexp string
18972 (if (and notfirst
18973 (= start (match-beginning 0))
18974 (< start (length string)))
18975 (1+ start) start))
18976 (< (match-beginning 0) (length string)))
18977 (setq notfirst t)
18978 (or (eq (match-beginning 0) 0)
18979 (and (eq (match-beginning 0) (match-end 0))
18980 (eq (match-beginning 0) start))
18981 (setq list
18982 (cons (substring string start (match-beginning 0))
18983 list)))
18984 (setq start (match-end 0)))
18985 (or (eq start (length string))
18986 (setq list
18987 (cons (substring string start)
18988 list)))
18989 (nreverse list)))
18991 (defun org-quote-vert (s)
18992 "Replace \"|\" with \"\\vert\"."
18993 (while (string-match "|" s)
18994 (setq s (replace-match "\\vert" t t s)))
18997 (defun org-uuidgen-p (s)
18998 "Is S an ID created by UUIDGEN?"
18999 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
19001 (defun org-context ()
19002 "Return a list of contexts of the current cursor position.
19003 If several contexts apply, all are returned.
19004 Each context entry is a list with a symbol naming the context, and
19005 two positions indicating start and end of the context. Possible
19006 contexts are:
19008 :headline anywhere in a headline
19009 :headline-stars on the leading stars in a headline
19010 :todo-keyword on a TODO keyword (including DONE) in a headline
19011 :tags on the TAGS in a headline
19012 :priority on the priority cookie in a headline
19013 :item on the first line of a plain list item
19014 :item-bullet on the bullet/number of a plain list item
19015 :checkbox on the checkbox in a plain list item
19016 :table in an org-mode table
19017 :table-special on a special filed in a table
19018 :table-table in a table.el table
19019 :link on a hyperlink
19020 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
19021 :target on a <<target>>
19022 :radio-target on a <<<radio-target>>>
19023 :latex-fragment on a LaTeX fragment
19024 :latex-preview on a LaTeX fragment with overlayed preview image
19026 This function expects the position to be visible because it uses font-lock
19027 faces as a help to recognize the following contexts: :table-special, :link,
19028 and :keyword."
19029 (let* ((f (get-text-property (point) 'face))
19030 (faces (if (listp f) f (list f)))
19031 (p (point)) clist o)
19032 ;; First the large context
19033 (cond
19034 ((org-on-heading-p t)
19035 (push (list :headline (point-at-bol) (point-at-eol)) clist)
19036 (when (progn
19037 (beginning-of-line 1)
19038 (looking-at org-todo-line-tags-regexp))
19039 (push (org-point-in-group p 1 :headline-stars) clist)
19040 (push (org-point-in-group p 2 :todo-keyword) clist)
19041 (push (org-point-in-group p 4 :tags) clist))
19042 (goto-char p)
19043 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
19044 (if (looking-at "\\[#[A-Z0-9]\\]")
19045 (push (org-point-in-group p 0 :priority) clist)))
19047 ((org-at-item-p)
19048 (push (org-point-in-group p 2 :item-bullet) clist)
19049 (push (list :item (point-at-bol)
19050 (save-excursion (org-end-of-item) (point)))
19051 clist)
19052 (and (org-at-item-checkbox-p)
19053 (push (org-point-in-group p 0 :checkbox) clist)))
19055 ((org-at-table-p)
19056 (push (list :table (org-table-begin) (org-table-end)) clist)
19057 (if (memq 'org-formula faces)
19058 (push (list :table-special
19059 (previous-single-property-change p 'face)
19060 (next-single-property-change p 'face)) clist)))
19061 ((org-at-table-p 'any)
19062 (push (list :table-table) clist)))
19063 (goto-char p)
19065 ;; Now the small context
19066 (cond
19067 ((org-at-timestamp-p)
19068 (push (org-point-in-group p 0 :timestamp) clist))
19069 ((memq 'org-link faces)
19070 (push (list :link
19071 (previous-single-property-change p 'face)
19072 (next-single-property-change p 'face)) clist))
19073 ((memq 'org-special-keyword faces)
19074 (push (list :keyword
19075 (previous-single-property-change p 'face)
19076 (next-single-property-change p 'face)) clist))
19077 ((org-on-target-p)
19078 (push (org-point-in-group p 0 :target) clist)
19079 (goto-char (1- (match-beginning 0)))
19080 (if (looking-at org-radio-target-regexp)
19081 (push (org-point-in-group p 0 :radio-target) clist))
19082 (goto-char p))
19083 ((setq o (car (delq nil
19084 (mapcar
19085 (lambda (x)
19086 (if (memq x org-latex-fragment-image-overlays) x))
19087 (overlays-at (point))))))
19088 (push (list :latex-fragment
19089 (overlay-start o) (overlay-end o)) clist)
19090 (push (list :latex-preview
19091 (overlay-start o) (overlay-end o)) clist))
19092 ((org-inside-LaTeX-fragment-p)
19093 ;; FIXME: positions wrong.
19094 (push (list :latex-fragment (point) (point)) clist)))
19096 (setq clist (nreverse (delq nil clist)))
19097 clist))
19099 ;; FIXME: Compare with at-regexp-p Do we need both?
19100 (defun org-in-regexp (re &optional nlines visually)
19101 "Check if point is inside a match of regexp.
19102 Normally only the current line is checked, but you can include NLINES extra
19103 lines both before and after point into the search.
19104 If VISUALLY is set, require that the cursor is not after the match but
19105 really on, so that the block visually is on the match."
19106 (catch 'exit
19107 (let ((pos (point))
19108 (eol (point-at-eol (+ 1 (or nlines 0))))
19109 (inc (if visually 1 0)))
19110 (save-excursion
19111 (beginning-of-line (- 1 (or nlines 0)))
19112 (while (re-search-forward re eol t)
19113 (if (and (<= (match-beginning 0) pos)
19114 (>= (+ inc (match-end 0)) pos))
19115 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
19117 (defun org-at-regexp-p (regexp)
19118 "Is point inside a match of REGEXP in the current line?"
19119 (catch 'exit
19120 (save-excursion
19121 (let ((pos (point)) (end (point-at-eol)))
19122 (beginning-of-line 1)
19123 (while (re-search-forward regexp end t)
19124 (if (and (<= (match-beginning 0) pos)
19125 (>= (match-end 0) pos))
19126 (throw 'exit t)))
19127 nil))))
19129 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
19130 "Non-nil when point is between matches of START-RE and END-RE.
19132 Also return a non-nil value when point is on one of the matches.
19134 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
19135 buffer positions. Default values are the positions of headlines
19136 surrounding the point.
19138 The functions returns a cons cell whose car (resp. cdr) is the
19139 position before START-RE (resp. after END-RE)."
19140 (save-match-data
19141 (let ((pos (point))
19142 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
19143 (limit-down (or lim-down (save-excursion (outline-next-heading))))
19144 beg end)
19145 (save-excursion
19146 ;; Point is on a block when on START-RE or if START-RE can be
19147 ;; found before it...
19148 (and (or (org-at-regexp-p start-re)
19149 (re-search-backward start-re limit-up t))
19150 (setq beg (match-beginning 0))
19151 ;; ... and END-RE after it...
19152 (goto-char (match-end 0))
19153 (re-search-forward end-re limit-down t)
19154 (> (setq end (match-end 0)) pos)
19155 ;; ... without another START-RE in-between.
19156 (goto-char (match-beginning 0))
19157 (not (re-search-backward start-re (1+ beg) t))
19158 ;; Return value.
19159 (cons beg end))))))
19161 (defun org-in-block-p (names)
19162 "Is point inside any block whose name belongs to NAMES?
19164 NAMES is a list of strings containing names of blocks."
19165 (save-match-data
19166 (catch 'exit
19167 (let ((case-fold-search t)
19168 (lim-up (save-excursion (outline-previous-heading)))
19169 (lim-down (save-excursion (outline-next-heading))))
19170 (mapc (lambda (name)
19171 (let ((n (regexp-quote name)))
19172 (when (org-between-regexps-p
19173 (concat "^[ \t]*#\\+begin_" n)
19174 (concat "^[ \t]*#\\+end_" n)
19175 lim-up lim-down)
19176 (throw 'exit t))))
19177 names))
19178 nil)))
19180 (defun org-occur-in-agenda-files (regexp &optional nlines)
19181 "Call `multi-occur' with buffers for all agenda files."
19182 (interactive "sOrg-files matching: \np")
19183 (let* ((files (org-agenda-files))
19184 (tnames (mapcar 'file-truename files))
19185 (extra org-agenda-text-search-extra-files)
19187 (when (eq (car extra) 'agenda-archives)
19188 (setq extra (cdr extra))
19189 (setq files (org-add-archive-files files)))
19190 (while (setq f (pop extra))
19191 (unless (member (file-truename f) tnames)
19192 (add-to-list 'files f 'append)
19193 (add-to-list 'tnames (file-truename f) 'append)))
19194 (multi-occur
19195 (mapcar (lambda (x)
19196 (with-current-buffer
19197 (or (get-file-buffer x) (find-file-noselect x))
19198 (widen)
19199 (current-buffer)))
19200 files)
19201 regexp)))
19203 (if (boundp 'occur-mode-find-occurrence-hook)
19204 ;; Emacs 23
19205 (add-hook 'occur-mode-find-occurrence-hook
19206 (lambda ()
19207 (when (org-mode-p)
19208 (org-reveal))))
19209 ;; Emacs 22
19210 (defadvice occur-mode-goto-occurrence
19211 (after org-occur-reveal activate)
19212 (and (org-mode-p) (org-reveal)))
19213 (defadvice occur-mode-goto-occurrence-other-window
19214 (after org-occur-reveal activate)
19215 (and (org-mode-p) (org-reveal)))
19216 (defadvice occur-mode-display-occurrence
19217 (after org-occur-reveal activate)
19218 (when (org-mode-p)
19219 (let ((pos (occur-mode-find-occurrence)))
19220 (with-current-buffer (marker-buffer pos)
19221 (save-excursion
19222 (goto-char pos)
19223 (org-reveal)))))))
19225 (defun org-occur-link-in-agenda-files ()
19226 "Create a link and search for it in the agendas.
19227 The link is not stored in `org-stored-links', it is just created
19228 for the search purpose."
19229 (interactive)
19230 (let ((link (condition-case nil
19231 (org-store-link nil)
19232 (error "Unable to create a link to here"))))
19233 (org-occur-in-agenda-files (regexp-quote link))))
19235 (defun org-uniquify (list)
19236 "Remove duplicate elements from LIST."
19237 (let (res)
19238 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
19239 res))
19241 (defun org-delete-all (elts list)
19242 "Remove all elements in ELTS from LIST."
19243 (while elts
19244 (setq list (delete (pop elts) list)))
19245 list)
19247 (defun org-count (cl-item cl-seq)
19248 "Count the number of occurrences of ITEM in SEQ.
19249 Taken from `count' in cl-seq.el with all keyword arguments removed."
19250 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
19251 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
19252 (while (< cl-start cl-end)
19253 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
19254 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
19255 (setq cl-start (1+ cl-start)))
19256 cl-count))
19258 (defun org-remove-if (predicate seq)
19259 "Remove everything from SEQ that fulfills PREDICATE."
19260 (let (res e)
19261 (while seq
19262 (setq e (pop seq))
19263 (if (not (funcall predicate e)) (push e res)))
19264 (nreverse res)))
19266 (defun org-remove-if-not (predicate seq)
19267 "Remove everything from SEQ that does not fulfill PREDICATE."
19268 (let (res e)
19269 (while seq
19270 (setq e (pop seq))
19271 (if (funcall predicate e) (push e res)))
19272 (nreverse res)))
19274 (defun org-back-over-empty-lines ()
19275 "Move backwards over whitespace, to the beginning of the first empty line.
19276 Returns the number of empty lines passed."
19277 (let ((pos (point)))
19278 (if (cdr (assoc 'heading org-blank-before-new-entry))
19279 (skip-chars-backward " \t\n\r")
19280 (unless (eobp)
19281 (forward-line -1)))
19282 (beginning-of-line 2)
19283 (goto-char (min (point) pos))
19284 (count-lines (point) pos)))
19286 (defun org-skip-whitespace ()
19287 (skip-chars-forward " \t\n\r"))
19289 (defun org-point-in-group (point group &optional context)
19290 "Check if POINT is in match-group GROUP.
19291 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
19292 match. If the match group does not exist or point is not inside it,
19293 return nil."
19294 (and (match-beginning group)
19295 (>= point (match-beginning group))
19296 (<= point (match-end group))
19297 (if context
19298 (list context (match-beginning group) (match-end group))
19299 t)))
19301 (defun org-switch-to-buffer-other-window (&rest args)
19302 "Switch to buffer in a second window on the current frame.
19303 In particular, do not allow pop-up frames.
19304 Returns the newly created buffer."
19305 (let (pop-up-frames special-display-buffer-names special-display-regexps
19306 special-display-function)
19307 (apply 'switch-to-buffer-other-window args)))
19309 (defun org-combine-plists (&rest plists)
19310 "Create a single property list from all plists in PLISTS.
19311 The process starts by copying the first list, and then setting properties
19312 from the other lists. Settings in the last list are the most significant
19313 ones and overrule settings in the other lists."
19314 (let ((rtn (copy-sequence (pop plists)))
19315 p v ls)
19316 (while plists
19317 (setq ls (pop plists))
19318 (while ls
19319 (setq p (pop ls) v (pop ls))
19320 (setq rtn (plist-put rtn p v))))
19321 rtn))
19323 (defun org-move-line-down (arg)
19324 "Move the current line down. With prefix argument, move it past ARG lines."
19325 (interactive "p")
19326 (let ((col (current-column))
19327 beg end pos)
19328 (beginning-of-line 1) (setq beg (point))
19329 (beginning-of-line 2) (setq end (point))
19330 (beginning-of-line (+ 1 arg))
19331 (setq pos (move-marker (make-marker) (point)))
19332 (insert (delete-and-extract-region beg end))
19333 (goto-char pos)
19334 (org-move-to-column col)))
19336 (defun org-move-line-up (arg)
19337 "Move the current line up. With prefix argument, move it past ARG lines."
19338 (interactive "p")
19339 (let ((col (current-column))
19340 beg end pos)
19341 (beginning-of-line 1) (setq beg (point))
19342 (beginning-of-line 2) (setq end (point))
19343 (beginning-of-line (- arg))
19344 (setq pos (move-marker (make-marker) (point)))
19345 (insert (delete-and-extract-region beg end))
19346 (goto-char pos)
19347 (org-move-to-column col)))
19349 (defun org-replace-escapes (string table)
19350 "Replace %-escapes in STRING with values in TABLE.
19351 TABLE is an association list with keys like \"%a\" and string values.
19352 The sequences in STRING may contain normal field width and padding information,
19353 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
19354 so values can contain further %-escapes if they are define later in TABLE."
19355 (let ((tbl (copy-alist table))
19356 (case-fold-search nil)
19357 (pchg 0)
19358 e re rpl)
19359 (while (setq e (pop tbl))
19360 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
19361 (when (and (cdr e) (string-match re (cdr e)))
19362 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
19363 (safe "SREF"))
19364 (add-text-properties 0 3 (list 'sref sref) safe)
19365 (setcdr e (replace-match safe t t (cdr e)))))
19366 (while (string-match re string)
19367 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
19368 (cdr e)))
19369 (setq string (replace-match rpl t t string))))
19370 (while (setq pchg (next-property-change pchg string))
19371 (let ((sref (get-text-property pchg 'sref string)))
19372 (when (and sref (string-match "SREF" string pchg))
19373 (setq string (replace-match sref t t string)))))
19374 string))
19376 (defun org-sublist (list start end)
19377 "Return a section of LIST, from START to END.
19378 Counting starts at 1."
19379 (let (rtn (c start))
19380 (setq list (nthcdr (1- start) list))
19381 (while (and list (<= c end))
19382 (push (pop list) rtn)
19383 (setq c (1+ c)))
19384 (nreverse rtn)))
19386 (defun org-find-base-buffer-visiting (file)
19387 "Like `find-buffer-visiting' but always return the base buffer and
19388 not an indirect buffer."
19389 (let ((buf (or (get-file-buffer file)
19390 (find-buffer-visiting file))))
19391 (if buf
19392 (or (buffer-base-buffer buf) buf)
19393 nil)))
19395 (defun org-image-file-name-regexp (&optional extensions)
19396 "Return regexp matching the file names of images.
19397 If EXTENSIONS is given, only match these."
19398 (if (and (not extensions) (fboundp 'image-file-name-regexp))
19399 (image-file-name-regexp)
19400 (let ((image-file-name-extensions
19401 (or extensions
19402 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
19403 "xbm" "xpm" "pbm" "pgm" "ppm"))))
19404 (concat "\\."
19405 (regexp-opt (nconc (mapcar 'upcase
19406 image-file-name-extensions)
19407 image-file-name-extensions)
19409 "\\'"))))
19411 (defun org-file-image-p (file &optional extensions)
19412 "Return non-nil if FILE is an image."
19413 (save-match-data
19414 (string-match (org-image-file-name-regexp extensions) file)))
19416 (defun org-get-cursor-date ()
19417 "Return the date at cursor in as a time.
19418 This works in the calendar and in the agenda, anywhere else it just
19419 returns the current time."
19420 (let (date day defd)
19421 (cond
19422 ((eq major-mode 'calendar-mode)
19423 (setq date (calendar-cursor-to-date)
19424 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
19425 ((eq major-mode 'org-agenda-mode)
19426 (setq day (get-text-property (point) 'day))
19427 (if day
19428 (setq date (calendar-gregorian-from-absolute day)
19429 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
19430 (nth 2 date))))))
19431 (or defd (current-time))))
19433 (defvar org-agenda-action-marker (make-marker)
19434 "Marker pointing to the entry for the next agenda action.")
19436 (defun org-mark-entry-for-agenda-action ()
19437 "Mark the current entry as target of an agenda action.
19438 Agenda actions are actions executed from the agenda with the key `k',
19439 which make use of the date at the cursor."
19440 (interactive)
19441 (move-marker org-agenda-action-marker
19442 (save-excursion (org-back-to-heading t) (point))
19443 (current-buffer))
19444 (message
19445 "Entry marked for action; press `k' at desired date in agenda or calendar"))
19447 (defun org-mark-subtree ()
19448 "Mark the current subtree.
19449 This puts point at the start of the current subtree, and mark at the end.
19451 If point is in an inline task, mark that task instead."
19452 (interactive)
19453 (let ((inline-task-p
19454 (and (featurep 'org-inlinetask)
19455 (org-inlinetask-in-task-p)))
19456 (beg))
19457 ;; Get beginning of subtree
19458 (cond
19459 (inline-task-p (org-inlinetask-goto-beginning))
19460 ((org-at-heading-p) (beginning-of-line))
19461 (t (org-with-limited-levels (outline-previous-visible-heading 1))))
19462 (setq beg (point))
19463 ;; Get end of it
19464 (if inline-task-p
19465 (org-inlinetask-goto-end)
19466 (org-end-of-subtree))
19467 ;; Mark zone
19468 (push-mark (point) nil t)
19469 (goto-char beg)))
19471 ;;; Paragraph filling stuff.
19472 ;; We want this to be just right, so use the full arsenal.
19474 (defun org-indent-line-function ()
19475 "Indent line depending on context."
19476 (interactive)
19477 (let* ((pos (point))
19478 (itemp (org-at-item-p))
19479 (case-fold-search t)
19480 (org-drawer-regexp (or org-drawer-regexp "\000"))
19481 (inline-task-p (and (featurep 'org-inlinetask)
19482 (org-inlinetask-in-task-p)))
19483 (inline-re (and inline-task-p
19484 (org-inlinetask-outline-regexp)))
19485 column)
19486 (beginning-of-line 1)
19487 (cond
19488 ;; Comments
19489 ((looking-at "# ") (setq column 0))
19490 ;; Headings
19491 ((looking-at org-outline-regexp) (setq column 0))
19492 ;; Included files
19493 ((looking-at "#\\+include:") (setq column 0))
19494 ;; Footnote definition
19495 ((looking-at org-footnote-definition-re) (setq column 0))
19496 ;; Literal examples
19497 ((looking-at "[ \t]*:\\( \\|$\\)")
19498 (setq column (org-get-indentation))) ; do nothing
19499 ;; Lists
19500 ((ignore-errors (goto-char (org-in-item-p)))
19501 (setq column (if itemp
19502 (org-get-indentation)
19503 (org-list-item-body-column (point))))
19504 (goto-char pos))
19505 ;; Drawers
19506 ((and (looking-at "[ \t]*:END:")
19507 (save-excursion (re-search-backward org-drawer-regexp nil t)))
19508 (save-excursion
19509 (goto-char (1- (match-beginning 1)))
19510 (setq column (current-column))))
19511 ;; Special blocks
19512 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
19513 (save-excursion
19514 (re-search-backward
19515 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
19516 (setq column (org-get-indentation (match-string 0))))
19517 ((and (not (looking-at "[ \t]*#\\+begin_"))
19518 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
19519 (save-excursion
19520 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
19521 (setq column
19522 (cond ((equal (downcase (match-string 1)) "src")
19523 ;; src blocks: let `org-edit-src-exit' handle them
19524 (org-get-indentation))
19525 ((equal (downcase (match-string 1)) "example")
19526 (max (org-get-indentation)
19527 (org-get-indentation (match-string 0))))
19529 (org-get-indentation (match-string 0))))))
19530 ;; This line has nothing special, look at the previous relevant
19531 ;; line to compute indentation
19533 (beginning-of-line 0)
19534 (while (and (not (bobp))
19535 (not (looking-at org-drawer-regexp))
19536 ;; When point started in an inline task, do not move
19537 ;; above task starting line.
19538 (not (and inline-task-p (looking-at inline-re)))
19539 ;; Skip drawers, blocks, empty lines, verbatim,
19540 ;; comments, tables, footnotes definitions, lists,
19541 ;; inline tasks.
19542 (or (and (looking-at "[ \t]*:END:")
19543 (re-search-backward org-drawer-regexp nil t))
19544 (and (looking-at "[ \t]*#\\+end_")
19545 (re-search-backward "[ \t]*#\\+begin_"nil t))
19546 (looking-at "[ \t]*[\n:#|]")
19547 (looking-at org-footnote-definition-re)
19548 (and (ignore-errors (goto-char (org-in-item-p)))
19549 (goto-char
19550 (org-list-get-top-point (org-list-struct))))
19551 (and (not inline-task-p)
19552 (featurep 'org-inlinetask)
19553 (org-inlinetask-in-task-p)
19554 (or (org-inlinetask-goto-beginning) t))))
19555 (beginning-of-line 0))
19556 (cond
19557 ;; There was an heading above.
19558 ((looking-at "\\*+[ \t]+")
19559 (if (not org-adapt-indentation)
19560 (setq column 0)
19561 (goto-char (match-end 0))
19562 (setq column (current-column))))
19563 ;; A drawer had started and is unfinished
19564 ((looking-at org-drawer-regexp)
19565 (goto-char (1- (match-beginning 1)))
19566 (setq column (current-column)))
19567 ;; Else, nothing noticeable found: get indentation and go on.
19568 (t (setq column (org-get-indentation))))))
19569 ;; Now apply indentation and move cursor accordingly
19570 (goto-char pos)
19571 (if (<= (current-column) (current-indentation))
19572 (org-indent-line-to column)
19573 (save-excursion (org-indent-line-to column)))
19574 ;; Special polishing for properties, see `org-property-format'
19575 (setq column (current-column))
19576 (beginning-of-line 1)
19577 (if (looking-at
19578 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
19579 (replace-match (concat (match-string 1)
19580 (format org-property-format
19581 (match-string 2) (match-string 3)))
19582 t t))
19583 (org-move-to-column column)))
19585 (defvar org-adaptive-fill-regexp-backup adaptive-fill-regexp
19586 "Variable to store copy of `adaptive-fill-regexp'.
19587 Since `adaptive-fill-regexp' is set to never match, we need to
19588 store a backup of its value before entering `org-mode' so that
19589 the functionality can be provided as a fall-back.")
19591 (defun org-set-autofill-regexps ()
19592 (interactive)
19593 ;; In the paragraph separator we include headlines, because filling
19594 ;; text in a line directly attached to a headline would otherwise
19595 ;; fill the headline as well.
19596 (org-set-local 'comment-start-skip "^#+[ \t]*")
19597 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|#]")
19598 ;; The paragraph starter includes hand-formatted lists.
19599 (org-set-local
19600 'paragraph-start
19601 (concat
19602 "\f" "\\|"
19603 "[ ]*$" "\\|"
19604 org-outline-regexp "\\|"
19605 "[ \t]*#" "\\|"
19606 (org-item-re) "\\|"
19607 "[ \t]*[:|]" "\\|"
19608 "\\$\\$" "\\|"
19609 "\\\\\\(begin\\|end\\|[][]\\)"))
19610 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
19611 ;; But only if the user has not turned off tables or fixed-width regions
19612 (org-set-local
19613 'auto-fill-inhibit-regexp
19614 (concat org-outline-regexp
19615 "\\|#\\+"
19616 "\\|[ \t]*" org-keyword-time-regexp
19617 (if (or org-enable-table-editor org-enable-fixed-width-editor)
19618 (concat
19619 "\\|[ \t]*["
19620 (if org-enable-table-editor "|" "")
19621 (if org-enable-fixed-width-editor ":" "")
19622 "]"))))
19623 ;; We use our own fill-paragraph function, to make sure that tables
19624 ;; and fixed-width regions are not wrapped. That function will pass
19625 ;; through to `fill-paragraph' when appropriate.
19626 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
19627 ;; Prevent auto-fill from inserting unwanted new items.
19628 (org-set-local 'fill-nobreak-predicate
19629 (if (memq 'org-fill-item-nobreak-p fill-nobreak-predicate)
19630 fill-nobreak-predicate
19631 (cons 'org-fill-item-nobreak-p fill-nobreak-predicate)))
19632 ;; Adaptive filling: To get full control, first make sure that
19633 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
19634 (unless (local-variable-p 'adaptive-fill-regexp (current-buffer))
19635 (org-set-local 'org-adaptive-fill-regexp-backup
19636 adaptive-fill-regexp))
19637 (org-set-local 'adaptive-fill-regexp "\000")
19638 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
19639 (org-set-local 'adaptive-fill-function
19640 'org-adaptive-fill-function)
19641 (org-set-local
19642 'align-mode-rules-list
19643 '((org-in-buffer-settings
19644 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
19645 (modes . '(org-mode))))))
19647 (defun org-fill-item-nobreak-p ()
19648 "Non-nil when a line break at point would insert a new item."
19649 (and (looking-at (org-item-re)) (org-list-in-valid-context-p)))
19651 (defun org-fill-paragraph (&optional justify)
19652 "Re-align a table, pass through to fill-paragraph if no table."
19653 (let ((table-p (org-at-table-p))
19654 (table.el-p (org-at-table.el-p))
19655 (itemp (org-in-item-p)))
19656 (cond ((and (equal (char-after (point-at-bol)) ?*)
19657 (save-excursion (goto-char (point-at-bol))
19658 (looking-at org-outline-regexp)))
19659 t) ; skip headlines
19660 (table.el-p t) ; skip table.el tables
19661 (table-p (org-table-align) t) ; align Org tables
19662 (itemp ; align text in items
19663 (let* ((struct (save-excursion (goto-char itemp)
19664 (org-list-struct)))
19665 (parents (org-list-parents-alist struct))
19666 (children (org-list-get-children itemp struct parents))
19667 beg end prev next prefix)
19668 ;; Determine in which part of item point is: before
19669 ;; first child, after last child, between two
19670 ;; sub-lists, or simply in item if there's no child.
19671 (cond
19672 ((not children)
19673 (setq prefix (make-string (org-list-item-body-column itemp) ?\ )
19674 beg itemp
19675 end (org-list-get-item-end itemp struct)))
19676 ((< (point) (setq next (car children)))
19677 (setq prefix (make-string (org-list-item-body-column itemp) ?\ )
19678 beg itemp
19679 end next))
19680 ((> (point) (setq prev (car (last children))))
19681 (setq beg (org-list-get-item-end prev struct)
19682 end (org-list-get-item-end itemp struct)
19683 prefix (save-excursion
19684 (goto-char beg)
19685 (skip-chars-forward " \t")
19686 (make-string (current-column) ?\ ))))
19687 (t (catch 'exit
19688 (while (setq next (pop children))
19689 (if (> (point) next)
19690 (setq prev next)
19691 (setq beg (org-list-get-item-end prev struct)
19692 end next
19693 prefix (save-excursion
19694 (goto-char beg)
19695 (skip-chars-forward " \t")
19696 (make-string (current-column) ?\ )))
19697 (throw 'exit nil))))))
19698 ;; Use `fill-paragraph' with buffer narrowed to item
19699 ;; without any child, and with our computed PREFIX.
19700 (flet ((fill-context-prefix (from to &optional flr) prefix))
19701 (save-restriction
19702 (narrow-to-region beg end)
19703 (save-excursion (fill-paragraph justify)))) t))
19704 ;; Special case where point is not in a list but is on
19705 ;; a paragraph adjacent to a list: make sure this paragraph
19706 ;; doesn't get merged with the end of the list by narrowing
19707 ;; buffer first.
19708 ((save-excursion (forward-paragraph -1)
19709 (setq itemp (org-in-item-p)))
19710 (let ((struct (save-excursion (goto-char itemp)
19711 (org-list-struct))))
19712 (save-restriction
19713 (narrow-to-region (org-list-get-bottom-point struct)
19714 (save-excursion (forward-paragraph 1)
19715 (point)))
19716 (fill-paragraph justify) t)))
19717 ;; Else simply call `fill-paragraph'.
19718 (t nil))))
19720 ;; For reference, this is the default value of adaptive-fill-regexp
19721 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
19723 (defun org-adaptive-fill-function ()
19724 "Return a fill prefix for org-mode files."
19725 (let (itemp)
19726 (save-excursion
19727 (cond
19728 ;; Comment line
19729 ((looking-at "#[ \t]+")
19730 (match-string-no-properties 0))
19731 ;; Plain list item
19732 ((org-at-item-p)
19733 (make-string (org-list-item-body-column (point-at-bol)) ?\ ))
19734 ;; Point is in a list after `backward-paragraph': original
19735 ;; point wasn't in the list, or filling would have been taken
19736 ;; care of by `org-auto-fill-function', but the list and the
19737 ;; real paragraph are not separated by a blank line. Thus, move
19738 ;; point after the list to go back to real paragraph and
19739 ;; determine fill-prefix.
19740 ((setq itemp (org-in-item-p))
19741 (goto-char itemp)
19742 (let* ((struct (org-list-struct))
19743 (bottom (org-list-get-bottom-point struct)))
19744 (goto-char bottom)
19745 (make-string (org-get-indentation) ?\ )))
19746 ;; Other text
19747 ((looking-at org-adaptive-fill-regexp-backup)
19748 (match-string-no-properties 0))))))
19750 (defun org-auto-fill-function ()
19751 "Auto-fill function."
19752 (let (itemp prefix)
19753 ;; When in a list, compute an appropriate fill-prefix and make
19754 ;; sure it will be used by `do-auto-fill'.
19755 (if (setq itemp (org-in-item-p))
19756 (progn
19757 (setq prefix (make-string (org-list-item-body-column itemp) ?\ ))
19758 (flet ((fill-context-prefix (from to &optional flr) prefix))
19759 (do-auto-fill)))
19760 ;; Else just use `do-auto-fill'.
19761 (do-auto-fill))))
19763 ;;; Other stuff.
19765 (defun org-toggle-fixed-width-section (arg)
19766 "Toggle the fixed-width export.
19767 If there is no active region, the QUOTE keyword at the current headline is
19768 inserted or removed. When present, it causes the text between this headline
19769 and the next to be exported as fixed-width text, and unmodified.
19770 If there is an active region, this command adds or removes a colon as the
19771 first character of this line. If the first character of a line is a colon,
19772 this line is also exported in fixed-width font."
19773 (interactive "P")
19774 (let* ((cc 0)
19775 (regionp (org-region-active-p))
19776 (beg (if regionp (region-beginning) (point)))
19777 (end (if regionp (region-end)))
19778 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
19779 (case-fold-search nil)
19780 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
19781 off)
19782 (if regionp
19783 (save-excursion
19784 (goto-char beg)
19785 (setq cc (current-column))
19786 (beginning-of-line 1)
19787 (setq off (looking-at re))
19788 (while (> nlines 0)
19789 (setq nlines (1- nlines))
19790 (beginning-of-line 1)
19791 (cond
19792 (arg
19793 (org-move-to-column cc t)
19794 (insert ": \n")
19795 (forward-line -1))
19796 ((and off (looking-at re))
19797 (replace-match "" t t nil 1))
19798 ((not off) (org-move-to-column cc t) (insert ": ")))
19799 (forward-line 1)))
19800 (save-excursion
19801 (org-back-to-heading)
19802 (if (looking-at (concat org-outline-regexp
19803 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
19804 (replace-match "" t t nil 1)
19805 (if (looking-at org-outline-regexp)
19806 (progn
19807 (goto-char (match-end 0))
19808 (insert org-quote-string " "))))))))
19810 (defun org-reftex-citation ()
19811 "Use reftex-citation to insert a citation into the buffer.
19812 This looks for a line like
19814 #+BIBLIOGRAPHY: foo plain option:-d
19816 and derives from it that foo.bib is the bibliography file relevant
19817 for this document. It then installs the necessary environment for RefTeX
19818 to work in this buffer and calls `reftex-citation' to insert a citation
19819 into the buffer.
19821 Export of such citations to both LaTeX and HTML is handled by the contributed
19822 package org-exp-bibtex by Taru Karttunen."
19823 (interactive)
19824 (let ((reftex-docstruct-symbol 'rds)
19825 (reftex-cite-format "\\cite{%l}")
19826 rds bib)
19827 (save-excursion
19828 (save-restriction
19829 (widen)
19830 (let ((case-fold-search t)
19831 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
19832 (if (not (save-excursion
19833 (or (re-search-forward re nil t)
19834 (re-search-backward re nil t))))
19835 (error "No bibliography defined in file")
19836 (setq bib (concat (match-string 1) ".bib")
19837 rds (list (list 'bib bib)))))))
19838 (call-interactively 'reftex-citation)))
19840 ;;;; Functions extending outline functionality
19842 (defun org-beginning-of-line (&optional arg)
19843 "Go to the beginning of the current line. If that is invisible, continue
19844 to a visible line beginning. This makes the function of C-a more intuitive.
19845 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
19846 first attempt, and only move to after the tags when the cursor is already
19847 beyond the end of the headline."
19848 (interactive "P")
19849 (let ((pos (point))
19850 (special (if (consp org-special-ctrl-a/e)
19851 (car org-special-ctrl-a/e)
19852 org-special-ctrl-a/e))
19853 refpos)
19854 (if (org-bound-and-true-p line-move-visual)
19855 (beginning-of-visual-line 1)
19856 (beginning-of-line 1))
19857 (if (and arg (fboundp 'move-beginning-of-line))
19858 (call-interactively 'move-beginning-of-line)
19859 (if (bobp)
19861 (backward-char 1)
19862 (if (org-truely-invisible-p)
19863 (while (and (not (bobp)) (org-truely-invisible-p))
19864 (backward-char 1)
19865 (beginning-of-line 1))
19866 (forward-char 1))))
19867 (when special
19868 (cond
19869 ((and (looking-at org-complex-heading-regexp)
19870 (= (char-after (match-end 1)) ?\ ))
19871 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
19872 (point-at-eol)))
19873 (goto-char
19874 (if (eq special t)
19875 (cond ((> pos refpos) refpos)
19876 ((= pos (point)) refpos)
19877 (t (point)))
19878 (cond ((> pos (point)) (point))
19879 ((not (eq last-command this-command)) (point))
19880 (t refpos)))))
19881 ((org-at-item-p)
19882 (goto-char
19883 (if (eq special t)
19884 (cond ((> pos (match-end 0)) (match-end 0))
19885 ((= pos (point)) (match-end 0))
19886 (t (point)))
19887 (cond ((> pos (point)) (point))
19888 ((not (eq last-command this-command)) (point))
19889 (t (match-end 0))))))))
19890 (org-no-warnings
19891 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
19893 (defun org-end-of-line (&optional arg)
19894 "Go to the end of the line.
19895 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
19896 first attempt, and only move to after the tags when the cursor is already
19897 beyond the end of the headline."
19898 (interactive "P")
19899 (let ((special (if (consp org-special-ctrl-a/e)
19900 (cdr org-special-ctrl-a/e)
19901 org-special-ctrl-a/e)))
19902 (if (or (not special)
19903 (not (org-on-heading-p))
19904 arg)
19905 (call-interactively
19906 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
19907 ((fboundp 'move-end-of-line) 'move-end-of-line)
19908 (t 'end-of-line)))
19909 (let ((pos (point)))
19910 (beginning-of-line 1)
19911 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
19912 (if (eq special t)
19913 (if (or (< pos (match-beginning 1))
19914 (= pos (match-end 0)))
19915 (goto-char (match-beginning 1))
19916 (goto-char (match-end 0)))
19917 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
19918 (goto-char (match-end 0))
19919 (goto-char (match-beginning 1))))
19920 (call-interactively (if (fboundp 'move-end-of-line)
19921 'move-end-of-line
19922 'end-of-line)))))
19923 (org-no-warnings
19924 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
19926 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
19927 (define-key org-mode-map "\C-e" 'org-end-of-line)
19929 (defun org-backward-sentence (&optional arg)
19930 "Go to beginning of sentence, or beginning of table field.
19931 This will call `backward-sentence' or `org-table-beginning-of-field',
19932 depending on context."
19933 (interactive "P")
19934 (cond
19935 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
19936 (t (call-interactively 'backward-sentence))))
19938 (defun org-forward-sentence (&optional arg)
19939 "Go to end of sentence, or end of table field.
19940 This will call `forward-sentence' or `org-table-end-of-field',
19941 depending on context."
19942 (interactive "P")
19943 (cond
19944 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
19945 (t (call-interactively 'forward-sentence))))
19947 (define-key org-mode-map "\M-a" 'org-backward-sentence)
19948 (define-key org-mode-map "\M-e" 'org-forward-sentence)
19950 (defun org-kill-line (&optional arg)
19951 "Kill line, to tags or end of line."
19952 (interactive "P")
19953 (cond
19954 ((or (not org-special-ctrl-k)
19955 (bolp)
19956 (not (org-on-heading-p)))
19957 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
19958 org-ctrl-k-protect-subtree)
19959 (if (or (eq org-ctrl-k-protect-subtree 'error)
19960 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
19961 (error "C-k aborted - would kill hidden subtree")))
19962 (call-interactively 'kill-line))
19963 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
19964 (kill-region (point) (match-beginning 1))
19965 (org-set-tags nil t))
19966 (t (kill-region (point) (point-at-eol)))))
19968 (define-key org-mode-map "\C-k" 'org-kill-line)
19970 (defun org-yank (&optional arg)
19971 "Yank. If the kill is a subtree, treat it specially.
19972 This command will look at the current kill and check if is a single
19973 subtree, or a series of subtrees[1]. If it passes the test, and if the
19974 cursor is at the beginning of a line or after the stars of a currently
19975 empty headline, then the yank is handled specially. How exactly depends
19976 on the value of the following variables, both set by default.
19978 org-yank-folded-subtrees
19979 When set, the subtree(s) will be folded after insertion, but only
19980 if doing so would now swallow text after the yanked text.
19982 org-yank-adjusted-subtrees
19983 When set, the subtree will be promoted or demoted in order to
19984 fit into the local outline tree structure, which means that the level
19985 will be adjusted so that it becomes the smaller one of the two
19986 *visible* surrounding headings.
19988 Any prefix to this command will cause `yank' to be called directly with
19989 no special treatment. In particular, a simple \\[universal-argument] prefix \
19990 will just
19991 plainly yank the text as it is.
19993 \[1] The test checks if the first non-white line is a heading
19994 and if there are no other headings with fewer stars."
19995 (interactive "P")
19996 (org-yank-generic 'yank arg))
19998 (defun org-yank-generic (command arg)
19999 "Perform some yank-like command.
20001 This function implements the behavior described in the `org-yank'
20002 documentation. However, it has been generalized to work for any
20003 interactive command with similar behavior."
20005 ;; pretend to be command COMMAND
20006 (setq this-command command)
20008 (if arg
20009 (call-interactively command)
20011 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
20012 (and (org-kill-is-subtree-p)
20013 (or (bolp)
20014 (and (looking-at "[ \t]*$")
20015 (string-match
20016 "\\`\\*+\\'"
20017 (buffer-substring (point-at-bol) (point)))))))
20018 swallowp)
20019 (cond
20020 ((and subtreep org-yank-folded-subtrees)
20021 (let ((beg (point))
20022 end)
20023 (if (and subtreep org-yank-adjusted-subtrees)
20024 (org-paste-subtree nil nil 'for-yank)
20025 (call-interactively command))
20027 (setq end (point))
20028 (goto-char beg)
20029 (when (and (bolp) subtreep
20030 (not (setq swallowp
20031 (org-yank-folding-would-swallow-text beg end))))
20032 (org-with-limited-levels
20033 (or (looking-at org-outline-regexp)
20034 (re-search-forward org-outline-regexp-bol end t))
20035 (while (and (< (point) end) (looking-at org-outline-regexp))
20036 (hide-subtree)
20037 (org-cycle-show-empty-lines 'folded)
20038 (condition-case nil
20039 (outline-forward-same-level 1)
20040 (error (goto-char end))))))
20041 (when swallowp
20042 (message
20043 "Inserted text not folded because that would swallow text"))
20045 (goto-char end)
20046 (skip-chars-forward " \t\n\r")
20047 (beginning-of-line 1)
20048 (push-mark beg 'nomsg)))
20049 ((and subtreep org-yank-adjusted-subtrees)
20050 (let ((beg (point-at-bol)))
20051 (org-paste-subtree nil nil 'for-yank)
20052 (push-mark beg 'nomsg)))
20054 (call-interactively command))))))
20056 (defun org-yank-folding-would-swallow-text (beg end)
20057 "Would hide-subtree at BEG swallow any text after END?"
20058 (let (level)
20059 (org-with-limited-levels
20060 (save-excursion
20061 (goto-char beg)
20062 (when (or (looking-at org-outline-regexp)
20063 (re-search-forward org-outline-regexp-bol end t))
20064 (setq level (org-outline-level)))
20065 (goto-char end)
20066 (skip-chars-forward " \t\r\n\v\f")
20067 (if (or (eobp)
20068 (and (bolp) (looking-at org-outline-regexp)
20069 (<= (org-outline-level) level)))
20070 nil ; Nothing would be swallowed
20071 t))))) ; something would swallow
20073 (define-key org-mode-map "\C-y" 'org-yank)
20075 (defun org-truely-invisible-p ()
20076 "Check if point is at a character currently not visible.
20077 This version does not only check the character property, but also
20078 `visible-mode'."
20079 ;; Early versions of noutline don't have `outline-invisible-p'.
20080 (if (org-bound-and-true-p visible-mode)
20082 (outline-invisible-p)))
20084 (defun org-invisible-p2 ()
20085 "Check if point is at a character currently not visible."
20086 (save-excursion
20087 (if (and (eolp) (not (bobp))) (backward-char 1))
20088 ;; Early versions of noutline don't have `outline-invisible-p'.
20089 (outline-invisible-p)))
20091 (defun org-back-to-heading (&optional invisible-ok)
20092 "Call `outline-back-to-heading', but provide a better error message."
20093 (condition-case nil
20094 (outline-back-to-heading invisible-ok)
20095 (error (error "Before first headline at position %d in buffer %s"
20096 (point) (current-buffer)))))
20098 (defun org-beginning-of-defun ()
20099 "Go to the beginning of the subtree, i.e. back to the heading."
20100 (org-back-to-heading))
20101 (defun org-end-of-defun ()
20102 "Go to the end of the subtree."
20103 (org-end-of-subtree nil t))
20105 (defun org-before-first-heading-p ()
20106 "Before first heading?"
20107 (save-excursion
20108 (end-of-line)
20109 (null (re-search-backward org-outline-regexp-bol nil t))))
20111 (defun org-on-heading-p (&optional ignored)
20112 (outline-on-heading-p t))
20113 (defun org-at-heading-p (&optional ignored)
20114 (outline-on-heading-p t))
20116 (defun org-point-at-end-of-empty-headline ()
20117 "If point is at the end of an empty headline, return t, else nil.
20118 If the heading only contains a TODO keyword, it is still still considered
20119 empty."
20120 (and (looking-at "[ \t]*$")
20121 (save-excursion
20122 (beginning-of-line 1)
20123 (let ((case-fold-search nil))
20124 (looking-at (concat "^\\(\\*+\\)[ \t]+\\(" org-todo-regexp
20125 "\\)?[ \t]*$"))))))
20126 (defun org-at-heading-or-item-p ()
20127 (or (org-on-heading-p) (org-at-item-p)))
20129 (defun org-on-target-p ()
20130 (or (org-in-regexp org-radio-target-regexp)
20131 (org-in-regexp org-target-regexp)))
20133 (defun org-up-heading-all (arg)
20134 "Move to the heading line of which the present line is a subheading.
20135 This function considers both visible and invisible heading lines.
20136 With argument, move up ARG levels."
20137 (if (fboundp 'outline-up-heading-all)
20138 (outline-up-heading-all arg) ; emacs 21 version of outline.el
20139 (outline-up-heading arg t))) ; emacs 22 version of outline.el
20141 (defun org-up-heading-safe ()
20142 "Move to the heading line of which the present line is a subheading.
20143 This version will not throw an error. It will return the level of the
20144 headline found, or nil if no higher level is found.
20146 Also, this function will be a lot faster than `outline-up-heading',
20147 because it relies on stars being the outline starters. This can really
20148 make a significant difference in outlines with very many siblings."
20149 (let (start-level re)
20150 (org-back-to-heading t)
20151 (setq start-level (funcall outline-level))
20152 (if (equal start-level 1)
20154 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
20155 (if (re-search-backward re nil t)
20156 (funcall outline-level)))))
20158 (defun org-first-sibling-p ()
20159 "Is this heading the first child of its parents?"
20160 (interactive)
20161 (let ((re org-outline-regexp-bol)
20162 level l)
20163 (unless (org-at-heading-p t)
20164 (error "Not at a heading"))
20165 (setq level (funcall outline-level))
20166 (save-excursion
20167 (if (not (re-search-backward re nil t))
20169 (setq l (funcall outline-level))
20170 (< l level)))))
20172 (defun org-goto-sibling (&optional previous)
20173 "Goto the next sibling, even if it is invisible.
20174 When PREVIOUS is set, go to the previous sibling instead. Returns t
20175 when a sibling was found. When none is found, return nil and don't
20176 move point."
20177 (let ((fun (if previous 're-search-backward 're-search-forward))
20178 (pos (point))
20179 (re org-outline-regexp-bol)
20180 level l)
20181 (when (condition-case nil (org-back-to-heading t) (error nil))
20182 (setq level (funcall outline-level))
20183 (catch 'exit
20184 (or previous (forward-char 1))
20185 (while (funcall fun re nil t)
20186 (setq l (funcall outline-level))
20187 (when (< l level) (goto-char pos) (throw 'exit nil))
20188 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
20189 (goto-char pos)
20190 nil))))
20192 (defun org-show-siblings ()
20193 "Show all siblings of the current headline."
20194 (save-excursion
20195 (while (org-goto-sibling) (org-flag-heading nil)))
20196 (save-excursion
20197 (while (org-goto-sibling 'previous)
20198 (org-flag-heading nil))))
20200 (defun org-goto-first-child ()
20201 "Goto the first child, even if it is invisible.
20202 Return t when a child was found. Otherwise don't move point and
20203 return nil."
20204 (let (level (pos (point)) (re org-outline-regexp-bol))
20205 (when (condition-case nil (org-back-to-heading t) (error nil))
20206 (setq level (outline-level))
20207 (forward-char 1)
20208 (if (and (re-search-forward re nil t) (> (outline-level) level))
20209 (progn (goto-char (match-beginning 0)) t)
20210 (goto-char pos) nil))))
20212 (defun org-show-hidden-entry ()
20213 "Show an entry where even the heading is hidden."
20214 (save-excursion
20215 (org-show-entry)))
20217 (defun org-flag-heading (flag &optional entry)
20218 "Flag the current heading. FLAG non-nil means make invisible.
20219 When ENTRY is non-nil, show the entire entry."
20220 (save-excursion
20221 (org-back-to-heading t)
20222 ;; Check if we should show the entire entry
20223 (if entry
20224 (progn
20225 (org-show-entry)
20226 (save-excursion
20227 (and (outline-next-heading)
20228 (org-flag-heading nil))))
20229 (outline-flag-region (max (point-min) (1- (point)))
20230 (save-excursion (outline-end-of-heading) (point))
20231 flag))))
20233 (defun org-get-next-sibling ()
20234 "Move to next heading of the same level, and return point.
20235 If there is no such heading, return nil.
20236 This is like outline-next-sibling, but invisible headings are ok."
20237 (let ((level (funcall outline-level)))
20238 (outline-next-heading)
20239 (while (and (not (eobp)) (> (funcall outline-level) level))
20240 (outline-next-heading))
20241 (if (or (eobp) (< (funcall outline-level) level))
20243 (point))))
20245 (defun org-get-last-sibling ()
20246 "Move to previous heading of the same level, and return point.
20247 If there is no such heading, return nil."
20248 (let ((opoint (point))
20249 (level (funcall outline-level)))
20250 (outline-previous-heading)
20251 (when (and (/= (point) opoint) (outline-on-heading-p t))
20252 (while (and (> (funcall outline-level) level)
20253 (not (bobp)))
20254 (outline-previous-heading))
20255 (if (< (funcall outline-level) level)
20257 (point)))))
20259 (defun org-end-of-subtree (&optional invisible-OK to-heading)
20260 ;; This contains an exact copy of the original function, but it uses
20261 ;; `org-back-to-heading', to make it work also in invisible
20262 ;; trees. And is uses an invisible-OK argument.
20263 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
20264 ;; Furthermore, when used inside Org, finding the end of a large subtree
20265 ;; with many children and grandchildren etc, this can be much faster
20266 ;; than the outline version.
20267 (org-back-to-heading invisible-OK)
20268 (let ((first t)
20269 (level (funcall outline-level)))
20270 (if (and (org-mode-p) (< level 1000))
20271 ;; A true heading (not a plain list item), in Org-mode
20272 ;; This means we can easily find the end by looking
20273 ;; only for the right number of stars. Using a regexp to do
20274 ;; this is so much faster than using a Lisp loop.
20275 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
20276 (forward-char 1)
20277 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
20278 ;; something else, do it the slow way
20279 (while (and (not (eobp))
20280 (or first (> (funcall outline-level) level)))
20281 (setq first nil)
20282 (outline-next-heading)))
20283 (unless to-heading
20284 (if (memq (preceding-char) '(?\n ?\^M))
20285 (progn
20286 ;; Go to end of line before heading
20287 (forward-char -1)
20288 (if (memq (preceding-char) '(?\n ?\^M))
20289 ;; leave blank line before heading
20290 (forward-char -1))))))
20291 (point))
20293 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
20294 "Use Org version in org-mode, for dramatic speed-up."
20295 (if (org-mode-p)
20296 (progn
20297 (org-end-of-subtree nil t)
20298 (unless (eobp) (backward-char 1)))
20299 ad-do-it))
20301 ;; FIXME This should not match :END: for custom drawers?
20302 (defun org-end-of-meta-data-and-drawers ()
20303 "Jump to the first text after meta data and drawers in the current entry.
20304 This will move over empty lines, lines with planning time stamps,
20305 clocking lines, and drawers."
20306 (org-back-to-heading t)
20307 (let ((end (save-excursion (outline-next-heading) (point)))
20308 (re (concat "\\(" org-drawer-regexp "\\)"
20309 "\\|" "[ \t]*" org-keyword-time-regexp)))
20310 (forward-line 1)
20311 (while (re-search-forward re end t)
20312 (if (not (match-end 1))
20313 ;; empty or planning line
20314 (forward-line 1)
20315 ;; a drawer, find the end
20316 (re-search-forward "^[ \t]*:END:" end 'move)
20317 (forward-line 1)))
20318 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
20319 (point)))
20321 (defun org-forward-same-level (arg &optional invisible-ok)
20322 "Move forward to the arg'th subheading at same level as this one.
20323 Stop at the first and last subheadings of a superior heading.
20324 Normally this only looks at visible headings, but when INVISIBLE-OK is non-nil
20325 it wil also look at invisible ones."
20326 (interactive "p")
20327 (org-back-to-heading invisible-ok)
20328 (org-on-heading-p)
20329 (let* ((level (- (match-end 0) (match-beginning 0) 1))
20330 (re (format "^\\*\\{1,%d\\} " level))
20332 (forward-char 1)
20333 (while (> arg 0)
20334 (while (and (re-search-forward re nil 'move)
20335 (setq l (- (match-end 0) (match-beginning 0) 1))
20336 (= l level)
20337 (not invisible-ok)
20338 (progn (backward-char 1) (outline-invisible-p)))
20339 (if (< l level) (setq arg 1)))
20340 (setq arg (1- arg)))
20341 (beginning-of-line 1)))
20343 (defun org-backward-same-level (arg &optional invisible-ok)
20344 "Move backward to the arg'th subheading at same level as this one.
20345 Stop at the first and last subheadings of a superior heading."
20346 (interactive "p")
20347 (org-back-to-heading)
20348 (org-on-heading-p)
20349 (let* ((level (- (match-end 0) (match-beginning 0) 1))
20350 (re (format "^\\*\\{1,%d\\} " level))
20352 (while (> arg 0)
20353 (while (and (re-search-backward re nil 'move)
20354 (setq l (- (match-end 0) (match-beginning 0) 1))
20355 (= l level)
20356 (not invisible-ok)
20357 (outline-invisible-p))
20358 (if (< l level) (setq arg 1)))
20359 (setq arg (1- arg)))))
20361 (defun org-show-subtree ()
20362 "Show everything after this heading at deeper levels."
20363 (outline-flag-region
20364 (point)
20365 (save-excursion
20366 (org-end-of-subtree t t))
20367 nil))
20369 (defun org-show-entry ()
20370 "Show the body directly following this heading.
20371 Show the heading too, if it is currently invisible."
20372 (interactive)
20373 (save-excursion
20374 (condition-case nil
20375 (progn
20376 (org-back-to-heading t)
20377 (outline-flag-region
20378 (max (point-min) (1- (point)))
20379 (save-excursion
20380 (if (re-search-forward
20381 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
20382 (match-beginning 1)
20383 (point-max)))
20384 nil)
20385 (org-cycle-hide-drawers 'children))
20386 (error nil))))
20388 (defun org-make-options-regexp (kwds &optional extra)
20389 "Make a regular expression for keyword lines."
20390 (concat
20392 "#?[ \t]*\\+\\("
20393 (mapconcat 'regexp-quote kwds "\\|")
20394 (if extra (concat "\\|" extra))
20395 "\\):[ \t]*"
20396 "\\(.*\\)"))
20398 ;; Make isearch reveal the necessary context
20399 (defun org-isearch-end ()
20400 "Reveal context after isearch exits."
20401 (when isearch-success ; only if search was successful
20402 (if (featurep 'xemacs)
20403 ;; Under XEmacs, the hook is run in the correct place,
20404 ;; we directly show the context.
20405 (org-show-context 'isearch)
20406 ;; In Emacs the hook runs *before* restoring the overlays.
20407 ;; So we have to use a one-time post-command-hook to do this.
20408 ;; (Emacs 22 has a special variable, see function `org-mode')
20409 (unless (and (boundp 'isearch-mode-end-hook-quit)
20410 isearch-mode-end-hook-quit)
20411 ;; Only when the isearch was not quitted.
20412 (org-add-hook 'post-command-hook 'org-isearch-post-command
20413 'append 'local)))))
20415 (defun org-isearch-post-command ()
20416 "Remove self from hook, and show context."
20417 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
20418 (org-show-context 'isearch))
20421 ;;;; Integration with and fixes for other packages
20423 ;;; Imenu support
20425 (defvar org-imenu-markers nil
20426 "All markers currently used by Imenu.")
20427 (make-variable-buffer-local 'org-imenu-markers)
20429 (defun org-imenu-new-marker (&optional pos)
20430 "Return a new marker for use by Imenu, and remember the marker."
20431 (let ((m (make-marker)))
20432 (move-marker m (or pos (point)))
20433 (push m org-imenu-markers)
20436 (defun org-imenu-get-tree ()
20437 "Produce the index for Imenu."
20438 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
20439 (setq org-imenu-markers nil)
20440 (let* ((n org-imenu-depth)
20441 (re (concat "^" (org-get-limited-outline-regexp)))
20442 (subs (make-vector (1+ n) nil))
20443 (last-level 0)
20444 m level head)
20445 (save-excursion
20446 (save-restriction
20447 (widen)
20448 (goto-char (point-max))
20449 (while (re-search-backward re nil t)
20450 (setq level (org-reduced-level (funcall outline-level)))
20451 (when (<= level n)
20452 (looking-at org-complex-heading-regexp)
20453 (setq head (org-link-display-format
20454 (org-match-string-no-properties 4))
20455 m (org-imenu-new-marker))
20456 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
20457 (if (>= level last-level)
20458 (push (cons head m) (aref subs level))
20459 (push (cons head (aref subs (1+ level))) (aref subs level))
20460 (loop for i from (1+ level) to n do (aset subs i nil)))
20461 (setq last-level level)))))
20462 (aref subs 1)))
20464 (eval-after-load "imenu"
20465 '(progn
20466 (add-hook 'imenu-after-jump-hook
20467 (lambda ()
20468 (if (org-mode-p)
20469 (org-show-context 'org-goto))))))
20471 (defun org-link-display-format (link)
20472 "Replace a link with either the description, or the link target
20473 if no description is present"
20474 (save-match-data
20475 (if (string-match org-bracket-link-analytic-regexp link)
20476 (replace-match (if (match-end 5)
20477 (match-string 5 link)
20478 (concat (match-string 1 link)
20479 (match-string 3 link)))
20480 nil t link)
20481 link)))
20483 (defun org-toggle-link-display ()
20484 "Toggle the literal or descriptive display of links."
20485 (interactive)
20486 (if org-link-display-descriptive
20487 (progn (org-remove-from-invisibility-spec '(org-link))
20488 (org-restart-font-lock)
20489 (setq org-link-display-descriptive nil))
20490 (progn (add-to-invisibility-spec '(org-link))
20491 (org-restart-font-lock)
20492 (setq org-link-display-descriptive t))))
20494 ;; Speedbar support
20496 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
20497 "Overlay marking the agenda restriction line in speedbar.")
20498 (overlay-put org-speedbar-restriction-lock-overlay
20499 'face 'org-agenda-restriction-lock)
20500 (overlay-put org-speedbar-restriction-lock-overlay
20501 'help-echo "Agendas are currently limited to this item.")
20502 (org-detach-overlay org-speedbar-restriction-lock-overlay)
20504 (defun org-speedbar-set-agenda-restriction ()
20505 "Restrict future agenda commands to the location at point in speedbar.
20506 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
20507 (interactive)
20508 (require 'org-agenda)
20509 (let (p m tp np dir txt)
20510 (cond
20511 ((setq p (text-property-any (point-at-bol) (point-at-eol)
20512 'org-imenu t))
20513 (setq m (get-text-property p 'org-imenu-marker))
20514 (with-current-buffer (marker-buffer m)
20515 (goto-char m)
20516 (org-agenda-set-restriction-lock 'subtree)))
20517 ((setq p (text-property-any (point-at-bol) (point-at-eol)
20518 'speedbar-function 'speedbar-find-file))
20519 (setq tp (previous-single-property-change
20520 (1+ p) 'speedbar-function)
20521 np (next-single-property-change
20522 tp 'speedbar-function)
20523 dir (speedbar-line-directory)
20524 txt (buffer-substring-no-properties (or tp (point-min))
20525 (or np (point-max))))
20526 (with-current-buffer (find-file-noselect
20527 (let ((default-directory dir))
20528 (expand-file-name txt)))
20529 (unless (org-mode-p)
20530 (error "Cannot restrict to non-Org-mode file"))
20531 (org-agenda-set-restriction-lock 'file)))
20532 (t (error "Don't know how to restrict Org-mode's agenda")))
20533 (move-overlay org-speedbar-restriction-lock-overlay
20534 (point-at-bol) (point-at-eol))
20535 (setq current-prefix-arg nil)
20536 (org-agenda-maybe-redo)))
20538 (eval-after-load "speedbar"
20539 '(progn
20540 (speedbar-add-supported-extension ".org")
20541 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
20542 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
20543 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
20544 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
20545 (add-hook 'speedbar-visiting-tag-hook
20546 (lambda () (and (org-mode-p) (org-show-context 'org-goto))))))
20548 ;;; Fixes and Hacks for problems with other packages
20550 ;; Make flyspell not check words in links, to not mess up our keymap
20551 (defun org-mode-flyspell-verify ()
20552 "Don't let flyspell put overlays at active buttons, or on
20553 {todo,all-time,additional-option-like}-keywords."
20554 (let ((pos (max (1- (point)) (point-min)))
20555 (word (thing-at-point 'word)))
20556 (and (not (get-text-property pos 'keymap))
20557 (not (get-text-property pos 'org-no-flyspell))
20558 (not (member word org-todo-keywords-1))
20559 (not (member word org-all-time-keywords))
20560 (not (member word org-additional-option-like-keywords)))))
20562 (defun org-remove-flyspell-overlays-in (beg end)
20563 "Remove flyspell overlays in region."
20564 (and (org-bound-and-true-p flyspell-mode)
20565 (fboundp 'flyspell-delete-region-overlays)
20566 (flyspell-delete-region-overlays beg end))
20567 (add-text-properties beg end '(org-no-flyspell t)))
20569 ;; Make `bookmark-jump' shows the jump location if it was hidden.
20570 (eval-after-load "bookmark"
20571 '(if (boundp 'bookmark-after-jump-hook)
20572 ;; We can use the hook
20573 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
20574 ;; Hook not available, use advice
20575 (defadvice bookmark-jump (after org-make-visible activate)
20576 "Make the position visible."
20577 (org-bookmark-jump-unhide))))
20579 ;; Make sure saveplace shows the location if it was hidden
20580 (eval-after-load "saveplace"
20581 '(defadvice save-place-find-file-hook (after org-make-visible activate)
20582 "Make the position visible."
20583 (org-bookmark-jump-unhide)))
20585 ;; Make sure ecb shows the location if it was hidden
20586 (eval-after-load "ecb"
20587 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
20588 "Make hierarchy visible when jumping into location from ECB tree buffer."
20589 (if (org-mode-p)
20590 (org-show-context))))
20592 (defun org-bookmark-jump-unhide ()
20593 "Unhide the current position, to show the bookmark location."
20594 (and (org-mode-p)
20595 (or (outline-invisible-p)
20596 (save-excursion (goto-char (max (point-min) (1- (point))))
20597 (outline-invisible-p)))
20598 (org-show-context 'bookmark-jump)))
20600 ;; Make session.el ignore our circular variable
20601 (eval-after-load "session"
20602 '(add-to-list 'session-globals-exclude 'org-mark-ring))
20604 ;;;; Experimental code
20606 (defun org-closed-in-range ()
20607 "Sparse tree of items closed in a certain time range.
20608 Still experimental, may disappear in the future."
20609 (interactive)
20610 ;; Get the time interval from the user.
20611 (let* ((time1 (org-float-time
20612 (org-read-date nil 'to-time nil "Starting date: ")))
20613 (time2 (org-float-time
20614 (org-read-date nil 'to-time nil "End date:")))
20615 ;; callback function
20616 (callback (lambda ()
20617 (let ((time
20618 (org-float-time
20619 (apply 'encode-time
20620 (org-parse-time-string
20621 (match-string 1))))))
20622 ;; check if time in interval
20623 (and (>= time time1) (<= time time2))))))
20624 ;; make tree, check each match with the callback
20625 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
20627 ;;;; Finish up
20629 (provide 'org)
20631 (run-hooks 'org-load-hook)
20633 ;;; org.el ends here